From nicolas.lehuen at thecrmcompany.com Wed Apr 21 06:57:33 2004 From: nicolas.lehuen at thecrmcompany.com (Nicolas Lehuen) Date: Wed, 21 Apr 2004 12:57:33 +0200 Subject: Python 2.3.3 super() behaviour References: <40863bd7$0$25528$afc38c87@news.easynet.fr> <40864674$0$24834$afc38c87@news.easynet.fr> <40864ea6$0$25528$afc38c87@news.easynet.fr> Message-ID: <4086539d$0$24773$afc38c87@news.easynet.fr> Ah, so there *is* more than one way to do it, then ? ;) What the example shows is that super(...).__init__ does make one call to each superclass' __init__, provided that those superclasses play nicely and use super() themselves (as Peter wrote). If one of the superclasses does not use super(), the 'magical' iteration over parent methods is interrupted, hence the need to put those bad guys at the end of the superclasses list in the class declaration. But you're right, David, the simplest way to get what I want is to explicitely call the superclasses' __init__. However, this would mean that super() is not as useful as it seems. I'd rather find a way to *always* use super() than have special cases for certain inheritance trees. In other words, I'd rather have only one way to do it :). Regards, Nicolas "David Fraser" a ?crit dans le message de news:c65j4o$3me$1 at ctb-nnrp2.saix.net... > super is not going to be helpful here, so why not call the X.__init__ > functions explicitly? > Since you *need* multiple __init__ calls from the multiply-inherited > class, super isn't going to work... > > Nicolas Lehuen wrote: > > The only problem I have is that I want to build a multiple inheritance > > involving an object which does not cooperate, namely : > > > > class T(object): > > def __init__(self): > > super(T,self).__init__() > > > > class TL(list,object): > > def __init__(self) > > super(TL,self).__init__() > > > > In this case, T.__init__ is not called, because list.__init__ does not use > > super(). The only clean way to proceed is to change the inheritance order : > > TL(T,list). This way, both constructors are called. > > > > Here is another example which exhibits the behaviour : > > > > class A(object): > > def __init__(self): > > super(A,self).__init__() > > print 'A' > > > > class B(object): > > def __init__(self): > > print 'B' > > > > class C(B,A): > > def __init__(self): > > super(C,self).__init__() > > print 'C' > > > > class D(A,B): > > def __init__(self): > > super(D,self).__init__() > > print 'D' > > > > > >>>>C() > > > > B > > C > > <__main__.C object at 0x008F3D70> > > > >>>>D() > > > > B > > A > > D > > <__main__.D object at 0x008F39F0> > > > > The problem is that if you go further down the inheritance, the behaviour is > > even more complicated : > > > > class E(object): > > def __init__(self): > > super(E,self).__init__() > > print 'E' > > > > class F(C,E): > > def __init__(self): > > super(F,self).__init__() > > print 'F' > > > > class G(D,E): > > def __init__(self): > > super(G,self).__init__() > > print 'G' > > > > > >>>>F() > > > > B > > C > > F > > <__main__.F object at 0x008F3D70> > > > >>>>G() > > > > B > > A > > D > > G > > <__main__.G object at 0x008F3EF0> > > > > class H(E,C): > > def __init__(self): > > super(H,self).__init__() > > print 'H' > > > > class I(E,D): > > def __init__(self): > > super(I,self).__init__() > > print 'I' > > > > > >>>>H() > > > > B > > C > > E > > H > > <__main__.H object at 0x008F3E30> > > > >>>>I() > > > > B > > A > > D > > E > > I > > <__main__.I object at 0x008F3FD0> > > > > So the conclusion is : never do that :). Another more constructive > > conclusion would be : always put the most cooperative classes first in the > > inheritance declaration, provided that it doesn't interfere with your needs. > > A class which has an uncooperative ancestor is less cooperative than a class > > which has only cooperative ancestors. > > > > Regards, > > Nicolas > > > > "Nicolas Lehuen" a ?crit dans le message > > de news:40864674$0$24834$afc38c87 at news.easynet.fr... > > > >>OK, I get it now, thanks. > >> > >>super() method calls should only be used for method involved in > >>diamond-shaped inheritance. This is logical since in this case the base > >>classe (from which the diamond-shaped inheritance starts) defines the > >>interface of the method. > >> > >>This solves another question I was asking myself about super() : "how can > > > > it > > > >>work when the method signature differ between B and C ?". Answer : the > >>method signature should not change because polymorphic calls would be > >>greatly endangered. The base class defines the signature of the method > > > > which > > > >>must be followed by all its children, this way super() can work properly. > >> > >>The base method signature is not enforced by Python, of course, but you'd > >>better respect it unless you get weird result in polymorphic calls. > >> > >>Regards, > >>Nicolas > >> > >>"Peter Otten" <__peter__ at web.de> a ?crit dans le message de > >>news:c65fbo$1q4$05$1 at news.t-online.com... > >> > >>>Nicolas Lehuen wrote: > >>> > >>> > >>>>Hi, > >>>> > >>>>I hope this is not a FAQ, but I have trouble understanding the > > > > behaviour > > > >>>>of the super() built-in function. I've read the excellent book 'Python > >> > >>in > >> > >>>>a Nutshell' which explains this built-in function on pages 89-90. > > > > Based > > > >>on > >> > >>>>the example on page 90, I wrote this test code : > >>>> > >>>>class A(object): > >>>> def test(self): > >>>> print 'A' > >>>> > >>>>class B(object): > >>>> def test(self): > >>>> print 'B' > >>>> > >>>>class C(A,B): > >>>> def test(self): > >>>> super(C,self).test() > >>>> print 'C' > >>>> > >>>>print C.__mro__ > >>>>c=C() > >>>>c.test() > >>>> > >>>>The output is : > >>>>(, , , > > > > > > >>>>'object'>) > >>>>A > >>>>C > >>>> > >>>>Whereas I was expecting : > >>>>(, , , > > > > > > >>>>'object'>) > >>>>A > >>>>B > >>>>C > >>>> > >>>>Was I wrong to expect this (based on what I've read ?) > >>> > >>>As soon as a test() method without the super(...).test() is reached, no > >>>further test methods will be invoked. Only the first in the list of base > >>>classes will be invoked. If I'm getting it right you have to do > > > > something > > > >>>like: > >>> > >>>class Base(object): > >>> def test(self): > >>> print "base" > >>> > >>>class D1(Base): > >>> def test(self): > >>> super(D1, self).test() > >>> print "derived 1" > >>> > >>>class D2(Base): > >>> def test(self): > >>> super(D2, self).test() > >>> print "derived 2" > >>> > >>>class All(D1, D2): > >>> pass > >>> > >>>All().test() > >>> > >>>Here all cooperating methods have a super() call, and the base class > > > > acts > > > >>as > >> > >>>a showstopper to prevent that Python tries to invoke the non-existent > >>>object.test(). > >>> > >>>Peter > >>> > >>> > >>> > >> > >> > > > > From jepler at unpythonic.net Thu Apr 15 07:53:17 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Thu, 15 Apr 2004 06:53:17 -0500 Subject: Deleting objects with method reference In-Reply-To: References: Message-ID: <20040415115316.GB15354@unpythonic.net> It works here when I call gc.collect(). There's not exactly a guarantee about when garbage will be collected otherwise. >>> o2 = B() >>> o2.Set() >>> w2 = weakref.ref(o2, ondel) >>> del o2 >>> gc.collect() del 3 Jeff From boudot-kim at wanadoo.fr Thu Apr 22 11:58:10 2004 From: boudot-kim at wanadoo.fr (Seo-Kyeong KIM-BOUDOT) Date: Thu, 22 Apr 2004 17:58:10 +0200 Subject: Paris python user group? References: <408795ee$0$25893$79c14f64@nan-newsreader-02.noos.net> Message-ID: Salut ca me fait penser aux phpbeermeeting tout ca :) Enfin moi pour boire un coup je suis toujours d'accord. c'est quoi ce truc de poster un message en anglais + francais ? sur fr.xxx le francais suffit. et pour l'universalit?, ya esperanto :p le plus simple pour commencer serait de creer une liste de diffusion (mailinglist pour les anglophones), pour ca on a l'embarras du choix (yahoo groups, ou les mailing lists Sympa, etc). From paul at prescod.net Thu Apr 1 11:18:48 2004 From: paul at prescod.net (Paul Prescod) Date: Thu, 01 Apr 2004 08:18:48 -0800 Subject: PLEASE STOP!!! In-Reply-To: <95aa1afa.0404010352.80de14e@posting.google.com> References: <95aa1afa.0404010352.80de14e@posting.google.com> Message-ID: <406C40E8.10209@prescod.net> ...ruining April Fools! The point is to get long-running debates between newbies sucked into believing the joke is real. Michele Simionato wrote: > > Today is April the first ... ;) Camilo Olarte wrote: > > OOUCH ! I Almost believe it! Paul "So I top-posted. What are you going to do about it?" Prescod From no at sp.am Wed Apr 7 03:02:55 2004 From: no at sp.am (DH) Date: Wed, 07 Apr 2004 02:02:55 -0500 Subject: GUI Frameworks in Python? In-Reply-To: References: <930ba99a.0404030246.786455f5@posting.google.com> <8ef9bea6.0404041009.26ae2683@posting.google.com> Message-ID: <8bydnQEwvqo-Ou7dRVn-hQ@comcast.com> Josiah Carlson wrote: >>> That's just one example of how the PyGtk API is simpler. It might >>> not sound like much, but lots of little things like that add up >>> to make me like PyGtk much better. ... > What parts of the 2.4 to 2.5 conversion are steps backward? Here's one example of unneeded extra typing, compared to virtually every other GUI API, to further illustrate Josiah's point: Java drawline: (AWT & Swing) graphics.drawline(x1,y1,x2,y2) Visual Basic drawline: graphics.drawline(pen,x1,y1,x2,y2) pyqt drawline: painter.drawline(x1,y1,x2,y2) anygui drawline: (wraps wxpython and other guis) canvas.drawLine(x1,y1,x2,y2) piddle drawline: (wraps wxpython and other guis) canvas.drawline(x1,y1,x2,y2) pythoncard drawline (wraps wxpython) drawline(x1,y1,x2,y2) pygtk drawline: draw_line(drawable, gc, x1, y1, x2, y2) tkinter drawline: canvas.create_line(x1,y1,x2,y2) pygame drawline: pygame.draw.line(surface,(r,g,b),(x1,y1),(x2,y2)) wxPython 2.4 drawline: wxdc.drawline(x1,y1,x2,y2) wxPython 2.5 drawline: wxdc.drawline (wxPoint(x1,y1),wxPoint(x2,y2)) or the much simpler ((x1,y1),(x2,y2)) or you can do drawlineXY(x1,y1,x2,y2) Admittedly, wxPython is still simpler than OpenGL: def drawline(x1,y1,x2,y2): glBegin (GL_LINES) glVertex2f (x1,y1) glVertex2f (x2,y2) glEnd () From imbosol at aerojockey.invalid Tue Apr 27 22:19:35 2004 From: imbosol at aerojockey.invalid (Carl Banks) Date: Wed, 28 Apr 2004 02:19:35 GMT Subject: Is Perl *that* good? References: <87fzaqmm8t.fsf@strauser.com> <38ec68a6.0404262308.50029919@posting.google.com> Message-ID: Roy Smith wrote: > In article , > Carl Banks wrote: > >> It's worse because, unlike most objects, regexp objects are usually >> global (at least they are when I use them). Moreover, the library >> encourages us to make regexp objects global by exposing the regexp >> compiler. So even if you personally use local regexps (and accept the >> resulting performance hit), many will declare them global. > > I don't see why regexps are usually global. Nor do I see why exposing > the compiler encourages them to be global, or why making them local > should result in a performance hit. Because if regexp objects are local, they have to be recompiled every time you call the function. If you're doing that, you could be taking a performance hit. I guess it depends on your functional style, though. If your scripts have only one or two functions where all the regexps are and it only gets called a few times, then it probably won't matter too much to you. If you do stuff recursively (as I often do) or break up code into smaller functions (as I often do) so that the functions with these regexps get called numerous times, it can help performance to move the compile step out of the functions. The point is, the existence re.compile encourages people to make regexp objects global so they only need to be compiled once, when the module is loaded. Because of this, and especially because regexps are prone to being used in recursive functions and such, it's dangerous to allow them to have state. > I do a lot of regex work. I just looked over a bunch of scripts I > happen to have handy and only found one where I used global regexp > objects. In that script, the regexps were only used in a single > routine, so moving them down in scope to be local to that routine would > have made more sense anyway. Looking back at the code, which I wrote > several years ago, I have no idea why I decided to make them global. Well, that's fine. For the reasons I've stated, I think there are good reasons to not do it the way you did it. -- CARL BANKS http://www.aerojockey.com/software "If you believe in yourself, drink your school, stay on drugs, and don't do milk, you can get work." -- Parody of Mr. T from a Robert Smigel Cartoon From claird at lairds.com Mon Apr 26 09:52:51 2004 From: claird at lairds.com (Cameron Laird) Date: Mon, 26 Apr 2004 13:52:51 -0000 Subject: Is Perl *that* good? (was: How's ruby compare to it older brother python) References: Message-ID: <108q51j4dscn7dc@corp.supernews.com> In article , Leif B. Kristensen wrote: . . . >getting dynamic HTML pages up and running quickly. Perl is great for >its string-handling abilities. (On my Web pages, I actually call a Perl >script from PHP precisely for this reason.) . . . I hear this more often than I understand it. Perl certainly does support many string-oriented operations. What's a speci- fic example, though, of an action you feel more comfortable coding in external Perl? I suspect there's something I need to learn about PHP's deficiencies, or Perl's power. -- Cameron Laird Business: http://www.Phaseit.net From claird at lairds.com Wed Apr 21 10:50:55 2004 From: claird at lairds.com (Cameron Laird) Date: Wed, 21 Apr 2004 14:50:55 -0000 Subject: Python GUI wrapper for a long operation References: <108cnp89aedqp82@corp.supernews.com> Message-ID: <108d2ifgg4fqh7d@corp.supernews.com> In article , Jeff Epler wrote: >To interleave calculation and GUI activity in the same thread, simply >call the "update_idletasks" or "update" method on any Tk widget at >intervals. . [much useful detail] . . Yes and no. First, I want readers to know that they're lucky. Jeff's *good* with Tkinter, among other things Pythonic, and I always seek out his postings for their valuable content. I have particular experience that obliges me to supplement his counsel in specialized areas. The proposition above is slightly fragile in the vicinity of "simply". Some developers never seem to "get the hang" of update(). Update() itself has subtleties, and a significant number of developers like to rework our designs to avoid it; as it turns out, it's possible and desirable in general to rewrite update() uses in terms of transformed, event-oriented segments. Finally, there are some "long operation[s]" that simply are not compatible with the Tcl-based event- orientation behind update(). While I'm sure Fredrik has written on at least some of these matters, I'll not make the time now to track down his essays. For the moment, I recommend the Tcl-targeted , which I think those with an interest in intermediate Tkinter topics find readable. -- Cameron Laird Business: http://www.Phaseit.net From glc at well.com Fri Apr 23 07:34:26 2004 From: glc at well.com (Greg Chapman) Date: Fri, 23 Apr 2004 11:34:26 GMT Subject: problem pickling objects created with the type function References: <85bc2819.0404211357.6ec10ec7@posting.google.com> Message-ID: <2nvh80hafh97pqsqsrgdeh9e2af0f385ql@4ax.com> On 21 Apr 2004 14:57:17 -0700, danny_shevitz at yahoo.com (danny) wrote: >I'm pretty sure the failure is because 'foobar' is never in the global >namespace. If I change the code to foobar = type('foobar',... then >the code works, but I dont' want to do this because I create the class >name in a factory and it is mangled to prevent different invocations >of the factory from having the same class name. > >Does anyone know how to get around this, or how to get 'foobar' = >childType into the global namespace? You should be able to make foobars pickleable without introducing foobar into the global namespace by using a __reduce__ method, see: http://www.python.org/peps/pep-0307.html expecially the section "Extended __reduce__ API". --- Greg Chapman From http Fri Apr 16 16:08:11 2004 From: http (Paul Rubin) Date: 16 Apr 2004 13:08:11 -0700 Subject: Automatic, portable optimization of global access References: <5d83790c.0404150721.46a3b5d0@posting.google.com> <7xvfk17zeg.fsf@ruckus.brouhaha.com> <5d83790c.0404151803.598c1807@posting.google.com> <7xbrlseclf.fsf@ruckus.brouhaha.com> <5d83790c.0404160319.f46f2f9@posting.google.com> Message-ID: <7x1xmnvg7o.fsf@ruckus.brouhaha.com> python at rcn.com (Raymond Hettinger) writes: > > Well, it's possible that builtins get changed too. I've used "len" as > > a variable a few times without realizing that I was clobbering a builtin. > > Paul, I don't know how to say this more clearly. Don't use constant > binding in places where the underlying values can change. I'm saying your optimization is important enough that it should be run on everything, except the rare cases where it's invalid to do so, and running it should not require manual intervention on the user's part. I think the places where the underlying values can change can be detected by the compiler enough of the time to usually run the optimizer. From richie at entrian.com Sat Apr 3 05:13:50 2004 From: richie at entrian.com (Richie Hindle) Date: Sat, 03 Apr 2004 11:13:50 +0100 Subject: [maybe OT] Making posters In-Reply-To: <95aa1afa.0404030143.58c32975@posting.google.com> References: <95aa1afa.0404030143.58c32975@posting.google.com> Message-ID: <9e3t6097tuokt4hu5r11ejgvkqk24341oo@4ax.com> [Michele] > Perhaps this is a bit off topic, but I haven't had look browsing on the > net, so I thought I will try my chance here. I am looking for a > tool taking a postscript file and enlarging it to make a poster. > For instance I want to convert a picture taking a sheet in a poster > made by four sheet that I can compose. Any suggestion? A Python > suggestion would help me to stay on topic ;) You don't mention your platform, but my printer driver (WinXP driver for the Samsumg ML-1210 laser printer) will do this itself for any document - have you had a good dig though your printer driver options? -- Richie Hindle richie at entrian.com From peter at engcorp.com Thu Apr 22 22:10:24 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 22 Apr 2004 22:10:24 -0400 Subject: Why we will use obj$func() often In-Reply-To: <27_hc.23801$dZ1.2716@fed1read04> References: <84Uhc.22278$dZ1.5087@fed1read04> <8AWhc.23114$dZ1.11070@fed1read04> <40883BFE.B381518A@alcyone.com> <27_hc.23801$dZ1.2716@fed1read04> Message-ID: Mark Hahn wrote: > I am serious when I say I think that Python has headed off into egghead land > a bit and I feel that keeps a lot of people from switching to it. I think > that this heady stuff scares them off. Not likely. Most people learning or using Python still have little interest in or need for metaclass programming, and I *strongly* doubt it has scared off more than a handful of people. Likewise, the differences between prototype-based languages and class-based languages do not appear significant enough to be the sole reason to pick one over the other. The community, on the other hand, and the libraries -- well, those are good reasons for picking Python. It will be interesting to see whether Prothon manages to achieve similar success in either area. And if it does, well, see my first point in this sentence again... -Peter From gandreas at no.reply Thu Apr 1 09:47:36 2004 From: gandreas at no.reply (Glenn Andreas) Date: Thu, 01 Apr 2004 08:47:36 -0600 Subject: Prothon Prototypes vs Python Classes References: <569c605ld1cj8fc1emolk08ete0s1prls1@4ax.com> <69cbbef2.0403280928.438d194f@posting.google.com> <69cbbef2.0403311324.32837704@posting.google.com> Message-ID: In article , Joe Mason wrote: > In article <69cbbef2.0403311324.32837704 at posting.google.com>, has wrote: > > Joe Mason wrote in message > > news:... > >> In article <69cbbef2.0403280928.438d194f at posting.google.com>, has wrote: > >> > # Library pseudocode > >> > > >> > _fooRegistry = [] > >> > > >> > obj _Foo: # prototype object > >> > # Foo's code goes here > >> > > >> > def Foo(): # constructor function > >> > newFoo = _Foo.copy() > >> > _fooRegistry.append(newFoo) > >> > return newFoo > >> > > >> > > >> > Dirt simple with not an ounce of class metaprogramming in sight. > >> > >> Is Foo() the standard syntax for making a new _Foo object? If this is a > >> new wrapper you just created, then it's no different than adding a > >> register() method - the user has to know that something different is > >> being done. > >> > >> If Foo() is the standard syntax, and you're just overriding the > >> implementation here, does that get inherited? If so, this missed the > >> condition that only some of the descendants should get added to the > >> registry. If not - well, inheriting the constructor seems like the more > >> useful behaviour in general, so why not? > > > > Don't think you've quite got the point of prototype-based OO yet. > > There's no real 'standard syntax' for making objects; nor is there any > > inheritance, classes, metaclasses, or instances. To create a new > > object from scratch, execute the code that defines it. Alternatively, > > duplicate an existing object. > > There certainly is a standard syntax for making objects. I need to know > how to "duplicate an existing object". Is it "obj.dup()"? > "obj.clone()"? "duplicate obj"? Most probably, the language (or > standard library) defines one of these, and I expect most objects to be > duplicated in the same way. > It can be a bit more subtle than that in a prototype based system, since there are two things that are different, but have nearly identical results, but could both be considered "duplicate an object". In general, you don't want to _duplicate_ the object, but rather use that object as "prototype" for the new object. First, you can make a new object that has all the same slots/properties/attributes as the first object - let's just call that "clone" for now (and we'll assume single inheritence, via a slot called "__parent") > print obj.__parent None > obj.a = 1 > obj.foo = def (): print "a=",self.a > obj.foo() a=1 > obj1 = obj.clone() > print obj1.__parent None > obj.a = 2 # change something in the original object > print obj1.a # unchanged in the "clone" 1 > obj1.foo() a=1 and we'll make the second object that has first object as the __parent (and we'll pretend that the syntax is "new " > obj2 = new obj1 > print obj2.__parent > obj2.foo() a=2 # since it inherits from obj1 (obviously, the object doesn't actually retain the binded local variable name) If we looked at these three objects in a debugger: obj = { __parent: None, a: 1, foo: } obj1 = { __parent: None, a: 2, foo: } obj2 = { __parent: } If we hadn't changed obj1.a, both obj1 and obj2 would behave identically to obj (they all have the same properties, same behavior), even though internally, they are fairly different (obj1 is independant of obj, while obj2 is completely dependant on obj). Since both "data" and "behavior" is inherited, this is different from traditional class/instance organization (where an instance shares its behavior (methods) with all other instances, but has private data). This also makes the issue of "obj2.a = 5" important, since at that point obj2 would normally get it's own value of "a" (and otherwise would inherit the value of obj.a), and you'd want a clean way to alter obj.a from a method in obj2 ("obj2.__parent.a = 3" would work, this is where directed resends are used in Self). In general, you want obj2 (since it inherits everything from obj, much like an instance "inherits" stuff from its superclass), but both are useful. From joe at notcharles.ca Mon Apr 12 02:53:53 2004 From: joe at notcharles.ca (Joe Mason) Date: Mon, 12 Apr 2004 06:53:53 GMT Subject: Is there a boolean(somestring) equivalent of int(somestring). bool('false') -> True References: Message-ID: In article , Paul Prescod wrote: > Maybe in your mind. What about "true", "TRUE", "oui", "1.0", "positive" > and "yeah". How far do you intend to go? Name a single language or > system that treats "True", "on", "1" and "yes" as positive values and > "False", "off", "0" and "no" as negative values. If Python started UniConf http://open.nit.ca/wiki/?page=UniConf (The current list is "true", "yes", "on", and "enabled" evaluate to 1, "false", "no", "off", and "disabled" to 0, anything else is passed through strtol. This is specifically a configuration system, where it makes sense to be forgiving in what you accept, but you did ask for a language *or system*.) Joe From ngps at netmemetic.com Fri Apr 9 08:12:50 2004 From: ngps at netmemetic.com (Ng Pheng Siong) Date: 9 Apr 2004 12:12:50 GMT Subject: user authentication via /etc/passwd|/etc/shadow References: Message-ID: According to Marco Herrn : > And what about the prefix $1$ for md5? When this is available just cut > it off the hash? Yes, don't hash it. > Are there any other forms of such prefixes? $ uname FreeBSD $ man 3 crypt [...] Modular crypt: If the salt begins with the string $digit$ then the Modular Crypt Format is used. The digit represents which algorithm is used in encryption. Following the token is the actual salt to use in the encryption. The length of the salt is limited to 8 characters--because the length of the returned output is also limited (_PASSWORD_LEN). The salt must be termi- nated with the end of the string (NULL) or a dollar sign. Any characters after the dollar sign are ignored. Currently supported algorithms are: 1. MD5 2. Blowfish I believe this $digit$ convention was invented by the BSDs. Cheers. -- Ng Pheng Siong http://firewall.rulemaker.net -+- Firewall Change Management & Version Control http://sandbox.rulemaker.net/ngps -+- ZServerSSL/Zope Windows Installers From peter.maas at mplusr.de Fri Apr 2 10:57:54 2004 From: peter.maas at mplusr.de (Peter Maas) Date: Fri, 02 Apr 2004 17:57:54 +0200 Subject: Creating a matrix? In-Reply-To: References: Message-ID: Peter Hansen wrote: > >>> matrix[1][2] = '1' > >>> matrix > [['0', '0', '1', '0'], ['0', '0', '1', '0'], ['0', '0', '1', '0'], ['0', > '0', '1 > ', '0']] > > Notice that each of the inner lists contains four seperate references > to the string '0', but the outer repetition simply copies the inner > list four times, resulting in four references to the same inner list! > Changing any one element affects the same entry in each of the other > three lists... Sorry: matrix = [['0']*N for i in range(N)] Mit freundlichen Gruessen, Peter Maas -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Hubert-Wienen-Str. 24 Tel +49-241-93878-0 Fax +49-241-93878-20 eMail peter.maas at mplusr.de ------------------------------------------------------------------- From my_full_name_concatenated at myrealbox.com Thu Apr 29 03:03:54 2004 From: my_full_name_concatenated at myrealbox.com (Ivan Karajas) Date: Wed, 28 Apr 2004 23:03:54 -0800 Subject: 404 errors References: <408dcc25$0$16577$5a62ac22@freenews.iinet.net.au> Message-ID: On Tue, 27 Apr 2004 10:46:47 +0200, Tut wrote: > Tue, 27 Apr 2004 11:00:57 +0800, Derek Fountain wrote: > >> Some servers respond with a nicely formatted bit of HTML explaining the >> problem, which is fine for a human, but not for a script. Is there some >> flag or something definitive on the response which says "this is a 404 >> error"? > > Maybe catch the urllib2.HTTPError? This kind of answers the question. urllib will let you read whatever it receives, regardless of the HTTP status; you need to use urllib2 if you want to find out the status code when a request results in an error (any HTTP status beginning with a 4 or 5). This can be done like so: import urllib2 try: asock = urllib2.urlopen("http://www.foo.com/qwerty.html") except urllib2.HTTPError, e: print e.code The value in urllib2.HTTPError.code comes from the first line of the web server's HTTP response, just before the headers begin, e.g. "HTTP/1.1 200 OK", or "HTTP/1.1 404 Not Found". One thing you need to be aware of is that some web sites don't behave as you would expect them to; e.g. responding with a redirection rather than a 404 error when you when you request a page that doesn't exist. In these cases you might still have to rely on some clever scripting. Cheers, Ivan From premshree_python at yahoo.co.in Wed Apr 7 02:34:28 2004 From: premshree_python at yahoo.co.in (=?iso-8859-1?q?Premshree=20Pillai?=) Date: Wed, 7 Apr 2004 07:34:28 +0100 (BST) Subject: pyAlbum.py - Python Album Generator Message-ID: <20040407063428.49036.qmail@web8312.mail.in.yahoo.com> Hello people, I recently updated one of my Python scripts -- pyAlbum.py This is a simple, command-line based, lightweight Python script to create an image album. Of course, there are plenty of image album creation tools -- a lot of them are very good. But, I wanted something very simple, something that doesn't scare the user with too many options. The final album should be clean -- something like what Zope's Image object offers. Here are some of the features of the script: + Thumbnail creation (using a scaling factor that the user enters) + Image creation for the HTML of individual images (again using a scaling factor that the user enters) + The album Index file includes dimensions and file size of each image + The script generates a single CSS -- this makes changing the style very simple + The script runs on the command-line, and does not require any server-side processing Other requirements: + Python Imaging Library (http://www.pythonware.com/products/daily) So, the idea of the script is -- Keep It As Simple As Possible You can see a sample of an album created using this script at http://www.premshree.resource-locator.com/python/pyAlbum/sample/index.htm Oh, and the script itself is available at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/271246 I hope it's useful. Sincerely, Premshree Pillai ________________________________________________________________________ Yahoo! India Insurance Special: Be informed on the best policies, services, tools and more. Go to: http://in.insurance.yahoo.com/licspecial/index.html From mwh at python.net Thu Apr 22 10:27:15 2004 From: mwh at python.net (Michael Hudson) Date: Thu, 22 Apr 2004 14:27:15 GMT Subject: AOP use cases References: <84fc4588.0404140106.3fa0c55@posting.google.com> <0pydnSB4WYuieuLdRVn-hQ@powergate.ca> Message-ID: Jacek Generowicz writes: [...] > Well, that depends on what you think AOP is. [...] > Sorry, this ended up much longer than it should have been. Nevertheless, thank you for it. I was at the PythonUK conference last week, which was part of the ACCU spring conference, and *lots* of people were asking "can you do Aspect Oriented Programming in python?" and my repsonses tended to be much less articulate versions of that post. Cheers, mwh -- In general, I'd recommend injecting LSD directly into your temples, Syd-Barret-style, before mucking with Motif's resource framework. The former has far lower odds of leading directly to terminal insanity. -- Dan Martinez From no at spam.pls Mon Apr 5 04:26:43 2004 From: no at spam.pls (Matthias) Date: 05 Apr 2004 10:26:43 +0200 Subject: Python is faster than C References: Message-ID: <36wn05qkeyk.fsf@hundertwasser.ti.uni-mannheim.de> aahz at pythoncraft.com (Aahz) writes: > While I'm generally in favor of what you're talking about, it seems to a > certain extent that you're simply shifting complexity. Maintaining the > simplicity of the Python VM is an important goal, I think, and some of > your suggestions run counter to that goal. Isn't the whole idea of very high level languages to shift complexity from the user code to the language implementation? That's not a rhetorical question: Why is it that "simplicity of the Python VM is an important goal"? I would guess that overall it pays to have a more complex language implementation and be rewarded by simpler user code: For any decent language there's much more user code out there than language implementation code. One example where Python in the past made (in my opinion, for my particular projects) the wrong choice is speed: People argued that "simplicity of the Python VM" is more important than speed gains. The result (for my code) was that after profiling, etc., I was coding significant parts of my programs in C. No productivity gain observed. With JIT compilation (psyco) this step might become unnecessary: More complex VM, greatly simplified user code. From roman.yakovenko at actimize.com Wed Apr 14 09:21:01 2004 From: roman.yakovenko at actimize.com (Roman Yakovenko) Date: Wed, 14 Apr 2004 16:21:01 +0300 Subject: Unable to create com object - need help Message-ID: <2D89F6C4A80FA547BF5D5B8FDDD04523060C64@exchange.adrembi.com> Sorry, wrong alarm. The only thing that is wrong is an order of class defined in generated module. IEnumUnknown defined after first use. Roman > -----Original Message----- > From: Roman Yakovenko > Sent: Wednesday, April 14, 2004 4:06 PM > To: python-list at python.org > Subject: RE: Unable to create com object - need help > > > I tried your module. It seems that you generate code right :-) > but IEnumUnknown doesn't defined in any file. > I can try to edit ctypes.com.__init__.py to get the desired result. > But before I do this I'd like to ask you do you have more > recent version that fix it. > If so I'll be glad. If not I will try to write a patch. > > Roman > > > -----Original Message----- > > From: Roman Yakovenko > > Sent: Wednesday, April 14, 2004 3:34 PM > > To: python-list at python.org > > Subject: RE: Unable to create com object - need help > > > > > > Thank you very much. I definitly will try your module. > > Also I still have to questions: > > 1. How does VB success to work with this dll? > > 2. Why after using makepy utility I don't get interface > > registered in DiaSource class > > > > I understand that the first question is generic one, and has > > nothing to do with python. > > But any reference to this specifiec topic will be > > appreciated. Also I'd like to know the answer > > to the second question. It will help me a lot in my future work > > > > Roman. > > > > > > > -----Original Message----- > > > From: Thomas Heller [mailto:theller at python.net] > > > Sent: Wednesday, April 14, 2004 2:57 PM > > > To: python-list at python.org > > > Subject: Re: Unable to create com object - need help > > > > > > > > > "Roman Yakovenko" writes: > > > > > > > Hi. I need some help. > > > > Here is my situation. It is a little bit difficult to > > > explain and/or understand. > > > > I'd like to use msdia71.dll. This dll gives you access to > > > program database files > > > > created during a build. I register this dll. This is pure > > com dll. > > > > This dll contains 3 top classes. I'd like to create one of > > > them - DiaSource. > > > > This class implements IDiaDataSource interface. This fact I > > > can see in dia2.idl. > > > > > > > > importlib("stdole2.tlb"); > > > > [ > > > > uuid(e60afbee-502d-46ae-858f-8272a09bd707), > > > > helpstring("DiaSource Class") > > > > ] > > > > coclass DiaSource > > > > { > > > > [default] interface IDiaDataSource; > > > > }; > > > > > > > > after using makepy I get > > > > > > > > class DiaSource(CoClassBaseClass): # A CoClass > > > > # DiaSource Class > > > > CLSID = IID('{E60AFBEE-502D-46AE-858F-8272A09BD707}') > > > > coclass_sources = [ > > > > ] > > > > coclass_interfaces = [ > > > > ] > > > > If I understand right DiaSource doesn't implements > > > IDiaDataSource interface at all. > > > > May be this is a bug, may be I don't understand something. > > > Clarifying this point will be great. > > > > > > I think this has to do with the fact that with pywin32 you > > > cannot access > > > arbitrary com interfaces - only interfaces that either have > > > been wrapped > > > in pythoncom.dll or that derive from IDispatch. The DIA > > > interfaces all > > > derive from IUnknown, so it seems you cannot call them. > > > > > > There is ongoing work in pywin32 named 'universal' or > something like > > > that, but I don't know how far it is. > > > > > > Another possibility is to use ctypes com layer, it has a > > tool somewhat > > > similar to makepy - it's called readtlb.py, and creates > > > python wrappers > > > for com interfaces. ctypes.com has some samples > > > demonstrating all this. > > > > > > HTH, > > > > > > Thomas > > > > > > > > > -- > > > http://mail.python.org/mailman/listinfo/python-list > > > > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > -- > http://mail.python.org/mailman/listinfo/python-list > From rmunn at pobox.com Tue Apr 20 09:32:04 2004 From: rmunn at pobox.com (Robin Munn) Date: Tue, 20 Apr 2004 13:32:04 GMT Subject: tutorials References: Message-ID: Deefex wrote: > hey what's up, i've been looking for online tutorials to learn python on > windows but i can't find anything. does anyone know a good site with > good beginner's python information? thank you very much. Python's own website, http://www.python.org/, contains good beginner's Python information. Start with http://www.python.org/topics/learn/ and explore the links, especially the tutorial links. As for tutorials specific to Python on Windows: most of Python is OS-independent and will work the same no matter what operating system you're running on: Windows, Unix, or Mac. Once you've got a sufficient grasp of Python as a language, then you can start exploring the parts that are specific to Windows. I don't know much about that subject, as I mainly use Linux, but you could start with Mark Hammond's Python for Windows extensions and go from there: http://starship.python.net/crew/mhammond/ -- Robin Munn rmunn at pobox.com From fumanchu at amor.org Sun Apr 4 13:14:22 2004 From: fumanchu at amor.org (Robert Brewer) Date: Sun, 4 Apr 2004 10:14:22 -0700 Subject: Python is faster than C Message-ID: Raymond Hettinger wrote: > [Armin Rigo] > > >>> enumerate([6,7,8,9]) # uh ? > > > > This got me thinking about how much I would like to see the contents > of an iterator at the interactive prompt. >8 > >>> enumerate('abcdefgh') > This would not bring joy to not-repeatable iterators... :( FuManChu From theller at python.net Fri Apr 16 15:35:40 2004 From: theller at python.net (Thomas Heller) Date: Fri, 16 Apr 2004 21:35:40 +0200 Subject: Best IDE? References: <4ace7f9f.0404111147.3120288a@posting.google.com> Message-ID: Peter Hansen writes: > Chuck Spears wrote: >>>CodeWright, now available from Borland. AFAIK, it's feature >>> compatible with Visual SlickEdit, though I think it's available >>> only on multiple Windows platforms. ;-) >>> --dang >> Borland is killing off this project. Am I happy that I dropped CodeWright some years ago, and switched to XEmacs ;-) > Thanks for the tip. References are always nice though, so for > the record: > > http://discuss.fogcreek.com/joelonsoftware/default.asp?cmd=show&ixPost=131490 > > I can't find anything official (from Borland) about this, but the > above note was posted on April 10, not April 1, and says Borland > emailed an announcement to customers, so it seems likely to be true. ;-) http://www.codewright.com/ automatically redirects to http://www.codewright.com/borland/, and this has a link to the open letter to the CodeWright customers. Not too prominent, though. Thomas From steve at ninereeds.fsnet.co.uk Tue Apr 6 10:34:34 2004 From: steve at ninereeds.fsnet.co.uk (Stephen Horne) Date: Tue, 06 Apr 2004 15:34:34 +0100 Subject: Type checking inside a C extension... doesn't throw exception on failure References: <40712D9E.3050802@prescod.net> <407229F6.6080809@yahoo.com> Message-ID: On Tue, 06 Apr 2004 11:54:30 +0800, Jon Perez wrote: >Paul Prescod wrote: > >> It isn't true that PyLong_AsLong does no type checking. It does. It >> reports problems through the standard Python exception system. > >This illustrates a case where a crash occurs instead of an >exception being thrown. Feed spam.getstring() something besides a >string: > >static PyObject *spam_getstring(PyObject *self, PyObject *args) { > PyObject *tup, *a, *b; > > char strstr[100]; > > if (!PyArg_ParseTuple(args, "O", &strobj)) > return NULL; > > // PyString_AsString(strobj); // raises exception > strcpy(strstr,PyString_AsString(strobj)); /* crashes!! */ > > Py_INCREF(Py_None); > return Py_None; >} > >What gives? Shouldn't the exception be raised within PyString_AsString() >before it even gets a chance to return a value to strcpy()? I assume you're talking about when the PyString_AsString *isn't* commented out ;-) Python exceptions aren't converted to C exceptions, and the Python C API doesn't use C exceptions at all. There is a good reason for this. C doesn't have exceptions - C++ does, but this is a C API. Given that C lacks exceptions, there is no practical (and portable) way to forcibly unwind the stack. Even if something could be done with longjump, for instance, there would be the issue of how your function gets to do its cleanup. Therefore, the simplest way for a Python C API function to propogate a Python exception is by returning an error return value to the caller, and keeping associated data in global variables. The caller then takes on the responsibility for propogating the exception up to its caller and so on. Which is precisely what Python appears to do. The caller needs to check for the error value, do any neccessary cleanup, and then propogate the error out of the function. Python C API functions often return zero for error IIRC, so... if (PyString_AsString(strobj) == 0) { return 0; } Should ensure that the Python exception raised by PyString_AsString is propogated correctly. -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From jack at performancedrivers.com Thu Apr 8 14:47:49 2004 From: jack at performancedrivers.com (Jack Diederich) Date: Thu, 8 Apr 2004 14:47:49 -0400 Subject: Special Method and Class In-Reply-To: References: Message-ID: <20040408184749.GA5285@performancedrivers.com> On Thu, Apr 08, 2004 at 08:07:01PM +0200, Yermat wrote: > Hi all, > > Why does special methods not work on class ? Or how to make them work ? > Here a simple example : > > >>> class Test(object): > ... def __repr__(cls): > ... return "" % cls.__name__ > ... __repr__ = classmethod(__repr__) > ... > >>> print repr(Test) > This is your clue, this didn't print for the same reason the __iter__ does work below. The special __method__'s only work for instances of the class and not for the class itself. >>> print repr(Test) >>> print repr(Test()) > import weakref > class RememberInstance(object): > instances = [] > > def __init__(self,name): > self.name = name > self.__class__.instances.append(weakref.ref(self)) > > def __iter__(cls): > for wref in cls.instances: > inst = wref() > if inst: > yield inst > __iter__ = classmethod(__iter__) > > > t1 = RememberInstance('t1') > t2 = RememberInstance('t2') > > for inst in RememberInstance: > print inst.name > drop the __iter__ altogether and just iterate over the class's list for (inst) in RememberInstance.instances: if (inst()): # the weakref hasn't expired print inst().name It is much clearer and less magic to boot. -jackdied From ae Mon Apr 12 16:43:42 2004 From: ae (A Evans) Date: Mon, 12 Apr 2004 13:43:42 -0700 Subject: I am puzled about numbers Message-ID: <107lvs6mree8pee@corp.supernews.com> Hello I came across an interesting loop in math today To me its interesting anyway I don't know if it will interest you var = 999 % 333 print var >>> 0 var = 9999 % 333 print var >>> 9 var = 99999 % 333 print var >>> 99 var = 999999 % 333 print var >>> 0 var = 9999999 % 333 print var >>> 9 var = 99999999 % 333 print var >>> 99 var = 999999999 % 333 print var >>> 0 and so on I guess that just goes to show nine is a universal number or am I just completely insane and everyone knows this already From PeterAbel at gmx.net Fri Apr 2 03:58:15 2004 From: PeterAbel at gmx.net (Peter Abel) Date: 2 Apr 2004 00:58:15 -0800 Subject: splitting one dictionary into two References: <20040401153103.GC4577@jsaul.de> Message-ID: <21064255.0404020058.20a70197@posting.google.com> jsaul wrote in message news:<20040401153103.GC4577 at jsaul.de>... > Hello all, > > I have to split a dict into two dicts. Depending on their values, > the items shall remain in the original dict or be moved to another > one and at the same time be removed from the original dict. > > OK, this is how I do it right now: > > dict1 = { "a":1, "b":3, "c":5, "d":4, "e":2 } > dict2 = {} > klist = [] klist is not necessary because key in dict1 will give you the same but faster. > > for key in dict1: > if dict1[key] > 3: # some criterion > dict2[key] = dict1[key] > klist.append(key) > > for key in klist: > del dict1[key] > > print dict1 > print dict2 > > That means that I store the keys of the items to be removed from > the original dict in a list (klist) and subsequently remove the > items using these keys. > > Is there an "even more pythonic" way? > > Cheers, jsaul One solution could be: >>> dict1 = { "a":1, "b":3, "c":5, "d":4, "e":2 } # a little transfer-function, which deletes an item (k,v) in d and # returns (k,v) >>> transfer=lambda d,(k,v):[d.__delitem__(k)] and (k,v) # transfer the items from one dict into a list and make a dict # from it on the fly >>> dict2=dict([transfer(dict1,(k,v)) for (k,v) in dict1.items() if v>3]) >>> dict1 {'a': 1, 'b': 3, 'e': 2} >>> dict2 {'c': 5, 'd': 4} >>> Regards Peter From Vincent.Raaijmakers at ge.com Wed Apr 7 16:10:44 2004 From: Vincent.Raaijmakers at ge.com (Raaijmakers, Vincent (GE Infrastructure)) Date: Wed, 7 Apr 2004 15:10:44 -0500 Subject: Acceptance test framework Message-ID: <971323274247EB44B9A01D0A3B424C850814D71D@FTWMLVEM02.e2k.ad.ge.com> While 'Googling' and reading old news posts, I can remember that there were already previous questions posted. Of course, now I need them but can't find it anymore. So, can someone give me a good reference to acceptance test frameworks completely written in python? Would fit perfectly in our XP environment and Python test framework we already have. I prefer to have a framework that is XML driven, but it is not required..... Ton of stuff available in Java, but in Python not that much. At least, that tells my 1 hour search experience now. If possible, like to hear some experience as well, pro's and con's. Thanks in advance, and I will continue with the search as well. Vincent From h.b.furuseth at usit.uio.no Sat Apr 3 19:05:32 2004 From: h.b.furuseth at usit.uio.no (Hallvard B Furuseth (nospam nospam)) Date: 04 Apr 2004 02:05:32 +0200 Subject: Python is faster than C References: Message-ID: Armin Rigo wrote: >> Forcing enumerate to return a list would drag not only the entire >> 40GB.csv into memory, but also the entire set of i. Using an iterator >> in this case instead of a list *is* the optimization. > > Yes, and I'm ranting against the idea that the programmer should be > bothered about it, when it could be as efficient automatically. From > the programmer's perspective, iterators are mostly like a sequence > that you can only access once and in order. A better implementation > can figure out for itself when you are only accessing this sequence > once and in order. It seems bad to me to teach programmers to depend on such optimizations happening automatically. Then people will sometimes depend on an optimization at a time Python does not perform it, and the program will unexpectedly try to consume 4G memory or whatever. In particular if too many such optimizations are added, so programmers lose track of which optimizations are performed when. Debugging such a problem will be no fun either, for the same reason. By all means use the same types and language constructs that already exist instead of heaping on new ones, but add a way to say 'optimize this!' and raise an exception if the construct is used in a way which prevents the optimization. -- Hallvard From t-meyer at ihug.co.nz Fri Apr 16 18:19:37 2004 From: t-meyer at ihug.co.nz (Tony Meyer) Date: Sat, 17 Apr 2004 10:19:37 +1200 Subject: Difficulty Finding Python Developers In-Reply-To: <1ED4ECF91CDED24C8D012BCF2B034F1305E11A7F@its-xchg4.massey.ac.nz> Message-ID: <1ED4ECF91CDED24C8D012BCF2B034F13026F2BA3@its-xchg4.massey.ac.nz> > We've worked hard to convince our company to migrate our core > applications to Python, and now we're looking for a Python > developer in Atlanta to handle a short-term (approx. 3 month) > project. But our initial searches have been fairly > unsuccessful. [...] > Suggestions? A couple of days later, it seems to me that a good way to advertise such a position would be to post a message like this on c.l.p and enjoy the interest generated by the resulting thread... =Tony Meyer From davidf at sjsoft.com Thu Apr 22 03:57:48 2004 From: davidf at sjsoft.com (David Fraser) Date: Thu, 22 Apr 2004 09:57:48 +0200 Subject: COM & Python In-Reply-To: References: Message-ID: What about http://www.onlamp.com/pub/a/python/excerpts/chpt20/pythonwin.html (from that book)? Or have you tried wxPython (not COM but great)? David Anand K Rayudu wrote: > Hi Larry, > > Thanks for the suggestion, I have gone through the book, but > unfortunately nothing much is discussed about this topic. > Being new to MFC i am finding it difficult to get started. > I want to just create a dialog box, with my own controls and get the > python call backs for them. > can some one please share some example source code or any experience > regarding this. > Any help will be a great start point for me. > > Regards, > Anand > > > Larry Bates wrote: > >>Get a copy of >>Python Programming on Win32 By Mark Hammond, Andy Robinson >> >>This is the best starting point for you. >> >>Larry Bates >>Syscon, Inc. >> >>"Anand K Rayudu" wrote in message >>news:mailman.752.1082375155.20120.python-list at python.org... >> >> >>>Hi all, >>> >>>I want to use python with COM extension. I am successful using python as >>>client. >>>I could interact to my application through COM interfaces from python. >>> >>>I also want to use the win32ui layer, which wrapped all MFC user >>>interface functionality. >>>I am just wondering if some on can guide me with some documentation on >>>using them. >>>I want to know how the call backs are handled in particular. >>>Any sample code will be a great start for me. >>>If this is possible I can create any dialog boxes with any controls from >>>python itself!! :-) >>>And take advantage of MFC's View , scroll view and so on. Just exciting!! >>> >>>Thanks in advance, >>>Anand >>> >>> >>> >>> >>> >>> >> >> >> >> > From paddy3118 at netscape.net Mon Apr 19 02:50:17 2004 From: paddy3118 at netscape.net (Paddy McCarthy) Date: 18 Apr 2004 23:50:17 -0700 Subject: Threats to the: Daily Python URL! Message-ID: <2ae25c6b.0404182250.4c5bc870@posting.google.com> I sent the following this morning: -------- Original Message -------- Subject: Threats to the: Daily Python URL! Date: Mon, 19 Apr 2004 07:50:04 +0100 From: Donald 'Paddy' McCarthy To: daily at pythonware.com Hi, I read your 'Administrative note' at http://www.pythonware.com/daily/ today Please don't stop the excellent work that you do. I don't know what threats and insults you suffered but I would like to ensure you that I for one read the column and value it. Thanks, Paddy. From edcjones at erols.com Sat Apr 17 12:21:30 2004 From: edcjones at erols.com (Edward C. Jones) Date: Sat, 17 Apr 2004 12:21:30 -0400 Subject: Creating function object from text Message-ID: <40815ab3$0$16479$61fed72c@news.rcn.com> Suppose I have a piece of text that defines a function: text ="""\ def fun(i): return i + 2 """ How do I turn this into a function object, f, which can be called or passed around? From newsuser at itgoesclick.com Wed Apr 21 12:23:25 2004 From: newsuser at itgoesclick.com (Noah from IT Goes Click) Date: Wed, 21 Apr 2004 16:23:25 GMT Subject: This is very simple question In-Reply-To: References: Message-ID: <1exhc.198230$Ig.10697@pd7tw2no> I'm not sure those are factors? But then again I never was good at math for say 13 you could just count up by two and then find the largest number you can make of the twos and then move down until you find the next one and then add 1 say you start with 13=[2,2,2,2,2,2,1] ? then you know you have [12,1] 12 is a multiple of 2 or do you want powers? if you want powers you could make the nessisary logic adjustments Why exactly do you want this anyways? Eric wrote: > I would want to obtain a list of factors (multiples of 2) given a > prime number in python. > > For example 13=[8,4,1], 5=[4,1], 7=[4,2,1], 15=[8,4,2,1] > > I would appreciate a fuction which would do this. > > Eric From tim.golden at viacom-outdoor.co.uk Wed Apr 21 04:11:47 2004 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Wed, 21 Apr 2004 09:11:47 +0100 Subject: how to calculate correctly the cluster size Message-ID: Josiah> The Windows 2k "Disk Administrator" software for Josiah> 2K always uses 4k cluster sizes by default. Josiah> I believe your varied cluster sizes are the Josiah> result of using Partition Magic to create them. FWIW, the FORMAT command does offer the possibility of selecting different cluster sizes. I've never used it personally (and I'm not about to try it on this machine, either!) FORMAT volume [/FS:file-system] [/V:label] [/Q] [/A:size] [/C] [/X] [...] /A:size Overrides the default allocation unit size. Default settings are strongly recommended for general use. NTFS supports 512, 1024, 2048, 4096, 8192, 16K, 32K, 64K. FAT supports 512, 1024, 2048, 4096, 8192, 16K, 32K, 64K, (128K, 256K for sector size > 512 bytes). FAT32 supports 512, 1024, 2048, 4096, 8192, 16K, 32K, 64K, (128K, 256K for sector size > 512 bytes). Note that the FAT and FAT32 files systems impose the following restrictions on the number of clusters on a volume: FAT: Number of clusters <= 65526 FAT32: 65526 < Number of clusters < 268435446 Format will immediately stop processing if it decides that the above requirements cannot be met using the specified cluster size. NTFS compression is not supported for allocation unit sizes above 4096. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star Internet. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From fumanchu at amor.org Wed Apr 21 14:17:07 2004 From: fumanchu at amor.org (Robert Brewer) Date: Wed, 21 Apr 2004 11:17:07 -0700 Subject: Stupid Regex Question Message-ID: Fredrik Lundh wrote: > Jonas Galvez wrote: > > > And I do it by 'hand' hehe :-) I didn't do any 'top-posting' at all, > > a few posts back, you "top-posted" a followup to your own post. I do it by hand, too. But cf. http://article.gmane.org/gmane.comp.python.general/339488, the post to which I originally replied. ;) FMC From no.email at please.com Sat Apr 10 10:37:59 2004 From: no.email at please.com (Stevie_mac) Date: Sat, 10 Apr 2004 15:37:59 +0100 Subject: Static Data? Message-ID: <2FTdc.56817$Id.5813@news-binary.blueyonder.co.uk> I need to have a static class data member like c (see semi pseudo-like code below). How can I achieve this? class object static _ID _ID = _ID + 1 self.ID = _ID class group . . . def AddObject(self,obj) objs.append(obj) def GetObject(self,iWhich) return objs[iWhich] g = group() o1=object() #gets ID of 1 o2=object() #gets ID of 2 o3=object() #gets ID of 3 g.append(o2) #store object with ID of 2 g.append(o3) #store object with ID of 3 g.append(o1) #store object with ID of 1 print g.GetObject(0).ID #print ID of group object 0 print g.GetObject(1).ID #print ID of group object 1 print g.GetObject(2).ID #print ID of group object 2 >>> 2 >>> 3 >>> 1 obviously this code is duff, its the solution I need. Cheers Stevie_Mac. From db3l at fitlinxx.com Fri Apr 23 15:13:11 2004 From: db3l at fitlinxx.com (David Bolen) Date: 23 Apr 2004 15:13:11 -0400 Subject: Multi-threaded printing and IOErrors in Windows References: <10nll1-rt5.ln1@home.rogerbinns.com> Message-ID: "Roger Binns" writes: > When using py2exe, the stdout doesn't go anywhere anyway > (it is gui app not a console app). > > The bizarre thing is that the IOError is very infrequent, > but very annoying when it happens. Have you tried replacing sys.stdout with your own object that just throws away anything it is given? If you're not getting the output anywhere anyway, it would avoid any attempt to actually use the underlying I/O facilities. You could conditionalize this code based on whether or not you were running under py2exe. I know there can be an issue under Windows under some startup scenarios where you don't actually have opened O/S filesystem handles for the handles underlying stdin/stdout (which can cause this sort of problem), such as running as a service, but haven't normally had this problem with GUI applications. Although it may matter on how you are starting the application (from a command line, the start menu, as a service, etc...), since it will inherit its parent environment. If that's the problem, I'd expect it to happen any time actual I/O was attempted. However, since there is probably some buffering going on beneath the level of print within the underlying C library, maybe the randomness of the error you are seeing is due to how long it takes to print enough data to cause the C library to attempt to flush the data to the underlying O/S filesystem handle. If that were the case, doing some test prints in your code of very long strings (the C buffer is probably anywhere from 2-8K) should be able to reproduce the problem more reliably. -- David From pirx at python.net Sun Apr 4 22:56:07 2004 From: pirx at python.net (Christian Tismer) Date: Mon, 05 Apr 2004 04:56:07 +0200 Subject: Fake post alert(was: Stackless Website down, Project gone, I'm dead.) In-Reply-To: <20040402195104.186481807.eric@zomething.com> References: <20040402195104.186481807.eric@zomething.com> Message-ID: <4070CAC7.80901@python.net> Eric @ Zomething wrote: > someone identified as "Christian Tismer" wrote: > > >>I don't deserve this honor, since I didn't write that nonsense. >>But many thanks, anyway. > > > per the headers rec'd- > > this post: gd31e.g.pppool.de ([80.185.211.30] > the fool post: gd31e.g.pppool.de ([80.185.211.30] Yes, it was the same company network. Not going into details... ciao - chris From junkmail at solumslekt.org Tue Apr 6 08:12:53 2004 From: junkmail at solumslekt.org (Leif B. Kristensen) Date: Tue, 06 Apr 2004 14:12:53 +0200 Subject: Up to 80 percent off on medication, Python. References: <1081199068.13889.0@eunomia.uk.clara.net> Message-ID: Timo Virkkala wrote: > Garry Knight wrote: >> In message , >> Moon D. Rungs wrote: >>>Python, searching for a source to purchase medication? >>>A moment's insight is sometimes worth a life's experience. >>>The quality of decision is like the well-timed swoop of a falcon >>>which enables it to strike and destroy its victim. There is a >>>tendency for things to right themselves. >> You should be *taking* your medication, not trying to sell it on to >> others... > > Especially to a language. Or a snake. Either way, it's a futile > attempt. =) Some need of medication for a flying circus might in principle be conceivable. regards, -- Leif Biberg Kristensen http://solumslekt.org/ Validare necesse est From davidf at sjsoft.com Wed Apr 21 06:47:20 2004 From: davidf at sjsoft.com (David Fraser) Date: Wed, 21 Apr 2004 12:47:20 +0200 Subject: Python 2.3.3 super() behaviour In-Reply-To: <40864ea6$0$25528$afc38c87@news.easynet.fr> References: <40863bd7$0$25528$afc38c87@news.easynet.fr> <40864674$0$24834$afc38c87@news.easynet.fr> <40864ea6$0$25528$afc38c87@news.easynet.fr> Message-ID: super is not going to be helpful here, so why not call the X.__init__ functions explicitly? Since you *need* multiple __init__ calls from the multiply-inherited class, super isn't going to work... Nicolas Lehuen wrote: > The only problem I have is that I want to build a multiple inheritance > involving an object which does not cooperate, namely : > > class T(object): > def __init__(self): > super(T,self).__init__() > > class TL(list,object): > def __init__(self) > super(TL,self).__init__() > > In this case, T.__init__ is not called, because list.__init__ does not use > super(). The only clean way to proceed is to change the inheritance order : > TL(T,list). This way, both constructors are called. > > Here is another example which exhibits the behaviour : > > class A(object): > def __init__(self): > super(A,self).__init__() > print 'A' > > class B(object): > def __init__(self): > print 'B' > > class C(B,A): > def __init__(self): > super(C,self).__init__() > print 'C' > > class D(A,B): > def __init__(self): > super(D,self).__init__() > print 'D' > > >>>>C() > > B > C > <__main__.C object at 0x008F3D70> > >>>>D() > > B > A > D > <__main__.D object at 0x008F39F0> > > The problem is that if you go further down the inheritance, the behaviour is > even more complicated : > > class E(object): > def __init__(self): > super(E,self).__init__() > print 'E' > > class F(C,E): > def __init__(self): > super(F,self).__init__() > print 'F' > > class G(D,E): > def __init__(self): > super(G,self).__init__() > print 'G' > > >>>>F() > > B > C > F > <__main__.F object at 0x008F3D70> > >>>>G() > > B > A > D > G > <__main__.G object at 0x008F3EF0> > > class H(E,C): > def __init__(self): > super(H,self).__init__() > print 'H' > > class I(E,D): > def __init__(self): > super(I,self).__init__() > print 'I' > > >>>>H() > > B > C > E > H > <__main__.H object at 0x008F3E30> > >>>>I() > > B > A > D > E > I > <__main__.I object at 0x008F3FD0> > > So the conclusion is : never do that :). Another more constructive > conclusion would be : always put the most cooperative classes first in the > inheritance declaration, provided that it doesn't interfere with your needs. > A class which has an uncooperative ancestor is less cooperative than a class > which has only cooperative ancestors. > > Regards, > Nicolas > > "Nicolas Lehuen" a ?crit dans le message > de news:40864674$0$24834$afc38c87 at news.easynet.fr... > >>OK, I get it now, thanks. >> >>super() method calls should only be used for method involved in >>diamond-shaped inheritance. This is logical since in this case the base >>classe (from which the diamond-shaped inheritance starts) defines the >>interface of the method. >> >>This solves another question I was asking myself about super() : "how can > > it > >>work when the method signature differ between B and C ?". Answer : the >>method signature should not change because polymorphic calls would be >>greatly endangered. The base class defines the signature of the method > > which > >>must be followed by all its children, this way super() can work properly. >> >>The base method signature is not enforced by Python, of course, but you'd >>better respect it unless you get weird result in polymorphic calls. >> >>Regards, >>Nicolas >> >>"Peter Otten" <__peter__ at web.de> a ?crit dans le message de >>news:c65fbo$1q4$05$1 at news.t-online.com... >> >>>Nicolas Lehuen wrote: >>> >>> >>>>Hi, >>>> >>>>I hope this is not a FAQ, but I have trouble understanding the > > behaviour > >>>>of the super() built-in function. I've read the excellent book 'Python >> >>in >> >>>>a Nutshell' which explains this built-in function on pages 89-90. > > Based > >>on >> >>>>the example on page 90, I wrote this test code : >>>> >>>>class A(object): >>>> def test(self): >>>> print 'A' >>>> >>>>class B(object): >>>> def test(self): >>>> print 'B' >>>> >>>>class C(A,B): >>>> def test(self): >>>> super(C,self).test() >>>> print 'C' >>>> >>>>print C.__mro__ >>>>c=C() >>>>c.test() >>>> >>>>The output is : >>>>(, , , > > >>>>'object'>) >>>>A >>>>C >>>> >>>>Whereas I was expecting : >>>>(, , , > > >>>>'object'>) >>>>A >>>>B >>>>C >>>> >>>>Was I wrong to expect this (based on what I've read ?) >>> >>>As soon as a test() method without the super(...).test() is reached, no >>>further test methods will be invoked. Only the first in the list of base >>>classes will be invoked. If I'm getting it right you have to do > > something > >>>like: >>> >>>class Base(object): >>> def test(self): >>> print "base" >>> >>>class D1(Base): >>> def test(self): >>> super(D1, self).test() >>> print "derived 1" >>> >>>class D2(Base): >>> def test(self): >>> super(D2, self).test() >>> print "derived 2" >>> >>>class All(D1, D2): >>> pass >>> >>>All().test() >>> >>>Here all cooperating methods have a super() call, and the base class > > acts > >>as >> >>>a showstopper to prevent that Python tries to invoke the non-existent >>>object.test(). >>> >>>Peter >>> >>> >>> >> >> > > From tzot at sil-tec.gr Fri Apr 2 10:23:05 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Fri, 02 Apr 2004 18:23:05 +0300 Subject: An attempt at guessing the encoding of a (non-unicode) string References: Message-ID: <671r60l5atp68s3auh4l8htoi6p1er1udp@4ax.com> On Fri, 02 Apr 2004 15:05:42 GMT, rumours say that Jon Willeke might have written: >Christos TZOTZIOY Georgiou wrote: >> >> This could be implemented as a function in codecs.py (let's call it >> "wild_guess"), that is based on some pre-calculated data. These >> pre-calculated data would be produced as follows: >... [Jon] >The representative text would, in some circles, be called a training >corpus. See the Natural Language Toolkit for some modules that may help >you prototype this approach: > > > >In particular, check out the probability tutorial. Thanks for the hint, and I am browsing the documentation now. However, I'd like to create something that would not be dependent on external python libraries, so that anyone interested would just download a small module that would do the job, hopefully good. -- TZOTZIOY, I speak England very best, Ils sont fous ces Redmontains! --Harddix From mogmios at mlug.missouri.edu Wed Apr 28 23:44:08 2004 From: mogmios at mlug.missouri.edu (Michael) Date: Wed, 28 Apr 2004 20:44:08 -0700 Subject: Is classless worth consideration In-Reply-To: <1090r77d97k0tb1@news.supernews.com> References: <1090r77d97k0tb1@news.supernews.com> Message-ID: <40907A08.6000604@mlug.missouri.edu> >It's just occured to me that backing into that particular >issue might work: use class methods and never bother >with instantiating the classes at all. I'm not sure what >we'd lose. (possibly descriptors?) > You can already use: class test: x = 1 t = test print t.x Is there any way to to call a class method without making an instance of that class? To me that would be useful because you could mimic modules without having to create a sepperate file. Or is there already a way to do that? From dwimansjur at hotmail.com Fri Apr 30 07:36:42 2004 From: dwimansjur at hotmail.com (Dwi Sianto Mansjur) Date: 30 Apr 2004 04:36:42 -0700 Subject: PYTHONSTARTUP and Cygwin References: <9c1c646f.0404291107.5a6137dc@posting.google.com> <%Sckc.8205$f_5.1627@lakeread01> Message-ID: <9c1c646f.0404300336.8208272@posting.google.com> yes, it works after I use: export PYTHONPATH=/home/Cherna/DevelopingTools I set the shell/environment variable in Cywin.bat I thought that will take car of the business. But now it works, Thanks a lot. Steve Holden wrote in message news:<%Sckc.8205$f_5.1627 at lakeread01>... > Dwi Sianto Mansjur wrote: > > I tried to set up PYTHONPATH in cygwin but it doesn't work. > > Any clue why ? > > The following is my session. > > > > $ echo $PYTHONPATH > > /home/Cherna/86_DevelopingTools:/home/Cherna/87_TestingCorpus > > > > $ echo $PYTHONSTARTUP > > /home/Cherna/86_DevelopingTools:/home/Cherna/87_TestingCorpus > > > > $ python > > Python 2.3.3 (#1, Dec 30 2003, 08:29:25) > > [GCC 3.3.1 (cygming special)] on cygwin > > Type "help", "copyright", "credits" or "license" for more information. > > > >>>>import sys > >>>>sys.path > > > > ['', '/usr/lib/python23.zip', '/usr/lib/python2.3', > > '/usr/lib/python2.3/plat-cygwin', '/usr/lib/python2.3/lib-tk', > > '/usr/lib/python2.3/lib-dynload', '/usr/lib/python2.3/site-packages', > > '/usr/lib/python2.3/site-packages/Numeric'] > > > > thanks. > > You probably forgot to export them to put them in the environment? > > $ export PYTHONPATH=/c/testwebapp:/c/Steve > > sholden at DELLBOY /c/testwebapp/views > $ echo $PYTHONPATH > /c/testwebapp:/c/Steve > > sholden at DELLBOY /c/testwebapp/views > $ python > Python 2.3.3 (#1, Dec 30 2003, 08:29:25) > [GCC 3.3.1 (cygming special)] on cygwin > Type "help", "copyright", "credits" or "license" for more information. > >>> import sys > >>> sys.path > ['', '/c/testwebapp', '/c/Steve', '/usr/lib/python23.zip', > '/usr/lib/python2.3', '/usr/lib/python2.3/plat-cygwin', > '/usr/lib/python2.3/lib-tk', '/usr/lib/python > 2.3/lib-dynload', > '/usr/lib/python2.3/site-packages'] > >>> > > Certainly works for me, anyhow ... > > regards > Steve From rawbobb at hotmail.com Mon Apr 12 09:17:41 2004 From: rawbobb at hotmail.com (bobb) Date: Mon, 12 Apr 2004 13:17:41 GMT Subject: A new OS References: <107k441hitt2ld9@corp.supernews.com> Message-ID: This reminds me of the discount book I saw once "How to build your own 32 bit operationg system" I wouldn't bother. (I agree w/ peter hansen) "A Evans" wrote in message news:107k441hitt2ld9 at corp.supernews.com... > Hello Everyone I am working towards starting a project developing a new > Operating System using the Python language (or a derivative thereof). As > recommended on this forum I am asking if people are interested in something > like this and ask who would be willing to support a project this large. > > Any and all ideas are welcome this message is just to see what kind of > support this project would recieve > > Cheers > > Andrew > > From jepler at unpythonic.net Sun Apr 11 18:35:14 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Sun, 11 Apr 2004 17:35:14 -0500 Subject: Is there a boolean(somestring) equivalent of int(somestring). bool('false') -> True In-Reply-To: References: Message-ID: <20040411223514.GA30373@unpythonic.net> The reason that >>> bool('false') returns True is the same reason that >>> not 'false' is False: A non-empty string, when treated as a boolean, is true. Changing the meaning of bool() is not likely to happen. Here's one piece of code you might try to get the behavior you desire: true_values = '1 yes true on'.split() false_values = '0 no false off'.split() def parse_boolean_value(s): if s in true_values: return True if s in false_values: return False raise ValueError 'i in seq' is just like checking whether any item in seq is equal to i. If seq is a dictionary or a set (or defines __contains__), this test can be a little more efficient, but the efficiency is unlikely to matter when there are only 4 items. Jeff From peter at engcorp.com Fri Apr 2 12:05:36 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 02 Apr 2004 12:05:36 -0500 Subject: Making the Zen of Python more useful In-Reply-To: References: <106qp0uivlefo40@corp.supernews.com> <-5ydnTEmxfuZHvDdRVn-iQ@powergate.ca> Message-ID: Andrew Henshaw wrote: > In article <-5ydnTEmxfuZHvDdRVn-iQ at powergate.ca>, peter at engcorp.com says... > my main > problem was with the automatic printing of the text upon import. Obviously, > that functionality needs to remain. It would just be nice if there was > some clean way of (sometimes) using the module without it. I don't think your particular use case was known to the developers when they implemented that module. Maybe you should suggest it as an enhancement on Sourceforge. Be sure to include a patch! ;-) -Peter From hwlgw at hotmail.com Mon Apr 26 03:56:13 2004 From: hwlgw at hotmail.com (Will Stuyvesant) Date: 26 Apr 2004 00:56:13 -0700 Subject: AOP use cases References: <84fc4588.0404140106.3fa0c55@posting.google.com> <0pydnSB4WYuieuLdRVn-hQ@powergate.ca> Message-ID: > [Eric Eide, from the academics] > Will> Forget about *real* real-world examples, these people just want > Will> to get papers published. > > Perhaps that explains IBM's excitement about aspect-oriented technologies, as > reported here: > > > > Thank you for the links. > Will> Usability is considered of minor impportance. > > Perhaps that explains why AspectJ 1.1 received a Jolt Productivity Award in > the "Languages and Development Environments" category, as reported here: > > AspectJ is for Java... > > Will> I have come to the conclusion that AOP is nothing more than what > Will> I expect from a decent programmer: a good, or at least > Will> reasonable, design of software in the first place. > > I would say that the *goal* of AOP is "nothing more" that what you would > expect from a good programmer: good implementation of good software > designs. AOP is a an approach that augments existing approaches, such as > OOP, for obtaining that goal. One of my original points was that Java needs "AOP" to solve problems imposed by the static typing system. The links you provide are Java-centric. A better designed programming language, like the dynamicall typed language Python, does not need "AOP". It is up to the software designer to make good designs, orthogonal where needed, with separation of concerns, etc. From michele.simionato at poste.it Thu Apr 15 04:33:02 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 15 Apr 2004 01:33:02 -0700 Subject: Generic constructors and duplication of internal Python logic References: <87ekqq41ya.fsf@pobox.com> Message-ID: <95aa1afa.0404150033.79a53e1a@posting.google.com> jjl at pobox.com (John J. Lee) wrote in message news:<87ekqq41ya.fsf at pobox.com>... > I have to check things like: > > -are there too many positional arguments? > -any unexpected keyword arguments? > -multiple keyword arguments? > -any duplication between positional and keyword arguments? > > etc. > > Surely there's some easy way of making use of Python's internal logic > here? For some reason, I can't see how. Can anybody see a way? > > > John Have you thought of performing the checks in the __call__ method of a custom metaclass? Michele Simionato From newsgroups at jhrothjr.com Sun Apr 4 21:23:00 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Sun, 4 Apr 2004 21:23:00 -0400 Subject: Difference between default arguments and keyword arguments References: <10713rf4bjl1bab@news.supernews.com> Message-ID: <1071dast63t0g39@news.supernews.com> "Edward Diener" wrote in message news:yD1cc.12064$yN6.3263 at newsread2.news.atl.earthlink.net... > Roy Smith wrote: > > "John Roth" wrote: > >> In going through the tutorial I also noticed that it explained > >> the * notation, but not the ** notation. I think this also needs > >> to be repaired - if one is in the tutorial, both should be. > > > > I suspect this will be an unpopular opinion, but I don't think either > > belong in the tutorial. I certainly wouldn't object to removing them; that's why I said "if". > > I think the function of a tutorial is to introduce somebody to the > > main features of the language, not cover every nook and cranny of the > > syntax. The * and ** syntaxes (synti?), while certainly useful, are > > also somewhat advanced topics. I think their appearance in an > > introductory document is misplaced. > > Along the same lines, I would like to add to that the explanation for > classes in the tutorial is very poor since it assumes a much higher > understanding of Python than a tutorial should about the language. A much > simpler and more direct explanation regarding classes in Python would be > much better. While I mostly got it because I have programmed extensively in > other OOP languages, I would expect your average Python beginner to be > completely lost by much of the high-level explanation in that chapter. > Whoever wrote it was much more interested in explaining the theory of > classes in Python, to beginners no less !, than they were toward explaining > what classes are in Python and how to use them. And why iterators and > generators are included in that chapter are beyond me. Also the tutorial > mentions some usages of classes, in previous sections, before the > explanation of classes occur, which I feel is definitely a mistake. One of the things going on here is that the tutorial has grown over the releases; it's not entirely clear what level of expertise is expected for a reader. As you say, there are topics that are fairly advanced. On the other hand, since the libraries are shipped in source, and since they do use all of those features, I think they should be mentioned in some kind of tuorial. John Roth > > From peter9547 at btinternet.com Fri Apr 2 06:37:49 2004 From: peter9547 at btinternet.com (Peter MacKenzie) Date: Fri, 2 Apr 2004 11:37:49 +0000 (UTC) Subject: emergent/swarm/evolutionary systems etc References: Message-ID: And how near that future was! I've been going over the open/read/edit file stuff again, trying to make it work, but I'm still having no success. I'm not sure if I'm missing something fundamental (like a frontal lobe), or if there's some less worrying problem afoot, but this is what I've been trying. I've put it through many iterations, dropping and adding brackets and full-stops, playing around with the structure and grammar etc, but nothing seems to work. import sys file = 'myfile.txt' open(file,'r+b') file.write("some string of what you want to write") file.close() When I run this, it returns the message: Traceback (most recent call last): File "C:\Python23\openfile.py", line 5, in ? file.write()("some string of what you want to write") AttributeError: 'str' object has no attribute 'write' It must be something really simple that I've overlooked or failed to grasp, but I've exhausted my willingness to continue experimenting and attempting to reverse engineer code from the library modules. Please help. My brain hurts. From peter at engcorp.com Fri Apr 2 07:03:11 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 02 Apr 2004 07:03:11 -0500 Subject: emergent/swarm/evolutionary systems etc In-Reply-To: References: Message-ID: Peter MacKenzie wrote: > import sys This part is useless for the four lines that follow, but of course you'll need it if you ever want to access anything that really is in the sys module... > file = 'myfile.txt' Here the name "file" is bound to a string. > open(file,'r+b') Here you call a builtin and pass it two strings. Functions can "never" modify what the arguments are bound to, so this cannot modify the name "file" to something else. Clearly not what you intended. Note that open() really *returns* the newly created file object, so you should be assigning the result as: file = open(filename, 'r+b') Of course, now you need a "filename" name, which is what the first line should be doing: filename = 'myfile.txt' # instead of "file = ..." > file.write("some string of what you want to write") > file.close() These two will now work. Why don't you run through the Python tutorial first, since these are pretty basic questions, some of which will be resolved if you go the defined routes first. There are also other good Python/newbie resources linked to from the web site if you go there and poke around. -Peter From __peter__ at web.de Sun Apr 11 04:16:19 2004 From: __peter__ at web.de (Peter Otten) Date: Sun, 11 Apr 2004 10:16:19 +0200 Subject: Static Data? References: <2FTdc.56817$Id.5813@news-binary.blueyonder.co.uk> Message-ID: Stevie_mac wrote: > In Jeffs solution, Is self._ID the same variable as _ID (declared > immediately after class Counted). Is there 3 _IDs? If you have the time, Jeff Epler's code with annotations: class Counted: _ID = 0 # set the class attribute; same as Counted._ID = 0 def __init__(self): Counted._ID += 1 # increment the class attribute self._ID = Counted._ID # set the instance attribute to the # current value of the class attribute > could you explain (nothing fancy, just brief) the meaning of declaring > variables in different > locations (like self, below class, as part of class, in a class def). > This would be greatly appreciated. > > and Peters solution > class Object: > _ID = 1 > def __init__(self): > self.ID = Object._ID > Object._ID += 1 > Is Object._ID a class instance variable and self.ID a 'shared' class > variable This is basically the same as Jeff's. I just chose different names for the class attribute (_ID) and instance attribute (ID). If you set an attribute in the class, class Object: clsattr = 1 that is the same as class Object: pass Object.clsattr = 1 If you set an instance attribute you always need the instance: inst = Object() inst.attr = 2 Inside a method it's the same, only the instance will most likely be named self. class Object: def method(self, newvalue): self.attr = newvalue Now for attribute lookup: inst.attr will first look up attr in the instance, and if it's not there, it will fall back to the class: >>> class Object: ... pass ... >>> Object.attr = "in class" >>> inst = Object() >>> inst.attr 'in class' >>> inst.attr = "in instance" >>> inst.attr 'in instance' The class attribute is still there, only "shaded" bye the instance attribute: >>> Object.attr 'in class' Now let's delete the instance attribute: >>> del inst.attr >>> inst.attr 'in class' The class attribute becomes visible again. Once you have understood the above, classmethods are just a another way to access the class instead of the instance. The advantage over an explicit use of the class identifier is that with inheritance they always provide the actual class: >>> class Object(object): ... def method(cls): ... print cls.__name__ ... method = classmethod(method) ... >>> class Sub(Object): ... pass ... >>> Object().method() Object >>> Sub().method() Sub Peter From google0 at lazytwinacres.net Sat Apr 3 08:02:32 2004 From: google0 at lazytwinacres.net (Dang Griffith) Date: Sat, 03 Apr 2004 13:02:32 GMT Subject: emergent/swarm/evolutionary systems etc References: Message-ID: <2de080a12a9c6c488149f4b031bb46be@news.teranews.com> On Fri, 2 Apr 2004 16:58:32 +0000 (UTC), "Peter MacKenzie" wrote: >Spreadsheets do seem to be an attractive option, but the benefits are not >without their detractors: ... >-Require no/limited skill acquisition (being familiar and honest with my own >psychological composition, I know that the only way I'm likely to develop a >fair degree of programming competence is if there's a driving pressure to do >so. It's something I'd like to learn, and this gives me the excuse/leverage >to do so.) Sorry I can't help you with that one--it's for you to decide. >Unknowns: Time series graphical output would be necessary, even if it's >very primitive. Do you know if the spreadsheet could be set up in such a >way that cells would change colour depending on their values, or if the >graph making facilities would be able to create reasonable representations >of said values so that a series of graphs would be capable of showing up >phenomena with fluidic (wavelike, turbulent, etc) characteristics? I don't know what spreadsheet you're using, but I know Microsoft Excel support conditional coloring. >I'm afraid the temptation to take the hard route my prove too great >(psychological paradoxes: I always feel good about feeling so terrible about >these things after I've passed the point of no return in the undertaking, >and the enormity of the task at hand sinks in - it's a whole adrenalin >thing), but I'd still like to make a comprehensive assessment of my options >before I commit to anything. It's a complex project. I'm pretty sure a spreadsheet is capable of performing the calculations, but it may not be the best to provide the graphical result you're looking for. On the other hand, maybe it could generate the numbers for the graphics, and then you could have a second program that reads the numbers to perform only the graphics operations. I agree with Josiah--two months is tight. I suggest if you're more comfortable with a spreadsheet, start with a minimal "program" in the spreadsheet. Realize that writing a python program will require you to make many of the same design / algorithm decisions as the spreadsheet. --dang From donn at u.washington.edu Wed Apr 28 17:21:18 2004 From: donn at u.washington.edu (Donn Cave) Date: Wed, 28 Apr 2004 14:21:18 -0700 Subject: Why we will use obj$func() often References: <84Uhc.22278$dZ1.5087@fed1read04> <8AWhc.23114$dZ1.11070@fed1read04> <40883BFE.B381518A@alcyone.com> <27_hc.23801$dZ1.2716@fed1read04> <40887145.789A2FE8@alcyone.com> <7cki80hj976bia36lhf9er97v073o1pqvm@4ax.com> <5vJjc.13116$Qy.1954@fed1read04> <52Ujc.16275$Qy.3111@fed1read04> Message-ID: In article <52Ujc.16275$Qy.3111 at fed1read04>, "Mark Hahn" wrote: > Donn Cave wrote: > > In article <5vJjc.13116$Qy.1954 at fed1read04>, > > > Well, in a sense this (&var) is a simplistic avoidance of scope. Scope > > is how unqualified identifiers are resolved. > > Scope is a noun, not a verb. To me a scope is just a namespace defined by > syntax. There are many ways to specify what scope a var belongs in, and > qualification using &var is just as valid as any other. Whatever you want scope to mean, that's up to you, but let's observe that whatever you want to call it, programming languages have in common a need to resolve multiple occurrences of an identifier without syntactical aids, and some of them manage to do it just fine in a fairly complex code structure. > > As I said there, declaration isn't an interesting part of that, > > but the idea that declarations are "not Pythonic" strikes me as > > particularly absurd (not to mention just seeing you, of all people, > > offer this criticism.) > > I didn't mean to be critical, just stating pros and cons. > > > What is "class"? > > Be fair. You know that I didn't throw out classes on a capricious whim. I actually had forgotten that you threw out class, that's not my point. Declarations are "Pythonic", because Python code is necessarily full of declarations. When you reject a solution because it's "not Pythonic", that is structurally a criticism. I don't care how you rationalize your preferences in these matters, really, and it might be that you would do better to leave that part alone and just state your preferences. There's nothing more inflammatory in a place like this than an absurd proposition. > I go through crazy moments where I consider every possibility and throw out > ideas. I considered the idea of replacing def with func (def is misnamed > after all) and that proposal lasted about 30 minutes. Another idea that > lasted about 45 minutes was changing __init__ to init. Please don't hold > anything against me during these trial-idea times. Wait until you see the > final Prothon before you criticize my wanton destruction of the Python > heritage. It also wouldn't hurt to hear you voice on the Prothon mailing > list influencing the outcome. You can't afford to indulge my tastes in programming languages, because the result would be utterly foreign to Python users. I use Python because it works. Roughly the 2.0 subset of the language is all I know and seem to need to know to make programs work. When I dream of a better language, it's not pasting new gimmicks on Python, it's really a radically different direction. OOP languages are today's FORTRAN. Donn Cave, donn at u.washington.edu From dippyd at yahoo.com.au Wed Apr 14 04:23:12 2004 From: dippyd at yahoo.com.au (Steve) Date: Wed, 14 Apr 2004 18:23:12 +1000 Subject: Method for providing a trail period on a program References: Message-ID: <407CF4F0.4020604@yahoo.com.au> Ben Finney wrote: > On Thu, 1 Apr 2004 17:46:12 -0600, Larry Bates wrote: > >>I'm searching for a good way to provide a "trail period" (something >>like 90 days) for a commercial application that I'm writing. I'd like >>something that can easily stop working 90 days after installation. > > > Why do you want to break your user's programs to gain money? Will they > not pay for your work without their programs breaking? What does that > say about the value of your work? In fairness, it might not be Larry's work that he isn't confident about, but the honesty of his customers. Larry, how foolproof do you want this trial period to be? How sophisticated are your clients? How motivated are they to crack it? What are your motives for wanting to disable the program? Are you sure your business model is the best way? For example, perhaps you would be better off distributing a free version with reduced functionality, with the additional functionality only in the non-free version. If you want a foolproof mechanism for disabling the program after the trial period, then Python is probably not the language for you. Actually, a sufficiently motivated hacker will find some way to crack your protection no matter what you do. Besides, there is one other thing you should consider. You're not Microsoft. Your biggest problem isn't people ripping you off by not paying for your software, it is that people don't even know your software exists. Perhaps it is worth letting people make free copies in order to spread the word. Don't think of it as being ripped off, think of it as advertising. Just a few thoughts for you to consider. -- Steven D'Aprano From cbrown at metservice.com Wed Apr 7 17:01:10 2004 From: cbrown at metservice.com (Colin Brown) Date: Thu, 8 Apr 2004 09:01:10 +1200 Subject: shutil.move, permission denied, why ? References: Message-ID: <40746c0a$1@news.iconz.co.nz> "St?phane Ninin" wrote in message news:Xns94C3B42DA41DEstefninalussinanorg at 212.27.42.68... ... > I just do not understand what could cause this "permissions denied" for this > file. Any idea of what stupid thing I could have done somewhere in the code > that could cause that ? ... > Stephane Ninin Hi St?phane Some time ago I had a "permission denied" problem on Windows that I finally tracked down to os.system duplicating open handles at the creation instance! The method I used to locate the problem area was by having python fire off an instance of handle.exe (freely available from www.sysinternals.com) when the permission error occurred to see what else had the file open. Colin Brown PyNZ From bkelley at wi.mit.edu Tue Apr 27 10:08:28 2004 From: bkelley at wi.mit.edu (Brian Kelley) Date: Tue, 27 Apr 2004 10:08:28 -0400 Subject: Is there a Python library that packs binary data into one file? In-Reply-To: <85b54e91.0404261301.69d5c1e9@posting.google.com> References: <85b54e91.0404261301.69d5c1e9@posting.google.com> Message-ID: <408e698c$0$573$b45e6eb0@senator-bedfellow.mit.edu> Jacob H wrote: > Hello all, > > Today I began writing a utility script that takes given binary files > and puts them all into one datafile. My idea is to be able to access > any binary data I want by indexing the datafile, e.g. > wanted_image_data = datafileobj[IMAGE_DATA]. The purpose is to hide > external image files from the user in a simple game I'm writing. In the vein of giving a man a fish: if you are using python 2.2+ import dbhash, zlib db = dbhash.open("foo.db", 'w') db['hi'] = zlib.compress("my dog has fleas") print zlib.decompress(db['hi']) for more help type help(dbhash) at the interpreter In the vein of teaching a man to fish, read the library reference here for a lot of python goodies: http://python.org/doc/2.3.3/lib/ Brian From mark at prothon.org Fri Apr 23 14:07:20 2004 From: mark at prothon.org (Mark Hahn) Date: Fri, 23 Apr 2004 11:07:20 -0700 Subject: Why we will use obj$func() often References: <84Uhc.22278$dZ1.5087@fed1read04> <8AWhc.23114$dZ1.11070@fed1read04> Message-ID: "Mike C. Fletcher" wrote ... > $ is basically a character as far as glyphs go, it's a > full-height glyph with ascenders and descenders, is very similar to a > capital S, and generally makes reading code much harder as it obscures > word-shape; .this or even self.this is much easier to read because you > can pick out the words using your learned vocabulary of word-shapes. Well I have a problem now. I gave people on my mailing list a choice between $var, `var, ~var, and ^var. The current tally is four votes for $var and none for any of the others. According to your criteria, $var is the worst and ~var should be the best. Am I correct? From mailsecurity at drugstore.com Mon Apr 5 22:55:16 2004 From: mailsecurity at drugstore.com (mailsecurity at drugstore.com) Date: Mon, 5 Apr 2004 19:55:16 -0700 Subject: Symantec Mail Security detected that you sent a message containing prohibited attachment (SYM:20842306390302457264) Message-ID: <1d7d01c41b82$96e75d20$8406000a@corp.drugstore.com> Subject of the message: Re: hi Recipient of the message: "aboutrx at drugstore.com" From mgibson at tripwire.com Thu Apr 15 18:50:00 2004 From: mgibson at tripwire.com (uebertester) Date: 15 Apr 2004 15:50:00 -0700 Subject: md5.hexdigest() converting unicode string to ascii Message-ID: <77b925de.0404151450.5c1f720a@posting.google.com> I'm trying to get a MD5 hash of a registry key value on Windows 2000 Server. The registry value is a string which is stored as a unicode string. I can get the registry key value and pass it to md5 via update(), however, hexdigest() returns a hash value for the ascii equivalent of the unicode string. Not the hash of the unicode string itself. I've verified this by creating a text file containing an ascii form of the string and one containing a unicode form of the string. The hash returned by md5.hexdigest() matches that when I run md5sum on the ascii file. Here is the code I'm using: import _winreg from md5 import md5 x=_winreg.ConnectRegistry(None,_winreg.HKEY_LOCAL_MACHINE) y= _winreg.OpenKey(x, r"SOFTWARE\Microsoft\Windows\CurrentVersion\URL\DefaultPrefix") sValue = _winreg.QueryValueEx(y,"") print sValue m = md5() m.update(unicode(sValue[0])) MD5 = m.hexdigest() print "%s \n%d" % (sValue[0], sValue[1]) print MD5 _winreg.CloseKey(y) _winreg.CloseKey(x) Any help would be appreciated. From vincent at visualtrans.de Tue Apr 27 16:05:17 2004 From: vincent at visualtrans.de (vincent wehren) Date: Tue, 27 Apr 2004 22:05:17 +0200 Subject: linux-python arrow-key problem when in interactive interpreter In-Reply-To: References: Message-ID: Gabriel Cooper wrote: > I'm running redhat 9 with python 2.3.3 and when I'm in gnome-terminal > and inside the python interpreter I can't use the arrow keys anymore. > They simply show ^[[A, ^[[B, etc. This might indicate that Python was built without readline. Also see: http://groups.google.nl/groups?hl=nl&lr=&ie=UTF-8&oe=UTF-8&selm=87lluaeiy9.fsf%40pobox.com HTH, -- Vincent Wehren http://www.visualtrans.de From andymac at bullseye.apana.org.au Mon Apr 5 06:44:08 2004 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Mon, 5 Apr 2004 20:44:08 +1000 (EST) Subject: Type checking inside a C extension In-Reply-To: References: Message-ID: <20040405204039.Q91458@bullseye.apana.org.au> On Mon, 5 Apr 2004, Jon Perez wrote: > Is there a less expensive way to check the type, or somehow > avoid a crashing situation (i.e. an exception gets properly raised) > without calling PyLong_Check() and PyString_Check() the elements > of each and every tuple? It might be expensive, but perhaps PyArg_ParseTuple() might be able to do the decoding of your tuples more neatly than the various PyXX_Check() calls. -- 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 gry at ll.mit.edu Fri Apr 16 11:08:57 2004 From: gry at ll.mit.edu (george young) Date: 16 Apr 2004 08:08:57 -0700 Subject: Fast Data Comparison (dict v. list. v string) References: Message-ID: <78b6a744.0404160708.653ae9a8@posting.google.com> "Scott Brady Drummonds" wrote in message news:... > Hi, everyone, > > I'm a relative novice at Python and am working on some optimizations in my > first Python project. At its core, this tool I'm writing needs to perform > many comparisons to fixed-size lists of fixed-length strings. > > Currently, my implementation uses dictionaries to store each string. I > maintain a separate "key-mapping" dictionary that maps keys from one > dictionary to the other. Then, all I have to do to compare the two > dictionaries is as follows: > for metaKey in keyMap.keys(): > if dict1[metaKey] != dict2[keyMap[metaKey]]: > # Do some processing > > Since the sizes of the dictionaries never change, I tried implementing this > using lists. The solution looks something like this (and assumes that a > pre-processing phase has sorted the contents of each list so their indexes > are the same): > for i in len(list1): > if list1[i] != list2[i]: > # Do some processing > > As it turns out, this implementation appears to be about 33% faster than the > dictionary-based one. Now, assuming that the datum being stored at each > index can fit into one character, I could do a string-based implementation > like this: > for i in len(string1): > if string1[i] != string[i]: > # Do some processing > > This last solution actually runs about the same as the dictionary, which > takes 50% longer than the list implementation. > > Now, my questions are: > 1) Does anyone have another suggestion as to how I can organize these data > so that I can compare many elements many times? > 2) Is there a string comparison operator that will return which indexes > have different values? Maybe it would be faster than the iterative > comparison approach for the third implementation. > 3) Since my data are changing between the successive executions of the code > snippets above, I need a way of having the other parts of the program update > it. But, it appears that strings are constant as I can't assign individual > characters with "string1[i] = '0'". Is there any way around this? You might also take a look at psyco: http://psyco.sourceforge.net. It is very easy to use, non-intrusive, and claims large performance improvements for code like this. I have hopes that things like psyco can let us keep code in the simplest and *clearest* form, and let external optimization mechanisms make it fast enough when needed. -- George Young From has.temp2 at virgin.net Fri Apr 30 12:55:32 2004 From: has.temp2 at virgin.net (has) Date: 30 Apr 2004 09:55:32 -0700 Subject: What is good about Prothon? References: <108t2tlo06j8vb9@corp.supernews.com> <69cbbef2.0404281446.4e0ab52e@posting.google.com> <69cbbef2.0404291609.72d391db@posting.google.com> Message-ID: <69cbbef2.0404300855.4dce5e5@posting.google.com> "Mark Hahn" wrote in message news:... > has wrote: > > > In Prothon, b and c derive state and behaviour from a > > unless/until it's modified locally (ie on b or c). Changes made to one > > may or may not show up in another depending on the derived > > relationship and subsequent changes*, > > I told you before that we had a Self-like copy and asked you then if using > that would make you happy. You never answered that question. Now you've > posted an example that ignores the Prothon copy (yes, it is spelled exactly > like the AS copy :) See my other post for the reason why I did this (yes, it was quite intentional). But to answer your question directly: no, simply adding a copy() operation (the "trying to please everybody, and ultimately pleasing no-one" strategy) won't make me happy; I have no use for another C++. You might think I'm merely being obtuse; trying to give you a bad day just for jollies. But no; and perhaps a little digression will help explain why... Right now you should be sketching out lots of rough ideas quickly and in the large, critiquing them, throwing some away, experimenting further with others, critiquing the results of those tests, revising, reviewing, refactoring those ideas, compacting and simplifying them, stripping them down as hard as you can to see just how far you can simplify them, reversing direction and changing tack; and not letting yourself get blocked in to a single developmental rat-run where you can only proceed forward on a single, predetermined path. Or, in short, for every feature added: 1. justify its addition; and 2. find at least one other feature - preferably more - that can't adequately justify theirs and strip them right back out again. This is another lesson I learnt in art school, btw: when working in clay, one should always build up. Add a bit of clay, step back, analyse the result. If you add too much or put it in the wrong place, don't try to carve it flat or smear it into position; instead, cut the whole lot right back 'to the bone' and start building it up again. For me, who learnt this lesson very quickly, it was rather depressing watching the rest of the class, who didn't, plod away day after day, fighting a losing battle for hours on end with a material they just couldn't seem to understand as it turned into a buttery caricature instead of a portrait head. Meantime, I'm scooting around the room like a madman, never standing more than a minute or two in front of my piece before stepping back, or walking away, or going to get drinks from the vending machine. And each morning I came in, I'd take a long look with fresh eyes at where I'd got to the previous day, and if I didn't like it, out came the big knife as I'd chop great gobs off and throw them back in the clay bin. I think by the end of that class I'd produced two pretty decent busts, and had already made a start on the third. The better of the two I completed within three afternoons too, with the bulk of it done in two and the third spend mostly idling around and occasionally diving in to tweak a feature here or there. Now, wood and stone carving I suck at. You get one chance to get it right, and if you screw up just once you have to start all over again. Such fear of failure made me nervous and timid - which, considering the price of each fresh bit of stone, maybe wasn't entirely unsurprising - and the results were insipid and flat and utterly, utterly boring. But clay I love. It rewards excitement and adventure, and encourages risk-taking and experimentation; the more bold and daring you are, the more it becomes alive. If you screw up along the way there's no permanent loss, and the valuable lessons you gain from doing so _far_ outweigh the cost of any time spent. So you work fast and loose, try lots of different ideas quickly to see where they might go, screw up often and learn as much by your mistakes as your successes. Code is like clay. It's so frustrating for me to see programmers treat it like stone. If you were in my art class I'd hand you a pile of newsprint and box of charcoal and have you do 30-second sketches for an hour. Then another hour doing five-minute drawings. And I can guarantee the if I then set you to do a finished drawing in the remaining hour the final result would be far, far better than if I'd given you a whole day - or even week - to work on it. -- I'll see if I can get around to answering some of your other questions later. Meantime, I hope you can find a little time to spend pondering the above. Who knows, maybe even put what implementation you've done aside for a bit, and go stroll round the room for a while... maybe catch some fresh perspective - even surprise yourself. :) (p.s. My new favourite phrase for the week: "Premature implementation is the root of all evil." Hope nobody minds!;-) From martin at v.loewis.de Wed Apr 14 16:31:21 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 14 Apr 2004 22:31:21 +0200 Subject: Does Python compete with Java? In-Reply-To: References: <8b336527.0404051337.51bb4a1b@posting.google.com> Message-ID: Jakub Fast wrote: > Is there really no chance this goes into python on an "if you really > have to do this, be warned, but here are the tools" basis? Certainly. Write a PEP, and an implementation. Alternatively, write a different parser front end that converts your enriched language into standard Python. Regards, Martin From as at ore.com Wed Apr 21 06:25:00 2004 From: as at ore.com (mic) Date: Wed, 21 Apr 2004 12:25:00 +0200 Subject: .net interoperability Message-ID: I'm trying to expose some of my code to the "outer world" components, specifically applications written in .NET (Visual Studio) technology. But as far as it is I could not find the proper way to go: - at first I thought about SOAP and webservices, but available solutions (Twisted Matrix, ZSI, SOAPpy) seem to be well... immature. For example I was not able to generate WSDL file, so I cannot expose information about the services I have. This is required by Visual Studio and generally I think it's a good practice. - then I decided to make my own COM server but unfortunatelly I'm not able to make type library for it. So again - no success.Of course I could try to make it by hand, but that should be done more or less automatically. How to interoperate then? Michal From jbenson at sextans.lowell.edu Fri Apr 2 17:48:01 2004 From: jbenson at sextans.lowell.edu (Jim Benson) Date: Fri, 2 Apr 2004 15:48:01 -0700 (MST) Subject: simple popen question Message-ID: Hi, I use popen to run a binary executable. A code snippit is below. This part runs fine. I use readline() to catch and print output from the binary to the screen. The system obviously buffers things. i.e. readline doesn't return after every line of output from the executable. Is there an easy way to turn off the buffering? I tried adding the extra 'r' and a small bufsize to the popen...no difference. iFd = os.popen(self.sCmd + ' ' + sArgs) # Run sCmd while True: line = iFd.readline() if line == '': # EOF found...break out. break; print '%s' % line[:-1] iRet = iFd.close() if (iRet != None): print 'ERROR: error message' Thanks, Jim From michaelmossey at yahoo.com Wed Apr 7 15:13:41 2004 From: michaelmossey at yahoo.com (Michael Mossey) Date: 7 Apr 2004 12:13:41 -0700 Subject: Intermittant slow startup References: <9badaf0.0404051033.9fec2db@posting.google.com> <4071A86D.97CA6CAE@alcyone.com> <9badaf0.0404051445.5b26b945@posting.google.com> Message-ID: <9badaf0.0404071113.6cdcee6b@posting.google.com> Andrew MacIntyre wrote in message news:... > On Tue, 5 Apr 2004, Michael Mossey wrote: > > > Erik Max Francis wrote in message news:<4071A86D.97CA6CAE at alcyone.com>... > > > Michael Mossey wrote: > > > > > > > Runnng python 2.2 on HP-UX, I get intermittant slow startup. > > > > Sometimes python starts up in a small fraction of a second, and > > > > sometimes takes 3-5 seconds. This applies to any script I run, or > > > > just typing 'python' at the prompt. > > > > > > > > I also observed something similar on Linux. > > > > > > > > Any ideas what would cause *intermittant* slow startup? > > > > > > Caching? Is it a long time between invocations that it takes a long > > > time to start up? > > > > It is quite intermittant without much of a pattern I can see. One > > thing that is definitely true is that if I start up python several > > times in a row one right after the other, some can be slow and some > > fast. I just observed it start fast twice, then start slow. I don't > > remember if it ever does the other way around but I think it does. > > is any resource coming from an NFS mount? or other network source? I double-checked that and asked the sysadmin to check if the python build was using any network source. I do have AFS and NFS drives mounted on this machine, but I'm not reading any python code from them as nearly as I can tell. PYTHONPATH points only to local disk. -Mike From peter.maas at mplusr.de Fri Apr 2 06:27:36 2004 From: peter.maas at mplusr.de (Peter Maas) Date: Fri, 02 Apr 2004 13:27:36 +0200 Subject: Travelling salesman variation in python In-Reply-To: References: Message-ID: Nick Craig-Wood wrote: > I used Simulated Annealing - have a search for the term and you'll see > plenty of references. Its good at finding a (local) minimum. I used to think that Simulated Annealing avoids local traps and is good at finding a global minimum, at least with a certain probability that depends on some temperature function. Am I wrong? Mit freundlichen Gruessen, Peter Maas -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Hubert-Wienen-Str. 24 Tel +49-241-93878-0 Fax +49-241-93878-20 eMail peter.maas at mplusr.de ------------------------------------------------------------------- From colin.blackburn at durham.ac.uk Tue Apr 6 07:03:42 2004 From: colin.blackburn at durham.ac.uk (Colin Blackburn) Date: Tue, 06 Apr 2004 12:03:42 +0100 Subject: design by contract versus doctest References: <407174ea$0$5066$4d4ebb8e@news.nl.uu.net> <40718ddb$0$5071$4d4ebb8e@news.nl.uu.net> <4071a6d4$0$5064$4d4ebb8e@news.nl.uu.net> Message-ID: On Tue, 06 Apr 2004 06:51:16 -0400, Peter Hansen wrote: > Yermat wrote: > >> Peter Hansen wrote: >>> But I'm certainly no expert in (or proponent of) DBC... >> see http://www.python.org/doc/essays/metaclasses/Eiffel.py >> to now how to do (at least one way to) design by contract in Python. > > This doesn't appear to do what the OP says it should do. > I see preconditions which, while coded in separate methods > from the code for which it is written, still executes > every time the method is called. That is, in terms of the > sequence of code, it's the same as just putting the check > in at the top of the called method. In this case yes because python does not support DbC within itself. However, in a language that does support DbC (Eiffel) these checks can be turned on during the implementation phase and turned off in the delivered code. There are techniques in python, java and other languages to implement DbC using comments and documentation, ie the contract checks are only executed when a tool/module able to process the structure comments is loaded. DbC though is about design rather than just a way testing of parameters. It is a philosophy of program design. See Object Oriented Software Construction, ed 2, by Bertrand Mayer. Colin -- From helge at hefre.com Thu Apr 29 15:10:03 2004 From: helge at hefre.com (Helge) Date: 29 Apr 2004 12:10:03 -0700 Subject: Create object for item in list Message-ID: <39885b3c.0404291110.7bd152ba@posting.google.com> I wonder how this can be accomplished: I've got a list, containing several strings. The strings look like this: [ "Name1/N1/N2/N3" , "Name2/N1/N2/N3" , "..." ] I would like to create one object for each item in the list, and the name of the object should be "str(item.split("/")[0])". I've tried this, but it won't work: for item in list: str(item.split("/")[0]) = class(item) ... From deetsNOSPAM at web.de Thu Apr 22 13:59:31 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Thu, 22 Apr 2004 19:59:31 +0200 Subject: equivalent to Tcl 'after' command? References: Message-ID: > after 1000 {puts "one second has elapsed"} > > 1. What's the most canonical way of doing this? > > 2. What's the best reference that talks about non-gui event loop > programming in Python? Has been a while since I used tcl/tk, so I'm a bit rusty here. But AFAIK that after stuff was needed when the tk event loop took over control. Sooo - _if_ you use a toolkit, it most probably features such a facility. In python, such stuff is usually accomplished using threads - and since a recent version, there is the module sched. Which internally uses threads. I personally ripped the webware taskkit for recurrent tasks. -- Regards, Diez B. Roggisch From workingdudetor at yahoo.com Sat Apr 3 19:54:47 2004 From: workingdudetor at yahoo.com (Neo) Date: 3 Apr 2004 16:54:47 -0800 Subject: IBM Developerworks: Learn how to write DB2 JDBC tools in Jython Message-ID: <3ea34487.0404031654.596cbd06@posting.google.com> Java Libraries + Python Syntax http://www-106.ibm.com/developerworks/db2/library/techarticle/dm-0404yang/index.html From greg at cosc.canterbury.ac.nz Sun Apr 25 23:10:22 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Mon, 26 Apr 2004 15:10:22 +1200 Subject: Why we will use obj$func() often In-Reply-To: References: <84Uhc.22278$dZ1.5087@fed1read04> <8AWhc.23114$dZ1.11070@fed1read04> <40883BFE.B381518A@alcyone.com> <27_hc.23801$dZ1.2716@fed1read04> <40887145.789A2FE8@alcyone.com> <7cki80hj976bia36lhf9er97v073o1pqvm@4ax.com> Message-ID: Mark Hahn wrote: > The whole point is to make things simpler, more readable, and more > efficient, but when people see the & symbol they somehow automatically think > it's complex. The feature itself might not be complex, but it's unfamiliar, since it's not quite like anything in any other language they're likely to be familiar with. So it makes learning the language a more complex exercise, since it's one more new thing to learn. It's also something that will be quite rarely used, and is totally non-suggestive of its meaning, so I expect people will be looking it up in the manual a lot before it finally gets internalised. On the other hand, replacing it with a keyword such as "outer" would make it highly suggestive, to the point where I'd wager most people wouldn't have to look it up at all. This is a big advantage that words have over punctuation -- you have much more scope for choosing one that means something to people. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From eric at zomething.com Fri Apr 2 22:51:04 2004 From: eric at zomething.com (Eric @ Zomething) Date: Fri, 2 Apr 2004 19:51:04 -0800 Subject: Fake post alert(was: Stackless Website down, Project gone, I'm dead.) Message-ID: <20040402195104.186481807.eric@zomething.com> someone identified as "Christian Tismer" wrote: > I don't deserver this honor, since I didn't write that nonsense. > But many thanks, anyway. per the headers rec'd- this post: gd31e.g.pppool.de ([80.185.211.30] the fool post: gd31e.g.pppool.de ([80.185.211.30] guess I need to get smarter(!) someone show me the light... From tjreedy at udel.edu Thu Apr 22 11:16:33 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 22 Apr 2004 11:16:33 -0400 Subject: Optimizing a text statistics function References: <4086efbc$1@nntp0.pdx.net> Message-ID: "Nickolay Kolev" wrote in message news:c67kmc$utu$1 at f1node01.rhrz.uni-bonn.de... > From my understanding, for line in file('...'): is only useful if I > want to make checks on the lines and then do something with them: It is also useful for limiting amount in RAM at one time. The main downside would be if the units you want to analyse, in this case words, are split across line endings. But split() on whitespace will also split the units at line endings. > Both methods should produce the same amount of memory usage as all words > are stored in a list. It seems to me that 300 meg file chunk + 400 meg list/dict is larger than small file chunk + 400 meg list/dict, but maybe I misunderstand what you meant. > Reading a file line by line should be slower, as > Python would have to check where the newline characters are. 'for line in file' has now been optimized to run quickly. Behind the scenes, sensibly sized chunks (such as 64K) are read from disk into a memory buffer. Lines are then doled out one at a time. This is done with compiled C. So I suspect the slowdown compared to read-all and split is minimal. Terry J. Reedy From tjreedy at udel.edu Thu Apr 22 11:42:47 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 22 Apr 2004 11:42:47 -0400 Subject: Simple question about mutable container iterator References: Message-ID: "Neal D. Becker" wrote in message news:c68iet$8qd$1 at sea.gmane.org... > x = [1,2,3] > > for i in x: > i = 2 > > This doesn't change x. 2 questions: > > 1) Why not? Why would it? You are just rebinding the name 'i' to the int 2, over and over. > Why doesn't assign to an iterator of a mutable type change the > underlying object? 'i' is not an iterator, it is just a name > 2) What is the preferred way to do this? Assuming 'this' is 'change the contents of x' for i in range(len(x)): x[i] = 2 # or x = [2]*len(x) Terry J. Reedy From loic at fejoz.net Thu Apr 29 10:57:47 2004 From: loic at fejoz.net (Yermat) Date: Thu, 29 Apr 2004 16:57:47 +0200 Subject: static keyword In-Reply-To: References: Message-ID: Peter Hansen wrote: > Nick Jacobson wrote: > >> I believe the following "static" command would be useful in Python. I do not ! Static variable are like global... > [snip] > >> Just like in C, the variables i and firstcall are only assigned the >> first time foo() is called. To get this effect currently, one could >> use default arguments or wrapping the whole thing in a class. Both of >> these solutions seem like hacks, the above method IMO is more >> Pythonic. :) or use global with carefully choosed name... > class HasState: > def __init__(self): > self.firstCall = True > self.i = [10, 11] > > def foo(self): > if self.firstCall: > print "First pass" > self.firstCall = False > self.i[0] += 1 > print self.i[0] > > obj = HasState() > obj.foo() > obj.foo() Like this solution because most of the timethis is not really static variable that we want but a per context "static" variable. Anyway, if this is really static variable that you want, what about this : 8-) >>> i = [10 ,11] >>> firstcall = True >>> >>> def foo(): ... global i ... global firstcall ... if firstcall: ... print "First pass" ... firstcall = False ... i[0] += 1 ... print i[0] ... >>> foo() First pass 11 >>> foo() 12 -- Yermat From greg at cosc.canterbury.ac.nz Wed Apr 21 22:31:57 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Thu, 22 Apr 2004 14:31:57 +1200 Subject: CamelCase versus wide_names (Prothon) In-Reply-To: References: <407ec022$0$54153$1b2cd167@news.wanadoo.nl> Message-ID: Mark Hahn wrote: > When I first started I thought everyone's opnion mattered and that I had the > job of merging eveyone's ideas into a grand scheme that made everyone happy > . That's the kind of process that gave us COBOL, Algol68 and Ada... -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From donn at u.washington.edu Fri Apr 30 14:25:19 2004 From: donn at u.washington.edu (Donn Cave) Date: Fri, 30 Apr 2004 11:25:19 -0700 Subject: Possible problem with popen2 module References: Message-ID: In article , alloydflanagan at comcast.net (A. Lloyd Flanagan) wrote: > OK, I've got a weird one I haven't been able to figure out yet. > Admittedly I haven't had time to dig into the library source, but this > behavior certainly doesn't seem right. Here's a test case: > > """Test program to demonstrate problem with popen2 module.""" > import popen2 > > def main (argv): > mycmd = 'python2.3 -c "for i in range(100000):\n print i"' > p = popen2.Popen3(mycmd) > print 'result code is %d' % p.wait() > for line in p.fromchild.xreadlines(): > print line, > > if __name__ == '__main__': > import sys > main(sys.argv) > > As you can see I'm using the popen2.Popen3 class to run a process > which prints a lot of output. > > Here's the problem: for small values of the constant in the range() > call, e.g. 1000, this works as expected. For larger values, e.g. > 100,000, the program never returns from the p.wait() call after the > child process completes. It appears tbe waiting forever on the > waitpid() call. > I don't see this behavior with calling os.popen(). I DO see it with > the current implementation of popen5() from the PEP. > > Does anyone know why this is occurring? Is this a bona-fide bug? Or > am I just being stupid somehow? Well, I will leave it to you to decide how stupid this was. Nice job on the problem report though, really covers all the bases. Pipes are `slow', fixed size devices. You can write only some small amount of data to a pipe, and then you have to wait for the peer process on the other end to read that data and make more room. Waiting like (and waiting for the peer on reads) is what makes them slow, which really means interruptible by signals (just an aside.) What would work the way you want is a disk file. Redirect output to a file, wait for the process to exit, and read the file. Pipes are for processes whose output you want to read while in progress, and you must do that whether you want to or not. You don't have exactly this problem with popen() because you're not really doing the same thing - it doesn't have a wait(), just a close(), and close() closes the pipe first, which kills the process so the wait works. Donn Cave, donn at u.washington.edu From has.temp2 at virgin.net Thu Apr 29 20:09:11 2004 From: has.temp2 at virgin.net (has) Date: 29 Apr 2004 17:09:11 -0700 Subject: What is good about Prothon? References: <108t2tlo06j8vb9@corp.supernews.com> <69cbbef2.0404281446.4e0ab52e@posting.google.com> Message-ID: <69cbbef2.0404291609.72d391db@posting.google.com> "Mark Hahn" wrote in message news:... > My position (which is basicly in agreement with Lieberman's paper) is that > having multiple tiers is inherent in all programming and is a natural result > of factoring the problem of making many copies of the same thing. And my position is that: 1. Anyone can find pieces of paper to prop up an existing position. It doesn't really prove anything. It's finding pieces of paper that actively contradict your position and being able to A. convincingly refute their arguments or, if that fails, B. acknowlege that they're right and you're wrong, and revise your position accordingly. 2. There's a world of difference between the user imposing their own tiers upon an environment, and having the environment impose its choice of tiers upon them. Tiers can add convenience, which is what makes them tempting in the first place, but they also add restrictions. Adding tiers is easy; it's removing them that's hard. 3. Factoring's supposed to add simplicity, not complexity. Programmers are far too tolerant - sometimes even welcoming - of the latter. An attitude I think goes a long way to explaining why so much software is so damned complicated: there's simply not enough lazy, intolerant, impatient folk in software development. (Note: being lazy, intolerant and impatient, as well as somewhat slow-witted, I shall no doubt be doing my bit to redress this in future.;) For benefit of viewers who've just tuned in, here's a practical illustration of how Prothon freaks me out: let's say I want to create three objects; a, b and c. In AppleScript, I would do this: -- Create object 'a' script a property x : 1 end script -- Create objects 'b' and 'c' copy a to b copy a to c log {a's x, b's x, c's x} --> {1, 1, 1} set b's x to 4 log {a's x, b's x, c's x} --> {1, 4, 1} set a's x to 9 log {a's x, b's x, c's x} --> {9, 4, 1} [note: AS's 'copy' command performs a deep copy; unlike Python's, which is shallow] Whereas Prothon does this: # Create object 'a' a = Object() a.x = 1 # Create objects 'b' and 'c' b = a() c = a() print a.x, b.x, c.x # --> 1 1 1 b.x = 4 print a.x, b.x, c.x # --> 1 4 1 a.x = 9 print a.x, b.x, c.x # --> 9 4 9 In AS, a, b, and c are all equivalent and independent; any changes made to one do not affect the others. It's a no-brainer to use, and quite safe. In Prothon, b and c derive state and behaviour from a unless/until it's modified locally (ie on b or c). Changes made to one may or may not show up in another depending on the derived relationship and subsequent changes*, and it's up to the user to keep track of all this - IMO a great way for all sorts of unpleasant, unwanted interaction bugs to crop up in non-trivial code unless you're very, very careful. (And hey, I've already got C pointer arithmetic any time I feel like living dangerously.;) (* In class-based OO you've also got the potential to do this kind of data sharing, but there the difference between sharers - i.e. classes - and sharees - i.e. instances - is explicit, so casual mix-ups are much less likely to happen.) > We will continue to agree to disagree. Think I'll just continue to disagree, if it's all the same. > I have learned a lot in my arguing > with you though and do appreciate the time you've spent wearing out your > keyboard. Well I'm glad it wasn't completely wasted. And hey, who knows; you may always change your mind. (And I have some neat thoughts on how to set up a nice modules system if you ever tempt me back...;) From support at alcanet.com.au Sat Apr 3 19:00:01 2004 From: support at alcanet.com.au (support at alcanet.com.au) Date: Sun, 4 Apr 2004 10:00:01 +1000 Subject: ALCATEL POLICY : your message has been refused Message-ID: <200404040000.i34001xO019181@mailgate.alcanet.com.au> ******************** e-mail Manager Notification ********************** As a security precaution this mail was blocked and discarded since it contains attachments with file extensions not allowed by our email policy (.exe, .vbs etc ...) Source mailbox : Destination mailbox : Message Subject : Re: Failure Attachment: application/octet-stream; name="details.scr" Our mail system policy does not accept certain attachment types. See http://www.alcatel.com/mail_policy/email_attachments.htm for additional details. Please zip up the file and send again or use an alternate method to send the file. If you have questions, contact your local email support representative. ********************** End of message *************************** From fpetermaas at netscape.net Thu Apr 1 04:01:40 2004 From: fpetermaas at netscape.net (Peter Maas) Date: Thu, 01 Apr 2004 11:01:40 +0200 Subject: Python conference slogan In-Reply-To: References: Message-ID: Kyler Laird wrote: > Shane Hathaway writes: > > >>I don't know if international folks will >>get it, though. :-) > > > If they don't, we just send in troops to explain it > to them, right? I surrender immediately and have to admit that I don't get it (One Nation Under Under Python). Google was no help. I couldn't find the source, only echoes (seems to be a wide spread joke pattern in the US). Care to give us ignorants a hint? Mit freundlichen Gruessen, Peter Maas -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Hubert-Wienen-Str. 24 Tel +49-241-93878-0 Fax +49-241-93878-20 eMail peter.maas at mplusr.de ------------------------------------------------------------------- From edwin at localhost.localdomain Sun Apr 4 00:42:43 2004 From: edwin at localhost.localdomain (Edwin Young) Date: 03 Apr 2004 21:42:43 -0800 Subject: minor bug in cmath.asin? References: <406F3EDA.970F953A@alcyone.com> <406F960C.8FD57D46@alcyone.com> Message-ID: Erik Max Francis writes: > Edwin Young wrote: > > > It's not clear if the leading - sign affects the entire expression or > > indicates that i is negative. Python's implementation uses the former > > - I argue that the latter is more correct. > > What's the difference? Multiplication on complex numbers is > commutative. Floating point math is weird. Among its oddities it has a positive zero and a negative zero. The way Python implements asin, it produces -0 in some circumstances when it should ideally produce +0, because it multiples by (-0-1j) rather than (+0-1j). This in turn is because both parts of the expression are negated, not just the imaginary part. -- Edwin From wilkSPAM at OUTflibuste.net Thu Apr 15 17:26:35 2004 From: wilkSPAM at OUTflibuste.net (Wilk) Date: Thu, 15 Apr 2004 23:26:35 +0200 Subject: CamelCase versus wide_names (Prothon) References: <87hdvl2dny.fsf@blakie.riol> Message-ID: <87d6692ar8.fsf@blakie.riol> Jarek Zgoda writes: > Wilk pisze: > >>> 2) Wide_names is cleaner, more readable, compatible with C, which is the >>> standard module language for Python and Prothon. Wide_names is also the >>> Python standard. >> >> Before, i used CamelCase, but now i use only wide_name because i find >> that capitals letters are a pain for the finger and the wrist. For >> example when you whant to write Q (on querty or azerty keyboard), with >> one hand you must make a gymnastic, or you will need two hands. > > Underscore is such same pain. I cann't see any advantage. On azerty keyboard _ is under 8 and does'nt need to press shift... I did'nt remember that it's diffent on qwerty. -- Wilk - http://flibuste.net From fredrik at pythonware.com Fri Apr 23 15:03:43 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 23 Apr 2004 21:03:43 +0200 Subject: Why we will use obj$func() often References: <84Uhc.22278$dZ1.5087@fed1read04><8AWhc.23114$dZ1.11070@fed1read04> <40883BFE.B381518A@alcyone.com><27_hc.23801$dZ1.2716@fed1read04> <40887145.789A2FE8@alcyone.com><7cki80hj976bia36lhf9er97v073o1pqvm@4ax.com> Message-ID: Mark Hahn wrote: > (by the way, Python cannot do this) sure can, if you use mutable integers. > # tested example > def getFunc(): > counter = 0 > def count(): > &counter += 1 > print &counter > return count From rawbobb at hotmail.com Wed Apr 7 23:03:26 2004 From: rawbobb at hotmail.com (bobb) Date: Thu, 08 Apr 2004 03:03:26 GMT Subject: [OT] The Cracker's Guide To Python References: <04g770lqpbhdgr3n3b9mnu9o8f08fdkgk0@4ax.com> Message-ID: <2i3dc.6735$WX.1167@nwrdny01.gnilink.net> Sounds good to me. bobb "Christos TZOTZIOY Georgiou" wrote in message news:04g770lqpbhdgr3n3b9mnu9o8f08fdkgk0 at 4ax.com... > Dear all, > > yesterday afternoon I happened to be in the company of youngsters, and I > overheard them talking about the whereabouts of the crack of the latest > version of some famous video editing software... instead of preaching > about legalities at first etc, I asked: > > "What exactly do you need this software for?" > > "I have two avi files and I want to join them..." > > "Why don't you download VirtualDub and do your job then? Google for it, > it's open source and you can download it freely." > > "So I don't need a crack for it?" > > ... (!) > > I'm skipping the rest of the conversation, but the idea of lots of > youngsters around the world, brilliant and talented perhaps, that waste > their time in illegal activities instead of investing it into open > source software struck me as very depressing. > > So jokingly, how do we advertise python in that "underground" world? > Easy: let's provide a crack for every version of python for windows! :) > It doesn't matter what it does, perhaps only change the copyright > message into "H4x0r3d by Guid0 T34m" by changing directly the > pythonxx.dll. The only problem would be that if the crack is written in > Python, it won't be able to open the dll as read-write... > > It's a crazy world... > -- > TZOTZIOY, I speak England very best, > Ils sont fous ces Redmontains! --Harddix From newsgroups at jhrothjr.com Wed Apr 14 16:29:41 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Wed, 14 Apr 2004 16:29:41 -0400 Subject: Difficulty Finding Python Developers References: <65cbc3dd.0404140641.3501fde8@posting.google.com> Message-ID: <107r7s48qa3evd8@news.supernews.com> "Paul Morrow" wrote in message news:65cbc3dd.0404140641.3501fde8 at posting.google.com... > We've worked hard to convince our company to migrate our core > applications to Python, and now we're looking for a Python developer > in Atlanta to handle a short-term (approx. 3 month) project. But our > initial searches have been fairly unsuccessful. We haven't actually > posted a job on Monster, but we have been talking with various > headhunters in our area and they don't have many resumes that show > Python experience. An so now, of course, mgt is wondering whether > selecting Python was a mistake. > > As anyone had a similar experience? Suggestions? As someone else said, you can always put a reasonable request here. My resume will be there by return mail - I'm located in Duluth. John Roth > > Thanks. From jcarlson at uci.edu Sat Apr 10 16:02:01 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Sat, 10 Apr 2004 13:02:01 -0700 Subject: Compact Python library for math statistics In-Reply-To: <3064b51d.0404091308.472dfb78@posting.google.com> References: <3064b51d.0404061038.4d69fd89@posting.google.com> <5d83790c.0404090024.5cefb2ea@posting.google.com> <3064b51d.0404091308.472dfb78@posting.google.com> Message-ID: > Overall, the Python code below is about 100 times slower than the > Fortran equivalent. This is a typical ratio I have found for code > involving loops. > > from math import sqrt > n = 10000000 + 1 > sum_sqrt = 0.0 > for i in range(1,n): > sum_sqrt = sum_sqrt + (float(i))**0.5 > print sum_sqrt Yeah...you may want to consider doing some optimizations to the above code. Using 'xrange' instead of 'range' is significantly faster (especially when your machine can't hold 'n' integers in a Python list in memory), as is the removal of the 'float(i)' cast (which is unnecessary). As for Python being slow compared to Fortran, of course it is going to be slow in comparison. Fortran is compiled to assembly, and has fairly decent (if not amazing) optimizers. Python is bytecode compiled, interpreted, and lacks an even remotely equivalent optimizer. - Josiah From bokr at oz.net Mon Apr 12 16:43:15 2004 From: bokr at oz.net (Bengt Richter) Date: 12 Apr 2004 20:43:15 GMT Subject: maximum length of a list & tuple References: Message-ID: On Mon, 12 Apr 2004 07:22:26 -0400, Peter Hansen wrote: >Peter Hansen wrote: > >> Josiah Carlson wrote: >> >>> Checking the memory usage of Python before and after the creation of 1 >>> million integer list, I get a /very/ consistant ~16 bytes per. That >>> would be 12 bytes for the object, and 4 bytes for each pointer in the >>> list. >> >> Please post the expression you are using, for comparison. > >By the way, in case it wasn't clear, we have a disagreement (and perhaps >a misunderstanding) only about the meaning of the original code posted. >You believe it is allocating many integers. I believe it allocates >only a single one. Perhaps one of us is wrong. I hadn't read the code >in great detail, and still haven't, and perhaps that's my mistake. >Depending on your reply, I'll actually go back and look at it closely >and perhaps execute it myself and see the result (in terms of the list >produced, not in terms of the memory consumption). Maybe you will >do the same and we'll identify which of us is mistaken... > >>> dict([(id(x),x) for x in [1]*100]) {7946208: 1} >>> dict([(id(x),x) for x in range(5)]) {7939088: 0, 7946208: 1, 7943184: 4, 7945200: 2, 7944192: 3} >>> dict([(id(x),x) for x in range(5)*10]) {7939088: 0, 7946208: 1, 7943184: 4, 7945200: 2, 7944192: 3} >>> for v in -6,-5,0,1,99,100: ... print dict([(id(x),x) for x in [v for i in xrange(5)]]) ... {8053508: -6} {7936720: -5} {7939088: 0} {7946208: 1} {8042496: 99} {8166456: 100} >>> for v in -6,-5,0,1,99,100: ... print dict([(id(x),x) for x in [v*1 for i in xrange(5)]]) ... {8166384: -6, 8166444: -6, 8166492: -6, 8166360: -6, 8166468: -6} {7936720: -5} {7939088: 0} {7946208: 1} {8042496: 99} {8166360: 100, 8166468: 100, 8166480: 100, 8166348: 100, 8166492: 100} Regards, Bengt Richter From jcarlson at uci.edu Thu Apr 22 17:32:49 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Thu, 22 Apr 2004 14:32:49 -0700 Subject: Goodbye TCL In-Reply-To: References: <0LudnSads6NmpuPdRVn-vw@centurytel.net> <107u6ef5a2ise19@news.supernews.com> Message-ID: > I would be curious to know what is the biggest-capacity Python network > application in use? How does it scale in comparison with AOLServer? > Any ideas? Before egroups was purchased by Yahoo (becoming Yahoo Groups), egroups was written in Python. Is a few million users a large enough scale? - Josiah From tzot at sil-tec.gr Fri Apr 2 09:38:34 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Fri, 02 Apr 2004 17:38:34 +0300 Subject: PLEASE STOP!!! References: <95aa1afa.0404010352.80de14e@posting.google.com> <406C40E8.10209@prescod.net> Message-ID: On Thu, 01 Apr 2004 11:25:22 -0800, rumours say that Josiah Carlson might have written: >Of course, I suppose the prank is that people think it is a prank, when >in fact, is actually truth. Aren't double bluffs great?-) -- TZOTZIOY, I speak England very best, Ils sont fous ces Redmontains! --Harddix From rkern at ucsd.edu Thu Apr 29 17:15:22 2004 From: rkern at ucsd.edu (Robert Kern) Date: Thu, 29 Apr 2004 14:15:22 -0700 Subject: MATLAB2Python In-Reply-To: References: <1090ivtaa0b2e26@corp.supernews.com> <40904EDE.9060407@erols.com> <715kc.3$i6.251@psinet-eu-nl> Message-ID: Sarge wrote: > Il 29 apr 2004, John Hunter ha scritto: > > >>I find python + numeric/numarray + MLAb + scipy + matplotlib to >>be a very workable replacement for matlab, > > > [cut] > > I'm impressed. Especially I liked the scipts, awesome! > > Please help me a little more, would you? > > Now, I work on WindosXP and on MDK Linux, I have found on the > Internet and downloaded all the packages you were talking about: > python, numeric, MLAb, scipy, matplotlib, but I can't figure out in > which order (and where) I have to install them. I don't want to mess > things up, because the Windoze box is at work and I have to ask for > administrator priviledges in order to install/uninstall. Do you mind a hefty download? If not, then try Enthought's distribution of Python[1]. matplotlib seems to have an exe installer for Windows, so I assume it's straightforward. But, in short, that order is correct (the last three all depend on Numeric). [1] http://www.enthought.com/python/ > Thanx, > Sarge -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From alexanro at stud.ntnu.no Wed Apr 14 10:31:47 2004 From: alexanro at stud.ntnu.no (Alexander Rødseth) Date: Wed, 14 Apr 2004 16:31:47 +0200 Subject: Pygame References: <20040414155100.6c56e1e3@pistache.sara.nl> Message-ID: > Because PyGame has too many dependencies. > Adding it to Python itself would make Python less portable. Pygame is very portable. And adding plattform-specific modules in the past, doesn't seem to have been a problem: $ lynx http://docs.python.org/modindex.html --dump --nolist | grep -c "Mac" 56 $ lynx http://docs.python.org/modindex.html --dump --nolist | grep -c "Windows" 6 $ lynx http://docs.python.org/modindex.html --dump --nolist | grep -c "IRIX" 13 $ lynx http://docs.python.org/modindex.html --dump --nolist | grep -c -i "UNIX" 24 Even though I think your answer is very reasonable, and I agree that portability is a good thing, I don't quite see what would make Python so much less portable if Pygame were added as a module. I remember using Pippy for Palm Pilot once, and they had just chopped off all the modules they didn't want to port. I don't see why the same procedure couldn't be followed in other cases as well. - Alexander From lars.rasmusson at hp.com Wed Apr 28 16:27:17 2004 From: lars.rasmusson at hp.com (Rasmusson, Lars) Date: Wed, 28 Apr 2004 13:27:17 -0700 Subject: Doing readline in a thread from a popen4('rsync ...') stream blocks when the stream ends. Message-ID: <40700B4C02ABD5119F000090278766440AB9A8E3@hplex1.hpl.hp.com> As a claification: the readline hangs because the stream has not closed, and 'rsync' is still running. The question is what in the python thread causes rsync to lock up and never finish? From paul at prescod.net Sat Apr 10 19:11:11 2004 From: paul at prescod.net (Paul Prescod) Date: Sat, 10 Apr 2004 16:11:11 -0700 Subject: print u"\u0432": why is this so hard? UnciodeEncodeError In-Reply-To: References: Message-ID: <40787F0F.7050400@prescod.net> Nelson Minar wrote: >... > > So when Python can't guess the encoding, it assumes that ASCII is the > best it can do? Even as an American that annoys me; what do folks who > need non-ASCII do in practice? Martin, what do you do when you write a > Python script that prints your own name? > > I guess what I'd like is a way to set Python's default encoding and > have that respected for files, terminals, etc. I'd also like some way > to override the Unicode error mode. 'strict' is the right default, but > I'd like the option to do 'ignore' or 'replace' globally. The Python community has traditionally discouraged machine-specific configuration. The more you depend on the machine configuration the more likely you are to have problems when you move your program from one computer to another. The bug is in the third-party module that does not deal properly with Unicode data! >... > Now that I know the trick I can do it. But part of the joy of Python > is that it makes simple things simple. For a beginner to the language > having to learn about the difference between sys.stdout and > sys.__stdout__ seems a bit much. Agreed: the module should handle it for you. Paul Prescod From michael at foord.net Mon Apr 19 03:11:04 2004 From: michael at foord.net (Fuzzyman) Date: 19 Apr 2004 00:11:04 -0700 Subject: Wrapper round x86 Assembler References: <8089854e.0404082353.7bf163a2@posting.google.com> Message-ID: <8089854e.0404182311.15e3921@posting.google.com> [snip..] > > > > Anyway - it would be easy to reserve some memory with a string like > > object to pass to an 'assembly object' and allow some really nifty > > (and fast) stuff ?? For simple algorithms it would be very neat. > > Avoiding memory overflow etc would be up to the assembly code 'chunk' > > of course. > > > The following has been reposted by Bradley Schatz to the ctypes mailing > list, it may indeed contain what you want, and it *is* very > interesting. The original post was to the bugtraq mailing list (or so): > > from oliver.lavery at sympatico.ca > > Today marks another solar cycle I've spent on this planet. To celebrate I'd > like to share one of my toys with all of you. > > Adder is a tool I wrote for myself, so that I could experiment with runtime > modification of binary applications. I've found it really useful for > prototyping run-time patches, understanding the effects and possibilities of > call-hooking and other run-time program tweaks; that sort of thing. I hope > you might find it useful too... > > > Binary: > http://www.rootkit.com/vault/x3nophi1e/adder-0.3.3-win32.zip > ( NT 4 / 2000 / XP / 2003 ) > > Source: > http://www.rootkit.com/vault/x3nophi1e/adder-0.3.3-src.zip > > Documentation: > http://www.rootkit.com/vault/x3nophi1e/adder-manual.zip > ( please read the installation instructions in here. ) > > [snip..] Very interesting. It looks like Adder *does* contain what I originally asked for - a wrapper round an assembler, with the ability to assemble into memory and jump into the code. All contained within a much more sophisticated package for bug finding and reverse engineering. *However* - I've just discovered Weave - a package that is part of the SciPy project and allows for (almost) inline C functions that can be dynamically compiled at run-time. As I'd like to learn Pyrex (and so need to learn C) - I think I'll experiment with Weave. Thanks. Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html From pugnatio2 at yahoo.com Thu Apr 15 10:27:03 2004 From: pugnatio2 at yahoo.com (pugnatio2 at yahoo.com) Date: 15 Apr 2004 07:27:03 -0700 Subject: Newbie question: Returning mutable vs. immutable Message-ID: <997a06e0.0404150627.5fb95d9b@posting.google.com> Hi, Does anyone have an opinion as to whether functions/methods should return mutable or immutable objects? In some circumstances, I could see that mutable objects might be more convenient, but if the function is to be reused, it might be a good idea to return only immutables. Or is this question moot, since the function returns control to the caller and is out of the picture at that point? Thanks, --p From andy at dustman.net Sat Apr 10 23:07:31 2004 From: andy at dustman.net (Andy Dustman) Date: Sat, 10 Apr 2004 23:07:31 -0400 Subject: ZMySQLDA/MySQLdb: DON'T fix like this for Zope 2.7.0! In-Reply-To: <20040403173444.GC32655@calvados> References: <406E9DE4.2000604@simplistix.co.uk> <406EDE94.9000701@simplistix.co.uk> <406EEE33.9050901@simplistix.co.uk> <20040403171804.GA32655@calvados> <406EF43D.5040309@simplistix.co.uk> <20040403173444.GC32655@calvados> Message-ID: <1081652851.2911.2.camel@chef.neosouth.net> On Sat, 2004-04-03 at 12:34, Michal Kurowski wrote: > Chris Withers [lists at simplistix.co.uk] wrote: > > > > This is NOT a good fix. All you're doing is ignoring the server's > > capabilities, so if the server supports transactions and the client > > doesn't, or vice versa, you end up in a mess. > > You're right but I think it is not that severe. > Generally you use MyIsam tables and if you choose InnoDB you know your > own reasons for it. > > > I think the idea is that you're supposed to use mysql-python 0.9.3b2 with > > Python 2.3, but there's no Windows binary for that. > > Well, ZMySQLDA is Andy's code, so perhaps he could comment? ;-) > > Well, I'd be curious to hear Andy Dustman in here too ;-))) Chris is correct. For Python 2.2 and up, you need one of the MySQLdb-0.9.3 betas. -- Andy Dustman PGP: 0x930B8AB6 @ .net http://dustman.net/andy Freedom isn't free. It's sold to the highest bidder. From ramen at lackingtalent.com Sat Apr 10 04:14:22 2004 From: ramen at lackingtalent.com (Dave Benjamin) Date: Sat, 10 Apr 2004 08:14:22 -0000 Subject: Code blocks and top posting Message-ID: def answer(question): return 'For pretty much the same reason top posting is.' if __name__ == '__main__': question = 'Why is Python not having code blocks annoying?' print answer(question) # HaHaOnlySerious -- .:[ dave benjamin: ramen/[sp00] -:- spoomusic.com -:- ramenfest.com ]:. : please talk to your son or daughter about parametric polymorphism. : From lbates at swamisoft.com Mon Apr 26 17:46:42 2004 From: lbates at swamisoft.com (Larry Bates) Date: Mon, 26 Apr 2004 16:46:42 -0500 Subject: Is there a Python library that packs binary data into one file? References: <85b54e91.0404261301.69d5c1e9@posting.google.com> Message-ID: zipfile.py works pretty well and you get compression as well. Larry Bates Syscon, Inc. "Jacob H" wrote in message news:85b54e91.0404261301.69d5c1e9 at posting.google.com... > Hello all, > > Today I began writing a utility script that takes given binary files > and puts them all into one datafile. My idea is to be able to access > any binary data I want by indexing the datafile, e.g. > wanted_image_data = datafileobj[IMAGE_DATA]. The purpose is to hide > external image files from the user in a simple game I'm writing. > > Though I have a good idea of how to implement this, before I begin I > am curious to know if some Python master out there has already come > out with a library that does the same. Anyone? :) From heikowu at ceosg.de Tue Apr 27 13:58:21 2004 From: heikowu at ceosg.de (Heiko Wundram) Date: Tue, 27 Apr 2004 19:58:21 +0200 Subject: Could someone explain this to a newbie In-Reply-To: References: Message-ID: <200404271958.21328.heikowu@ceosg.de> Am Dienstag, 27. April 2004 19:45 schrieb Sean Berry: > >>> text = 'zone "newsouthpine.com" {' > >>> text.lstrip("zone \"") > > 'wsouthpine.com" {' > From the Python Manual: "" lstrip([chars]) Return a copy of the string with leading characters removed. If chars is omitted or None, whitespace characters are removed. If given and not None, chars must be a string; the characters in the string will be stripped from the beginning of the string this method is called on. Changed in version 2.2.2: Support for the chars argument. "" Thus, it does exactly as it sais. The first few characters after the "zone \"" in the string are contained in the chars array which you pass in (namely "ne"), and thus they are also stripped from the string. What you might want to do is something like the following: x = x.strip() if x.startswith("zone \""): x = x[6:] HTH! Heiko. From listas at grahal.net Fri Apr 2 22:07:11 2004 From: listas at grahal.net (Gustavo Rahal) Date: Sat, 03 Apr 2004 00:07:11 -0300 Subject: first python program.. lyrics search Message-ID: <406E2A5F.9060209@grahal.net> Hi I'm trying to learn python by doing something that I think it would be nice; Search lyrics using some websites like www.musicsonglyrics.com, http://www.sing365.com I am trying to parse the html code and get the information that i need. Since I am not very good with programing I am stuck on this part. Let's take the www.musicsonglyrics.com website as an example. So let's say Metallica lyrics would be on www.musicsonglyrics.com/M.htm. Getting the first letter, requesting the M.htm page and checking if Metallica is in the html code is easy. Here is what I did up to now: artist = raw_input("Name of the artist: ") music = raw_input("Name of the music: ") url = "http://www.musicsonglyrics.com/" + artist[0].capitalize() + ".htm" f = urllib2.urlopen(url) found = 0 lines = f.readlines() f.close() for x in lines: if x.find(artist) != -1: found = 1 if found: print "OK" else: print "No" The problem is once I have the M.htm page I don't now how to get from the html code the "http://www.musicsonglyrics.com/M/Metallica/Metallica lyrics.htm" link to proceed with the search. I tried to read about Regular Expressions but I think I'm to dumb for it. Any ideas? Maybe my approach is completely wrong.... Appreciate any help Gustavo From stevenbee at removethis.att.net Sun Apr 25 14:22:30 2004 From: stevenbee at removethis.att.net (Steven Brent) Date: Sun, 25 Apr 2004 14:22:30 -0400 Subject: List operator overloading snag References: <8TCdnQn1OKieaRbdRWPC-w@speakeasy.net> Message-ID: Crikey, is *that* all it was!? Thanks so much to all who responded so quickly. Y'all made my day :-) --SB From michael at foord.net Fri Apr 9 10:33:46 2004 From: michael at foord.net (Fuzzyman) Date: 9 Apr 2004 07:33:46 -0700 Subject: CGI Problems With Xitami References: <8089854e.0404072356.7f33f440@posting.google.com> Message-ID: <8089854e.0404090633.7c8541ea@posting.google.com> Andrew MacIntyre wrote in message news:... > On Thu, 8 Apr 2004, Fuzzyman wrote: > > > All of a sudden the 'POST' method has stopped working - when I specify > > 'POST' as the method in forms... the CGI gets no data... and I really > > don't want to use 'GET' as it makes the password visible in the URL... > > Are you using "python -u" when invoking your CGI script? Unbuffered I/O > saves lots of headaches with CGI, especially on Windows. Hmmm... I'm not, I'll try it. I might have fun working out how with Xitami.... and then with whatever server we have at work :-) I haven't managed to try tidy yet (the windows binary I have doesn't appear to do anything and we have a censoring proxy at work which makes getting to most sites 'difficult'). Regards, Fuzzy http://www.atlantibots.org.uk/pythonutils.html From gerrit at nl.linux.org Thu Apr 22 04:56:02 2004 From: gerrit at nl.linux.org (Gerrit) Date: Thu, 22 Apr 2004 10:56:02 +0200 Subject: saving interpreter source? In-Reply-To: References: Message-ID: <20040422085602.GA19868@nl.linux.org> Garett wrote: > Hello, I would like to be able to save source typed into the interpreter > to a file. Kind of like marshal, but I would like to have the file contain > the source so I can edit it later. Something like inspect.getsource() but > for source typed into the interpreter, not imported from a module. Is this > possible? Any ideas are greatly appreciated. -Garett Skip has once written something like that: http://manatee.mojam.com/~skip/python/save_session.py It won't work on Windows, however. Gerrit. -- Weather in Twenthe, Netherlands 22/04 10:25: 15.0?C Few clouds mostly cloudy wind 1.3 m/s SW (57 m above NAP) -- Experiences with Asperger's Syndrome: EN http://topjaklont.student.utwente.nl/english/ NL http://topjaklont.student.utwente.nl/ From project2501 at project2501.cor Thu Apr 22 12:09:35 2004 From: project2501 at project2501.cor (project2501) Date: Thu, 22 Apr 2004 17:09:35 +0100 Subject: alternative python compilers/vms? (like java) Message-ID: are there alternative compilers for python? or different VMs to run the bytecode? similar to IBM java jvm and sun jvm, and other jvms? jikes, gcj? From tstegen at cis.strath.ac.uk Mon Apr 12 18:06:48 2004 From: tstegen at cis.strath.ac.uk (Thomas stegen) Date: Mon, 12 Apr 2004 23:06:48 +0100 Subject: String + number split In-Reply-To: References: <2SAec.70005$Id.6002@news-binary.blueyonder.co.uk> Message-ID: Stevie_mac wrote: > now thats what im talking about! > note to self, learn reg exp! While you are at it I would recommend looking at finite state automatons since give a very simple theoretical viewpoint at what regular expressions are capable/incapable of doing. After that it is just syntax :) (It is also give a good hint at how you can implement reg exes yourself.) -- Thomas. From HughMacdonald at brokenpipefilms.com Tue Apr 20 06:19:02 2004 From: HughMacdonald at brokenpipefilms.com (Hugh Macdonald) Date: Tue, 20 Apr 2004 11:19:02 +0100 Subject: Dollar sign ($) on foriegn keyboards? (prothon) In-Reply-To: References: Message-ID: <20040420111902.0764d2dc.HughMacdonald@brokenpipefilms.com> On Mon, 19 Apr 2004 23:22:10 -0700 "Mark Hahn" wrote: > Can people from outside the U.S. tell me if typing the dollar sign > often would be a problem in writing code? Is it available and > somewhat easy to type on international Anyone who writes a language like Perl or PHP would use it a lot anyway (all variables start with a symbol, usually $) -- Hugh Macdonald The Moving Picture Company From mwh at python.net Thu Apr 22 10:23:52 2004 From: mwh at python.net (Michael Hudson) Date: Thu, 22 Apr 2004 14:23:52 GMT Subject: Deleting objects References: Message-ID: tkpmep at hotmail.com (Thomas Philips) writes: [snip] > Villain dies and executes its destructor (__del__). The game then > ends. However, when I execute the program in IDLE, IT FINISHES BY > EXECUTING THE DESTRUCTOR FOR BOTH HERO AND VILLAIN. Err, __del__ isn't a destructor, it's a finalizer. It's called by the Python runtime when it has determined that the object is garbage, which is usually immediately after the last reference to it is dropped. Cheers, mwh -- Good? Bad? Strap him into the IETF-approved witch-dunking apparatus immediately! -- NTK now, 21/07/2000 From roy at panix.com Mon Apr 19 12:05:13 2004 From: roy at panix.com (Roy Smith) Date: Mon, 19 Apr 2004 12:05:13 -0400 Subject: equivalent to Java's toString()? References: <1087t9hc5vl833b@corp.supernews.com> Message-ID: In article <1087t9hc5vl833b at corp.supernews.com>, "Michael Geary" wrote: > Gabriel Cooper wrote: > > What is the python equivalent to java's toString()? > > > > When debugging I want to be able to basically be able to do this: > > > > print MyObjectInstance > > > > or > > print str(MyObjectInstance) > > > > and have it print out formatted output along the lines of: > > > > Object properties: Red=0 Yellow=0 Blue=255 > > Define a __str__ method in your class. It works just like toString() in Java > and JavaScript: > > >>> class MyTest( object ): > ... def __str__( self ): > ... return 'My Test!' > ... > >>> test = MyTest() > >>> print test > My Test! > >>> > > Also see __repr__ for a related method. > > -Mike Also, you might want to look at the pprint module. It's not quite what you were asking for, but it's worth knowing about if you're doing this kind of stuff. From stefnin at alussinan.org Thu Apr 8 06:05:28 2004 From: stefnin at alussinan.org (Stéphane Ninin) Date: 08 Apr 2004 10:05:28 GMT Subject: shutil.move, permission denied, why ? References: <40746c0a$1@news.iconz.co.nz> Message-ID: Also sprach Colin Brown : > > Some time ago I had a "permission denied" problem on Windows that I > finally tracked down to os.system duplicating open handles at the > creation instance! The method I used to locate the problem area was by > having python fire off an instance of handle.exe (freely available from > www.sysinternals.com) when the permission error occurred to see what > else had the file open. > Thanks for the idea. It helps. On this part of the code: (see for full test script) def read(self,filename): from _xmlplus.sax.sax2exts import XMLValParserFactory parser = XMLValParserFactory.make_parser() dh = DefaultHandler() parser.setContentHandler(dh) parser.setErrorHandler(dh) f = file(filename,'r') print 'TestReader B' system('handle.exe xml') r=raw_input('Press\n') try: parser.parse(f) finally: print 'CLOSE FILE' parser.close() parser.reset() f.close() print 'TestReader C' system('handle.exe xml') r=raw_input('Press\n') print f.closed return 1 I have the following output for a "bad file" (parser throws exception during parsing): TestReader B Handle v2.2 Copyright (C) 1997-2004 Mark Russinovich Sysinternals - www.sysinternals.com python.exe pid: 1776 path to test3.xml CMD.EXE pid: 1304 path to test3.xml handle.exe pid: 1072 path to test3.xml Press CLOSE FILE B1 Handle v2.2 Copyright (C) 1997-2004 Mark Russinovich Sysinternals - www.sysinternals.com python.exe pid: 1776 path to test3.xml CMD.EXE pid: 1020 path to test3.xml handle.exe pid: 1724 path to test3.xml Press ... while, for a file which is correctly parsed I have this output: TestReader B Handle v2.2 Copyright (C) 1997-2004 Mark Russinovich Sysinternals - www.sysinternals.com python.exe pid: 1324 path to test3.xml CMD.EXE pid: 1020 path to test3.xml handle.exe pid: 1776 path to test3.xml Press CLOSE FILE TestReader C Handle v2.2 Copyright (C) 1997-2004 Mark Russinovich Sysinternals - www.sysinternals.com No matching handles found. Press ~~~ I am not sure I am interpreting this correctly... Even if file is closed (as say f.closed), handles are still there ? And if problem comes from the parser (PyXML), I guess I will somehow workaround the problem, as I dont want to dig into PyXML code. :) (Unless you have some other idea.) Well, I will also test this week-end if problem also happens on Linux. (as this code is supposed to run only on Linux, I will just skip this problem if it works fine on linux) Thanks for your suggestion. Regards, -- Stephane Ninin From rogerb at rogerbinns.com Wed Apr 28 03:33:17 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Wed, 28 Apr 2004 00:33:17 -0700 Subject: Don't understand wxPython ids References: <408ed938$0$17263$a1866201@newsreader.visi.com> Message-ID: <1a34m1-fml.ln1@home.rogerbinns.com> Greg Krohn wrote: > I can only think of one reasn why they chose to use ids in the first > place. Don't forget how old wxWidgets is, and that it has to interoperate with the underlying toolkits. > Assigning many objects the same id allows you to use one EVT_* > call for those objects. But is that really a useful feature? Who knows? Here is how I use the same id in multiple locations. I can have a menu entry, a toolbar button, and a button inside some HTML all invoke the same function. The only coupling between them is the id number. You can also use id ranges in wxPython 2.5 which makes it easy to send a whole bunch of different items to the same handler. class FooFrame(wx.Frame): ID_FILE_DELETE=wx.NewId() def _init_(...): ... menu.Append(self.ID_FILE_DELETE, "&Delete", "Delete the file") .... toolbar.AddLabelTool(self.ID_FILE_DELETE, "Delete", ....) .... wx.EVT_MENU(self, self.ID_FILE_DELETE, self.OnFileDelete) .... wx.EVT_BUTTON(self, self.ID_FILE_DELETE, self.OnFileDelete) .... def OnStateChange(...): .... self.GetToolBar().EnableTool(self.ID_FILE_DELETE, True) .... In my HTML: Roger From peter.maas at mplusr.de Wed Apr 14 06:04:47 2004 From: peter.maas at mplusr.de (Peter Maas) Date: Wed, 14 Apr 2004 12:04:47 +0200 Subject: spherical coordinates In-Reply-To: <20040414111334.34b5d225@pistache.sara.nl> References: <20040414111334.34b5d225@pistache.sara.nl> Message-ID: Bram Stolk wrote: > Which module could I use if I want to do spherical coordinates in Python? math. Formulas: --- 2D r = sqrt(x**2 + y**2) phi = atan(y/x) x = r*cos(phi) y = r*sin(phi) --- 3D r = sqrt(x**2 + y**2 + z**2) phi = atan(y/x) theta = atan(z/sqrt(x**2+y**2) x = r*cos(phi)*cos(theta) y = r*sin(phi)*cos(theta) z = r*sin(theta) Mit freundlichen Gruessen, Peter Maas -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Hubert-Wienen-Str. 24 Tel +49-241-93878-0 Fax +49-241-93878-20 eMail peter.maas at mplusr.de ------------------------------------------------------------------- From peter.maas at mplusr.de Fri Apr 2 06:34:37 2004 From: peter.maas at mplusr.de (Peter Maas) Date: Fri, 02 Apr 2004 13:34:37 +0200 Subject: Python conference slogan In-Reply-To: References: <30260531.0404010833.1b834032@posting.google.com> <406C4DDF.5000907@zope.com> Message-ID: Neil Benn wrote: > 'We are the coders who say nee' - from the knight in the holy grail > 'Good god man, I've thrown you an exception It's nothing a mere > NoneType' holy grail again > > The joy of being English is you grow up with this stuff! These slogans are meaningless to (Monty) Python outsiders. As I understand this thread there is a need for a slogan that is short, not too hard to understand and unforgettable (probably a definition of the word slogan). Python insiders don't need a slogan at all. Mit freundlichen Gruessen, Peter Maas -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Hubert-Wienen-Str. 24 Tel +49-241-93878-0 Fax +49-241-93878-20 eMail peter.maas at mplusr.de ------------------------------------------------------------------- From peter at engcorp.com Thu Apr 29 10:06:54 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 29 Apr 2004 10:06:54 -0400 Subject: reading and removing first x bytes of a file In-Reply-To: References: Message-ID: bart_nessux wrote: > I have some Macbinary files on a PC. I want to recursively read these > files and remove the first 128 bytes of the files if they contain the > macbinary header info. I know how to read directories recursively, but > how would I read the first 128 bytes of each file in the path? os.listdir() can return a list of the names in the path. You can use os.path.isfile() to check that a given name doesn't refer to a subdirectory. Once you've opened one of the files for reading, just use .read(128) to get a string containing the first 128 bytes from the file. -Peter From bram at nospam.sara.nl Wed Apr 14 09:51:00 2004 From: bram at nospam.sara.nl (Bram Stolk) Date: Wed, 14 Apr 2004 15:51:00 +0200 Subject: Pygame References: Message-ID: <20040414155100.6c56e1e3@pistache.sara.nl> On Wed, 14 Apr 2004 15:22:42 +0200 "Alexander R?dseth" wrote: > Hi! > > Why isn't Pygame a part of Python? Because PyGame has too many dependencies. Adding it to Python itself would make Python less portable. > > Cheers, > Alexander R_dseth > > -- ------------------------------------------------------------------------------ Bram Stolk, VR Engineer. SARA Academic Computing Services Amsterdam, PO Box 94613, 1090 GP AMSTERDAM email: bram at nospam.sara.nl Phone +31-20-5923059 Fax +31-20-6683167 "For the costs of subsidized agriculture in the EU, we can have all 56 million European cows fly around the world. First Class." - J. Norberg ------------------------------------------------------------------------------ From anton at vredegoor.doge.nl Mon Apr 5 05:29:14 2004 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Mon, 05 Apr 2004 11:29:14 +0200 Subject: Working with bytes. References: <406EE606.4000604@yahoo.com> <406f33b6$0$30963$3a628fcd@reader1.nntp.hccnet.nl> Message-ID: <4071273d$0$132$3a628fcd@reader1.nntp.hccnet.nl> Piet van Oostrum wrote: >AV> [snip] >Which includes quite a few NON-ASCII characters. >So what is ASCII-compliant about it? >You can't store 7 bits per byte and still be ASCII-compliant. At least if >you don't want to include control characters. Thanks, and yes you are right. I thought that getting rid of control codes just meant switching to the high bit codes, but of course control codes are part of the lower bit population and can't be removed that way. Worse than that: high bit codes are not ASCII-compliant at all! However the code below has the 8'th and 7'th bit always set to 0 and 1 respectively, so it should produce ASCII-compliant output using 6 bits per byte. I wonder whether it would be possible to use more than six bits per byte but less than seven? There seem to be some character codes left and these could be used too? Anton from itertools import islice def _bits(i): return [('01'[i>>j & 1]) for j in range(8)][::-1] _table = dict([(chr(i),_bits(i)) for i in range(256)]) def _bitstream(bytes): for byte in bytes: for bit in _table[byte]: yield bit def _drop_first_two(gen): while 1: gen.next() gen.next() for x in islice(gen,6): yield x def sixes(bytes): """ stream normal bytes to bytes where bits 8,7 are 0,1 """ gen = _bitstream(bytes) while 1: R = list(islice(gen,6)) if not R: break s = '01'+ "".join(R) + '0' * (6-len(R)) yield chr(int(s,2)) def eights(bytes,n): """ the reverse of the sixes function :-| """ gen = _bitstream(bytes) df = _drop_first_two(gen) for i in xrange(n): s = ''.join(islice(df,8)) yield chr(int(s,2)) def test(): from random import randint size = 20 R = [chr(randint(0,255)) for i in xrange(size)] bytes = ''.join(R) sx = ''.join(sixes(bytes)) check = ''.join(eights(sx,size)) assert check == bytes print sx if __name__ == '__main__': test() output: VMtdh[LII~Qexdyg}xFRhXRIVx From grante at visi.com Fri Apr 9 10:10:06 2004 From: grante at visi.com (Grant Edwards) Date: 09 Apr 2004 14:10:06 GMT Subject: surface fitting library for Python? References: <40748902$0$17253$a1866201@newsreader.visi.com> <60dfb6f6.0404081300.78bbe0f9@posting.google.com> Message-ID: <4076aebe$0$17266$a1866201@newsreader.visi.com> On 2004-04-08, Carl Banks wrote: > Grant Edwards wrote in message news:<40748902$0$17253$a1866201 at newsreader.visi.com>... >> I'm looking for a surface fitting library for Python. >> >> Something like the least-squares module in scientific python, >> except I want to fit a surface (z = f(x,y)) instead of a curve >> (y = f(x)). > > > Idea: see if you can use the versatility of Python to fool SciPy into > fitting a surface when it thinks it's fitting a curve. Cool -- that's the plan for now... -- Grant Edwards grante Yow! Did you move a lot at of KOREAN STEAK KNIVES this visi.com trip, Dingy? From __peter__ at web.de Thu Apr 29 12:54:54 2004 From: __peter__ at web.de (Peter Otten) Date: Thu, 29 Apr 2004 18:54:54 +0200 Subject: Generic constructors and duplication of internal Python logic References: <87ekqq41ya.fsf@pobox.com> <87oepnzlbp.fsf@pobox.com> <87k707elth.fsf@pobox.com> <87smetxjjj.fsf@pobox.com> Message-ID: Turns out it has already been done with more magic (no explicit locals() call) in http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/157572 Peter From OlafMeding at compuserve.com Thu Apr 29 09:56:48 2004 From: OlafMeding at compuserve.com (Olaf Meding) Date: 29 Apr 2004 06:56:48 -0700 Subject: makepy generating a file versus a directory Message-ID: <9e5ea2c4.0404290556.35c51c64@posting.google.com> When does the makepy utility generate a .py file and when a directory? And what decided if a directory or a file is generated? What is the difference between a file and a directory (both named after the uuid in the IDL file)? Most of the time the code below generates a file called BF79B6C5-47BE-11D2-BACD-006008060A3A.py. But one time it generated a directory with that same name. This directory contained several .py files. Both the .py file and the directory are generated at: "C:\Python23\Lib\site-packages\win32com\gen_py". Here is the Python code: from win32com.client import gencache gencache.EnsureModule('{BF79B6C5-47BE-11D2-BACD-006008060A3A}', 0, 1, 0) Thanks so much for your help. Olaf From jcarlson at uci.edu Thu Apr 1 14:37:47 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Thu, 01 Apr 2004 11:37:47 -0800 Subject: From python-dev, space vs. tab controversy finally settled In-Reply-To: References: Message-ID: > Spoil-sport! > > You could have at least given it a few *minutes* to get some traction! It was right at the top for the last message I read last night. It was unlucky. Sorry to the original poster for ruining the joke so early. - Josiah From pedietz at west.com Fri Apr 16 10:39:11 2004 From: pedietz at west.com (Phil Dietz) Date: 16 Apr 2004 07:39:11 -0700 Subject: Goodbye TCL References: <0LudnSads6NmpuPdRVn-vw@centurytel.net> Message-ID: <21ccedf1.0404160639.14c2d852@posting.google.com> Forget OO... TCL still doesn't have a standard database API in the core yet.... From johnc_tan at hotmail.com Fri Apr 16 14:34:28 2004 From: johnc_tan at hotmail.com (JT) Date: 16 Apr 2004 11:34:28 -0700 Subject: Initializing Python in Optimized mode from C++ Message-ID: Hi, When embedding Python in C++, is there anyway to initialize the interpreter so that it runs in optimized mode, equivalent to specifying the -O flag when running the interpreter from the command line? Thanks, John From wallacethinmintr at eircom.net Wed Apr 7 16:18:04 2004 From: wallacethinmintr at eircom.net (Russell Wallace) Date: Wed, 07 Apr 2004 20:18:04 GMT Subject: Are line continuations needed? References: <407409ef.82801353@news.eircom.net> Message-ID: <407461ac.105265095@news.eircom.net> On Wed, 07 Apr 2004 17:53:00 GMT, Christopher Koppler wrote: >On Wed, 07 Apr 2004 14:05:29 GMT, wallacethinmintr at eircom.net (Russell >Wallace) wrote: > >>Python lets you continue a single logical line across more than one >>physical line, either by putting a \ at the end or letting it happen >>automatically with an incomplete infix operator. > >I don't have any ready examples, but I do occasionally need it, if >only for readability porpoises, or more often to fit a line to a >certain length limit. If a parenthetical expression will work, and >doesn't look stranger (really can't think of a case), I'll use that. Okay, thanks. >But problems there'll surely be - with legacy code compatibility. *nod* I was more asking whether it was a good idea to include it originally than whether it could be removed now, though I suppose since 3.0 is supposed to be breaking with backward compatibility, there's the question of whether it should be retained there. >Not really it isn't ;-) ^.^ -- "Sore wa himitsu desu." To reply by email, remove the small snack from address. http://www.esatclear.ie/~rwallace From osv at javad.ru Wed Apr 21 09:53:43 2004 From: osv at javad.ru (Sergei Organov) Date: 21 Apr 2004 17:53:43 +0400 Subject: CamelCase versus wide_names (Prothon) References: <6ee58e07.0404192141.2229efd6@posting.google.com> <1082549174.163233@ns.topconrd.ru> Message-ID: <1082555623.345996@ns.topconrd.ru> Peter Hansen writes: > Sergei Organov wrote: > > Yet nobody mentioned that we don't have lower-case digits ;) > > > usb201_driver <-> usb201Driver <-> usb2??Driver > > usbTwoOhOneDriver ? ;-) Who would call underscored version "wide names" then? :) From tjreedy at udel.edu Mon Apr 19 14:36:01 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 19 Apr 2004 14:36:01 -0400 Subject: outline-style sorting algorithm References: <71650A6F73F1D411BE8000805F65E3CB3B3A4D@SRV-03> Message-ID: wrote in message news:71650A6F73F1D411BE8000805F65E3CB3B3A4D at SRV-03... > I have a need to sort a list of elements that represent sections of a > document in dot-separated notation. The built in sort does the wrong thing. Which is to say, the standard alphabetical thing ;-). > Obviously 1.20.1 should be after 1.9 if we look at this as dot-delimited > integers, not as decimal numbers. It it a well known problem that left-justified variable-length number representations in strings do not sort well when the strings are sorted in the standard manner. Even without dots, directory listings will give you file1 file10 ... file19 file2 file20 ... file29 file3 etc. One solution is a custom compare or sort algorithm as others have suggested. The other is adjustment of the strings by left padding numbers with spaces or 0s so that they end up right justified to the same column. Then the standard alphabetical sort does what you want. For instance, Windows scandisk, when it recovers fragments, labels them file001 file002 etc so that they sort correctly. In your case, 1.09 would sort before 1.10, let alone 1.20. Your choice. Terry J. Reedy From peter at engcorp.com Sat Apr 24 10:54:07 2004 From: peter at engcorp.com (Peter Hansen) Date: Sat, 24 Apr 2004 10:54:07 -0400 Subject: command-line args In-Reply-To: <408A7B35.7040702@mlug.missouri.edu> Message-ID: Michael [mailto:mogmios at mlug.missouri.edu] wrote: > Peter Hansen wrote: > > Create an empty module called "globals" and import that wherever > > needed. Populate it with settings from the command-line parsing > > stage. Get fancier and put defaults in there to begin with, and > > override them only if specified in the command-line parsing area. > > Flavour as needed... > > What do you do about multiple processes (of the same program) > running at once? Save to /tmp//globals.py or something like that? Why would you save anything? If you're just parsing command-line arguments, the settings are not persistent, are they? Just kept in memory for the duration of the current program. If you have multiple processes, each gets its own command line arguments and thus its own in-memory values from globals.py. If you are actually interested in persistent, you'll need to expand on your original question, I think, because talking about "command line argument parsing" generally doesn't involve persistence, for most people. -Peter From __peter__ at web.de Wed Apr 7 12:55:52 2004 From: __peter__ at web.de (Peter Otten) Date: Wed, 07 Apr 2004 18:55:52 +0200 Subject: Are line continuations needed? References: <407409ef.82801353@news.eircom.net> Message-ID: Peter Maas wrote: > Russell Wallace wrote: >> Python lets you continue a single logical line across more than one >> physical line, either by putting a \ at the end or letting it happen >> automatically with an incomplete infix operator. >> >> I'm wondering how often is this feature needed? Would there be any >> problems if it weren't part of the language? > > Just had this example: > > d = { 'key1' : 'A very very long string of several hundred '\ > 'characters. I could use a multi-line string but '\ > 'then either left white space would be part of the '\ > 'string or I would have to align it at column 0 '\ > '(ugly). I could embed it into a pair of brackets '\ > 'but I see no advantage over \\. Finally I could '\ > 'put this string on a single line (also ugly and hard '\ > 'to read).' > ... > } >>> d = {1: "Hi Peter, " ... "what do you " ... "think of this?"} Peter From martin at v.loewis.de Thu Apr 8 14:51:18 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 08 Apr 2004 20:51:18 +0200 Subject: print u"\u0432": why is this so hard? UnciodeEncodeError In-Reply-To: References: Message-ID: David Eppstein wrote: > Py2.3 sure doesn't discover the encoding of my terminal automatically: > > hyperbolic ~: python > Python 2.3 (#1, Sep 13 2003, 00:49:11) > [GCC 3.3 20030304 (Apple Computer, Inc. build 1495)] on darwin Ah, Darwin. You lose. If anybody can tell me how to programmatically discover the encoding of Terminal.App, I'll happily incorporate a change into a 2.3.x release. Regards, Martin From peter at engcorp.com Wed Apr 28 08:56:08 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 28 Apr 2004 08:56:08 -0400 Subject: Is Perl *that* good? In-Reply-To: References: Message-ID: Michael wrote: >> I wish Python had won, as well. But time is linear (in my mind). I now >> wish only that we could leverage the similarity of JS and Python >> (execution and binding models) into more Python users. Marketing needs >> to run with the line, "So you know Javascript? Then you know Python!" >> > I wish Python could be ran inside a browser as a client-side scripting > language. I've seen it done but it'd be awesome to seen done properly > and intergrated into something like Mozilla. Although at that point we would unfortunately run smack into the security flaws Python has in this area. If the "I've seen it done" above refers to the existing support for this in pywin32 (formerly win32all), you probably know how it was disabled since it is inherently (with current Python) unsafe. -Peter From ngps at netmemetic.com Mon Apr 12 10:17:11 2004 From: ngps at netmemetic.com (Ng Pheng Siong) Date: 12 Apr 2004 14:17:11 GMT Subject: solaris install of python References: Message-ID: According to Skip Montanaro : > > gotcha> has anyone installed pythong on solaris 8 before, > > Yes, plenty of times. I received a query in the mail about a Solaris installation of M2Crypto: bash-2.03$ ldd *.so libssl.so.0.9.7 => /esdev/ssl/lib/libssl.so.0.9.7 libcrypto.so.0.9.7 => /esdev/ssl/lib/libcrypto.so.0.9.7 libgcc_s.so.1 => /usr/local/lib/libgcc_s.so.1 libsocket.so.1 => /usr/lib/libsocket.so.1 libnsl.so.1 => /usr/lib/libnsl.so.1 libdl.so.1 => /usr/lib/libdl.so.1 libc.so.1 => /usr/lib/libc.so.1 libmp.so.2 => /usr/lib/libmp.so.2 /usr/platform/SUNW,UltraAX-i2/lib/libc_psr.so.1 On my FreeBSD boxen, I get ./__m2crypto.so: libssl.so.3 => /usr/lib/libssl.so.3 (0x28134000) libcrypto.so.3 => /usr/lib/libcrypto.so.3 (0x28163000) The sender (hi!, if you're reading this ;-), is wondering if the output is typical for a Python extension on a Solaris box, and if the presence of the libgcc_s.so line is "normal"? Any idea? TIA. Cheers. -- Ng Pheng Siong http://firewall.rulemaker.net -+- Firewall Change Management & Version Control http://sandbox.rulemaker.net/ngps -+- ZServerSSL/Zope Windows Installers From noah at noah.org Mon Apr 5 17:51:54 2004 From: noah at noah.org (Noah) Date: 5 Apr 2004 14:51:54 -0700 Subject: What is the correct method for installing modules on old Python 1.5.2? Message-ID: I have a module that I currently install using the distutils module, but I also need to document how to install the module on old Python 1.5.2. I used to know how to do this, but now I've forgotten and I can't seem to find any documentation on the process anymore. I know that I have to copy my module to site-packages, but I think I also need to add a line to a text file in the python home directory. Can someone list the steps for me? Yours, Noah From mogmios at mlug.missouri.edu Wed Apr 28 13:14:29 2004 From: mogmios at mlug.missouri.edu (Michael) Date: Wed, 28 Apr 2004 10:14:29 -0700 Subject: Is Perl *that* good? In-Reply-To: References: <108v74768o9sb9f@corp.supernews.com> Message-ID: <408FE675.1050605@mlug.missouri.edu> >BTW, nobody seems to miss Perl libs and CPAN anymore. A few years ago >most of the complaints regarding python were that perl has more >libraries. This is a good sign :-). > IMO, CPAN is still the biggest benefit to using Python. It'd be great to see a project to port all of CPAN functionality into standard Python modules. From mhammond at keypoint.com.au Thu Apr 29 01:08:42 2004 From: mhammond at keypoint.com.au (Mark Hammond) Date: Thu, 29 Apr 2004 15:08:42 +1000 Subject: asp script engine registrition In-Reply-To: References: Message-ID: jianchiwei wrote: > question: > I run > c:\python23\Lib\site-packages\win32comext\axscript\client\pyscript.py > and it told me > Registered: Python > Registration of Python ActiveX Scripting Engine complete. > > But, when I run a asp script > > <%@LANGUAGE=Python%> > > > >

Python - Test

> > > > > I still get > HTTP/1.1 500 Server Error > caused by the first line of code "<%@LANGUAGE=Python%>". > It seems to me that python script engine is not correctly registered. > Could someone help me on this please? Do the sample .asp files work? If so, then you should be able to work out what is wrong by comparing them. If not, try registering the engine with "--debug" on the command-line, then use Pythonwin's "Tools->Remote Trace Collector" - hopefully you will see a traceback with the specific problem. Mark. From http Fri Apr 2 14:40:04 2004 From: http (Paul Rubin) Date: 02 Apr 2004 11:40:04 -0800 Subject: Simple text markup (-> HTML) References: Message-ID: <7x7jwy5fu3.fsf@ruckus.brouhaha.com> Please don't invent yet another markup language. It gets incredibly difficult to keep them all straight. There's some standard being developed for Wiki markup. Why don't you use that. The stuff in your example already looks pretty similar to wikipedia markup. Another idea is use Texinfo. From mwh at python.net Mon Apr 26 08:37:04 2004 From: mwh at python.net (Michael Hudson) Date: Mon, 26 Apr 2004 12:37:04 GMT Subject: Magic methods in extension types References: Message-ID: Jacek Generowicz writes: > Michael Hudson writes: > > > Not finding the tp_as_number->nb_inplace_add field? > > ( ... or tp_as_sequence ... ) > > I was afraid you (someone) was going to say that. Why? > > I think *all* magic methods correspond to slots in (or near) the type > > object -- it's practically the definition of "magic method"! > > Hmmm > > >>> class foo: > ... def __iadd__(self,other): > ... print "__iadd__ running" > ... return self > ... > >>> f = foo() > >>> f += 2 > __iadd__ running > > I'd be surprised if I've added __iadd__ to a type object here, yet it > seems to work. Well, the type of old-style classes has something in it's tp_as_number->nb_inplace_add slot that looks in the class dictionary for an __iadd__ method. If you'd made that a new-style class, you would be surprised! > Python manages to map "+=" to the method called "__iadd__" in > user-defined classes, but not for extension types. What is the > essential difference that makes that mapping work in one case but > not in the other? Well, for old-style classes a whole bunch of code like: BINARY_INPLACE(instance_ior, "or", PyNumber_InPlaceOr) BINARY_INPLACE(instance_ixor, "xor", PyNumber_InPlaceXor) BINARY_INPLACE(instance_iand, "and", PyNumber_InPlaceAnd) BINARY_INPLACE(instance_ilshift, "lshift", PyNumber_InPlaceLshift) BINARY_INPLACE(instance_irshift, "rshift", PyNumber_InPlaceRshift) BINARY_INPLACE(instance_iadd, "add", PyNumber_InPlaceAdd) BINARY_INPLACE(instance_isub, "sub", PyNumber_InPlaceSubtract) BINARY_INPLACE(instance_imul, "mul", PyNumber_InPlaceMultiply) BINARY_INPLACE(instance_idiv, "div", PyNumber_InPlaceDivide) BINARY_INPLACE(instance_imod, "mod", PyNumber_InPlaceRemainder) BINARY_INPLACE(instance_ifloordiv, "floordiv", PyNumber_InPlaceFloorDivide) BINARY_INPLACE(instance_itruediv, "truediv", PyNumber_InPlaceTrueDivide) and for new-style classes much hair in typeobject.c:type_new and therein called functions. Extension types don't go through type_new and are expected to go the other way round, in a sense: define something in tp_as_number->nb_inplace_add and a wrapper called __iadd__ will be created for you. Cheers, mwh -- Windows installation day one. Getting rid of the old windows was easy - they fell apart quite happily, and certainly wont be re-installable anywhere else. -- http://www.linux.org.uk/diary/ (not *that* sort of windows...) From belred1 at yahoo.com Thu Apr 22 10:27:48 2004 From: belred1 at yahoo.com (Bryan) Date: Thu, 22 Apr 2004 14:27:48 GMT Subject: AOP use cases In-Reply-To: References: <84fc4588.0404140106.3fa0c55@posting.google.com> <0pydnSB4WYuieuLdRVn-hQ@powergate.ca> Message-ID: <4087D662.6010209@yahoo.com> > > Those of you using XML might want to visualize the program as a DOM tree and > AOP as applying a XSLT stylesheet. (Now visualize applying several different > stylesheets in arbitrary order) > > > Daniel > thank you for this explanation... it's the best explanation i've heard yet and now i have a grasp and can visualize what AOP is. bryan From tim.golden at viacom-outdoor.co.uk Wed Apr 28 09:44:30 2004 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Wed, 28 Apr 2004 14:44:30 +0100 Subject: Path ... where is my application's home dir? Message-ID: >I want to store a file in the application directory. What is >the easiest >way to figure out, where my application is situated? > >sys.argv[0] does not work for my purposes... do you have any >other ideas. a) Why doesn't argv[0] work? b) What O/S are you running? TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star Internet. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From roy at panix.com Mon Apr 19 18:56:21 2004 From: roy at panix.com (Roy Smith) Date: Mon, 19 Apr 2004 18:56:21 -0400 Subject: Difficulty Finding Python Developers References: <65cbc3dd.0404140641.3501fde8@posting.google.com> Message-ID: pm_mon at yahoo.com (Paul Morrow) wrote: > We've worked hard to convince our company to migrate our core > applications to Python, and now we're looking for a Python developer > in Atlanta to handle a short-term (approx. 3 month) project. But our > initial searches have been fairly unsuccessful. We haven't actually > posted a job on Monster, but we have been talking with various > headhunters in our area and they don't have many resumes that show > Python experience. An so now, of course, mgt is wondering whether > selecting Python was a mistake. > > As anyone had a similar experience? Suggestions? I'm guessing this is your ad: Company: Loyaltyworks, Inc. Location: Atlanta, GA 30305 Salary/Wage: 45.00 - 55.00 USD /year Status: Per Diem, Temporary/Contract/Project I think you'd do better if you were willing to pay a bit more. Most developers find it difficult to pay the rent on $55 a year. :-) From versy59 at yandex.ru Thu Apr 29 15:51:15 2004 From: versy59 at yandex.ru (Alex Yakovlev) Date: Thu, 29 Apr 2004 23:51:15 +0400 Subject: MATLAB2Python References: Message-ID: > I'm a moderately experienced programmer in Matlab, and looking for a > free computational language (Matlab is *REALLY* expensive for an > individual, like me). > I came across Python (actually Scipy) and immediately felt > comfortable with the interface and syntax. May be SciLab ? It's not Python, it's free Mathlab-compatible pakage. http://scilabsoft.inria.fr/ From pedronis at bluewin.ch Mon Apr 19 10:45:37 2004 From: pedronis at bluewin.ch (Samuele Pedroni) Date: Mon, 19 Apr 2004 16:45:37 +0200 Subject: [Python-Dev] PEP 329: Treating Builtins as Constants in the Standard Library In-Reply-To: <200404191456.14865.gmccaughan@synaptics-uk.com> References: <5.2.1.1.0.20040419154633.02d12be8@pop.bluewin.ch> <5.2.1.1.0.20040419154633.02d12be8@pop.bluewin.ch> Message-ID: <5.2.1.1.0.20040419161441.02d12688@pop.bluewin.ch> At 13:56 19.04.2004 +0000, Gareth McCaughan wrote: >On Monday 2004-04-19 14:49, Samuele Pedroni wrote: > > > Raymond, could you please try to tame your speed obsession without > > devising even more hacks and pissing in other people's pool. > >What a gratuitously obnoxious and pointless reply. If you have >reason to think Raymond's proposal, if implemented, will cause >trouble, then show it. If not, then why shouldn't he work on >making Python faster if he wants to? he's proposing an hack that would speed up CPython and slow down Jython (because it would result in a no-op but OTOH he would like to remove the code when some globals are bound to locals for speed reason. Of course that's not nice too but replacing a hack with another is just sort of a win. Honestly there are probably very convoluted ways to make this, in this form, a non no-op on Jython too, not that I would like to implement them or that Raymond cared). if he has an elegant proposal that works for all of Python that would be a proposal, this seems just a hack. [Not that I particularly like this kind of semi-overt mud slinging] Other people do not completely share Raymond's design taste, so to say, in fact they have politely responded to single proposals, OTOH although it was a bit over-rudely formulated, I think it was the case to bring to the day-light that that is creating some real tension. PS: I'm starting to be really annoyed by the fact that Jython is often cited good PR but a 2nd class citizen for all the rest. I'm aware of the practical circumstances of why that's the case in some occassions, OTOH we are mostly all investing our free time on Python activities, it would be nice if we showed respect beyond just the forms and politeness. I'm back from the ACCU which was fun but tiring and also an occasion of some related heat taking. All I was looking forward is restarting to finish the new-style class work (started in December and January) in Jython,after the stop because of working on the negotations for the PyPy EU proposal together with the others PyPy people, which we hope will conclude positively for the people working on it and looking forward to restart making PyPy a real concrete contribution to Python future. From t2wu at ucsd.edu Thu Apr 8 06:30:54 2004 From: t2wu at ucsd.edu (Timothy Wu) Date: Thu, 08 Apr 2004 18:30:54 +0800 Subject: A beginner's question on thread In-Reply-To: <1081316259.664569@yasure> References: <1081316259.664569@yasure> Message-ID: <407529DE.6050101@ucsd.edu> Donn Cave wrote: > Well, that's the deal. Use threads to solve a problem, and now > you have two problems. > > I'd probably do it the way Aurelio Martin proposed, with I/O to > the socket thread. It's much neater than whacking the thread, > which is the alternative. > > I wouldn't necessarily use threads in the first place, though. > I think it really depends on the user interface - usually that > has to be the dispatch core of the application, and if it's > built for threads, then there you go. Typically there will be > some provision for dispatch on an I/O channel like a socket. > If you're writing your own user interface, probably just reading > and writing to the tty, and the socket thread is going to be > the one and lonely extra thread - then don't do it, I'd say. > Use select.select, or a package like asyncore or twisted or > whatever (not very familiar with that territory, I just use select.) I think Roger Binns's setDaemon() suggestion works for me. =) Thanks for suggestion the other options. I'll take a look at asnycore or twisted when I have time or perhaps for other projects. Since from what I read somewhere else, it doesn't seem like Python thread's performance is exceptional. Timothy From mwh at python.net Wed Apr 14 12:34:46 2004 From: mwh at python.net (Michael Hudson) Date: Wed, 14 Apr 2004 16:34:46 GMT Subject: Wrapper round x86 Assembler References: <8089854e.0404082353.7bf163a2@posting.google.com> <4dKdnQlIXMIXIevdRVn-gg@powergate.ca> <8089854e.0404100204.504186a0@posting.google.com> <8089854e.0404122329.5dfe5ce1@posting.google.com> <8089854e.0404132323.3283390@posting.google.com> Message-ID: michael at foord.net (Fuzzyman) writes: > In summary - I'm better off learning C and how to write Python > extensions !! I'm a bit lost on where this thread is at, but I've written Python extensions in PPC assembly (more to see if I could than for any real reason...). Cheers, mwh -- In short, just business as usual in the wacky world of floating point . -- Tim Peters, comp.lang.python From lbates at swamisoft.com Thu Apr 1 11:56:07 2004 From: lbates at swamisoft.com (Larry Bates) Date: Thu, 1 Apr 2004 10:56:07 -0600 Subject: splitting one dictionary into two References: <20040401153103.GC4577@jsaul.de> Message-ID: There a quite a few different ways to do this, but I might suggest something like: dict1={"a":1, "b":3, "c":5, "d":4, "e":2} dict2={} dict3={} [dict2.setdefault(k,v) for k,v in dict1.items() if v > 3] [dict3.setdefault(k,v) for k,v in dict1.items() if not v > 3] dict1=dict3.copy() Very "Pythonic" but is 2 times slower than your original code. Another suggestion is: dict1 = { "a":1, "b":3, "c":5, "d":4, "e":2 } dict2 = {} keys=dict1.keys() for key in keys: if dict1[key] > 3: # some criterion dict2[key] = dict1[key] del dict1[key] This is a "little" faster (100000 iterations of your method time=1.13 seconds, my method=0.94 seconds and I find easier to read (eliminates the unneeded klist variable and second loop). Larry Bates Syscon, Inc. "jsaul" wrote in message news:20040401153103.GC4577 at jsaul.de... > Hello all, > > I have to split a dict into two dicts. Depending on their values, > the items shall remain in the original dict or be moved to another > one and at the same time be removed from the original dict. > > OK, this is how I do it right now: > > dict1 = { "a":1, "b":3, "c":5, "d":4, "e":2 } > dict2 = {} > klist = [] > > for key in dict1: > if dict1[key] > 3: # some criterion > dict2[key] = dict1[key] > klist.append(key) > > for key in klist: > del dict1[key] > > print dict1 > print dict2 > > That means that I store the keys of the items to be removed from > the original dict in a list (klist) and subsequently remove the > items using these keys. > > Is there an "even more pythonic" way? > > Cheers, jsaul From langspam at yahoo.com Fri Apr 16 01:58:21 2004 From: langspam at yahoo.com (AndrewL) Date: 15 Apr 2004 22:58:21 -0700 Subject: CamelCase versus wide_names (Prothon) References: Message-ID: <75ad240a.0404152158.1530ab4b@posting.google.com> I most prefer Lisp style, which uses dashes, as in (with-open-file (do-foo-bar)) but that's not an option. Note that I don't yet find Lisp more readable than Python. It's just that I like the dashes. Next would be wide_names. I think it looks less elegant than camel case, but it's more readable for me. It's what I use in my Python (and the Perl they force me to write at work). And I don't know why I find Lisp's dash less jarring than underscores. It just flows better for me. A professor in a programming class told us of a study that found wide names are easier for non-native speakers to read. I can see that. Compare trying to make sense of these two: genusIrritabileVatumDel versus genus_irritabile_vatum_del, especially if you're getting pages of it. The ease of typing is much less of an issue for me than readability. I have a macro in jEdit that inserts an underscore, and it's mapped to alt-spacebar. Plus I use auto-complete. So go for (what I personally consider) readability. Andrew Langman From eppstein at ics.uci.edu Sun Apr 4 18:09:23 2004 From: eppstein at ics.uci.edu (David Eppstein) Date: Sun, 04 Apr 2004 14:09:23 -0800 Subject: Working with a list in a more "pythonic" way References: <20040404124833458+0200@news.rhrz.uni-bonn.de> Message-ID: In article , "Terry Reedy" wrote: > Rewritten, your code is > > score = 0 > for i in range(len(phrase)-1): > score += soundScoreMatrix[ord(x[i]) - 65][ord(x[i + 1]) - 65] > > Once written thusly, the reduce form is obvious (but obviously not tested): > > reduce(lambda score, i: score + soundScoreMatrix[ord(x[i]) - 65][ord(x[i + > 1]) - 65], > range(len(phrase)-1), 0) > > but aside from any didactic value this has, I prefer, in this case, the > written-out loop. I prefer the sum form -- if sum() isn't good for this example, what is it there for at all? I also don't like seeing the magic number 65 without some sort of explanation. And how come you're using x in one place and phrase in another? ords = [ord(c) - ord('A') for c in phrase.upper()] score = sum([soundScoreMatrix[ords[i]][ords[i+1]] for i in range(len(phrase)-1) if 0 <= ords[i] < 26 and 0 <= ords[i+1] < 26]) -- David Eppstein http://www.ics.uci.edu/~eppstein/ Univ. of California, Irvine, School of Information & Computer Science From nc-jantzegu at netcologne.de Fri Apr 2 16:09:55 2004 From: nc-jantzegu at netcologne.de (Günter Jantzen) Date: Fri, 2 Apr 2004 23:09:55 +0200 Subject: Travelling salesman variation in python References: Message-ID: "Jeff Epler" schrieb im Newsbeitrag news:mailman.248.1080852947.20120.python-list at python.org... > Can't TSP be converted to your problem? > > If you have TSP with distance(Xi, Xj)=Dij, then convert it to your > problem by letting distance(X'i, X'j)=distance(X'j, X'i)=-Dij. > or if only positive weights are allowed then use max(D)-Dij. > > Jeff > Of course, Jeff you are right! There is a lot of pointers at the ACM portal http://portal.acm.org/results.cfm?coll=Portal&dl=Portal&CFID=19701367&CFTOKE N=66344476 G?nter From josh.reeves at gmail.com Thu Apr 15 19:13:06 2004 From: josh.reeves at gmail.com (josh R) Date: 15 Apr 2004 16:13:06 -0700 Subject: Newbie question: matching Message-ID: Hi all, I am trying to write some python to parse html code. I find it easier to do in perl, but would like to learn some basic python. My code looks like this: line = "eat at joe'sor elseyou'll starve" so = re.compile("(\.*?\<\\tr\>)") foo=so.match(line) print foo.groups() I'd like to get an array of elements that looks like this: array(0)= eat at joe's array(1)= or else array(2)= you'll starve Could you please tell me the correct way to do the matching? also, is there something similiar to perl's s/foo/bar/g? Thanks!!! Josh From ny_r_marquez at yahoo.com Mon Apr 19 15:14:51 2004 From: ny_r_marquez at yahoo.com (R.Marquez) Date: 19 Apr 2004 12:14:51 -0700 Subject: Does Python compete with Java? References: <8b336527.0404051337.51bb4a1b@posting.google.com> <407deb56$1@news.unimelb.edu.au> <8b336527.0404151019.14b93502@posting.google.com> Message-ID: <8a27e309.0404191114.4a6328da@posting.google.com> > I would hope that someday Python would be a "tool" that "most" > developers would want to have in their "tool box". The day "most" developers use Python is the day it stops being a competitive advantage. ;) Seriously, if you are starting a company with a good product idea in mind, Python would be an excelent choice to get you going. (Wasn't a certain search engine company started that way?) -Ruben From bdesth.quelquechose at free.quelquepart.fr Thu Apr 1 04:12:51 2004 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 01 Apr 2004 11:12:51 +0200 Subject: ANNOUNCE: 'goto' for Python In-Reply-To: References: Message-ID: <406bd703$0$14074$626a14ce@news.free.fr> Richie Hindle wrote: > Entrian Solutions is pleased to announce version 1.0 of the 'goto' module. > > This adds the 'goto' and 'comefrom' keywords to Python 2.3, adding > flexibility to Python's control flow mechanisms and allowing Python > programmers to use many common control flow idioms that were previously > denied to them. > Trop gros, passera pas... !-) From roy at panix.com Sat Apr 17 08:54:26 2004 From: roy at panix.com (Roy Smith) Date: Sat, 17 Apr 2004 08:54:26 -0400 Subject: Difficulty Finding Python Developers References: <65cbc3dd.0404140641.3501fde8@posting.google.com> <407D6269.3090909@engcorp.com> <40808FF1.7060204@cs.com> <4080AE97.C4CF0755@alcyone.com> <408110CE.7030402@cs.com> Message-ID: "Robert M. Emmons" wrote: > I think I would be more worried about the non-python language things -- > they are harder to learn and take more time, and are where depth is > important. Python itself is easy to learn. Learning to write CGI > scripts, using Zope, doing database work, making a web site, using > wxWindows, etc. These are more than just Python. Because of that -- > the person that's going to do the job is going to need to be an expert > in some of these areas...otherwise long learning curve. That's an excellent point. I think most programmers underestimate the importance (and difficulty) of all the non-coding activities that go into making a successful business. Web development is a perfect example. A good website is more about content and usability (and often, databases) than it is about coding the dynamic page generation engine. Likewise, in any project involving more than about 2 people, software process engineering starts to become as critical as programming. Things like poor configuration management, quality control, requirements gathering and documentation are more likely to sink a big project than bad coding. From mwh at python.net Thu Apr 8 07:55:27 2004 From: mwh at python.net (Michael Hudson) Date: 08 Apr 2004 12:55:27 +0100 Subject: getting from code object to class/function In-Reply-To: <16500.50009.267575.290860@montanaro.dyndns.org> References: <16500.50009.267575.290860@montanaro.dyndns.org> Message-ID: Skip Montanaro writes: > >> There is, however, no direct way back from the code object to (for > >> example) the class and method which "own" that object. I didn't see > >> anything obvious in the inspect module that would allow me to worm > >> around this problem. > > mwh> gc.get_referrers? > > Interesting idea. I'm not sure it'll work though: I don't think code objects participate in GC, so I don't know if function's traverse function call the callback on the code object. That said, I've just tried it, and it does work :-) Cheers, mwh -- We've had a lot of problems going from glibc 2.0 to glibc 2.1. People claim binary compatibility. Except for functions they don't like. -- Peter Van Eynde, comp.lang.lisp From fredrik at pythonware.com Wed Apr 21 12:55:24 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 21 Apr 2004 18:55:24 +0200 Subject: python shutting down sloooooooowly/tuning dictionaries References: <20040421153923.GA13234%till@score.is.tsukuba.ac.jp> Message-ID: > have you tried using > > os._exit() > > instead of sys.exit() better make that os._exit(0) From no.email at please.com Mon Apr 12 15:07:43 2004 From: no.email at please.com (Stevie_mac) Date: Mon, 12 Apr 2004 20:07:43 +0100 Subject: String + number split References: <2SAec.70005$Id.6002@news-binary.blueyonder.co.uk> Message-ID: > It's impossible to say if it's more elegant, since you didn't > post your attempt. Yeh, sorry bout tha! > (Homework? I'll assume not.) Only a student of life! Heres my solution... import string def makefont(sFontName): num = [] nam = [] acnt = 0 #reverse it l = list(sFontName); l.reverse(); ''.join(l) sFontName = string.join(l,'') #now loop it while isdigit(), store number, then store alphas for c in sFontName: if c.isdigit() and acnt == 0: num.append(c) elif c.isalpha() or acnt > 1: acnt += 1 nam.append(c) nam.reverse() num.reverse() return (string.join( nam, '' ), int(string.join( num, '' ))) Now you see why i was asking for a more elegant solution! PS, the number on the end may vary & the _ could be any non alpha char! font12 becomes ('font',12) arial_14 becomes ('arial',14) arial__8 becomes ('arial',8) times 6 becomes ('times',6) "Peter Hansen" wrote in message news:mfydnfKTtqtWRufdRVn-uQ at powergate.ca... > Stevie_mac wrote: > > Hello again, I can do this, but I'm sure there is a much more elegant way... > > > > A string, with a number on the end, strip off the number & discard any underscores > > > > eg... > > > > font12 becomes ('font',12) > > arial_14 becomes ('arial',14) > (Homework? I'll assume not.) > > >>> import re > >>> def fsplit(fs): > ... return tuple(re.split('(\d+)', fs.replace('_', ''))[:2]) > ... > >>> fsplit('font12') > ('font', '12') > >>> fsplit('arial_14') > ('arial', '14') > > I wouldn't actually code it this way myself, but it meets > your requirements as stated. > > -Peter From gerrit at nl.linux.org Thu Apr 15 05:47:15 2004 From: gerrit at nl.linux.org (Gerrit) Date: Thu, 15 Apr 2004 11:47:15 +0200 Subject: Pygame In-Reply-To: <107rlp0in3r1k76@news.supernews.com> References: <107qkrbhnjpmh9b@news.supernews.com> <107rlp0in3r1k76@news.supernews.com> Message-ID: <20040415094715.GA29865@nl.linux.org> John Roth wrote: > What I don't find is support for specialty application areas. > Games are a specialty application area. The name pygame is IMHO misleading. It's applicable beyond games. > > Python is supposed to be "batteries included", but still hasn't got native > > support for fullscreen graphics. > > Pygame is layered on top of SDL, which in turn is layered on > top of Open GL. SDL is not layered on top of OpenGL. I think it's exactly the other way around. I use Pygame a lot and I don't have OpenGL installed. Gerrit. -- Weather in Twenthe, Netherlands 15/04 11:25: 16.0?C Clear sky clear wind 3.1 m/s SSE (57 m above NAP) -- Experiences with Asperger's Syndrome: EN http://topjaklont.student.utwente.nl/english/ NL http://topjaklont.student.utwente.nl/ From nuffsaid at phreaker.net Fri Apr 30 21:54:40 2004 From: nuffsaid at phreaker.net (Nuff Said) Date: Sat, 01 May 2004 03:54:40 +0200 Subject: IDE for Python References: Message-ID: On Sat, 01 May 2004 01:10:51 +0000, Venkatesh Prasad Ranganath wrote: > Nuff Said wrote: >> Why an IDE? Python is - IMO - (one of) THE languages, where >> a good editor (tabs2spaces, comment blocks, select encoding, >> syntax highlighting, auto-indentation, scriptable ...) is all >> you really need. >> >> (Bluefish ain't the editor of your choice here; write your own >> from scrap or write one using Scintilla; resp. use SciTE with >> a good customization file; or go for (X)Emacs resp. Vim.) > Try eric3 at http://www.die-offenbachs.de/detlev/eric3.html Why? If you are into Qt, it might be a good choice (but if you are not, eric3 is a little bit *too* Qt-centric, IMHO). There are a lot of solutions for special Python/GUI combinations, but none of them seems to be the *editor of your choice* if you are not yet restricted to one GUI solution. Nuff. From gmuller at worldonline.nl Sun Apr 25 16:46:48 2004 From: gmuller at worldonline.nl (GerritM) Date: Sun, 25 Apr 2004 22:46:48 +0200 Subject: Andreas' practical language comparison References: Message-ID: <408c23b8$0$41746$5fc3050@dreader2.news.tiscali.nl> "Andreas Koch" schreef in bericht news:c6gu81$pk6$05$2 at news.t-online.com... <..snip...> > > I sent bubble sort, based on the algorithm, but I'm not going > > to bother with more if this is simply a fewest-lines competition, > > since the first person to post some Perl will win (although K > > appears to be ready to give tight competition in that area, > > if the current list is any indication). > > It is on no way a fewest-lines competiton, especially considering > that my favourite language (Delphi) had the most lines in nearly > every test case :-) > > I removed the line counts from the overview matrix until we find > a better solution. > I really would like to see the linecount. I do belive that it is one of the indicators of the power of the language and its batteries. Somehow it would be nice to have a figure for "readability", but I don't have a clue how to generate such a figure in an automatic way. Maybe you need some panel of experts that gives a readability figure? kind regards, Gerrit -- www.extra.research.philips.com/natlab/sysarch/ From eppstein at ics.uci.edu Fri Apr 30 01:29:21 2004 From: eppstein at ics.uci.edu (David Eppstein) Date: Thu, 29 Apr 2004 22:29:21 -0700 Subject: Feedback on Sets, and Partitions References: Message-ID: In article , David Eppstein wrote: > In article , > "Steve" wrote: > > > For my current project, I need to generate partitions of sets up to size > > 25. I am rather hopeless it will ever be feasible, and I have begun > > looking for a different approach. Thanks for any replies! > > There are 4638590332229999353 partitions of an 25 item set. > > > So, I think generating them all is a little out of the question. BTW, here is some code for generating these numbers. I think it's a little interesting that one can write the obvious one-line definition for factorials, forgetting the base case, and then make it work anyway via the magic of memoization. Something to think about in connection with PEP 318... def memoize(recurrence, base_case={}): memo = {} for k,rk in base_case.items(): if not isinstance(k,tuple): k = (k,) memo[k] = rk def memoized(*args): if args not in memo: memo[args] = recurrence(*args) return memo[args] return memoized def factorial(n): return factorial(n-1)*n factorial = memoize(factorial, base_case={0:1}) def choose(n,k): return factorial(n) // factorial(k) // factorial(n-k) def bell(n): return sum([choose(n-1,k)*bell(n-1-k) for k in range(n)]) bell = memoize(bell, base_case={0:1}) print "There are",bell(25),"partitions of a 25 item set." -- David Eppstein http://www.ics.uci.edu/~eppstein/ Univ. of California, Irvine, School of Information & Computer Science From mwh at python.net Mon Apr 12 06:08:30 2004 From: mwh at python.net (Michael Hudson) Date: Mon, 12 Apr 2004 10:08:30 GMT Subject: new-style class instance check References: Message-ID: "Richard Gruet" writes: > Right, you are perfectly right. > As Robert (Brewer) guessed, I was actually naively trying to detect > whether an object was an instance of a *user-defined* new-style > class in an attempt to find and equivalent to type(o) is > InstanceType for new-style classes - so my function could be more > appropriately named e;G. isUserDefinedNewStyleClassInstance(o). You could check the tp_flags member for the TP_HEAPTYPE bit -- but this is C talk and doesn't translate into Python that cleanly (o.__class__.__flags__ & (1<<9) or similar) and isn't 100% reliable. Of course, type(o) is InstanceType isn't reliable either -- it's true for e.g. Exception. Why do you want to know? Cheers, mwh -- Windows XP: Big cow. Stands there, not especially malevolent but constantly crapping on your carpet. Eventually you have to open a window to let the crap out or you die. -- Jim's pedigree of operating systems, asr From python at simon.vc Mon Apr 19 09:42:20 2004 From: python at simon.vc (SimonVC) Date: 19 Apr 2004 06:42:20 -0700 Subject: imitating user input References: Message-ID: Try This: Rob Marchetti: Pamie [Pamie allows you to write Python scripts in order to drive Internet Explorer. Pamie is a lite Python port of SAMIE written in Perl by Henry Wasserman. This is a "free" open-source tool written for QA engineers or developers as a means to simulate users exploring a web site. ] http://pamie.sourceforge.net/ From peter at engcorp.com Fri Apr 9 22:42:27 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 09 Apr 2004 22:42:27 -0400 Subject: automatically generating file dependency information from python tools In-Reply-To: References: Message-ID: Moosebumps wrote: > Say you have a group of 20 programmers, and they're all writing python > scripts that are simple data crunchers -- i.e. command line tools that read > from one or more files and output one or more files. Shall we read into this the implication that there is no coding standard of any kind being used for these tools? So no hope of saying something as simple as "use constants for all filenames, using the following conventions..."? > I want to set up some sort of system that would automatically generate > makefile type information from the source code of these tools. Can anyone > think of a good way of doing it? You could make everyone call a special > function that wraps the file() and detects whether they are opening the file > for read or write. I think you've mixed up your two ideas in the above. You don't really mean "source code" here, do you? You mean catching the information dynamically from the running program, I think. That is something that is probably quite easy to do with Python. For example, just have everyone import a particular magic module that you create for this purpose at the top of their scripts. That module installs a replacement open() (or file()) function in the builtins module, and then any file that is opened for reading or writing can be noticed and relevant notes about it recorded in your repository. > The other thing I could think of is statically analyzing the source code -- > but what if the filenames are generated dynamically? As you've guessed, much harder to do. Especially with a language that is not statically typed... (dare I say? ;-) -Peter From simon at brunningonline.net Wed Apr 28 05:08:18 2004 From: simon at brunningonline.net (Simon Brunning) Date: 28 Apr 2004 02:08:18 -0700 Subject: MS COM early and late binding References: <9e5ea2c4.0404271039.2da829b5@posting.google.com> <408ed8e5$1_1@newspeer2.tds.net> Message-ID: <314b29e9.0404280108.65fbf9b@posting.google.com> "Olaf Meding" wrote in message news:<408ed8e5$1_1 at newspeer2.tds.net>... > What you suggest might work, but does not look to elegant. Can anyone else > perhaps suggest a more elegant solution? Thanks. Not elegant? This is COM, you know! Anyway, I do this: excel = win32com.client.gencache.EnsureDispatch('Excel.Application') Then I know I'm using early binding. Cheers, Simon B. From davidb at mcs.st-and.ac.uk Thu Apr 15 07:04:13 2004 From: davidb at mcs.st-and.ac.uk (David Boddie) Date: 15 Apr 2004 04:04:13 -0700 Subject: Pygame References: <107qkrbhnjpmh9b@news.supernews.com> <107rksn9nosm78a@news.supernews.com> Message-ID: <4de76ee2.0404150304.3048ee44@posting.google.com> "John Roth" wrote in message news:<107rksn9nosm78a at news.supernews.com>... > If you look at PyGame, you'll find that it's based on SDL, which seems > to be a very good library for doing graphics. That, in turn, is based on > OpenGL. Correct me if I'm wrong but, as far as I'm aware, SDL isn't based on OpenGL at all. If you're only creating 2D content, you don't need a working OpenGL implementation on your target platform. > It also (optionally) uses Numeric, which hasn't been included with Python > because the developers don't want to wait for major Python updates. That's a more important issue, I'll admit. Personally, I'm not in favour of sweeping all the most popular third party libraries into the standard library, although I can understand the motivation of the original poster for wanting to include Pygame. David From bkelley at wi.mit.edu Tue Apr 27 10:29:21 2004 From: bkelley at wi.mit.edu (Brian Kelley) Date: Tue, 27 Apr 2004 10:29:21 -0400 Subject: how to add new print %b format to python? In-Reply-To: <108qjne9jqtit4c@news.supernews.com> References: <108qjne9jqtit4c@news.supernews.com> Message-ID: <408e6e71$0$561$b45e6eb0@senator-bedfellow.mit.edu> John Roth wrote: > "Rusty Shackleford" wrote in message > news:slrnc8q9qp.htc.rs at frank.overlook.homelinux.net... > >>I have a Summer in front of me without any school, and I'd like to add a >>new format for python print strings that will show any number in a >>binary representation. For example: >> >> >>>>>'%b' % 3 >> >>11 >> >>>>>'%b' % 5 >> >>101 For some implementation PEP discussion ideas, I like this format, but there are additional complexities such as what is '%b' % -1 ? This might just be a binary string equivalent to the current machine bits. But what about long integers? '%b' % (-1L) This is technically an infinite string of ones. Perhaps a useful solution is when printing out negative numbers, the user must supply the padding. so >> '%b' % (-1) raise a ValueError or some such and Traceback (most recent call last): File "", line 1, in ? ValueError: Binary format %b for negative numbers must have bit length specified and >> '%32b' % (-1L) 11111111111111111111111111111111 Now for the source, you want to look at stringobject.c and in particular the PyString_Format function. You can find the cvs version here: http://cvs.sourceforge.net/viewcvs.py/python/python/dist/src/Objects/stringobject.c?view=markup Note that you can make a test case by subclass string and the __mod__ function. This might actually be harder though since you will have to figure out which argument is supposed to belong to the %b formatter. from types import StringType class mystring(StringType): def __mod__(self, *k, **kw): return StringType.__mod__(self, *k, **kw) Good Luck From greg at cosc.canterbury.ac.nz Fri Apr 16 00:19:23 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Fri, 16 Apr 2004 16:19:23 +1200 Subject: Wrapper round x86 Assembler In-Reply-To: <107g0m9sg8h85b3@news.supernews.com> References: <8089854e.0404082353.7bf163a2@posting.google.com> <107g0m9sg8h85b3@news.supernews.com> Message-ID: John Roth wrote: > Intel > CPU's are going to a model where dynamically generated code won't > work unless you provide the correct incantation. This is to eliminate a > large class of viri. As long as Microsoft continue to do things like providing a nice cross-platform virus environment in their word processors and mail handlers, I can't see this helping much... -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From michael at foord.net Wed Apr 14 03:16:35 2004 From: michael at foord.net (Fuzzyman) Date: 14 Apr 2004 00:16:35 -0700 Subject: Wrapper round x86 Assembler References: <8089854e.0404082353.7bf163a2@posting.google.com> <2ae25c6b.0404100840.10668dca@posting.google.com> Message-ID: <8089854e.0404132316.365e099b@posting.google.com> paddy3118 at netscape.net (Paddy McCarthy) wrote in message news:<2ae25c6b.0404100840.10668dca at posting.google.com>... > michael at foord.net (Fuzzyman) wrote in message news:<8089854e.0404082353.7bf163a2 at posting.google.com>... > > There might be a really good reason why this hasn't been done *or* > > someone might have done it and I just can't find it..... *but* > > > > what about a wrapper to an assembler (presumably for x86 assembly !) > > !! > > I just wrote some code doing binary operations which would have been > > about a zillion times faster in a few lines of assembly code. > > > > I also have fond memories of programming in BBC Basic which had an > > inline assembler - so you could wrap your assembly program in Basic. > > It meant some commercial games started with Basic ! > > > > Anyway - it would be easy to reserve some memory with a string like > > object to pass to an 'assembly object' and allow some really nifty > > (and fast) stuff ?? For simple algorithms it would be very neat. > > Avoiding memory overflow etc would be up to the assembly code 'chunk' > > of course. > > > > Regards, > > > > > > Fuzzy > > > > http://www.voidspace.org.uk/atlantibots/pythonutils.html > I.m sure that what I am about to suggest isn't as high tech as you > were expecting , > but I thought that Python already has a way of accessing functions in > a Unix > shared library, or Windows DLL. > If you cancompile Python on the platform than you no doubt have an > assembler handy too. > So, you could put your assemble language in a string; write the string > to a file; > assemble the file to create a shered library or DLL, then call the > function from Python! > > I don't think I'd do it that way though :-) > > Cheers, Pad. Ha - in someways this is more like what I envisioned. What would have been nice would have been to have kept the string in memory and called it directly....(a nice dynamic solution - for a nice dynamic language) - but if modern OS / processor combinations have real issues with jumping directly into 'unoptimized' code - then it may remain a pipe-dream... *sigh* Regards, Fuzzy From agriff at tin.it Sun Apr 25 13:36:43 2004 From: agriff at tin.it (Andrea Griffini) Date: Sun, 25 Apr 2004 17:36:43 GMT Subject: iterating over collection, deleting entries References: Message-ID: On Sun, 25 Apr 2004 18:25:08 +0200, "Patrick von Harsdorf" wrote: >Please tell me, what?s the best way to do this? I'm pretty new to python, but normally this is done by a simple read-write approach. You iterate over the elements using a "read" pointer, and every time you find one you want to keep you just write it and increment the write pointer. In code... wrp = 0 for x in container: if is_good(x): container[wrp] = x wrp += 1 del container[wrp:] This is O(n) and doesn't require any additional memory I suppose however that it's not so common finding cases in which this is much better than... a = [x for x in a if is_good(x)] The latter will allocate a list for the result (instead of reusing the same), but can free the original (and this may be *better* than just resizing it - it may be better in C++, for example). HTH Andrea From psXdaXsilva at esotericaX.ptX Fri Apr 9 20:09:55 2004 From: psXdaXsilva at esotericaX.ptX (Paulo da Silva) Date: Sat, 10 Apr 2004 01:09:55 +0100 Subject: Parsing cmd line args problem Message-ID: <1081555827.877735@jubilee.esoterica.pt> Hi. I am writing my 1st. python program and I have the following problem: I need to build a list of lists (or tuples) for every -i option. Example: prog -i xxx -i yyy and get a list like [[xxx,1],[yyy,1]] I have tried this (callback) without any success: ... def ixOpt(option,opt,value,parser): if getattr(parser.values,option.dest)=="None": #setattr(parser.values,option.dest,[[value,1]]) parser.values.ix=[[value,1]] else: #setattr(parser.values,option.dest,getattr(parser.values,option.dest)+[value,1]) parser.values.ix.append([[value,1]]) def parseArgs(): ... add_option("-i", "--include", action="callback",callback=ixOpt, type="string",dest="ix", help="Include file PATTERN",metavar="PATTERN") Any help please? Thanks From chatralias at aol.com Mon Apr 12 13:48:45 2004 From: chatralias at aol.com (Chatralias) Date: 12 Apr 2004 17:48:45 GMT Subject: Newbie Prob Installing Pythonwin23 Message-ID: <20040412134845.12763.00000096@mb-m24.aol.com> Hello, all Installed Python2.3.3.exe seams to be working okay. Installed pywin32-200.win32-py2.3.exe and it can't find a file. Here is the traceback Python Traceback when executing Initinstance handler. File "C:\PYTHON23\Lib\site-packages\Pythonwin\pywin\framework\intpyapp.py", line 163, in InitInstance import interact File "C:\PYTHON23\Lib\site-packages\Pythonwin\pywin\framework\interact.py", line 26, in ? import winout File "C:\PYTHON23\Lib\site-packages\Pythonwin\pywin\framework\winout.py", line 26, in ? from pywintypes import UnicodeType File "C:\PYTHON23\Lib\site-packages\win32\lib\pywintypes.py", line 55, in ? __import_pywin32_system_module__("pywintypes", globals()) File "C:\PYTHON23\Lib\site-packages\win32\lib\pywintypes.py", line 48, in __import_pywin32_system_module__ raise ImportError, "Can not locate " + filename exceptions.ImportError: Can not locate pywintypes23.dll I thonght maybe it was a conflict with a previously installed version of python so I've cleaned all the python of my computer and redownloaded and reintalled Python2.3.3.exe and pywin32-200.win32-py2.3.exe. I can't seem to get pywin23-200 to start. Any Ideas? running on Pentium1 win98 Thanks Ray St. Marie Rastm2 at aol.com From pascal.parent at free.fr Wed Apr 28 04:35:11 2004 From: pascal.parent at free.fr (Pascal) Date: 28 Apr 2004 01:35:11 -0700 Subject: String formatting (%) Message-ID: Hello, I've a float number 123456789.01 and, I'de like to format it like this "123 456 789.01". Is this possible with % character? From cedmunds at spamless.rochester.rr.com Wed Apr 28 23:10:40 2004 From: cedmunds at spamless.rochester.rr.com (Cy Edmunds) Date: Thu, 29 Apr 2004 03:10:40 GMT Subject: GUI thread and Python IDLE References: Message-ID: "huwind" wrote in message news:f3acdcef.0404281348.157acfe7 at posting.google.com... > Hi, > > I got a problem with Python IDLE to run Tkinter application. I use > thread to start a Tkinter application. It works fine on Linux when I > invoke the program from command line. But when I try to use IDLE, the > GUI doesn't show up until I close the IDLE edit window and the Python > shell window. Does anybody have any idea? > > - huwind Have a look at: http://www.ferg.org/thinking_in_tkinter/index.html Evidently IDLE is itself a TKinter program. -- Cy http://home.rochester.rr.com/cyhome/ From hat at se-126.se.wtb.tue.nl Mon Apr 19 03:37:44 2004 From: hat at se-126.se.wtb.tue.nl (Albert Hofkamp) Date: Mon, 19 Apr 2004 07:37:44 +0000 (UTC) Subject: Python - matlab interface help!! Urgent References: Message-ID: On 16 Apr 2004 07:42:04 -0700, Leeny wrote: > leens_chacko at hotmail.com (Leeny) wrote in message news:... >> Hi Group, >> >> Hope someone can help me with this problem. I am a new user to python >> and am currently working with pymat module of python (for coursework). >> > >> I tried to create plots thru pymat using pymat.eval(h, 'plot(x,y)') >> This is working fine. However, i dont know how to print or save this >> plot as a .tif image something like >> >> print(gcf, '-dtiff', 'test') >> >> using pymat. > One suggestion I got was to use mathplotlib, but since i have done > some work uisng pymat, I would like to know if there is some way it > can be done using Pymat. The last parameter of eval is the literal matlab command as a string (ie quotes before and after it). In other words if you type XYZ to do it in matlab, then the pymat equivalent is pymat.eval(h,'XYZ') If you have ' inside XYZ, use " instead, like pymat.eval(h,"XYZ") . So, if the print command is how to print something, do pymat.eval(h,"print(gcf, '-dtiff', 'test')") Albert -- Unlike popular belief, the .doc format is not an open publically available format. From tjreedy at udel.edu Wed Apr 14 19:10:31 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 14 Apr 2004 19:10:31 -0400 Subject: Pygame References: Message-ID: "Alexander R?dseth" wrote in message news:c5jgvh$2m5$1 at orkan.itea.ntnu.no... > > What do you think should be the criteria for deciding whether > > something "is part of Python" or isn't? > > I agree that my question was a bit vague, so here's a clarification: > In that connection I meant "included in the standard installation procedure > for the average inexperienced user". Things do not just get 'included in the standard installation procedure' without someone doing the work to get it in and keep it working. Python is an all-volunteer operation. For anything new to get added to the distribution, someone (usually the project leader) must volunteer to write a PEP (if deemed necessary) or otherwise lead and participate in a discussion of features, interface, and implementation. This may result in changes required for acceptance. Then the documentation and code must meet current standards. Then there must be a commitment to respond to bug reports for at least a few years. And yes, the package should be 'generally' useful and the best available. Many package authors prefer to keep control of their own work. Terry J. Reedy From teiffel at attglobal.net Thu Apr 29 00:22:35 2004 From: teiffel at attglobal.net (Marcello Pietrobon) Date: Thu, 29 Apr 2004 00:22:35 -0400 Subject: uuid generator In-Reply-To: <408DE4F3.7080804@magma-da.com> References: <71djc.147368$Kc3.4878757@twister2.libero.it> <408DE4F3.7080804@magma-da.com> Message-ID: <4090830B.8010903@attglobal.net> ( sending it again ) Hello, I need to read newly generated uuid from Python but I am not sure if http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/163604 is the right code Maybe there is already the library in Python 2.3 Maybe I can use the one generated with uuidgen under cygwin but this would not be portable In this last case I would like to know how can I capture the output of uuidgen so I can use it in my script Thank you if you know the answer ! Cheers, Marcello From frenchsk8 at hotmail.com Wed Apr 14 13:40:22 2004 From: frenchsk8 at hotmail.com (Thibault) Date: 14 Apr 2004 10:40:22 -0700 Subject: lauching Spambayes on Mac OS 9 Message-ID: <104977dd.0404140940.1a4505d9@posting.google.com> Hi, i tried to use SpamBayes, a well known antispam on this group...but i cant't even launch it. I've installed the latest version of python for mac os 9. But now the spambayes indicates that i have to run python setup.py and then run python scripts/sb_server.py...and that's the problem! i can't figure out how to run these commands! I need your help!! please Thibault From ramen at lackingtalent.com Wed Apr 7 23:29:41 2004 From: ramen at lackingtalent.com (Dave Benjamin) Date: Thu, 08 Apr 2004 03:29:41 -0000 Subject: Does Python compete with Java? References: <8b336527.0404051337.51bb4a1b@posting.google.com> Message-ID: In article , A. Lloyd Flanagan wrote: > Greg Ewing wrote in message news:... >> >> I think it's a *good* thing. Python is succeeding very well >> by just existing and actually being well designed and useful, >> as opposed to having a large company's marketing machine trying >> to tell everyone that it is. > > Very true. In addition, I think python will gain a lot of > "mind-share" as more and more popular applications are written in > python. Over the long term, I think Python's biggest key to success will be that we will still be able to read the programs that we are writing now. -- .:[ dave benjamin: ramen/[sp00] -:- spoomusic.com -:- ramenfest.com ]:. : please talk to your son or daughter about parametric polymorphism. : From tundra at tundraware.com Fri Apr 9 01:40:11 2004 From: tundra at tundraware.com (Tim Daneliuk) Date: 09 Apr 2004 01:40:11 EDT Subject: why is python better than eg. smalltalk?? no one has any solid arguments! you should all go to church with all that religious talk! In-Reply-To: <1081487366.538219@yasure> References: <20031028061245.12451.00000133@mb-m01.aol.com> <1081487366.538219@yasure> Message-ID: Donn Cave wrote: > Quoth Tim Daneliuk : > ... > | My view on Python's real virtue from several years ago: > | > | http://www.tundraware.com/Technology/Python-Is-Middleware/ > > What do you think now, several years later, about `A Little Warning' > at the end of that page? > > Donn Cave, donn at drizzle.com I think that the community has mostly managed to keep this under control. The additions to the language in the past several years, IMHO, have been restrained, appropriate, and reasonable. -- ---------------------------------------------------------------------------- Tim Daneliuk tundra at tundraware.com PGP Key: http://www.tundraware.com/PGP/ From PeterAbel at gmx.net Tue Apr 13 12:02:54 2004 From: PeterAbel at gmx.net (Peter Abel) Date: 13 Apr 2004 09:02:54 -0700 Subject: how to break tuple to separate variables References: Message-ID: <21064255.0404130802.60930588@posting.google.com> Stano Paska wrote in message news:... > Hi. > > I need pass variables to function like tuple, but function accepts > separate variables. > > Is there some elegant solution? > > My example: > > # ------------------------------- > import datetime > > def date2tuple(aaa): > try: > y = int(aaa[:4]) > m = int(aaa[5:7]) > d = int(aaa[8:10]) > except: > y = m = d = 0 > return (y, m, d) > > # i need some like this > bbb = datetime.date(date2tuple('2004-11-03')) > > # but date requires > bbb = datetime.date(2004, 11, 03) > > # ------------------------------- > > Thanks. > > Stano Paska try: >>> tuple('2004-11-03'.split('-')) ('2004', '11', '03') >>> Regards Peter From jcm at FreeBSD-uk.eu.org Mon Apr 26 12:02:26 2004 From: jcm at FreeBSD-uk.eu.org (Jonathon McKitrick) Date: Mon, 26 Apr 2004 17:02:26 +0100 Subject: Best way to add attributes to shelved objects? In-Reply-To: <16525.12113.839367.623697@montanaro.dyndns.org> References: <20040423193951.GC27351@dogma.freebsd-uk.eu.org> <16521.29527.356495.151656@montanaro.dyndns.org> <20040426150535.GA63648@dogma.freebsd-uk.eu.org> <16525.12113.839367.623697@montanaro.dyndns.org> Message-ID: <20040426160226.GA65172@dogma.freebsd-uk.eu.org> On Mon, Apr 26, 2004 at 10:48:33AM -0500, Skip Montanaro wrote: : skip> Why not check for those attributes in your __getstate__ method and : skip> add default (or computed) values for any missing attributes? : : jm> I tried experimenting with these, and could not get them to work. : ... : jm> Are there any examples on how to do this? : : How about: : : class Foo: : def __init__(self): : self.a = 1 : : def __setstate__(self, d): : if 'b' not in d: : d['b'] = 2 : self.__dict__ = d Perfect! Just what I was looking for. I was just doing the wrong thing in setstate. Thanks! jm -- My other computer is your Windows box. From greg at cosc.canterbury.ac.nz Mon Apr 26 00:35:00 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Mon, 26 Apr 2004 16:35:00 +1200 Subject: CamelCase versus wide_names (Prothon) In-Reply-To: References: <6e0680ac.0404211252.7f7b4358@posting.google.com> <4086DFA7.9736E7D3@alcyone.com> Message-ID: Paramjit Oberoi wrote: > If the language 'knew' that identifiers potentially consisted of > multiple words, maybe it could detect a few different kinds of > styles and automatically do the right thing? That could be achieved by making it case-insensitive and underscore-ignoring. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From alloydflanagan at comcast.net Thu Apr 15 13:36:47 2004 From: alloydflanagan at comcast.net (A. Lloyd Flanagan) Date: 15 Apr 2004 10:36:47 -0700 Subject: Best IDE? References: Message-ID: "Stevie_mac" wrote in message news:... > This has prolly been asked 100 times - so please refrain from flaming if you can... > > What's the best MSwindows editor for python? I'm currently using PythonWin I use Emacs. I keep trying new editors because emacs is hard to learn and I'd like to use Python as a scripting language. Then I find that one feature or another I depend on in emacs can't be done, or not easily, and I'm back to emacs. Emacs is an extremely powerful editor which is able to integrate well with the python interpreter and debugger. There used to be a separate version for Windows, but you can now get it from the same site as the other versions: http://www.gnu.org/directory/devel/editors/emacs.html From claird at lairds.com Sun Apr 4 20:22:37 2004 From: claird at lairds.com (Cameron Laird) Date: Mon, 05 Apr 2004 00:22:37 -0000 Subject: Advocacy opportunity Message-ID: <10719mdp83juif4@corp.supernews.com> I've been advised that is open to correction in its Python column. Who wants to tackle this? Python certainly supports interaction, we have plenty to boast about in regard to foreign functions, we offer GUIs in abundance, ... They seem rather liberal. If Python supports private methods and variables (and JavaScript does native threads!?!) (but somebody seems to have it in for C++), we might as well argue it gives root classes, too. I think if I had friends who were salesmen, they'd advise me, "You just mark, 'Yes', everywhere, and deal with it if someone argues." -- Cameron Laird Business: http://www.Phaseit.net From timr at probo.com Sun Apr 11 00:19:36 2004 From: timr at probo.com (Tim Roberts) Date: Sat, 10 Apr 2004 21:19:36 -0700 Subject: maximum length of a list & tuple References: Message-ID: Josiah Carlson wrote: >> I just would like to know if there is any limit to a list or tuple. > >It depends on how much memory you have. > >Run the following and the last thing it prints out is your limit... > > c = 1 > while c < 2**32: > try: > d = [1]*c > print c > c *= 2 > except: > break Interesting experiment. I get 64M on my 384MB machine, which suggests 4 bytes per list entry. Of course, now my swap file is packed full, and all my apps are running slowly while they page themselves back in... -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From spamtrap at nowhere.net Mon Apr 26 18:38:53 2004 From: spamtrap at nowhere.net (Steven) Date: Mon, 26 Apr 2004 23:38:53 +0100 Subject: Compiler Message-ID: Hi folks, Just curious, is there a python compiler? Or something that creates bytecode, like java? Regards, Steven From buzzard at urubu.freeserve.co.uk Fri Apr 2 08:16:57 2004 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Fri, 2 Apr 2004 14:16:57 +0100 Subject: Travelling salesman variation in python References: Message-ID: "Peter Maas" wrote in message news:c4jikc$eq4$1 at swifty.westend.com... > Nick Craig-Wood wrote: > > I used Simulated Annealing - have a search for the term and you'll see > > plenty of references. Its good at finding a (local) minimum. > > I used to think that Simulated Annealing avoids local traps and > is good at finding a global minimum, at least with a certain > probability that depends on some temperature function. Am I wrong? > > Mit freundlichen Gruessen, > > Peter Maas No, you're not. I think simulated annealing is a decent candidate for this problem. The difficulty (in my experience) is in finding decent parameters for the cooling schedule, so you can find good solutions in reasonable time. Duncan From mcfletch at rogers.com Tue Apr 20 12:20:36 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Tue, 20 Apr 2004 12:20:36 -0400 Subject: Difficulty Finding Python Developers In-Reply-To: References: <65cbc3dd.0404140641.3501fde8@posting.google.com> Message-ID: <40854DD4.60301@rogers.com> Paul Morrow wrote: > Yes, that's our ad. I guess hr wasn't as careful as they should've > been when they authored it (there's also a mispelled word)... :-( > > You probably already realized this, but that should've been $45 to $55 > per hour. *I* didn't realise that, I assumed $45,000/year to $55,000/year annual rate, which would be a reasonable rate in Canada (in Canadian dollars even) for a programmer with 1 or 2 years of experience. I'd forgotten just how well Americans get paid for having fun... but at least our taxes are higher :) . Enjoy, Mike _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From mark at prothon.org Fri Apr 30 01:32:35 2004 From: mark at prothon.org (Mark Hahn) Date: Thu, 29 Apr 2004 22:32:35 -0700 Subject: What is good about Prothon? References: <108t2tlo06j8vb9@corp.supernews.com> <69cbbef2.0404281446.4e0ab52e@posting.google.com> <69cbbef2.0404291609.72d391db@posting.google.com> Message-ID: has wrote: > In AS, a, b, and c are all equivalent and independent; any changes > made to one do not affect the others. It's a no-brainer to use, and > quite safe. In Prothon, b and c derive state and behaviour from a > unless/until it's modified locally (ie on b or c). Changes made to one > may or may not show up in another depending on the derived > relationship and subsequent changes*, I told you before that we had a Self-like copy and asked you then if using that would make you happy. You never answered that question. Now you've posted an example that ignores the Prothon copy (yes, it is spelled exactly like the AS copy :) Will you only be happy with Prothon if I rip out everything that is not like AS or Self? Isn't having Prothon capable of doing everything AS and Self can do, in the same way they do it, good enough for you? I know for a fact that it can do everything they can do because there are months left in the design and if you just got rid of that chip on your shoulder and pitched in and helped, it could work well for people who want to use it like you do. You should be aware that we are discussing right now the possibility of putting the whole "class-mimicing" structure on an object that is a descendent of a pure Self-like root object. Lenard is doing a pretty good job of explaing to me why we sometimes need objects without the "class-like" methods __new__ and __init__. Here is his response to my question about that ("Object" is the "pure" object and "buildable" would have __new__ and __init__): ------ Beginning of Lenard Lindstrom's post ------ > This is all very logical and I have no problem with it, but can you give me > a usage example of an object that would inherit directly from Object instead > of Buildable? I do not know about a specific usage example, but knowledge bases in artificial intelligence comes to mind as a general case: object ClydeLike(Object): $colour = "grey" $legcount = 4 $mass = 2500 object Clyde(ClydeLike): # Lieberman got it wrong. I can explain in a separate posting. pass object Fred(ClydeLike): $mass = 2400 Probably anything whose attributes are initialized to contants, that is, no calculations are required. Then specific initial attribute values for an extension object are set with the object statement. If descriptors are implemented in Prothon then value checks and special computations can be done on a per attribute bases, removing one more need for an _init_ function. The Buildable prototype would come into play for immutables and objects that convert several input values into a different internal representation at creation time. ---------- End of Lenard Lindstrom's post ------------ Lenard even said "Lieberman got it wrong." See! If you come over and help out there are other like-minded people to work with you By the way, the above code samples are from current builds of Prothon. The object keyword was added recently. From max at alcyone.com Sat Apr 3 23:58:52 2004 From: max at alcyone.com (Erik Max Francis) Date: Sat, 03 Apr 2004 20:58:52 -0800 Subject: minor bug in cmath.asin? References: <406F3EDA.970F953A@alcyone.com> Message-ID: <406F960C.8FD57D46@alcyone.com> Edwin Young wrote: > It's not clear if the leading - sign affects the entire expression or > indicates that i is negative. Python's implementation uses the former > - I argue that the latter is more correct. What's the difference? Multiplication on complex numbers is commutative. > I've also noticed that cmath.acos has the same issue, and that the > formula used for cmath.asinh is not quite accurate around 0 : > cmath.asinh(0) gives 4.44089e-16+0j, rather than 0 as expected. Remember that these transcendental functions are usually computed by approxmation. So it's not all that surprising that sin(0) isn't exactly 0. -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis \__/ Sit loosely in the saddle of life. -- Robert Louis Stevenson From cleso at hotmail.com Tue Apr 13 20:50:36 2004 From: cleso at hotmail.com (Dave) Date: Tue, 13 Apr 2004 17:50:36 -0700 Subject: Looking for Python Definition Message-ID: Greetings! Python22 is installed on my WINXP Home PC. I have no idea what is does, or why it is installed. I am not a programmer and do not know what purpose this program provides to me. Any and all information and suggestions are welcome. Thanks! -- Dave From helge at hefre.com Thu Apr 29 15:09:51 2004 From: helge at hefre.com (Helge) Date: 29 Apr 2004 12:09:51 -0700 Subject: Create object for item in list Message-ID: <39885b3c.0404291109.1ec58db2@posting.google.com> I wonder how this can be accomplished: I've got a list, containing several strings. The strings look like this: [ "Name1/N1/N2/N3" , "Name2/N1/N2/N3" , "..." ] I would like to create one object for each item in the list, and the name of the object should be "str(item.split("/")[0])". I've tried this, but it won't work: for item in list: str(item.split("/")[0]) = class(item) ... From gianluca.trombetta at tin.it Tue Apr 13 11:23:10 2004 From: gianluca.trombetta at tin.it (Gianluca Trombetta) Date: Tue, 13 Apr 2004 17:23:10 +0200 Subject: Processes list under Windows and Linux: How? References: Message-ID: Take a look at os module. There are some methods like geteuid() and other. Regards Gianluca "Carmine Moleti" ha scritto nel messaggio news:N7Tec.66715$rM4.2704780 at news4.tin.it... > Hi to everyone, > > I was thinking of a way to get the list of processes running on a machine > both with Windows and Linux. > > Is there anything I could search for in the standard library? > > Thanks in advance for your help > Regards, > Carmine > > > -- > http://mail.python.org/mailman/listinfo/python-list > From loic at fejoz.net Thu Apr 8 07:49:15 2004 From: loic at fejoz.net (Yermat) Date: Thu, 08 Apr 2004 13:49:15 +0200 Subject: getattr() in default namespace. In-Reply-To: References: Message-ID: SimonVC wrote: > Hi group, long time reader first time poster (ive always wanted to say > that). > > How do you use getattr() to get a refernce to a function defined in > the default namespace.. > > eg: > > >>>>dir() > > ['__doc__', '__name__', 'b1', 'b2', 'b3', 'rd'] > > >>>>b1 > > > >>>>getattr(self, "b1") > > > Traceback (innermost last): > File "", line 1, in ? > NameError: self > > >>>>getattr("b1") > > Traceback (innermost last): > File "", line 1, in ? > TypeError: getattr(): expected 2-3 args; got 1 >>> def b1(a): ... return a ... >>> dir() ['__builtins__', '__doc__', '__name__', 'b1'] >>> globals().keys() ['__builtins__', '__name__', '__doc__', 'b1'] >>> >>> globals()['b1'] >>> globals() {'__builtins__': , '__name__': '__main__', '__doc__': None, 'b1': } I can't see what you can do with getattr here... but : >>> len >>> getattr(__builtins__,"len") >>> getattr(__builtins__,"len") is len True Yermat From Scott.Daniels at Acm.Org Sun Apr 4 09:02:59 2004 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sun, 04 Apr 2004 06:02:59 -0700 Subject: Working with a list in a more =?utf-8?b?4oCecHl0aG9uaWPigJwg?= =?utf-8?q?way?= In-Reply-To: <20040404124833458+0200@news.rhrz.uni-bonn.de> References: <20040404124833458+0200@news.rhrz.uni-bonn.de> Message-ID: <40700e82$1@nntp0.pdx.net> Nickolay Kolev wrote: > ...The sum of transition scores between the characters in a string. > The transition scores are stored in a 26 x 26 matrix. I.e. the > transition A -> F would have the score soundScoreMatrix[0][5]. This is the part I'd change: # Setup: transitionScore['AF'] = soundScoreMatrix[0][5]. transitionScore = {} for i in range(26): first = chr(65+i) row = soundScoreMatrix[i] for j in range(26): transitionScore[first + chr(65+j)] = row[j] > n = 0 # the final score of the string > for i in range(len(phrase)): > try: > n += soundScoreMatrix[ord(x[i]) - 65][ord(x[i + 1]) - 65] > except IndexError: > pass def scoreit(phrase): score = 0 for i in range(len(phrase) - 1): score += transitionScore.get(phrase[i : i+2], 0) return score But if you insist on a more functional style: def scoreterse(phrase): return sum([transitionScore.get(phrase[i : i+2], 0) for i in range(len(phrase) - 1)]) which doesn't really look clearer to me. I'd be tempted to insert a line: phrase = phrase.upper() at the top of the function (scoreit or scoreterse) you use, depending, of course, on the reliability of the source of your data. -- -Scott David Daniels Scott.Daniels at Acm.Org From wweston at att.net Sat Apr 17 09:40:16 2004 From: wweston at att.net (wes weston) Date: Sat, 17 Apr 2004 13:40:16 GMT Subject: MySQLdb error for sql >64K In-Reply-To: <11vs3qm7platj$.e7an576g31z5.dlg@40tude.net> References: <11vs3qm7platj$.e7an576g31z5.dlg@40tude.net> Message-ID: <4tagc.40626$i74.996398@bgtnsc04-news.ops.worldnet.att.net> JZ wrote: > I cannot execute insert data into TEXT field if that data is bigger than > 64KB. :( > > >>>>cursor.execute("INSERT INTO table (field) VALUES(%s) WHERE id=1", myValue) > > > Traceback (most recent call last): > File "", line 1, in ? > File "C:\opt\PYTHON~1\lib\site-packages\MySQLdb\cursors.py", line 95, in > execute > return self._execute(query, args) > File "C:\opt\PYTHON~1\lib\site-packages\MySQLdb\cursors.py", line 114, in > _execute > self.errorhandler(self, exc, value) > File "C:\opt\PYTHON~1\lib\site-packages\MySQLdb\connections.py", line 33, > in defaulterrorhandler > raise errorclass, errorvalue > Warning: Rows matched: 1 Changed: 0 Warnings: 1 > > The same sql query executed using MySQLFront client works without any > problems. So, I think the problem must be with MySQLdb 0.9.2 module. > > Any suggestions? > > -- > JZ jz, A MYSQL "text" type can be 0 to 65535 bytes; a "mediumtext" type 2**8 times as big. Just a guess but maybe the failing insert checks the sizes and the 'working' one just chops off the excess. You could alter the column and try it fairly easily. wes From newsgroups at jhrothjr.com Tue Apr 13 09:40:03 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Tue, 13 Apr 2004 09:40:03 -0400 Subject: FutureWarning question References: <16mnetilcmds6.1apnyu46tbjpw.dlg@40tude.net> Message-ID: <107nretba0fikbd@news.supernews.com> "Mike" wrote in message news:16mnetilcmds6.1apnyu46tbjpw.dlg at 40tude.net... > I ran across the message below in 2.3.2 today. These are the lines of code: > > 402: if m1_hi >> 15 & 0x0001 == 1: > 403: m1_hi = m1_hi | 0xFFFF0000 > 404: if m1_lo >> 15 & 0x0001 == 1: > 405: m1_lo = m1_lo | 0xFFFF0000 > > This is the warning message: > > pwg.py:403: FutureWarning: hex/oct constants > sys.maxint will return > positive values in Python 2.4 and up > m1_hi = m1_hi | 0xFFFF0000 > pwg.py:405: FutureWarning: hex/oct constants > sys.maxint will return > positive values in Python 2.4 and up > m1_lo = m1_lo | 0xFFFF0000 > > m1_hi and m1_lo are 32 bit values read from a file. It's not clear to me > what the warning message means. The only constant is 0xffff0000; does the > message mean that the result of the OR operation won't be what I think it > is? Can anyone elucidate? It doesn't have anything to do with bitwise operations. What it has to do with is that 0xFFFF0000 is a negative number today, and it will be a positive number in 2.4 As far as I can tell, the bitwise operations are not affected. See PEP 237 (http://www.python.org/peps/pep-0237.html) for the explanation. John Roth > > Thanks, > > -- Mike -- From nico-NoSp at m-tekNico.net Fri Apr 16 12:20:28 2004 From: nico-NoSp at m-tekNico.net (Nicola Larosa) Date: Fri, 16 Apr 2004 18:20:28 +0200 Subject: List vs tuples In-Reply-To: <7illl3dxcf.fsf@enark.csis.hku.hk> References: <107bf8q8fhsmg5e@news.supernews.com> <7in05lfpqt.fsf@enark.csis.hku.hk> <107d52rib5bfrd7@news.supernews.com> <7illl3dxcf.fsf@enark.csis.hku.hk> Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 > So I don't buy that line of thoughts. Lists is something that can change, > and tuples is something that can't change Amen to that, my thoughts exactly. The fact that our beloved BDFL follows the other line of thought does not change matters, except for the unfortunate detail that tuples do not have the "index" and "count" methods that lists have, and that tuples definitely *should* have, too. - -- Nicola Larosa - nico-NoSp at m-tekNico.net Aki: "I don't know how much time I have left." Gary: "Who does?" -- "Final Fantasy: The Spirits Within" movie -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.4 (GNU/Linux) iD8DBQFAgAfKXv0hgDImBm4RAu5yAJ4ywoypS2HfvJ3BOhrPUVYia6H8IQCfd0w/ hAviP3pdzNcOKRLrJXne26c= =lKzF -----END PGP SIGNATURE----- From bkc at Murkworks.com Tue Apr 13 13:33:56 2004 From: bkc at Murkworks.com (Brad Clements) Date: Tue, 13 Apr 2004 13:33:56 -0400 Subject: embedding python References: Message-ID: "Andrea Fino" wrote in message news:f5drk1-g6j.ln1 at netzen.intra.faino.org... > Brad Clements wrote: > > You didn't mention which OS you want. > > > Yeah, you right sorry about that. It's linux in 2.4 version with the > normal glibc (i don't remenber which version). > Thanks. I used uClibc and had problems with Posix threads. This was .. about 11 months ago. If you're using standard glibc than I think you won't have any problems. From donn at u.washington.edu Fri Apr 23 18:34:57 2004 From: donn at u.washington.edu (Donn Cave) Date: Fri, 23 Apr 2004 15:34:57 -0700 Subject: Why we will use obj$func() often References: <84Uhc.22278$dZ1.5087@fed1read04> <8AWhc.23114$dZ1.11070@fed1read04> <40883BFE.B381518A@alcyone.com> <27_hc.23801$dZ1.2716@fed1read04> <40887145.789A2FE8@alcyone.com> <7cki80hj976bia36lhf9er97v073o1pqvm@4ax.com> Message-ID: In article , "Mark Hahn" wrote: > "Mel Wilson" wrote in message > news:ulXiAls/KH1K089yn at the-wire.com... > > > It can, if you spell '&' differently: > > > > def getfunc(): > > def count (n=[0]): > > n[0] += 1 > > print n[0] > > return count > > > > c = getfunc() > > c() > > c() > > c() > > True. A bit inelegant, but then so is &. > > Would you trade the "mutable integer" and "count(n=[0])" kludges for a > solution like &count ? Does anyone agree with me that a "closure variable > prefix" is more explicit and readable? > > Let's seperate the aesthetic issues of using "Perl-like" symbols from the > "closure variable prefix" functionality for a moment. I'd like feedback on > both issues, but try to keep them sep~rate. I don't think a closure variable prefix sounds very good. What you're doing there looks to me a bit like Objective CAML's ref type. "a = ref 0" is a mutable container for an immutable integer. It's just syntactic sugar for a mutable record; the sugar is the assignment a := 1, and then there's some special dereference notation -- a := !a + 1, something like that, I forget. There could be a case for a mutable-container-of-one-item type in Python, with or without special syntax. Without the syntax, it's still mildly interesting because it expresses intent - both to the human reader, and to other software components which should not be invited to delete or add items etc. class Ref: def __init__(self, a): self.value = a def __setattr__(self, a, v): if a == 'value': self.__dict__['value'] = v else: raise AttributeError, a var = Ref(0) var.value = var.value + 1 I personally think syntactic sugar wouldn't add any real value to that, but that just seems to be one of those matters of taste, where some people like languages like Pe... oops. Donn Cave, donn at u.washingtno.edu From skip at pobox.com Wed Apr 28 07:48:07 2004 From: skip at pobox.com (Skip Montanaro) Date: Wed, 28 Apr 2004 06:48:07 -0500 Subject: Is Perl *that* good? In-Reply-To: References: <108q51j4dscn7dc@corp.supernews.com> <87fzaqmm8t.fsf@strauser.com> <38ec68a6.0404262308.50029919@posting.google.com> Message-ID: <16527.39415.518927.299648@montanaro.dyndns.org> > If only compiled regular expression objects allowed easy access to the > last match object, python regxes would become significantly more > convenient. For example, today you have to write: > > m = myregex.match(line) > if (m): > xyz = m.group('xyz') > > It would be much easier to do: > > if myregex.match(line): > xyz = myregex.lastm.group('xyz') > > Having to introduce a new variable name for a match object just > muddles the code unnecessarily in common regex usage scenarios. Sure, it's more convenient but it's not thread-safe. The old regex package used to do this. When Perl-compatible regular expressions were introduced into Python it was removed precisely because of that limitation. As Peter Hansen pointed out, if you want that behavior you can write it on a per-application basis. Skip From tjreedy at udel.edu Thu Apr 22 19:54:47 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 22 Apr 2004 19:54:47 -0400 Subject: Deleting objects - my earler post got garbled References: Message-ID: Your original post may have been garbled, but our answers were not. From tezt at email.si Thu Apr 8 12:51:21 2004 From: tezt at email.si (Mitja) Date: Thu, 8 Apr 2004 18:51:21 +0200 Subject: OT: making queues in DB Message-ID: I just posted a more theoretical question here, and since this is of more practical nature, I decided to make a new post. It doesn't have much to do with Python, it's just a thing I came across when making a CGI-driven webpage. I have a games page, on which I would like to display a list of 10 last downloaded games. Therefore, I'd need a kind of queue in the database. What is the best way to go about this? Extending each game's entry with a "timelastdownloaded"-like column is of course an option, but I don't favor it too much. From theller at python.net Fri Apr 30 15:10:33 2004 From: theller at python.net (Thomas Heller) Date: Fri, 30 Apr 2004 21:10:33 +0200 Subject: uuid generator References: Message-ID: Piet van Oostrum writes: >>>>>> Marcello Pietrobon (MP) wrote: > > MP> Hello, > MP> I need to read newly generated uuid from Python > MP> but I am not sure if > MP> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/163604 > > MP> is the right code > > There's another one at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/213761 I posted ctypes code which wraps libuuid.so on linux, a while ago. And someone else in the same thread posted a C wrapper. Thomas From claird at lairds.com Sat Apr 24 18:32:09 2004 From: claird at lairds.com (Cameron Laird) Date: Sat, 24 Apr 2004 22:32:09 -0000 Subject: command-line args References: Message-ID: <108lqn9mdimaq1a@corp.supernews.com> In article , Peter Hansen wrote: . . . >What I mean is this. > >You create globals.py ahead of time, the usual way with a text >editor. It can contain defaults if you wish, or be empty. E.g.: > >(globals.py) >logging = False >userName = None >timeout = 5.0 > >Then you simply import this where you are doing the command-line >argument parsing: > >import globals, getopt >opts, args = getopt.getopt(sys.argv[1:], 'at:fse:') # or whatever >for opt, val in opts: > if opt = '-t': > globals.timeout = float(val) > # etc etc > > >Then, elsewhere where you need to use the values, just do another >import. > >(some code that needs to know the timeout) > >import globals, time >time.sleep(globals.timeout) ># or whatever > > >There is no reason to create the .py file on the fly... > >(This works because after the first import of a module inside an >application, subsequent imports do *not* re-read the .py file, >but simply get a reference to the already-imported module object >from the sys.modules dictionary.) . . . You seem to have given Michael everything he needed. I don't get it, though. Why must "some code that needs to know the timeout" import globals? In what context would it not already be present? -- Cameron Laird Business: http://www.Phaseit.net From project5 at redrival.net Fri Apr 16 13:52:42 2004 From: project5 at redrival.net (Andrei) Date: Fri, 16 Apr 2004 19:52:42 +0200 Subject: Learning about dictionaries References: Message-ID: <40801d6a$0$64604$4a441750@news.euronet.nl> Thomas Philips wrote on Friday 16 April 2004 18:50: > I'm teaching myself python and in the course of playing around with > dictionaries, I tried to create the following trivial dictionary > > {1:'one', 2:'two'} > > So I entered >>>> dict(1='one',2='two') > SyntaxError: keyword can't be an expression Try doing 1 = 'one' in the interactive interpreter. Does it work? Nope. Did you expect it to work? (Hopefully not :).) So obviously it doesn't work inside a function call neither. > Out of curiosity, I tried >>>> dict(one=1,two=2) > {'two': 2, 'one': 1} Bingo :). Python has a special construct for functions which accept any numbers of keyword arguments (these are arguments which have the form of =, as opposed to non-keyword arguments which are just ). This means that you don't have to specify the parameters in advance like this: >>> def myfunc(a, b): ... pass Instead, you allow any number of parameters to be passed to the function using '**' >>> def myfunc(**kwds): ... print kwds ... # kwds is a dictionary containing all parametername-value pairs ... >>> myfunc(a='5', b=6, c=True) {'a': '5', 'c': True, 'b': 6} You can modify myfunc now very easily to behave like dict() in this particular case: >>> def myfunc(**kwds): ... return kwds ... >>> mydict = myfunc(a='5', b=6, c=True) >>> print mydict {'a': '5', 'c': True, 'b': 6} The method Wes specified for creating dictionaries is more useful and usable IMO than dict() with keyword parameters. -- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5 at jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From python-url at phaseit.net Wed Apr 28 10:34:19 2004 From: python-url at phaseit.net (John J Lee) Date: Wed, 28 Apr 2004 14:34:19 -0000 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Apr 28) Message-ID: <108vg7br1jpggf1@corp.supernews.com> QOTW: "The site that I worked on spent TWO MILLION U.S. DOLLARS on its web server hardware. OK, it used Java servlets that are even slower than Python, but you have to understand that there's a point after which you can no longer pretend that hardware is free." -- Paul Rubin "Monte Carlo sampling is no way to understand code." -- Gordon McMillan Martin v. Loewis clarifies what entities might "compete" with Python http://www.google.com/groups?selm=c4sqle%24ds%2403%241%40news.t-online.com Peter Otten determines to find the simplest way of automatically assigning instance attributes from an argument list http://groups.google.com/groups?selm=c6alei$hv4$05$1 at news.t-online.com http://groups.google.com/groups?threadm=c6alei%24hv4%2405%241%40news.t-online.com Is application-level configuration worth its own "advanced ... parser and validator"? Is working with*out* tconfpy any more sensible? Give thanks to Tim Daneliuk http://www.tundraware.com/Software/tconfpy/ A question from a Delphi user about getters and setters in Python elicits a good set of URLs on properties http://groups.google.com/groups?&threadm=407e402c%241%40newsflash.abo.fi The long-awaited SciPy 0.3 arrives http://groups.google.com/groups?&selm=mailman.880.1082583661.20120.python-list at python.org Alan Kennedy bravely works through a concrete example of management of Word-as-XML http://groups.google.com/groups?frame=left&th=fa888d67a6991cfd Python 2.4 is on its way http://python.org/peps/pep-0320.html Francois Pinard believes he improves on Guido's main() model http://groups.google.com/groups?frame=left&th=f94d0e366becbbca Michael Hudson Thinks Like a Pythonista about stacklessness, bytecodehacks, and more http://starship.python.net/crew/mwh/hacks/ Ero Carrera's pydot interface to the graphviz graph visualization library (the "nodes and edges" kind of graph) is addictive http://dkbza.org/pydot.html ======================================================================== Everything Python-related 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 marvelous 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 newsgroup 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 intelligently 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 (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donate.html Cetus collects Python hyperlinks. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://aspn.activestate.com/ASPN/Cookbook/Python Among several Python-oriented RSS/RDF feeds available are http://www.python.org/channews.rdf http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi http://python.de/backend.php For more, see http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all 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 peter at engcorp.com Wed Apr 14 09:48:07 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 14 Apr 2004 09:48:07 -0400 Subject: Pygame In-Reply-To: References: Message-ID: Alexander R?dseth wrote: > Why isn't Pygame a part of Python? What do you think should be the criteria for deciding whether something "is part of Python" or isn't? Keep in mind that your guidelines should be applied somewhat consistently to all packages that might be possibly be included. And keep in mind that no one wants Python to be a 150MB download... -Peter From dwelch91 at comcast.net Fri Apr 9 13:07:05 2004 From: dwelch91 at comcast.net (djw) Date: Fri, 09 Apr 2004 17:07:05 GMT Subject: module not callable - why not? In-Reply-To: References: Message-ID: Diez B. Roggisch wrote: > Hi, > > I just thought about creating a module for quaternions (as an personal > exercise, so I'm not after pointers to classlibs here). > > Now usually I'd create a file called "quaternion.py", define my quaternion > class in there and then import and create an instance like this: > > import quaternion > > q = quaternion.quaternion() > > Thats a lot to type. doing a > > from quaternion import quaternion > > would solve that - but AFAIK thats considered bad for some reasons. I think what people consider dangerous is 'from import *'. The form you give here is OK, as far as I know. > > Now I thought about defining a __call__ operator at module level to allow > this: > > import quaternion > > q = quaternion() > > > where the call looks like this: > > def __call__(*a, *kw): > return quaternion() > > But that doesn't work. > > Now my question is: Is there a way to make a module callable that way? And > wouldn't it make sense to allow the implementation of a call operator on > module level? I know this has been discussed before (using __main__() instead). Try googling for some discussions. -Don From harry.g.george at boeing.com Thu Apr 1 11:54:58 2004 From: harry.g.george at boeing.com (Harry George) Date: Thu, 1 Apr 2004 16:54:58 GMT Subject: ftpmirror.py in reverse? Message-ID: I maintain a website on a local machine, and want to maintain a clone of it on a www-visible remote machine via ftp. I.e., local to remote. Going remote to local, ftpmirror.py would (I understand) do the job. Is there some tool available (or even a parameter for ftpmirror.py) which can do local-->remote? -- harry.g.george at boeing.com 6-6M21 BCA CompArch Design Engineering Phone: (425) 342-0007 From thefirstofnovember at yahoo.com Thu Apr 22 14:50:32 2004 From: thefirstofnovember at yahoo.com (Kim) Date: 22 Apr 2004 11:50:32 -0700 Subject: Getting output from embedded python program References: <2aa196bb.0404190554.74631058@posting.google.com> <4084B179.6020807@magma-da.com> Message-ID: <2aa196bb.0404221050.38f806@posting.google.com> Hi Rich, You post is extremely useful. However when I tried to run the expression in My Module's context, instead of __main__ module. It always retunns NULL. How can I do that? I tried PyRun_String().. but didn't work. i don't really understand global and local arguments in PyRun_String(), token is set to 0? THanks very much ! Kim > ... > PyObject* evalModule; > PyObject* evalDict; > PyObject* evalVal; > char* retString; > > PyRun_SimpleString( "result = 'foo' + 'bar'" ) > > evalModule = PyImport_AddModule( (char*)"__main__" ); > evalDict = PyModule_GetDict( evalModule ); > evalVal = PyDict_GetItemString( evalDict, "result" ); > > if( evalVal == NULL ) { > PyErr_Print(); > exit( 1 ); > > } else { > /* > * PyString_AsString returns char* repr of PyObject, which should > * not be modified in any way...this should probably be copied for > * safety > */ > retString = PyString_AsString( evalVal ); > } > ... > > In this case, you need to know that the expression will evaluate to > a string result in order to call PyString_AsString(). If you don't know > this, you will have to check the type of the PyObject first. From deetsNOSPAM at web.de Thu Apr 29 09:01:38 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Thu, 29 Apr 2004 15:01:38 +0200 Subject: How to find the length of an iterator? References: <1a6oinf1xl5ui$.dlg@thorstenkampe.de> Message-ID: Thorsten Kampe wrote: > What is the best way to find out the length of an iterator? len() > doesn't work. In the above code snippet[1] I am only interested in the > index (= length of the iterator), so I'm using len(list(iterator))... > > Anything better? Its the nature of an iterator that it doesn't support anything beyond access to the current item and signaling when its finished. So if you need the length, try to get a hold on the underlying connection. -- Regards, Diez B. Roggisch From tor.iver.wilhelmsen at broadpark.no Sat Apr 24 15:26:54 2004 From: tor.iver.wilhelmsen at broadpark.no (Tor Iver Wilhelmsen) Date: 24 Apr 2004 21:26:54 +0200 Subject: 3D Graphics Engine References: <8089854e.0404130639.3eb0db62@posting.google.com> Message-ID: michael at foord.net (Fuzzyman) writes: > Platform for development (!) is win32 - so I would like an engine with > precompiled binaries and a documented python binding available. A > freeware object modeller IRRLicht has a Python binding, you could try that. IRRLicht: http://irrlicht.sourceforge.net/downloads.html Venom: http://stenhard.net/download.php?list.6 From http Wed Apr 14 06:25:27 2004 From: http (Paul Rubin) Date: 14 Apr 2004 03:25:27 -0700 Subject: spherical coordinates References: <20040414111334.34b5d225@pistache.sara.nl> Message-ID: <7x1xmqua94.fsf@ruckus.brouhaha.com> Peter Maas writes: > r = sqrt(x**2 + y**2) > phi = atan(y/x) Better use phi=atan2(y,x) in case x=0. Similarly for the other atan calls. From harry.g.george at boeing.com Tue Apr 27 09:36:46 2004 From: harry.g.george at boeing.com (Harry George) Date: Tue, 27 Apr 2004 13:36:46 GMT Subject: python under subversion (svn) Message-ID: I'm experimenting with svn. What is the best way to set up the original project, anticipating "importing" to a truck-and-branch world? When I start I have: myproject/ doc/ mypackage/ stable.py changing.py test/ go_test To do branches, I think I'm supposed to get to end up with: myproject/ trunk/ doc/ mypackage/ stable.py test/ go_test branches/ branch1/ mypackage/ changing.py test/ go_test But a simple "import" of the starting project doesn't get me to the endpoint, and the "go_test" scripts have to be tweaked to point to the right PYTHONPATH's to pickup both stable and changing modules. Am I correctly understanding the problem? Are there clean solutions? Should I be totally replicating the whole project under trunk and each branch, instead of trying to keep some items on the trunk? -- harry.g.george at boeing.com 6-6M21 BCA CompArch Design Engineering Phone: (425) 342-0007 From kfast at poczta.onet.pl Wed Apr 14 17:04:36 2004 From: kfast at poczta.onet.pl (Jakub Fast) Date: Wed, 14 Apr 2004 23:04:36 +0200 Subject: Pygame In-Reply-To: References: Message-ID: <407DA764.9080806@poczta.onet.pl> > > the lgpl license _is_ commercial-friendly. > AFAIK, you're required to provide the ability to re-link the application with newer version of the lgpl'd library. this involoves the obligation to at least provide the source code of the library -- which doesn't seem like something you'd always want to expose your end users too. note that many projects specifically modify the lgpl for it to be what i consider commercial-friendly -- vide wxwidgets, for example. kuba From fumanchu at amor.org Thu Apr 8 11:34:03 2004 From: fumanchu at amor.org (Robert Brewer) Date: Thu, 8 Apr 2004 08:34:03 -0700 Subject: getattr() in default namespace. Message-ID: SimonVC wrote: > How do you use getattr() to get a refernce to a function defined in > the default namespace.. If you must use getattr, and you're doing this in a module, try: import sys def b(): pass print getattr(sys.modules[__name__], 'b') FuManChu From theller at python.net Wed Apr 14 09:22:27 2004 From: theller at python.net (Thomas Heller) Date: Wed, 14 Apr 2004 15:22:27 +0200 Subject: Unable to create com object - need help References: <2D89F6C4A80FA547BF5D5B8FDDD04523060C63@exchange.adrembi.com> Message-ID: "Roman Yakovenko" writes: > I tried your module. It seems that you generate code right :-) > but IEnumUnknown doesn't defined in any file. There is still the problem that sometimes the order of the definitions is wrong. You have to move the definition of IEnumUnknown *before* the definition of IDiaTable (where IEnumUnknown is used). A patch I just cooked up myself would be to replace these lines: interfaces.sort(self.depends) for itf in interfaces: print >> ofi print >> ofi, itf.declaration() with these: done = ["IUnknown", "IDispatch", "dispinterface"] while interfaces: interfaces = [i for i in interfaces if i.name not in done] for itf in interfaces: for b in itf._uses: if b not in done: break else: print >> ofi print >> ofi, itf.declaration() done.append(itf.name) This is near line 740 in readtlb.py. Thomas From deetsNOSPAM at web.de Mon Apr 26 09:38:04 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Mon, 26 Apr 2004 15:38:04 +0200 Subject: Regular Expressions References: Message-ID: > A - TYPE1: any_text
> B - TYPE2: any_text_2
> C - TYPE2: any_text_3
> w - any_text_15
>
> html code > > > I need to have only following data: > (B, any_text_2) > (C, any_text_3) > that is, these data TYPE2 in which. you should utilize the htmlparser class to extract the text first. Then this regular expression might help: r"(.) TYPE. : (.*)" -- Regards, Diez B. Roggisch From jepler at unpythonic.net Fri Apr 23 07:30:12 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Fri, 23 Apr 2004 06:30:12 -0500 Subject: Why we will use obj$func() often In-Reply-To: References: Message-ID: <20040423113011.GA2150@unpythonic.net> On Fri, Apr 23, 2004 at 01:24:42AM -0700, Mark Hahn wrote: > My biggest problem right now is stupid aesthetics. I have to decide where > to place Prothon on the continuum between lisp and perl. When I crossed the > line and added $ for self people screamed bloody murder that it looked like > Perl. Before when I had a period for self they thought it looked great. I > can't believe how much they care about something so silly. I didn't know about your ^ syntax either. In Python, there is one way[*] to get an attribute on an object. This works whether it's a data attribute on the instance, a data attribute on the class or a superclass, an instancemethod, classmethod, or staticmethod: obj.attr Having all of obj.attr, obj$attr and obj^attr *does* reek of perl's $var, @var, %var distinction (which I have never bothered to understand). To me it looks like you've eliminated/combined one thing (instances + classes become objects) but as a result you've had to invent two new kinds of complication. What may have made people jump to a conclusion about $ is that you wrote something like "$ will remind users of $elf". This reeks of Perl's bad explanations of why all their internal variables with punctuation names are really mnemonic for something: $/ The input record separator, newline by default. (Mnemonic: / delimits line boundaries when quoting poetry.) $. Current line number for the last filehandle accessed. (Mnemonic: many programs use "." to mean the current line number.) Yeah, right. Jeff [*] Yes, I know full well there are other ways you can do it getattr(obj, "attr"), obj.__dict__['attr'], etc, etc. My point is, then, that everything can be done with a single "dotted name" syntax. From nf2 at scheinwelt.at Mon Apr 19 05:18:08 2004 From: nf2 at scheinwelt.at (n.o.) Date: Mon, 19 Apr 2004 11:18:08 +0200 Subject: problem with commands.getstatusoutput/os.popen and pygtk Message-ID: Hi! Can you please help me with the following problem? My application calls (rval, outp) = commands.getstatusoutput("...") inside a pygtk timer. when i start the application from a terminal window, everything works. when i use GNOME/"Run application" or a desktop launcher, i get errorcode 35584 for rval. i tried the thing with os.popen also - same problem. thanks in advance, norbert From robin at SPAMREMOVEjessikat.fsnet.co.uk Tue Apr 20 17:32:14 2004 From: robin at SPAMREMOVEjessikat.fsnet.co.uk (Robin Becker) Date: Tue, 20 Apr 2004 22:32:14 +0100 Subject: here document as script and read from stdin Message-ID: <408596DE.10004@jessikat.fsnet.co.uk> Is it possible to use python with a shell HERE document as the script and read the standard input? In other words make python usable as a filter with a side input? It doesn't seem to be obvous unless I can somehow use the -c option. -- Robin Becker From alan_salmoni at yahoo.com Sun Apr 4 18:45:35 2004 From: alan_salmoni at yahoo.com (Alan James Salmoni) Date: 4 Apr 2004 15:45:35 -0700 Subject: ANNOUNCE: 'goto' for Python References: Message-ID: Wow! Thanks very much! Just what I've been looking for. Umm, would it be possible to discuss a few other possibilities, like in-line assembly language, GOSUB's, PEEK's, POKE's and file operations only possible through direct access to the hard disk? I reckon with these in place, we could out-obfuscate any Perl code in no time! ;^) Oh damn, it's April 4th - jokes on me... =:/ Alan James Salmoni Richie Hindle wrote in message news:... > Entrian Solutions is pleased to announce version 1.0 of the 'goto' module. > > This adds the 'goto' and 'comefrom' keywords to Python 2.3, adding > flexibility to Python's control flow mechanisms and allowing Python > programmers to use many common control flow idioms that were previously > denied to them. > > 'goto' example: breaking out from a deeply nested loop: > > from goto import goto, label > for i in range(1, 10): > for j in range(1, 20): > for k in range(1, 30): > print i, j, k > if k == 3: > goto .end > label .end > print "Finished\n" > > > 'comefrom' example: letting cleanup code take control after an error. > > from goto import comefrom, label > def bigFunction(): > setUp() > if not doFirstTask(): > label .failed > if not doSecondTask(): > label .failed > if not doThirdTask(): > label .failed > > comefrom .failed > cleanUp() > > Computed 'goto's are also supported - see the documentation for details. > Computed 'comefrom's are planned for a future release. > > Documentation and further examples: > http://entrian.com/goto/index.html > > Downloads: > http://entrian.com/goto/download.html > > The 'goto' module is released under the Python Software Foundation > license, and requires Python 2.3 or later. > > Please note that this version does not work at the interactive Python > prompt - code importing 'goto' must be in a .py file. This restriction > will hopefully be lifted in a future release. From cleso at hotmail.com Tue Apr 13 22:47:17 2004 From: cleso at hotmail.com (Dave) Date: Tue, 13 Apr 2004 19:47:17 -0700 Subject: Looking for Python Definition References: Message-ID: Andres, Yes, my PC is a Compaq. Thank you for the information. -- Dave "Andres Rosado-Sepulveda" wrote in message news:c5i35l$2274t$1 at ID-203388.news.uni-berlin.de... > Dave wrote: > > Greetings! > > Python22 is installed on my WINXP Home PC. > > I have no idea what is does, or why it is installed. > > I am not a programmer and do not know what purpose this program provides to > > me. > > > > Any and all information and suggestions are welcome. > > Is your computer an HP or Compaq model? HP/Compaq's utilities are > written in Python. > > -- > Andres Rosado > Email: andresr at despammed.com > Homepage: http://andres980.tripod.com/ > > A man wrapped up in himself is a very small bundle. > -- Benjamin Franklin From ml at dynkin.com Wed Apr 21 23:56:54 2004 From: ml at dynkin.com (George Yoshida) Date: Thu, 22 Apr 2004 12:56:54 +0900 Subject: zip 2 sequences into 1 In-Reply-To: References: Message-ID: Neal Becker wrote: > What's an easy/efficient way to zip together 2 (or more) sequences into a > single sequence? > How about itertools.chain(*zip(seq1, seq2, seq3, ...)) For example: >>> a = 'abcde' >>> b = range(5) >>> c = 'python' >>> from itertools import chain >>> list(chain(*zip(a,b,c))) ['a', 0, 'p', 'b', 1, 'y', 'c', 2, 't', 'd', 3, 'h', 'e', 4, 'o'] -- George From adalke at mindspring.com Sun Apr 11 18:55:02 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Sun, 11 Apr 2004 22:55:02 GMT Subject: Compact Python library for math statistics References: <3064b51d.0404061038.4d69fd89@posting.google.com> <5d83790c.0404090024.5cefb2ea@posting.google.com> <3064b51d.0404091308.472dfb78@posting.google.com> <3064b51d.0404111025.646d4223@posting.google.com> Message-ID: > My original code, the code with range replaced by xrange, and the code > with the further replacement of "float(i)" with "i" take 22.0, 20.5, > and 14.4 seconds. So it looks like removing unnecessary casts can save > substantial time. Thanks. The following should be even faster def sum_sqrt(n): sum = 0.0 for i in xrange(1, n): sum = sum + i ** 0.5 return sum print sum_sqrt(10000000 + 1) Local variables have a fast lookup while module variables (that is, ones outside a function) have to look up the variable in the module dictionary. Your code (in module scope) takes 24.5 seconds on my box while my function version takes 17.5 seconds. Andrew dalke at dalkescientific.com From ae Sun Apr 11 20:54:18 2004 From: ae (A Evans) Date: Sun, 11 Apr 2004 17:54:18 -0700 Subject: Python OS References: <107j4eu6ffn2c68@corp.supernews.com> Message-ID: <107jq68ao58o7ff@corp.supernews.com> Hey thanks everyone for the replies I guess it would be quite the task to embark on I would like to do it and I think I will over the next couple of years as my skills improve and I start saving some cash to get it off the ground and to get other programmers and planners involved. Cool the Open Source operating system of the future is going to happen I am going to make it happen Its a long road from here Cheers Andrew From mark at prothon.org Thu Apr 29 01:41:49 2004 From: mark at prothon.org (Mark Hahn) Date: Wed, 28 Apr 2004 22:41:49 -0700 Subject: Why we will use obj$func() often References: <84Uhc.22278$dZ1.5087@fed1read04> <8AWhc.23114$dZ1.11070@fed1read04> <40883BFE.B381518A@alcyone.com> <27_hc.23801$dZ1.2716@fed1read04> <40887145.789A2FE8@alcyone.com> <7cki80hj976bia36lhf9er97v073o1pqvm@4ax.com> <5vJjc.13116$Qy.1954@fed1read04> <52Ujc.16275$Qy.3111@fed1read04> Message-ID: Greg Ewing wrote: > Mark Hahn wrote: >> It turns out that Greg and I were mistaken. The &var syntax can >> easily handle unlimited nested scopes and not even slow up my >> one-pass compiler. > > It does incur the expense of a run-time lookup for > intermediate-scoped variables, however. Prototype-based systems incur a prototype chain lookup expense on every single attribute lookup. This is a disadvantage compared to class-based systems. See the Lieberman paper linked near the top of the Prothon home page. That same paper also discusses a cache method that effectively eliminates that expense. That same expense and cache fix will apply without change to the closure lookup. So the bottom line is there will effectively be no expense. We won't be working on performance in Prothon until July or August though, so you'll have to take my word on that until then. From http Mon Apr 19 21:40:41 2004 From: http (Paul Rubin) Date: 19 Apr 2004 18:40:41 -0700 Subject: block ciphers References: <7L_gc.53134$Gn6.49963@newssvr25.news.prodigy.com> Message-ID: <7x3c6zqvdy.fsf@ruckus.brouhaha.com> Trevor Perrin writes: > Q: How about adding block ciphers to Python 2.4? > > PEP 272 defines an API, and there's an excellent library that > implements it [1]. It would be very little work to copy the AES and > DES3 modules into stdlib (perhaps in a 'ciphers' package). PEP 272 has an API for both block and stream ciphers, and the block cipher API is kind of cumbersome. I did some work a while back on defining a new block cipher API and posted some about it back then. I've been meaning to get that code out of mothballs and propose a new PEP. A sample implementation is at http://www.nightsong.com/phr/crypto/blockcipher.tgz but there are some things about it that I want to change. I recently used it to write a pure-Python script that decrypts PGP files, if that's of any interest too. > So is this totally out of the question? Or would it be worth > pursuing, through a PEP, or patch, or discussion on python-dev? I'm not sure exactly what you're asking. From maschio_77 at hotmail.com Sun Apr 4 17:00:28 2004 From: maschio_77 at hotmail.com (Federico) Date: Sun, 04 Apr 2004 23:00:28 +0200 Subject: where download mcmillan installer Message-ID: Hi, Where can I download the mcmillan installer utility? http://www.mcmillan-inc.com/ doesn't exist anymore? Thanks From tjreedy at udel.edu Fri Apr 23 13:39:06 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 23 Apr 2004 13:39:06 -0400 Subject: AOP use cases References: <84fc4588.0404140106.3fa0c55@posting.google.com><0pydnSB4WYuieuLdRVn-hQ@powergate.ca> Message-ID: "Jacek Generowicz" wrote in message news:tyfvfjrp2at.fsf at lxplus026.cern.ch... > "Terry Reedy" writes: > > > The funny thing about this example is that its success critically depends > > on fib *not* being 'optimized' by having the recursive calls being either > > compiled as or replaced by (as with Hettinger's recent proposal) efficient > > local calls. To be more precise, the example depends on dynamic lookup not being disabled *before* the wrapping. But I believe *after* would be ok. > Please remember that the _point_ of the example is to show what > separation of concerns is, in the context of the claim that C moving > IO from language to library constitutes separation of concerns. That may have been *your* point in writing it, but given that I never seriously considered the claim you refuted as being worth much attention, I had a different point in reading your example ;-) > Picking nits in the implementation details is completely missing the point. Given that I expect to someday make use of Hettinger's recipe, it is not nitpicking for me to notice the interaction between the two patterns and how to mix them and get the intended result. Terry J. Reedy From dmq at gain.com Wed Apr 28 14:35:32 2004 From: dmq at gain.com (David MacQuigg) Date: Wed, 28 Apr 2004 11:35:32 -0700 Subject: Ideas for Python 3 References: Message-ID: On Wed, 28 Apr 2004 18:33:24 +1200, Greg Ewing wrote: >David MacQuigg wrote: >> Explanation of Simplified Instance Variables >> -------------------------------------------- >> """ Some of the variables inside the functions in a prototype have a >> leading dot. This is to distinguish local variables in the function >> from "instance variables". When a function is called from an instance >> ( cat1.talk() ) a special global variable __self__ is automatically >> assigned to that instance ( __self__ = cat1 ) Then when the function >> needs an instance variable ( .sound ) it uses __self__ just as if you >> had typed it in front of the dot ( __self__.sound ) The leading dot >> is just an abbreviation to avoid typing __self__ everywhere. """ > >Explanation of Python Instance Variables, Omitting Unnecessary Words >-------------------------------------------------------------------- > >When a function is called from an instance (e.g. cat1.talk()), >the instance is passed in as an extra parameter at the beginning >of the parameter list, conventionally named 'self'. This allows >you to refer to attributes of the instance as 'self.attrname' >(e.g. self.sound). > >========== END ============== > >(I've left out mention of the difference between classes and >instances, as you did in your explanation even though it's just >as important in your scheme. Including it still wouldn't make >my explanation significantly longer than yours.) This seems much too brief for my taste. I think some of the "unnecessary words" will be very helpful for students. I need other opinions on this. The distinction between calling from classes and calling from instances is not necessary with the new syntax, because we don't have the problem of needing a different calling sequence. i.e. the student doesn't have to remember cat1.talk() in one case and Mammal.talk(cat1) in another. With the new syntax, the distinction becomes important when we get to bound and unbound functions (same as in Python), but that is later in the chapter, not part of the introductory explanation. I've started a new thread "Explanation of Instance Variables in Python" so we can explore this topic more fully. Thanks for your help. -- Dave From Mike at DeleteThis.Geary.com Mon Apr 12 13:03:43 2004 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Mon, 12 Apr 2004 10:03:43 -0700 Subject: Best IDE? References: Message-ID: <107livg4brum9af@corp.supernews.com> > What's the best MSwindows editor for python? I'm currently > using PythonWin (ActiveState) at the moment, its a bit buggy - > but not too bad. I mean, its got autocomplete & tips & help & > autoindentaion (not always good tho). > > Thing is, I'm sure there is something better. Is there? > > (is there a VS.NET addin?) Someone mentioned ActiveState's Visual Python addin for VS.NET. ActiveState also has Komodo which I like quite a lot. I tried both Visual Python and Komodo and found that I liked them about equally well. I ended up buying Komodo because I can use it on Linux as well as Windows, and it supports other languages in addition to Python. For a VS.NET user like me, the nice thing about Komodo is that it feels just like VS.NET. I can switch back and forth between VS.NET and Komodo without having to switch mental gears. I tried many other editors, including most of the ones mentioned in this thread, and despite their good points I couldn't get comfortable with them. One thing in particular that I found in many editors was poor typeface support. For example, JEdit is a very powerful editor, but it doesn't support ClearType! It has its own font anti-aliasing which is fairly pitiful by comparison. I find that ClearType makes such a huge difference in eye comfort for me that I won't consider an editor that doesn't support it. (I use a ThinkPad with a high-density 1600 x 1200 15" display, and the Lucida Console typeface with ClearType looks great on this display.) Of course, YMMV, so the best thing is to download and try out a number of editors and IDEs and see what fits your needs and style the best. -Mike From claird at lairds.com Sat Apr 3 18:43:28 2004 From: claird at lairds.com (Cameron Laird) Date: Sat, 03 Apr 2004 23:43:28 -0000 Subject: emergent/swarm/evolutionary systems etc References: Message-ID: <106uj10g611v0f5@corp.supernews.com> In article , Peter MacKenzie wrote: >Spreadsheets do seem to be an attractive option, but the benefits are not >without their detractors: > >+Easy to work with >+Require no/limited skill acquisition >+Flexible > >-Cells can only hold single items of data (which can be worked around by >using arrays of cells to hold multiple attributes for each location) >-Require no/limited skill acquisition (being familiar and honest with my own >psychological composition, I know that the only way I'm likely to develop a >fair degree of programming competence is if there's a driving pressure to do >so. It's something I'd like to learn, and this gives me the excuse/leverage >to do so.) > >Unknowns: Time series graphical output would be necessary, even if it's >very primitive. Do you know if the spreadsheet could be set up in such a >way that cells would change colour depending on their values, or if the >graph making facilities would be able to create reasonable representations >of said values so that a series of graphs would be capable of showing up >phenomena with fluidic (wavelike, turbulent, etc) characteristics? > >I'm afraid the temptation to take the hard route my prove too great >(psychological paradoxes: I always feel good about feeling so terrible about >these things after I've passed the point of no return in the undertaking, >and the enormity of the task at hand sinks in - it's a whole adrenalin >thing), but I'd still like to make a comprehensive assessment of my options >before I commit to anything. > > Spreadsheets can do anything. Python can do anything. To first approximation, at least. They both have developed enough to have far more capabilities than you'll exhaust in a couple of months. The key questions are: which better suit your psychology? Which will get in the way less? Which support "libraries" of related material in your "domain" (geography)? You're not experienced enough with software yet to judge the first of these questions well. Whatever first impres- sions Python or Excel make on you are likely to dwindle to insignicance after a few more weeks of software exploration. One of the dimensions your comparison of the two approaches doesn't cover is robustness of expression and abstraction. You aren't in a position to appreciate this yet, but Python beats spreadsheets all to pieces in these regards. Crudely, you can hand a Python solution to someone else, two years from now, and he'll understand what you've done, and how to modify or validate or ... it. I argue strongly that that is *not* true for spreadsheet solutions. I therefore regard spreadsheet approaches, except in specialized circumstances, as anti-scientific, because they don't promote the free exchange of ideas. There's a rich literature on simulation done with computers, some of it specifically by those coming from geography. It would be no particular problem to dissipate the entire two months just reading up on what you plan to do. You need to figure out a very circumscribed goal, and ask experts on what you should do to achieve it. Reading through *Thinking ... with Python* certainly can be part of that path. -- Cameron Laird Business: http://www.Phaseit.net From python at holdenweb.com Tue Apr 13 10:33:55 2004 From: python at holdenweb.com (Steve Holden) Date: Tue, 13 Apr 2004 10:33:55 -0400 Subject: Simple discussion of python cgi approaches? In-Reply-To: <153fa67.0404121727.45b23c30@posting.google.com> References: <153fa67.0404121727.45b23c30@posting.google.com> Message-ID: Kylotan wrote: > [Apologies if anyone sees this twice - at first I attempted to post it > via my ISP's news server, but my ISP is notorious for poor news > handling and I don't see it on Google Groups as having got through > yet.] > > I've been writing a CGI app with Python 2.3 and Apache. It's ok, but a > bit slow, and I assume a significant part of this is the process > start-up time, among other things. So I'm interested in alternatives > or optimisations. The problem is, there doesn't seem to be the kind of > information out there that I want. There seem to be plenty of places > that throw a list of URLs at you (eg. > http://www.python.org/cgi-bin/moinmoin/WebProgramming, > http://phaseit.net/claird/comp.lang.python/web_python.html), and a few > sites that will give the absolute basics of CGI programming itself > (which I don't need). > There are many differeing opinions on this subject, so maybe you'll just have to accept that c.l.py responses reflect the prejudices of their authors. They will at least usually be better-informed than random web sites, one might hope. > I'm particularly confused by a few people advocating things like > Xitami + LRWP for being very simple, yet it can't possibly be simpler > than just dropping a cgi script into a directory, as I do with Apache, > and the docs on LRWP > (http://www.imatix.com/html/xitami/index12.htm#TOC114) make it look > like I'd have to do significant rewriting of the scripts. It describes > itself as being like FastCGI which, if true, doesn't exactly endear > FastCGI to me either. > Well, you said you are looking for "alternatives or optimaizations", so it would appear that you feel you are approaching the limits of your simple approach. It's a very unsual solution that will be simpler, faster and cheaper than the "obvious" one, though such solutions aren't unheard of, even in the web world. > All I want is a short description on the technologies that very > closely resemble standard CGI, what they have to offer me, and what > sort of alterations I would have to make to my installation or code in > order to use these. Does such a comparison exist already? If not, is > anybody able to comment on their own experiences with Python CGI apps? > Well, let me briefly summaries the advantages of Xitami/LRWP and mod_python, two approaches with which I am familiar, as compared with good 'ole vanilla CGI. Both of these systems have the advantage that once your web functionality is stable (i.e. the programs aren't changing each time you want the run) you avoid the overhead of reloading both the interpreter and the source code of your page generators (CGI scripts) for each page. mod_python effectively works by integrating the interpreter into Apache in such a way that each directory can, if necessary, have a separate interpreter instance (to avoid namespace clashes between different applications). Modules are loaded on-demand, and stay resident in the Apache process unless changed. Sometimes there are problems if an indirectly-imported module changes, since mod_python only checks those it imports itself. The intergration is very tight, and you can write Apache handlers of all kinds in Python. I have experimented myself with writing request handlers, with results briefly reported at PyCON this year. It's a good general-purpose approach for uni-processor solutions. Xitami is slightly different: the server is deliberately written as a lightweight asynchronous request handler which is capable of queueing requests until a service routine becomes available. The LRWP linkage isn't actually as complicated as it might seem, and the only major difference is that a service process must register with the server to handle a class of URLs before it receives requests. This gives you two immediate benefits: firstly, since network sockets are used to communicate between the web server and the service process, the web server can act as a conduit to external functionality very easily - it's trivial to build a remote LRWP, since the only difference between a local and a remote LRWP is the fact that the remote one will use an external IP address for the web server rather than "localhost". Second, since the web server is perfectly happy to accept multiple registrations for a given class of URLs, and since each registration can come from a different host, the asynchronous nature of the Xitami system allows you to achieve potentially great scalability. I described this approach in "Python Web Programming", since it seemed to me to offer the easiest way to build web-based Python applications which could potentially scale to hundreds of processors. The really nice part is that you can add more LRWPs to any URL class that needs more power, dynamically and without trauma. I even built a system on Windows that had a URL to start up LRWPs on demand, and to shut them down, under client control. It's very flexible. Clearly anything that has performance benefits over CGI is likely to be a little more difficult to get running but believe me, the extra effort isn't that great when you consider the rewards. HTH regards Steve From pinard at iro.umontreal.ca Thu Apr 15 17:32:30 2004 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Thu, 15 Apr 2004 17:32:30 -0400 Subject: CamelCase versus wide_names (Prothon) In-Reply-To: References: Message-ID: <20040415213230.GA26163@alcyon.progiciels-bpi.ca> [Mark Hahn] > 1) CamelCase is more elegant, modern, more readable, and more efficient in > character usage. > 2) Wide_names is cleaner, more readable, compatible with C, which is the > standard module language for Python and Prothon. Wide_names is also the > Python standard. Both cannot be "more readable" simultaneously! :-) For Python, I think legibility should be the premium concern. I wish Prothon shares that priority. Efficiency on character usage may not be that much: there was once an habit of removing all vowels, and a few consonants at random, from variable names, to spare typing; this resulted in poor legibility and harder maintenance. Compatibility with C should not be a concern either. Whatever a capital or an underscore causes the highest strain on the typist may not be more important than legibility either: editors rather than languages should address editing difficulties. The problem here is that legibility is not defined the same way by all people. People develop habits, find more legible what they saw a lot, and are likely to fight to protect what they learn to find good. (This is like smoking: children gag the first time they try it, then they get used to it, but the habit does not make smoking a good thing, even if they much like it.) My own opinion is that identifiers are better clean than elegant, because legibility lies on the clean side. This is why I prefer wide_names. But maybe wide_names are my drug and I'm wrong. I do know that others prefer CamelCase. I do not fully understand their preference, they do not really understand mine! :-) Given full power and choice, what I would prefer is that identifiers be allowed to contain spaces -- would they have to be unbreakable spaces. That would be the most legible avenue, especially given that my editors and enscripters would then bold or colour Python/Prothon keywords, making it clear the extent of each identifier. Take this very message, save it in two files, then edit the first copy to replace all spaces within a sentence with underlines, and edit the second copy to replace all spaces within a sentence with the empty string, but capitalising the next character. My guess, which some might challenge, is that there will almost be a concensus that the first copy is easier to decipher. Legibility should be the overwhelming concern. -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From drs at remove-to-send-mail-ecpsoftware.com Sun Apr 11 12:55:15 2004 From: drs at remove-to-send-mail-ecpsoftware.com (drs) Date: Sun, 11 Apr 2004 16:55:15 GMT Subject: Best IDE? References: Message-ID: "Stevie_mac" wrote in message news:c5bg1k$25vq$1 at news.wplus.net... > (is there a VS.NET addin?) http://www.activestate.com/Products/Visual_Python/ From mwh at python.net Wed Apr 7 14:22:02 2004 From: mwh at python.net (Michael Hudson) Date: Wed, 7 Apr 2004 18:22:02 GMT Subject: getting from code object to class/function References: Message-ID: Skip Montanaro writes: > The trace module allows you to print all functions which were called at > least once during a program's run. I just checked in a change to also track > caller/callee relationships and display then at program exit. > > Both types of output suffer from the fact that all the trace function gets > is the current frame. From there it can find the code object and then the > source filename and function name. There is, however, no direct way back > from the code object to (for example) the class and method which "own" that > object. I didn't see anything obvious in the inspect module that would > allow me to worm around this problem. gc.get_referrers? It's impossible in general, of course, because you can using the 'new' module construct multiple functions that refer to the same code object. Cheers, mwh -- [1] If you're lost in the woods, just bury some fibre in the ground carrying data. Fairly soon a JCB will be along to cut it for you - follow the JCB back to civilsation/hitch a lift. -- Simon Burr, cam.misc From perky at i18n.org Sun Apr 4 01:41:35 2004 From: perky at i18n.org (Hye-Shik Chang) Date: Sun, 4 Apr 2004 15:41:35 +0900 Subject: Python is faster than C In-Reply-To: <5d83790c.0404032144.482787bd@posting.google.com> References: <406F0907.96F37EA1@tunes.org> <5d83790c.0404032144.482787bd@posting.google.com> Message-ID: <20040404064135.GA59716@i18n.org> On Sat, Apr 03, 2004 at 09:44:38PM -0800, Raymond Hettinger wrote: > [Armin Rigo] > > >>> enumerate([6,7,8,9]) # uh ? > > > > This got me thinking about how much I would like to see the contents > of an iterator at the interactive prompt. > > I wonder if the read-eval-print loop could be trained to make a better > display: [snip] > > # intended result > >>> enumerate('abcdefgh') > > >>> list(_) > [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e'), (5, 'f'), (6, 'g'), > (7, 'h'), (8, 'i'), (9, 'j'), (10, 'k'), (11, 'l'), (12, 'm'), (13, > 'n')] > Yeah! I love this idea. It may make not only enumerate() but also reverse() and itertools internal objects more interactive-friendly. Hye-Shik From ykingma at accessforall.nl Mon Apr 19 13:17:02 2004 From: ykingma at accessforall.nl (Ype Kingma) Date: Mon, 19 Apr 2004 19:17:02 +0200 Subject: equivalent to Java's toString()? References: <1087t9hc5vl833b@corp.supernews.com> Message-ID: <4084098e$0$562$e4fe514c@news.xs4all.nl> Michael Geary wrote: > Gabriel Cooper wrote: >> What is the python equivalent to java's toString()? >> >> When debugging I want to be able to basically be able to do this: >> >> print MyObjectInstance >> >> or >> print str(MyObjectInstance) >> >> and have it print out formatted output along the lines of: >> >> Object properties: Red=0 Yellow=0 Blue=255 > > Define a __str__ method in your class. It works just like toString() in Java > and JavaScript: > >>>> class MyTest( object ): > ... def __str__( self ): > ... return 'My Test!' > ... >>>> test = MyTest() >>>> print test > My Test! >>>> > > Also see __repr__ for a related method. > > -Mike Closing the circle, just for info, from the java docs of jython: http://www.jython.org/docs/javadoc/org/python/core/PyObject.html#__str__() """Equivalent to the standard Python __str__ method. This method should not typically need to be overridden. The easiest way to configure the string representation of a PyObject is to override the standard Java toString method.""" Regards, Ype From nuffsaid at phreaker.net Mon Apr 26 19:23:57 2004 From: nuffsaid at phreaker.net (Nuff Said) Date: Tue, 27 Apr 2004 01:23:57 +0200 Subject: locale.CODESET / different in python shell and scripts Message-ID: When I type the following code in the interactive python shell, I get 'UTF-8'; but if I put the code into a Python script and run the script - in the same terminal on my Linux box in which I opened the python shell before -, I get 'ANSI_X3.4-1968'. How does that come? Thanks in advance for your answers! Nuff. The Code: import locale print locale.nl_langinfo(locale.CODESET) From tony at deletethis.thoward.plus.net Tue Apr 20 11:32:28 2004 From: tony at deletethis.thoward.plus.net (Tony of Judicious) Date: Tue, 20 Apr 2004 16:32:28 +0100 Subject: Rekall configure probs Message-ID: Not sure if this is right ng but i'm trying to install Rekall on Suse 9 prof During ./configure i get the msg: checking for X... configure: error: Can't find X includes. Please check your installation and add the correct paths! Any idea what it is looking for? From theller at python.net Wed Apr 14 07:57:05 2004 From: theller at python.net (Thomas Heller) Date: Wed, 14 Apr 2004 13:57:05 +0200 Subject: Unable to create com object - need help References: <2D89F6C4A80FA547BF5D5B8FDDD04523060C60@exchange.adrembi.com> Message-ID: "Roman Yakovenko" writes: > Hi. I need some help. > Here is my situation. It is a little bit difficult to explain and/or understand. > I'd like to use msdia71.dll. This dll gives you access to program database files > created during a build. I register this dll. This is pure com dll. > This dll contains 3 top classes. I'd like to create one of them - DiaSource. > This class implements IDiaDataSource interface. This fact I can see in dia2.idl. > > importlib("stdole2.tlb"); > [ > uuid(e60afbee-502d-46ae-858f-8272a09bd707), > helpstring("DiaSource Class") > ] > coclass DiaSource > { > [default] interface IDiaDataSource; > }; > > after using makepy I get > > class DiaSource(CoClassBaseClass): # A CoClass > # DiaSource Class > CLSID = IID('{E60AFBEE-502D-46AE-858F-8272A09BD707}') > coclass_sources = [ > ] > coclass_interfaces = [ > ] > If I understand right DiaSource doesn't implements IDiaDataSource interface at all. > May be this is a bug, may be I don't understand something. Clarifying this point will be great. I think this has to do with the fact that with pywin32 you cannot access arbitrary com interfaces - only interfaces that either have been wrapped in pythoncom.dll or that derive from IDispatch. The DIA interfaces all derive from IUnknown, so it seems you cannot call them. There is ongoing work in pywin32 named 'universal' or something like that, but I don't know how far it is. Another possibility is to use ctypes com layer, it has a tool somewhat similar to makepy - it's called readtlb.py, and creates python wrappers for com interfaces. ctypes.com has some samples demonstrating all this. HTH, Thomas From peter at engcorp.com Fri Apr 23 18:01:36 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 23 Apr 2004 18:01:36 -0400 Subject: Richards bench benchmark In-Reply-To: <6748553f.0404211342.7591cd8e@posting.google.com> References: <6748553f.0403291446.27fb7b93@posting.google.com> <6748553f.0403300836.744e3e22@posting.google.com> <6748553f.0403302317.4595844@posting.google.com> <6748553f.0404060802.6e0d708c@posting.google.com> <6748553f.0404211342.7591cd8e@posting.google.com> Message-ID: <40899240.7020508@engcorp.com> Duncan Lissett wrote: > Peter Hansen wrote in message news:... > > Done some interpreter implementations, so Python won't look out of place ;-) > > http://www.lissett.com/ben/bench1.htm Okay, first working version is available by going to http://www.engcorp.com/main/projects/PyBench . That's about all the time I can spare on this for now. Feel free to download, hack, improve, or ignore. If nothing else, it would be of some interest to have someone run one of the other versions on a common machine and post the results. The above page is a wiki, so feel free to add results there, expand the page, whatever... -Peter From mark at prothon.org Tue Apr 20 02:22:10 2004 From: mark at prothon.org (Mark Hahn) Date: Mon, 19 Apr 2004 23:22:10 -0700 Subject: Dollar sign ($) on foriegn keyboards? (prothon) Message-ID: We are considering switching to the dollar sign ($) for self, instead of the period ( . ) we are using now in Prothon. Ruby uses the at-sign (@) for self, but our new usage of self also includes replacing the period for some attribute references, as in obj$func() versus obj.func(), and too many programs treat that as an email address and screw it up. Also the S in the symbol $ reminds one of the S in $elf. Can people from outside the U.S. tell me if typing the dollar sign often would be a problem in writing code? Is it available and somewhat easy to type on international keyboards? From roy at panix.com Thu Apr 15 10:18:03 2004 From: roy at panix.com (Roy Smith) Date: Thu, 15 Apr 2004 10:18:03 -0400 Subject: warnings References: Message-ID: Slightly off-topic, but what's the long-term future of the warnings module? It seems the new logging module pretty much subsumes the functionality of warning. From tzot at sil-tec.gr Fri Apr 2 09:24:06 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Fri, 02 Apr 2004 17:24:06 +0300 Subject: An attempt at guessing the encoding of a (non-unicode) string Message-ID: This is a subject that comes up fairly often. Last night, I had the following idea, for which I would like feedback from you. This could be implemented as a function in codecs.py (let's call it "wild_guess"), that is based on some pre-calculated data. These pre-calculated data would be produced as follows: 1. Create a dictionary (key: encoding, value: set of valid bytes for the encoding) 1a. the sets can be constructed by trial and error: def valid_bytes(encoding): result= set() for byte in xrange(256): char= chr(byte) try: char.decode(encoding) except UnicodeDecodeError: pass else: result.add(char) return result 2. for every 8-bit encoding, some "representative" text is given (the longer, the better) 2a. the following function is a quick generator of all two-char sequences from its string argument. can be used both for the production of the pre-calculated data and for the analysis of a given string in the 'wild_guess' function. def str_window(text): return itertools.imap( text.__getslice__, xrange(0, len(s)-1), xrange(2, len(s)+1) ) So for every encoding and 'representative' text, a bag of two-char sequences and their frequencies is calculated. {frequencies[encoding] = dict(key: two-chars, value: count)} 2b. do a lengthy comparison of the bags in order to find the most common two-char sequences that, as a set, can be considered unique for the specific encoding. 2c. For every encoding, keep only a set of the (chosen in step 2b) two-char sequences that were judged as 'representative'. Store these calculated sets plus those from step 1a as python code in a helper module to be imported from codecs.py for the wild_guess function (reproduce the helper module every time some 'representative' text is added or modified). 3. write the wild_guess function 3a. the function 'wild_guess' would first construct a set from its argument: sample_set= set(argument) and by set operations against the sets from step 1a, we can exclude codecs where the sample set is not a subset of the encoding valid set. I don't expect that this step would exclude many encodings, but I think it should not be skipped. 3b. pass the argument through the str_window function, and construct a set of all two-char sequencies 3c. from all sets from step 2c, find the one whose intersection with set from 3b is longest as a ratio of len(intersection)/len(encoding_set), and suggest the relevant encoding. What do you think? I can't test whether that would work unless I have 'representative' texts for various encodings. Please feel free to help or bash :) PS I know how generic 'representative' is, and how hard it is to qualify some text as such, therefore the quotes. That is why I said 'the longer, the better'. -- TZOTZIOY, I speak England very best, Ils sont fous ces Redmontains! --Harddix From bjg at network-theory.co.uk Mon Apr 19 12:12:20 2004 From: bjg at network-theory.co.uk (Brian Gough) Date: 19 Apr 2004 17:12:20 +0100 Subject: Problems using modulo References: Message-ID: <87hdvgx7yz.fsf@network-theory.co.uk> griffph at aol.com (Griff) writes: > Results: > 5.9 mod 2.0 = 1.9 > 6.0 mod 2.0 = 2.0 !!!!!! > 6.1 mod 2.0 = 0.1 > > I don't know much about how Python does its floating point, but it > seems like a bug to me ? This is a common "feature" of floating-point arithmetic. 0.1 does not have an exact machine representation in binary, so the numbers displayed are not exact (e.g. 6.0 is actually 5.9999999... with a difference O(10^-15)). There is an appendix in the Python tutorial which discusses this, with more examples. > What is the best workaround so that I can get my code working as > desired ? > (ie I just want to tell whether my time "t" is an exact multiple of > the time interval, 2.0 seconds in this case). For exact arithmetic, work with integers (e.g. in this case multiply everything 10) or compute the difference from zero in the modulus, d, s = t % interval d = min (s, interval-s) and compare it with a small tolerance, e.g. 1e-10 or something appropriate to your problem. HTH. -- Brian Gough Network Theory Ltd, Publishing Python Manuals --- http://www.network-theory.co.uk/ From loic at fejoz.net Fri Apr 16 03:31:50 2004 From: loic at fejoz.net (Yermat) Date: Fri, 16 Apr 2004 09:31:50 +0200 Subject: Aspect Programming Module In-Reply-To: References: <84fc4588.0404140106.3fa0c55@posting.google.com> <8ef9bea6.0404142155.90b41ef@posting.google.com> <407E394B.2050709@mxm.dk> Message-ID: Alexandre Fayolle wrote: > Le 15-04-2004, Max M a ?crit : > >>Hung Jung Lu wrote: >> >> >>>Python does not even have codeblocks. So how can you say AOP is not >>>needed for Python programmers? >> >>I am probably rather dense, but I have not seen aspect oriented examples >> that could not have been done with simple mixins. > > > Hi Max, > > I'm probably rather dense too :-) > How do you implement the logging aspect with a simple mixin? > > (the logging aspect prints a statement before and after each method call > of a class instance) > Does it help ? class LoggerAOP(object): def __init__(self, f, name): self.f = f self.name = name def __call__(self, *args, **keywords): if callable(self.f): print "calling %s" % self.name result = self.f(*args, **keywords) print "end of call %s" % self.name return result raise TypeError, "%s not callable" % self.name class MyClass(object): def __init__(self, name): self.name = name def foo(self, a): return "%s say hello to %s" % (self.name, a) m = MyClass("Yermat") print 'm.name:', m.name print 'm.foo:', m.foo("world") m.foo = LoggerAOP(m.foo, 'foo') print 'm.name:', m.name print 'm.foo:', m.foo("world") -- Yermat From grante at visi.com Fri Apr 9 10:08:25 2004 From: grante at visi.com (Grant Edwards) Date: 09 Apr 2004 14:08:25 GMT Subject: surface fitting library for Python? References: <40748902$0$17253$a1866201@newsreader.visi.com> Message-ID: <4076ae59$0$17266$a1866201@newsreader.visi.com> On 2004-04-08, David M. Cooke wrote: >> I'm looking for a surface fitting library for Python. >> >> Something like the least-squares module in scientific python, >> except I want to fit a surface (z = f(x,y)) instead of a curve >> (y = f(x)). > > You mean Konrad Hinsen's ScientificPython? That's the one. > Scientific.Functions.LeastSquares.leastSquaresFit should still > work for you. You just need to make your data a list of tuples > of (x,y) and z. > > Example: [...] Well, that's entirely too easy. For some reason I convinced myself that wouldn't work (though I hadn't tried it). > If your model isn't amiable to having derivatives taken, That I don't know yet. We haven't chosen a model, since we're still working on gather the data. > you might check out the wrapping by Robert Kern of ODRPACK: > http://starship.python.net/crew/kernr/Projects.html I've used > this successfully. I will. Thanks! -- Grant Edwards grante Yow! YOW!! Now I at understand advanced visi.com MICROBIOLOGY and th' new TAX REFORM laws!! From bokr at oz.net Mon Apr 12 17:30:27 2004 From: bokr at oz.net (Bengt Richter) Date: 12 Apr 2004 21:30:27 GMT Subject: I am puzled about numbers References: <107lvs6mree8pee@corp.supernews.com> Message-ID: On Mon, 12 Apr 2004 13:43:42 -0700, "A Evans" wrote: >Hello I came across an interesting loop in math today >To me its interesting anyway I don't know if it will interest you > >var = 999 % 333 > >print var >>>> 0 > >var = 9999 % 333 >print var >>>> 9 > >var = 99999 % 333 >print var >>>> 99 > >var = 999999 % 333 >print var >>>> 0 > > >var = 9999999 % 333 >print var >>>> 9 > > >var = 99999999 % 333 >print var >>>> 99 > > >var = 999999999 % 333 >print var >>>> 0 > >and so on > >I guess that just goes to show nine is a universal number >or am I just completely insane and everyone knows this already > > >>> for digit in '97': ... for digits in xrange(1,10): ... num = eval(digit*digits) ... mod = eval(digit*3) ... var = num % mod ... print '%s: %s %% %s => %s' % (digits, num, mod, var) ... 1: 9 % 999 => 9 2: 99 % 999 => 99 3: 999 % 999 => 0 4: 9999 % 999 => 9 5: 99999 % 999 => 99 6: 999999 % 999 => 0 7: 9999999 % 999 => 9 8: 99999999 % 999 => 99 9: 999999999 % 999 => 0 1: 7 % 777 => 7 2: 77 % 777 => 77 3: 777 % 777 => 0 4: 7777 % 777 => 7 5: 77777 % 777 => 77 6: 777777 % 777 => 0 7: 7777777 % 777 => 7 8: 77777777 % 777 => 77 9: 777777777 % 777 => 0 Careful not to jump to conclusions ;-) Regards, Bengt Richter From dmq at gain.com Fri Apr 9 20:35:43 2004 From: dmq at gain.com (David MacQuigg) Date: Fri, 09 Apr 2004 17:35:43 -0700 Subject: Intro Chapter on OOP using Prothon Message-ID: <97ee70p2g40a060sef7nlg1lerf16rtpdi@4ax.com> I've been working with the folks at www.prothon.org trying to come up with a variation on Prothon that will preserve the ability to automatically translate Python to Prothon, while not limiting their wonderful creativity in developing all kinds of useful extensions to Python. My motiviation is having a language I can teach to electronic design engineers in two days. Currently that is Python without classes. I'm intriqued by the idea of adding OOP with only a few more hours of instruction. I've written a draft of a chapter as a replacement for the OOP chapters in Learning Python, 2nd ed. See ece.arizona.edu/~edatools/Prothon/Prototypes.doc (or .htm if you can't read teh MS Word .doc format). This chapter makes some assumptions about Prothon syntax that are not consistent with the current implementation, but I felt it better to keep things simple and self-consistent for now, and add the complexities later when the language is stable. Comments on the chapter are welcome. I am also interested in any comments on the question -- Can we do this with Python? Prothon is a real breakthrough in simplification (elimination?) of classes. If "prototypes" are done right, we can enjoy the new simpler style without having to re-write all our old programs or give up anything we now have in Python. -- Dave From arigo at tunes.org Sat Apr 3 16:04:35 2004 From: arigo at tunes.org (Armin Rigo) Date: Sat, 3 Apr 2004 21:04:35 +0000 (UTC) Subject: popen2 trouble References: Message-ID: <406F2905.C685715F@tunes.org> Hello Diez, "Diez B. Roggisch" wrote: > When performing this in my console window, everything works as expected. I > can paste several blocks of text that look like the above one, and the > crm114 constantly outputs classification results. Try using the 'bufsize' optional argument in the call to popen2. Set it to 0 to disable all buffering, if you are writing in large chunks (e.g. calling inn.write(bigstring)). Armin From shalabh at cafepy.com Sun Apr 25 13:51:37 2004 From: shalabh at cafepy.com (Shalabh Chaturvedi) Date: Sun, 25 Apr 2004 10:51:37 -0700 Subject: List operator overloading snag In-Reply-To: <8TCdnQn1OKieaRbdRWPC-w@speakeasy.net> References: <8TCdnQn1OKieaRbdRWPC-w@speakeasy.net> Message-ID: Steven Brent wrote: > Dear Group: > > I am a little perplexed by a basic example from the O'Reilly book, 2nd ed., > which demonstrates overloading some builtin list operators by embedding > lists in a wrapper class. > > Below is a snippet which shows the wrapper class and the overloaded > operator definition within (in this case, '__or__') > > > > The problem is that I can't seem to get my wrapped lists to use the > overloaded versions of the operators without calling the customize > instance method directly, as shown below: > >>>>import setwrapper; from setwrapper import * > > >>>>S1 = Set(['s','p','a','m']) >>>>S2 = Set(['s','c','a','t']) > > >>>>print S1 or S2 > > Set: ['s', 'p', 'a', 'm'] # custom __repr__ used but still default > # __or__ behavior, returns first true operand > > >>>>print S1.__or__(S2) > > using Set.__or__ > Set: ['s', 'p', 'a', 'm', 'c', 't'] # now all the custom behaviors > > This happens regardless of whether the module is imported into IDLE, or run > standalone. Obviously I'm missing something very basic namespace issue, and > I don't want to gloss over any bumps in my learning curve. > > Many thanks. > Try S1 | S2. The '|' operator (commonly known as the bitwise 'or' operator for integers) is what gets customized. You cannot change the meaning of the Python boolean 'or' which returns the left side value if it is true, else it returns the right side value. So what you're seeing is normal behavior, you always get the left side value since it's truth value is true. See also __nonzero__() in the Python docs. Btw, if you really want sets, you can use builtin module sets (new in 2.3). -- Shalabh From Bill.Scherer at VerizonWireless.com Thu Apr 1 07:08:39 2004 From: Bill.Scherer at VerizonWireless.com (Bill Scherer) Date: Thu, 01 Apr 2004 07:08:39 -0500 Subject: Unsung Modules, rev 3 Message-ID: <406C0647.30307@VerizonWireless.com> Soory I missed the anniversary by a few months, but here I am again taking up the unsung modules torch. For a review see: http://www.google.com/groups?as_q=unsung%20modules&safe=images&ie=UTF-8&oe=UTF-8&as_ugroup=comp.lang.python&lr=&hl=en Spread is still unsung, I think. And there has been a fair bit of bickering about threads latey, so maybe Queue needs to be sung about more. For this year's installment, I nominate VPython, aka visual. No, I'm not related (AFAIK!) to it's creator David Scherer. What amazes me most about it is this: this 3D graphical environment is easier to use than most, if not all, of the 2D gui toolkits. And that's not an April Fool's joke! So, what's your favorite unsung module today? -- Bill Scherer When Python's all you've got, Every problem looks like a mouse. From mark at prothon.org Thu Apr 15 19:30:38 2004 From: mark at prothon.org (Mark Hahn) Date: Thu, 15 Apr 2004 16:30:38 -0700 Subject: CamelCase versus wide_names (Prothon) References: Message-ID: <%VEfc.9387$dZ1.177@fed1read04> Joe Mason wrote: > Wasn't one of the Prothon design goals "when in doubt, follow Python"? Yes, and that was why I was voting for wide_names. Buit the logic was to make conversion from Python to Prothon easy and to make ex-Pythoners (like myself) happy. That logic falls apart if it is easy to convert names and Pythoners want camelCase. After posting this question and seeing that the majority want camelCase, I switched my vote (and have already switched Prothon's var names; it only took 10 minutes to switch). From sc0rp at hot.pl Fri Apr 30 22:57:52 2004 From: sc0rp at hot.pl (Jacek Trzmiel) Date: Sat, 01 May 2004 04:57:52 +0200 Subject: Urllib2/threading errors under Cygwin Message-ID: <40931230.84EECF31@hot.pl> Hi, I have a problem with using urllib2 with threading module under Cygwin. $ cygcheck -cd cygwin python Cygwin Package Information Package Version cygwin 1.5.5-1 python 2.3.2-1 Here is minimal app where I can reproduce errors: --- MtUrllib2Test.py ------------------------------------------------- #!/usr/bin/env python import urllib2 import threading import sys import time def FetchPage(): # time.sleep(3) # return opener = urllib2.build_opener() urlFile = opener.open( 'http://google.com/' ) pageData = urlFile.read() def IncCounterAndPrint( count=[0] ): count[0] += 1 print count[0] # sys.stdout.flush() def Main(): noOfThreads = 1 for unused in range(noOfThreads): thread = threading.Thread( target=FetchPage, args=() ) thread.start() # time.sleep(0.2) IncCounterAndPrint() while(threading.activeCount()>1): IncCounterAndPrint() time.sleep(0.5) IncCounterAndPrint() if __name__ == "__main__": Main() --- MtUrllib2Test.py ------------------------------------------------- 0. Simple case. Here everything looks ok: $ python MtUrllib2Test.py 1 2 3 4 5 1. First error. $ python MtUrllib2Test.py | tee out.txt 3 4 5 Leading prints has been eaten somewhere. Uncommenting disabled code in ANY of the functions does make output correct, but none of the solutions looks good for me: a) IncCounterAndPrint() - sys.stdout.flush() As I understand if stdout is not console then output gets buffered (i.e. it's not flushed automatically). Adding a flush call does make output good, but this looks like a kludge for me, not a real fix. I am writing to stdout from only one thread, so everything should be fine without calling flush, shouldn't it? b) Main() - time.sleep(0.2) Adding a little sleep after starting thread does make output correct too. For me it looks like race condition either in urllib2 or in cygwin. Or am I completely off here? c) FetchPage() - time.sleep(3), return Disabling calls to urllib2 does make problem go away, too. 2. Second error. If I increase number of threads: noOfThreads = 20 and run this prog (you may need to run it several times, or rise number of threads more to reproduce), then sometimes it does fail this way : $ python MtUrllib2Test.py | tee out.txt 4 [win] python 1744 Winmain: Cannot register window class C:\cygwin\bin\python2.3.exe: *** WFSO failed, Win32 error 6 or hangs this way: $ python MtUrllib2Test.py | tee out.txt 243 [win] python 1696 Winmain: Cannot register window class 520 [win] python 1696 Winmain: Cannot register window class Can anyone help me on those two? Best regards, Jacek. From moosebumps at moosebumps.com Sat Apr 17 17:18:05 2004 From: moosebumps at moosebumps.com (Moosebumps) Date: Sat, 17 Apr 2004 21:18:05 GMT Subject: python module for interactive web charts Message-ID: Is there anything that is made to generate web pages which have charts similar to the yahoo finance stock charts? Not looking to graph stocks specifically, but anything. I like how you can zoom on each axis, and maybe click to see numerical values and such. If there isn't anything in Python, what do people typically use for that kind of stuff, or is it all hand-rolled? thanks, MB From thorsten at thorstenkampe.de Wed Apr 28 18:55:29 2004 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Thu, 29 Apr 2004 00:55:29 +0200 Subject: maximum element? References: Message-ID: <2sf86pbtw35m$.dlg@thorstenkampe.de> Catching up... * Ivan Voras (2004-03-04 22:52 +0100) > What is the 'most pythonic' way of searching the largest element in a > list/tuple? > > My 'standard' idea is: > > max = list[0] # or -infinity, or whatever... > for i in list: > if i > max: > max = i > > While this is ok, I somehow 'feel' there could be a more concise > solution... :) max(seq) In a real world example you wouldn't be interested in "the" maximum but in the extrema/maxima according to function f (in your case the identity f(x)=x), which could be more than just one item. Thorsten From wweston at att.net Fri Apr 16 13:23:59 2004 From: wweston at att.net (wes weston) Date: Fri, 16 Apr 2004 17:23:59 GMT Subject: Learning about dictionaries In-Reply-To: References: Message-ID: Thomas Philips wrote: > I'm teaching myself python and in the course of playing around with > dictionaries, I tried to create the following trivial dictionary > > {1:'one', 2:'two'} > > So I entered > >>>>dict(1='one',2='two') > > SyntaxError: keyword can't be an expression > > As this did not work, I tried > >>>>dict(1=one,2=two) > > SyntaxError: keyword can't be an expression > > and > >>>>dict('1'='one','2'='two') > > SyntaxError: keyword can't be an expression > > as well as > >>>>dict('1'=one,'2'=two) > > SyntaxError: keyword can't be an expression > > Out of curiosity, I tried > >>>>dict(one=1,two=2) > > {'two': 2, 'one': 1} > > Why does this last attempt work, and more importantly, why did my four > earlier attempts fail? I might add that I have no trouble getting what > I want with > >>>>dict(zip((1,2),('one','two'))) > > {1: 'one', 2: 'two'} > or > >>>>dict(((1,'one'),(2,'two'))) > > {1: 'one', 2: 'two'} > > Sincerely > > Thomas Philips >>> d={1:'one',2:'two'} >>> d {1: 'one', 2: 'two'} >>> dd=dict(d) >>> dd {1: 'one', 2: 'two'} From wweston at att.net Mon Apr 26 12:34:00 2004 From: wweston at att.net (wes weston) Date: Mon, 26 Apr 2004 16:34:00 GMT Subject: askstring => grab failes Message-ID: Guys/Gals, Does anyone know why a call to tkSimpleDialog.askstring would result in a grab fail error. The call is from a toplevel window. The error happens about two thirds of the time! It doesn't happen at all in other apps. Is it a build issue? Redhat 9.0 Python 2.3.3 Thanks, wes From jacek.generowicz at cern.ch Fri Apr 2 03:31:35 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 02 Apr 2004 10:31:35 +0200 Subject: [OT] Top posting is a PITA References: <569c605ld1cj8fc1emolk08ete0s1prls1@4ax.com> <106di86neu1qh4d@news.supernews.com> <4069a001$0$4237$afc38c87@news.easynet.co.uk> <4069e9d9$0$8915$636a15ce@news.free.fr> <406a98ee$0$290$edfadb0f@dread12.news.tele.dk> <106lh64rda8t9d4@news.supernews.com> Message-ID: Roy Smith writes: > What makes you think people who top post don't also put a lot of effort > into carefully organizing their replies and trimming the original post > down to the most relevant points? Over a decade of observation of usenet and mailing lists. From kfast at poczta.onet.pl Wed Apr 14 10:41:37 2004 From: kfast at poczta.onet.pl (Jakub Fast) Date: Wed, 14 Apr 2004 16:41:37 +0200 Subject: Pygame In-Reply-To: References: Message-ID: <407D4DA1.1000607@poczta.onet.pl> pygame (and sdl) are lgpl licensed and as such they are not commercial-friendly. kuba From fumanchu at amor.org Thu Apr 22 16:48:16 2004 From: fumanchu at amor.org (Robert Brewer) Date: Thu, 22 Apr 2004 13:48:16 -0700 Subject: bytecode JUMP_IF_* always followed by POP_TOP? Message-ID: Playing around with bytecodes some more: >>> def g(x): ... if x: ... y ... else: ... z ... >>> dis.dis(g) 2 0 LOAD_FAST 0 (x) 3 JUMP_IF_FALSE 8 (to 14) 6 POP_TOP 3 7 LOAD_GLOBAL 1 (y) 10 POP_TOP 11 JUMP_FORWARD 5 (to 19) >> 14 POP_TOP 5 15 LOAD_GLOBAL 2 (z) 18 POP_TOP >> 19 LOAD_CONST 0 (None) 22 RETURN_VALUE I notice that, whether JUMP_IF_FALSE jumps or not, the next instruction it executes is POP_TOP (in the above, instruction numbers 6 and 14). Are there any constructions whereby this does not happen for JUMP_IF_FALSE and JUMP_IF_TRUE? If there aren't, is it just explicitness that kept JUMP_IF_* from doing the POP on its own, before the jump (which would thereby save two instructions)? Robert Brewer MIS Amor Ministries fumanchu at amor.org From maxm at mxm.dk Mon Apr 26 18:22:50 2004 From: maxm at mxm.dk (Max M) Date: Tue, 27 Apr 2004 00:22:50 +0200 Subject: Is there a Python library that packs binary data into one file? In-Reply-To: <85b54e91.0404261301.69d5c1e9@posting.google.com> References: <85b54e91.0404261301.69d5c1e9@posting.google.com> Message-ID: <408d8ba4$0$255$edfadb0f@dread12.news.tele.dk> Jacob H wrote: > Hello all, > > Today I began writing a utility script that takes given binary files > and puts them all into one datafile. My idea is to be able to access > any binary data I want by indexing the datafile, e.g. > wanted_image_data = datafileobj[IMAGE_DATA]. The purpose is to hide > external image files from the user in a simple game I'm writing. What you need, is a simple pickle of a dictionary save to disk. It's dead easy, and does exactly what you want. import cPickle some_dict = {'my':'name','is':'norman','bates':'!'} file_name = 'some.dict' f = open(file_name, 'wb') cPickle.dump(some_dict, f, -1) f.close() f = open(file_name, 'rb') c = cPickle.load(f) f.close() print c >>{'my': 'name', 'is': 'norman', 'bates': '!'} " 3.14 pickle -- Python object serialization The pickle module implements a fundamental, but powerful algorithm for serializing and de-serializing a Python object structure. ``Pickling'' is the process whereby a Python object hierarchy is converted into a byte stream, and ``unpickling'' is the inverse operation, whereby a byte stream is converted back into an object hierarchy. Pickling (and unpickling) is alternatively known as ``serialization'', ``marshalling,''3.2 or ``flattening'', however, to avoid confusion, the terms used here are ``pickling'' and ``unpickling''. This documentation describes both the pickle module and the cPickle module. " regards Max M From rzantow at ntelos.net Sat Apr 3 16:51:01 2004 From: rzantow at ntelos.net (rzed) Date: Sat, 03 Apr 2004 21:51:01 GMT Subject: Indent testers needed (Prothon) References: Message-ID: "Mark Hahn" wrote in news:KFDbc.148020$cx5.28330 at fed1read04: > > "Ville Vainio" wrote > >> Just allow both spaces and tabs, but not in the same block. > > This is a good idea. I could reset the flag for the indent type > whenever the indentation goes to zero. I'll pitch this on the > Prothon list. > > "rezed" wrote ... > >> I don't show visible tab marks in my editors, and I don't want >> to have to, but if I don't, I haven't any good way to know >> whether a piece of code contains tabs or spaces. Until I run >> it, at least. > > I agree this is a problem, but the whole problem we are trying > to solve, that of mixed spaces and tabs, would cause you the > same grief, or worse, right? > > > Not necessarily, at least in Python. I can paste a function in its entirety and not need to know whether it uses tabs or spaces. In Prothon (at the moment), a mixture would give me a parse error. But in the more general case, yes it could cause the same grief. If I made wholesale cut and paste changes to a file, scattering many tab-indented statements in among my space-indented ones, it would take at least a little while to straighten it out. In any case, it is more an annoyance than a showstopper, I'd say. If I got into the habit of bringing all external code into a file and saving it, my editor would convert the tabs to my default and the code would be usable without difficulty. I can live with that little thing. -- rzed From Felix.Wiemann at gmx.net Wed Apr 7 08:35:13 2004 From: Felix.Wiemann at gmx.net (Felix Wiemann) Date: Wed, 07 Apr 2004 14:35:13 +0200 Subject: min() with custom compare. References: <20040407114407.0a07d143@pistache.sara.nl> Message-ID: <87fzbgge4e.fsf@news2.ososo.de> Heather Coppersmith schrieb: > Use reduce: > > def absolulte_minimum_function( x, y ): > x, y = abs( x ), abs( y ) > if x < y: > return x > else: > return y > > minimum = reduce( absolute_minimum_function, l ) That doesn't work if the "minimum" element is negative, e.g. l = [5, -4, -1, 9, -9]. # ^^ def absolute_minimum_function(x, y): if abs(x) < abs(y): return x else: return y minimum = reduce(absolute_minimum_function, l) -- http://www.ososo.de/ From lbates at swamisoft.com Thu Apr 15 09:55:36 2004 From: lbates at swamisoft.com (Larry Bates) Date: Thu, 15 Apr 2004 08:55:36 -0500 Subject: [Newbie Q on String & List Manipulation] References: <567a7c35.0404150247.7809bef5@posting.google.com> Message-ID: If you want to join all the items in a list together try: mycookies="".join(thecookies) Secondly, your append to the cookies list is not inside your loop. In your code it will only get executed a single time (after exiting the loop) which is most likely why you only see the LAST item. Remember that indention in Python has meaning! Something more like this: for item in thecookies: if re.compile("^SID").search(item): foundsessionid = 1 break if not foundsessionid: print '> Failed to retrieve the "SID" cookie' sys.exit() # # grep the GV cookie from the HTTP response or die # matches = re.compile('^\s*var cookieVal= "(.*)";.*', re.M).search(response) if matches: thecookies.append("GV=" + matches.group(1)) else: print '> Failed to retrieve the "GV" cookie' sys.exit() print thecookies mycookies = "".join(thecookies) Regards, Larry Bates Syscon, Inc. "Matthew" wrote in message news:567a7c35.0404150247.7809bef5 at posting.google.com... > Hello All, > > today is the first day i try to programming in Python, > my assignment is, write a silly script that probably > will run a few times a day to check if the Gmail services > is ready or not. ;) > > however, i encountered some problem when playing with the > list and string. > > i'm using Python 2.2.2 on Redhat. if i write something like: > > a = "one" > b = "two" > a += b > print a > > i will get: > > onetwo > > ok, seems quite ok, however, not sure why it doesn't work on > my silly Gmail script (pls refer to my script belows): > > for item in thecookies: > mycookies += item > > print mycookies > > i have exactly 4 items in the "thecookies" list, however, when > printing out "mycookies", it just show the last item (in fact, > seems the 4 items have been overlapped each others). > > could somebody pls kindly take a look at my silly script and > gimme some advise? > > thanks very much in advance! :) > > --- > matthew > > > > > import re > import string > import sys > import urllib > > user = "da at email.address" > pswd = "dapassword" > > schm = "https://" > host = "www.google.com" > path = "/accounts/ServiceLoginBoxAuth" > qstr = {"service" : "mail", \ > "continue" : "http://gmail.google.com/", \ > "Email" : user, \ > "Passwd" : pswd} > > qstr = urllib.urlencode(qstr) > > url = schm + host + path + "?" + qstr > > conn = urllib.urlopen(url) > > headers = conn.info().headers > response = conn.read() > > thecookies = [] > > # > # extract all the Set-Cookie from the HTTP response header and put it in thecookies > # > > for header in headers: > matches = re.compile("^Set-Cookie: (.*)$").search(header) > if matches: > thecookies.append(matches.group(1)) > > # > # make sure we've grep the SID or die > # > > foundsessionid = 0 > > for item in thecookies: > if re.compile("^SID").search(item): > foundsessionid = 1 > break > > if not foundsessionid: > print "> Failded to retrieve the \"SID\" cookie" > sys.exit() > > # > # grep the GV cookie from the HTTP response or die > # > > matches = re.compile("^\s*var cookieVal= \"(.*)\";.*", re.M).search(response) > > if matches: > thecookies.append("GV=" + matches.group(1)) > else: > print "> Failed to retrieve the \"GV\" cookie" > sys.exit() > > print thecookies > > mycookies = "" > > for item in thecookies: > mycookies += item > > print mycookies > > # > # still got many things to do right here... > # > > sys.exit() From fumanchu at amor.org Wed Apr 21 18:58:06 2004 From: fumanchu at amor.org (Robert Brewer) Date: Wed, 21 Apr 2004 15:58:06 -0700 Subject: PEP 329 and bytecode hacking Message-ID: Phillip J. Eby wrote: > At 03:07 PM 4/21/04 -0700, Robert Brewer wrote: > >Raymond's cookbook recipe inspired me to write a generic Visitor for > >inspecting and rewriting bytecode. Maybe it'll help someone out there > >with prototyping bytecode hacks. > > For more sophisticated bytecode modifications, you'll want to > keep track of > things like source line number, the nth instruction and its > operand if any > (so you can scan *backwards*), the list of locations of a > given opcode, > etc. This Pyrex module: > > http://cvs.eby-sarna.com/PEAK/src/peak/util/_Code.pyx?rev=1.2&content-ty pe=text/vnd.viewcvs-markup > provides high-speed dynamic access to bytecode metadata, and is suitable > for use in runtime bytecode hacks, since it does not require Python > function call overhead for each instruction. Good idea! I'll work on including that. It's not as context-sensitive as visiting each opcode in turn, but sometimes no context is good context. :) Since it's already available from Pyrex, I'll adapt the functionality into a codewalk.Visitor subclass. Robert Brewer MIS Amor Ministries fumanchu at amor.org From harry.g.george at boeing.com Mon Apr 26 10:56:25 2004 From: harry.g.george at boeing.com (Harry George) Date: Mon, 26 Apr 2004 14:56:25 GMT Subject: interfacing to a remote excel app References: <20040426150428.69010a3c@pistache.sara.nl> Message-ID: Bram Stolk writes: > pyHello, > > > Google helped me find a nice package to interface python with MS Excel. > "win32all", or sometimes called by the name "pywin32". > > http://starship.python.net/crew/mhammond/ > > However, this win32all extension seems to be specifically built for the > windows platform only. > > What could I use if I want to interface to excel from a python interpreter > running on a remote UNIX machine? > > The specific task I want to accomplish is as follows: > I want python on UNIX to be able to make selections in excel (highlight rows). > Also, I want to have changes in the selected (highlighted) items in excel > to be communicated to the python running on UNIX. > > What would be the best way to do this? > > Thanks, > > Bram > > PS: A possible approach would be to run two interpreters, one on both > platforms, and have the MS python talk to excel. However, I would like a > solution with low-impact to the MS platform, and want to get away without > having to install python and win32all on the MS machine. > > -- > ------------------------------------------------------------------------------ > Bram Stolk, VR Engineer. > SARA Academic Computing Services Amsterdam, PO Box 94613, 1090 GP AMSTERDAM > email: bram at nospam.sara.nl Phone +31-20-5923059 Fax +31-20-6683167 > > "For the costs of subsidized agriculture in the EU, we can have all > 56 million European cows fly around the world. First Class." - > J. Norberg > ------------------------------------------------------------------------------ You are going to have to do *something* on the MS Excel box. Otherwise you have a security nightmare (I'm now accessing your Excel spreadsheet, and I don't even have to tell you about it.) So it is a matter of how much work you are willing to do on the MS box. Installing a py2exe bundle is pretty straightforward, so I'm not sure this is a stumbling block. You could do a proxy with Python-and-pywin32 talking to Excel via COM, and to the LAN via Pyro or XMLRPC or SOAP. Other than that, you could try to setup remote access to Excel.NET via .NET remoting, and try to reach that from Mono or DotGNU. But .NET and its clones are not very Python-friendly, so the bindings may not be available. Even if you got it to work, you would be in a Microsoft lockin situation, subject to changing protocols as .NET evolved (and as patent fights perhaps made non-MS implementaitons difficult.) -- harry.g.george at boeing.com 6-6M21 BCA CompArch Design Engineering Phone: (425) 342-0007 From mwilson at the-wire.com Thu Apr 1 14:42:55 2004 From: mwilson at the-wire.com (Mel Wilson) Date: Thu, 01 Apr 2004 14:42:55 -0500 Subject: ESR's fortune.pl redone in python - request for critique References: Message-ID: In article , Peter Otten <__peter__ at web.de> wrote: >Yes, Mel's approach is the least scalable (it keeps the whole file), I have even more sympathy now (I had quite a bit before) for the poster who asked whether Python had a built-in way to read a file up to an arbitrarily-chosen delimiter. (Subject: Can python read up to where a certain pattern is matched?) Regards. Mel. From nospam at nopes Tue Apr 6 21:40:16 2004 From: nospam at nopes (Steve) Date: Wed, 07 Apr 2004 11:40:16 +1000 Subject: Python and postgres Message-ID: <40735c00$1@clarion.carno.net.au> Hi, I have postgres 7.4.1 running on my server and I've been trying to find a good python-postgres interface module. I installed Pygres on another machine running Linux using a RPM release and it works. However, I need to do the same for an alpha server and I can't find source files for PyGres that would compile with 7.4.1 anywhere. Can someone please help me out? I need a good postgres python interface to work with. Cheers, Steve From sdahlbac at abo.fi Wed Apr 28 07:46:13 2004 From: sdahlbac at abo.fi (Simon Dahlbacka) Date: 28 Apr 2004 04:46:13 -0700 Subject: wxpython + py2exe + innosetup References: <408eca0c$1@newsflash.abo.fi> <30260531.0404272030.3fe52362@posting.google.com> Message-ID: simoninusa2001 at yahoo.co.uk (simo) wrote in message news:<30260531.0404272030.3fe52362 at posting.google.com>... > "Simon Dahlbacka" wrote: > > > I'm "exefying" an application that uses wxpython, some com to control excel > > and word and want to distribute this application. > > > > after creating the executable with py2exe, it still works fine (at least on > > my development machine), however, if I create an installer package with > > innosetup, install it and try to run it, I get a busy cursor for a split > > second and then.. nothing. no errors no traceback no nothing.. viewing > > dependencies does not reveal anything strange, and running the installed > > program in a debugger just tells that the application has exited with code > > 0. > > Does the program rely on any paths to files - i.e. does it open your > Excel/Word file from the current directory? it _should_ not, I had a problem with this earlier regarding icons, but switched over to resourcepackage now. And both Excel and Word doesn't do any filehandling until I explicitely "hit the button" > This is the only problem I've ever found with Inno - it's an FAQ too, > there's an option to set the "Run From" property in the shortcuts. The > sympton is that it won't work from the shortcut in Start/Desktop but > will work from the program directory. > > What about permissions - if you installed it as non-Admin and it needs > to write something Admin-only..... ..hmm, I'm just doing a default install, there is however registry settings involved, but since I've installed it being admin and running it being admin, I doubt this is the problem. > ISTool can make the InnoSetup options a bit easier to deal with - > maybe you're accepting a default that needs to be changed? hmm, never heard of that, I have to check it out later.. another strange thing is that I tried to sprinkle "print I got here statements" all over the place, but didn't see any of those, even running from a console. /Simon From colin.blackburn at durham.ac.uk Tue Apr 6 06:20:46 2004 From: colin.blackburn at durham.ac.uk (Colin Blackburn) Date: Tue, 06 Apr 2004 11:20:46 +0100 Subject: slightly OT: BUT NEEDs to be said References: <8b42d1998c978c8c1cddf15c52a1c57b@dizum.com> Message-ID: On Mon, 5 Apr 2004 21:50:07 +0200 (CEST), Nomen Nescio wrote: > People have very real reason to fear MPFC: Highly educated/wealthy > family background/private > school/Oxford/Cambridge people jumping about and acting 'zany' and > coming up > with all sorts of useless sketches designed to appeal strictly to the > liberal-elite > is a fairly repulsive artistic concept especially if you do not find the > style > of MPFC even remotely amusing. > > Unfortunately this formula (hiring these sorts of people) was to become > the > bed rock of BBC alternative comedy for years to come (Ben Elton, Steven > Fry > etc etc) and remember people in the UK did not have the choice about > this crap > as it came out of their licence fee (that is another subject) Ben Elton went to Manchester Uni, in a northern industrial city, a far cry from Oxbridge. We did have a choice we could watch commercial ITV, unfortunately it's crap. Colin -- From news at bolognini.net Fri Apr 30 20:50:49 2004 From: news at bolognini.net (Lorenzo Bolognini) Date: Sat, 1 May 2004 02:50:49 +0200 Subject: Web development class References: Message-ID: I wrote: > h1.red (assigning properties to html entities) Sorry, h1.color("red") Lorenzo Bolognini From no.mail at available.net Sun Apr 25 14:30:44 2004 From: no.mail at available.net (Georgy) Date: Sun, 25 Apr 2004 18:30:44 GMT Subject: Andreas' practical language comparison References: Message-ID: "Andreas Koch" wrote in message news:c6glig$phm$07$4 at news.t-online.com... | Hi all, | | i started a little "practical language comparison" - practical | in the sense that i compare how actual distributions and versions | and their libraries (not abstract language specifications) solve small | test cases like the 8 queens problem. | | Currently there are contributions for 17 different languages, and | none for Phyton (and Lisp. And Forth. And many others ). | If someone is interested in contributing a few implementations, | please have a look at: | | http://www.kochandreas.com/home/language/lang.htm | | and mail me your code snippets (or critics) or post them here. | | thanks a lot, | -- | Andreas | He screamed: THIS IS SIG! From loic at fejoz.net Fri Apr 2 02:12:44 2004 From: loic at fejoz.net (Yermat) Date: Fri, 02 Apr 2004 09:12:44 +0200 Subject: Pyrex gets a perfect score. In-Reply-To: References: <905fcd91.0404011433.6681abd9@posting.google.com> Message-ID: Kyler Laird wrote: > rlratzel at siliconmetrics.com (Rick Ratzel) writes: > > >>...just curious...did you look at Elmer >>(http://elmer.sourceforge.net)? > > > I hadn't. (I'm partial to Debian packages.) > > The description "Elmer is not a Python-to-C or Python-to-Tcl > translator" makes me think that it's not appropriate for what I need > right now - the ability to submit only C code. > > It does look like it would be useful for later work though. I think > it's likely to provide cleaner interfaces than what I was able to > generate using Pyrex. > > Thank you. > > --kyler Does it help ? http://sourceforge.net/projects/py2cmod Yermat From No.Spam.mc at No.Spam.mclaveau.No.Spam.com Sun Apr 4 08:27:16 2004 From: No.Spam.mc at No.Spam.mclaveau.No.Spam.com (Michel Claveau/Hamster) Date: Sun, 4 Apr 2004 14:27:16 +0200 Subject: Python is faster than C References: <406F0907.96F37EA1@tunes.org> Message-ID: Hi ! Yes, but Psyco is writted in C & Python, and it use an C module. Said "Psyco is faster than C", it's like said "Psyco is faster than Psyco". @-salutations (and sorry for my *bad english*) -- Michel Claveau From greg at cosc.canterbury.ac.nz Tue Apr 27 00:56:33 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Tue, 27 Apr 2004 16:56:33 +1200 Subject: Magic methods in extension types In-Reply-To: References: Message-ID: Jacek Generowicz wrote: > You are, in summary, saying that by _far_ the simplest way of adding > __iadd__ to an extenion type is via tp_as_number->nb_inplace_add, > aren't you. It's the *only* way to do it. Unless you use Pyrex, of course: http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/ -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From rick.ratzel at austin.rr.com Wed Apr 7 23:33:54 2004 From: rick.ratzel at austin.rr.com (Rick L. Ratzel) Date: Thu, 08 Apr 2004 03:33:54 GMT Subject: query regarding embeding python in C References: Message-ID: <4074C562.1020707@austin.rr.com> Looks like you may have forgotton to link with libpython.a...for example, if your system has Python 2.3 installed, add this to your compile/link line: -L/usr/lib/python2.3/config -lpython2.3 Vardhman Jain wrote: > Hi, > I am trying out the concept of python code being executed from a C > program. I got a peice of code from the tutorial but I don't know how to > compile/use it > > The code is > #include > > int > main(int argc, char *argv[]) > { > Py_Initialize(); > PyRun_SimpleString("from time import time,ctime\n" > "print 'Today is',ctime(time())\n"); > Py_Finalize(); > return 0; > } > ~ > ~ > > > Now If I do "c++ temp.c -I /usr/include/python2.2/" I get the errors > [vardhman at linuxAddict TA]$ c++ temp.c -I /usr/include/python2.2/ > /tmp/ccnpr9em.o(.text+0x11): In function `main': > : undefined reference to `Py_Initialize' > /tmp/ccnpr9em.o(.text+0x1e): In function `main': > : undefined reference to `PyRun_SimpleString' > /tmp/ccnpr9em.o(.text+0x26): In function `main': > : undefined reference to `Py_Finalize' > collect2: ld returned 1 exit status > > Can some one tell me how to compile and use this code. > > > Vardhman > > > -- > Vardhman Jain > III Year B.Tech. CSE > IIIT-Hyderabad > Address: > Room No 27, NBH, IIIT-Hyderabad,Hyderabad 500019 > > presence on net: > http://students.iiit.net/~vardhman > > > From __peter__ at web.de Fri Apr 30 07:42:22 2004 From: __peter__ at web.de (Peter Otten) Date: Fri, 30 Apr 2004 13:42:22 +0200 Subject: Where to put the HTMLgen files References: Message-ID: dont bother wrote: > It does not work. When I write a python program and > include : > > import HTMLgen > > it does not finds this module. Can anyone tell me > where should I place this HTMLgen directory? and how > to make it work? Put HTMLgen.py directly into the site-packages directory of your python installation, e. g. /usr/local/lib/python2.3/site-packages/ or include the directory containing HTMLgen.py in the python search path by defining an environment variable PYTHONPATH=/dir/containing/my/module/ or put a text file dontbother.pth (only the suffix is important) containing /dir/containing/my/module/ into a folder already in the python module search path, e. g. the site-packages mentioned above. Peter From peter at engcorp.com Fri Apr 30 07:52:04 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 30 Apr 2004 07:52:04 -0400 Subject: Is classless worth consideration In-Reply-To: <8ef9bea6.0404292307.66b78b83@posting.google.com> References: <69cbbef2.0404290259.fd8d71c@posting.google.com> <69cbbef2.0404291209.7a98a799@posting.google.com> <8ef9bea6.0404292307.66b78b83@posting.google.com> Message-ID: <84Kdnfu3OoN4oA_dRVn-vg@powergate.ca> Hung Jung Lu wrote: > I have also pointed out previously that > Python uses 5 devices where prototype-based needs only one: (a) class, > (b) instance, (c) module, (d) metaclass, (e) scope. If this is not > hideously baroque, then, Houston, we've got a problem. If you can > really think outside the box, you'd pitch in also: (f) aspect. Well, (c) module is merely a packaging technique, not anything to do specifically with OOP, so it shouldn't appear in a list of "what do you think makes Python's OO model hideously baroque". As for class and instance, unless all other languages that have class and instance are also considered baroque, it hardly seems fair to separate them. Scope doesn't quite seem to fit in this either, but not being a theoretician I'll just leave the discussion at this point and point out that for the purposes of a *large* majority of the people using Python, these issues do not arise and Python OO is very much a breath of fresh air compared to anything else they've used. Which still makes it hard for me to see a claim of "hideous baroqueness" as anything other than deliberately inflammatory, but wrong. -Peter From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Fri Apr 30 16:44:22 2004 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Fri, 30 Apr 2004 22:44:22 +0200 Subject: Tkinter: focus/text selection problem with tkFileDialog In-Reply-To: References: <409259ed$0$574$e4fe514c@news.xs4all.nl> Message-ID: <4092baaa$0$559$e4fe514c@news.xs4all.nl> Peter Otten wrote: > Irmen de Jong wrote: > > >>Hi, >>I'm having trouble with the code below. >>It's just a regular Tk text widget in which you can type and >>select text as expected, however the call to >>tkFileDialog.askopenfilename() seems to screw things up. After the file >>dialog, I can no longer use the Text widget (typing, selecting, it doesn't >>work anymore!) What am I doing wrong? > > > No sure, but opening the dialog before entering the main loop could be the > problem. The following modification seems to work: > > import Tkinter, tkFileDialog > > window = Tkinter.Tk() > txt = Tkinter.Text(window) > txt.insert(Tkinter.END, "Choose a file, then try to select me") > txt.pack() > > def openFile(event=None): > name = tkFileDialog.askopenfilename() > txt.insert(Tkinter.END, "\nFile chosen: " + name) > > txt.focus_set() > window.after_idle(openFile) > window.mainloop() > > Peter > Okay, I didn't know about the after_idle, and still don't understand why my first attempt resulted in the weird behavior I described. But hey, with a bit of tweaking, it works now :-) Also another weird thing: I found out (using my original code without the after_idle) that if I inserted a tkMessageBox before the mainloop(), that the 'correct' behavior of the Text box is restored! ...confused... --Irmen. P.S. I have now also discovered Fredrik Lundh's page: http://www.effbot.org/zone/tkinter-threads.htm Interesting. From fgeiger at datec.at Thu Apr 1 10:24:45 2004 From: fgeiger at datec.at (F. GEIGER) Date: Thu, 1 Apr 2004 17:24:45 +0200 Subject: [Twisted] Cookbook? Message-ID: Does anybody know of a cookbook for Twisted? It's not that helpful for me to see how an echo server is written (can do this with std sockets) and success stories are too little concrete. What I actually want to try is using Twisted in factory automation. So I'm thinking of cookbook topics like "If you want to capture data from an OPC server and put them into a database, then go this way..." or "If you want to notify the production manager of troubles found in production data, then go for chapter..." etc. Probably the way to answer such questions is to try it myself - no problem with that, I'm working thru the examples right now. But if there are shortcuts, I'd like to take them (who wouldn't do so?). BTW, the dox itself seem to be extensive (the book in pdf format has 380+ pages), which is really pleasing. Many thanks in advance and best regards Franz GEIGER From Mike at DeleteThis.Geary.com Sat Apr 3 11:50:09 2004 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Sat, 3 Apr 2004 08:50:09 -0800 Subject: Indent testers needed (Prothon) References: <2Msbc.136673$cx5.2385@fed1read04> Message-ID: <106tqq5e6gn8aaf@corp.supernews.com> Josiah Carlson wrote: > >>/* loop 2 */ > >>ix = 2 > >>for > >> item > >> in > >> blist > >> : > >> alist[ix] = > >> alist[ > >> ix > >> ] > > > ... > The above code shows how you can make Prothon code > extraordinarily ugly by exploting the continuation rules. > Certainly most people don't see such ugly continuations > in Python, but I think rule #3 is begging for trouble. That's a strawman. The fact that you *could* write strange code like that doesn't mean that there is anything wrong with Mark's continuation rules. I could write a long Python program that uses no functions, classes, or anything else to break it into smaller understandable pieces. Just one big long piece of code that is indented to twenty levels. While I'm at it, I'll use variable names that obscure what the code does. Does that imply that there should be a maximum length to a Python source file, a limit on the level of indenting, and restrictions on what variable names I can use? Of course not. -Mike From peter at engcorp.com Tue Apr 27 07:33:23 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 27 Apr 2004 07:33:23 -0400 Subject: CPU usage of Python interpreter doing empty while loop under XP In-Reply-To: References: <7kpr805ou6g8ucm9rok4nodkolcp02viig@4ax.com> Message-ID: Jon Perez wrote: > Dennis Lee Bieber wrote: > >>Stick a sleep(0) inside it, and no doubt you will see performance >>return to "normal". Even though the 0 means no actual delay is wanted, >>the task swap will occur, giving the OS a chance to respond to events. > > > Great, it worked. > > So > > while 1: sleep(0) > > is a better alternative to > > while 1: pass > > (I'm using this for debugging purposes...) How does that help your debugging? That will tell us whether sleep(0) is a better alternative, or whether there is really something else you should be doing instead. (I have never had occasion to use "while 1: pass" in Python, ever.) -Peter From faassen at infrae.com Tue Apr 27 14:32:29 2004 From: faassen at infrae.com (Martijn Faassen) Date: Tue, 27 Apr 2004 20:32:29 +0200 Subject: Is Perl *that* good? In-Reply-To: <108t1tlhnhi46ee@corp.supernews.com> References: <108t1tlhnhi46ee@corp.supernews.com> Message-ID: <408EA73D.5000507@infrae.com> Michael Geary wrote: > Robert Brewer wrote: > >>I wish Python had won, as well. But time is linear (in >>my mind). I now wish only that we could leverage the >>similarity of JS and Python (execution and binding >>models) into more Python users. Marketing needs >>to run with the line, "So you know Javascript? Then >>you know Python!" > > That was my impression of Python when I started using it after some > extensive JavaScript work: "Cool! It's just like JavaScript but with a lot > more goodies!" The two languages struck me as very similar. Even though > JavaScript *looks* like C, it *works* much more like Python. When I played with JavaScript it felt like a badly broken Python. That's still not bad for a language. :) Playing with JavaScript really quickly makes you realize how many details Python got right. Regards, Martijn From ramen at lackingtalent.com Mon Apr 5 02:44:48 2004 From: ramen at lackingtalent.com (Dave Benjamin) Date: Mon, 05 Apr 2004 06:44:48 -0000 Subject: Python conference slogan References: Message-ID: Python: It starts with "P" and runs on Linux. ;) From richie at entrian.com Thu Apr 1 12:09:34 2004 From: richie at entrian.com (Richie Hindle) Date: Thu, 01 Apr 2004 18:09:34 +0100 Subject: PLEASE STOP!!! In-Reply-To: <406C40E8.10209@prescod.net> References: <95aa1afa.0404010352.80de14e@posting.google.com> <406C40E8.10209@prescod.net> Message-ID: <3uio60lcna2ivhejcgtjqus40tj1n5ne1n@4ax.com> [Paul] > PLEASE STOP!!! ...ruining April Fools! > > Camilo Olarte wrote: > > > > OOUCH ! I Almost believe it! You can't count Camilo in with the spoilers - Camilo obviously believes that my 'goto' module is some kind of prank fiction, when in fact it's a working module ready to be downloaded and used. There's probably a word for this but I've no idea what it is... -- Richie Hindle richie at entrian.com From mark at prothon.org Thu Apr 22 14:20:57 2004 From: mark at prothon.org (Mark Hahn) Date: Thu, 22 Apr 2004 11:20:57 -0700 Subject: Why we will use obj$func() often Message-ID: "Michael Geary" wrote ... >Does anyone have some sample code where obj$func() would be used? > (Apologies if I missed it.) There have been so many messages about delegation and binding since Greg originally posted his meowing cat message that it's hard to remember what the original problem was that Greg pointed out. At that time Prothon had no solution for the problem. Now there is a released solution but it is incomplete and has broken the xor operator ( ^ ) (don't tell anyone ). I'll restate it here in my own way (this is copied from something I posted on comp.lang.py). Statement of problem (These are tested programs from released Python and Prothon:): # Python class klass: def __init__(self): self.me = 1 def func(self): print "func1,self"+str(self.me), class klass2(klass): def __init__(self): self.me = 2 def func(self): klass.func(self) # delegation print "func2,self"+str(self.me), inst = klass2() inst.func() # prints func1,self2 func2,self2 # Directly translated to Prothon Klass = Object() with Klass: .me = 0 # extra line def .__init__(): .me = 1 def .func(): print "func1,self"+.me, Klass2 = Klass() with Klass2: def .__init__(): .me = 2 def .func(): Klass.func() # does not do what python does print "func2,self"+.me, inst = Klass2() inst.func() # prints func1,self0 func2,self2 As you can see, the call Klass.func() got the function func from the object Klass and then called it on Klass using Klass as the target "self" instead of the instance "inst". This is not what Python did and this is the problem. In Python the call klass.func() was different because Python knows that klass is a class and therefore obviously cannot be the target of call (an instance), so it made the programmer pass the instance self to use as a parameter. To fix this, we need to be able to specify in general, what the self object is going to be during the execution of a function in Prothon (I call this choice of self "binding self to function" even though it's temporary during execution). Greg's solution was to replace the period before the function name in klass.func() with a different symbol to indicate that the func is not supposed to be bound to klass as the syntax normally suggests (as in list.sort!()), but instead defaults to the current self. My final scheme is almost the same but instead of just defaulting to self, it specifically forces it to self (this may seem like a semantic difference, but don't say that to Greg ). So now we have this solution. Note that delegation to an ancestor prototype (class in Python), is a common operation, especially in the __init__ function: Klass = Object() with Klass: def $__init__(): $me = 1 def $func(): print "func1,self"+$me, Klass2 = Klass() with Klass2: def $__init__(): $me = 2 def $func(): Klass$func() # voila! problem fixed print "func2,self"+$me, inst = Klass2() inst.func() # prints func1,self2 func2,self2 From http Fri Apr 16 01:06:04 2004 From: http (Paul Rubin) Date: 15 Apr 2004 22:06:04 -0700 Subject: Automatic, portable optimization of global access References: <5d83790c.0404150721.46a3b5d0@posting.google.com> <7xvfk17zeg.fsf@ruckus.brouhaha.com> <5d83790c.0404151803.598c1807@posting.google.com> Message-ID: <7xbrlseclf.fsf@ruckus.brouhaha.com> python at rcn.com (Raymond Hettinger) writes: > """ Binding should be applied selectively to those functions where > speed is important and dynamic updates are not desired (i.e. the > globals do not change). In more dynamic environments, a more > conservative approach is to set builtin_only to True so that only the > builtins get optimized (this includes functions like len(), exceptions > like IndexError, and constants like True or False). > """ Well, it's possible that builtins get changed too. I've used "len" as a variable a few times without realizing that I was clobbering a builtin. Maybe the compiler could detect when it's ok to run the optimizer, and automatically run it when it can. From russelllear at earthlink.net Tue Apr 6 23:49:56 2004 From: russelllear at earthlink.net (Russell Lear) Date: Wed, 07 Apr 2004 03:49:56 GMT Subject: OFF-TOPIC:: Why Lisp is not my favorite programming language References: <165b3efa.0403030443.4d591f04@posting.google.com> <40460dd5$0$5916$7a628cd7@news.club-internet.fr> <6in670lrldbjkuujle68a526293j57a7mn@4ax.com> Message-ID: Stephen Horne wrote: > On 6 Apr 2004 13:58:45 -0700, nish20 at netzero.net (Mike Nishizawa) > wrote: > >>mintiSPAMBLOCK at yahoo.com (Minti) wrote in message >>news:... > >>> However when some one says that the code might be 31.? >>> times slower as compared to C, kinda of scares me. Could assert such >>> figures. I know speed is not the one and only goal but just wondering >>> if these figures are correct. > > It wouldn't surprise me. LISP is normally interpreted - maybe always, > though I'm not certain of that. The interpreter would be written in C. > And, depending on the implementation, the built-in list operations may > well be much more basic than those in Python, for instance, meaning > that more of the relatively sophisticated operations will be handled > using interpreted library code. I'm not sure what version of LISP you're talking about here, but modern LISP implementations are actually quite efficient. I've run a web server implemented in Scheme (a Lisp varient) with the equivalent of JSP pages - and I believe performance would compare favorably with the equivalent Java or Python. Not that I'd take on IIS or Apache, but they suffice for many situations. (I know that FranzLisp offers an Enterprise version. But there's too many digits in the price tag for me to bring one home.) I've also written some graphics programs and they performed as well as Java. (again, I wouldn't try to re-implement a 3D video game in it, but it did ok for menus, card games or turtle graphics). Certainly LISP started out as a list processing language, but it's grown up in the last 40 years. The Lisp programmer has access to hashtables, trees and the usual OO tools of inheritance, polymorphism, macros, etc. And, if specialized or high-performance libraries are needed, most Lisp implementations provide for extensions similar in concept to Python's. I'm not pushing a Lisp agenda here - I actually prefer Python - but I don't think people should dismiss Lisp as being a language suitable only (or mainly) for list processing. Russell. From flupke at nonexistingdomain.com Thu Apr 22 17:39:17 2004 From: flupke at nonexistingdomain.com (flupke) Date: Thu, 22 Apr 2004 21:39:17 GMT Subject: python web programming / CMS References: <0kVhc.54316$eB7.29255@newssvr25.news.prodigy.com> Message-ID: <9YWhc.82882$%l7.5377160@phobos.telenet-ops.be> asdf sdf wrote: > > i've only played a bit with Spyce. > > you can use it as plain CGI, or you can use FastCGI or modpython. > your choice. > > you can invoke python scripts which can make database connections. > > database support isn't built into Spyce. you get the python-wrapper > for whatever database you want. a bunch are available. certainly > all the major databases. > > modpython has recently greatly expanded its scope. now it includes > PSP style functionality. also session support. seems to overlap > pretty heavily/maybe subsume what Spyce does. > > i tried asking on the modpython group for a comparison of modpython > PSP v. Spyce PSP, especially in terms on completeness, stability, > scope, etc. > > i triggered an interesting discussion of PSP-style templates, but no > one directly answered my question. > > Be advised also there are other python PSP-style projects out there, > including one named PSP. > > Also I hope you realize none of these projects are a CMS framework of > any sort. They are tools with which you could write your own. > > I assume your CMS requirements are very minimal or you would avoid > trying to reinvent the wheel. Well, i'm assigned a project where i have to choose a intranet sollution and a platform for future webbased tools development. I'm trying to get a clear idea of what is possible. For the moment 2 kinds of setup are considered OpenCMS - JBoss - Apache - Tomcat or Plone - Zope - Apache - Spyce / modpython A have worked with jsp's before so i pretty much know what i could except from the first environment. But python triggered my interest because it's faster to develop code (and clean code) and Plone seems like one of the best opensource CMS around. I know that with OpenCMS, i could make html pages with jsp code inside. Is that also possible in Plone/Zope? I mean having plone process pages with embedded Python through modpython or Spyce? Or is plone going to send the pages to Zope? That's a part that's not yet clear for me. Also, can one use his own python objects in those PSP pages? flupke From has.temp2 at virgin.net Fri Apr 30 10:55:24 2004 From: has.temp2 at virgin.net (has) Date: 30 Apr 2004 07:55:24 -0700 Subject: Is classless worth consideration References: <69cbbef2.0404290259.fd8d71c@posting.google.com> <69cbbef2.0404291209.7a98a799@posting.google.com> Message-ID: <69cbbef2.0404300655.4cc51bbf@posting.google.com> Peter Hansen wrote in message news:... > > Compared to C++, I expect it's a real breath of fresh air. But > > compared to how something like Self does OO, it is indeed hideously > > baroque. > > Oh, now you're qualifying the statement. In comparison to > something less baroque, it's baroque. Fair enough... Merely posting you some meaningful reference points, as I take it by your adjectives you're more from the C++ end of the spectrum. > But at least you say what you think. That counts for > something. :-) > > -Peter > > P.S. You've got an art background, I've got an engineering > background, neither of us has a CS background. Maybe that > ought to tell us how well we're likely to communicate about > software and we can just stop here. ;-) The day that scientists, engineers, programmers and artists start talking to one another, instead of constructing vast impenetrable fortresses to hide behind, is one I _greatly_ look forward to. Where such rampant self-serving cliquery and deeply reactionary conservativism sprung from I don't know, but I do wish it'd hurry up and bog off again. Poor Leonardo must be spinning in his grave. :( From deetsNOSPAM at web.de Thu Apr 29 09:32:02 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Thu, 29 Apr 2004 15:32:02 +0200 Subject: How to find the length of an iterator? References: <1a6oinf1xl5ui$.dlg@thorstenkampe.de> Message-ID: Diez B. Roggisch wrote: > Its the nature of an iterator that it doesn't support anything beyond > access to the current item and signaling when its finished. So if you need > the length, try to get a hold on the underlying connection. s/connection/collection/ Got confused on my new touchstream dvorak keyboard :) -- Regards, Diez B. Roggisch From pythongnome at hotmail.com Tue Apr 20 08:12:00 2004 From: pythongnome at hotmail.com (Lucas Raab) Date: Tue, 20 Apr 2004 12:12:00 GMT Subject: Good Python Tk overview References: Message-ID: "News User" wrote in message news:J13hc.186320$oR5.5397 at pd7tw3no... > I'm comming from the background of being primarily a data processing > programmer (Python) and I'd like to do some GUI stuff for a comercial > project but I have quite a bit of time, nothing too complex but it has > to work on Windows98+ OSX and Solaris so I was thinking Tkinter. I was > wondering if there were some sites with a good overview of the whole > Python +Tk shpeal, I've got some code examples and "Programming Python > 2nd Edition" but that's more of a learn by example, rather than an > overview of concepts. Anyone have a good recommendation? An Introduction to Tkinter by Fredrik Lundh is an excellent place to start. You can find it at: http://www.pythonware.com.library/tkinter/introduction. There's a link to download the file as a PDF for later viewing. From python at rcn.com Sat Apr 17 19:57:44 2004 From: python at rcn.com (Raymond Hettinger) Date: 17 Apr 2004 16:57:44 -0700 Subject: Proposed PEP: Treating Builtins as Constants in the Standard Library Message-ID: <5d83790c.0404171557.3db69f48@posting.google.com> Comments are invited on the following proposed PEP. Raymond Hettinger ------------------------------------------------------- PEP: 329 Title: Treating Builtins as Constants in the Standard Library Author: Raymond Hettinger Status: Pre-PEP Abstract ======== This proposal is to add a private function for treating builtin references as constants and to apply that function throughout the standard library. Motivation ========== The library contains code such as _len=len which is intended to create fast local references instead of a slower global lookups. Though necessary for performance, these constructions clutter the code and are usually incomplete (missing many opportunities). If the proposal is adopted, those constructions could be eliminated from the code base and at the same time improve upon their results in terms of performance. There are currently over a hundred instances of ``while 1`` in the library. They were not replaced with the more readable ``while True`` because of performance reasons (the compiler cannot eliminate the test because True is not known to always be a constant). Conversion of True to a constant will clarify the code while retaining performance. Many other basic Python operations run much slower because of global lookups. In a try/except statement, the matching exception must be re-looked up on every call (whether or not the exception is raised). Similarly, simple identity tests such as ``while input is not None`` require the None variable to be re-looked up on every pass. Builtin lookups are especially egregious because the enclosing global scope must be checked first. These lookup chains devour cache space that is best used elsewhere. In short, if the proposal is adopted, the code will become cleaner and performance will improve across the board. Proposal ======== Add an internal module called _bind.py which contains two functions, bind_builtins() and bind_builtins_and_globals(). For each module in the standard library, add a pair of lines near the near of the code:: import _bind, sys _bind.bind_builtins(sys.modules[__name__]) In a few select cases (such as sre_compile) where the module variables are just a collection of constants, the globals will also be converted to constants using bind_builtins_and_globals(). This will not be applied anywhere there would be cause for a user to externally change the value of one of the module variables. Question and Answers ==================== Q. Will this make everyone divert their attention to optimization issues? A. No, it is internal only (not user visible). Also, it reduces the need to think about optimization because it is done automatically. Q. What if the module defines a variable shadowing a builtin? A. This does happen. For instance, True can be redefined at the module level as `True = (1==1)`. The sample implementation below detects the shadowing and leaves the global lookup unchanged. Q. How do you know this works? A. I implemented it, applied it to every module in library, and ran the test suite without exception. Q. Are you the first person to recognize that most global lookups are for values that never change? A. No, this has long been known. Skip provides an especially eloquent explanation in [1]_. Q. Why not make this a public module so that users can optimize builtins or builtins and globals in their own code? A. The ASPN recipe [2]_ is provided for this purpose. It takes a modicum of skill to use correctly and not inadvertently tranform a non-constant. Q. What if I have an overpowering urge to import a library module, write a new shadowing builtin, and insert it into the module's namespace? A. Your problems are less acute than with a module written in C because you can always comment out the automatic binding. Q. More realistically, what if I want to replace the builtins module and supply my own implementations? A. Either do this before importing a module, or just reload the module, or disable _bind.py. Q. How susceptible is this module to changes in Python's byte coding? A. It imports opcode.py to protect against renumbering. Also, it uses LOAD_CONST and LOAD_GLOBAL which are fundamental and have been around forever. That notwithstanding, the coding scheme could change dramatically and this implementation would have to change along with modules like `dis` which also rely on the current coding scheme. Sample Implementation ===================== Here is a sample implementation for _bind.py:: from types import ClassType, FunctionType from opcode import opmap, HAVE_ARGUMENT, EXTENDED_ARG LOAD_GLOBAL, LOAD_CONST = opmap['LOAD_GLOBAL'], opmap['LOAD_CONST'] __all__ = ['bind_builtins', 'bind_builtins_and_globals'] def bind(f, builtin_only=True): """ Return a new function with global references converted to constants. If builtin_only is True (the default), will convert all builtin references unless they have been overridden in the function's globals. If builtin_only is False, will also convert other module variable references into constants. """ import __builtin__ env = vars(__builtin__).copy() if builtin_only: stoplist = f.func_globals # do not replace overridden builtins else: stoplist = {} env.update(f.func_globals) co = f.func_code newcode = map(ord, co.co_code) newconsts = list(co.co_consts) codelen = len(newcode) i = 0 while i < codelen: opcode = newcode[i] if opcode == EXTENDED_ARG: return f # handle only the simple cases if opcode == LOAD_GLOBAL: oparg = newcode[i+1] + (newcode[i+2] << 8) name = co.co_names[oparg] if name in env and name not in stoplist: value = env[name] try: pos = newconsts.index(value) except ValueError: pos = len(newconsts) newconsts.append(value) newcode[i] = LOAD_CONST newcode[i+1] = pos & 0xFF newcode[i+2] = pos >> 8 i += 1 if opcode >= HAVE_ARGUMENT: i += 2 codestr = ''.join(map(chr, newcode)) if codestr == co.co_code: return f # no changes were found codeobj = type(co)(co.co_argcount, co.co_nlocals, co.co_stacksize, co.co_flags, codestr, tuple(newconsts), co.co_names, co.co_varnames, co.co_filename, co.co_name, co.co_firstlineno, co.co_lnotab, co.co_freevars, co.co_cellvars) return type(f)(codeobj, f.func_globals, f.func_name, f.func_defaults, f.func_closure) def bind_all(module_or_class, builtin_only=True): """Recursively apply bind() to functions in a module or class. Use as the last line of the module (after everything is defined, but before test code or lines defining shorthand references to functions. If builtin_only is True (the default), will convert all builtin references unless they have been overridden in the function's globals. If builtin_only is False, will also convert other module variable references into constants. This should only be used in modules where the values of the module variables are truly constant. """ for k, v in vars(module_or_class).items(): if type(v) is FunctionType: newv = bind(v) setattr(module_or_class, k, newv) elif type(v) in (type, ClassType): bind_all(v, builtin_only) import sys bind_all(sys.modules[__name__], False) # Binder, bind thyself! # Self-documenting API (eliminates the builtin_only switch) bind_builtins = bind_all bind_builtins_and_globals = lambda m: bind_all(m, False) The final code should have some minor embellishments: * Automatic detection of a non-CPython environment that does not have bytecodes. In that situation, the bind functions would simply return the original function unchanged. This assures that the two line additions to library modules do not impact other implementations. * Add a few lines to handle reading and writing of EXTENDED_ARG. While this almost never arises in practice, it is best to have the code as adaptable as possible. References ========== .. [1] Optimizing Global Variable/Attribute Access http://www.python.org/peps/pep-0266.html .. [2] ASPN Recipe for a non-private implementation http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/277940 Copyright ========= This document has been placed in the public domain. .. Local Variables: mode: indented-text indent-tabs-mode: nil sentence-end-double-space: t fill-column: 70 End: From rook_5150 at yahoo.com Mon Apr 12 23:11:30 2004 From: rook_5150 at yahoo.com (Bryan Castillo) Date: 12 Apr 2004 20:11:30 -0700 Subject: Escaping characters in MySQLdb query References: Message-ID: <1bff1830.0404121911.1dc9a9dc@posting.google.com> "Sean Berry" wrote in message > > I wrote a little script that is inserting thousands of records into a > mysql > > database. > > > > How do I escape characters like ' in my insert statements? > > > > I have something like the following (much shorter) example: > > > > c.execute("INSERT INTO records (var1, var2) values ('%s', '%s')" > %(value1, > > value2)) > > > > My problem is when value1 is something like "Tom's auto supply". The ' in > > Tom's needs to be escaped. How can I do this? Python 2.3.3 (#51, Dec 18 2003, 20:22:39) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import MySQLdb >>> print MySQLdb.escape_string.__doc__ escape_string(s) -- quote any SQL-interpreted characters in string s. Use connection.escape_string(s), if you use it at all. _mysql.escape_string(s) cannot handle character sets. You are probably better off using connection.escape(o) instead, since it will escape entire sequences as well as strings. >>> > > > > Thanks. > > > > From deetsNOSPAM at web.de Tue Apr 27 09:27:58 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Tue, 27 Apr 2004 15:27:58 +0200 Subject: Regular Expressions References: Message-ID: ..:: sjf ::.. wrote: > it works as long as any_text_2 and any_text_3 _not_ contains spaces, but > in my files these contain spaces and then this regexp cuts any_text_2 (and > any_text_3) after first space :(( As long as you don't provide better examples, I can't come up with a better solution. I suggest a read: http://catb.org/~esr/faqs/smart-questions.html And while I don't have a problem helping you, people (including me) generally prefer that someone shows that he tries for himself and not only tries to benefit from the helpfulness of other people. So how about trying to figure out how regexes work fer yourself? -- Regards, Diez B. Roggisch From sarah_wang23 at hotmail.com Sat Apr 3 21:52:04 2004 From: sarah_wang23 at hotmail.com (Sarah Wang) Date: 3 Apr 2004 18:52:04 -0800 Subject: Siginificant figures calculating zprob Message-ID: <9405c70f.0404031852.155d17d5@posting.google.com> Hello everyone! I want to calculate zprob(the area under the normal curve) with python and I managed to find a function from the internet. But the problem is that the function calculates the result with only a few significant figures. If I want to get the 20th number of the result(z-prob) what should I do? I want to get the confidence level of "6sigma" and all I get at the moment is "1". I remember that Python's long type has unlimited number of significant figures as long as the memory allows. What about floating point numbers? BTW, I don't have enough knowledge in numerical analysis. Thanks in advance, Sarah Wang p.s. Apologize me if I have made any mistake writing in the posting -- I am not very goot at both English and mathematics. :) From nmkolev at uni-bonn.de Wed Apr 21 10:51:56 2004 From: nmkolev at uni-bonn.de (Nickolay Kolev) Date: Wed, 21 Apr 2004 16:51:56 +0200 Subject: Optimizing a text statistics function Message-ID: Hi all, I am currently writing some simple functions in the process of learning Python. I have a task where the program has to read in a text file and display some statistics about the tokens in that file. The text I have been feeding it is Dickens' David Copperfield. It is really simple - it reads the file in memory, splits it on whitespace, strips punctuation characters and transforms all remaining elements to lowercase. It then looks through what has been left and creates a list of tuples (count, word) which contain each unique word and the number of time it appears in the text. The code (~30 lines and easy to read :-) can be found at http://www.uni-bonn.de/~nmkolev/python/textStats.py I am now looking for a way to make the whole thing run faster. I have already made many changes since the initial version, realising many mistakes. As I do not think of anything else, I thought I would ask the more knowledgeable. I find the two loops through the initial list a bit troubling. Could this be avoided? Any other remarks and suggestions will also be greatly appreciated. Many thanks in advance, Nicky From fredrik at pythonware.com Fri Apr 16 06:28:48 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 16 Apr 2004 12:28:48 +0200 Subject: tear-off buttons for Tkinter Text objects? References: Message-ID: Deacon Sweeney wrote: > Hi. I've embedded some buttons in a Text object, and I would like these > buttons to perform a 'tear-off' of that line when clicked. That is, when the > button is clicked, I would like a new Toplevel to appear with a new Text > object which contains the text. Creating a 'pop-off' button, where the > Toplevel appears at some predetermined (or calculatable) point would be > easy, I'd just create the Toplevel, position it, and pass the info to it. > The difference would be that the 'tear-off' button would automatically > 'grab' the new Toplevel so that it could be easily repositioned in the same > motion of the mouse. this approach should work: - add custom event handlers for button press, mouse motion, and button release. - in the button press handler, register the current mouse coordinates (relative to the root window), create the toplevel, and position it in a suitable location. also grab the mouse pointer (to make sure you get all mouse events) (autograbbing may take care of that, but a little explicitness never hurts) - in the mouse motion handler, calculate the difference between the current mouse position and the last registered position, and move the toplevel accordingly - in the mouse release handler, release the grab (if necessary) From simoninusa2001 at yahoo.co.uk Tue Apr 13 18:54:31 2004 From: simoninusa2001 at yahoo.co.uk (simo) Date: 13 Apr 2004 15:54:31 -0700 Subject: Making urllib2 work with proxy urls References: <84fc4588.0404130351.77a1faf0@posting.google.com> Message-ID: <30260531.0404131454.49adec6d@posting.google.com> pythonguy at Hotpop.com (Anand Pillai) wrote: > My company uses an automatic proxy configuration url of the form > http://server.company.com/department/proxy.pac . > > I have made urllib2 work with normal proxies/firewalls, even the ones > requiring authentication, but I am stuck with this problem. > > I tried getting the actual proxy server IP and configuring urllib2 > with the normal way it works with proxies, but it has not worked > for me. The pac file is usually just a script with the config data for browsers, it will return something like "PROXY http-proxy.mydomain.com:80" I very much doubt urllib2 can actually proces the .pac file. You should be able to open that file and figure out what you need to set the proxy variable to in urllib2 (or your ENVironment). urllib just "automagically" works through proxies, not sure about 2.... From NAVMSE-KAOMAL-HQ01 at kao.com.my Fri Apr 30 04:31:29 2004 From: NAVMSE-KAOMAL-HQ01 at kao.com.my (NAV for Microsoft Exchange-KAOMAL-HQ01) Date: Fri, 30 Apr 2004 16:31:29 +0800 Subject: Norton AntiVirus detected a virus in a message you sent. Message-ID: Norton AntiVirus found the "W32.Netsky.D at mm" virus in the attachment "your_details.pif". The file was Quarantined. Recipient of the infected attachment: Yew, Siak Heng\Inbox Subject of the message: Re: Your details -------------- next part -------------- An HTML attachment was scrubbed... URL: From fumanchu at amor.org Sun Apr 4 13:21:20 2004 From: fumanchu at amor.org (Robert Brewer) Date: Sun, 4 Apr 2004 10:21:20 -0700 Subject: __import__() with packages Message-ID: Marco Herrn wrote: > On 2004-04-04, John Roth wrote: > > m = __import__("spam.eggs") > > eggs = spam.eggs > > > > This will probably also work: > > > > eggs = __import__("spam.eggs").eggs > > Thanks, > but in my application I read the names of the modules from a file, > so I do not know them when writing (in this case I wouldn't know the > name 'eggs'). Since the solution from Paul works for me, I will use > that. Feel free to use my xray tool: http://www.aminus.org/rbre/python/xray.py Robert Brewer MIS Amor Ministries fumanchu at amor.org From peter at engcorp.com Mon Apr 5 08:33:49 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 05 Apr 2004 08:33:49 -0400 Subject: Newbie need help In-Reply-To: References: Message-ID: Tony Ha wrote: > Question from a newbie. > > In the interactive Python shell. > > 1. How do I find out where I am in the file system under WindowXP? > > I try os.curdir, which only give '.' back, I would like a full path > like the Unix 'pwd' give. Cameron answered that. Note that os.curdir isn't even a function call, so it is really just returning "the symbol which represents the current directory in paths". > 2. How do I change directory under WindowXp? > > I try os.chdir('C:\Downloads\Python\SOAPpy-0.11.3\fpconst-0.6.0') > but I get the following Error message: Learn about escape sequences in strings. You have a \f in the above, which translates into an ASCII formfeed character. The other three are all (I believe) "safe" since there is no corresponding escape sequence but that's just luck. Use either a "raw string" (exactly what you wrote above, but with a lowercase r in front of the string as in r'C:\Downloads .....) or switch to using forward slashes as much as possible, since they will work as long as the shell is not going to see your path (which is the case with a simple chdir among many other things). -Peter From spamtrap at nowhere.net Thu Apr 15 08:53:22 2004 From: spamtrap at nowhere.net (Steven) Date: Thu, 15 Apr 2004 13:53:22 +0100 Subject: pyKDE won't build References: <4de76ee2.0404150405.6ac2f50d@posting.google.com> Message-ID: David Boddie wrote: > Steven wrote in message > news:... > Unfortunately, PyKDE 3.8 isn't guaranteed to work with versions of SIP or > PyQt later than SIP 3.8 and PyQt 3.8. A later version of PyKDE which works > with both KDE 3.2 and more recent versions of PyQt and SIP is scheduled > for release in the near future. Meanwhile, you might want to try getting > hold of compatible versions of PyQt and SIP. > This all sounds familiar. You may want to take a look at the PyKDE mailing > list archives at > > http://mats.imk.fraunhofer.de/pipermail/pykde/ > > or even subscribe and repost details of your problem there. > > Hopefully, you won't need to understand Python to get it all working, > although you may wish to look at it more closely once you see what can be > achieved with Python, PyQt and PyKDE. > > David I've now got earlier versions of pyQt and sip, which I'll use until a new version of pyKDE becomes available. Thanks for the info Steven From rjt-usenet at thegrindstone.me.uk Wed Apr 21 05:36:53 2004 From: rjt-usenet at thegrindstone.me.uk (Richard Taylor) Date: Wed, 21 Apr 2004 09:36:53 +0000 Subject: Passing argument to setsockopt(socket.SOL_SOCKET, IN.SO_BINDTODEVICE, intr) Message-ID: <408640b7$0$31671$fa0fcedb@lovejoy.zen.co.uk> Hi Does anyone know the correct way to pass the 'device' argument to setsockopt with the SO_BINDTODEVICE flag? I have tried various methods: setsockopt(socket.SOL_SOCKET,IN.SO_BINDTODEVICE,"eth0") setsockopt(socket.SOL_SOCKET,IN.SO_BINDTODEVICE,inet_aton("eth0")) setsockopt(socket.SOL_SOCKET,IN.SO_BINDTODEVICE,struct.pack("s","eth0")) setsockopt(socket.SOL_SOCKET,IN.SO_BINDTODEVICE,struct.pack("p","eth0")) None of these work. I just get a "socket.error: (19, 'No such device')". I do have an "eth0" device :-) Many thanks Richard From shalabh at cafepy.com Fri Apr 9 20:18:42 2004 From: shalabh at cafepy.com (Shalabh Chaturvedi) Date: Fri, 09 Apr 2004 17:18:42 -0700 Subject: Special Method and Class References: <20040408184749.GA5285@performancedrivers.com> Message-ID: Yermat wrote: > Jack Diederich wrote: >> On Thu, Apr 08, 2004 at 02:47:49PM -0400, Jack Diederich wrote: >> >>>On Thu, Apr 08, 2004 at 08:07:01PM +0200, Yermat wrote: >>> >>>>Hi all, >>>> >>>>Why does special methods not work on class ? Or how to make them work ? > I thought that those special method were bounded methods but they are > not... > > >>> class toto(object): > ... def __init__(self, name): > ... self.name = name > ... def __repr__(self): > ... return "toto('%s')" % self.name > ... > >>> > >>> t = toto('titi') > >>> repr(t) > "toto('titi')" > >>> t.__repr__ > > >>> t.__init__ > Are you sure you haven't left anything out (like a t.__repr__ = anotherRepr line somewhere ;) ? On my machine I get: >>> class C(object): ... def __repr__(self): ... return 'C inst' ... >>> c = C() >>> c.__repr__ >>> Yup it's a bound method for sure. > That also mean that I can't change the __repr__ for only one instance : > >>> def anotherRepr(self): > ... return "anotherRepr('%s')" % self.name > ... > >>> > >>> t.__repr__ = anotherRepr > >>> > >>> repr(t) > "toto('titi')" > > > Is it really consistent ? > Should'nt it be also bounded methods even for clas instead of using > MetaClass ? Actually this has less to do with bound methods and more to do with how repr() works. Simple formula for new-style objects: repr(x) calls x.__class__.__repr__(x) so repr(C) will call C.__class__.__repr__(C) which is really type.__repr__(C). Also, repr(c) will call c.__class__.__repr__(c), which is really C.__repr__(c). If both repr(C) and repr(c) called C.__repr__(), *that* would be inconsistent (how would one implement C.__repr__()? for the instance or the class?). A simple solution to be able to override special methods on instances might be to do (not tested): class C(object): def __repr__(self): instrepr = getattr(self, '_instrepr', None) if instrepr: return instrepr(self) else: return "default repr" and then define a function (like anotherRepr above) and assign it to c._instrepr. > Yermat HTH, Shalabh From fma at doe.carleton.ca Tue Apr 13 16:49:36 2004 From: fma at doe.carleton.ca (Fred Ma) Date: 13 Apr 2004 20:49:36 GMT Subject: Once-only evaluation of default parameter values function definitions References: <407B79D7.424F65A1@doe.carleton.ca> Message-ID: <407C5259.E04E87C0@doe.carleton.ca> Brian, Sean, Thanks for the clarification and example. I'll need a bit more time to get my head around the example, but I'm pretty clear about what's happening in the situation of default values for function arguments, as well as the idiom to avoid sharing default values across function calls. Fred -- Fred Ma Dept. of Electronics, Carleton University 1125 Colonel By Drive, Ottawa, Ontario Canada, K1S 5B6 From nicksjacobson at yahoo.com Thu Apr 29 18:03:24 2004 From: nicksjacobson at yahoo.com (Nick Jacobson) Date: 29 Apr 2004 15:03:24 -0700 Subject: static keyword References: Message-ID: Yes, that is excellent. Thank you very much. :) The good news: you can reset all your "static" data whenever you want, by calling foo(). Can't do that in C. The bad news: I just hope I don't forget and call foo() instead of g.next(). I would rather the command foo() by default call the next iteration, and, say, foo().reset() would recall the function from scratch. But that's neither here nor there.. "Robert Brewer" wrote in message news:... > Nick Jacobson wrote: > > I believe the following "static" command would be useful in Python. > > > > def foo(): > > static i = [10, 11] > > static firstcall = True > > if firstcall: > > print "First pass" > > firstcall = False > > i[0] += 1 > > print i[0] > > foo() > > foo() > > > > > > This would output: > > > > First pass > > 11 > > 12 > > Bah. All these old fogies with their default arg hacks, when Nick > *clearly* wants a generator: > > >>> def foo(): > ... i = 10 > ... print "First pass" > ... while True: > ... i += 1 > ... yield i > ... > >>> g = foo() > >>> g.next() > First pass > 11 > >>> g.next() > 12 > > > Robert Brewer > MIS > Amor Ministries > fumanchu at amor.org From agriff at tin.it Sun Apr 25 19:12:40 2004 From: agriff at tin.it (Andrea Griffini) Date: Sun, 25 Apr 2004 23:12:40 GMT Subject: Andreas' practical language comparison References: <408c23b8$0$41746$5fc3050@dreader2.news.tiscali.nl> Message-ID: <5ago80thlgfrsrapol1lldi2cq0uulto4n@4ax.com> On Sun, 25 Apr 2004 22:46:48 +0200, "GerritM" wrote: >I really would like to see the linecount. I do belive that it is one of the >indicators of the power of the language and its batteries. Then at least you should be talking of the same problem and of the same solution to the problem. For example the Delphi solution for the 8 queens problem is completely different from the ALGOL one (and I must say IMO the Delphi solution is quite terrible from an algorithm point of view), comparing a linecount for that that with a linecount for a totally different solution is just nonsense. However this create problems for very different approaches; implementing a certain algorithm in prolog and comparing it with the same algorithm in C has any meaning ? If say one solution uses generators (may be heavily and with backtracking, for example in Icon) how can you implement the same solution on a language that has no generator concept at all ? Even if you manage to do that, what's the point in finding that you needed a lot of lines of code to do it ? >Somehow it would be nice to have a figure for "readability", but I >don't have a clue how to generate such a figure in an automatic way. >Maybe you need some panel of experts that gives a readability figure? I'm very new to python, but anyway this is my solution to 8 queen's problem: ------------------------ PYTHON -------------------------- import sets def solve(base, # starting position, as a list of cols free_cols, # list of columns not yet taken free_diag1, # list of diagonals not yet taken free_diag2): # list of counter diagonals not yet taken if free_cols: row = len(base) for i,col in enumerate(free_cols): d1 = row + col d2 = row - col if d1 in free_diag1 and d2 in free_diag2: solve(base+[col], free_cols[0:i]+free_cols[i+1:], free_diag1.difference([d1]), free_diag2.difference([d2])) else: print base n = 8 solve([], range(1,n+1), sets.Set(range(1+1,n+n+1)), sets.Set(range(1-n,n-1+1))) ----------------------------------------------------------- and this is a solution to the same problem I wrote in C some time ago while having fun in trying to use as few characters as possible... ----------------------- C ------------------------------- char n[39],q=7;void s(){char*x=n+7,*e,*d;while((*x+*( e=x+9+q)+*(d=x+31-q)?0:(*x=*e=*d='1'+q,q--?s(),1:puts (n),q++,*x=*e=*d=0))|x--!=n);}main(){s();return 0;} --------------------------------------------------------- Does this mean that Python is less expressive ? that C is less clear ? Or just means one program has been written trying to be expressive and the other trying to be compact ? If I run that Delphi solution for the 8 queens problem should I conclude that Python is faster than Delphi ? Andrea From theller at python.net Tue Apr 6 10:08:40 2004 From: theller at python.net (Thomas Heller) Date: Tue, 06 Apr 2004 16:08:40 +0200 Subject: GUI Frameworks in Python? References: <930ba99a.0404030246.786455f5@posting.google.com> <8ef9bea6.0404041009.26ae2683@posting.google.com> Message-ID: > Hung Jung Lu wrote: >> Can someone outline some differences/advantages of PyGTK vs. wxPython? > Greg Ewing : > Having had an intensive experience with both recently, I > can give you some of my impressions. > > I started a project using wxPython, having heard good things > about it. At first it seemed all right, but as things progressed > I found myself becoming more and more frustrated with it. > Everything seemed to be just a little more complicated than > it needed to be, and I kept on running into bugs, limitations and > strange behaviours that I had to work around. > > As an experiment, I tried re-writing it to use PyGtk, to find > out what it would be like. It turned out to be a much more > pleasant experience. The wrapping is very straightforward and > Pythonic, and everything Just Works the way I expect. I've > yet to encounter a single bug or unreasonable limitation. > >> A first look at PyGTK shows me a more Unix-like look-and-feel. On the >> other hand, wxPython on Windows does look very much like any other >> Windows applications. > > It doesn't look quite the same as native apps on Windows, but > for my purposes it's close enough. If precise Windows authenticity > is important to you, you might have to use wxPython or something else > that uses native Windows widgets. I still think that a native windows toolkit written in pure Python, based on venster, maybe, with a 'pythonic' api on top would be a killer. Thomas From edcogburn at hotpop.com Thu Apr 1 07:22:04 2004 From: edcogburn at hotpop.com (Ed Cogburn) Date: Thu, 01 Apr 2004 07:22:04 -0500 Subject: Python Documentation Blows! In-Reply-To: References: <20040330181802.04141.00000304@mb-m17.aol.com> Message-ID: Peter Hansen wrote: > anton muhin wrote: > >> Maybe just start a wiki based on the current documentation? It >> shouldn't be too difficult, should it? > > > What part of http://wiki.wxpython.org/ is not adequate? ;-) The poster is referring to Python, not wxPython. I like the idea myself very much. My biggest problem with the official Python docs, is that there is too much space wasted on formal definitions and not enough space on actual examples using valid code. To anyone without a complete and formal CS education, the use of the formal syntax to specify Python's syntax amounts to describing one new language using another new language - not exactly helpful. :) An 8 to 10 line example is worth a page of BNF (or whatever), IMO, and the difference is that the simple but real-world example works just as well for the CS graduate as it does for the hobbyist programmer. A wiki site for this would have meant I could have provided some example code for the things I had trouble with, once I figured them out myself, it would at least make it easier for a lot more people to participate on the creation of Python's docs. I like Python very much, but the truth is, had it not been for the 2 third-party books on Python that I have (Bible and Complete Reference), I might not be using Python now. From herrn at gmx.net Sun Apr 4 10:04:29 2004 From: herrn at gmx.net (Marco Herrn) Date: 4 Apr 2004 14:04:29 GMT Subject: Difference between default arguments and keyword arguments References: <406FFEAF.3080400@netscape.net> Message-ID: On 2004-04-04, DoubleM wrote: > All arguments are keyword arguments. They may or may not have a default > value. In your example, voltage is a keyword argument, but it has no > default. But what does this mean?: >>> __import__(name="eggs") Traceback (most recent call last): File "", line 1, in ? TypeError: __import__() takes no keyword arguments Is it because the other arguments are optional? The function is defined as follows: __import__( name[, globals[, locals[, fromlist]]]) Marco -- Marco Herrn herrn at gmx.net (GnuPG/PGP-signed and crypted mail preferred) Key ID: 0x94620736 From FBatista at uniFON.com.ar Mon Apr 26 11:27:30 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Mon, 26 Apr 2004 12:27:30 -0300 Subject: how to add new print %b format to python? Message-ID: [Rusty Shackleford] #- part is done, but where do I go to tinker with the python #- interpreter to #- add this new format? You can download the source code from SourceForge with anonymous CVS or browse it at: http://cvs.sourceforge.net/viewcvs.py/python/python/dist/src/ #- Please don't argue with me about whether this is an advisable goal in #- itself -- I'm using it as a method to learn about the #- internals of the #- python language. I think this would be a nice thing to have. The best you can do is write a PEP to propose the change. If a lot like it, this will be in the language in the future. . Facundo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA La informaci?n contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener informaci?n confidencial o propietaria, cuya divulgaci?n es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no est? autorizado a divulgar, copiar, distribuir o retener informaci?n (o parte de ella) contenida en este mensaje. Por favor notif?quenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magn?tico) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telef?nica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electr?nicos pueden ser alterados, motivo por el cual Telef?nica Comunicaciones Personales S.A. no aceptar? ninguna obligaci?n cualquiera sea el resultante de este mensaje. Muchas Gracias. -------------- next part -------------- An HTML attachment was scrubbed... URL: From maxm at mxm.dk Thu Apr 15 03:27:07 2004 From: maxm at mxm.dk (Max M) Date: Thu, 15 Apr 2004 09:27:07 +0200 Subject: Aspect Programming Module In-Reply-To: <8ef9bea6.0404142155.90b41ef@posting.google.com> References: <84fc4588.0404140106.3fa0c55@posting.google.com> <8ef9bea6.0404142155.90b41ef@posting.google.com> Message-ID: <407E394B.2050709@mxm.dk> Hung Jung Lu wrote: > Python does not even have codeblocks. So how can you say AOP is not > needed for Python programmers? I am probably rather dense, but I have not seen aspect oriented examples that could not have been done with simple mixins. Isn't it needed in Java because it doesn't have multiple inheritance? regards Max M From ramagnus at t-online.de Sat Apr 24 19:57:32 2004 From: ramagnus at t-online.de (Rolf Magnus) Date: Sun, 25 Apr 2004 01:57:32 +0200 Subject: python extension, -pthreads and speed References: <4fd1aa5e.0404222336.2a1347a8@posting.google.com> Message-ID: Pedro Rodriguez wrote: > If your extension use IOs (fgets, sprintf...) or others standard > library calls, they may be affected by the fact that Python is build > with multithreading enabled, on so all those API start using mutexes > to be thread safe, thus the extract cost. Another candidate for such slowdowns is malloc. From chrish at cryptocard.com Tue Apr 6 08:40:18 2004 From: chrish at cryptocard.com (Chris Herborth) Date: Tue, 06 Apr 2004 08:40:18 -0400 Subject: Does Python compete with Java? In-Reply-To: References: <8b336527.0404051337.51bb4a1b@posting.google.com> <1073su4etm95p35@news.supernews.com> Message-ID: Harald Massa wrote: > Roy Smith wrote in news:roy-094613.21022405042004 > @reader1.panix.com: > >>http://www-users.cs.york.ac.uk/~susan/joke/foot.htm > >>They don't have one for Python, but I expect it would be something like >>this: > > I think the most common solution is: > >>How to Shoot Yourself In the Foot > > Python > you discover that Guido used his time machine to shoot you in the foot > years ago My experience: Post to comp.lang.python: "I'm looking for a good scripting language, and Python's got some great features, but that syntactically-relevant whitespace thing just seems wrong..." Replies: "Don't worry about it, in practice you'll see that you write code that way anyway and it's very natural..." Me: "I don't know..." [Wanders off for a few months. Returns.] "Python rules! Best scripting language EVAR!" -- Chris Herborth chrish at cryptocard.com Documentation Overlord, CRYPTOCard Corp. http://www.cryptocard.com/ Never send a monster to do the work of an evil scientist. Postatem obscuri lateris nescitis. From aku at europe.com Wed Apr 7 05:26:33 2004 From: aku at europe.com (aku) Date: 07 Apr 2004 09:26:33 GMT Subject: design by contract versus doctest References: <407174ea$0$5066$4d4ebb8e@news.nl.uu.net> <4072977b$0$1699$afc38c87@news.easynet.co.uk> <4072a7d3$0$23314$afc38c87@news.easynet.co.uk> Message-ID: <4073c949$0$5066$4d4ebb8e@news.nl.uu.net> On 2004-04-06, Colin Blackburn wrote: > > Getting the require section to pass is no guarantee that the > > post-conditions (ensure section) will be met, the do section is code > > like anything else and may get things wrong. > > In correctly developed DbC that is precisely what is guaranteed. The > post-condition is *guaranteed* if the pre-condition is met. Exactly! postcondition is guaranteed if precondition is true. And in addition to that - and that was part of what I was trying to say in the original post - in www.python.org/doc/current/lib/module-doctest.html, the 3 tests after the line "import math" shouldn't be necessary because they should be part of the precondition in the doc string if DBC was applied. From ed-no at spam-eepatents.com Sat Apr 24 13:29:28 2004 From: ed-no at spam-eepatents.com (Ed Suominen) Date: Sat, 24 Apr 2004 10:29:28 -0700 Subject: [ANN] XPN 0.2.6 References: <7kbd6c.fu1.ln@nemesis.homeinvalid> Message-ID: I was very impressed by this application. It's a great testimony to the power of Python. -Ed Suominen Nemesis wrote: > XPN is a newsreader written in Python+GTK with unicode support. > > Major Changes in this release: > > *Added Import/Export newsrc file. > *Added autoencode feature. Now XPN automatically chooses the best > encodig for outgoing articles. > *Fixed another bug in threads building > > Links: > http://sf.net/projects/xpn > http://xpn.altervista.org (italian) > From arigo at tunes.org Sat Apr 3 19:59:40 2004 From: arigo at tunes.org (Armin Rigo) Date: Sun, 4 Apr 2004 00:59:40 +0000 (UTC) Subject: Python is faster than C References: <406F0907.96F37EA1@tunes.org> Message-ID: <406F6020.F1361B55@tunes.org> Hi, Joe Mason wrote: > > The reason is that the C implementation must use a generic '<' operator > > to compare elements, while the Psyco version quickly figures out that it > > can expect to find ints in the list; it still has to check this > > assumption, but this is cheap and then the comparison is done with a > > single machine instruction. > > Why can't the C implementation do the same thing? You could, if you wanted to optimize specifically lists of integers. If you did the result would probably be really fast. The problem is that you can only really special-case so many types: the C code has to deal with all cases without knowing which cases are likely. The Psyco version quickly figures out that for this list it pays off to make a special case for integers; with another list, the machine code would be different, special-cased differently. However, in most real examples, you are not sorting a list of integers but of something more complex anyway, where the built-in sort wins easily. My message was intended as a long-term hint that maybe, at some point, the built-in sort will actually be more often faster than the C one if rewritten in Python. The advantage would then be that (as Psyco does in a limited fashion) you can specialize the code for the particular kind of list you are dealing with. Armin From pxlpluker at cfl.rr.com Fri Apr 30 16:58:30 2004 From: pxlpluker at cfl.rr.com (pxlpluker) Date: Fri, 30 Apr 2004 16:58:30 -0400 Subject: ms compiler Message-ID: <4092BDF6.6040008@cfl.rr.com> sense M$ has just realesed there C++ compiler as a free download is python compilable with it. I am just C stupid. fred From rnichol_rrc at yahoo.com Sun Apr 18 00:32:01 2004 From: rnichol_rrc at yahoo.com (Reid Nichol) Date: Sat, 17 Apr 2004 23:32:01 -0500 Subject: os.system help In-Reply-To: References: <78lgc.3445$AL1.7744@news1.mts.net> Message-ID: Unfortunately PIL only writes .eps files. I was going to get the users to install gs but of course it's install directory is variable. I've tried using shortcuts but that didn't work. Since most of my intended users use windows only... Grzegorz Dostatni wrote: > Cheers. > > In short ghostscript is not installed by default on windows. You can > install it yourself (http://www.cs.wisc.edu/~ghost/doc/AFPL/get814.htm) > and install. You could also try to package it in your program somehow (for > example including the binary in your program directory). I'm not sure if > it will work properly though. > > I don't think there is anything installed by default on windows that can > read .ps files. > > You could also try another approach. I am not entirely sure, but I think > that Python Imaging Library supports writing/reading .ps files. > > Greg > > > > Advice is what we ask for when we already know the answer but wish we > didn't. > -- Erica Jong (How to Save Your Own Life, 1977) > > > On Sat, 17 Apr 2004, Reid Nichol wrote: > > >>Hello, >> I have made a program that works wonderfully on OpenBSD but it uses >>os.system to get ghostscript to convert ps to jpeg. But, I wish this >>program to run on Windows as well. Is there any way I can snag where >>the gs executable is on Windows? What it is named? And so forth. >> >> > > From rjgruet at yahoo.com Sat Apr 10 20:04:41 2004 From: rjgruet at yahoo.com (Richard Gruet) Date: Sun, 11 Apr 2004 02:04:41 +0200 Subject: new-style class instance check References: Message-ID: Robert Thank you for your suggestion. But unfortunately, isNewStyleClassInstance(o) must return False for *everything but* an instance of a new-style class. If o is e.g. a function: def foo(): pass foo.__class__.rmo so isNewStyleClassInstance(foo) would return True ! Richard "Robert Brewer" wrote in message news:mailman.516.1081639807.20120.python-list at python.org... Richard Gruet wrote: > How to determine that an object o is for sure an instance of > a new-style > class, without knowing of which specific class ? > That is, if I define a function: > > def isNewStyleClassInstance(o): > pass ## to be completed > > .. I want to pass the following test: > > def C: pass > def CNew(object): pass I assume you meant "class C" instead of "def C" ;) If it's new-style, it'll have an "mro" attribute: >>> class OldStyle: pass ... >>> class NewStyle(object): pass ... >>> NewStyle.mro >>> NewStyle.mro() [, ] >>> OldStyle.mro() Traceback (most recent call last): File "", line 1, in ? AttributeError: class OldStyle has no attribute 'mro' Hope that helps, Robert Brewer MIS Amor Ministries fumanchu at amor.org From eric_brunel at despammed.com Tue Apr 27 03:59:17 2004 From: eric_brunel at despammed.com (Eric Brunel) Date: Tue, 27 Apr 2004 09:59:17 +0200 Subject: Question on creating Tkinter Widgets References: Message-ID: Adonis wrote: > I am creating some widgets by inheriting from Tkinter.Frame and populating > the frame with whatever the widget will be then creating certain > attributes/methods to be accessed later. My question is, is this a poper way > to create widgets or should I take a different approach? > > Any help is greatly appreciated. > > Adonis Most Tkinter "megawidgets" are created by either specializing Tkinter.Frame or Tkinter.Canvas, so it seems to be the way to go. It has at least a major advantage: the widgets you create directly inherit the basic behaviour of all Tkinter widgets, so you can directly pack them, grid them, or whatever else, without having a single line of code to write. I made some Tkinter widgets myself and always used this approach; up to this time, it worked pretty well. HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From fumanchu at amor.org Tue Apr 13 23:23:09 2004 From: fumanchu at amor.org (Robert Brewer) Date: Tue, 13 Apr 2004 20:23:09 -0700 Subject: Simple discussion of python cgi approaches? Message-ID: Kylotan wrote about mod_python: > Yet I'm guessing it requires a significant amount of special-case code > to > use its own API? Looking at the manual it seems non-trivial to get it > to work with scripts that were originally written to consume stdin and > emit to stdout. Then later... > The main problem I face is that I don't know what platform my scripts > will > eventually run on. I may not have the ability to install extra > software so I > need to keep my scripts close to the CGI standard. That is, one file > per script, > using the cgi module for form processing and print for output. I don't > mind > having to redirect stdout or call these scripts indirectly instead of > via > their __main__ functions, but writing to specific APIs (beyond a small > wrapper > layer, of course) is not an option at the moment. The wrappers can be quite small. Have a look at my small wrappers for ASP/IIS and mod_python/Apache (which I just dicovered is the first Google hit for "IIS mod_python" ;) http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/225299 I write apps that drop in on either platform. I often test by turning on Apache, running the site for a while, then turn off Apache, turn on IIS, and keep going. Total downtime--about 15 seconds. Robert Brewer MIS Amor Ministries fumanchu at amor.org From ramen at lackingtalent.com Fri Apr 30 13:52:03 2004 From: ramen at lackingtalent.com (Dave Benjamin) Date: Fri, 30 Apr 2004 17:52:03 -0000 Subject: Simple prototyping in Python References: <69cbbef2.0404300855.20dd436b@posting.google.com> Message-ID: In article <69cbbef2.0404300855.20dd436b at posting.google.com>, has wrote: > Dave Benjamin wrote in message news:... >> The recent conversation on prototype-based OOP and the Prothon project has >> been interesting. I've been playing around with the idea for awhile now, >> actually, since I do a lot of programming in JavaScript/ActionScript. I feel >> like people are focusing too much on the "prototype chain", which to me is >> mainly an attempt at reintroducing inheritance. > > It doesn't even do that; at least not in the sense that class-based OO > defines it, where inheritance merely describes the initial state for > every object created from a class. But that is how it is used, anyway. See any textbook describing OO programming in JavaScript. The caveats are also typically described, and other hacks like the "__proto__" attribute (which is the object's prototype object, not to be confused with the constructor's prototype object, "prototype") are used to exercise more control (or confusion) over the matter. > In a proto-OO system all objects are _completely_ anonymous*, having > no 'class' and all being of the same type, 'object'. In this respect, > they're just like strings, lists, dicts, or any other 'anonymous' > type; a list is a list is a list, for example, regardless of how it is > used. Not necessarily. In JavaScript, you can still do "instanceof", for example. >> JavaScript has a syntax >> for this: >> >> var o = {a: 5, b: 6} > > Looks on the surface like AppleScript's record type, which is roughly > analogous to C structs... and useless for anything more than > struct-style usage. While I did read about JS programming in the > dim-n-distant past - it was one of a number of languages I looked at > when learning proto-OO on AS, which lacked any decent learning > material on the topic - I've pretty much forgotten everything since. > So can I ask: is the JS structure more flexible; e.g. can one add > functions to it to operate like methods on the other data in the > structure? Or does it have to provide a second structure for proto-OO > use, as AS does? Sure! JavaScript supports function literals that are true closures. In fact, this feature can be used to support private data, which has been described in some detail by Douglas Crockford, here: http://www.crockford.com/javascript/private.html The same technique can be accomplished by Python, though it'd be really nice to have code blocks or function literals that accept statements. -- .:[ dave benjamin: ramen/[sp00] -:- spoomusic.com -:- ramenfest.com ]:. : please talk to your son or daughter about parametric polymorphism. : From roy at panix.com Thu Apr 15 17:32:59 2004 From: roy at panix.com (Roy Smith) Date: Thu, 15 Apr 2004 17:32:59 -0400 Subject: CamelCase versus wide_names (Prothon) References: <407ec022$0$54153$1b2cd167@news.wanadoo.nl> Message-ID: Jan Dries wrote: > But when someone claims 100% of Python users > want camelCase, I cannot but speak up. I hope this doesn't turn into a flame war, but I agree with Jan. One of my pet peeves is expressing a minority opinion ("I want X") and then hearing my opinion dismissed with a statement like "Everybody wants Y". I'm willing to be outvoted, but I sure won't stand for being ignored. I happen to be one of the people who expressed the majority opinion, i.e. in favor of DromiDaryOrthoGraphy, but it's still unfair to say that 100% of Python users agree with me. From imbosol at aerojockey.com Wed Apr 28 21:54:13 2004 From: imbosol at aerojockey.com (Carl Banks) Date: 28 Apr 2004 18:54:13 -0700 Subject: Is Perl *that* good? References: <108v74768o9sb9f@corp.supernews.com> <60dfb6f6.0404281459.21675af4@posting.google.com> Message-ID: <60dfb6f6.0404281754.473deae9@posting.google.com> imbosol at aerojockey.com (Carl Banks) wrote in message news:<60dfb6f6.0404281459.21675af4 at posting.google.com>... > In file x.pl: > > sub muck() { > $_ = "sucker\n"; > } > > while(<>) { > if (/^abc/) { > muck(); > print $_; > } > } > > Command line: > > echo abcdefg | perl x.pl > > Output: > > sucker > > > I had actually thought it restored $_. > It never ceases to amaze me how bad Perl is. Wait a minute, Perl does restore the regexp implicits. In file x.pl: sub muck() { $_ = sucker; /sucker/; } while(<>) { if (/^abc/) { muck(); print $&; print "\n"; } } Command line: echo abcdefg | perl x.pl Output: abc Perl has failed to amaze me at just how bad it is this one time. :) -- CARL BANKS From deetsNOSPAM at web.de Wed Apr 28 12:34:35 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Wed, 28 Apr 2004 18:34:35 +0200 Subject: PyChecker does STATIC analysis? References: <3064b51d.0404280728.5fb7539e@posting.google.com> Message-ID: Diez B. Roggisch wrote: >>> xrange = lambda x: [1,2,3,4,5] Oops - that was supposed to be range = lambda x: [1,2,3,4,5] of course... I'm so used to prefering xrange over range, I confused myself... -- Regards, Diez B. Roggisch From NAIGIMSESRIMAIL at gims.com Wed Apr 7 04:46:59 2004 From: NAIGIMSESRIMAIL at gims.com (GroupShield for Exchange (ESRIMAIL)) Date: Wed, 7 Apr 2004 10:46:59 +0200 Subject: ALERT - GroupShield ticket number OB87_1081327614_ESRIMAIL_3 was generated Message-ID: Action Taken: The message was blocked because of its subject. To: python-list at python.org From: jason willows Sent: -499706240,29629564 Subject: test Attachment Details:- Attachment Name: N/A File: Infected.msg Infected? No Repaired? No Blocked? Yes Deleted? No Virus Name: -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/ms-tnef Size: 1809 bytes Desc: not available URL: From solution88pro at hotmail.com Mon Apr 5 04:34:34 2004 From: solution88pro at hotmail.com (Senthoorkumaran Punniamoorthy) Date: Mon, 05 Apr 2004 14:34:34 +0600 Subject: Can someone give me a short explanation? Message-ID: I found this code in the book text processing with Python. But having little difficulty understanding how exactly it works and what should be passed as argument? Can someone decode this for me please? apply_each = lambda fns, args=[]: map(apply, fns, [args]*len(fns)) Senthoor _________________________________________________________________ STOP MORE SPAM with the new MSN 8 and get 2 months FREE* http://join.msn.com/?page=features/junkmail From amk at amk.ca Fri Apr 23 09:20:59 2004 From: amk at amk.ca (A.M. Kuchling) Date: Fri, 23 Apr 2004 08:20:59 -0500 Subject: Why we will use obj$func() often References: <84Uhc.22278$dZ1.5087@fed1read04> <8AWhc.23114$dZ1.11070@fed1read04> <40883BFE.B381518A@alcyone.com> <27_hc.23801$dZ1.2716@fed1read04> <40887145.789A2FE8@alcyone.com> Message-ID: On Thu, 22 Apr 2004 18:28:37 -0700, Erik Max Francis wrote: > Being a fan of Io, I think prototype-languages are interesting. Even so > far, I lost interest in looking at the actual main feature of Prothon, > after seeing all the extra baggage that was brought on in unecessary > stylistic changes. There's a rule in experiments that you should only change one thing at a time, trying to answer a single question with each change. Prothon started out asking two questions: * Does implementing an interpreter on top of the Apache Portable Runtime for the sake of free threading work? (Presumably the answer is yes, since Prothon does run. I haven't seen performance numbers on Prothon, though.) * Is prototyping a workable replacement for a class-based object system? Unclear, since I don't know that anyone has written sizable systems in Prothon yet. The problem is that if you then make a whole bunch of additional changes -- a 'with' statement, changing the rules for indenting, changing the names of various built-in methods -- it becomes harder for Python users to try out the new language for a while because there are more changes they have to cope with. After a certain point the number of crossover users dwindles to near-zero. None of these changes is critical or results in a 100% improvement in functionality (or even a 10% one), but their collective effect is to make the distance too great to cross conveniently; you might as well start a new language with a blank sheet of paper at that point. --amk From herrn at gmx.net Sun Apr 4 07:30:17 2004 From: herrn at gmx.net (Marco Herrn) Date: 4 Apr 2004 11:30:17 GMT Subject: user authentication via /etc/passwd|/etc/shadow Message-ID: Hi, I want to write a program where I authenticate users via the standard unix system accounts. I didn't find a module providing this functionality. Is there such a module available? If not, how can I achieve this? Marco -- Marco Herrn herrn at gmx.net (GnuPG/PGP-signed and crypted mail preferred) Key ID: 0x94620736 From deetsNOSPAM at web.de Tue Apr 27 14:31:19 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Tue, 27 Apr 2004 20:31:19 +0200 Subject: Implement new editing format/through-the-web site management? References: <997a06e0.0404270805.72b15909@posting.google.com> Message-ID: pugnatio2 at yahoo.com wrote: > Hi, > > I'm a Zope newbie but an experienced Python programmer. Could someone > suggest a general approach for the two parts below? > > 1) I'd like to build a system that stores XML documents in the ZODB > and allows them to be edited through the web in a new text format. The > format is similar to StructuredText and can be translated to XML and > vice versa, using Python methods. > > 2) The second part of system would be to maintain the site map as an > XML document, also in the ZODB, and allow it to be edited using a > tree-like HTML form or javascript interface, so that the structure of > the entire site could be managed interactively from a single page. > Elements in the site map XML would point to the IDs of XML objects > stored in the ZODB. These pointers could be moved around by editing > the site map. The Zope folder hierarchy would not drive the structure > of the site, the XML document would. > afaik zope has a xml-export/import facility that might you help on this. The zms publishing system abstracts from this and offers a even simpler format. Thus the objects aren't stored as xml itself, but you can access it that way in both directions. Then your second point is more or less zope standard - you can use the zope management interface to cut and paste objects to rearange them. -- Regards, Diez B. Roggisch From walter at livinglogic.de Tue Apr 20 09:03:07 2004 From: walter at livinglogic.de (=?ISO-8859-1?Q?Walter_D=F6rwald?=) Date: Tue, 20 Apr 2004 15:03:07 +0200 Subject: when does issubclass fail? In-Reply-To: References: Message-ID: <1082466101.191546@homer.tmt.de> Chris Green wrote: > Heyas folks, > > When does issubclass fail? That's a loaded question so here's my test > case (also available at http://cmg.dok.org/code/classimports.tar.gz): > > directory structure: > > ./test.py > ./d/__init__.py > ./d/b.py > ./c/__init__.py > ./c/a.py > > #--------[a.py]--------- > class A(object): > pass > #------[end a.py]------- > > #--------[b.py]--------- > import sys > sys.path.append("/home/cmg/src/python/classtest/a") > class B(a.A): > pass > #------[end b.py]------- > > #--------[test.py]------ > import c.a > import d.b > print issubclass(d.b.B,c.a.A) > #--------[end test.py]-- > > issubclass(d.b.B,c.a.A) => False > > I'm trying to figure out why this is failing. My guess is that there > are two distinct imports of a.A in memory though I can't come up with > a simple test case that makes this happen without manipulating > sys.path. The simplest demo for this problem is importing the __main__ script a second time as a module: -----[foo.py]----- class A: pass import foo print issubclass(A, foo.A) ------------------ executing "python foo.py" prints True False > [...] Bye, Walter D?rwald From andymac at bullseye.apana.org.au Thu Apr 8 06:38:48 2004 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Thu, 8 Apr 2004 20:38:48 +1000 (EST) Subject: Intermittant slow startup In-Reply-To: <9badaf0.0404071113.6cdcee6b@posting.google.com> References: <9badaf0.0404051033.9fec2db@posting.google.com> <4071A86D.97CA6CAE@alcyone.com> <9badaf0.0404051445.5b26b945@posting.google.com> <9badaf0.0404071113.6cdcee6b@posting.google.com> Message-ID: <20040408203219.H9951@bullseye.apana.org.au> On Thu, 7 Apr 2004, Michael Mossey wrote: > I double-checked that and asked the sysadmin to check if the python > build was using any network source. I do have AFS and NFS drives > mounted on this machine, but I'm not reading any python code from them > as nearly as I can tell. PYTHONPATH points only to local disk. All I can think of is to try using "python -v" and see where in the startup process the delay appears to be occurring. If the same module is involved in every stumble, then at least you have a module to investigate. -- 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 jonas at jonasgalvez.com Wed Apr 21 15:40:56 2004 From: jonas at jonasgalvez.com (Jonas Galvez) Date: Wed, 21 Apr 2004 16:40:56 -0300 Subject: Time References: Message-ID: Thanks all. > [Mike Fletcher] > That format is the ISO standard date-time format. The modern way > to work with date-times in Python is to use the datetime module, > so: > > >>> import datetime > >>> d = datetime.datetime( 2004, 4, 21, 15, 05) > >>> d.isoformat() > '2004-04-21T15:05:00' > > You can use datetime.datetime( * mytuple ) to auto-unpack your > tuple, btw. Cool, that's what I was looking for. > [Peter Hansen] > You want to read about the "time" module: > > >>> t = (2004, 4, 21, 15, 33) > >>> import time > >>> time.strftime('%Y-%m-%dT%H:%M:00', t+(0,0,0,0)) > '2004-04-21T15:33:00' > > I left the "T" in there as a literal because I don't know what you > meant it to be and there's no obvious single-character > substitution. The "T" is from the W3C format: http://www.w3.org/TR/NOTE-datetime I need it to generate valid RSS/ATOM feeds. =- Jonas Galvez jonasgalvez.com/blog macromedia.com/go/team From mark at prothon.org Sat Apr 3 01:29:03 2004 From: mark at prothon.org (Mark Hahn) Date: Fri, 2 Apr 2004 22:29:03 -0800 Subject: Indent testers needed (Prothon) References: Message-ID: I have a newer better-working version to download and test: http://prothon.org/pub/prothon/prothon-unstable-b266-win32.zip The instructions are the same except the folder name will be Prothon: Unzip the file which will make a folder called Prothon. Drop your .pr file into the folder. Open a dos command window. CD to the win32 folder and run the prothon.exe file with the .pr file name: prothon.exe code.pr Features: 1) You must use only tabs or only spaces for indents in any one file. You cannot mix them. 2) Each indent level can have any number of characters more than the previous level, whether you are using tabs or spaces. If you drop back to the left to dedent, and your column position does not match any level above, you will get a lexer error. 3) If you increase the indentation level above the previous line by even one space, and that previous line does not end in a colon, then the new line will be considered a continuation of the previous line. 4) If a line contains an active (not quoted or commented) (, {, or [ without a matching end character, then the following line is always a continuation, no matter what that following line contains. 5) There is still support for using the trailing backslash ( \ ) to indicate that the next line is a continuation. This may be removed in the future if everyone agrees to do so. 6) A continuation line is effectively added to the end of the previous line so any line following a continuation line uses the last non-continuation line for the "previous line" in all the rules above. From sross at connectmail.carleton.ca Tue Apr 13 11:59:28 2004 From: sross at connectmail.carleton.ca (Sean Ross) Date: Tue, 13 Apr 2004 11:59:28 -0400 Subject: Once-only evaluation of default parameter values function definitions References: <407B79D7.424F65A1@doe.carleton.ca> Message-ID: "Fred Ma" wrote in message news:407B79D7.424F65A1 at doe.carleton.ca... > From the python tutorial, it's clear that to avoid sharing default > values between function calls, one has to avoid: > > Example#1 > --------- > def f(a, L=[]): > L.append(a) > return L > > Instead, one should use: > > Example#2 > --------- > def f(a, L=None): > if L is None: > L = [] > L.append(a) > return L > For fun, here's a little hack to work around that: from copy import deepcopy def fresh_defaults(f): fdefaults = f.func_defaults # get f's defaults def freshener(*args, **kwds): f.func_defaults = deepcopy(fdefaults) # and keep fresh return f(*args, **kwds) # between calls return freshener def f(a, L=[]): L.append(a) return L f = fresh_defaults(f) # <= transform f [snip] > print f(1) > print f(2) > print f(3) > > prints > > [1] > [1, 2] > [1, 2, 3] > now prints [1] [2] [3] Neat. Of course, it adds indirection and slows down the code... oh well ;) Welcome to Python, Sean From aahz at pythoncraft.com Fri Apr 2 15:10:28 2004 From: aahz at pythoncraft.com (Aahz) Date: 2 Apr 2004 15:10:28 -0500 Subject: Python conference slogan References: Message-ID: In article , Jacek Generowicz wrote: > >A previous slogan was: > > Python: Programming the way Guido indented it. > >Pretty meaningless to Python outsiders, I'd say. Close, but no cigar: Python: Programming the way Guido indented it -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "usenet imitates usenet" --Darkhawk From peter at engcorp.com Wed Apr 14 12:06:08 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 14 Apr 2004 12:06:08 -0400 Subject: interpreter limits In-Reply-To: References: <407c23bf$0$570$e4fe514c@news.xs4all.nl> <407c2ecc$0$574$e4fe514c@news.xs4all.nl> <7xisg3vfat.fsf@ruckus.brouhaha.com> Message-ID: djw wrote: > Paul Rubin wrote: > >> Irmen de Jong writes: >> >>> Can't you do something smart with signals, threads, alarm() and kill() ? >>> Like running the code in a worker thread, where the main thread >>> keeps track of how long it has been running and if not finished >>> within a certain time, kill() it. >> >> >> >> How do you kill a thread from another thread? I don't know of any way >> to do that. >> >> Maybe it's safest to run the user script in a separate process and >> communicate through a socket or through shm. That allows using the >> normal OS features for resource limits, file protection, etc. > > My exploration into threads indicated that you can't kill one thread > from another. http://www.strakt.com/docs/os03_threads_interrupt.pdf has some info about an approach (via a C extension only) which can be used in 2.3 to do it. From rob at robdijkshoorn.com Mon Apr 5 08:59:33 2004 From: rob at robdijkshoorn.com (Rob Dijkshoorn) Date: Mon, 5 Apr 2004 14:59:33 +0200 Subject: Building 2.3.3 on AIX, term.h complaint References: <406f537f$1_1@themost.net> Message-ID: <1081169983.528012@blaat.sara.nl> "Paul Watson" wrote in message news:406f537f$1_1 at themost.net... > > checking term.h usability... no > checking term.h presence... yes > configure: WARNING: term.h: present but cannot be compiled > configure: WARNING: term.h: check for missing prerequisite headers? > configure: WARNING: term.h: proceeding with the preprocessor's result > configure: WARNING: ## ------------------------------------ ## > configure: WARNING: ## Report this to bug-autoconf at gnu.org. ## > configure: WARNING: ## ------------------------------------ ## > checking for term.h... yes > Hi Paul, I got the same message (AIX 5.1, xlC) but the compile went fine. I have seen this warning on Linux a lot as well, when compiling various oss packages (Samba comes to mind). Does your compile fail? On a side note, I am unable to compile the modules, it fails with the following error: building '_tkinter' extension ./Modules/ld_so_aix cc_r -bI:Modules/python.exp build/temp.aix-5.1-2.3/_tkinter.o build/temp.aix-5.1-2.3/tkappinit.o -L/usr/X11R6/lib -L/usr/local/lib -ltk8.2 -ltcl8.2 -lX11 -o build/lib.aix-5.1-2.3/_tkinter.so ld: 0706-006 Cannot find or open library file: -l tk8.2 ld:open(): A file or directory in the path name does not exist. ld: 0706-006 Cannot find or open library file: -l tcl8.2 ld:open(): A file or directory in the path name does not exist. *** WARNING: renaming "_tkinter" since importing it failed: A file or directory in the path name does not exist. error: A file or directory in the path name does not exist. make: 1254-004 The error code from the last command is 1. Something you have come across? Regards, Rob From jbenson at sextans.lowell.edu Fri Apr 30 21:01:58 2004 From: jbenson at sextans.lowell.edu (Jim Benson) Date: Fri, 30 Apr 2004 18:01:58 -0700 (MST) Subject: IDE for Python In-Reply-To: <20040430211732.38504.qmail@web60802.mail.yahoo.com> Message-ID: On Fri, 30 Apr 2004, dont bother wrote: > Hi Guys: > Is there any good IDE for Python. I checked on > www.python.org and found some. Installed bluefish but I asked a similar question a while back on this list. I received a number of very helpful replies. here is the link to that thread: http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&oe=UTF-8&threadm= mailman.142.1078798509.19534.python-list%40python.org&rnum=4&prev= /groups%3Fsafe%3Dimages%26ie%3DUTF-8%26oe%3DUTF-8%26as_ugroup%3D comp.lang.python%26as_uauthors%3DJim%2520Benson%26lr%3D%26hl%3Den If this link didn't copy correctly the subject was: "a desired python editor" Jim From kier at sdf1.net Tue Apr 13 09:52:44 2004 From: kier at sdf1.net (Ray Slakinski) Date: 13 Apr 2004 06:52:44 -0700 Subject: Parsing string array for differences References: <7598e160.0404120856.217bc8d5@posting.google.com> <10vqk1-lcb1.ln1@eskimo.tundraware.com> Message-ID: <7598e160.0404130552.299fcca0@posting.google.com> Yup, someone on IRC introduced me to sets, and I love it :) Thanks for the help guys. Ray Tim Daneliuk wrote in message news:<10vqk1-lcb1.ln1 at eskimo.tundraware.com>... > > http://pydoc.org/2.3/sets.html From jcarlson at uci.edu Sun Apr 18 04:28:59 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Sun, 18 Apr 2004 01:28:59 -0700 Subject: module not callable - why not? In-Reply-To: <8ef9bea6.0404122025.36efc84e@posting.google.com> References: <107dras2heahcb6@news.supernews.com> <8ef9bea6.0404122025.36efc84e@posting.google.com> Message-ID: >>- Don't name the module and a class in it the same thing >> import Queue # Queue is a module >> from Queue import Queue # Queue is a class >> ... > > To be frank, this problem is just one of the symptoms of a sickened > programming language. Python runs into this problem (like > SimpleXMLRPCServer.SimpleXMLRPCServer) because: > > (a) By historical accident, Python modules differ significantly from > regular classes. (Modules are like singleton without constructor for > multiple instantiation, and without property getters/setters.) > > (b) Python uses class-based OOP, instead of prototype-based OOP. > > Class-based OOP is a historical mistake. If time could be turned back, > I think people would rather start with prototype-based OOP, instead. > > Because of this mistake of using class-based OOP, you have incomplete > objects like modules and classes: you usually can't use them directly, > at least not as comfortably/powerfully. Therefore, you find yourself > dealing with names like SimpleXMLPRCServer.SimpleXMLRPCServer, without > being able to collapse instance/class/module into one single object > and one single name. I think of modules as a namespace. Why? Because that is what they are. They contain a space of names, some of which may be useful to you, otherwise you wouldn't have imported the module. One really nifty thing about modules is that you can rename them if you want to, or even rebind names within them. The user is allowed to do anything they want, even foolish things like "from module_blah import *". In my opinion, modules are an explicit (and correct) solution to the namespace problem. You don't like them? Fine, write your own custom import command and stick it in site.py. If you're good, you can enable it per-module (so that you can still use the standard library), and only have to deal with the "mistake" every once and a while. - Josiah From bkelley at wi.mit.edu Tue Apr 13 17:29:09 2004 From: bkelley at wi.mit.edu (Brian Kelley) Date: Tue, 13 Apr 2004 17:29:09 -0400 Subject: Python crashes - cannot pin it down! In-Reply-To: References: Message-ID: <407c5bd5$0$559$b45e6eb0@senator-bedfellow.mit.edu> > from wxPython.wx import * > app = wxPySimpleApp() > app.MainLoop() > wxMessageBox("Hello") Actually, you don't need the app.MainLoop() here. Dialog boxes essentially start their own main loops. The reason your application was crashing was because wxPython needs to have an application created before you can create windows and such, you can think of this as an initialization step. It's not quite smart enough to know that an application hasn't been created though, hence the crash. Brian From jfabiani at yolo.com Thu Apr 22 09:52:21 2004 From: jfabiani at yolo.com (John Fabiani) Date: Thu, 22 Apr 2004 13:52:21 GMT Subject: Newbie to client/server Message-ID: I don't understand how to get data from multi tables for my forms/windows. I have been reading how to connect and get data (using a SQL statement) from MySQL. I think I understand. Now the question if I have a form (i.e. AR invoice) that requires data from more than one table (or I need multi SQL statements) where do I put it. It appears that I can have only one cursor. This must be wrong. I can understand that I can reuse the connect object but the returning information ends up into the same cursor. I don't want code (just how to do it right) but when I do something like the following it does not work: Con=myconnection_string Cursor=con.cursor() Cursor.execute(somestatement) newCursor=con.cursor() newCursor.execute(somestatement) #does not work John -- John Fabiani From grante at visi.com Thu Apr 29 17:36:27 2004 From: grante at visi.com (Grant Edwards) Date: 29 Apr 2004 21:36:27 GMT Subject: Don't understand wxPython ids References: <408ed938$0$17263$a1866201@newsreader.visi.com> Message-ID: <4091755b$0$30295$a1866201@newsreader.visi.com> On 2004-04-29, Matt Brubeck wrote: > "Wax" is a wxPython wrapper under development at: > > http://zephyrfalcon.org/labs/ > http://zephyrfalcon.org/weblog/arch_Wax.html > > Wax has a much more Pythonic API than wxPython, and gets rid of the > numeric IDs completely. I like it! I'm currently downloading a set of Mandrake 10 CDs so I can run wxPython 2.5. Hopefully the upgrade won't kill more than a few days. Once the system upgrade is done, I'll give Wax a try. -- Grant Edwards grante Yow! ... I want FORTY-TWO at TRYNEL FLOATATION SYSTEMS visi.com installed withinSIX AND A HALF HOURS!!! From Stanislav.Paska at kios.sk Thu Apr 29 00:23:45 2004 From: Stanislav.Paska at kios.sk (Stano Paska) Date: Thu, 29 Apr 2004 06:23:45 +0200 Subject: Path ... where is my application's home dir? In-Reply-To: References: Message-ID: <40908351.8040204@kios.sk> Marco Aschwanden wrote: > I want to store a file in the application directory. What is the easiest > way to figure out, where my application is situated? > > sys.argv[0] does not work for my purposes... do you have any other ideas. > > Thanks for any hint, > Marco > > I use this piece of code (on WinNT, WinXP): import os, os.path aaa = os.path.dirname(sys.argv[0]) if aaa == '': aaa = os.getcwd() print "homedir is: " % aaa Stano. From tim.golden at viacom-outdoor.co.uk Mon Apr 26 03:16:52 2004 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Mon, 26 Apr 2004 08:16:52 +0100 Subject: my first program- List Box help? Message-ID: >I am new to python and am trying to make a front end for an emulator. >I am using python, livewires and pygame. I am able to do everything I >want except createa list box. > >So I think all I need to learn how to do is draw a text box that >imports a xml file and with every click of an arrow key it updates a >variable. I also do not know how to start the bat file. But I think I >might be able to figure out on my own. It's quite difficult to know where to start: you've obviously already got the pygame and livewires documentation, and equally obviously you already know that once you're into pygame-style development you're rolling your own all the way. Which means that there is no one canonical way to produce a list box and to trigger a set of images on each movement within it, so it's difficult to post a code fragment. Having said that I have produced some small widgets for use in a pygame-based application here, including a listbox which I use for selecting a printer from the available list. If this would be of use to you I'm happy to send it. Let me know. And/Or give a clearer idea of what you're up to. And post some code that you've already done so we can see what approach you're taking. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star Internet. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From aku at europe.com Mon Apr 5 12:48:27 2004 From: aku at europe.com (aku) Date: 05 Apr 2004 16:48:27 GMT Subject: design by contract versus doctest References: <407174ea$0$5066$4d4ebb8e@news.nl.uu.net> Message-ID: <40718ddb$0$5071$4d4ebb8e@news.nl.uu.net> On 2004-04-05, Peter Hansen wrote: > aku wrote: > > > Isn't it so, that by applying DBC, a lot of unittests can be > > made redundant? > > How would you propose verifying that your code will work if you > don't run tests before you ship? in debugging mode you obviously have to ensure that the caller makes sure that all preconditions are met...then - by contract - the postconditions are met on returning from the function. A very very simple example, but just to make the point: n = 1 # at this point we are sure that n is an integer and n>=0 result = sort(n) > > Don't say "manual testing"... > > -Peter From junkmail at solumslekt.org Thu Apr 1 17:35:58 2004 From: junkmail at solumslekt.org (Leif B. Kristensen) Date: Fri, 02 Apr 2004 00:35:58 +0200 Subject: [OT] Top posting is a PITA References: <569c605ld1cj8fc1emolk08ete0s1prls1@4ax.com> <106di86neu1qh4d@news.supernews.com> <4069a001$0$4237$afc38c87@news.easynet.co.uk> <4069e9d9$0$8915$636a15ce@news.free.fr> <406a98ee$0$290$edfadb0f@dread12.news.tele.dk> <106lh64rda8t9d4@news.supernews.com> <3YXac.5683$406.5360@newssvr15.news.prodigy.com> Message-ID: Robin Munn wrote: > Another problem that occurs when some people top-post and some do not > is that the conversation thread quickly becomes unreadable unless > someone takes the time to rearrange it into a consistent form (as I > did in composing this reply). And more often than not, that's perceived as really not worth the effort. So, a lot of people that might have provided useful answers, doesn't care to reply to top-postings because it involves too much work to rearrange the text to respond in a sensible way. Top-posting *is* shitting in your pants. regards, -- Leif Biberg Kristensen http://solumslekt.org/ Validare necesse est From roy at panix.com Thu Apr 15 10:38:16 2004 From: roy at panix.com (Roy Smith) Date: Thu, 15 Apr 2004 10:38:16 -0400 Subject: Newbie question: Returning mutable vs. immutable References: <997a06e0.0404150627.5fb95d9b@posting.google.com> Message-ID: In article <997a06e0.0404150627.5fb95d9b at posting.google.com>, pugnatio2 at yahoo.com wrote: > Hi, Does anyone have an opinion as to whether functions/methods should > return mutable or immutable objects? In some circumstances, I could > see that mutable objects might be more convenient, but if the function > is to be reused, it might be a good idea to return only immutables. > > Or is this question moot, since the function returns control to the > caller and is out of the picture at that point? > > Thanks, > > --p I don't think there's any general rule for this. Return what makes sense to return and don't worry about the mutability unless there's some specific reason it needs to be mutable (i.e. you're going to change it) or immutable (i.e. you're going to use it as a dictionary key). From cm at leetspeak.org Mon Apr 12 21:31:25 2004 From: cm at leetspeak.org (Michael Walter) Date: Tue, 13 Apr 2004 03:31:25 +0200 Subject: Escaping characters in MySQLdb query In-Reply-To: References: Message-ID: Sean Berry wrote: > It doesn't work. If I have a value with a ', it creates an error. > > > "Michael Walter" wrote in message > news:c5fb0o$131c4$1 at ID-88904.news.uni-berlin.de... > >>Sean Berry wrote: >> >>>I wrote a little script that is inserting thousands of records into a > > mysql > >>>database. >>> >>>How do I escape characters like ' in my insert statements? >>> >>>I have something like the following (much shorter) example: >>> >>>c.execute("INSERT INTO records (var1, var2) values ('%s', '%s')" > > %(value1, > >>>value2)) >>> >>>My problem is when value1 is something like "Tom's auto supply". The ' > > in > >>>Tom's needs to be escaped. How can I do this? >>> >>>Thanks. >>> >>> >> >>I suppose you do like: >> >>c.execute("INSERT INTO records (var1, var2) values ('%s', '%s')", >>(value1,value2)) >> >>and have all magic done for you. >> >>Cheers, >>Michael > > > It should obviously be without the quotations marks inside the SQL string, but besides it does work. c.execute("INSERT INTO records (var1, var2) values (%s, %s)", (value1,value2)) Cheers, Michael From michele.simionato at poste.it Thu Apr 1 03:17:45 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 1 Apr 2004 00:17:45 -0800 Subject: Prothon, metaclasses, Zope [Was: A 'Python like' language] References: <95aa1afa.0403272243.78d60724@posting.google.com> Message-ID: <95aa1afa.0404010017.2f1683b8@posting.google.com> "Mark Hahn" wrote in message news:... Original top posting maintained on purpose: > Does anyone get anything done around here with all the bitching? I've been > communicating via email for 30 years and never have I seen such complaining > about something so silly. If you have anything to contribute to Prothon > I'll be over in the Prothon lists. We are too busy creating to have > conversations like this over there. > > You may not be able to tell it, but I'm a nice guy who would really like > feedback from intelligent knowledgable people like yourself. I just can't > take this anymore. > > Aahz wrote: > > In article , > > Mark Hahn wrote: > >> > >> Self defines having the same attribute in two different prototypes > >> illegal. That seemed extremely constraining to me so I went with the > >> Python 2.2 mro solution in Prothon. > > > > Bad idea. But I won't tell you why until you stop top-posting and > > over-quoting. Aahz is probably referring to the fact that Python 2.3 has changed the MRO since the 2.2 one was a bad idea. See http://www.python.org/2.3/mro.html for more. A part for this, Aahz is right in pointing out that you cannot get the attention of a lot of intelligent knowledgable people on c.l.py because of your postings habits. Actually this is the reason why I have downloaded Prothon yet. It is kinda of a pity, since maybe the idea is worth, but it is difficult to give credit to people liking tabs and top posting. Those are not stupid things IMNSHO. Michele Simionato From peter at engcorp.com Wed Apr 14 08:36:37 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 14 Apr 2004 08:36:37 -0400 Subject: Wrapper round x86 Assembler In-Reply-To: <8089854e.0404132323.3283390@posting.google.com> References: <8089854e.0404082353.7bf163a2@posting.google.com> <4dKdnQlIXMIXIevdRVn-gg@powergate.ca> <8089854e.0404100204.504186a0@posting.google.com> <8089854e.0404122329.5dfe5ce1@posting.google.com> <8089854e.0404132323.3283390@posting.google.com> Message-ID: Fuzzyman wrote: > In summary - I'm better off learning C and how to write Python > extensions !! > It's just a very 'undynamic solution'. > > Ho hum.... I've been trying to avoid delving into the arcane > makefile/linker/compiler chain mysteries... probably be more useful > anyway. That is where Pyrex comes in. You aren't supposed to have to know all those gory details then. Just some of them. :-) > I'm 'aware' of the concepts of memory allocation, garbage collection > etc - but I'm sure there's plenty more to learn.......... I doubt you'll need to encounter those if you're just trying to squeeze performance out of some bit-twiddling code. -Peter From chrish at cryptocard.com Wed Apr 14 08:34:02 2004 From: chrish at cryptocard.com (Chris Herborth) Date: Wed, 14 Apr 2004 08:34:02 -0400 Subject: Simple pyhon-based CMS In-Reply-To: References: <9396ba6f.0404131817.1219c695@posting.google.com> Message-ID: Chris Herborth wrote: > Stewart Midwinter wrote: > >> I'm looking for a simple python-based CMS (content management system), >> maybe with some blog-like features, ability to add articles - nothing >> too fancy. Do you have any suggestions? > > A friend of mine is working on one called MangoBery > (http://sourceforge.net/projects/mangobery/), which is in use at several > sites... not sure if it meets your needs, but take a look. Oh, wait, I just checked... it's written in PHP, which may or may not be a problem for you. Sorry about that! -- Chris Herborth chrish at cryptocard.com Documentation Overlord, CRYPTOCard Corp. http://www.cryptocard.com/ Never send a monster to do the work of an evil scientist. Postatem obscuri lateris nescitis. From len-1 at telus.net Tue Apr 6 01:35:46 2004 From: len-1 at telus.net (Lenard Lindstrom) Date: Tue, 06 Apr 2004 05:35:46 GMT Subject: Using function parameters to determine method kind References: <4qrzym6e.fsf@telus.net> <95aa1afa.0404050417.2d11b369@posting.google.com> Message-ID: <8yh9r7p2.fsf@telus.net> Michele Simionato wrote: >Lenard Lindstrom wrote in message > news:<4qrzym6e.fsf at telus.net>... >> I was wondering if anyone has suggested having Python determine >> a method's kind from its first parameter. ... >I find relaying on tbe parameter name to specify the kind of method >to be rather fragile. It works most times but not always. What about >inner classes for instance? Do you mean: from dparams import Object class A(Object): class B(Object): def __init__(self, x): self.x = x b=A.B(x) ? Class A.B is not affected. Parameter checking only happens for instances of type function. Other callables have to be or use descriptors to be anything other than static. As for B's methods, parameter checking works just fine. My module is more of a demonstration than a practical solution anyway. I would suggest a different approach for implementing parameter checking in the python interpreter. > Also, there are situations where you want >a method to work both with instances and classes, so do you want to >use self or cls? I can only imagine one way to do this now, wrap the function in a descriptor. >>> from dparams import Object >>> from types import MethodType >>> class bimethod(Object): ... def __init__(self, f): self.f=f ... def __get__(self, o, t): ... if o is None: return MethodType(self.f, t, type(t)) ... return MethodType(self.f, o, t) ... >>> class A(Object): ... def bi(x): return x ... bi=bimethod(bi) ... >>> A.bi() >>> A().bi() <__main__.A object at 0x0119C1B0> Descriptors are unaffected by the function's parameters, so the first parameter can be anything you want. If I am not mistaken, the only methods other that __new__ that currently work without descriptors are instance methods. Is it not good form for instance methods to start with 'self' anyways? (except maybe for a metaclass's __init__, but this is a special case) >I support PEP 318 also because this will kill home grown hacks (including >my own) to provide this kind of functionality. This is a good PEP. It would complement the use of parameters. >I am also waiting for a better "super" but it seems nobody is talking >about it. I gave it a try by changing the type argument passed to a descriptor's __get__ method, but it required a rewritten classmethod of course. Lenard Lindstrom From donn at u.washington.edu Tue Apr 13 12:29:16 2004 From: donn at u.washington.edu (Donn Cave) Date: Tue, 13 Apr 2004 09:29:16 -0700 Subject: How to kill a SocketServer? References: Message-ID: In article , Josiah Carlson wrote: > > Since the whole application uses much CPU power, the performance (esp. the > > reaction time) of an asynchronous server is too low. > > > > We found out that a threading server is much the better choise for this, but > > we'd need a way to stop a server and start it again (wich new parameters). > > That is very interesting. > > After doing some research into heavily multi-threaded servers in Python > a few years back, I discovered that for raw throughput, a properly > written async server could do far better than a threaded one. > > If your request processing takes the most time, you may consider a > communication thread and a processing thread. > > If your processing thread does a lot of waiting on a database or > something else, it may make sense to have one communication thread, and > a handful of database query threads. > > What part of a request takes up the most time? I wonder if you're making it more complicated than necessary. The application uses a lot of CPU as it handles multiple concurrent client connections. That makes a pretty clear case for some kind of parallel thread architecture, not only to dispatch inputs promptly but also to take advantage of commonly available SMP hardware. As you acknowledge above, the details of that architecture depend a lot on what exactly they're doing - how many connections over time, the nature of the request processing, etc. But at any rate, now they have a thread waiting in accept, and they need to shake it loose. My answer is `define a shutdown request as part of the service protocol', but maybe you would have a better idea. Donn Cave, donn at u.washington.edu From peter at engcorp.com Mon Apr 26 19:53:33 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 26 Apr 2004 19:53:33 -0400 Subject: Uploading files from a server In-Reply-To: References: Message-ID: Edward Diener wrote: > What is the easiest way in Python in a web server ^^^^^^^^^^^^^^^^^^^^^^^^^ What does this mean? Are you asking about a specific situation you have already, such as Python CGI scripts running behind an Apache server, or are you asking for suggestions for a web framework which can handle this task, where the web server itself is written in Python? Or something else? > to upload a client file, > once the file name on the client's machine has been entered, to a directory > on the server ? That is done using the usual means laid out by the HTTP and HTML standards, same with Python as with any other language. Are you actually asking how this is done? (That is, using POST, and an input type of "file", and so forth...) Please clarify what you really want. -Peter From fumanchu at amor.org Fri Apr 16 13:42:12 2004 From: fumanchu at amor.org (Robert Brewer) Date: Fri, 16 Apr 2004 10:42:12 -0700 Subject: datetimes, tzinfo and gmtime epoch Message-ID: John Hunter wrote: > I have a python2.3 datetime instance and a tzinfo instance (eg Eastern > from the python library reference). > > What is the best way to convert that datetime instance to seconds > since the epoch, gmtime? You might try time.mktime(t), where t is a 9-tuple as desribed at: http://docs.python.org/lib/module-time.html FuManChu From jdhunter at ace.bsd.uchicago.edu Thu Apr 29 14:05:16 2004 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Thu, 29 Apr 2004 13:05:16 -0500 Subject: MATLAB2Python In-Reply-To: ("Colin J. Williams"'s message of "Thu, 29 Apr 2004 13:38:45 -0400") References: Message-ID: >>>>> "Colin" == Colin J Williams writes: Colin> You might like to take a look at PyMatrix. It is still Colin> very much a development project, but I would appreciate Colin> your thoughts on the areas where it is deficient, as Colin> compared with MatLab. Colin> http://www3.sympatico.ca/cjw/PyMatrix I looked over your site and examples, but didn't see any explanation of what PyMatrix provides over the required numarray and all the helpful linear algebra and summary functions it provides in numarray.linear_algebra and numarray.linear_algebra.mlab. With the exception of Hilbert, most of the code seems like a wrapper of numarray functionality. Is the main difference how you define the default behavior of operators? Or is this just a starting point for a much larger package? Thanks, JDH From Mike at DeleteThis.Geary.com Sat Apr 17 02:07:52 2004 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Fri, 16 Apr 2004 23:07:52 -0700 Subject: CamelCase versus wide_names (Prothon) References: <407ec022$0$54153$1b2cd167@news.wanadoo.nl><69KdndtPUZT-5h3dRVn-uw@powergate.ca> Message-ID: <1081idpaib8q2e9@corp.supernews.com> Jack Diederich wrote: > Strength of the belief that you have found the one true way is > inversely proportional to the number of things you have tried. > Java and VB folks are more likely to have an N of one and a > belief approaching unity. They are also more likely to be > mixedCase people. That is my opinion. I'll volunteer to be the exception that proves the rule. :-) I'm 52, have been programming since 1968, and have coded in at least 30 different languages, using all of the naming conventions that have been discussed here along with a few more. I spent many years coding using names with underscores, but now I'm a big fan of mixed case names and use them in all of my code. In fact, you can blame me for talking Mark into changing Prothon to use mixed case names. So, it ain't just the young'uns with limited experience. :-) -Mike From mark at prothon.org Sat Apr 24 02:07:47 2004 From: mark at prothon.org (Mark Hahn) Date: Fri, 23 Apr 2004 23:07:47 -0700 Subject: Why we will use obj$func() often References: <84Uhc.22278$dZ1.5087@fed1read04> <8AWhc.23114$dZ1.11070@fed1read04> <40883BFE.B381518A@alcyone.com> <27_hc.23801$dZ1.2716@fed1read04> <40887145.789A2FE8@alcyone.com> <7cki80hj976bia36lhf9er97v073o1pqvm@4ax.com> <1082783076.585831@yasure> Message-ID: "Donn Cave" wrote ... > When I want > a thing with persistent data, I'm thinking of an object. One > must keep things simple. You aren't the only one who thinks that closures are unnecessary. Dave McQuigg has posted several messages today making that argument. I also have several people saying they couldn't live without them. One javascript programmer says he uses instance variables for access outside of objects (properties) and closure variables for storage variables inside objects. He has posted a lengthy messge about it on the Prothon lists. Go figure. I personally think the complications of adding one '&' prefix to give all the benefits of closures is a good trade-off. No matter how much people rant and rave about Prothon heading down the path to the Perl-y gates of hell (sorry about that pun) I refuse to believe that some ugly punctuation is going to ruin an otherwise good language. > I might seriously > consider what I believe we call lexical scoping, and a declaration - > not assigning a type, but an initial value, like "let x = 0". > Namespaces like Python's would be for objects - modules, classes, > class instances, whatever - not functions - and would be purely > explicit, not implicit like a scope (I think that would most > conspicuously require some alternative for "def" statements, > for example.) I'm not following you exactly, but I think what you are asking for is the declaration of variables with "let x = 0", or what some languages use is just "var x" that specify that the variable belongs in the scope of that declaration. This resolves the ambiguity of local versus global variables and even gives a nice solution for closures. That is an interesting idea. It turns out to be a little harder for the compiler and program reader to use because both have to still scan the code to find that declaration and discover what scope a variable belongs in, although it is much easier than the current Python scheme where there are complex rules and more code scanning involved, but less typing. The Python intrpreter requires three scans to parse the source and generate bytecodes. The advantage of prefix symbols that Ruby and Prothon use right now is that the compiler and the program reader don't have to scan the code at all to see what scope the var belongs to. When you see the & you know it's in the surrounding function, when you see a capital letter you know it's global to the module, when you see a lower-case letter you know it's local, etc. Once you get used to it the code is much more readable. The Prothon compiler parses source and generates code in one fast pass. I'm sorry, I got into sales pitch mode again. I'll let you go. It's been interesting chatting... From fadelorme at free.fr Fri Apr 30 13:38:53 2004 From: fadelorme at free.fr (Famille Delorme) Date: Fri, 30 Apr 2004 19:38:53 +0200 Subject: Dictionnary vs Class for configuration Message-ID: <40929016$0$8635$626a14ce@news.free.fr> Sorry if this discussion are already submited, but I don't find anything really interresting for me. And sorry for my bad english, it is not my native language. I wrote a program in Python for a school project and I am in trouble. I have make a Python script called conf.py. This file contains dictionnarys for configuration like this: config_sql = { "DATABASE" : "nanana", "USERDB" : "bob", "PASSWORD" : "********" } config_script = { "TIMETOSLEEP" : 100 "PATH" : "/home/script" } The config_section variable is included in each modules (script python) used in my program (with from config.py import config_section) And the use is like this from conf.py import config_sql print config["DATABASE"] But my master say it's better to do a class like this class config : def __init__(self, part=="") : if (part=="SQL") : self.database="nanana" self.userdb="bob" self.password="*******" elif (part=="SCRIPT") : self.timetosleep=10 self.path="/home/script" .... and the use like this from conf.py import config cfg=config("SQL") print cfg.database We have do only a file for configuration because the administrator is no searching for configuration. I want know : - what is more faster, dictionnary method or class method? - what use more ram memory ? - if you are administrator, what method you like for configure program ? Note: * the class will not have methods, it is not necessary. * the program is composed of several modules which import config_section. Thank you for futures answers, 3Zen From peter at engcorp.com Thu Apr 22 22:16:20 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 22 Apr 2004 22:16:20 -0400 Subject: AOP use cases In-Reply-To: References: <84fc4588.0404140106.3fa0c55@posting.google.com> <0pydnSB4WYuieuLdRVn-hQ@powergate.ca> Message-ID: Jacek Generowicz wrote: > Jacek Generowicz writes: >>Stupid example: > > Let's give a better one, which is still short > > # Mix concerns of calculating Fibonnaci numbers, and avoiding > # recalculating the same answer repeatedly There's a large contingent of folks in the world, not trained as computer scientists, who would question the claim that anything involving Fibonnaci sequences makes a good "real world" example. ;-) -Peter From alf at calvin.fayauffre.org Fri Apr 16 04:21:02 2004 From: alf at calvin.fayauffre.org (Alexandre Fayolle) Date: Fri, 16 Apr 2004 08:21:02 +0000 (UTC) Subject: Aspect Programming Module References: <84fc4588.0404140106.3fa0c55@posting.google.com> <8ef9bea6.0404142155.90b41ef@posting.google.com> <407E394B.2050709@mxm.dk> Message-ID: Le 16-04-2004, Yermat a ?crit?: > Does it help ? Well, yes and no. I agree that this is how AOP can be made to work in Python (aand your implementation is not conceptually very different from logilab.aspect (except that the module has some entry points for choosing which methods are tied to the aspect) However, I would not call this a "mixin" (which was the key word in my question). My vision of a mixin implies (maybe wrongly) some responsibilities to be added or customized through multiple inheritance to a given class by a mixin class. This supposes that the originial class was designed with the mixin in mind. -- Alexandre Fayolle LOGILAB, Paris (France) http://www.logilab.com http://www.logilab.fr http://www.logilab.org From deetsNOSPAM at web.de Thu Apr 22 12:29:10 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Thu, 22 Apr 2004 18:29:10 +0200 Subject: alternative python compilers/vms? (like java) References: Message-ID: project2501 wrote: > > are there alternative compilers for python? or different VMs to run the > bytecode? > > similar to IBM java jvm and sun jvm, and other jvms? jikes, gcj? there is jython, a very popular python 2.1 implementation on top of the java vm. Apart from that, AFAIX python is not specified in terms of a vm, as jva is. The bytecode might actually change between versions. -- Regards, Diez B. Roggisch From jacek.generowicz at cern.ch Wed Apr 7 07:43:26 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 07 Apr 2004 13:43:26 +0200 Subject: OFF-TOPIC:: Why Lisp is not my favorite programming language References: <165b3efa.0403030443.4d591f04@posting.google.com> <40460dd5$0$5916$7a628cd7@news.club-internet.fr> <6in670lrldbjkuujle68a526293j57a7mn@4ax.com> <95aa1afa.0404070205.94b32e4@posting.google.com> Message-ID: michele.simionato at poste.it (Michele Simionato) writes: > Stephen Horne wrote in message news:<6in670lrldbjkuujle68a526293j57a7mn at 4ax.com>... > > > LISP is normally interpreted - maybe always, > > I think you will be crucified for that affirmation. Yes, maybe crucifiction is a more appropriate reaction :-) > Anyway, here is an interesting thread talking about Lisp > optimizations: > > http://groups.google.it/groups?hl=it&lr=&ie=UTF-8&threadm=95aa1afa.0402262158.5b33de79%40posting.google.com&rnum=1&prev=/groups%3Fhl%3Dit%26lr%3D%26ie%3DISO-8859-1%26q%3Dsimionato%2Bfeature%2Brequest%26btnG%3DCerca%2Bcon%2BGoogle%26meta%3Dgroup%253Dcomp.lang.python.* Eh, methinks you posted the wrong link. Did you mean to point to this thread containing this post: http://www.google.ch/groups?as_umsgid=ad2vzxoq.fsf%40ccs.neu.edu ? [Summary: Troll comes to c.l.l claiming that Lisp is slow. Challenges Lispniks to try to beat C++ on speed on a program that was designed to test speed of C++ compilers. Lispniks beat C++ for speed in both Common Lisp and Scheme.] From zhristov at enchant.com.au Wed Apr 14 18:58:40 2004 From: zhristov at enchant.com.au (Zlatko Hristov) Date: Thu, 15 Apr 2004 08:58:40 +1000 Subject: Python script to grep squid logs Message-ID: <1081983520.1417.17.camel@easynote> Hello guys, I am a newby python user, I want to create a script which will go through the squid log file and return me all the URL's accessed(i.e www.bbc.com). Is RE the way to go? Thank you, Regards, Zlatko. From n3613 at klaff.org Fri Apr 2 12:49:02 2004 From: n3613 at klaff.org (Dave) Date: Fri, 2 Apr 2004 09:49:02 -0800 (PST) Subject: Making the Zen of Python more useful Message-ID: <20040402174902.906E23FE4C@omta10.mta.everyone.net> from this import s s.decode('rot13') From peter at engcorp.com Tue Apr 27 07:25:35 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 27 Apr 2004 07:25:35 -0400 Subject: Is Perl *that* good? (was: How's ruby compare to it older bro In-Reply-To: References: Message-ID: Peter Maas wrote: > Peter Hansen wrote: > >> I guess it would be interesting to pose the question back to >> them "If you could not use regexes in Perl, would you still >> like to program in it?" or "If you couldn't use mysql in PHP >> would you still use it?" >> >> What similar question, if any, would be a difficult one for >> us Python types? > > If you could not use block indentation in Python, would you > still like to program in it? :-) The way I indent my braces (the One True Way ;-), I wouldn't really mind, I suppose: def install(name) { if os.path.exists(name) { path, ext = os.path.splitext(name) if ext == '.zip' { try { x = Extractor(name) path = os.path.join(x.extract(), path.replace('_', '.')) } finally { x.close() } } else { path = name } } } -Peter From imbosol at aerojockey.invalid Tue Apr 27 19:26:49 2004 From: imbosol at aerojockey.invalid (Carl Banks) Date: Tue, 27 Apr 2004 23:26:49 GMT Subject: Is Perl *that* good? References: <108q51j4dscn7dc@corp.supernews.com> <87fzaqmm8t.fsf@strauser.com> <38ec68a6.0404262308.50029919@posting.google.com> Message-ID: Paramjit Oberoi wrote: > > >> Asun> Regex is much more 'immediate' in Perl. >> >> Sure, it's syntactically bound into the language. There will always be an >> extra constant overhead to enable regular expressions in Python. That > > If only compiled regular expression objects allowed easy access to the > last match object, python regxes would become significantly more > convenient. For example, today you have to write: > > m = myregex.match(line) > if (m): > xyz = m.group('xyz') > > It would be much easier to do: > > if myregex.match(line): > xyz = myregex.lastm.group('xyz') > > Having to introduce a new variable name for a match object just > muddles the code unnecessarily in common regex usage scenarios. Hmm. The reason this hasn't been done is that it makes the match method non-reentrant. For example, suppose you call some functions in between the matching and use of the matched object, like this: if myregex.match(line): xyz = (subprocess(line[myregex.lastm.end():]) + myregex.lastm.group(1)) And suppose subprocess goes on to use the same regexp. By the time subprocess returns, myregex.lastm could have been overwritten. This is not a far-fetched example at all; one could easily encounter this problem when writing, say, a recursive descent parser. Murphy's law says that if anything bad can happen, sooner or later it will, and this is why non-reentrant functions like your proposed myregex.match are so heinous. So, I can't agree that this is a good idea as it stands. -- CARL BANKS http://www.aerojockey.com/software "If you believe in yourself, drink your school, stay on drugs, and don't do milk, you can get work." -- Parody of Mr. T from a Robert Smigel Cartoon From tjreedy at udel.edu Mon Apr 5 02:44:55 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 5 Apr 2004 02:44:55 -0400 Subject: Working with a list in a more "pythonic" way References: <20040404124833458+0200@news.rhrz.uni-bonn.de> Message-ID: "David Eppstein" wrote in message news:eppstein-78D3D6.14092304042004 at news.service.uci.edu... > In article , > "Terry Reedy" wrote: > > > Rewritten, your code is > > > > score = 0 > > for i in range(len(phrase)-1): > > score += soundScoreMatrix[ord(x[i]) - 65][ord(x[i + 1]) - 65] > > > > Once written thusly, the reduce form is obvious (but obviously not tested): > > > > reduce(lambda score, i: score + soundScoreMatrix[ord(x[i]) - 65][ord(x[i + > > 1]) - 65], > > range(len(phrase)-1), 0) > > > > but aside from any didactic value this has, I prefer, in this case, the > > written-out loop. > > I prefer the sum form -- if sum() isn't good for this example, what is > it there for at all? In order to use sum(), one must have the items to be summed. The OP does not have them but must generate them in a explicit loop. At that point, it seems sensible to me to directly add them instead of yielding or collecting them to be summed in a second (or third) loop in the sum function. > I also don't like seeing the magic number 65 > without some sort of explanation. Agreed. Something for the OP to add. > And how come you're using x in one place and phrase in another? I cut and pasted. Obvious, OP needs to use one or the other. > ords = [ord(c) - ord('A') for c in phrase.upper()] > score = sum([soundScoreMatrix[ords[i]][ords[i+1]] > for i in range(len(phrase)-1) > if 0 <= ords[i] < 26 and 0 <= ords[i+1] < 26]) Terry J. Reedy From adam_gautier at yahoo.com Sat Apr 3 12:35:19 2004 From: adam_gautier at yahoo.com (Adam T. Gautier) Date: Sat, 03 Apr 2004 12:35:19 -0500 Subject: Working with bytes. In-Reply-To: <406EE606.4000604@yahoo.com> References: <406EE606.4000604@yahoo.com> Message-ID: <406EF5D7.6070508@yahoo.com> I came up with a solution using the binascii module's hexlify method. Thanks Adam T. Gautier wrote: > I have been unable to solve a problem. I am working with MD5 > signatures trying to put these in a database. The MD5 signatures are > not generated using the python md5 module but an external application > that is producing the valid 16 byte signature formats. Anyway, these > 16 byte signatures are not nescarrally valid strings. How do I > manipulate the bytes? I need to concatenate the bytes with a SQL > statement which is a string. This works fine for most of the md5 > signatures but some blow up with a TypeError. Because there is a NULL > byte or something else. So I guess my ultimate question is how do I > get a prepared SQL statement to accept a series of bytes? How do I > convert the bytes to a valid string like: > > 'x%L9d\340\316\262\363\037\311\345<\262\357\215' > > that can be concatenated? > > Thanks > From richie at entrian.com Sun Apr 4 17:21:43 2004 From: richie at entrian.com (Richie Hindle) Date: Sun, 04 Apr 2004 22:21:43 +0100 Subject: ANNOUNCE: 'goto' for Python In-Reply-To: <40705B5E.5010709@cfl.rr.com> References: <40705B5E.5010709@cfl.rr.com> Message-ID: [pxlpluker] > If i am right i sure could have used > this 2 weeks ago. I am a python noob and I eventually just set a "skip > this" flag with an if statement. Oh dear... I think it's time to knock this one on the head (unless pxlpluker is cleverly continuing the joke, in which case hats off to you because you were very convincing 8-) To all the Python newbies: the 'goto' module was an April Fool's joke. Yes, it has a working implementation, but it was a joke nevertheless. No-one would suggest that goto or comefrom are good ideas for Python. Please don't use them in real code! I think the module may have one legitimate use: as the basis for test implementations of *sensible* new control flow structures for Python. Every couple of months there's a thread here about how the 'while' construct isn't powerful enough - maybe next time we can have a working implementation of the latest suggested alternative, based on the techniques used by goto.py. I've enjoyed this thread immensely, and I hope others have too, but let's call a halt to it before it does some real damage. 8-) -- Richie Hindle richie at entrian.com From mh at pixar.com Thu Apr 22 13:42:37 2004 From: mh at pixar.com (Mark Harrison) Date: Thu, 22 Apr 2004 17:42:37 GMT Subject: equivalent to Tcl 'after' command? Message-ID: I'm writing some event-driven programs, and I would like to do the equivalent of the Tcl 'after' command, e.g.: after 1000 {puts "one second has elapsed"} 1. What's the most canonical way of doing this? 2. What's the best reference that talks about non-gui event loop programming in Python? Many TIA! Mark -- Mark Harrison Pixar Animation Studios From premshree_python at yahoo.co.in Mon Apr 12 05:38:16 2004 From: premshree_python at yahoo.co.in (=?iso-8859-1?q?Premshree=20Pillai?=) Date: Mon, 12 Apr 2004 10:38:16 +0100 (BST) Subject: pyAlbum.py: EXIF support added Message-ID: <20040412093816.57899.qmail@web8308.mail.in.yahoo.com> Hello, I've now added an optional EXIF support to pyAlbum.py (http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/271246) A sample album is available at http://premshree.seacrow.com/temp/pics/2004-04-11/index.htm -Premshree Pillai ===== -Premshree [http://www.qiksearch.com/] ________________________________________________________________________ Yahoo! India Matrimony: Find your partner online. http://yahoo.shaadi.com/india-matrimony/ From mark at prothon.org Fri Apr 23 14:21:16 2004 From: mark at prothon.org (Mark Hahn) Date: Fri, 23 Apr 2004 11:21:16 -0700 Subject: Why we will use obj$func() often References: <84Uhc.22278$dZ1.5087@fed1read04> <8AWhc.23114$dZ1.11070@fed1read04> <40883BFE.B381518A@alcyone.com> <27_hc.23801$dZ1.2716@fed1read04> <40887145.789A2FE8@alcyone.com> <7cki80hj976bia36lhf9er97v073o1pqvm@4ax.com> Message-ID: "David MacQuigg" wrote > I would take this as constructive criticism, not an ad-hominem attack. Yes, I admitted I was mistaken. I was upset when I read the message and I misread it as a slur. > Adding syntax or making changes just because it allows you to do > something that can't be done in Python is not good. We have to look at > *use cases* for these features and compare them to a well-written > Python equivalent. Then, we can see if the benefit is worth the extra > syntax. We spend far to much time debating syntax without a clear > benefit in mind. Show us a nice closure. The benefits of closures are well known. I'll give you the canonical example, but I'm sure textbooks can give you many more (by the way, Python cannot do this): # tested example def getFunc(): counter = 0 def count(): &counter += 1 print &counter return count c = getFunc() c() # prints 1 c() # prints 2 c() # prints 3 From jacek.generowicz at cern.ch Mon Apr 5 05:30:53 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 05 Apr 2004 11:30:53 +0200 Subject: Can someone give me a short explanation? References: Message-ID: "Senthoorkumaran Punniamoorthy" writes: > I found this code in the book text processing with Python. But having > little difficulty understanding how exactly it works and what should > be passed as argument? Can someone decode this for me please? > > > apply_each = lambda fns, args=[]: map(apply, fns, [args]*len(fns)) "map" is a builtin which applies its first argument (which should be a function[*]) to the elements coming out of the sequences which are passed to it as arguments 2,3, ... N, and collects all the results in a list, which it returns. [*] Where I say "function" in any of this, I should really be saying "callable". If you don't know what this means, ignore it. Not important. In this case, the first argument of "map" is "apply". "apply" is a builtin which takes a function as its first argument, and applies it to whatever is in the sequence that is its second argument. (It also has the ability to deal with keyword args, but forget those for now.) Take in for granted, for now, that "args" in "[args]*len(fns)" refers to an empty list. In which case "[args]*len(fns)" creates a list of empty lists, whose length is equal to the length of the sequence "fns". Take it for granted, for now, that "fns" is a sequence of functions. So, "map(apply, fns, [args]*len(fns))" calls the first function in the "fns" (giving it no arguments) and remembers the result, then it calls the next function in "fns" (with no args), and so on ... then it returns all the results. Now, "lambda" is a way of creating anonymous functions. You could created "apply_each" like this: def apply_each(fns, args=[]): return map(apply, fns, [args]*len(fns)) So, "apply_each" is basically a function, which takes a sequence of functions, calls them all, and returns all the results in a list. Let's define a few simple functions, which take no arguments and return something ... and pass them to apply_each >>> apply_each = lambda fns, args=[]: map(apply, fns, [args]*len(fns)) >>> def one(): return "one" ... >>> def two(): return "two" ... >>> def three(): return "three" ... >>> apply_each([one,two,three]) ['one', 'two', 'three'] >>> Now, you could pass a second argument to "apply_args", in which case it should be a sequence, and the elements of the sequence would be used as the arguments in each of the calls to the functions you pass. Without seeing the broader context in which the original appears, it's difficult to say why it was defined the way it was. Nowadays, I suspect that many Pythoneers would prefer something like def apply_each(fns, args=[]): return [ fn(*args) for fn in fns ] - The stuff appearing after "return" is a List Comprehension. - The "*" in "fn(*args") means "args is a sequence: pass its contents as separate arguments to 'fn'". From shane at zope.com Fri Apr 2 14:00:18 2004 From: shane at zope.com (Shane Hathaway) Date: Fri, 02 Apr 2004 14:00:18 -0500 Subject: GUI Frameworks in Python? In-Reply-To: <45228044.0404021040.3860a027@posting.google.com> References: <45228044.0404021040.3860a027@posting.google.com> Message-ID: <406DB842.6090106@zope.com> Chris Perkins wrote: > I just upgraded from 2.4.2.4 to 2.5.1.5, and the start-up time for the > demo app went from about 5 seconds to less than a second. Wow! I'd really like to know how this was accomplished. Do you know? (Robin?) Shane From RobMEmmons at cs.com Fri Apr 16 22:01:21 2004 From: RobMEmmons at cs.com (Robert M. Emmons) Date: Fri, 16 Apr 2004 21:01:21 -0500 Subject: Difficulty Finding Python Developers In-Reply-To: <407D6269.3090909@engcorp.com> References: <65cbc3dd.0404140641.3501fde8@posting.google.com> <407D6269.3090909@engcorp.com> Message-ID: <40808FF1.7060204@cs.com> > I would actually suggest, however, that instead of hiring someone > new for the position, take one of your talented existing programmers > and have him or her learn Python while starting on this project. > If the project goes well, you can more easily make the case for > doing other projects with Python, and you might in the meantime > have found some actual "Python programmers". I still wouldn't > hire them, however, if they didn't fit the afore-mentioned criteria... I agree with Peter. I learned python in an afternoon. I'm not saying I was highly productive after 4 hours, but I could program and start working immediately. Any good programmer should be able to do this. For reference: On the scale of programmers -- I'm not on the expert high end -- just someone that has many years of experience in a variety of languagues for a variety of small projects. The ease and power of using python is what sold me immediately. Very Cool... Rob From cmg at dok.org Fri Apr 16 17:54:17 2004 From: cmg at dok.org (Chris Green) Date: Fri, 16 Apr 2004 17:54:17 -0400 Subject: when does issubclass fail? Message-ID: Heyas folks, When does issubclass fail? That's a loaded question so here's my test case (also available at http://cmg.dok.org/code/classimports.tar.gz): directory structure: ./test.py ./d/__init__.py ./d/b.py ./c/__init__.py ./c/a.py #--------[a.py]--------- class A(object): pass #------[end a.py]------- #--------[b.py]--------- import sys sys.path.append("/home/cmg/src/python/classtest/a") class B(a.A): pass #------[end b.py]------- #--------[test.py]------ import c.a import d.b print issubclass(d.b.B,c.a.A) #--------[end test.py]-- issubclass(d.b.B,c.a.A) => False I'm trying to figure out why this is failing. My guess is that there are two distinct imports of a.A in memory though I can't come up with a simple test case that makes this happen without manipulating sys.path. My goal is to define a baseclass BasePoller and then have user configured directories searched for that baseclass so I can load modules at run time. Since I can't do absolute imports, I treat that directory as a suitable spot to import from and do some fancy dir() walking to find instances of my subclass. This work fine as long as the path I search is contained within an original element of the main init script. I'm trying to handle the case where the directory is specified as an absolute path and can't come up with a way to make issubclass work. Is there anyway out of this other than defining a special attribute I can check for the presense of? -- Chris Green A watched process never cores. From mark at prothon.org Tue Apr 20 17:31:20 2004 From: mark at prothon.org (Mark Hahn) Date: Tue, 20 Apr 2004 14:31:20 -0700 Subject: Dollar sign ($) on foriegn keyboards? (prothon) References: Message-ID: "Fredrik Lundh" wrote ... > any reason you cannot set up a mailing list for your little pet > project? you're generating tons of off-topic traffic, and frankly, > I don't think I'm the only one who couldn't care less about your > pre-alpha hack with minimum capabilities. > > (if I posted hundreds of messages for every pre-alpha hack I've > ever made, people would quickly label me as an annoying crack- > pot.) Sorry if I annoy, but I've only posted a total of about 4 thread-starting messages. The hundreds of messages have been replies. We do have active Prothon mailing lists, but no international members yet, which is why I asked this particular question here. When I posted my first Prothon messages, I asked if I should stay away from c.l.p. out of courtesy. I was specifically told to hang around here by several of the top Pythoneers, because they view Prothon as a potential learning ground, or sandbox, for Python. So I will do so until those same top Pythoneers tell me I have worn out my welcome, thank you very much. From adalke at mindspring.com Mon Apr 5 16:00:00 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Mon, 05 Apr 2004 20:00:00 GMT Subject: allocate TWO interpreters in a C program? References: Message-ID: <4Vicc.16932$lt2.13201@newsread1.news.pas.earthlink.net> Torsten Mohr: > i can embed Perl into a C program and allocate MORE THAN ONE > interpreter if i want to. They are independent from each other. > > Is this also possible in Python? As no one else has answered, I'll take a stab at it, on the assumption that a wrong answer will be corrected. No, it isn't possible. Various bits of state, like exceptions, are stored in global variable (actually thread global I think). I think there is other global state, like sys.modules which contains all of the imported modules. There are experimental systems like PyPy which can provide independent interpreters but I know little about them. Andrew dalke at dalkescientific.com From Joseph.V.Laughlin at boeing.com Wed Apr 28 15:27:43 2004 From: Joseph.V.Laughlin at boeing.com (Laughlin, Joseph V) Date: Wed, 28 Apr 2004 12:27:43 -0700 Subject: Using C libraries Message-ID: <67B3A7DA6591BE439001F2736233351202876CE9@xch-nw-28.nw.nos.boeing.com> I was thinking more along the lines of unix C libraries, not windows DLL. Also, has anyone had any success getting Python to use Ada data structures? Joe Laughlin -----Original Message----- From: Larry Bates [mailto:lbates at swamisoft.com] Sent: Wednesday, April 28, 2004 12:18 PM To: python-list at python.org Subject: Re: Using C libraries Depends on what you mean by "difficulties". I've interfaced Python with lots of different .DLL libraries. The "tricky" part is getting enough information about the proper data structures for calling the external functions. Much study of struct module is normally required. And you need either my DLLInterface code: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146847 or you can use Thomas Heller's ctypes module: http://starship.python.net/crew/theller/ctypes/ Or you can roll your own... Larry Bates Syscon, Inc. "Laughlin, Joseph V" wrote in message news:mailman.92.1083177600.25742.python-list at python.org... Has anyone had any difficulties using C libraries / data structures with python? Are there any things I need to be aware of? Joe Laughlin Phantom Works - Integrated Technology Development Labs The Boeing Company -- http://mail.python.org/mailman/listinfo/python-list From apardon at forel.vub.ac.be Mon Apr 26 05:14:37 2004 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 26 Apr 2004 09:14:37 GMT Subject: CamelCase versus wide_names (Prothon) References: <6e0680ac.0404211252.7f7b4358@posting.google.com> <4086DFA7.9736E7D3@alcyone.com> Message-ID: Op 2004-04-23, Mark Hahn schreef : > > "Antoon Pardon" wrote in message > news:slrnc8hluh.s60.apardon at trout.vub.ac.be... > >> copy(a)to(b) > > That's cool looking but I'm pretty sure impossible to parse the way you want >:) What is so hard to parse? It is just a sequence of components and argumentlists. You just string the components together to form an identifier and combine all the argumentlists into one. > Although, out angle brackets are free in Prothon right now. We could > reserve them for that: > > copyto. > > Interesting. That would drive newbies to the language crazy :) It sure is > readable. It kind of lets you design you own syntax inside the symbols. > > I must hand it to you. That's one of the most creative crazy ideas I've > seen lately. It is refreshing to see fun creative feedback instead of the > "your language is just Perl" type of feedback. > > Maybe you could hang out on Prothon-user ? Where do I subscribe? -- Antoon Pardon From aahz at pythoncraft.com Sat Apr 10 22:43:02 2004 From: aahz at pythoncraft.com (Aahz) Date: 10 Apr 2004 22:43:02 -0400 Subject: why is python better than eg. smalltalk?? no one has any solid arguments! you should all go to church with all that religious talk! References: Message-ID: In article , Jarek Zgoda wrote: >Jon Perez pisze: >> >> For the past 10 years, I have been in search for a 'holy grail' of >> a text editor and a language. Something I could absolutely devote >> myself to using. After the dozens and dozens I've tried and looked >> at, I can now say to myself that I have found what I've been looking >> for with SciTE and Python. > >I didn't found *the editor* yet (although Eric3 looks very promising), >but my opinion on Python is very similar. I found my editor fifteen years ago. Guess which it is. (The point being that there are only two editors still in regular use that were available fifteen years ago -- and those two editors are still ubiquitous now. Doesn't matter much which you pick, they'll still be available fifteen years in the future.) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Why is this newsgroup different from all other newsgroups? From roy at panix.com Sun Apr 4 19:23:24 2004 From: roy at panix.com (Roy Smith) Date: Sun, 04 Apr 2004 19:23:24 -0400 Subject: Difference between default arguments and keyword arguments References: <10713rf4bjl1bab@news.supernews.com> Message-ID: "John Roth" wrote: > In going through the tutorial I also noticed that it explained > the * notation, but not the ** notation. I think this also needs > to be repaired - if one is in the tutorial, both should be. I suspect this will be an unpopular opinion, but I don't think either belong in the tutorial. I think the function of a tutorial is to introduce somebody to the main features of the language, not cover every nook and cranny of the syntax. The * and ** syntaxes (synti?), while certainly useful, are also somewhat advanced topics. I think their appearance in an introductory document is misplaced. From ville at spammers.com Sat Apr 3 03:22:12 2004 From: ville at spammers.com (Ville Vainio) Date: 03 Apr 2004 11:22:12 +0300 Subject: Indent testers needed (Prothon) References: Message-ID: >>>>> "Peter" == Peter Hansen writes: Peter> I heard a rumour Python is heading for "no tabs", period. Peter> Why not just I find this rumor hard to believe - there would have been some more official announcement, and the resulting code breakage would be major. Not all legacy code can be run through reindent.py either... I think the most sensible thing would be to give warnings on mixed indenting by default, not by some command line switch nobody uses. Newbies get burned by it all the time. Alternatively, change the tab size as interpreted by Python to 321 spaces. The current assumption of 8 violates "explicit is better than implicit". -- Ville Vainio http://tinyurl.com/2prnb From premshree_python at yahoo.co.in Fri Apr 9 05:12:42 2004 From: premshree_python at yahoo.co.in (=?iso-8859-1?q?Premshree=20Pillai?=) Date: Fri, 9 Apr 2004 10:12:42 +0100 (BST) Subject: pyAlbum.py - Python Album Generator In-Reply-To: Message-ID: <20040409091242.50066.qmail@web8311.mail.in.yahoo.com> --- Cousin Stanley wrote: > Premshree .... > > Thanks for making your pyAlbum.py program > available .... Welcome! > > A glimpse of what the Arizona desert east of Phoenix > > toward Globe on highway US 60 looked like > last Sunday April 04, 2004 .... > > http://fastq.com/~sckitching/Album_01 > > Photography by .... John C. Schluterbusch > > The slide show was generated using > a locally edited version of your Python program > pyAlbum .... They are good. > > > http://premshree.resource-locator.com/python/pyAlbum.py > > > It took about 100 Seconds on this machine > to generate the SlideShow for 31 images, > which includes .... > > Generating ThumbNails > Re-Sizing Images > Writing a CSS Style Sheet > Writing the Index HTML Page > Generating the Individual HTML Pages > > This machine .... > > Compaq ...... 250 MHz > Memory ...... 192 MB > System ...... Win98_SE > Python ...... 2.3 Enthought Edition > PIL ......... 1.1.4 > > So, for a S L O W machine, > 100 Seconds ain't too bad .... > So you're happy with the script, eh? I'm glad to hear that! > The edited version that I used .... > > http://fastq.com/~sckitching/Python/pyAlbum.py > > o Re-coded some of the l o n g string > concatenations > and ''' Triple Quoted String ''' % ( w , x > , y , z ... ) substitutions > into join( list_xxx ) function calls > which seemed a bit more readble/editable > > o Added a prompt and code for > Including/Excluding links > to Full-Size images > > o All other changes are basically coding style > cosmetics .... > > > Thanks again for a useful Python program .... Welcome...again! > > -- > Cousin Stanley > Human Being > Phoenix, Arizona > > -- > http://mail.python.org/mailman/listinfo/python-list ===== -Premshree [http://www.qiksearch.com/] ________________________________________________________________________ Yahoo! India Matrimony: Find your partner online. http://yahoo.shaadi.com/india-matrimony/ From tdelaney at avaya.com Wed Apr 28 20:52:48 2004 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Thu, 29 Apr 2004 10:52:48 +1000 Subject: outline-style sorting algorithm Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE016BCAAF@au3010avexu1.global.avaya.com> Thorsten Kampe wrote: >>>>> foo >> ['1.0', '1.0.1', '1.1.1', '1.2', '1.9', '1.10', '1.11', '1.20', >> '1.20.1', '1.30'] >>>>> foo.sort() >>>>> foo >> ['1.0', '1.0.1', '1.1.1', '1.10', '1.11', '1.2', '1.20', '1.20.1', >> '1.30', '1.9'] >> >> Obviously 1.20.1 should be after 1.9 if we look at this as >> dot-delimited integers, not as decimal numbers. > > You need some general approach to avoid the DSU thing: > > def funcsort(seq, func): > """ sort seq by func(item) """ > seq = seq[:] > seq.sort(lambda x, y: cmp(func(x), func(y))) > return seq > > funcsort(foo, lambda x: map(int, x.split('.'))) I've seen you give this advice several times, today, and IMO it's completely wrong. DSU is *exactly* what you want to do. If you want to wrap it inside a general function, that's fine, but DSU is in almost all cases preferred to passing a comparison function - it's much faster. def sorted (seq, cmp=None, key=None): """ sort seq by func(item) """ if key is None: seq = seq[:] else: seq = [(key(e), i, e) for i, e in enumerate(seq)] seq.sort(cmp) if key is None: return seq else: return [i[-1] for i in seq] foo = ['1.0', '1.0.1', '1.1.1', '1.2', '1.9', '1.10', '1.11', '1.20', '1.20.1', '1.30'] foo = sorted(foo, key=lambda x: map(int, x.split('.'))) print foo Note that Python 2.4 will have DSU as a built-in idiom to `list.sort` i.e. `list.sort(key=func)` but will be somewhat more efficient than the above. Likewise there will be a new builtin `sorted` which has exactly the same semantics as the above - it is stable, and it does not ever compare the actual value if a key function is supplied - only the key value (the above also compares the position, but that's an implementation detail and has no visible effect). Tim Delaney From maney at pobox.com Thu Apr 29 14:17:52 2004 From: maney at pobox.com (Martin Maney) Date: Thu, 29 Apr 2004 18:17:52 +0000 (UTC) Subject: CamelCase versus wide_names (Prothon) References: <407ec022$0$54153$1b2cd167@news.wanadoo.nl> Message-ID: Greg Ewing wrote: > Mark Hahn wrote: >> When I first started I thought everyone's opnion mattered and that I had the >> job of merging eveyone's ideas into a grand scheme that made everyone happy >> . > That's the kind of process that gave us COBOL, Algol68 and Ada... Sounds like there's something to be said for it, then. One that's still the underpinning for a scary portion of the heavy lifting behind large corporations, one that died while leaving its influence all over the next generation, and one that... well, two out of three is still 'way above average. -- I look on the events of November and December 2000 in my own country, and I reflect on what a truly science-fictional experience it is to be living under an authentically illegitimate American government, born of force and fraud. -- Patrick Nielsen Hayden (in Starlight 3) From fumanchu at amor.org Sat Apr 10 20:22:40 2004 From: fumanchu at amor.org (Robert Brewer) Date: Sat, 10 Apr 2004 17:22:40 -0700 Subject: new-style class instance check Message-ID: Richard Gruet wrote: > Robert > > Thank you for your suggestion. > But unfortunately, isNewStyleClassInstance(o) must return False for > *everything but* an instance of a new-style class. If o is > e.g. a function: > def foo(): pass > foo.__class__.rmo > > > so isNewStyleClassInstance(foo) would return True ! Yes, function() is new-style. So is int. I think what you're asking for is not whether a given object is new-style or not, but whether it is a *user-defined* new-style object (correct me if I'm wrong). The problem with that approach occurs with, e.g.: class RangedInt(int): def __init__(self, value, lower, upper): int.__init__(self, value) self.lower = lower self.upper = upper Now, since int() creates new-style objects, should RangedInt pass your test or not? If not, then you could simply check the mro to see that there are only two values: the target class and "object": >>> class C(object): pass ... >>> C.mro() [, ] ...but if you want RangedInt(3) to pass when int(3) doesn't, you've got more inspection to do: >>> RangedInt.mro() [, , ] Robert Brewer MIS Amor Ministries fumanchu at amor.org From claird at lairds.com Wed Apr 21 13:21:37 2004 From: claird at lairds.com (Cameron Laird) Date: Wed, 21 Apr 2004 17:21:37 -0000 Subject: This is very simple question References: Message-ID: <108dbd1aftmkc48@corp.supernews.com> In article , Brian Quinlan wrote: > >> I would want to obtain a list of factors (multiples of 2) given a >> prime number in python. >> >> For example 13=[8,4,1], 5=[4,1], 7=[4,2,1], 15=[8,4,2,1] >> >> I would appreciate a fuction which would do this. > >If we told you it wouldn't be fair to the other students in your class :-) . . . I'm surprised only one of the responses I've seen so far has objected to what sure seems like an inappropriate response to classwork. I'm astonished that no one is reading this question as I do. I leave as an exercise for readers this generalization of what *I* think is going on: def positional_addends(positive_integer, base = 2): result = [] current = 1 while positive_integer: remainder = positive_integer % (base * current) if remainder: result.append(remainder) positive_integer -= remainder current *= base result.reverse() return result print positional_addends(13) print positional_addends(5) print positional_addends(7) print positional_addends(15) print positional_addends(78904, 10) The real exercise is to convert this to a readable one-liner, at least for the binary case. -- Cameron Laird Business: http://www.Phaseit.net From richie at entrian.com Thu Apr 1 15:46:06 2004 From: richie at entrian.com (Richie Hindle) Date: Thu, 01 Apr 2004 21:46:06 +0100 Subject: ANNOUNCE: 'goto' for Python In-Reply-To: <20040401193109.GA6475@nl.linux.org> References: <20040401193109.GA6475@nl.linux.org> Message-ID: [Gerrit] > Why don't we call goto '$@' and comefrom '@$'? A bit verbose don't you think? How about ">label" and "" aren't currently used as unary operators. Mind you, at least your suggestion would confuse the perlistas. -- Richie Hindle richie at entrian.com From peter at engcorp.com Tue Apr 13 08:37:32 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 13 Apr 2004 08:37:32 -0400 Subject: A new OS In-Reply-To: References: <107k441hitt2ld9@corp.supernews.com> Message-ID: <6tadnVL-4_mRQubdRVn-tw@powergate.ca> Gerrit wrote: > http://sourceforge.net/projects/cleese > http://cleese.sourceforge.net/ > > I don't believe in it. Apparently no one else really does either, to judge from http://cleese.sourceforge.net/cgi-bin/moin.cgi/RecentChanges -Peter From roy at panix.com Thu Apr 22 23:14:51 2004 From: roy at panix.com (Roy Smith) Date: Thu, 22 Apr 2004 23:14:51 -0400 Subject: Subclasses in Python References: Message-ID: tkpmep at hotmail.com (Thomas Philips) wrote: > I'm teaching myself programming using Python I'm not sure how to parse that. Do you mean, "I'm teaching myself programming, and I'm using Python", or do you mean, "I already know how to program, and now I'm teaching myself Python"? > and have a question about subclasses. My game has two classes, Player > and Alien, with identical functions, and I want to make Player a base > class and Alien a derived class. > [...] > The two classes are almost identical, except that: > 1. When a new player is instantiated or destroyed, Player.n is > incremented/decremented, while when a new alien is instantiated, > Alien.n is incremented/decremented. It sounds from your description that you really want Player and Alien to both be subclasses of a common base class. The reason I say that is because Player.n doesn't get incremented when you create an Alien. > 2. When hit by an energy blast, the player and the alien have > different thresholds below which they die. Again, this sounds like two subclasses of a common base class; let's call it Humanoid. It sounds like hit() and blast() belong in Humanoid, and the "n" attribute should be a class variable of Alien and Player, each of which have their own __init__(). It's not clear what to do with "self.strength = 100" which currently you've got in each Player.__init__() and Alien.__init__(). One possibility is that you could factor this out into Humanoid.__init__(), and have each of the subclass's __init__() call Humanoid.__init__ (self). The other possibility is to just leave it in each subclass's __init__() and not have a base class __init__() at all. The XP folks would yell "refactor mercilessly", but in this case I'm not sure it's justified. BTW, there's nothing in the above that's specific to Python. The same arguments would work in pretty much any OOPL. From abingham at sfu.ca Tue Apr 6 07:26:13 2004 From: abingham at sfu.ca (Aaron Bingham) Date: Tue, 6 Apr 2004 13:26:13 +0200 Subject: Programatically Building MS Access DB Message-ID: <20040406112613.GE11912@nomad> Hello, I am working on a Python app that has to output to an Access DB to keep the customer happy. If possible, I would like to construct the entire database, including tables, querys, and forms, and also the odd simple VM macro, programatically from Python. I've successfully constructed the tables and queries, but I'm having trouble building the forms. In particular, I can set form properties and create controls, but control properties are not saved when I save the form, even if I open the form in design view from my code. Attached is a little program that creates a DB with a table, and a form based on the table. However, the fields on the form are not placed correctly, nor are they bound to the source data. Any ideas? Thanks, -- Aaron Bingham abingham at sfu.ca -------------- next part -------------- A non-text attachment was scrubbed... Name: buildtestdb.py Type: text/x-python Size: 3274 bytes Desc: not available URL: From project5 at redrival.net Fri Apr 30 18:04:00 2004 From: project5 at redrival.net (Andrei) Date: Sat, 1 May 2004 00:04:00 +0200 Subject: Dictionnary vs Class for configuration References: <40929016$0$8635$626a14ce@news.free.fr> Message-ID: <1w1bel01epeem.yr92r722m4ok.dlg@40tude.net> Famille Delorme wrote on Fri, 30 Apr 2004 19:38:53 +0200: > The config_section variable is included in each modules (script python) used > in my program > (with from config.py import config_section) I agree with the other posters that unless you know the end users know Python, you shouldn't configure in Python code (well, unless you have a system (e.g. GUI) to change it for people who don't know Python). > And the use is like this > from conf.py import config_sql > print config["DATABASE"] > > But my master say it's better to do a class like this > class config : > def __init__(self, part=="") : > if (part=="SQL") : > self.database="nanana" > self.userdb="bob" > self.password="*******" > elif (part=="SCRIPT") : > self.timetosleep=10 > self.path="/home/script" > .... Given the choice between dictionary and class, I would probably take the dictionary, because it just has more of a "storage" feel to it. OTOH, the class requires less typing of quotes, which slightly decreases the amount of time spent on writing the program :). > We have do only a file for configuration because the administrator is no > searching for configuration. > I want know : > - what is more faster, dictionnary method or class method? Speed in this case is completely irrelevant. > - what use more ram memory ? As long as you don't plan to have dozens of megabytes of configuration, I don't really see why this would make any difference in your choice neither. > - if you are administrator, what method you like for configure program ? GUI, INI file or, if constrained to your two options, the dictionary approach. Dictionary is probably easier to understand and less intimidating for non-programmers than the class. With the class being modified by non-programmers I'd be very afraid they'd break indentation even if they get the rest of the syntax right. -- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5 at jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From me at privacy.net Fri Apr 9 04:42:01 2004 From: me at privacy.net (Duncan Booth) Date: 9 Apr 2004 08:42:01 GMT Subject: Are line continuations needed? References: <1078dq6i93pc12d@news.supernews.com> <1078skqn9hgdd19@corp.supernews.com> <1079015hfg56i28@news.supernews.com> Message-ID: Josiah Carlson wrote in news:c55811$4be$1 at news.service.uci.edu: > Graham Breed wrote: > >>> I think that you might find there wasn't any indentation to lose. Read >>> the point more carefully and you might see he has a valid concern. >>> Consider this (none of the lines are indented): >>> >>> mystring = """\ >>> +---------------+ >>> | '" | >>> +---------------+ >>> """ >>> >>> Without a line continuation there simply isn't any way to write this >>> string and still have the box characters line up neatly. >> >> >> mystring = """ >> +---------------+ >> | '" | >> +---------------+ >> """[1:] >> > > What about Windows? You'd need to use [2:]. No, [1:] will work fine for windows. Windows stores files on disc with '\r\n' as line terminators, but Python (and most other programming languages) use '\n' internally as the line terminator. > > I would also say that the trailing string slice is ugly. > Agreed. Also it wouldn't work if you wanted the string as a docstring. From richie at entrian.com Thu Apr 1 10:25:54 2004 From: richie at entrian.com (Richie Hindle) Date: Thu, 01 Apr 2004 16:25:54 +0100 Subject: Python as natural language (was Re: ANNOUNCE: 'goto' for Python In-Reply-To: References: Message-ID: [Richie] > This adds the 'goto' and 'comefrom' keywords to Python [Ville] > I like it! I especially like the way comefrom maps to how we > speak. You know, "come here when you are done with the first > file". Programming is hard for the beginners because there really is > no direct mapping of many everyday speech idioms, and comefrom goes a > long way to redeem this for Python. Absolutely. I should have referred to the definitive reference the 'comefrom' statement, "A Linguistic Contribution to GOTO-less Programming" by R. Lawrence Clark in Comm. ACM, Vol 27 Nr. 4 (pp. 349-350) (reprint from Datamation, Dec 1973). [Thanks to Sjoerd Mullender for the full reference.] I confess that although I've implemented the statement, I've never read this seminal paper because I couldn't find a free-to-view copy on the web - I don't suppose anyone knows where such a thing can be found? I'd be interested to see whether Mr Clark discusses the English-idiomatic nature of 'comefrom'. > err = foo() > dostuff() > domorestuff() > :if not err Nice idea, though an 'unless' keyword would make for more idiomatic English Python - we rarely say "if not". Also, you probably want to write 'foo()' *after* 'dostuff' even though it is executed before - consider this example: "Go and buy some more lubricant, unless you find some in the fridge." -- Richie Hindle richie at entrian.com From phil at riverbankcomputing.co.uk Sat Apr 3 18:03:17 2004 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Sun, 4 Apr 2004 00:03:17 +0100 Subject: PyQt & PyKDE current snapshot In-Reply-To: <9sb3k1-s7s.ln1@mcgonnagal.hogwarts.net> References: <9sb3k1-s7s.ln1@mcgonnagal.hogwarts.net> Message-ID: <200404040003.17691.phil@riverbankcomputing.co.uk> On Saturday 03 April 2004 8:07 pm, Markus Zimmermann wrote: > Hi, > does anybody of you know, where to get a current snapshot of PyQt and > PyKDE ? > Thanx, Markus http://www.river-bank.demon.co.uk/download/snaphots/PyQt/ ...for PyQt. There are no snapshots of PyKDE, but expect a new release soon. Phil From project5 at redrival.net Thu Apr 15 13:02:25 2004 From: project5 at redrival.net (Andrei) Date: Thu, 15 Apr 2004 19:02:25 +0200 Subject: CamelCase versus wide_names (Prothon) References: Message-ID: <407ec022$0$54153$1b2cd167@news.wanadoo.nl> Mark Hahn wrote on Thursday 15 April 2004 17:17: > We have agreed in Prothon that unlike Python we are going to be 100% > consistant in our var and method naming. We will not have run-together > words like iteritems, we are going to always have seperated words like > has_key. I don't like underscores in variable names for the same reason as Brendan/OKB: they're hard to type and they slow me down because: a) it's one extra keypress compared to MixedCase (or CamelCase - depending on who you ask) and b) even at same word length, it takes longer for me to type the underscore than any alphanumeric character. Personally I also find MixedCase easier to read than under_scores (especially in code and especially when more than two words are concatenated, e.g. AskUserPermission vs. ask_user_permission - the first is immediateyl obvious as being one word, the second might fool me at first (quick) glance into thinking it's three words). I'm not sure if this universally true or just a matter of what I'm used to. -- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5 at jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From lubowiecka at go2.pl Tue Apr 13 03:10:57 2004 From: lubowiecka at go2.pl (Sylwia) Date: 13 Apr 2004 00:10:57 -0700 Subject: how to force a python service to reconfigure itself after updating? References: Message-ID: Thanks for help! Best wishes, Farraige "Larry Bates" wrote in message news:... > You could move the reading of the configuration > file inside the loop so it is read each time > the service wakes up. Unless your configuration > file is huge (10,000+ lines), the overhead is > negligible. > > The other alternative is to put a socket server > inside the service and have a small external > program to send something to it when it needs > to reread the config file. From mark at prothon.org Thu Apr 22 21:15:42 2004 From: mark at prothon.org (Mark Hahn) Date: Thu, 22 Apr 2004 18:15:42 -0700 Subject: Why we will use obj$func() often References: <84Uhc.22278$dZ1.5087@fed1read04> <8AWhc.23114$dZ1.11070@fed1read04> <40883BFE.B381518A@alcyone.com> Message-ID: <27_hc.23801$dZ1.2716@fed1read04> "Erik Max Francis" wrote ... > Says the guy who's introducing a new operator to his language before > even understanding the behavior of the original one, by his own > admission ... Well, I do tend to exaggerate a bit. I can understand it when I study it, but in everyday coding it does not roll off my fingers. Also, it is possible to design something new without understanding the old. It might even be an advantage in some circumstances to not be tainted by old concepts. I am serious when I say I think that Python has headed off into egghead land a bit and I feel that keeps a lot of people from switching to it. I think that this heady stuff scares them off. I really am trying to make things simpler in Prothon. Now, whether I can succeed or not is another question. Only time will tell. From donn at drizzle.com Sat Apr 24 01:04:38 2004 From: donn at drizzle.com (Donn Cave) Date: Sat, 24 Apr 2004 05:04:38 -0000 Subject: Why we will use obj$func() often References: <84Uhc.22278$dZ1.5087@fed1read04> <8AWhc.23114$dZ1.11070@fed1read04> <40883BFE.B381518A@alcyone.com> <27_hc.23801$dZ1.2716@fed1read04> <40887145.789A2FE8@alcyone.com> <7cki80hj976bia36lhf9er97v073o1pqvm@4ax.com> Message-ID: <1082783076.585831@yasure> Quoth "Mark Hahn" : ... | ... & just | tells the compiler where to find the variable, just like capitalized | variables in Prothon say to find them in the global space and .var says to | find var in self. ... | The whole point is to make things simpler, more readable, and more | efficient, but when people see the & symbol they somehow automatically think | it's complex. Maybe my mind doesn't work like everyone else's. It may be one the language inventor's perils - hard to communicate with people in a language you just invented for the purpose! To me, if you want simple - this counter closure thing is done better with an object. It's weird, unnatural and sounds like an implementation headache to support persistence in a function local variable namespace. I don't know if Python does that already, but that wouldn't make it any better. When I want a thing with persistent data, I'm thinking of an object. One must keep things simple. I think if I were writing a language from scratch, one that's vaguely similar to Python but not especially, I might seriously consider what I believe we call lexical scoping, and a declaration - not assigning a type, but an initial value, like "let x = 0". Namespaces like Python's would be for objects - modules, classes, class instances, whatever - not functions - and would be purely explicit, not implicit like a scope (I think that would most conspicuously require some alternative for "def" statements, for example.) Donn Cave, donn at drizzle.com From "Charles Krug" at cdksystems.com Tue Apr 13 09:34:09 2004 From: "Charles Krug" at cdksystems.com (U-CDK_CHARLES\Charles) Date: Tue, 13 Apr 2004 13:34:09 GMT Subject: Starting a Python COM server from vb? References: <407B3592.7010508@cs.com> Message-ID: On Mon, 12 Apr 2004 19:34:26 -0500, Robert M. Emmons wrote: > >> Pretty much what it says. >> >> I've a number of Python services that I'd like to use from vb. The >> hitch is ensuring the services are started before the VB program tries >> to use them. >> >> Startup folder isn't a good solution, as folks sometimes putter with >> their startup folder options. >> >> Is it as simple as exec()-ing the service script? That IS workable, >> provided VB's exec() function plays nice and allows the service to run. > > Maybe I missunderstand -- but as far as I know there are NO reasons to > RUN anything before you use it. Only thing you need to do is to > register your Python COM servers. > > When you use them in VB, just instantiate them like any other COM > object. Python is not special in any way. > > Rob How do I ensure that the service is registered? Does this need to happen after every bootup? Yes, I AM confused about Win32 services, thank you for noticing :-) Charles From jacek.generowicz at cern.ch Thu Apr 22 12:11:50 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 22 Apr 2004 18:11:50 +0200 Subject: AOP use cases References: <84fc4588.0404140106.3fa0c55@posting.google.com> <0pydnSB4WYuieuLdRVn-hQ@powergate.ca> Message-ID: "Daniel Dittmar" writes: > Jacek Generowicz wrote: > >>> SEPARATION OF CONCERNS. [snip] > > C moved the I/O from the language to a library. This is separation of > concerns Not really. By separation of concerns I mean: Where previously you had to keep two orthogonal goals in mind in a single chunk of code, you now deal with each goal separately. Stupid example: def foo(a): print "before", a a.sort() print "after", a ... print "before", a a.reverse() print "after", a foo(bar) In the above you are manually mixing the concern of modifying an object, with the concern of tracking its changes. In the following you separate them. # Worry about the modifications you want to make def foo(a): a.sort() ... a.reverse() # Worry about tracking changes to an object class mutation_reporter: def __init__(self, obj): self.obj = obj def __getattr__(self, name): if name in mutating_methods: print "before", self self.blah(name) print "after", self def __setattr__(...): ... # Weave together the separate concerns. foo(mutation_reporter(bar)) Is this AOP? Should I care? Is it useful? Should I care? (I guess the way one answers questions 2 and 4, is ... err ... interesting.) From jzgoda at gazeta.usun.pl Wed Apr 7 16:53:54 2004 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Wed, 7 Apr 2004 20:53:54 +0000 (UTC) Subject: [OT] The Cracker's Guide To Python References: <04g770lqpbhdgr3n3b9mnu9o8f08fdkgk0@4ax.com> Message-ID: Christos TZOTZIOY Georgiou pisze: > yesterday afternoon I happened to be in the company of youngsters, and I > overheard them talking about the whereabouts of the crack of the latest > version of some famous video editing software... instead of preaching > about legalities at first etc, I asked: > > "What exactly do you need this software for?" > > "I have two avi files and I want to join them..." > > "Why don't you download VirtualDub and do your job then? Google for it, > it's open source and you can download it freely." > > "So I don't need a crack for it?" > > ... (!) This reminds me some guy that downloaded his copy of MDK9.2 CD images by Kazaa arguing that "something of any commercial value can not be downloaded freely". > It's a crazy world... Indeed! -- Jarek Zgoda http://jpa.berlios.de/ NP: Nick Cave & the Bad Seeds - Sweetheart Come From michele.simionato at poste.it Mon Apr 5 10:50:57 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 5 Apr 2004 07:50:57 -0700 Subject: [maybe OT] Making posters References: <95aa1afa.0404030143.58c32975@posting.google.com> Message-ID: <95aa1afa.0404050650.2d39b1a5@posting.google.com> Jacek Generowicz wrote in message news:... > michele.simionato at poste.it (Michele Simionato) writes: > > > I am looking for a tool taking a postscript file and enlarging it to > > make a poster. > > It's called "Postscript". > > You could start by looking here: > > http://www.cs.indiana.edu/docproject/programming/postscript/operators.html#scale What I do not understand is if the "scale" operator automatically splits the graph in many pages if it becomes too large. Anyway, I have found a way to get what I want from GraphViz, but I cannot check it since the printer died just today! :-( Michele Simionato From anton at vredegoor.doge.nl Tue Apr 13 10:29:56 2004 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Tue, 13 Apr 2004 16:29:56 +0200 Subject: A new OS References: <107k441hitt2ld9@corp.supernews.com> <107lskfjvqvc3e5@corp.supernews.com> Message-ID: <407bf968$0$119$3a628fcd@reader3.nntp.hccnet.nl> Harald Massa wrote: >I propose you should take a look at PyPy first. > >PyPy is an attempt to realise Python in Python. Because "IN THE END" your >Operating System must run on existing hardware. And there is a step between >Python and Assembler... > >With standard CPython it is C-language, with Jython it is Java. > >But there can be C-Errors in Python and C-Errors within Java ... so to get >"only Python", you need a PythonPython first. > >Am I wrong? Yes I think so. PyPy is a nice project, but it is a kind of all or nothing project. What is needed is something like Prothon, but even smaller. Prothon is using a set of separate dlls (f.e. dict.dll, list.dll etc.) to provide the basic objects. This is a lot better than what Python is doing at the moment, because Python depends on one megadll (pythonxx.dll) for these objects. The problem with this approach is that all objects have to be compiled using the same compiler, while it would theoretically be possible to write one dll using C, another using Lisp another using assembler and another using something else. Prothon theoretically could do that, but it loads the basic dlls the moment the interpreter is started, which makes it dependent on having all these dlls available (and possibly all dlls need to be compiled using the same compiler, I don't know about that). What is needed for Python to come closer to the OS and to enable it to advance faster is a bootstrapping interpreter which basically only provides a ctypes alike functionality that enables it to import a set of basic Python object dlls in the same way as if it were standard operating system dlls. It would make no difference for the interpreter if it imported dict.dll or for example kernel32.dll, but of course this strategy would introduce needing to have *some* dlls imported before all others in order to provide basic functionality. This is currently necessary for the __future__ extension too so there is a precedent already. I expect such a beast to have a footprint of about 100k. There would be no problems with Python extensions needing to be compiled with a certain C-compiler since all dlls would be required to conform to the dlls of the operating system. This would bring Python a lot closer to seamless interaction with the operating system and enable it to eventually turn into not a completely separate operating system but into something akin to Cygwin (which is a kind of Linux running under Windows). Another advantage would be that it would be possible to update Python in smaller steps, for example only a newer dict.dll, this time a dll written in assembler or even in Lisp. For systems that don't have this compilers older dict.dll files would still be available. Some Python scripts could have a really small footprint as if it were Lua scripts because we only need to provide those dlls that the script uses, sometimes only dlls that the operating system already has, or dlls that are in Cygwin, Visual Basic or C# and which are freely available on the net. In the latter case probably some flexible dll loader functionality would be necessary, hence the need for ctypes. Or we could compile the necessary dlls on the fly using a Python compile-to-os-specific-dll script that only needed a few standard Python dlls itself. Since I'm not an OS-guru or even know a lot about the lower level details (though I have been able to write and compile extensions in C) I might be wrong about the feasibility of such a project (maybe it can be done but the standardization of dll interfaces would be prohibitively difficult given Pythons dynamic and platform independent development cycle) but I remain confident that this is the way to go. (I'm Dutch you know, so I can't be proven wrong unless you've got a timemachine, I have used mine to post the same kind of idea about half a year ago and I *will* use it to retroactively fix *this* post in case there are problems with it :-)) Anton From greg at cosc.canterbury.ac.nz Wed Apr 28 02:33:24 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Wed, 28 Apr 2004 18:33:24 +1200 Subject: Ideas for Python 3 In-Reply-To: References: Message-ID: David MacQuigg wrote: > Explanation of Simplified Instance Variables > -------------------------------------------- > """ Some of the variables inside the functions in a prototype have a > leading dot. This is to distinguish local variables in the function > from "instance variables". When a function is called from an instance > ( cat1.talk() ) a special global variable __self__ is automatically > assigned to that instance ( __self__ = cat1 ) Then when the function > needs an instance variable ( .sound ) it uses __self__ just as if you > had typed it in front of the dot ( __self__.sound ) The leading dot > is just an abbreviation to avoid typing __self__ everywhere. """ Explanation of Python Instance Variables, Omitting Unnecessary Words -------------------------------------------------------------------- When a function is called from an instance (e.g. cat1.talk()), the instance is passed in as an extra parameter at the beginning of the parameter list, conventionally named 'self'. This allows you to refer to attributes of the instance as 'self.attrname' (e.g. self.sound). ========== END ============== (I've left out mention of the difference between classes and instances, as you did in your explanation even though it's just as important in your scheme. Including it still wouldn't make my explanation significantly longer than yours.) -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From FBatista at uniFON.com.ar Tue Apr 27 15:21:02 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Tue, 27 Apr 2004 16:21:02 -0300 Subject: Tkinter vs. wxPython? Message-ID: [claird at lairds.com] . #- And then you'll write up the experience so the rest of us #- can benefit from your experiment? My plan was not to document the experience: I'm writing this code at lunch time at work, so it's kinda distributed in weeks. And, it's my first code in Tkinter, so it won't represent what anyone can do with experience. But, I was planning to write an essay about the differences between both finished codes. I'll post the link to the list! . Facundo From CousinStanley at hotmail.com Thu Apr 1 18:16:17 2004 From: CousinStanley at hotmail.com (Cousin Stanley) Date: Thu, 1 Apr 2004 16:16:17 -0700 Subject: ANNOUNCE: 'goto' for Python References: <20040401193109.GA6475@nl.linux.org> Message-ID: | .... | How about ">label" and "" | aren't currently used as unary operators | .... The Multics OS used the > and < characters for paths with > indicating a move deeper into the hierarchy and < indicating a move higher in the hierarchy and used for relative paths .... http://www.multicians.org I liked it .... -- Cousin Stanley Human Being Phoenix, Arizona From peter at engcorp.com Thu Apr 15 06:11:02 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 15 Apr 2004 06:11:02 -0400 Subject: Getters and setters in python, common practise In-Reply-To: <407e402c$1@newsflash.abo.fi> References: <407e402c$1@newsflash.abo.fi> Message-ID: Petter Holmstr?m wrote: > Having a Delphi/Object Pascal-background, I'm very used to using getters > and setters when designing my classes. What is the common practise in > the Python world? Should one use them or not? Max described the common practice (don't use them until you actually need them) but forgot to mention that in recent versions of Python you can use "properties", in pretty much the same manner as Delphi uses them. Again though it's common, unless you are still tied to experience in another language (such as Java), not to use even properties until you actually have a case where it's really necessary. Most Python code just directly accesses the attributes and winds up much cleaner as a result. Even historically you could implement the equivalent of get/set under the covers after the fact, using __getattr__ and its ilk, but that's now been made mostly obsolete with properties. -Peter From john at spock.fcs.uga.edu Mon Apr 12 11:15:19 2004 From: john at spock.fcs.uga.edu (John Taylor) Date: 12 Apr 2004 15:15:19 GMT Subject: Problem with dates and daylight savings... Message-ID: I was wondering if some one could explain this anomaly. I wrote a program to add/subtract dates. For example, ./ComputeDay.py 2004/04/12 -7 %Y/%m/%d 2004/04/05 Here is the anomaly.... ./ComputeDay.py 2004/04/12 -8 %Y/%m/%d 2004/04/03 I would have thought this would have returned the 4th. I have a feeling that daylight savings has something to do with this, as the time changed on the 3rd. Can someone explain this? How can I correct this problem? ./ComputeDay.py 2004/04/12 -9 %Y/%m/%d 2004/04/02 Thanks, -John Here is the code: #!/usr/bin/env python2 ## ## ComputeDay.py ## John Taylor, Apr 12, 2004 ## import time import sys ############################################################################ def Usage(): print print "Usage: %s [ t1 ] [ n ] [ format string ]" % sys.argv[0] print "Given arguments t1 and n, where n is a positvie or negative number," print "return the date +/- t1" print """format should be a date format string, such as: %Y/%m/%d""" print "See the man page for strptime for formatting options" print print "Example:", sys.argv[0], "2004/03/01 -1 %Y/%m/%d" print sys.exit() ############################################################################ def main(): if len(sys.argv) != 4: Usage() fmt = sys.argv[3] try: t1 = time.strptime(sys.argv[1], fmt) except ValueError, e: print "Error for t1: ", e return try: n = int(sys.argv[2]) except ValueError, e: print "Error for n: ", e return oneday = 60 * 60 * 24 * 1.0 diff = time.mktime(t1) + (n * oneday) diff = time.localtime(diff) try: result = time.strftime(fmt, diff) except ValueError, e: print "Error for result: ", e return print "%s" % ( result ) ############################################################################ main() -- end of code From mark at prothon.org Thu Apr 22 23:31:41 2004 From: mark at prothon.org (Mark Hahn) Date: Thu, 22 Apr 2004 20:31:41 -0700 Subject: Why we will use obj$func() often References: <84Uhc.22278$dZ1.5087@fed1read04> <8AWhc.23114$dZ1.11070@fed1read04> <40883BFE.B381518A@alcyone.com> <27_hc.23801$dZ1.2716@fed1read04> <40887145.789A2FE8@alcyone.com> Message-ID: "Erik Max Francis" wrote in message news:40887145.789A2FE8 at alcyone.com... > Seriously considering every single possible proposal is not constructive. I could see one making an argument about efficiency, but to say it's not constructive is ludicrous. > Without a strong sense of what the language should look > like, Prothon is going to continue to look more and more like Perl. > It's already most of the way there. You haven't seen the final product. My design process is (and always has been) to go through an expansion phase where more and more gets added or at least considered and then through a contraction phase where the fat gets cut out. I find this process works very well. Please hold off your ad hominem attacks until the product is designed, thank you very much. From chrisl_ak at hotmail.com Wed Apr 14 14:22:25 2004 From: chrisl_ak at hotmail.com (Chris) Date: 14 Apr 2004 11:22:25 -0700 Subject: Python for Presentations Message-ID: Is anyone aware of Python packages/software for generating "presentations"-- something that can generate a nice XHTML/CSS or PDF presentation would be cool. I am looking for a better alternative to PowerPoint for building presentation slides, and if that alternative used Python, that would be even better. Otherwise I could use LaTeX or something, I suppose. From mwh at python.net Fri Apr 2 05:15:59 2004 From: mwh at python.net (Michael Hudson) Date: Fri, 2 Apr 2004 10:15:59 GMT Subject: IPC share queue References: Message-ID: "Joe Wong" writes: > Hi, the buildin Queue() class is good to use among multiple threads > in the program. Is there anything similar to this across process > boundary? I don't believe so. There's POSH: http://poshmodule.sourceforge.net/, which could probably be used to build something similar. I believe POSH is x86 only at the moment, but that's probably fixable by someone with sufficient knowledge and energy... Cheers, mwh -- The Internet is full. Go away. -- http://www.disobey.com/devilshat/ds011101.htm From eeide at cs.utah.edu Mon Apr 26 12:32:20 2004 From: eeide at cs.utah.edu (Eric Eide) Date: Mon, 26 Apr 2004 10:32:20 -0600 (MDT) Subject: AOP use cases References: <84fc4588.0404140106.3fa0c55@posting.google.com> <0pydnSB4WYuieuLdRVn-hQ@powergate.ca> <7NudnQB0EdLerxDdRVn_iw@powergate.ca> Message-ID: "Peter" == Peter Hansen writes: >> Peter> Thanks, but """Full-Text is a controlled feature. Peter> To access this feature: Peter> * Please login with your ACM Web Account. Peter> * Please review the requirements below. Peter> """ Peter> Peter> And it appears memberships must be purchased. Yes, it is true that some sort of ACM membership (individual or institutional) is required in order to access the ACM Digital Library. Those of you who are interested in the paper that I mentioned can probably get a copy by sending email to the authors (who are listed on the cited Web page). Most authors of conference papers are happy to send copies to interested parties; just ask them :-)! I won't post the authors' email addresses here, for fear of increasing their spam load --- but their addresses are easy to find via Google. 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 Kyler at news.Lairds.org Wed Apr 28 14:08:31 2004 From: Kyler at news.Lairds.org (Kyler Laird) Date: Wed, 28 Apr 2004 18:08:31 GMT Subject: sending an object - twisted or what? References: <20040427152051.50234c65.mutah@NOSPAM-libertysurf.fr> Message-ID: "Paul Sweeney" writes: >> SSH is typically available (and already running as a daemon) on most >> computers I touch these days. It would provide for the secure >> transport needed. Any reason not to use it? >It's quite likely this is going the way of xml-rpc over ssh. That seems like a bit of overhead for something that might be simpler. (I'm making guesses about your situation.) Both sides are running Python so it could just be a matter of pickling the object, pushing it to the other side, and unpickling it, right? --kyler From wouter at voti.nl Mon Apr 19 04:12:56 2004 From: wouter at voti.nl (Wouter van Ooijen www.voti.nl) Date: Mon, 19 Apr 2004 08:12:56 GMT Subject: using a USB HID device References: <40827ce3.1151345337@news.xs4all.nl> <4082e29d.1177387563@news.xs4all.nl> Message-ID: <4083899d.1220139618@news.xs4all.nl> >OTOH, it may well be that USB devices, on Windows, cannot be >accessed purely from user mode, and that you always need some >sort of kernel driver. But I can live with something that appears to be pure python, like one which only requires a win-specific addition. after all win32all is windows-specific too, but I regard it as part of the windows-python installation. One more dll is no problem, as long as I don't have to write (and maintain!) it :) Wouter van Ooijen -- ------------------------------------ http://www.voti.nl PICmicro chips, programmers, consulting From edwin at localhost.localdomain Sat Apr 3 17:32:30 2004 From: edwin at localhost.localdomain (Edwin Young) Date: 03 Apr 2004 14:32:30 -0800 Subject: minor bug in cmath.asin? Message-ID: Hi, I think there might (emphasize might) be a minor bug in Python's cmath library. Basically, Python says cmath.asin(0) = 0-0j (+0 real part, -0 imaginary part). I think it should be 0+0j (+0 for both parts). The official formula is at http://functions.wolfram.com/ElementaryFunctions/ArcSin/02/ and is asin(z) = -i * log(i*z + sqrt(1 - z*z)) Which is slightly ambiguous. I read it as: (+0 - 1i) * log(i*z + sqrt(1 - z*z)) But Python's implementation in cmathmodule.c is essentially: -(i * log(i*z + sqrt(1 - z*z))) Which is basically the same as = (-0 - 1i) * log(i*z + sqrt(1 - z*z)) The only difference is +0 vs -0, which not many people will care about, but I thought I'd mention it. Regards, -- Edwin From nhodgson at bigpond.net.au Tue Apr 27 08:15:11 2004 From: nhodgson at bigpond.net.au (Neil Hodgson) Date: Tue, 27 Apr 2004 12:15:11 GMT Subject: How to map python's unicode stuff to a wchar_t based api? References: Message-ID: Ames Andreas: > Therefore I have a default argument useUnicode and > if possible I want to get rid of the > > if (PyObject_IsTrue(useUnicode)) { > doTheUnicodeStuff(); > ... > } > else { > doTheAnsiThingWhichLooksAlmostIdenticalToTheAboveButJustAlmost(); > ... > } > > annoyance in almost any function. To support Unicode file names on Win32, the convention described in PEP 277 is to call the wide API when the argument was Unicode, otherwise call the ANSI API. From src/Modules/posixmodule.c this looks like #ifdef Py_WIN_WIDE_FILENAMES if (unicode_file_names()) { PyUnicodeObject *po; if (PyArg_ParseTuple(args, "Ui:access", &po, &mode)) { Py_BEGIN_ALLOW_THREADS /* PyUnicode_AS_UNICODE OK without thread lock as it is a simple dereference. */ res = _waccess(PyUnicode_AS_UNICODE(po), mode); Py_END_ALLOW_THREADS return(PyBool_FromLong(res == 0)); } /* Drop the argument parsing error as narrow strings are also valid. */ PyErr_Clear(); } #endif This code then falls through to the ANSI API. Py_WIN_WIDE_FILENAMES is only defined (in src/PC/pyconfig.h) when Python is using 2 byte wide Unicode characters (Py_UNICODE_SIZE == 2), thus ensuring that the result on Win32 of PyUnicode_AS_UNICODE is equivalent to wchar_t*. Whether PY_UNICODE_TYPE is wchar_t depends on platform and other definitions. The extra code required for PEP 277 adds to size and obscures intent. Various code reduction techniques can be alleviate this such as posix_1str in posixmodule or using some preprocessor cleverness. Neil From PeterAbel at gmx.net Thu Apr 22 12:14:04 2004 From: PeterAbel at gmx.net (Peter Abel) Date: 22 Apr 2004 09:14:04 -0700 Subject: This is very simple question References: <108dbd1aftmkc48@corp.supernews.com> Message-ID: <21064255.0404220814.102f42a4@posting.google.com> claird at lairds.com (Cameron Laird) wrote in message news:<108dbd1aftmkc48 at corp.supernews.com>... > In article , > Brian Quinlan wrote: > > > >> I would want to obtain a list of factors (multiples of 2) given a > >> prime number in python. > >> > >> For example 13=[8,4,1], 5=[4,1], 7=[4,2,1], 15=[8,4,2,1] > >> > >> I would appreciate a fuction which would do this. > > > >If we told you it wouldn't be fair to the other students in your class :-) > . > . > . > I'm surprised only one of the responses I've seen so far has > objected to what sure seems like an inappropriate response to > classwork. I'm astonished that no one is reading this question > as I do. I leave as an exercise for readers this generalization > of what *I* think is going on: > > def positional_addends(positive_integer, base = 2): > result = [] > current = 1 > while positive_integer: > remainder = positive_integer % (base * current) > if remainder: > result.append(remainder) > positive_integer -= remainder > current *= base > result.reverse() > return result > > print positional_addends(13) > print positional_addends(5) > print positional_addends(7) > print positional_addends(15) > print positional_addends(78904, 10) > > The real exercise is to convert this to a readable one-liner, > at least for the binary case. I'm not quite sure, if I understood, what you mean. One-liners ... OK. Readable ??? Mmmhm ?? i2b=lambda num,s=[],i=1:num and i2b(num>>1,(num &1) and [(num &1)*i]+s or s,i<<1) or s >>> i2b(13) [8, 4, 1] >>> i2b(15) [8, 4, 2, 1] Let's test it in general: >>> sum=lambda l:reduce(lambda x,y:x+y,l,0) >>> sum([8, 4, 2, 1]) 15 >>> for i in range(1,100000): ... if sum(i2b(i))!=i: ... print 'i=%d: sum(i2b(i))=%d' % (i,sum(i2b(i))) ... break ... else: ... print 'OK' ... OK >>> Regards Peter From opengeometry at yahoo.ca Fri Apr 23 21:24:33 2004 From: opengeometry at yahoo.ca (William Park) Date: 24 Apr 2004 01:24:33 GMT Subject: Regexp optimization question References: Message-ID: Magnus Lie Hetland wrote: > In article , William Park wrote: > [snip] > > > >Since you want both the matched strings and their locations in file, you > >pretty much have to this manually, one by one. > > Well -- that's more or less what I'm doing. (Or -- I can get the match > objects all at once, of course, using finditer.) > > I guess I'll have to look elsewhere for performance improvements. Hm. You can write up something in C, as standalone or as patch to Bash shell. Essentially, - locate start of string match - print location (and the string) - move pointer past the end of string. - repeat. Closest you can do using standary tools is strings and byte-offset of the lines the strings occurs. -- William Park, Open Geometry Consulting, Linux solution/training/migration, Thin-client From RobMEmmons at cs.com Sun Apr 18 06:38:32 2004 From: RobMEmmons at cs.com (Robert M. Emmons) Date: Sun, 18 Apr 2004 05:38:32 -0500 Subject: help with str() In-Reply-To: References: Message-ID: <40825AA8.8050404@cs.com> > > No dice. In every case, I get the following error: > > Traceback (most recent call last): > File "headhunter.py", line 317, in ? > response, poster = n.xhdr("from", > first_available_message+"-"+str(last_message)) > TypeError: 'str' object is not callable > > I have tried everything I could think of and there is only one > possibility still left that I can think of. My theory is this: by using > the int() function, I am typing the numbers in the last_message > assignment to type integer, and str() is expecting type float, or > something. str() will work on ints. str() will even work on classes if you have the right special method handler defined. You might want to verify that displaying the value of "str" gives you something like . You can do this by using "print str". Might be fun to try also "print str(str)" and print "repr(str)". You should get the same thing for these others. Why I say that is that it is possible to assign something in your code to str then it's no-longer associated with the built-in function you want, then it might not be callable. You could have done this in your function, or in the global scope for example. Rob Rob From has.temp2 at virgin.net Fri Apr 16 18:06:44 2004 From: has.temp2 at virgin.net (has) Date: 16 Apr 2004 15:06:44 -0700 Subject: (For gurus) Embed functions in webpages like in PHP? References: <5eq4l1-9vm.ln1@pilz.hasos.com> Message-ID: <69cbbef2.0404161406.23a2d3b5@posting.google.com> Robert Ferber wrote in message news:<5eq4l1-9vm.ln1 at pilz.hasos.com>... > As far as I've seen, there is no way to embed Python-code in a webpage with > "" or anything equivalent and I don't see any other way to solve this > problem. If you're open to alternatives, there's also several simplified-DOM templating engines: http://www.entrian.com/PyMeld/ http://www.divmod.org/Home/Projects/Nevow/ http://freespace.virgin.net/hamish.sanderson/htmltemplate.html I think Nevow's maybe still a work in progress, but the other two have been around awhile. (I recommend HTMLTemplate myself, though may be biased as it's one of mine.:) These systems are much simpler and more flexible than traditional 'code-in-markup' systems, compiling an HTML template into a simple object model that can be manipulated directly from Python code. Bit different to what you're used to, but you really should give 'em a look. Simple APIs, low cruft/bloat, and total separation between presentation logic (in Python) and HTML markup. Can be used on their own, or in conjunction with a web framework like Quixote. Not sure of the others, but HTMLTemplate certainly allows you template both full pages and HTML chunks so you can easily compose a page from multiple parts, so implementing selective caching and reuse of semi-static page areas should be straightforward. From peter at engcorp.com Thu Apr 15 07:58:42 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 15 Apr 2004 07:58:42 -0400 Subject: Threading question In-Reply-To: References: Message-ID: Torsten Marek wrote: > Peter Hansen schrieb: >> The other threads are running in, well, other threads, so you >> won't see any effect on the above thread when they end. Therefore >> you can't get much mileage out of a finally clause. A .join() >> is definitely the way to go here. > I found another way to go for now, which works fine for me. > Since the threading module sets sys.exitfunc, I just do: > > def my_exitfunc(): > global thread_wait > thread_wait() > # own stuff follows here... > > thread_wait = sys.exitfunc > sys.exitfunc = my_exitfunc > > That's maybe not very clean, but it's just a minor script I wrote, so I > don't want to waste to much time on it;-) Good solution. You're actually taking advantage of the fact that the main thread does a join() on all non-daemon threads automatically as it exits. The source in threading.py for the "main thread" can make illuminating reading... -Peter From therve at neocles.com Wed Apr 28 05:30:08 2004 From: therve at neocles.com (=?ISO-8859-1?Q?Thomas_Herv=E9?=) Date: Wed, 28 Apr 2004 11:30:08 +0200 Subject: Problem with socket Message-ID: <408f7917$0$27016$626a14ce@news.free.fr> My problem is not really python specific but as I do my implementation in python I hope someone here can help me. I have two programs that talk through a socket. Here is the code : sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.settimeout(5.0) sock.bind(("", port) # We only handle one connection sock.listen(1) while 1: newsock, address = sock.accept() handle(newsock, address) def handle(sock, address) : print "Connection from", address dataReceived = newsock.recv(1024) while 1: try: newsock.send(data) except socket.timeout, err: print "Connection timeout %s" % err break except socket.error, err: print "Connection broken %s" % err break sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(5.0) sock.connect((host, port)) sock.send("Gimme a piece of information, please\r\n") while 1: r, w, e = select.select([s], [], [], 1.0) if r != []: handle_connection(s) def handle_connection(sock): try: response_data = sock.recv(1024) except socket.timeout: print "Socket timeout" return manage(response_data) Ok I hope it's clear. My problem is that "select" only tests if there's data on the socket, and not the state of the socket. I want to be able to know if socket is "alive" or something like that. But I don't want to make "send" in the client (stay passive). Then, if I know that my socket is closed or my link down, I can try to reconnect periodically. I would rewrite the while in the client like that : while 1: if not test_connect(s) : reconnect(s) # else continue normally r, w, e = select.select([s], [], [], 1.0) if r != []: handle_connection(s) From jcarlson at uci.edu Sun Apr 18 13:56:20 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Sun, 18 Apr 2004 10:56:20 -0700 Subject: Does Python compete with Java? In-Reply-To: References: <8b336527.0404051337.51bb4a1b@posting.google.com> Message-ID: > instance. Also, can "and", "or", "not" etc. be overloaded? No one has said it yet, so here's my advice, check the operator module for names you should call your 'overloaded' operators, the ones with __name__ are ones that can be 'overloaded'. http://www.python.org/doc/current/lib/module-operator.html - Josiah From john.abel at pa.press.net Fri Apr 2 04:10:21 2004 From: john.abel at pa.press.net (John Abel) Date: Fri, 02 Apr 2004 10:10:21 +0100 Subject: HTML writer In-Reply-To: References: Message-ID: <406D2DFD.8040509@pa.press.net> You could always try HTMLgen, though I don't know how much CSS it supports. HTH J Moosebumps wrote: >Is there a standard solution for writing HTML web pages with Python? I >don't know that much about web programming, but basically I want to generate >some internal reports on a web page. > >It doesn't need to be fancy, just basic tables and linking, maybe indexing >and navigation, but I want it to all look nice and I want to be able to >change the formatting easily without combing through source code (hence my >next question about CSS). > >I know there newer things like CSS and XHTML -- are these more or less >effort to generate? i.e. are they more complicated, or do they have more >uniform syntax? What do they necessarily buy you? > >I searched the python website and I have seen HTML parsers, but no examples >of generators. I searched for "Python HTML" and "Python CSS" and found some >stuff -- but it doesn't seem like there is a "standard" solution that is >EASY for non-expert web programmers to use. I am an experienced >programming, but I don't know that much about all the alphabet soup that is >web programming. > >thanks, >MB > > > > From peter at engcorp.com Fri Apr 16 20:33:39 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 16 Apr 2004 20:33:39 -0400 Subject: CamelCase versus wide_names (Prothon) In-Reply-To: References: <407ec022$0$54153$1b2cd167@news.wanadoo.nl> Message-ID: <69KdndtPUZT-5h3dRVn-uw@powergate.ca> Jack Diederich wrote: > I'm a wide_case_fanboy, having done mixedCase and wide_names over the last > fifteen years. It all comes down to personal preference, of course. IMO > mixedCase people tend to be younger, and younger people tend to be more > zealous on newsgroups. Define "younger". From martin at v.loewis.de Sun Apr 4 13:47:16 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 04 Apr 2004 19:47:16 +0200 Subject: user authentication via /etc/passwd|/etc/shadow In-Reply-To: References: Message-ID: Marco Herrn wrote: > I want to write a program where I authenticate users via the standard > unix system accounts. I didn't find a module providing this > functionality. Is there such a module available? If not, how can I > achieve this? You need a combination of the pwd and crypt modules. Lookup the name of the user using the pwd module, and fetch the encrypted password. Then use crypt.crypt for encryption; use the first two letters of the encrypted password as the salt. Be aware that some installations use MD5 passwords, which can be recognized by starting with $1$ (or some such). Regards, Martin From root at mbtricot.it Sun Apr 25 10:41:43 2004 From: root at mbtricot.it (root at mbtricot.it) Date: Sun, 25 Apr 2004 16:41:43 +0200 Subject: Virus Alert Message-ID: <200404251441.i3PEfhU20330@linuxbox.mbtricot.it> The mail message (file: message.scr) you sent to mbtfederico contains a virus. (InterScan on linuxbox.mbtricot.it) From heikowu at ceosg.de Thu Apr 22 03:23:27 2004 From: heikowu at ceosg.de (Heiko Wundram) Date: Thu, 22 Apr 2004 09:23:27 +0200 Subject: String/source code analysis tools In-Reply-To: References: Message-ID: <200404220923.27647.heikowu@ceosg.de> Am Donnerstag 22 April 2004 08:56 schrieb Moosebumps: > It is actually sort of like a diff algorithm maybe, but it wouldn't go line > by line. How would I do a diff, token by token? I don't know anything > about what algorithms diffs use. What about difflib? (part of the standard library) You'd have to write your own tokenization function, but that shouldn't be hard... Heiko. From mwilson at the-wire.com Fri Apr 23 16:15:42 2004 From: mwilson at the-wire.com (Mel Wilson) Date: Fri, 23 Apr 2004 16:15:42 -0400 Subject: Why we will use obj$func() often References: <84Uhc.22278$dZ1.5087@fed1read04> <8AWhc.23114$dZ1.11070@fed1read04> <40883BFE.B381518A@alcyone.com> <27_hc.23801$dZ1.2716@fed1read04> <40887145.789A2FE8@alcyone.com> <7cki80hj976bia36lhf9er97v073o1pqvm@4ax.com> Message-ID: In article , "Mark Hahn" wrote: >The benefits of closures are well known. I'll give you the canonical >example, but I'm sure textbooks can give you many more (by the way, Python >cannot do this): > ># tested example >def getFunc(): > counter = 0 > def count(): > &counter += 1 > print &counter > return count > >c = getFunc() >c() # prints 1 >c() # prints 2 >c() # prints 3 It can, if you spell '&' differently: def getfunc(): def count (n=[0]): n[0] += 1 print n[0] return count c = getfunc() c() c() c() Regards. Mel. From __peter__ at web.de Sat Apr 3 04:48:16 2004 From: __peter__ at web.de (Peter Otten) Date: Sat, 03 Apr 2004 11:48:16 +0200 Subject: String concatenation References: <7xisgi24fm.fsf@ruckus.brouhaha.com> <406D27A7.6550A00B@alcyone.com> <406D2CD5.878EBD4E@alcyone.com> <406D2FA2.6E5118CC@alcyone.com> Message-ID: Leif B. Kristensen wrote: > It was of course full of \xa0's. But now that I know about the bug, a > search/replace takes only seconds. I copied it back from the newsgroup with no problems, using only KNode and Kate. This is really strange. Peter From suporte at grad.icmc.usp.br Fri Apr 23 08:19:18 2004 From: suporte at grad.icmc.usp.br (suporte at grad.icmc.usp.br) Date: Fri, 23 Apr 2004 09:19:18 -0300 (EST) Subject: [blockmail] E-mail bloqueado - blocked e-mail Message-ID: <20040423121918.87B23FF544@mail.grad.icmc.usp.br> O e-mail abaixo indicado foi bloqueado por este servidor, pois cont?m um anexo execut?vel. Arquivos execut?veis s?o potencialmente perigosos por constituir meio de propaga??o de v?rus e worms de e-mail. The following e-mail was blocked by this server because it contains an executable attachment. Executable files are potentially dangerous, as they are used for e-mail virus and worms propagation. Mail headers: Date : Fri, 23 Apr 2004 09:27:30 -0300 Subject : Mail Delivery failure (gabicr at grad.icmc.usp.br) From : python-list at python.org Return-Path: Received : from grad.icmc.usp.br (200-158-32-206.dsl.telesp.net.br [200.158.32.206]) To (system): gabicr To (header): gabicr at grad.icmc.usp.br Cc : Bcc : Executables: data12551.pif Mensagem autom?tica - automatic message Blockmail: http://www.icmc.usp.br/~sti/Tutoriais/MainTutoriais.html From ZZZ-ialbert-ZZZ at mailblocks-ZZZ.com-ZZZ Mon Apr 19 13:33:48 2004 From: ZZZ-ialbert-ZZZ at mailblocks-ZZZ.com-ZZZ (Istvan Albert) Date: Mon, 19 Apr 2004 13:33:48 -0400 Subject: Threats to the: Daily Python URL! In-Reply-To: References: <2ae25c6b.0404182250.4c5bc870@posting.google.com> Message-ID: Fredrik Lundh wrote: > the daily URL won't go away. we'll continue to provide fresh links to > potentially interesting stuff for as long as we possibly can (if you want > old links, use google or gigablast). Great! I'm a big fan of the Daily Python URL. But I wish there was an archive. Many times I remembered something that I read there but could not find it again. Regardless of that, thanks for the excellent work Istvan. From klappnase at web.de Thu Apr 22 14:35:37 2004 From: klappnase at web.de (klappnase) Date: 22 Apr 2004 11:35:37 -0700 Subject: tkinter widget collection project References: Message-ID: rick.lawson at rbc.com wrote in message news:... > I, like a lot of developers, have collected a homegrown set of widgets for > Tkinter. > > Any thoughts on a central repository for Tkinter widgets or widget > extensions? Stuff that's not in Tkinter or standard extensions like Pmw. > > It would be nice if you could go to sourceforge and download a package > instead of hunting the Vaults, the Activestate cookbook, googling, etc. > > If there's enough interest I'd be willing to set the project up on > sourceforge and provide some (limited) manpower towards packaging submitted > widgets. > Great idea! Maybe it might be even nicer if it was not necessary to download the whole package; I was thinking of a page where you could directly copy and paste the code of a widget into your application. I'm not sure about that, but maybe the Tkinter wiki Cameron Laird mentioned might be a good place for that, it might make it easier for other people to extend existing widgets (or maybe fix bugs in more complex ones). > Thanks, > Rick Lawson > Thanks to you! Michael From tjreedy at udel.edu Fri Apr 2 12:32:14 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 2 Apr 2004 12:32:14 -0500 Subject: Python conference slogan References: <30260531.0404010833.1b834032@posting.google.com> Message-ID: "Ville Vainio" wrote in message news:du7ptara46v.fsf at lehtori.cc.tut.fi... > >>>>> "Shane" == Shane Hathaway writes: > > >>> I surrender immediately and have to admit that I don't get it (One > >>> Nation Under Under Python). Google was no help. I couldn't find the > > Shane> Ok, it's definitely not good. It's a cross between the > Shane> U.S. Pledge of Allegience and Python's use of > Shane> double-underscores. It was *not* intended to suggest that > Shane> Python replaces deity. ;-) > > Actually, it seems to bring up mostly fascistic connotations, esp. if > you are not American. Throw in the fact that we like to refer to Guido > as BDFL, and you are conveying a very unfortunate image ;-). I originally read this as "One Nation Under Python". As an American somewhat amused by the current court case and concurrent fuss, I thought this a bit funny (but not as a serious proposal). The double under version doesn't do anything for me, but that is perhaps because I do not mentally sound out __. I'll bypass discussion of the socialist/fascist aspects. Terry J. Reedy From whisper at oz.net Fri Apr 16 16:16:22 2004 From: whisper at oz.net (David LeBlanc) Date: Fri, 16 Apr 2004 13:16:22 -0700 Subject: Python CPU? (Re: Python OS) In-Reply-To: Message-ID: > -----Original Message----- > From: python-list-bounces+whisper=oz.net at python.org > [mailto:python-list-bounces+whisper=oz.net at python.org]On Behalf Of Greg > Ewing > Sent: Thursday, April 15, 2004 22:54 > To: python-list at python.org > Subject: Python CPU? (Re: Python OS) > > > Peter Maas wrote: > > The first step would probably be to define a Python OS. Surely no > > CPU speaks Python :) > > Currently, no, but... *could* there be one? > > In one of my wilder daydreaming moments recently, I got > to wondering what a machine designed from the ground up > to run Python code might be like. I got a vision of a > Python interpreter implemented in microcode, with a few > extra bytecodes for low-level hardware access, with an > OS written in Python running on top of it. > > Would it run Python code any faster than an interpreter > running on an off-the-shelf CPU? Possibly not, but it's > not clear that it couldn't, either. In any case, it > would be a fun thing to design, and maybe even to build, > perhaps using an FPGA. > > Anyone want to help? > > -- > Greg Ewing, Computer Science Dept, > University of Canterbury, > Christchurch, New Zealand > http://www.cosc.canterbury.ac.nz/~greg There's a project on sourceforge to develop a Lua microprocessor. Don't know how active it is, but it could suggest some ideas. David LeBlanc Seattle, WA USA From rzantow at ntelos.net Sat Apr 3 08:52:05 2004 From: rzantow at ntelos.net (rzed) Date: Sat, 03 Apr 2004 13:52:05 GMT Subject: Indent testers needed (Prothon) References: <2Msbc.136673$cx5.2385@fed1read04> Message-ID: "Mark Hahn" wrote in news:2Msbc.136673$cx5.2385 at fed1read04: > "rzed" wrote > >> /* loop 2 */ >> ix = 2 >> for >> item >> in >> blist >> : >> alist[ix] = >> alist[ >> ix >> ] > > Do you think this is a good thing or a bad thing? You could do > the same thing or worse in C or Java. > > My first reaction was negative, but in fact I don't think it makes as much difference as it appears to. I'm not going to code like that, and I don't know anyone who will. But the absurdist approach to coding won't necessarily be used just because is possible. The continuation lines in general are more convenient than Python's stricter rule, though I liked the first version of Prothon's rule (a double indent implies continuation) as well. The open-bracket rule in particular seems intuitive. I think either Prothon rule is handier than \ continuations. But I agree with Josiah, in that cut and paste will become problematic if the mixture is not allowed. I tried to make the point to Michael earlier (though apparently in a muddled way). I don't show visible tab marks in my editors, and I don't want to have to, but if I don't, I haven't any good way to know whether a piece of code contains tabs or spaces. Until I run it, at least. -- rzed From project5 at redrival.net Fri Apr 9 09:10:47 2004 From: project5 at redrival.net (Andrei) Date: Fri, 9 Apr 2004 15:10:47 +0200 Subject: improve a Python error message References: <3064b51d.0404081113.58aa1838@posting.google.com> Message-ID: <1vctq85ss4ztd.qh6l6b34xqgu$.dlg@40tude.net> beliavsky at aol.com wrote on 8 Apr 2004 12:13:07 -0700: > x = (1,2 > print x > > gives an error message > > File "err.py", line 2 > print x > ^ > SyntaxError: invalid syntax > > The real error is on line 1, but I guess the error is attributed to > line 2 because the code would be legal if the 2nd line were (for > example) a closing parenthesis. I wonder if the error message Python > produces could be improved. It is technically correct but could > confuse a beginner. Perhaps the message could be > > SyntaxError: invalid syntax (missing closing parenthesis on previous > line?) I think that generally speaking you're right and this type of error does tend to come from forgetting to close parens. But Python doesn't know if you forgot to close the paren or forgot a comma inside a tuple. E.g. it's legal to not close a tuple on the same line where you begin it: >>> x = (1, 2 ... ,3 ... ) >>> x (1, 2, 3) But: >>> x = (1,2 ... 3) File "", line 2 3) ^ SyntaxError: invalid syntax In this case I didn't forget the parenthesis, I forgot the comma. It's also illegal to put a print inside the tuple, regardless of comma and parens: >>> x = (1, 2, print 3) File "", line 1 x = (1, 2, print 3) ^ SyntaxError: invalid syntax Your example is a mix of all three possible errors: you might have forgotten the paren, you might have forgotten a comma and you might have accidentally put a print inside a tuple. Python can't really know what you meant to write there. Imagine you have a variable called Print which you wanted to put inside a tuple, but mistyped it as "print". Python tells you to close your parentheses on line 1, but the mistake is really in line 2, where you should have put a comma, uppercased 'print' and closed the parens. -- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5 at jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From jbperez808 at yahoo.com Fri Apr 9 20:09:20 2004 From: jbperez808 at yahoo.com (Jon Perez) Date: Sat, 10 Apr 2004 08:09:20 +0800 Subject: Indent testers needed (Prothon) In-Reply-To: <60dfb6f6.0404091317.4875c203@posting.google.com> References: <60dfb6f6.0404091317.4875c203@posting.google.com> Message-ID: Carl Banks wrote: >>Asking people to stop switch away from their favorite editors > > He wasn't doing that, bub. So what was he doing... bub? From beliavsky at aol.com Sun Apr 11 14:25:55 2004 From: beliavsky at aol.com (beliavsky at aol.com) Date: 11 Apr 2004 11:25:55 -0700 Subject: Compact Python library for math statistics References: <3064b51d.0404061038.4d69fd89@posting.google.com> <5d83790c.0404090024.5cefb2ea@posting.google.com> <3064b51d.0404091308.472dfb78@posting.google.com> Message-ID: <3064b51d.0404111025.646d4223@posting.google.com> Josiah Carlson wrote in message news:... > > Overall, the Python code below is about 100 times slower than the > > Fortran equivalent. This is a typical ratio I have found for code > > involving loops. > > > > from math import sqrt > > n = 10000000 + 1 > > sum_sqrt = 0.0 > > for i in range(1,n): > > sum_sqrt = sum_sqrt + (float(i))**0.5 > > print sum_sqrt > > Yeah...you may want to consider doing some optimizations to the above > code. Using 'xrange' instead of 'range' is significantly faster > (especially when your machine can't hold 'n' integers in a Python list > in memory), as is the removal of the 'float(i)' cast (which is unnecessary). My original code, the code with range replaced by xrange, and the code with the further replacement of "float(i)" with "i" take 22.0, 20.5, and 14.4 seconds. So it looks like removing unnecessary casts can save substantial time. Thanks. From __peter__ at web.de Sat Apr 3 12:50:19 2004 From: __peter__ at web.de (Peter Otten) Date: Sat, 03 Apr 2004 19:50:19 +0200 Subject: Subclassing file and getting around the file.__init__ rigidity References: <807692de.0404012244.53b476dc@posting.google.com> Message-ID: Jan Burgy wrote: > Hi all y'all, > > Consider the class down below. I've implemented it just because I > needed the pushback method. Now of course the third line in __init__ > doesn't work and I even understand why. My question is: is there any > way to make it work? Somebody proposed a patch for fileobject.c to > allow stuff like fp = file(fp1.fileno()) but it looks like it's been > rejected. I won't so bold as to request a change in Python. Should I > try to re-write this class in C? Although I know C I'm much to lazy to > take on the entire python API, not that it doesn't look nice. > > Thanks for your help > > Jan Burgy > > class BufferedFile(file): > > def __init__(self, name): > if type(name) == file: > self = name # DOESN'T WORK! > else: > file.__init__(self, name) > self.buffer = None > > def readline(self): > if self.buffer: > i = self.buffer.find("\n") > line, self.buffer = self.buffer[:i], self.buffer[:i+1] > else: > line = file.readline(self) > return line > > def pushback(self, line): > self.buffer = line + self.buffer Here's a way to force it by using a wrapper instead of a subclass: class BufferedFile(object): def __init__(self, name, *more): if isinstance(name, basestring): self.fo = file(name, *more) else: self.fo = name assert len(more) == 0 self.buffer = [] def readline(self): if self.buffer: return self.buffer.pop() return self.fo.readline() def __iter__(self): return self def next(self): result = self.readline() if not result: raise StopIteration return result def pushback(self, line): self.buffer.append(line) def __getattr__(self, name): return getattr(self.fo, name) Unfortunately it grew clumsier than I originaly expected because of the duplicated interface (next() and readline() for essentially the same thing). Personally, I would recommend using the subclass approach and drop the requirement of accepting a file object as an __init__() parameter. Still the above has the advantage of working with "real files" and StringIO objects alike (not tested, so don't blame me). Peter From llothar at web.de Thu Apr 15 17:29:16 2004 From: llothar at web.de (Lothar Scholz) Date: 15 Apr 2004 14:29:16 -0700 Subject: Difficulty Finding Python Developers References: <65cbc3dd.0404140641.3501fde8@posting.google.com> <5d83790c.0404150701.605782a7@posting.google.com> Message-ID: <6ee58e07.0404151329.5ad3b61b@posting.google.com> python at rcn.com (Raymond Hettinger) wrote in message news:<5d83790c.0404150701.605782a7 at posting.google.com>... > [Paul Morrow] > > posted a job on Monster, but we have been talking with various > > headhunters in our area and they don't have many resumes that show > > Python experience. An so now, of course, mgt is wondering whether > > selecting Python was a mistake. > > With a C++ code, it is critical for your programmers to have years of > C++ experience. However, with Python, experienced programmers can get > up to speed over a weekend. > But thats only true for the pure language. You still need a lot of idioms and knowledge of the libraries to become really productive with python. And this can increase the time you need. For example if you want to use webware you can get something up within 2 weeks, but you need 2 more weeks to really understand whats going on (at this level you know what is defined in each module and where it is used). From Mike at DeleteThis.Geary.com Wed Apr 28 18:04:23 2004 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Wed, 28 Apr 2004 15:04:23 -0700 Subject: Path ... where is my application's home dir? References: <408fbc0a$0$17256$a1866201@newsreader.visi.com> Message-ID: <1090aj86bk47k02@corp.supernews.com> Roger Binns wrote: > from win32com.shell import shell, shellcon > path=shell.SHGetFolderPath(0, shellcon.CSIDL_PERSONAL, None, 0) CSIDL_PERSONAL is the user's "My Documents" folder, which is not the right place for configuration files. It's for documents that the user explicitly creates and saves. Configuration files generally belong in a subdirectory under CSIDL_APPDATA. Large data files that shouldn't be uploaded and downloaded when roaming profiles are used belong in a subdirectory under CSIDL_LOCAL_APPDATA. On systems that don't support CSIDL_LOCAL_APPDATA, fall back to CSIDL_APPDATA instead. -Mike From tim.golden at viacom-outdoor.co.uk Wed Apr 21 04:33:00 2004 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Wed, 21 Apr 2004 09:33:00 +0100 Subject: Opening MS Word files via Python Message-ID: >I am curious as to how I should approach this issue. I would just >want to parse simple text and maybe perhaps tables in the future. >Would I have to save the word file and open it in a text editor? That >would kind of....suck... Has anyone else tackled this issue? Have a look at antiword: http://www.winfield.demon.nl/ It's not written in Python (afaik) but it writes to stdout. Example: import os ANTIWORD = "c:/antiword/antiword.exe" filename = raw_input ("Enter name of word doc: ") text = os.popen ("%s %s" % (ANTIWORD, filename)).read () print text TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star Internet. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From steve at ferg.org Wed Apr 21 11:42:50 2004 From: steve at ferg.org (Stephen Ferg) Date: 21 Apr 2004 08:42:50 -0700 Subject: I'm looking for a good overview of Tk concepts. References: <_23hc.186323$oR5.125527@pd7tw3no> Message-ID: Look at: http://www.ferg.org/thinking_in_tkinter/index.html It may be useful, and it has links to other places that may be useful. From aahz at pythoncraft.com Fri Apr 2 15:07:28 2004 From: aahz at pythoncraft.com (Aahz) Date: 2 Apr 2004 15:07:28 -0500 Subject: Prothon, metaclasses, Zope [Was: A 'Python like' language] References: <95aa1afa.0403272243.78d60724@posting.google.com> <95aa1afa.0404010017.2f1683b8@posting.google.com> <406d55c6$0$206$edfadb0f@dread12.news.tele.dk> Message-ID: In article <406d55c6$0$206$edfadb0f at dread12.news.tele.dk>, Max M wrote: >Mark Hahn wrote: >> >> As far as top-posting, I am trying to improve, it's just hard to change my >> reply style after using it for 30 years without getting any complaints >> before. I feel like I'm in a twilight-zone episode. > >Actually I am too. There is some interresting dynamics going on here. > >Appart from that Brandon guy, I have never experienced such a reaction >before in this group. I hope it is just a fluke. Mark's the first person I recall seeing who was trying to participate in a serious discussion and also using top-posting. Also, there are a fair number of netiquette snobs here, and when Mark actively rejected the arguments against top-posting, people got annoyed. It was similar to the reaction you might expect from the following exchange: A: B: Please don't post spam, it's not appropriate A: Why not? Spam has a number of beneficial qualities.... I'm always surprised when I find someone who's been active on the Net for more than a few years who isn't even aware of how much a hot-button top-posting is in some communities. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "usenet imitates usenet" --Darkhawk From sarge at arena.invalid Thu Apr 29 16:13:40 2004 From: sarge at arena.invalid (Sarge) Date: Thu, 29 Apr 2004 20:13:40 GMT Subject: Newbe-books Message-ID: Hi, I'm newbe of python, but not of programming (a lot of Matlab, some C, a bit of C++), I want a *good* book on python for self-study. I'm short of money, I don't want to make any mistakes, so does anybody have any suggestions (buy this-don't buy that)? Thanx, Sarge From fredrik at pythonware.com Fri Apr 16 06:49:33 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 16 Apr 2004 12:49:33 +0200 Subject: Tkinter: cut'n'paste from DISABLED window? References: <1076oovf3jd9b28@corp.supernews.com> Message-ID: Michael Geary wrote: > I don't know if this will help, but maybe it will provide a hint... > > In a native Windows app, the way you do this is to make the edit control > read-only instead of disabled. For example, if you right-click a file in > Windows and select Properties, you'll notice that you can select and copy > text from any of the text fields in the General tab of the property sheet. > > The way this is done is by making those text fields Edit controls with the > ES_READONLY style (and without the WS_DISABLED style). Tk's Text widget is a custom widget, which doesn't rely on Windows native widgets. however, in recent versions, many Tk entry widgets supports both state="disabled" and state="readonly", but I don't think this is yet available for the Text widget. as for the original poster, the best way to solve this is probably to add custom mouse bindings for this widget. here's a start (needs a bit of tweaking, but you get the idea): w.tag_config("mysel", background="blue", foreground="white") def start(event): index = w.index("@%d,%d" % (event.x, event.y)) w.mark_set("myanchor", index) def drag(event): index = w.index("@%d,%d" % (event.x, event.y)) w.tag_remove("mysel", 1.0, END) w.tag_add("mysel", "myanchor", index) def copy(event): text = w.get("mysel.first", "mysel.last") if text: add to clipboard w.bind("", start) w.bind("", drag) w.bind("", copy) From jwsacksteder at ramprecision.com Thu Apr 22 10:24:05 2004 From: jwsacksteder at ramprecision.com (jwsacksteder at ramprecision.com) Date: Thu, 22 Apr 2004 10:24:05 -0400 Subject: python web programming / CMS Message-ID: <71650A6F73F1D411BE8000805F65E3CB3B3A6B@SRV-03> You should look at Webware for python, possible in conjunction with SQLObject. -----Original Message----- From: flupke [mailto:flupke at nonexistingdomain.com] Sent: Thursday, April 22, 2004 10:11 AM To: python-list at python.org Subject: Re: python web programming / CMS "Arcane" schreef in bericht news:mailman.910.1082637637.20120.python-list at python.org... > news.telenet.be wrote: > > >Hi, > > > >i'm looking at python to do programming for the new intranet > >here at the company. I'm looking at plone/zope also. > >Before, I've used jsp for webprogramming but i'm considering > >python for this. > >One thing that isn't clear to me is if it's possible to include python > >code in a html page like you would do with jsp and then have zope > >"translate" that to html. With jsp, one could use an apache/tomcat > >combo to accomplish this. > >If one can't include python in html, is Zope the only alternative and > >how does code look like then? > > > >Thanks > > > > > > > > > There are various ways to implement a "PSP (Python Server Pages)"-type > setup. > > I don't know how well regarded it is amongst other python users - in > fact, I'd be interested to know, but I use the > very lightweight Spyce : http://spyce.sourceforge.net. > > I use Spyce-flavoured apache, in combination with python cgi stuff to > great effect on our intranet. > > Hope this helps. (saw name was misconfigured as news.telenet.be) This seems to be doing what i want. However i have some more questions :) 1. Am i correct in thinking i would have to add for instance FastCGI to the Spyce install in order to get it working? 2. In jsp, i often used my own java objects in the code. Can you also do this with Spyce? For instance, if i would have to get data from a db, i would make an object that implements code to do this and then create an instance of that object in a PSP. Is this doable? 3. What databases can be accessed from Python? Flupke -- http://mail.python.org/mailman/listinfo/python-list From peter at engcorp.com Thu Apr 1 09:40:33 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 01 Apr 2004 09:40:33 -0500 Subject: Python Documentation Blows! In-Reply-To: References: <40699A31.8000708@yahoo.com> <20040330161531.GA17112@vulcan.cprogrammer.org> <4069C839.6020109@mlug.missouri.edu> <406a753b$0$12020$79c14f64@nan-newsreader-02.noos.net> Message-ID: Jorge Godoy wrote: > On Qua 31 Mar 2004 10:23, Peter Hansen wrote: >>francois lepoutre wrote: >>>As was mentioned in a recent thread python is definitively >>>the tool for applications with complex code and no or little UI. >>>For UI-intense apps, win32 C# and delphi are still hard to beat >> >>Do you say this because of the design tools, or for some >>other reason? > > One thing my partner always complain about is the lack of database classes > and navigators such as the ones available in Delphi. Specially the ones > that allow you going forward and back in a table with the records without > having to code that by hand. And no, ODBC isn't a good solution according > to him due to several variations of ODBC libraries and changes between > versions. > > I don't know Delphi... I do know Delphi, well, and your partner is right. On the other hand, many of us build GUIs without the least bit of database attached, and would not require such things. That's why I asked francois for his input. For me, wxPython GUIs are plenty fast even with what I would call "complex code", and I know Delphi wouldn't be significantly better for my kinds of GUI. -Peter From hungjunglu at yahoo.com Sun Apr 18 13:56:59 2004 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 18 Apr 2004 10:56:59 -0700 Subject: module not callable - why not? References: <107dras2heahcb6@news.supernews.com> <8ef9bea6.0404122025.36efc84e@posting.google.com> <7xsmf1fxd9.fsf@ruckus.brouhaha.com> Message-ID: <8ef9bea6.0404180956.cd1a152@posting.google.com> One more, I promise I'll stop. (i) For getting attributes by string names, for attributes of instances you do getattr(self, 'name'), for module attributes you do globals()['name']. I mention this because every once a month or so a newbie would ask how to get module level attributes by name. I'm not saying Python made the mistake alone: everyone else in C++/Java, etc. made the same mistakes and a lot more. I'm saying that in hindsight, prototype-based OOP would have saved a lot of troubles. Why split things into 3 or 4 concepts (instance, class, module, metaclass, etc.), when you could just have one (object)??? When you have 3 or 4 different concepts, you are bound to have to duplicate your effort. That's why people asked for staticmethod/classmethod in Python (and they were done.) That's why metaclass came to be. That's why people ask to make modules callable, that's why people ask about properties for modules. It's tiring and complicated to implement duplicated features: too much work, too many syntax conflicts. But if one has started with prototype-based OOP, it only needs to be done once, instead of 2 or 3 times. Why do I think it's a good idea to compile a list of these "symptoms"? Because many people are unfamiliar with prototype-based OOP, and they think there is nothing (or not much) wrong with class-based OOP like Python. When they see a list like what I am showing, they will hopefully understand they have been coping with these redundancies/inconsistencies for a long long time. Problems that needed not to be there, in the first place. It's just a way to help people think "out of the box." :) regards, Hung Jung From ptmcg at austin.rr._bogus_.com Fri Apr 23 23:30:24 2004 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Sat, 24 Apr 2004 03:30:24 GMT Subject: Regexp optimization question References: Message-ID: > One of the reasons I've avoided existing lexers is that I don't do > standard tokenization -- I don't partition all of the text into regexp > tokens. I allow the lexer to skip over text -- somewhat like how > whitespace is normally handled, except that this can be *any* text -- > and to return the next token that is of any use to the current parsing > rule. pyparsing supports this kind of text skipping, using scanString() instead of parseString(). scanString() is actually a generator, yielding for each match a tuple consisting of: - matched tokens (returned as a ParseResults object - sort of super-list, supporting simple list semantics, but some tokens can be named and accessed as in a dictionary or as attributes) - start location in source string - end location in source string Download pyparsing at http://pyparsing.sourceforge.net . -- Paul From rick.ratzel at magma-da.com Wed Apr 21 10:10:03 2004 From: rick.ratzel at magma-da.com (Rick L. Ratzel) Date: Wed, 21 Apr 2004 14:10:03 GMT Subject: Py_ParseTuple Problem References: <4039221c.0404202256.3f21d817@posting.google.com> Message-ID: <40867D57.3050705@magma-da.com> I'm assuming you mean PyArg_Parse and PyArg_ParseTuple? I couldn't find any docs on Py_Parse or Py_ParseTuple... Anyway, maybe something like this might work for you (portions taken from example in http://elmer.sourceforge.net/PyCon04/elmer_pycon04.html): ... PyObject* evalModule; PyObject* evalDict; PyObject* evalVal; PyObject* tupleItem; unsigned char* my_c_array; int i; int tupleSize; PyRun_SimpleString( "result = pyFuncWhichReadsDevice()" ) evalModule = PyImport_AddModule( (char*)"__main__" ); evalDict = PyModule_GetDict( evalModule ); evalVal = PyDict_GetItemString( evalDict, "result" ); if( evalVal == NULL ) { PyErr_Print(); exit( 1 ); } else { if( !PyTuple_Check( evalVal ) ) { printf( "Error: pyFuncWhichReadsDevice() did not return a tuple" ); exit( 1 ); } my_c_array = (unsigned char*) malloc( sizeof( unsigned char ) * PyTuple_Size( evalVal ) ); tupleSize = PyTuple_Size( evalVal ); for( i=0; i < tupleSize; i++ ) { tupleItem = PyTuple_GetItem( evalVal, i ); if( !PyInt_Check( tupleItem ) ) { printf( "Error: pyFuncWhichReadsDevice() returned tuple with non-int value" ); exit( 1 ); } my_c_array[i] = (unsigned char) PyInt_AsLong( tupleItem ); } } ... I have no idea if this will work for you since I haven't even tried to compile it...consider it pseudo-code. -Rick. youngdubliner at hotmail.com wrote: > Hi All , > > Bit of a problem with Py_Parse or Py_ParseTuple ? > > I have a python script that reads a sector of flash in an embedded device. > it returns the value of each byte within the sector as a tuple. > > i.e. [255,255,255,255,255,255,255, .......etc etc for the whole sector ! > > We are using this script to read whats currently in any sector. > No problems there. > > Now I need to call our script from C. > > I want to copy each of the bytes within the sector into an C unsigned char *array > > Is there any way to do this using Py_ParseTuple or Py_Parse ??? > > something like this for instance ??? ...... > > Py_ParseTuple[pres,"??",&my_c_array] > > so now my_c_array[0] = 255 ,my_c_array[1] = 255 ,my_c_array[2] = 255 , etc etc > > > Thanks for the help ! From eppstein at ics.uci.edu Sun Apr 11 22:35:20 2004 From: eppstein at ics.uci.edu (David Eppstein) Date: Sun, 11 Apr 2004 19:35:20 -0700 Subject: print u"\u0432": why is this so hard? UnciodeEncodeError References: Message-ID: In article , David Eppstein wrote: > > I wonder how much would break if Python would assume the terminal > > encoding is UTF-8 on Darwin. Do people use different terminal > > encodings? > > Now I'm curious -- how do you even find out it's a Terminal window > you're looking at, rather than say an xterm? Never mind, I just did a printenv and saw TERM_PROGRAM=Apple_Terminal But I also saw __CF_USER_TEXT_ENCODING=0x1F5:0:0 ...I wonder who's putting that there? -- David Eppstein http://www.ics.uci.edu/~eppstein/ Univ. of California, Irvine, School of Information & Computer Science From martin at v.loewis.de Tue Apr 13 17:02:36 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 13 Apr 2004 23:02:36 +0200 Subject: print u"\u0432": why is this so hard? UnciodeEncodeError In-Reply-To: <16507.22215.60324.63839@montanaro.dyndns.org> References: <16505.58626.39783.581506@montanaro.dyndns.org> <16507.22215.60324.63839@montanaro.dyndns.org> Message-ID: <407C556C.5000305@v.loewis.de> Skip Montanaro wrote: > Skip> I generally use xterm instead of Terminal.app. I think it's > Skip> encoding is latin-1. > > Martin> Not on OS X. > > I run xterms under XDarwin. Sorry, I completely misunderstood. My apologies, Martin From newsgroups at jhrothjr.com Wed Apr 7 10:33:30 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Wed, 7 Apr 2004 10:33:30 -0400 Subject: Are line continuations needed? References: <407409ef.82801353@news.eircom.net> <40740f99@duster.adelaide.on.net> Message-ID: <10784c8ps1vsu34@news.supernews.com> "Derek Thomson" wrote in message news:40740f99 at duster.adelaide.on.net... > Russell Wallace wrote: > > Hi all, > > > > Python lets you continue a single logical line across more than one > > physical line, either by putting a \ at the end or letting it happen > > automatically with an incomplete infix operator. > > > > I'm wondering how often is this feature needed? Would there be any > > problems if it weren't part of the language? > > > > I just needed to use this a few minutes ago, in a class declaration ... > > class ParticleDistributionBehaviorServer \ > (Microphysics__POA.ParticleDistributionBehavior): > > I had to split the line to fit within 80 columns, and without the '\' > character I get the following error: > > ===== > $ python scoping_server.py --POA > File "scoping_server.py", line 8 > class ParticleDistributionBehaviorServer > ^ > SyntaxError: invalid syntax > ===== > > So the fact that you don't need it in the case of incomplete expressions > eliminates *most* of the need for it, but there are still a few cases > where it is required. Technically, you could have split it at the period, but that might be even worse in terms of readability. BTW - why did it have to fit in 80 columns? John Roth > > Regards, > Derek. From rick.ratzel at magma-da.com Wed Apr 28 13:12:33 2004 From: rick.ratzel at magma-da.com (Rick Ratzel) Date: Wed, 28 Apr 2004 12:12:33 -0500 Subject: debugging code In-Reply-To: <3064b51d.0404280658.ccf1894@posting.google.com> References: <3064b51d.0404271139.6ec7057@posting.google.com> <408ee541$0$46510$39cecf19@news.twtelecom.net> <3064b51d.0404280658.ccf1894@posting.google.com> Message-ID: <408fe602$0$3708$39cecf19@news.twtelecom.net> beliavsky at aol.com wrote: > > > > Thanks -- I will take your suggestion. Where are the Python command > line options like -O and -OO documented? Typing 'python -h' just gives > me > > -O : optimize generated bytecode (a tad; also PYTHONOPTIMIZE=x) > -OO : remove doc-strings in addition to the -O optimizations Thats strange. Here they are for Python 2.3.3 as built on my system (should be the same for you): [rlratzel at gt6 ~] python -h usage: python [option] ... [-c cmd | file | -] [arg] ... Options and arguments (and corresponding environment variables): -c cmd : program passed in as string (terminates option list) -d : debug output from parser (also PYTHONDEBUG=x) -E : ignore environment variables (such as PYTHONPATH) -h : print this help message and exit -i : inspect interactively after running script, (also PYTHONINSPECT=x) and force prompts, even if stdin does not appear to be a terminal -O : optimize generated bytecode (a tad; also PYTHONOPTIMIZE=x) -OO : remove doc-strings in addition to the -O optimizations -Q arg : division options: -Qold (default), -Qwarn, -Qwarnall, -Qnew -S : don't imply 'import site' on initialization -t : issue warnings about inconsistent tab usage (-tt: issue errors) -u : unbuffered binary stdout and stderr (also PYTHONUNBUFFERED=x) see man page for details on internal buffering relating to '-u' -v : verbose (trace import statements) (also PYTHONVERBOSE=x) -V : print the Python version number and exit -W arg : warning control (arg is action:message:category:module:lineno) -x : skip first line of source, allowing use of non-Unix forms of #!cmd file : program read from script file - : program read from stdin (default; interactive mode if a tty) arg ...: arguments passed to program in sys.argv[1:] Other environment variables: PYTHONSTARTUP: file executed on interactive startup (no default) PYTHONPATH : ':'-separated list of directories prefixed to the default module search path. The result is sys.path. PYTHONHOME : alternate directory (or :). The default module search path uses /pythonX.X. PYTHONCASEOK : ignore case in 'import' statements (Windows). From Joseph.V.Laughlin at boeing.com Wed Apr 28 17:40:39 2004 From: Joseph.V.Laughlin at boeing.com (Laughlin, Joseph V) Date: Wed, 28 Apr 2004 14:40:39 -0700 Subject: Kiwi Message-ID: <67B3A7DA6591BE439001F2736233351202876D0E@xch-nw-28.nw.nos.boeing.com> Is anyone using the Kiwi wrappers for pygtk? Is there an updated version of it? The one I can find is from 2002 and it doesn't seem to work too well (for starters, it's trying to import libglade and not gtk.glade)... Joe Laughlin Phantom Works - Integrated Technology Development Labs The Boeing Company From fumanchu at amor.org Thu Apr 15 12:35:09 2004 From: fumanchu at amor.org (Robert Brewer) Date: Thu, 15 Apr 2004 09:35:09 -0700 Subject: CamelCase versus wide_names (Prothon) Message-ID: Mark Hahn wrote: > We have agreed in Prothon that unlike Python we are going to be 100% > consistant in our var and method naming. Until the unforeseen happens, of course. ;) > Now we are in the midst of a discussion of camelCase versus > wide_names...of course in the Python world you already have > wide_names as your standard, but could you for the moment > pretend you were picking your standard from scratch (as we > are doing in the Prothon world) and give your vote for which > you'd prefer? Not a vote, just an observation: if you use file names for object names (as in Python, one file per module), you're probably going to want to specify all_lowercase_wide_names to avoid case-sensitivity issues on various platforms. FuManChu From simoninusa2001 at yahoo.co.uk Fri Apr 9 15:53:39 2004 From: simoninusa2001 at yahoo.co.uk (simo) Date: 9 Apr 2004 12:53:39 -0700 Subject: Why Activestate Python ? References: <8089854e.0404090025.141f090c@posting.google.com> <1afv95dy6164y.1a9l3etptcw8w.dlg@40tude.net> Message-ID: <30260531.0404091153.57b571c0@posting.google.com> It's a bloody site easier to install on Solaris if you don't have root access. Unfortunately, the same doesn't seem to go for Windows - the official one seems easier to install without Admin access. From has.temp2 at virgin.net Wed Apr 28 11:22:40 2004 From: has.temp2 at virgin.net (has) Date: 28 Apr 2004 08:22:40 -0700 Subject: What is good about Prothon? References: <69cbbef2.0404271534.6a7c90e6@posting.google.com> Message-ID: <69cbbef2.0404280722.704c7c97@posting.google.com> "Mark Hahn" wrote in message news:... > has wrote: > > > (Note: scripts are compiled, so you'll need a Mac to view source.) > > Can you at least make a screen snapshot available or something for the "rest > of us"? Eh, I'll see what I can do. Here's a short example to get you started: on makeStack() script property class : "Stack" property _linkedList : missing value ------- on push(val) script node property nval : val property chain : _linkedList end script set _linkedList to node return end push -- on top() if _linkedList is missing value then error "Can't get top: stack is empty." number -1728 return _linkedList's nval end top -- on pop() if _linkedList is missing value then error "Can't pop: stack is empty." number -1728 set val to get _linkedList's nval set _linkedList to get _linkedList's chain return val end pop -- on isEmpty() return (_linkedList is missing value) end isEmpty end script end makeStack -- TEST set foo to makeStack() foo's push(3) foo's push(5) log foo's pop() --> 5 log foo's pop() --> 3 In AS, every compiled script is itself a script object. Scripts can be loaded into other scripts using the 'load script' command; this provides the foundation for library-based design. Script objects can also be declared within other script objects and handlers (aka procedures) using the 'script [identifier]...end script' block. This, along with their support for delegation via the 'parent' property, allows you to do prototype-based OOP. Incidentally, because script objects have first-class syntactic support, they also support modular design within a single file, sectioning off parts as separate namespaces without having to move code off into separate files as you'd do in Python; e.g.: ----- begin script (global namespace) ----- property foo : 0 script Sub_Namespace1 -- properties and handlers here end script Sub_Namespace2 -- properties and handlers here end on bar() ... end bar ----- end script ----- (e.g. This ability makes for a very handy halfway stage when refactoring one file into several or vice-versa.) Thus a single, very generic type (script) can perform all the roles that it takes Python several specialised and largely non-interchangeable types (classobj, instance, module) to do. It's such a clean, simple and extremely flexible way to do encapsulation that, though I can understand why more static languages might require the extra layers and complexity, I've never understood why languages like Python, Smalltalk, etc. feel such need to erect all these extra hurdles for themselves. Maybe they just like making work for themselves? Of course, greater freedom also implies greater responsibility and a better understanding of what you're trying to achieve, which might freak some folk from the BDSM school of programming, but that's their problem - and loss. Other nice stuff: while AS allows only a single delegate per object, the ability to compose object behaviour at runtime makes it much more powerful than class-based single inheritance, and less of a PITA to use than MI. Just create and delegate-chain together the objects you want as and when you need them. e.g. I used this approach in my original HTMLTemplate library to construct the various template objects - see for the relevant module (forgive the nasty source code-munging bit in the middle, but one of AS's limitations is an inability to add/remove slots once an object is created*). Compare this with the Python port where I had to use MI to compose behaviour - particularly the older 0.3.2 release where I managed to spaghetti the inheritance tree something awful on my first attempt (I had no such problems designing the AS version where composing objects was a no-brainer). [* Python shouldn't feel too smug, however, seeing as I had no better luck trying to dynamically attach property objects to class instances, and had to resort to sticking nodes into a private dict accessed via __getattr__ and __setattr__.] Obviously, there's some things about the AS implementation that don't translate well to a more Python-like language design: e.g. its use of object-centric Smalltalk/Obj-C-style message passing instead of Python-style bound functions make callbacks a bit of a chore (you have to pass the entire script object around rather than just a function object/pointer), and its lexical/dynamic variable scoping is a bit of a disaster area (though that may simply be down to poor implementation than fundamental design limitation). What's important is just to note the extreme simplicity and total lack of "sophistication" in its script object system; it may be a little _too_ simple for an industrial-size language, but it's a heck of a lot easier to start with an overly simple but clean and coherent model and build upward than begin with something that's over-complex and muddled and try to clean it up. Good programmers know how to add features; great ones know how NOT to. From fredrik at pythonware.com Wed Apr 21 12:03:40 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 21 Apr 2004 18:03:40 +0200 Subject: from newbie: how specify # of times to invoke a regex; conv tuple to string References: <40866ae1$1@news.bezeqint.net> Message-ID: Avraham Makeler wrote: > Summary of Question: How do you specify the number of times to run a > reg ex search using a complex reg ex? > > The reg _expression I wrote goes like this: > > MyRE = > re.compile('([k-z])(?:\'{6,9})(64|32|16|8|4|2|1)(\.)?') > > I ran it using this: > > tplstFound = MyRE.findall(InputStr) > > The problem is that this solution processes the whole input string. I > only need the first matches notes. (I don't know if this is going to make > any practical difference, since the name generation is a one-time thing, and > anyway PCs are very fast these days.) > > I could not see a way of writing the reg ex so that it specifies only > the first 25 matches. I tried putting the {m,n} construct (ie {0,25}) at the > end of the re ex but it did not work. {m,n} binds to the last expression element, not the entire expression. use (?:re){m,n} to repeat the entire re: "(?:([k-z])(?:\'{6,9})(64|32|16|8|4|2|1)(\.)?){0,25}" From mark at prothon.org Fri Apr 23 14:27:59 2004 From: mark at prothon.org (Mark Hahn) Date: Fri, 23 Apr 2004 11:27:59 -0700 Subject: Why we will use obj$func() often References: <84Uhc.22278$dZ1.5087@fed1read04> <8AWhc.23114$dZ1.11070@fed1read04> Message-ID: "Peter Hansen" wrote ... > Mike, you haven't been keeping up with the other thread. I think the > decision is now: > > fish_height$some_where() That is like SO two-hours-ago. Marcia like, told me that Biff like, said that Trish like, said camelCase was SO out, can you BELIEVE IT???? From michael at foord.net Tue Apr 6 11:21:25 2004 From: michael at foord.net (Fuzzyman) Date: 6 Apr 2004 08:21:25 -0700 Subject: ANNOUNCE : dataenc.py and Pythonutils References: <8089854e.0404052348.15e3a04e@posting.google.com> Message-ID: <8089854e.0404060721.1aa998c4@posting.google.com> Peter Hansen wrote in message news:... > Fuzzyman wrote: > > > http://www.voidspace.org.uk/atlantibots/pythonutils.html > > > > Various Python Resources > > > > Dateutils : > > Version 1.0.2 > > > > This is a set of functions for dealing with dates - written for a > > little tool called 'Victory Days'. They are particularly useful for > > dealing with appointments - e.g. the second Tuesday in March etc... > > > > The functions will tell you what day of the week a date is, work out > > the 'Julian day number' of a date is, correctly add numbers of days > > (weeks, months etc) to a date and tell you the number of days between > > a date, format a datestring etc. Full correction for leap years and > > much more. > > No tests? :-( How do you know it works? > > -Peter I use it in various applications... particularly the application 'victorydays' on the same page. (also a Customer Contact database I am writing for our company intranet). In fact there are a couple of tests in the module - but not many... still - I use it regularly and haven't made any changes for quite some time - I consider it stable now.... :-) Regards, Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html From peter at engcorp.com Wed Apr 21 16:15:41 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 21 Apr 2004 16:15:41 -0400 Subject: Python editors for Windows question In-Reply-To: References: Message-ID: Dustin wrote: > I just started programming in Python last night, and I've really enjoyed my > experience so far. I would like to know if there is a Windows editor that > recognizes Python and will support a module syntax/definition lists For > instance, let's say that I set form = cgi and then when I hit the period > (".") on the keyboard, a list of objects shows up, such as FieldStorage(), > etc.. Any suggestions are appreciated. Thank you! SciTE can handle that: http://scintilla.sourceforge.net/SciTE.html So can practically every other halfway decent editor these days, most likely. -Peter From jack at performancedrivers.com Wed Apr 21 11:34:21 2004 From: jack at performancedrivers.com (Jack Diederich) Date: Wed, 21 Apr 2004 11:34:21 -0400 Subject: Optimizing a text statistics function In-Reply-To: References: Message-ID: <20040421153421.GA9062@performancedrivers.com> On Wed, Apr 21, 2004 at 04:51:56PM +0200, Nickolay Kolev wrote: > It is really simple - it reads the file in memory, splits it on > whitespace, strips punctuation characters and transforms all remaining > elements to lowercase. It then looks through what has been left and > creates a list of tuples (count, word) which contain each unique word > and the number of time it appears in the text. > > The code (~30 lines and easy to read :-) can be found at > http://www.uni-bonn.de/~nmkolev/python/textStats.py > > I am now looking for a way to make the whole thing run faster. Do you actually need it to be faster? If the answer is "no, but it would be nice." then you are already done *wink*. A good profiling strategy is to wrap each part in a function so you can see which lines consume the most CPU. Just make sure to wrap big pieces so the function call overhead doesn't get added ten thousand times and distort the picture. You will get a bunch of suggestions on how to make the code faster, so I'll skip those. What you want to do is only do the expensive parsing once and not every time you run your program. Try pickle. [untested code follows] import pickle def proc(txt_filename): # txt_filename like 'dickens.txt' ... exiting code ... reutrn wordCountList def procWrap(txt_filename): cache_filename = tst_filename.replace('.txt', '.pickle') try: fob = open(cache_filename) wordCountList = pickle.load(fob) except IOError: wordCountList = proc(txt_filename) fob = open(cache_filename, 'w+') pickle.dump(wordCountList, fob, -1) # see the docs about the '-1' return wordCountList Use procWrap() instead of proc() to get the list. You'll need to delete the .pickle file every time you change proc() so the pickle gets refreshed. This way you never have to care about how effecient the parsing loop is, because you only have to call it once. -jackdied From imbosol at aerojockey.invalid Sun Apr 4 20:14:58 2004 From: imbosol at aerojockey.invalid (Carl Banks) Date: Mon, 05 Apr 2004 00:14:58 GMT Subject: Python is faster than C References: <406F0907.96F37EA1@tunes.org> <7xy8pcogaa.fsf@ruckus.brouhaha.com> <406F454B.C4CC8063@tunes.org> <7xekr4vdek.fsf@ruckus.brouhaha.com> <406F5E95.EBE6D3E8@tunes.org> Message-ID: <6y1cc.1345$Qv6.328@fe2.columbus.rr.com> Armin Rigo wrote: > Paul Rubin wrote: >> I think you're saying that instead of having xrange return a special >> object, range should return that special object instead. I'm not too >> clear on the distinction. > > No, range should return an object that is a list, as far as you can tell > from Python, but which is represented more efficiently than an array of > objects internally. The distinction is between the language level (it > would be a list, with all operations, etc.) and the implementation > (there is no reason why all lists should be arrays of PyObjects > internally). > > Another example would be 'a'*999999999: the result is a string, but > there is no reason that it takes 100MB of memory. Instead, store it > into a C structure that contains a pointer to the original string object > 'a' and the repetition counter, but still give this C structure the > Python type str, so that the difference doesn't show up and the Python > language remains simple. (This is a bit difficult to implement > currently in CPython, but not impossible.) Hmm. What would be really cool is an abstract sequence type with all kinds of knobs to specify the operations you want to support. In other words, rather than saying "I want a vector" or "I want a linked list," you say, "I want fast indexing, fast sorting, no insertion, and no resizing," or "I want no indexing, no sorting, fast insertion, fast appending on both ends". Then, let the computer choose the actual implementation. Better yet, if the compilation is highly optimized, the compiler could trace the path of the object (best as it can) through the program, and maybe use profiling data too, to see for itself the how the object is used, thus freeing the programmer from even specifying the operations. The programmer could say, "I want a sequence," use it, and the compiler could choose the best implementation. The only thing is, I think that would be prohibitively difficult in an on-the-fly compiled language like Python. Even having a list with one or two optimized forms would have drawbacks: it would be hard to optimize the fast parts with the interpretter second-guessing you all the time, and it would be hard to write extension modules, since they'd have to be aware of all the different layouts, or have to always use an API. And, frankly, I think having a simple implementation is important, too. Complex implementations are more likely to have lots of bugs that could burden users more than some distinct optimized types would. In my opinion, Python is doing the right thing by having one internal form per type. Given that, and keeping in mind that some of these optimizations really do help, the question to ask is: do the extra power and efficiency the optimized version gives you justify the extra burden of complexity on the programmer? I believe that the answer is occasionally yes. Consider tuples. Tuples are for the most part an optimized version of list, but with a few powers list doesn't have, and without a few powers list has. It's the same with iterators. IMO, the the benefit an iterator gives you is far more than the benefit a tuple gives you. I would say 'yes' for an iterator, it's worth a bit of complexity; and probably 'no' for a tuple (although it's close). my-two-cents-ly y'rs, -- CARL BANKS http://www.aerojockey.com/software "If you believe in yourself, drink your school, stay on drugs, and don't do milk, you can get work." -- Parody of Mr. T from a Robert Smigel Cartoon From wilkSPAM at OUTflibuste.net Tue Apr 27 09:45:02 2004 From: wilkSPAM at OUTflibuste.net (Wilk) Date: Tue, 27 Apr 2004 15:45:02 +0200 Subject: Is Perl *that* good? References: <108q51j4dscn7dc@corp.supernews.com> <87fzaqmm8t.fsf@strauser.com> <38ec68a6.0404262308.50029919@posting.google.com> Message-ID: <87u0z55ych.fsf@blakie.riol> Roy Smith writes: > Ville Vainio wrote: > >> >>>>> "Asun" == Asun Friere writes: >> >> Asun> Wouldn't you need to import the re module and compile the >> Asun> pattern first? (And wouldn't you use 'search' rather than >> Asun> 'match'?) And >> >> I rarely compile regexps, just pass the string to the re functions. > > For the occasional ad-hoc match, this is fine. The advantage of > pre-compiling is that it's faster, since it doesn't have to recompile > the regex each time. > > I don't see anything in the reference manual which says re.match() > caches compilations, but I suspect it does. Even a trivial check for > "thisRegEx is lastRegEx" would be sufficient to negate the speed > advantage of pre-compiling in most cases. Anybody know if it does this? Looking at the source code of sre.py, it seems that regexp are auto-cached anyway... def match(pattern, string, flags=0): """Try to apply the pattern at the start of the string, returning a match object, or None if no match was found.""" return _compile(pattern, flags).match(string) def compile(pattern, flags=0): "Compile a regular expression pattern, returning a pattern object." return _compile(pattern, flags) def _compile(*key): # internal: compile pattern p = _cache.get(key) if p is not None: return p I think the advantage of re.compile is just to don't have to repeat the string everytimes... -- Wilk - http://flibuste.net From tim.one at comcast.net Sat Apr 3 22:07:55 2004 From: tim.one at comcast.net (Tim Peters) Date: Sat, 3 Apr 2004 22:07:55 -0500 Subject: minor bug in cmath.asin? In-Reply-To: Message-ID: [Edwin Young] > ... > Does anyone know the history of the cmath implementation? There are > some interesting formulas used for some of the trig functions and I'm > curious to know where they came from. You can browse the entire CVS history of any part of Python online at SourceForge. What that won't tell you in this case is that Guido originally checked in the module as contributed by a scientist, who copied the formulas out of some forgotten book -- and it wasn't a book about numerical analysis. IOW, the formulas were numerically naive. A few of those have been improved over time, but nobody has cared enough about this module to maintain it seriously. From junkmail at solumslekt.org Fri Apr 2 05:26:58 2004 From: junkmail at solumslekt.org (Leif B. Kristensen) Date: Fri, 02 Apr 2004 12:26:58 +0200 Subject: HTML writer References: Message-ID: Moosebumps wrote: > I know there newer things like CSS and XHTML -- are these more or less > effort to generate? i.e. are they more complicated, or do they have > more uniform syntax? What do they necessarily buy you? I don't know anything about Python in relation to dynamic web pages, but I've worked quite a lot with PHP in this respect. XHTML is a very clean implementation of HTML, and should, at least in principle, be much more easily rendered by any browser than ninetyish tag soup. From a coder's point of view, it also of course has a lot of aesthetic appeal. The nicest thing about the XHTML/CSS combination, is the clean division between structure and presentation. The tag should go the same way as the GOTO. I would recommend to read up the specs of XHTML 1.0 on , write some experimental markup, and then try to validate it on . You'll get the hang of it after some iterations. There are many good tutorials on the net for writing XHTML and CSS; do a search on Google. You can of course also learn an awful lot by viewing the source of other people's validating pages. regards, -- Leif Biberg Kristensen http://solumslekt.org/ Validare necesse est From tjreedy at udel.edu Wed Apr 21 14:01:07 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 21 Apr 2004 14:01:07 -0400 Subject: Generator inside a class prevent __del__ ?? References: <4085BA96.651D2E4A@free.fr> <40866ECD.A45758B9@free.fr> Message-ID: "Emmanuel" wrote in message news:40866ECD.A45758B9 at free.fr... > > > Terry Reedy a ?crit : > > > >>> class toto: > > > def __init__(self): > > > print "init" > > > self.Coroutine = self.Gen() > > > > This creates a reference loop. Delete this (and correct typo below) and > > 'problem' will disappear. To amplify: the usual idiom for an instance-associated generator is to name the generator function (method) __iter__ (with one param, self) and to create and get a reference to the generator via iter() or let the for loop mechanism do so for you. c = C(*args) cgen =iter(c) Then there is no reference loop. And you can pass around the cgen object just like any other. If you only need the instance after initialization to get the generator and you only need one generator for the instance, then combine the two lines into cgen = iter(C(*args)) and the *only* reference to the instance is the one in the generator, which will disappear at the end of a for loop or with an explicit 'del cgen'. There is also the question whether you actually *need* to get rid of the object while the program is still running instead of just letting the program finish and clean up. Terry J. Reedy From rajarshi at presidency.com Mon Apr 5 20:55:00 2004 From: rajarshi at presidency.com (Rajarshi Guha) Date: Mon, 05 Apr 2004 20:55:00 -0400 Subject: regex question Message-ID: Hi, this is not specifically a Python question but since I'm doing it in Python I thought I'd ask here. I have a BibTeX file with entries of the form @Article{dkapp3, author = {Kier, L.B}, title = {Distinguishing Atom Differences in a Molecular Graph Index}, journal = {Quant. Struct.-Act. Relat. Pharmacol.,Chem. Bio}, year = {1986}, OPTkey = {}, volume = {5}, OPTnumber = {}, pages = {7-12}, OPTmonth = {}, OPTnote = {}, OPTannote = {} } (it also has entries for Book and InBook) I have an re that is able to get each bibitem: @Article{(.*?)}\n >From the result I can easily get the key using: @.+?\{(.+?), I was wondering if it would be possible to do the two things in one re. That is, first get the string of 1 bibitem and then within that get the key from the matched bibitem. I think I should be using a lookbehind(?) but I'm not sure. Any pointers would be appreicated Thanks -- ------------------------------------------------------------------- Rajarshi Guha GPG Fingerprint: 0CCA 8EE2 2EEB 25E2 AB04 06F7 1BB9 E634 9B87 56EE ------------------------------------------------------------------- Q: What's purple and commutes? A: An abelian grape. From csad7 at yahoo.com Fri Apr 9 17:16:57 2004 From: csad7 at yahoo.com (chris) Date: Fri, 09 Apr 2004 23:16:57 +0200 Subject: raise Exception Syntax question Message-ID: hi, i am wondering if there is a difference between the following possibilities to raise an exception, the first seems to be in all the books about python i have but the second gives the same result at least under Python 2.3.3: >>> import exceptions >>> e = exceptions.Exception >>> raise e, "MESSAGE" Traceback (most recent call last): File "", line 1, in ? Exception: MESSAGE >>> raise e("MESSAGE") Traceback (most recent call last): File "", line 1, in ? Exception: MESSAGE is there a preferable way? thanks chris From fgeiger at datec.at Tue Apr 13 13:48:02 2004 From: fgeiger at datec.at (F. GEIGER) Date: Tue, 13 Apr 2004 19:48:02 +0200 Subject: [wxPython] wxListCtrl_virtual crashes and I can't find what I'm doing wrong References: <407C1D34.8000205@alldunn.com> Message-ID: Thank you, Robin, for answering that quick! "Robin Dunn" schrieb im Newsbeitrag news:407C1D34.8000205 at alldunn.com... > F. GEIGER wrote: > [...] > > > And now I have problems: > > > > This control is named VipAPSpooler. It first used a wxTimer, to update > > itself periodically: If the underlying model had changed in the number of > > items, it exec'ed a DeleteAllItems() and a SetItemCount(). > > Since it's virtual just a SetItemCount should be enough. Okay, I'll try that. > > > > > This did not work: The debugger halted in the MainFrame's(!) on-idle-method > > in line > > > > currentTitle = self.GetTitle() > > > > saying "Inappropriate argument type: an integer is required". > > If an exception happens in some of the C++ wrapper code (such as after > returning from an event handler or a callback), then the next time > control enters Python code the exception is detected and raised from > that point. Normally the C++ code will detect the situation and print > the traceback and then clear the error, but it's possible that this is a > case that it is missed. > > Does the same thing happen if you run outside of WinIDE? Try running it Yes, but see below. > from a command-line window using python.exe so you can see any warning > log messages that wxWidgets is issuing. I seem to recall that WinIDE > has a setting that causes it to stop on all exceptions, even if they are > caught or cleared, perhaps changing that will help. > > > > > > I thought, that using too many wxTimer-s could cause this problem (other > > controls used timers too to update themselves). > > Doubtful, unless you have dozens of timers. Glad to here that. I'll unroll all my changes regarding timers. They are really handy for having controls updating themselves. > > > > > So I decided to eliminate all timers and to write an update method for all > > controls that should be able to update themselves. This update-method were > > then called from the MainFrames's on-idle-method. The rationale: No more > > timers and only one on-idle-method. > > > > But that did not solve the problem. The same and sometimes other weired > > errors popped up now in code called by OnGetItemAttr() ans OnGetItemText() > > of the virtual wxListCtrl. > > > > Example: > > > > def __str__(self): > > if self._value: # <- "Inappropriate argument type: an integer is > > required". > > return str(self._value) > > return '' > > > > Or this: > > > > def OnGetItemAttr(self, item): > > if item == self.model().currentLineNbr(): # <- "Inappropriate argument > > type: an integer is > > return self._attr > > return None > > > > > > Executing the offending line in the Debug Probe (yes, it's WingIDE) in each > > case passes w/o problems - weird. Looking at the stack data doesn't show any > > data corruption, everything seems okay. > > Because it probably happened in whatever weas executed before the error > was detected. > > > > > I commented out this and that and seem to have found out, that as soon > > SetItemCount() is called, the control is no more able to do its job. > > > Do you also implement OnGetItemImage? Does it always return an integer? > (If you don't use an ImageList for this control then just return -1.) > That's it . I had written: def OnGetItemImage(self, item): # if item % 3 == 0: # return self.idx1 # else: # return -1 pass Oh god, how embarrassing! When I deleted the whole method, wxPython 2.5 threw a wxAssert stating, that OnGetItemImage() shouldn't be called or something like that (can reproduce that if there's interest on it). Anyway, overriding this method seems to be a must. But with the right return value, of course... So, writing def OnGetItemImage(self, item): return -1 did it. Small cause, big effect. Again, thanks a lot, Robin! Kind regards Franz GEIGER > -- > Robin Dunn > Software Craftsman > http://wxPython.org Java give you jitters? Relax with wxPython! > > > --------------------------------------------------------------------- > To unsubscribe, e-mail: wx-users-unsubscribe at lists.wxwidgets.org > For additional commands, e-mail: wx-users-help at lists.wxwidgets.org > From jcarlson at uci.edu Thu Apr 8 23:28:29 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Thu, 08 Apr 2004 20:28:29 -0700 Subject: GUI Frameworks in Python? In-Reply-To: <4073C495.2050106@cosc.canterbury.ac.nz> References: <930ba99a.0404030246.786455f5@posting.google.com> <8ef9bea6.0404041009.26ae2683@posting.google.com> <4073C495.2050106@cosc.canterbury.ac.nz> Message-ID: >> Simpler? According to Greg, passing ids of the widget was a >> pain...well, in 2.5 you can pass the widget. Apparently that is >> significant enough to warrant Greg complaining about it, and Robin >> Dunn to fix it. > > > Like I said, it's not a big deal on its own, just something > that seemed needlessly awkward, among many others. Some > other examples: You can't create a widget until there's a > parent for it, forcing you to create widgets in a certain > order. When you create a widget, you have to either specify > an ID number, or -1 to say you don't care what its ID number > is (I didn't, mostly), instead of just letting it default. > Most widget constructors seem to take about half a dozen > parameters that you have to get in the right order because > you can't specify them using keywords. And so on. You know, the vast majority of widgets are created in the exact same way... widget(parent, id,...) Where everything in the '...' part /can/ be a keyword, unless that has changed for 2.5 (it works in 2.4 just fine). In terms of ordering, requiring a parent to be present before you create the child, I believe, is pretty standard. Conceptually it seems to be so that you can hook the child up to the parent event handlers during initialization, so you don't have to do multi-part initialization. > All these small things added up to an experience that I > didn't enjoy much overall. That is unfortunate, but I suppose as long as you found a toolkit that works and that you like using, it's all good. - Josiah From roy at panix.com Thu Apr 15 13:44:47 2004 From: roy at panix.com (Roy Smith) Date: Thu, 15 Apr 2004 13:44:47 -0400 Subject: CamelCase versus wide_names (Prothon) References: <407ec022$0$54153$1b2cd167@news.wanadoo.nl> Message-ID: Here's my entirely non-scientific two cents on this. I stated out programming on teletypes and card punches which only had a single case, so I got used to underscores. When bumpyCase started showing up 10 or 15 years ago, I thought it was froofy and ugly and hated it. Gradually, I've come around and now find mixed upper/lower very natural (including the initial cap for class names) and despise underscores. If an old goat like me can change, I figure everybody else can too. It's entirely unclear how any of the above should influence your decisions on language design :-) From mcfletch at rogers.com Fri Apr 23 01:22:44 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Fri, 23 Apr 2004 01:22:44 -0400 Subject: Why we will use obj$func() often In-Reply-To: <8AWhc.23114$dZ1.11070@fed1read04> References: <84Uhc.22278$dZ1.5087@fed1read04> <8AWhc.23114$dZ1.11070@fed1read04> Message-ID: <4088A824.4030009@rogers.com> Mark Hahn wrote: >Mike C. Fletcher wrote: > > > >>This isn't really a very clear description of what's going on in >>Python. It won't matter to the Prothon users, but don't want any >>Python users to get confused... >> >> > >My inability to understand this stuff is what drove me to do Prothon . >All the hidden wrapped this and wrapped that confused me to no end. > > Fascinating. Most users never even notice this stuff, let alone getting so worked up about it that they start a whole separate language ;) . After all, they don't generally even know that metaclasses *exist* and just know that it all works exactly as they would expect. You for instance, were describing how the interpreter just knows that a class can't be the target of an unbound class method. Sure, *maybe* it's all a hideously complex mess that has people running screaming from Python in horror, but from where I sit it is an extremely elegant system that most people use without any impedance mismatch at all. >> By the way, the modern Python idiom is: >> >> super( klass2, self ).func( ) >> >> >> > >You're kidding. That seems like a big leap backwards in friendliness. Kind >of a syntax castor oil. > > Explicit is better than implicit. You are attempting to call the superclass' method; using: klass.func( self ) is actually a far less maintainable and composable idiom. Here you are saying "call this *particular* superclass' method", introducing a dependency on the class' current superclass inside the method call. The super() version does introduce a dependency on the *current* class inside the call, but that's generally far less likely to mess up as code gets revised. super(), in other words, is a practical solution to avoiding the explicit dependencies that crop up when you directly reference a super-class. It solves problems *for large-systems developers* who need robust, cooperative, composable functionality (e.g. via mix-in classes). klass.func() might seem prettier and shorter in small systems, but it's something that Python's user community has outgrown over the years (if you can troll so can I ;) ). >That's explains why Joe Mason did his proposal for Prothon delegation using >that same idiom for Prothon. I thought he was somewhat crazy wanting us to >type all that each time. > > It's not the most elegant spelling of the idiom, that's true, but it was added without introducing any new magic. When creating a new language you can decide to add new magic to the system solely as a question of "what is right". When evolving a highly successful system, introducing new magic is a serious concern: super.func() with super as a key-word would be fine in Prothon, as there's no code that depends on using the name super. super().func() would work just as well, with the interpreter figuring out which class super() is being called from within but what happens when it's defined outside a class and injected later? After all, it's the class where it's *defined* that matters, not the one where it's being used. So Guido went for the minimum of magic. There's no special restriction on a function that uses super that the function must be defined in a class, there's no rules to figure out whether it affects inner or outer classes, there's, in short, no magic required to learn the idiom, it's a simple class instantiation like just about everything else. Special cases aren't special enough to break the rules. Although practicality beats purity. super is used primarily by large-systems developers (meta-programmers), so having the functionality require the introduction of special magic and rules for regular users (every time they see an instance of "magic" they need to learn what it does) seems unnecessarily "special". Implementing super as a simple class means that, should someone be interested, they can simply look up the implementation and go "ah, I see what it does", but until then they can understand it as a simple call that returns a wrapper which gives the superclass of the passed class in the passed instance' mro... i.e. it's a black box that follows all the regular rules of functions/callables in Python. Language design is about balancing the minimal set of ideas needed to give full generality and power with the need for expressivity and practicality. So far Guido's decisions have been, IMO, a fairly good balance. There are warts, but every language will have warts. Python is a *small* language where, particularly in the later incarnations the special cases are going away and the same basic mechanisms are getting used in more and more places (e.g. with descriptors). The reduction of special cases is an important design tool. >What problem caused Python to want to switch to such a general operation? >What is the usage case that is so important that it is making eveyone wear >out their keyboards typing that monstrosity? > > Remember, this is the Python list, we tend to find hugely rhetorical arguments somewhat off-putting ;) . On the other hand, we've extinguished more potential flamewars than I can count over the years, so it's not like the universe is going to collapse because of a few overblown statements :) . If it did I would have doomed us all ages ago :) . >Oh well, I guess it gives me one more argument to pitch for Prothon... > > Sure, the magic you sprinkle through your system is part of its flavour and character, that character is how languages sell themselves. Though honestly, if someone seriously came up to me and said: "Switch to Frobnaz, it has explicit syntax for referencing a superclass rather than that archaic explicit invocation stuff in Python" I'd probably dismiss them out of hand as being so totally out of touch with reality as to be not worth the effort of listening (well, not really, I *try* not to dismiss people out of hand no matter how crazy they are). Addressing a few of Python's warts is *not* going to make the world beat a path to your door. If you are going to get people to make a clean leap to your language (i.e. it's not source-code compatible with their current language, and doesn't have some compelling feature/niche) you need to design something that's about two times better, and you don't design something twice as good by copying and tweaking. You do it by making intelligent design decisions that create a coherent language that fits well with people's expectations, that fits in their mind without a lot of magic and arbitrary rules to remember (PERL, of course being the exception that proves the rule, where the attempt is to simply guess everything the user might want to do and create an explicit syntax for that ;) ). Your language *will* have it's own warts, that's a simple reality, pointing out that you don't have the same warts *in the same places* as another language is not a compelling argument for switching. For instance, I would almost certainly consider the fishHeight$Somewhere() syntax to be a wart ;) , so being told that I can save 20 characters or so in typing super (which I've only done maybe one or two hundred times since it was introduced) by introducing something that my end-developers are going to have to be trained on doesn't really make me wet my pants in anticipation and joy :) . After all, I've probably typed almost that much in this email alone. Oops, dang keyboard wore out again ;) , Mike _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From miki.tebeka at zoran.com Mon Apr 19 08:51:25 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Mon, 19 Apr 2004 14:51:25 +0200 Subject: imitating user input In-Reply-To: References: Message-ID: <4083CB4D.7050101@zoran.com> Hello Greg, > I need to imitate keyboard strokes in an active window inside of > internet explorer, specifically I need my program to log on to a > chatroom without me actually sitting in front of my computer. Also, > once it has logged on to the program I need my program to "read" > (search for strings, etc.) the text that's entered by other users in > this "chatroom". The problem I have is actually logging in to the > chatroom since I have not found a way to duplicate keyboard strokes. I agree with the other response, however if you're interested in generating key strokes anyhow have a look at AutoIt (http://www.hiddensoft.com/AutoIt/). You can use either the executable by generating scripts or the ActiveX component (or even the dll with ctypes). HTH. Miki From elainejackson7355 at home.com Sat Apr 10 23:47:16 2004 From: elainejackson7355 at home.com (Elaine Jackson) Date: Sun, 11 Apr 2004 03:47:16 GMT Subject: Tkinter Button image option Message-ID: <8d3ec.74988$Ig.46341@pd7tw2no> When I try to put an image onto a Tkinter button, I get a message that says the image in question "doesn't exist" (it does, though). One of the references I looked at said that Tkinter has to be "configured for" the Python Imaging Library in order for the 'image' option to work. I've got the PIL, but as for "configuration", I don't know. Maybe I need to reinstall Tcl/Tk? If anyone can point me to the appropriate resource, I'd be very much obliged. Peace From me at privacy.net Tue Apr 6 07:52:32 2004 From: me at privacy.net (Duncan Booth) Date: 6 Apr 2004 11:52:32 GMT Subject: int('2.1') does not work while int(float('2.1')) does References: <40722555.66C70D40@alcyone.com> <40722E98.253B5FF2@alcyone.com> Message-ID: Joe Mason wrote in news:slrnc74t4i.ccv.joe at gate.notcharles.ca: > In article <40722E98.253B5FF2 at alcyone.com>, Erik Max Francis wrote: >> Joe Mason wrote: >> >>> Why can it make this guess for "int(2.1)", then? It's got a rule for >>> converting floats to ints - why not use it here? >> >> Because int(aFloat) means round toward zero. int(aString) means make an >> int out of this string. > > So why can't int(string) mean round toward zero? > If you want to round towards zero then you have an easy way to do it: int(float(string)) If int(string) was changed to have this behaviour as well, then those of who don't want any rounding wouldn't have any way to get the current behaviour. Users may be surprised when they enter 2.1 and find the program accepted it but didn't use the value they entered; I don't like suprising users. Or in more concise terms: Explicit is better than implicit. From joe at notcharles.ca Fri Apr 16 00:25:16 2004 From: joe at notcharles.ca (Joe Mason) Date: Fri, 16 Apr 2004 04:25:16 GMT Subject: CamelCase versus wide_names (Prothon) References: <1XIfc.246$GN6.122@fe2.columbus.rr.com> Message-ID: In article <1XIfc.246$GN6.122 at fe2.columbus.rr.com>, Carl Banks wrote: > but avoid the wide names when they're uber-ugly and unreadable in > operator-laden code like this: > > pitch_rate_coefficient = pitch_rate*mean_aerodynamic_chord/total_airspeed Spaces are a much better way to fix this than camelCase. pitch_rate_coefficient = pitch_rate * mean_aerodynamic_chord / total_airspeed > It would not surprise me if the people who prefer wide names tend to > be applications-type programmers, whereas those who prefer camel case > naming tend to be numerical-type programmers. I'm somewhat surprised numerical-type programmers don't just use ubershort variable names. Using _ for subscript: P_r_c = P_r * ADC_m / A_t (I'm not advocating this style, but seems like direct translations from math or engineering algorithms would encourage it.) Joe From tundra at tundraware.com Sat Apr 24 20:30:08 2004 From: tundra at tundraware.com (Tim Daneliuk) Date: 24 Apr 2004 20:30:08 EDT Subject: command-line args In-Reply-To: References: Message-ID: <23drl1-d592.ln1@eskimo.tundraware.com> Michael wrote: > What's the perfered method of passing command-line args throughout a > Python program given that globals don't seem to really exist? I thought > of writing them out to a python file and then importing them when > needed.. but that seems like it'd only work for a single process.. not > in instances where more than one user is running the program. There > isn't anything like a virtual file space that could be used for this? > Anyway to set a global variable? > If I may be so immodest, I have just released this as another way to set program options: http://www.tundraware.com/Software/tconfpy/ Keep your options in a text file with each option in the form: option = value Call tconfpy.ParseConfig("myconfigfile") and you'll get back (among other things) a populated symbol table with each option as one of the keys... -- ---------------------------------------------------------------------------- Tim Daneliuk tundra at tundraware.com PGP Key: http://www.tundraware.com/PGP/ From bkelley at wi.mit.edu Tue Apr 27 10:37:42 2004 From: bkelley at wi.mit.edu (Brian Kelley) Date: Tue, 27 Apr 2004 10:37:42 -0400 Subject: interfacing to a remote excel app In-Reply-To: <20040426150428.69010a3c@pistache.sara.nl> References: <20040426150428.69010a3c@pistache.sara.nl> Message-ID: <408e7066$0$561$b45e6eb0@senator-bedfellow.mit.edu> One solution that I have used is a COM/CORBA bridge. A fairly decent one is here: http://www.octatec.co.uk/CB_sum.htm But it still requires installation on the windows box. Your goal is pretty easy actually if you can install python on the windows box. Now for a completely off the wall suggestion. Have you tried win32all and DCOM running under wine (linux win32 api)? That might supply enough of the framework for you to get things running. I'd be very interested if you can get this to work :) Brian Kelley From asdf at asdf.asdf Wed Apr 21 12:36:48 2004 From: asdf at asdf.asdf (Garett) Date: Wed, 21 Apr 2004 10:36:48 -0600 Subject: saving interpreter source? Message-ID: Hello, I would like to be able to save source typed into the interpreter to a file. Kind of like marshal, but I would like to have the file contain the source so I can edit it later. Something like inspect.getsource() but for source typed into the interpreter, not imported from a module. Is this possible? Any ideas are greatly appreciated. -Garett From bokr at oz.net Thu Apr 29 12:02:49 2004 From: bokr at oz.net (Bengt Richter) Date: 29 Apr 2004 16:02:49 GMT Subject: String formatting (%) References: Message-ID: On Wed, 28 Apr 2004 09:15:02 -0400, Peter Hansen wrote: >Pascal wrote: > >> Hello, >> I've a float number 123456789.01 and, I'de like to format it like this >> "123 456 789.01". >> Is this possible with % character? > >No, as shown by http://docs.python.org/lib/typesseq-strings.html >but you could probably use the 'locale' module instead. > >I suspect there's also a regular expression that could deal with >that, but I don't want to know what it is. ;-) > If you are willing to use a special name mod (you can choose it), you can get there with % and a commafy that stuffs spaces instead of commas ;-) >>> class Doit(dict): ... def __init__(self, d): dict.__init__(self, d) ... def __getitem__(self, name): ... if name.startswith('cfy_'): ... return commafy(self.get(name[4:],'??')) ... else: return self.get(name,'??') ... >>> def commafy(val): ... sign, val = '-'[:val<0], str(abs(val)) ... val, dec = (val.split('.')+[''])[:2] ... if dec: dec = '.'+dec ... rest = '' ... while val: val, rest = val[:-3], '%s %s'%(val[-3:], rest) ... return '%s%s%s' %(sign, rest[:-1], dec) ... >>> x=1234 >>> 'x: %(x)s cfy_x: %(cfy_x)s' % Doit(vars()) 'x: 1234 cfy_x: 1 234' >>> x=12345.678 >>> 'x: %(x)s cfy_x: %(cfy_x)s' % Doit(vars()) 'x: 12345.678 cfy_x: 12 345.678' >>> x = -12345.678 >>> 'x: %(x)s cfy_x: %(cfy_x)s' % Doit(vars()) 'x: -12345.678 cfy_x: -12 345.678' And the OP's example: >>> x = 123456789.01 >>> 'x: %(x)s cfy_x: %(cfy_x)s' % Doit(vars()) 'x: 123456789.01 cfy_x: 123 456 789.01' Regards, Bengt Richter From p_s_oberoi at hotmail.com Thu Apr 15 21:04:04 2004 From: p_s_oberoi at hotmail.com (Paramjit Oberoi) Date: Thu, 15 Apr 2004 20:04:04 -0500 Subject: CamelCase versus wide_names (Prothon) References: Message-ID: > 1) CamelCase is more elegant, modern, more readable, and more efficient in > character usage. > > 2) Wide_names is cleaner, more readable, compatible with C, which is the > standard module language for Python and Prothon. Wide_names is also the > Python standard. wide_names please. I have tried both and this is what I think: * wide_names is clearer & easier to read. - particularly with one and two letter words - ideally I would like to be able to use hyphens like-this, but that unfortunately clashes with subtraction (this is the only positive thing I remember about COBOL: variables with hyphens) * wide_names is easier to type. - camelCase requires the set [a-zA-Z], wide_names only requires [a-z_]. *MY* fingers find it easier to get used to one shift-key combination rather than 26. I propose that the underscore key be added to all keyboards to make things even easier (I should remap my windows key...). * the real problem is the absence of a character for indicating non-breaking spaces---that's why we have to use all these damn_WorkArounds. * I am of the opinion that identifiers/filenames/reserved words should be case insensitive. Or alternatively, case should be enforced but no two should be allowed to differ only in their case. Pascal got this right... -param From nelson at monkey.org Sat Apr 24 13:24:46 2004 From: nelson at monkey.org (Nelson Minar) Date: Sat, 24 Apr 2004 17:24:46 GMT Subject: python for console game development, memory tracking References: <6soic.40551$c77.17448@newssvr29.news.prodigy.com> Message-ID: "Moosebumps" writes: > When I have time, I am planning to evaluate Python for console game > development (on Playstation 2, GameCube, and Xbox). Does anyone have any > experience with this? Nope. But in addition to the PS2 and GC Python builds you found: http://asbahr.com/python.html There's Python for the XBox. Xbox Media Center, the unauthorized software, includes Python embedded in the XBMC builds. You'll need a modified / hacked XBox to run it. If you want to learn more, I just wrote an intro on my blog: http://www.nelson.monkey.org/~nelson/weblog/tech/xboxPython.html From nospam at kochandreas.com Mon Apr 26 15:50:41 2004 From: nospam at kochandreas.com (Andreas Koch) Date: Mon, 26 Apr 2004 21:50:41 +0200 Subject: Andreas' practical language comparison In-Reply-To: References: Message-ID: Dan Bishop wrote: thanks, but all cases but "spread sheet" got solved in this nights mail rush :-) -- Andreas He screamed: THIS IS SIG! From claird at lairds.com Tue Apr 27 15:04:34 2004 From: claird at lairds.com (Cameron Laird) Date: Tue, 27 Apr 2004 19:04:34 -0000 Subject: Tkinter vs. wxPython? References: Message-ID: <108tbm2ltnf7o37@corp.supernews.com> In article , Batista, Facundo wrote: . . . >So, I'm writing a small (but professional) application in Tkinter. And then >I'll write it in wxPython. Then I'll decide in what I'll wrote a bigger >application I'm building. . . . And then you'll write up the experience so the rest of us can benefit from your experiment? -- Cameron Laird Business: http://www.Phaseit.net From wilkSPAM at OUTflibuste.net Fri Apr 16 06:07:48 2004 From: wilkSPAM at OUTflibuste.net (Wilk) Date: Fri, 16 Apr 2004 12:07:48 +0200 Subject: CamelCase versus wide_names (Prothon) References: <87hdvl2dny.fsf@blakie.riol> <87d6692ar8.fsf@blakie.riol> Message-ID: <87wu4gjkwb.fsf@blakie.riol> "Leif B. Kristensen" writes: > Hugh Macdonald rose and spake: > >> On a qwerty keyboard, _ is SHIFT+- (to the right of 0) > > In my part of the world, _ is also Shift+-, but it's to the right of > the . (period). In OO programming in general that's a bit awkward as I > frequently type a dot where I want an underscore and vice versa. This > is an error that often can be very hard to spot. So, this may be an > argument for camelCasing, - which I actually haven't used much since my > TurboPascal days. Why not - instead of _ ? def my-function() it doesn't need shift on azerty and qwerty isn'it ? and we already use it in natural langage... -- Wilk - http://flibuste.net From peter at engcorp.com Fri Apr 9 10:58:53 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 09 Apr 2004 10:58:53 -0400 Subject: Customizing the python search path depending on source directory In-Reply-To: <5cf809e9.0404081306.5d8a81cb@posting.google.com> References: <5cf809e9.0404061853.41cd3c85@posting.google.com> <5cf809e9.0404070452.643b7053@posting.google.com> <5cf809e9.0404071734.26f1078a@posting.google.com> <4dudnVzbRvwbyOjdRVn-sw@powergate.ca> <5cf809e9.0404081306.5d8a81cb@posting.google.com> Message-ID: <4dKdnQ9IXMKzJ-vdRVn-gg@powergate.ca> Peter Schwalm wrote: > Peter Hansen wrote in message news:<4dudnVzbRvwbyOjdRVn-sw at powergate.ca>... > > I have run the programs with "python .py" now. For my > purposes the results look identical - the source directory is still > not accessible during the processing of sitecustomize.py. Thanks for your persistence, Peter. I've confirmed what you have observed here: during site.py processing (including near the end when "import sitecustomize" is tried) the directory containing the main script is not included in sys.path. Immediately after site.py is imported, sys.path does contain the proper script at the start. My guess is that recent changes to the import mechanism have broken this behaviour. Note that this change would also break sitecustomize processing in some installations, since it should (I believe) be possible to have a sitecustomize.py in the directory where the main script resides, but in Python 2.3.3 it is not imported at all. If anyone who knows about such things more than we do can confirm that this should in fact be considered a bug, I will add it to SourceForge. -Peter From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Fri Apr 2 11:17:28 2004 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Fri, 02 Apr 2004 18:17:28 +0200 Subject: IPC share queue In-Reply-To: References: Message-ID: <406d9219$0$560$e4fe514c@news.xs4all.nl> Joe Wong wrote: > > Hi, the buildin Queue() class is good to use among multiple threads in > the program. Is there anything similar to this across process boundary? Check out Pyro's Event Server (http://pyro.sourceforge.net) It might suit your needs... --Irmen From ncw at axis.demon.co.uk Fri Apr 2 08:30:02 2004 From: ncw at axis.demon.co.uk (Nick Craig-Wood) Date: 02 Apr 2004 13:30:02 GMT Subject: Travelling salesman variation in python References: Message-ID: Peter Maas wrote: > Nick Craig-Wood wrote: > > I used Simulated Annealing - have a search for the term and you'll see > > plenty of references. Its good at finding a (local) minimum. > > I used to think that Simulated Annealing avoids local traps and > is good at finding a global minimum, at least with a certain > probability that depends on some temperature function. Am I wrong? You aren't wrong... It does avoid local traps - that is what the simulated annealing bit is for - but it isn't guaranteed to find the global minimum otherwise you'd have solved an NP-complete problem in polynomial time... In practice it works extrememly well! -- Nick Craig-Wood ncw at axis.demon.co.uk From jcm at FreeBSD-uk.eu.org Fri Apr 23 15:39:51 2004 From: jcm at FreeBSD-uk.eu.org (Jonathon McKitrick) Date: Fri, 23 Apr 2004 20:39:51 +0100 Subject: Best way to add attributes to shelved objects? Message-ID: <20040423193951.GC27351@dogma.freebsd-uk.eu.org> I'm working on an app that persists a few classes with shelve. But if I load older saved classes, I get an exception in code that uses the new attributes, of course. What is the best way to load these older classes, check for the new attributes, and add them so they will work with the new code? jm -- My other computer is your Windows box. From fumanchu at amor.org Fri Apr 23 11:06:16 2004 From: fumanchu at amor.org (Robert Brewer) Date: Fri, 23 Apr 2004 08:06:16 -0700 Subject: Why we will use obj$func() often Message-ID: Mike C. Fletcher wrote: > Mark Hahn wrote: > ... > >My biggest problem right now is stupid aesthetics. I have > to decide where > >to place Prothon on the continuum between lisp and perl. > > > *poke* surely you see the humour that a Python user will derive from > that statement :) ;) . > > >When I crossed the > >line and added $ for self people screamed bloody murder that > it looked like > >Perl. Before when I had a period for self they thought it > looked great. I > >can't believe how much they care about something so silly. > > > > > Comparatively, instance-attribute access is used three or > four times a > minute when coding, while super is used once or twice a month for > non-framework-programmers, so yes, I can see someone screaming bloody > murder if they suddenly are looking at a screen full of $This > and $that > variables. $ is basically a character as far as glyphs go, it's a > full-height glyph with ascenders and descenders, is very similar to a > capital S, and generally makes reading code much harder as it > obscures > word-shape; .this or even self.this is much easier to read > because you > can pick out the words using your learned vocabulary of word-shapes. > > Readability counts > > BTW, I'm a professional designer, so "stupid aesthetics" are > what I care > about whenever I get a chance ;) . > > ... > > That's why I never post to newsgroups, Well, I for one have greatly enjoyed your contribution here. Most comp. newsgroups could use a professional designer once in a while. ;) Robert Brewer MIS (moving slowly to requirements analyst and designer :) Amor Ministries fumanchu at amor.org From fumanchu at amor.org Mon Apr 12 00:27:41 2004 From: fumanchu at amor.org (Robert Brewer) Date: Sun, 11 Apr 2004 21:27:41 -0700 Subject: Is there a boolean(somestring) equivalent of int(somestring).bool('false') -> True Message-ID: Vineet Jain wrote: > How can anyone argue that > > bool('false') = True > > is more natural (and what you would expect) than > > bool('false') = False In exactly the same way that I expect: bool("Ce n'est pas une bool") = True FuManChu From ajsiegel at optonline.com Mon Apr 26 20:38:14 2004 From: ajsiegel at optonline.com (Arthur) Date: Tue, 27 Apr 2004 00:38:14 GMT Subject: Problem with PY2EXE and VPython References: Message-ID: <7mar8057sjdqh5h54ojb4et2bd3p10teug@4ax.com> On Mon, 26 Apr 2004 23:29:28 GMT, "bap" wrote: >When I try to run a program on a clean machine using the VPython extensions >after compiling with PY2EXE I get the following error message: "The >procedure entry point IsWow64Process could not be located in the dynamic >link library KERNEL32.dll" . The compiled version runs fine on the original >machine (win NT OS) but gives this error message on a machine without >VPython installed (Win 2K OS). Is this anything that can be fixed with >appropriate parameters in PY2EXE or does it require that VPython be tweaked? >Any help appriciated. At: http://www.dstoys.com/content/education/index_html/Visual%20Arts/Interactive I have the VPython Tower of Hanoi demo as a Windows executable. It is an older version of VPython and of Python. I would be curious to know if there are problems running this on your machine without VPython installed. If it runs OK, we can see from there what I might have done differently from you in building the executable. Art From irmen at -nospam-remove-this-xs4all.nl Tue Apr 13 14:17:49 2004 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Tue, 13 Apr 2004 20:17:49 +0200 Subject: interpreter limits In-Reply-To: References: <407c23bf$0$570$e4fe514c@news.xs4all.nl> Message-ID: <407c2ecc$0$574$e4fe514c@news.xs4all.nl> Joseph T. Bore wrote: > Any idea if it's possible? should I write a PEP? Can't you do something smart with signals, threads, alarm() and kill() ? Like running the code in a worker thread, where the main thread keeps track of how long it has been running and if not finished within a certain time, kill() it. Or use alarm() to get signaled after some time, then kill it in the signal handler. --Irmen From rmanx at gmx.de Thu Apr 1 07:00:19 2004 From: rmanx at gmx.de (Robert) Date: Thu, 1 Apr 2004 14:00:19 +0200 Subject: Don't understand wxPython event handling Message-ID: Hello list, could somebody point me to a good reference about wxPython event handling? I have seen many examples but which one is the best. Waht are the advantages and disadvantages? Can you also have a short look at the example below and give me some comments, please? Example: I have implemented (or copied from somewhere) one event in two flavours. Both work, but which one is the best? Or does anybody have a better implementation. EVT_NEXT_PAGE_ID = wxNewId() def EVT_NEXT_PAGE( win, func ): """Your documentation here""" win.Connect( -1, -1, EVT_NEXT_PAGE_ID, func ) class showNextPageEvent(wxPyEvent): def __init__(self, windowID): wxPyEvent.__init__(self) self.SetEventType(EVT_NEXT_PAGE_ID) or EVT_NEXT_PAGE_TYPE = wxNewEventType() def EVT_NEXT_PAGE( window, function ): """Your documentation here""" window.Connect( -1, -1, EVT_NEXT_PAGE_TYPE, function ) class showNextPageEvent(wxPyCommandEvent): eventType = EVT_NEXT_PAGE_TYPE def __init__(self, windowID): wxPyCommandEvent.__init__(self, self.eventType, windowID) def Clone( self ): self.__class__( self.GetId() ) Thank you Robert From gabriel.cooper at mediapulse.com Thu Apr 15 09:15:20 2004 From: gabriel.cooper at mediapulse.com (Gabriel Cooper) Date: Thu, 15 Apr 2004 09:15:20 -0400 Subject: [Newbie Q on String & List Manipulation] In-Reply-To: <567a7c35.0404150247.7809bef5@posting.google.com> References: <567a7c35.0404150247.7809bef5@posting.google.com> Message-ID: <407E8AE8.1010709@mediapulse.com> Matthew wrote: >Hello All, > > today is the first day i try to programming in Python, > my assignment is, write a silly script that probably > will run a few times a day to check if the Gmail services > is ready or not. ;) > > however, i encountered some problem when playing with the > list and string. > >[...] > > for item in thecookies: > mycookies += item >[...] > > Try: mycookies = string.join(thecookies, "") From jcarlson at uci.edu Mon Apr 19 11:24:59 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Mon, 19 Apr 2004 08:24:59 -0700 Subject: how to calculate correctly the cluster size In-Reply-To: References: Message-ID: Dennis Lee Bieber wrote: > On Sun, 18 Apr 2004 23:19:46 -0700, Josiah Carlson > declaimed the following in comp.lang.python: > > >>in order to fix that, thank god for partitionmagic). I don't think you >>would be out of line to assume 4k clusters on installations using FAT32 >>or NTFS. >> > > Heh... Checking just two of my 10 partitions (spread over two > internal drives, and an external FireWire) I'm running 8K clusters, and > likely much larger on the FireWire (which has four 40GB partitions!). > > W98se/FAT32 Can you defrag your disks? If so, then perhaps my not being able to find a software to defragment disks was a 'feature' of using Windows 2000, NTFS and non-4k clusters. I'm curious; did you set the cluster size yourself, or were those automatic sizes generated by 98SE? - Josiah From peter at engcorp.com Sat Apr 17 10:47:25 2004 From: peter at engcorp.com (Peter Hansen) Date: Sat, 17 Apr 2004 10:47:25 -0400 Subject: AOP use cases In-Reply-To: References: <84fc4588.0404140106.3fa0c55@posting.google.com> <0pydnSB4WYuieuLdRVn-hQ@powergate.ca> <35qdnT4kNsX1kB3dRVn-gg@powergate.ca> Message-ID: Joe Mason wrote: > In article , Peter Hansen wrote: >>Sorry, but that doesn't fly. That's a clearly separate function >>that should have a simple, single call somewhere in the application. > > Not at all. You'll want to log when calls start and end, when features > are turned on and off, when specific services (voice mail, call > forwarding) are accessed. If your app is for a call center, you want to > log when people go on and off hold and when they enter specific service > queues. Okay, even given that we're talking about something hypothetical (I'm _quite_ interested in evidence that AOP for such things is more than just someone's cool theory), why wouldn't I just do this as a series of calls in the appropriate places? If I'm going to specify which methods of which classes/objects are getting this "logging" functionality, it seems to me that I can do that as easily (i.e. one line of code) by just making it explicit in the code that does the call. And if I had to do this in such a variety of "arbitrary" places that it would appear to be a maintenance issue or something, I would turn to data-driven programming and just have the appropriate logging calls inserted using wrappers around the methods of interest as the application configures itself. So where does AOP fit in? I realize I'm basically asking the same question some others have, as in what good does AOP provide if it's so easy to do this using traditional techniques. Or is anyone arguing that what I'm actually doing is AOP even though I don't call it that? (In which case AOP should be relegated to being a simple Software Pattern I guess.) I think one problem I have with the logging example, even modified from the contrived "log calls to all methods" case, is that I've done such things, without the slightest feeling that what I was doing was complicated or awkward or needed "a better way". So what does AOP buy for such things? (But I'm _really_ much more interested in real-world examples, since we can discuss the theory of AOP all you like and still not convince me or anyone that it's worth any change in our way of doing things. What's a *compelling* example?) -Peter From jcarlson at uci.edu Mon Apr 19 02:19:46 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Sun, 18 Apr 2004 23:19:46 -0700 Subject: how to calculate correctly the cluster size In-Reply-To: References: Message-ID: > I am trying to find a way to calculate the cluster size for a drive. I > looked at the GetDiskFreeSpaceEx function in Win32 and it turned out > that it didn't provide the information I was looking for. > Using the old GetDiskFreeSpace function I could just multiply the > Bytes per > Sector by the Sector per Cluster and get the cluster size. I heard > that the old GetDiskFreeSpace function may report not proper values > for volume sizes that are greater than 2 gigabytes. The new version of > that function (GetDiskFreeSpaceEx) returns the final disk free size > without the ability to calculate the cluster size - and the old > version does not work correctly with FAT 32... what can I do? Is there > another function I can use? Generally, I believe sectors are consistantly 512 bytes, and depending on the format of your drive, cluster size can vary. Both NTFS and FAT32 generally run with 4k clusters, and at least until mid-2002, there didn't exist a commercial defragmenter that could handle non-4k clusters in Windows (I had a drive with 16k clusters that I needed to repartition in order to fix that, thank god for partitionmagic). I don't think you would be out of line to assume 4k clusters on installations using FAT32 or NTFS. In terms of volume sizes > 2 gigs, that sounds like the old cluster size and addressing limit for FAT 16, but considering how rare FAT 16 is nowadays (perhaps pre Win95 OSR2 installations still use it), I wouldn't worry too much (unless you are specifically writing for old operating systems). - Josiah From Kyler at news.Lairds.org Thu Apr 1 10:08:06 2004 From: Kyler at news.Lairds.org (Kyler Laird) Date: Thu, 01 Apr 2004 15:08:06 GMT Subject: Pyrex gets a perfect score. Message-ID: I mentioned earlier that I started using Pyrex because I'm taking a computer vision course that requires all assignments to be submitted as C(++). While I could write C it would hurt me to do so and certainly distract me from the computer vision aspects. I like using Python these days and Pyrex looked like a good solution. (BTW, on the last assignment I saw several messages from someone having difficulty with segfaults due to memory allocation problems. Grrr... Time spent messing with pointers is not advancing one's understanding of computer vision.) Here's one reaction I got on the subject: > 1. How is your teacher going to react when you hand in obfuscated-ish > C code that depends on the whole Python interpreter _and_ PIL? The bottom line is that I got a perfect score on all (seven) of my homework assignments. At first, I spent way too much time on them - figuring out how to use Pyrex and also just having fun exploring possibilities that I wouldn't have considered if I'd used C. Later, however, I found that I could start on the assignment the night before it's due and complete it in time. In terms of time, it was still a good investment over this short period. Most important, I had fun doing these assignments and I learned a lot from them. I am confident that I would not have accomplished as much with C (from scratch). Our project is going to require fast decoding of an image. My homework solutions have been agonizingly slow. There's a lot of room for optimizations and I'm looking forward to using Pyrex to prototype in Python and then replace pieces with C as needed. I can certainly see how Pyrex could serve nicely beyond academic settings. Is it a way to sneak Python into projects that are "strictly C"? Sure, it can work. Can it free the developer to quickly experiment with new concepts without spending excessive effort on programming? Definitely. Is speed and ease of development sometimes more important than execution speed. Yup. Can Pyrex be used effectively as a path to a native C solution? We'll see, but I'm confident that it can. Thank you, Pyrex! --kyler From kfast at poczta.onet.pl Wed Apr 28 05:50:45 2004 From: kfast at poczta.onet.pl (Jakub Fast) Date: Wed, 28 Apr 2004 11:50:45 +0200 Subject: Embedding OCaml within Python In-Reply-To: <37aad18.0404280019.500e2841@posting.google.com> References: <37aad18.0404280019.500e2841@posting.google.com> Message-ID: <408F7E75.7050907@poczta.onet.pl> Max Powers wrote: > The situation is this; I've got a large legacy program that is written > in ocaml, within which there's a parser. I'd like to be able to call > that parser from my python program Doesn't the O'Caml compiler translate the code into C first? If you got it to generate C code for your your library, chances are you could dig into it and wrap whatever you got there with SWIG or BPL, and then compile both the wrapper and the lib in C. Then, > Python -> C extension -> OCaml -> callback to C -> callback to Python becomes Python -> C extension (O'Caml translation + callback to Python) Of course, it might be the case that the O'Caml C code is too complicated or too far removed from the O'Caml object interface... hth kuba From bdash at gmx.net Wed Apr 14 23:44:19 2004 From: bdash at gmx.net (Mark Rowe) Date: Thu, 15 Apr 2004 15:44:19 +1200 Subject: 7bit to 8bit In-Reply-To: References: Message-ID: <2CF1A5CA-8E8F-11D8-BBCE-000A95D05654@gmx.net> On 15/04/2004, at 15:05, Daniel Roth wrote: > how do one easy convert a 8bit-text, which by python seems to be in > 7bit, to 8bit? I want to convert '=F6' to '?', '=E4' to '?' and so on. > of course without doing a replace for all those characters. Strings containing sequences like '=F6' appear to have be latin-1 strings that have been encoding using the "quoted printable" encoding. The following snippet shows one method of decoding the data: >>> print "=F6=E4".decode('quopri').decode('latin-1') ?? Alternatively, you should look into the quopri module and it's decodestring function. Hope this helps, Mark Rowe http://bdash.bluewire.net.nz From mogmios at mlug.missouri.edu Fri Apr 23 23:51:46 2004 From: mogmios at mlug.missouri.edu (Michael) Date: Fri, 23 Apr 2004 20:51:46 -0700 Subject: command-line args Message-ID: <4089E452.3080102@mlug.missouri.edu> What's the perfered method of passing command-line args throughout a Python program given that globals don't seem to really exist? I thought of writing them out to a python file and then importing them when needed.. but that seems like it'd only work for a single process.. not in instances where more than one user is running the program. There isn't anything like a virtual file space that could be used for this? Anyway to set a global variable? From lutz at rmi.net Mon Apr 26 11:49:46 2004 From: lutz at rmi.net (Mark Lutz) Date: 26 Apr 2004 08:49:46 -0700 Subject: Trouble Understanding O'Reilly Example References: <108p21f7asq1cc8@corp.supernews.com> Message-ID: Congratulations -- you've found what is probably the worst typo in the first printing of the 2nd Edition of this book. As others have pointed out, it should say arg < res, not arg < args. For future reference, O'Reilly maintains the full list of errata for the book, including this one, here: http://www.oreilly.com/catalog/lpython2/errata/ Typos happen, of course, and this edition has a relatively low number of them. But this one is made all the more maddening by the fact that I've coded this example correctly at least one hundred times during classes. Despite this, testing, and a formal technical review process, typos always manage to sneak in. Alas, writing computer books is no place for a perfectionist to be. --Mark Lutz (http://www.rmi.net/~lutz) slyraymond wrote in message news:<108p21f7asq1cc8 at corp.supernews.com>... > On page 214 of _Learning Python_, the following function is described as one > that will return the smallest item in a group of arguments: > > def min1(*args): > res = args[0] > for arg in args[1:]: > if arg < args: > res = arg > return res > > However, when the function called with... > > print min1(3,4,1,2) > > ...it returns: > > 2 > > Why? From db3l at fitlinxx.com Wed Apr 7 11:38:47 2004 From: db3l at fitlinxx.com (David Bolen) Date: 07 Apr 2004 11:38:47 -0400 Subject: Capturing stdout incrementally References: Message-ID: Josiah Carlson writes: > Your experience in unix has colored your impression of popen on > Windows. The trick with Windows is that pipes going to/from apps are > not real file handles, nor do they support select calls (Windows > select comes from Windows' underlying socket library). If they did, > then the Python 2.4 module Popen5 would not be required. Pipes under Windows (at least for the built-in os.popen* calls) are true OS file handles (in terms of Windows OS system handles), created via a CreatePipe call which are connected to a child process created with CreateProcess. You are correct that you can't select on them, but that's not because they aren't real file handles, but because Winsock under Windows is the odd man out. Sockets in Winsock aren't equivalent to other native OS handles (they aren't the "real" file handles), and select was only written to work with sockets. That's also why sockets can't directly play in all of the other Windows synchronization mechanisms (such as WaitFor[Multiple]Object[s]) but you have to tie a socket to a different OS handle first, and then use that handle in the sychronization call. > Popen5 is supposed to allow the combination of os.popen and os.system > on all platforms. You get pollable pipes and the signal that the > program ended with. As for how they did it on Windows, I believe they > are using pywin32 or ctypes. I'm certainly all for additional portability for child process management - although the internal os.popen* calls under Windows already give you the exit code of the child process (which does get some unique values when the process terminates abruptly), just without any simulated signal bits. But implementing popen5 under Windows will still run into the same problem (that of select simply not working for other OS system handles other than sockets), so I agree that will be a challenge, since presumably they'll want to return a handle that looks like a Python file and thus does have to have the underlying OS handle for basic I/O to work. Last I saw about the module was in January with a PEP announcement on python-dev, but the PEP still indicates no Windows support (the example was built on top of the popen2 module), and the python-dev discussion led to proposing a start with a pure Python module. I can't find any code in the current CVS tree related to popen5, so I'm not sure of the status. Of course, none of this changes the original question in this thread in that if the child process is going to select output buffering based on the "tty" or "console" aspect of the pipe to which its output is connected, you can't override that from the calling program, but have to deal with the program being executed (or more properly fake it out so that the controlling pipe appears more tty/console like). I doubt any popen* changes will affect that. -- David From tjreedy at udel.edu Tue Apr 20 20:29:07 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 20 Apr 2004 20:29:07 -0400 Subject: Generator inside a class prevent __del__ ?? References: <4085BA96.651D2E4A@free.fr> Message-ID: "Emmanuel" wrote in message news:4085BA96.651D2E4A at free.fr... > I run across this problem, and couldn't find any solution (python 2.2.2) ... > Here, everything is normal... > But creating a generator : You both defined generator function and called it to create generator iterator. > > Code : > =========== > > >>> class toto: > def __init__(self): > print "init" > self.Coroutine = self.Gen() This creates a reference loop. Delete this (and correct typo below) and 'problem' will disappear. > def __del__(self): > print "del" > def Gen(self): If you do not really use self in the resulting iterator, define this outside of the class without self as a parameter, and problem will disappear. > yield 1 > > >>> a = toto() did you mean 'c = toto()'? > init > >>> c = [] > <--- Nothing there !!! > ============== > > I can't understand why the destructor is not called when a generator is > created, and what I should do to have a "correct" behavior. Either do not create reference loop or break it with del c.Coroutine. Terry J. Reedy From grante at visi.com Wed Apr 28 10:13:30 2004 From: grante at visi.com (Grant Edwards) Date: 28 Apr 2004 14:13:30 GMT Subject: Path ... where is my application's home dir? References: Message-ID: <408fbc0a$0$17256$a1866201@newsreader.visi.com> On 2004-04-28, Marco Aschwanden wrote: > I want to store a file in the application directory. 1) Don't 2) Why? > What is the easiest way to figure out, where my application is situated? 3) Under Unix in general there is no reliable, portable way to do that. > sys.argv[0] does not work for my purposes... do you have any > other ideas. Yes. It sounds like you're trying to do a bad thing in the Unix world. Firstly, some smart admins have entire filesystems mounted read-only. Your application may live in one of those. Secondly, global configuration files go in /etc. Per-user configuration files go in the user's home directory in .-conf .rc or under the ./ directory. If you want them preserved across reboots, then caches of stuff go in /var/cache/. Files that don't need to survive a reboot go in /tmp. What are you trying to do? -- Grant Edwards grante Yow! After THIS, let's go at to PHILADELPHIA and have visi.com TRIPLETS!! From peter at engcorp.com Sun Apr 11 22:17:57 2004 From: peter at engcorp.com (Peter Hansen) Date: Sun, 11 Apr 2004 22:17:57 -0400 Subject: OT: history of discussion forums In-Reply-To: <1081728319.76650.2@doris.uk.clara.net> References: <4079215A.3010606@cs.com> <1081728319.76650.2@doris.uk.clara.net> Message-ID: Garry Knight wrote: > In message , Peter Hansen wrote: > > >>Robert M. Emmons wrote: >> >>>USENET or Network News is the second oldest discussion forum >>>group around. >> >>What, in your opinion, was the first? > > > You snipped it from his post. He said: > > >>Incidently, the first >>discussion forum network was "mailing lists". Oops, . :-) From lbates at swamisoft.com Sat Apr 17 12:07:11 2004 From: lbates at swamisoft.com (Larry Bates) Date: Sat, 17 Apr 2004 11:07:11 -0500 Subject: text storage: shelve vs anydbm vs ? References: <1081kgpq4qrsa79@corp.supernews.com> Message-ID: If MySQL is available on your website it is both fast and stable. It is also very easy to call from Python. Lots of ISPs also have admin interfaces that make it easy to make ad-hoc changes via web interface. Normally it is free. If you are self hosted, the same is true. Larry Bates Syscon, Inc. "Anton Sherwood" wrote in message news:1081kgpq4qrsa79 at corp.supernews.com... > Rather newbie question here. > > My current project will build a database of solutions to a topology > problem, which I'll eventually put (readonly) on my website. The > entries are text of varying length. The keys are likewise of varying > length. > > Is anydbm the way to go? Is shelve anything more than a wrapper for it? > Should I be looking at something else? > > -- > Anton Sherwood (prepend "1" to address) > http://www.ogre.nu/ From peter at engcorp.com Fri Apr 23 16:58:45 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 23 Apr 2004 16:58:45 -0400 Subject: Why we will use obj$func() often In-Reply-To: References: <84Uhc.22278$dZ1.5087@fed1read04> <8AWhc.23114$dZ1.11070@fed1read04> Message-ID: Mark Hahn wrote: > "Mike C. Fletcher" wrote ... > > >>$ is basically a character as far as glyphs go, it's a >>full-height glyph with ascenders and descenders, is very similar to a >>capital S, and generally makes reading code much harder as it obscures >>word-shape; .this or even self.this is much easier to read because you >>can pick out the words using your learned vocabulary of word-shapes. > > > Well I have a problem now. I gave people on my mailing list a choice > between $var, `var, ~var, and ^var. The current tally is four votes for > $var and none for any of the others. According to your criteria, $var is > the worst and ~var should be the best. Am I correct? If I recall correctly, ObjectRexx uses ~ the way Python uses . (dot). I wasn't really partial to it, but it didn't really stand in the way of writing or reading the code. I have to go with Mike on the problem with $ however... From fraser at fake_email.cx Fri Apr 9 13:48:58 2004 From: fraser at fake_email.cx (Fraser Hanson) Date: Fri, 09 Apr 2004 17:48:58 GMT Subject: Function args In-Reply-To: References: Message-ID: Jean-Michel Caricand wrote: > Hi, > > I'm new in Python. I have a problem with function args. I want to pass > args by reference because the function must modify this arg. How I do > that in Python. > > I didn't found documentation ! The short answer is, you can modify mutable types(lists and dictionaries) by passing them to a function. You cannot modify immutable types (strings, numbers, tuples) in this way. If you want to modify a variable pointing to an immutable type, then you must have your function return the modified value or values, and assign your value to the result of your function. Like this: def func(s): return s + " shop" a = "cheese" a = func(a) print a # prints "cheese shop" Python allows you to return multiple variables from a function call, so you can modify any number of variables with this method. (Technically, when you use a statement like "return a,b,c" you are not returning three variables, you are returning one tuple. Still it looks and acts like three variables, it's just good to be aware of these things.) def func(x,y,z): x = x + 5 y = y + 10 z = z + 15 return x, y, z a, b, c = 1, 2, 3 a, b, c = func(a,b,c) print a, b, c # prints "6, 12, 18" The reason for this is as follows. All variables in Python are just names that point to the "real" object, sort of like C pointers. When you pass an immutable type argument to a function, the function receives a new variable that happens to be pointing to the same object. When you assign to that variable, you are making it point to a different object. Thus when your function exits, your old variable in the original scope still points to the same object it did before the function call. By assigning the original variable to something returned by your function, your are achieving the intended effect in a more explicit way. Some of this is discussed in the documentation here: Mutable and immutable types: http://www.python.org/doc/2.3.3/ref/objects.html What happens during assignment: http://www.python.org/doc/2.3.3/ref/assignment.html --Fraser Hanson ps. Are you aware that your message was posted 12 times in a row? From anton at vredegoor.doge.nl Thu Apr 15 04:36:55 2004 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Thu, 15 Apr 2004 10:36:55 +0200 Subject: Method for providing a trail period on a program References: <407CF4F0.4020604@yahoo.com.au> Message-ID: <407e49b9$0$148$3a628fcd@reader2.nntp.hccnet.nl> "Larry Bates" wrote: >I find the idea that you can give the software >away and charge for support an interesting one. >If you write REALLY good software with REALLY >good documentation that provides REALLY good >tracing and debugging support (so users can >track down their own problems), what are you >going to charge for? Maybe give away the previous version of the software but ask some money if they want to upgrade to the next version? If there is yet another new version start giving away the previous version for free. This way customers are motivated to stimulate software development processes by their desire to own the latest upgrade. The distinction between support and development of the code is made a bit less strict and you can use that to provide specialized versions of the code to those who are willing to pay some more. The understanding should be that everything they pay for could possibly end up in the free version after some time. I don't know if it would be wise to negotiate about how much time it would take before other customers will profit from the new features for free with some paying customer. Maybe some credit messages in the documentation like "this feature was added thanks to financial support by customer x" would be a way to appease feelings of injustice. Anton From loic at fejoz.net Mon Apr 5 03:13:19 2004 From: loic at fejoz.net (Yermat) Date: Mon, 05 Apr 2004 09:13:19 +0200 Subject: write data file In-Reply-To: <337e6cd5.0404042146.6e39153c@posting.google.com> References: <337e6cd5.0404042146.6e39153c@posting.google.com> Message-ID: SunX wrote: > Question from a newbie. How do you write out a data file of floating > point numbers? file.write only takes strings. > Many thanks. Have a look at struct http://www.python.org/doc/2.3.3/lib/module-struct.html Yermat From theller at python.net Thu Apr 29 10:29:55 2004 From: theller at python.net (Thomas Heller) Date: Thu, 29 Apr 2004 16:29:55 +0200 Subject: debugging code References: <3064b51d.0404271139.6ec7057@posting.google.com> <408ee541$0$46510$39cecf19@news.twtelecom.net> <3064b51d.0404280658.ccf1894@posting.google.com> <408fe602$0$3708$39cecf19@news.twtelecom.net> <3064b51d.0404290606.1fe669aa@posting.google.com> Message-ID: beliavsky at aol.com writes: > Rick Ratzel wrote in message news:<408fe602$0$3708$39cecf19 at news.twtelecom.net>... >> beliavsky at aol.com wrote: >> > >> > >> > >> > Thanks -- I will take your suggestion. Where are the Python command >> > line options like -O and -OO documented? Typing 'python -h' just gives >> > me >> > >> > -O : optimize generated bytecode (a tad; also PYTHONOPTIMIZE=x) >> > -OO : remove doc-strings in addition to the -O optimizations >> >> Thats strange. Here they are for Python 2.3.3 as built on my system >> (should be the same for you): > > > > I get the same output from 'python -h'. What I meant to say is that I > am looking for more detailed documentation of the Python interpreter > options. I looked briefly on python.org and did not find it. http://www.python.org/doc/current/ref/assert.html#l2h-460 Thomas From db3l at fitlinxx.com Wed Apr 7 12:20:37 2004 From: db3l at fitlinxx.com (David Bolen) Date: 07 Apr 2004 12:20:37 -0400 Subject: painful debugging: techniques? References: Message-ID: "Humpty Dumpty" writes: > I'm wondering if there are tricks people use to track down problems like > this. Perhaps not so much a trick as much as experience, but after working with Python a bit, you'll find that any time you see something like 'NoneType not a callable' (or really any type) it pretty much says that some object in your program should be a callable (function, method, etc..) but is None (or the other type) instead. So in general I'd immediately start looking for uses of None in my code (or ways in which my code could generate None at runtime). Now, depending on how much new code you had written before the error started happening could help bound your search, and/or depending on the complexity of the code being tested you might be able to insert judicious prints at various points to check the value of objects. As someone else pointed out, if you were proceeding in a test first fashion you'd be at an advantage here since you would have high confidence in existing code and that the error was introduced (or at least tickled) specifically by whatever small amount of new code you wrote since the last test execution. Also, since the error was occurring on cleanup, it's related to objects still alive at that time. So that would help indicate that you should focus your search on objects that live throughout the duration of the test, as opposed to more transient code. Not sure how much that would have streamlined this case (it is fairly tricky given the gap between source of error and eventual failure), but it sounds like just focusing on your uses of None would have at least selected the weakref.ref call as a potential issue fairly quickly. -- David From no.email at please.com Sat Apr 10 06:33:37 2004 From: no.email at please.com (Stevie_mac) Date: Sat, 10 Apr 2004 11:33:37 +0100 Subject: Simple Class Question - need clarity please References: <2tce701vv505395hcr6dqtvc8ot0fdmkrk@4ax.com> Message-ID: very odd. Works for my now too. Is there some sort of cache that holds onto old (bad) code? I was definitely getting an error when I ran test.py, but not when I ran mywindow directly! "Patrick Ellis" wrote in message news:CaKdc.4701$I83.74460 at twister.tampabay.rr.com... > Stevie_mac wrote: > > > > > > > > > > I cut and pasted from your post into mywindow.py and test.py. When I ran > test.py I got a window with a cancel button, that went away when I clicked > the button. There were no error messages. > > From zunbeltz at wm.lc.ehu.es.XXX Wed Apr 21 05:56:43 2004 From: zunbeltz at wm.lc.ehu.es.XXX (Zunbeltz Izaola) Date: 21 Apr 2004 11:56:43 +0200 Subject: fmod and % Message-ID: Hi, I have a problem with % operation. It returns a incorrect value in this case: >>> -2.77555756156e-17%1 1.0 where the returned value should be -2.77555756156e-17. The documentation says that there is same errors due to roundoff and suggest to use fmod from math module. >>> fmod( -2.77555756156e-17,1) -2.77555756156e-17 Ok, but when i try the following: >>> fmod(-0.32768000000000003,1) -0.32768000000000003 but i want to get the result % gives >>> -0.32768000000000003%1 0.67232000000000003 what is going wrong? Any suggestions Thanks in advance -- Zunbeltz Izaola From eldiener at earthlink.net Mon Apr 26 18:58:13 2004 From: eldiener at earthlink.net (Edward Diener) Date: Mon, 26 Apr 2004 22:58:13 GMT Subject: How to read a file from another server? Newbie References: <%Oejc.16$ph.9@fed1read07> Message-ID: <9ugjc.3709$g31.1370@newsread2.news.atl.earthlink.net> Sean Berry wrote: > I am trying to read in a file from another server. > > If I try > x = open("servername:/path/to/file", "r") x = open("servername://path/to/file", "r") > > I get the following error: > IOError: [Errno 2] No such file or directory: > 'servername:/path/to/file' From invalide at courriel.com Sat Apr 3 19:02:21 2004 From: invalide at courriel.com (Askari) Date: Sun, 04 Apr 2004 00:02:21 GMT Subject: Spinbox (Tkinter module) Message-ID: Hi, I search on google a example for Spinbox (with Tkinter module). Can't find! If someone have a basic example for with a Spinbox, send me him! Because? I don't know how use this widget! :-( I can put a Spinbox on my canvas, I see it but can't change the "value" with up/down button. How I must do for that the "value" change? Askari N.B. My public e-mail adresse is invalid. From gandreas at no.reply Wed Apr 14 13:16:53 2004 From: gandreas at no.reply (Glenn Andreas) Date: Wed, 14 Apr 2004 12:16:53 -0500 Subject: Pygame References: Message-ID: In article , Jakub Fast wrote: > pygame (and sdl) are lgpl licensed and as such they are not > commercial-friendly. > > kuba > sdl is used in a number of commercial settings including a bunch of ports done by Loki Games and even ThQ's "Nemo's Underwater World of Fun" (and it's hard to be more commercial than "Finding Nemo"). From bnetNOSPAM at ifrance.com Fri Apr 30 02:02:12 2004 From: bnetNOSPAM at ifrance.com (=?iso-8859-1?q?Beno=EEt_Dejean?=) Date: Fri, 30 Apr 2004 08:02:12 +0200 Subject: Why cannot jump out the loop? References: Message-ID: Le Thu, 29 Apr 2004 21:21:41 -0500, Jinming Xu a ?crit?: > Hi Everyone, > > I have a very simple python program, which includes a while loop. But to my > surprise, it cannot jump out the while loop. Does anyone know why? > > Here is the program: > ___________________________ > #!/usr/bin/env python > import sys > n=sys.argv[1] n = int(sys.argv[1]) > i=0 > while i print "i=",i," n=",n > i+=1 ugly C style, better use range for i in range(int(sys.argv[1])): print i From jean-michel.caricand at laposte.net Fri Apr 9 03:58:13 2004 From: jean-michel.caricand at laposte.net (Jean-Michel Caricand) Date: Fri, 9 Apr 2004 09:58:13 +0200 Subject: Function args References: Message-ID: J'ai bien compris la le?on. Mer?i pour tout ! "Michel Claveau/Hamster" a ?crit dans le message de news: c55joj$q5f$1 at news-reader1.wanadoo.fr... > Re > > Je redis : en Python, les objets ne sont pas modifiables (sauf listes et > dictionnaires). > > En faisant : > c = b > b = a > a = c > > Cela veut dire : > - c=b cr?ation d'un objet auquel on affecte la valeur b, avec une variable > c qui pointe dessus > - b=a cr?ation d'un objet auquel on affecte la valeur a, avec une variable > b qui pointe dessus > - a=c cr?ation d'un objet auquel on affecte la valeur c, avec une variable > a qui pointe dessus > > Donc, au r?sultat, on aura bien eu un ?change des valeurs, mais avec > cr?ation d'objets. > > D'ailleurs, on peut suivre ce qui se passe, avec id() qui donne > l'identifiant unique d'un objet. > > a=2 > print id (a) > a=3 > print id(a) > a+=1 > print id(a) > > On voit bien qu'il y a cr?ation d'un nouvel objet 'a' ? chaque affectation. > > Il faut comprendre qu'il y a deux notions : > - en Python, une variable est toujours une r?f?rence (? un objet) > - les objets ne sont pas modifiables (sauf listes et dictionnaires) > > > > > Si tu veux vraiment utiliser des objets modifiables, passe par une liste, ou > un dictionnaire. > Exemple avec un dictionnaire : > def permut(x,y): > d[x],d[y]=d[y],d[x] > > d={'a':2, 'b':3} > print d['a'],d['b'] > print id(d['a']),id(d['b']) > > permut('a','b') > print d['a'],d['b'] > print id(d['a']),id(d['b']) > > > On voit bien, ici, gr?ce a "id()", qu'ici, il y a eu ?change des adresses > (r?f?rence) des ?l?ments internes du dictionnaire. > > > Ce syst?me de gestion des objets par r?f?rence, dans Python, est assez > fabuleux, car une variable peut r?f?rencer n'importe quel objet : un nombre, > une fonction, un dictionnaire, une liste de liste de liste, une classe, etc. > Les possibilit?s deviennent inou?es. Mais il faut bien ma?triser les notions > d'abord. > > > > @-salutations > > Michel Claveau > > > > > > > From lbates at swamisoft.com Thu Apr 22 10:15:42 2004 From: lbates at swamisoft.com (Larry Bates) Date: Thu, 22 Apr 2004 09:15:42 -0500 Subject: Python use large scale projects References: <47fc6058.0404212327.24163290@posting.google.com> Message-ID: I mostly work on Windows platform, but about 20% of my work is on Linux so my answer will be slanted towards Windows development, but I think the same is true of a pure Linux development environment also. I commonly use Python on projects that exceed 10000 lines which would require 4x-5x times that much C. I just completed a project that included over 13,000 lines of Python code frozen by py2exe into a Windows NT service (this didn't count the many thousands of lines of code that is housed in external calls to Python Imaging Library, ReportLab .PDf generation library, wxPython and API .dll's that are called from my Python application). Total application size probably exceeds 70K lines of code. Maintainability of such code is outstanding. I have come back to projects written years ago and can quickly pick up where I left off. This is something I cannot seem to do with legacy PHP code that I've written. My choice of Python came down to this: If I want to write scripts, console apps, GUI apps, services/daemons, web apps, develop for Windows, Linux, Palm, etc. without Python I'm forced into several different languages (e.g. C++, VB, ASP, etc.). It is difficult enough to learn one language well, I found it impossible to learn ASP, C++, and VB well enough to be productive in all 3. With updates to 3 languages it was impossible to keep up. If you wish to develop on different platforms, the problem is even more severe (without Python). With Python I can do all this (and more) but can actually develop in one language that I'm learning very well. It also allows me to leverage off of libraries of debugged code that I've developed for prior applications, which accelerates application development greatly. Example: I have a single logging class that I use in ALL my applications (BTW-my logging class predates the new logging class built into Python 2.3). I include the logging class, instantiate it and go. It is 400+ lines of Python that I've debugged/enhanced over several years. The ONLY knock I have against Python is in developing pure GUI applications. My business partner is a PowerBuilder developer. For pure GUI applications he finds PowerBuilder superior to Python (actually this is something that I cannot argue against), but he still gets me to write COM objects, NT Services, console applications and data conversion/manipulation "pieces" for him when needed. Some day Python will have a GUI development environment that makes GUI/database applications as easy to develop as PowerBuilder apps. Of course he is limited to Widows and Web apps (while possible in PowerBuilder) are difficult and expensive (due to licensing). While I'm certain there are developers out there that can manage this juggling act, I couldn't. Even if you choose a "front end" language like PowerBuilder, VB, etc. you find that you still need "back end" pieces. I don't think there is a better choice than Python. I should point out that I have 30+ years of experience and have learned many languages over the years, so I'm not a language bigot. I just want something that makes me productive and that produces reliable programs that are HIGHLY maintainable. Maintenance becomes 80% of the problem after an application is developed. Python fits that bill for me. I hope this information is of some assistance. Regards, Larry Bates Syscon, Inc. "limor" wrote in message news:47fc6058.0404212327.24163290 at posting.google.com... > Hi, > I am considering using Python in a new testing tool application we > intend to build for out product. > I must get references before starting develope in this language , > since although lots of good things are said about this language , I > still have my doubts how can it compete with languages like C++ and > Java. > I have found te sytax and some features if the language not as > problematic in maintenance prospective (although I keep reading the > contrary everywhere I read somthing about python) . For people who are > used to write in C and C++ I think the python being typless makes the > code hard to maintain. > > But still, In many prespective the language seems to really suit my > needs and I would really like to talk with people who are using Python > in their company to medium-large scale project. > > I'd really like to talk with someone who is using this language in his > work for large scale projects. > 10x allot for whoe ever reply me on that. > With Regards, > limor. > Spediant Systems Ltd. > Igal Alon 126 TA, Israel. From eltronic at juno.com Sat Apr 3 17:51:47 2004 From: eltronic at juno.com (eltronic at juno.com) Date: Sat, 3 Apr 2004 17:51:47 -0500 Subject: emergent/swarm/evolutionary systems etc Message-ID: <20040403.175310.-478629.2.eltronic@juno.com> On Sat, 3 Apr 2004 18:19:05 +0000 (UTC) "Peter MacKenzie" writes: > I think then that I might stick with spreadsheets as far a possible. its easy to under estimate the time it takes to get fluent in a spreadsheet while over estimating the time it takes to get fluent with python based on familiarity alone. don't neglect the paper and pencil flowchart, clean data and apples to apples comparisons. > Do you > know of any simulation programs that might be more suited? Simpy http://simpy.sourceforge.net/ is one. see recent pycon one page presentation http://www.python.org/pycon/dc2004/papers/16/ > how would > you extract data from a spreadsheet for use in another program? export csv, saveas csv, Comma Delimited or Comma Separated Value python can parse that file, help(csv) . e please forward all spam to uce at ftc.gov ________________________________________________________________ The best thing to hit the Internet in years - Juno SpeedBand! Surf the Web up to FIVE TIMES FASTER! Only $14.95/ month - visit www.juno.com to sign up today! From simon at brunningonline.net Wed Apr 21 09:31:58 2004 From: simon at brunningonline.net (Simon Brunning) Date: 21 Apr 2004 06:31:58 -0700 Subject: Opening MS Word files via Python References: <7b454334.0404201628.371b9e8@posting.google.com> Message-ID: <314b29e9.0404210531.3be418ee@posting.google.com> faizan at jaredweb.com (Fazer) wrote in message > I am curious as to how I should approach this issue. I would just > want to parse simple text and maybe perhaps tables in the future. > Would I have to save the word file and open it in a text editor? That > would kind of....suck... Has anyone else tackled this issue? See http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/279003 Cheers, Simon B. From oliver.schoenborn at utoronto.ca Tue Apr 6 23:18:29 2004 From: oliver.schoenborn at utoronto.ca (Humpty Dumpty) Date: Tue, 6 Apr 2004 23:18:29 -0400 Subject: painful debugging: techniques? Message-ID: Hello, I've been using python for about 3 months now. Prior to that I did C++ for over 5 years. I'm wondering if my debugging techniques are too C++ oriented. E.g., it took me about 9 hrs of debugging to figure out that the second parameter to weakref.ref() was being passed as None. This is odd because the second parameter is optional, yet its default value is not documented, so I assumed that passing None would be fine, and then I forgot that I was doing that. It took that long mostly because the exception message was "Exception TypeError: 'NoneType not a callable' in None being ignored", ie it was being ignored and function from which it was being raised was unknown to Python (somehow), *and* it was only being raised upon exit of the test (cleanup). So I had no way of knowing where this was being raised. It was nasty. I'm wondering if there are tricks people use to track down problems like this. Thanks, Oliver From junkmail at solumslekt.org Tue Apr 27 17:52:50 2004 From: junkmail at solumslekt.org (Leif B. Kristensen) Date: Tue, 27 Apr 2004 23:52:50 +0200 Subject: Tkinter vs. wxPython? References: <05gt801pbp6jmprrcbr78npbp2j2q0i94p@4ax.com> Message-ID: <4DAjc.532$id.8014@news2.e.nsc.no> Alan Gauld rose and spake: [Tkinter, wxPython] > I've played with both but my GUI needs are simple - usually > putting a nice front end on a CLI script. (Fancy GUI stuff I tend > to do in Delphi - oh the shame of it...) > > But my experience suggests similar findings, Tkinter is dead easy > to build small GUIs but it has a limited widget set (even > including PMW) and has no currently maintained graphical GUI > builder so far as I know (SpecPython is long discontnued!) > > And there is no doubt that wxPython looks more natural, on > windows at least, although the differences aren't enough to make > me switch. BUt my needs are, as I said, very simple. Right now I'm trying to build a GUI frontend to my genealogy database. I've settled on Tkinter for the present. I've tried PyQT, wxPython, and Tkinter sofar, and have settled with Tkinter for the time being because of the superior documentation. This being my first serious attempt of building a GUI ever, I need to rely heavily on tutorials and sample code. There's nothing that beats Tkinter in this respect. What I really miss in the Libre Software world is a kind of integrated GUI data representation / entry interface like in the old DBase II days. I don't want to write thousands of lines of code just to throw pixels on the screen. What I want is a simple way to design forms, and spend my main effort on the interface to the backend database. I've had a good look on Knoda to this effect. It is very promising, but it isn't quite there yet. regards, -- Leif Biberg Kristensen http://solumslekt.org/ Validare necesse est From pm_mon at yahoo.com Wed Apr 21 13:54:28 2004 From: pm_mon at yahoo.com (Paul Morrow) Date: Wed, 21 Apr 2004 13:54:28 -0400 Subject: Difficulty Finding Python Developers In-Reply-To: <65cbc3dd.0404140641.3501fde8@posting.google.com> References: <65cbc3dd.0404140641.3501fde8@posting.google.com> Message-ID: Thanks to everyone for their suggestions and ideas on this. Our HR department placed an ad on monster.com, which currently is mostly being answered by recuiters and spammers, but we're hopeful we'll get more actual applicants soon. If anyone is interested in this short gig, and can work in Atlanta, you can find our ad by searching on loyaltyworks as the keyword. Thanks again! From mlh at furu.idi.ntnu.no Fri Apr 23 18:56:38 2004 From: mlh at furu.idi.ntnu.no (Magnus Lie Hetland) Date: Fri, 23 Apr 2004 22:56:38 +0000 (UTC) Subject: Regexp optimization question References: Message-ID: In article , William Park wrote: [snip] > >Since you want both the matched strings and their locations in file, you >pretty much have to this manually, one by one. Well -- that's more or less what I'm doing. (Or -- I can get the match objects all at once, of course, using finditer.) I guess I'll have to look elsewhere for performance improvements. Hm. -- Magnus Lie Hetland "Wake up!" - Rage Against The Machine http://hetland.org "Shut up!" - Linkin Park From newsgroups at jhrothjr.com Wed Apr 7 13:14:19 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Wed, 7 Apr 2004 13:14:19 -0400 Subject: Are line continuations needed? References: Message-ID: <1078dq6i93pc12d@news.supernews.com> RE: Are line continuations needed? "Batista, Facundo" wrote in message news:mailman.418.1081348606.20120.python-list at python.org... [wallacethinmintr at eircom.net] #- Python lets you continue a single logical line across more than one #- physical line, either by putting a \ at the end or letting it happen #- automatically with an incomplete infix operator. #- #- I'm wondering how often is this feature needed? Would there be any #- problems if it weren't part of the language? The issue is: How important is to remove this feature, considering that it'll break zillions of lines of code around the world? . Facundo [John Roth] It is, I believe, planned for removal in 3.0. Remember that 3.0 will break everything anyway: it's the release for incompatible changes. re someone else's comment about imports. The ability to put parentheses around lists of modules or elements in imports will be in 2.4. John Roth . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA La informaci?n contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener informaci?n confidencial o propietaria, cuya divulgaci?n es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no est? autorizado a divulgar, copiar, distribuir o retener informaci?n (o parte de ella) contenida en este mensaje. Por favor notif?quenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magn?tico) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telef?nica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electr?nicos pueden ser alterados, motivo por el cual Telef?nica Comunicaciones Personales S.A. no aceptar? ninguna obligaci?n cualquiera sea el resultante de este mensaje. Muchas Gracias. From skip at pobox.com Tue Apr 20 10:45:40 2004 From: skip at pobox.com (Skip Montanaro) Date: Tue, 20 Apr 2004 09:45:40 -0500 Subject: emacs for OS X In-Reply-To: References: Message-ID: <16517.14228.600379.15438@montanaro.dyndns.org> Tuxtrax> I found python-mode.el in the python distribution folder, but Tuxtrax> not only do I have no clue as to what to do with it, I can't Tuxtrax> find an emacs folder or a .emac file. Just the emac Tuxtrax> program. Any help with this would be greatly appreciated. If Tuxtrax> you have overcome this yourself I especially want to hear from Tuxtrax> you. Stick it in a directory in your Emacs load-path and byte-compile it. C-h v load-path RET will show you what your load-path is. M-x byte-compile-file RET will prompt you for a file to compile. Respond with the full path to your copy of python-mode.el. Finally, associate .py files with python-mode by adding something like (setq auto-mode-alist (cons '("\\.py$" . python-mode) auto-mode-alist)) to your ~/.xemacs (or ~/.xemacs/init.el, depending on XEmacs version) file. Skip From lbates at swamisoft.com Wed Apr 14 16:40:25 2004 From: lbates at swamisoft.com (Larry Bates) Date: Wed, 14 Apr 2004 15:40:25 -0500 Subject: Method for providing a trail period on a program References: <407CF4F0.4020604@yahoo.com.au> Message-ID: My post has gotten some really varied responses. I've been writing software for over 30 years so I know that there is no "fool-proof" way of doing what I want. But I thought someone may have come up with an "acceptable" solution. I contribute to this newsgroup on a regular basis and thought I would at least ask. I find the idea that you can give the software away and charge for support an interesting one. If you write REALLY good software with REALLY good documentation that provides REALLY good tracing and debugging support (so users can track down their own problems), what are you going to charge for? The reason I wanted to put a trial period on my software was that I may have the opportunity to place it on the CDROM with a hardware device that is being sold. I would like every end user to have the opportunity of trying out my add-on package. I am however, not prepared to let them run it forever for free. If it provides value to them, I believe they should purchase a license. This may put me in the minority on a Python site, but that's the way I feel. Regards, Larry Bates Syscon, Inc. "Steve" wrote in message news:407CF4F0.4020604 at yahoo.com.au... > Ben Finney wrote: > > On Thu, 1 Apr 2004 17:46:12 -0600, Larry Bates wrote: > > > >>I'm searching for a good way to provide a "trail period" (something > >>like 90 days) for a commercial application that I'm writing. I'd like > >>something that can easily stop working 90 days after installation. > > > > > > Why do you want to break your user's programs to gain money? Will they > > not pay for your work without their programs breaking? What does that > > say about the value of your work? > > In fairness, it might not be Larry's work that he isn't > confident about, but the honesty of his customers. > > Larry, how foolproof do you want this trial period to > be? How sophisticated are your clients? How motivated > are they to crack it? What are your motives for wanting > to disable the program? Are you sure your business > model is the best way? > > For example, perhaps you would be better off > distributing a free version with reduced functionality, > with the additional functionality only in the non-free > version. > > If you want a foolproof mechanism for disabling the > program after the trial period, then Python is probably > not the language for you. Actually, a sufficiently > motivated hacker will find some way to crack your > protection no matter what you do. > > Besides, there is one other thing you should consider. > You're not Microsoft. Your biggest problem isn't people > ripping you off by not paying for your software, it is > that people don't even know your software exists. > Perhaps it is worth letting people make free copies in > order to spread the word. Don't think of it as being > ripped off, think of it as advertising. > > Just a few thoughts for you to consider. > > > -- > Steven D'Aprano > > > > > > > From fumanchu at amor.org Thu Apr 1 23:23:39 2004 From: fumanchu at amor.org (Robert Brewer) Date: Thu, 1 Apr 2004 20:23:39 -0800 Subject: Stackless Website down, Project gone, I'm dead. Message-ID: Christian Tismer wrote: > On Mach 31st, some bad intruder has broken into our CVS > server. (S)he has replaced all of our files by some > dummy entries. This was quite bad, since the new Stackless > developer group was happily hacking on after the sprint, > March 10-14, and we were updating CVS on a very frequent basis. > > As a result, all sources of Stackless Python are totally lost, now. I'm very sorry to hear that, Christian. > Since I always was a very emotion driven guy, I thought this > was the right situation to say good-bye to you all. My life > is ending, soon, and so is my project. We could try to find some > backups, but I do say NO!, Please, do appropriate cleanup! > > The evil truth of real life has told me where my path is headed > to. Please make no attempt to revive Stackless. It is completely > dead, and I'm going to take it with me into my cold, lonely grave. > > I have spent the rest of my time on it, and now I want to rest > on it, since my time is over. So please avoid to mention it > any longer, not in news, not in interviews, and *please* > absolutely don't use it!!! > Stackless is gone, Tismer is gone, and this is good, since I > already have told you all the lies that I could tell you in a > lifetime. > > Rest In Peace forever with -- Stackfull Python -- Christian, I hope I'm hearing your words as worse than you mean them. I haven't been on this list for long, but I've quickly learned to appreciate your ingenuity, experience, and determination. I was going to tell you today I ended up using your solution to my recent deduping problem (sufficiently molded to my existing code, of course ;)--I really appreciate your help with that! If Stackless is truly gone, I pray you are able to find a new project or group where you feel truly useful. Hang in there, Robert Brewer MIS Amor Ministries fumanchu at amor.org From usenet_spam at janc.invalid Sat Apr 10 18:44:56 2004 From: usenet_spam at janc.invalid (JanC) Date: Sat, 10 Apr 2004 22:44:56 GMT Subject: [OT] The Cracker's Guide To Python References: <04g770lqpbhdgr3n3b9mnu9o8f08fdkgk0@4ax.com> Message-ID: alan_salmoni at yahoo.com (Alan James Salmoni) schreef: > Maybe the idea could be added to by laying emphasis on certain > modules. Bundle up Python and advertise it on Kazaa like: > > "Python - l334 5(r1pt1n9 t001z - crypt, encodings.idna, getpass, and > pwd [password] modules h4x0r3d and included as a bonus." :) You know, BitTorrent & IRC are more "in" than Kazaa these days... -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From tjreedy at udel.edu Thu Apr 22 12:17:36 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 22 Apr 2004 12:17:36 -0400 Subject: Deleting objects References: Message-ID: "Thomas Philips" wrote in message news:b4a8ffb6.0404220608.56bf3d63 at posting.google.com... > I'm teaching myself OOP using Michael Dawson's "Python Programming For > The Absolute Beginner" and have a question about deleting objects. My > game has two classes: Player and Alien, essentially identical, > instances of which can shoot at each other. Player is described below > > class Player(object): > #Class attributes for class Player > n=0 #n is the number of players > > #Private methods for class Player > def __init__(self,name): > self.name = name You appear to have use a tab here and spaces below. Never mix, and stick with spaces for posted code. > self.strength = 100 > Player.n +=1 > > def __del__(self): > Player.n -=1 > print "I guess I lost this battle" > > #Public methods for class Player > def blast(self,enemy,energy): > enemy.hit(energy) > > def hit(self,energy): > self.strength -= energy > if(self.strength <= 50): > self.__del__() > > I instantiate one instance of each class: > Hero = Player("Me") > Villain = Alien("Not Me") > > If Hero hits Villain with > Hero.blast(Villain, 100), > > Villain dies and executes its destructor (__del__). However, the name 'Villain' is still bound to the corresponding object in globals(). Executing the __del__ method of an object does *NOT* delete the object. This *only* thing special about that method is that it is called 'behind the scenes' when an objects refcount goes to 0. > The game then > ends. However, when I execute the program in IDLE, IT FINISHES BY > EXECUTING THE DESTRUCTOR FOR BOTH HERO AND VILLAIN. __del__ methods are not destructors. There are merely called be the interpreter's internal destructor function. > How can this be? As one of the two objects was destroyed prior to the > end of the game, As explained above, it was not destroyed. You merely called a method that happened to be named __del__. Getting rid of *all* references to an object, in order to allow destruction (but not guarantee it), can be difficult. > how can it be re-destroyed when the program ends? Terry J. Reedy From soeren_kunst at hotmail.NOSPAM.com Tue Apr 20 08:22:05 2004 From: soeren_kunst at hotmail.NOSPAM.com (Sören Kunst) Date: Tue, 20 Apr 2004 14:22:05 +0200 Subject: Tutorial Message-ID: hello, i need a good tutorial for Python, nothing for beginners wfw S?ren From claird at lairds.com Mon Apr 5 07:24:48 2004 From: claird at lairds.com (Cameron Laird) Date: Mon, 05 Apr 2004 11:24:48 -0000 Subject: python processes names References: Message-ID: <1072gg0ru281n48@corp.supernews.com> In article , Sylwia wrote: >Hi! > >How to make python programs show up by name is ps (e.g ps -e). By >default if we have many different python processes running >simultaneously, then we can only see python python python for three >different python processes. I would much rather see >first_python_program_name.py, second_python_program_name.py and >third_python_program_name.py listed by ps. Is that possible without >downloading and installing any non-standard modules? . . . There are MANY ways to go about this. I presume Linux is your host. Does "ps -F" bring you closer to what you're after? -- Cameron Laird Business: http://www.Phaseit.net From ny_r_marquez at yahoo.com Thu Apr 8 10:02:01 2004 From: ny_r_marquez at yahoo.com (R.Marquez) Date: 8 Apr 2004 07:02:01 -0700 Subject: unc paths in os.path.walk on win2000? References: Message-ID: <8a27e309.0404080602.294ebf34@posting.google.com> I'm not sure if this is the problem but from the little info you give... You may have to escape the backlash like this: "\\\\server\\path" Or, you may want to use raw strings like this: r"\\server\path" -Ruben "leo" wrote in message news:... > how can i use unc paths in os.path.walk on win2000? > > i tried the \\server\path representation in python 2.3 and it didn't work... > > thanks, leo From jacek.generowicz at cern.ch Thu Apr 22 07:40:39 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 22 Apr 2004 13:40:39 +0200 Subject: AOP use cases References: <84fc4588.0404140106.3fa0c55@posting.google.com> <0pydnSB4WYuieuLdRVn-hQ@powergate.ca> Message-ID: Peter Hansen writes: > Jacek Generowicz wrote: > (a lengthy reply, and thank you for taking the time!) > > Peter Hansen writes: > >>I would be very interested to hear some real-world and real useful > >>use cases for AOP as well. > > AOP is about separation of concerns. Let me repeat that: AOP is about > > > SEPARATION OF CONCERNS. > [snip] > > As for real world examples ... if you think of AOP as separation of > > concerns which you want to be weaved together, then I am sure that you > > will be able to come up with plenty of excellent real world examples > > yourself. > > Unfortunately, that's just my point. So far I haven't been able > to do that, it seems. > The example posted previously with the "synchronization wrapper" > approach is, however, quite understandable and comes from real-world > experience that many of us share. Is that AOP? Is it not AOP? Well, that depends on what you think AOP is. If you think that AOP is Kiczales' work in Java, then clearly the synchronization wrapper isn't AOP. If you think of AOP as separation of concerns, then the synchornization wrapper is AOP ... but then so are optimizing compilers. I am partial to a view somewhere in between those two extremes ... maybe viewing AOP as a pattern. But "AOP" is a buzzphrase and it's probably best not to get too hung up on buzzphrases. I would prefer to see the ideas behind it and to try to apply any that have merit where they may help me. "Separation of concerns" summarizes something towards which I've been striving, even unconciously, before I ever heard of AOP, but seeing it as an active field of study encourages me to believe that it might become easier to separate concerns in my programs, either through language support, or people discovering neat ways of achieving it in various languages. > If it's an application of AOP principles, then is AOP anything other > than a good practice which some of us have been doing for years, > prettied up with a nice name. In other words, Just Another Pattern? Yes, I think that you are justified, to some extent, to view it as just another pattern. Of course, some languages make it easier to do AOP as a pattern, while others require external help, while in others still it's so trivial that it doesn't even merit being called a pattern: Consider multiple dispatch in Common Lisp, C++ and C; in C++ it's a pattern (Visitor), in CL it just is, and in C ... ? How about the State Pattern? "foo.__class__ = bar" is how you do it in Python, is that a pattern? How about OOP in C++ and C? in C++ it just is, and in C it's a pattern (or requires external help: ie somebody coming along and implementing C++ or Objective C). So, maybe AOP is a technology in Java, a pattern in Python, and just is in the CLOS MOP ? (Hmm, I recall a pertinent anecdote about this ... let's see if I can find it ... here it is Message id: : I am reminded of Gregor Kiczales (sp?) at ILC 2003 displaying some AspectJ to a silent crowd, pausing, then plaintively adding, "When I show that to Java programmers they stand up and cheer." ) > You seem to be someone who understands AOP well: Oh lawd, I never intended to create such an illision ! I like to think that one of my merits is trying (and sometimes even succeeding) to see past all the noise and hype surrounding something and understaing, in as simple terms as possible, what the essence of it is. It is from this perspective that I offered my article: I know essentially bugger all about AOP in Java, but I believe that AOP is about separation of concerns. If you look at it that way, next time you are come across the need to separate concerns, a little bell might ring and you might think of AOP. How you go about separating those concerns is strongly dependent on the language you happen to be using. > do you use it? Certainly not in the Java sense. Unfortunately I'm stuck mostly in C++ hell, but I suspect that separation of concerns creeps into my Python code (when I get to write some), probably even without me explicitly identifying it a such. > Could you please provide an example from your own uses which > demonstrates the effectiveness of AOP versus "not AOP" in the same > way that the synchronization example posted earlier is clearly > better when done as a wrapper than with the code duplicated > everywhere (i.e. with the "concerns" not separated)? Not offhand. If I notice some neat separation of concerns in my work I'll try to remember to post it. Sorry, this ended up much longer than it should have been. From peter at engcorp.com Mon Apr 5 15:12:33 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 05 Apr 2004 15:12:33 -0400 Subject: design by contract versus doctest In-Reply-To: <4071a6d4$0$5064$4d4ebb8e@news.nl.uu.net> References: <407174ea$0$5066$4d4ebb8e@news.nl.uu.net> <40718ddb$0$5071$4d4ebb8e@news.nl.uu.net> <4071a6d4$0$5064$4d4ebb8e@news.nl.uu.net> Message-ID: aku wrote: > A nr of unittests will > still be necessary to ensure preconditions, but in > the (oversimplified) example I gave (n = 1), the test > "if n < 0: ..." isn't necessary anymore and certainly not *in* > the called function itself. > > The "downside" with DBC I see is: when the caller *cannot* > ensure a precondition, then the behavior in the called > function becomes unpredictable. I agree that that appears to be a downside. Furthermore, if you have to verify in calling code that preconditions are met, don't you end up with duplication outside of the function that would otherwise have the check in it? Well written code will have less duplication, not more, so I'm still unclear how moving the check out of the function (from your original example from doctest) will actually improve things... And if the code that checks this is in the function, then a single unit test can verify that the check is in place and working properly. It sounds like moving the check out of that function will lead to more tests and/or more checks in other places, neither of which is a good idea. But I'm certainly no expert in (or proponent of) DBC... -Peter From tezt at email.si Thu Apr 8 12:47:07 2004 From: tezt at email.si (Mitja) Date: Thu, 8 Apr 2004 18:47:07 +0200 Subject: List vs tuples Message-ID: A neewbie's question here, probably discussed before: what's the purpose of having both lists AND tuples? At the first (and second and third, to be honest) glance lists are just tuples with extended functionality, so why have tuples around? I've been working with Python for a few months now but haven't yet come across a problem that would really require tuples. Thanks in advance, Mitja From samschul at pacbell.net Tue Apr 27 21:16:34 2004 From: samschul at pacbell.net (Samuel Schulenburg) Date: 27 Apr 2004 18:16:34 -0700 Subject: [ANN] USB mass storage support added to SCSIPython Message-ID: I have added SCSITOOLS23USBBeta.zip USB mass storage support to my SCSIPython scsi diagnostic tools that I have been maintaining. This is being released as a Beta as I expect to add some more features shortly. This release supports all the functionality as the previous release's and will allow you to test SCSI,ATA,USB, and PCMCIA storage devices using the SCSIPASSTHROUGH layer in WindowsXX. These routines can be found at http://starship.python.net/crew/samschul/ Sam Schulenburg samschul at pacbell.net From nuffsaid at phreaker.net Fri Apr 30 05:56:19 2004 From: nuffsaid at phreaker.net (Nuff Said) Date: Fri, 30 Apr 2004 11:56:19 +0200 Subject: locale.CODESET / different in python shell and scripts References: <4091621F.5060307@v.loewis.de> <4091BA4A.4000608@v.loewis.de> Message-ID: On Fri, 30 Apr 2004 04:30:34 +0200, Martin v. L?wis wrote: > Nuff Said wrote: >> When I add the following line to the above script >> >> print u"sch?nes M?dchen".encode(encoding) >> >> the result is: >> >> sch?nes M?dchen (with my self-compiled Python 2.3) >> sch??nes M??dchen (with Fedora's Python 2.2) >> >> I observed, that my Python gives me (the correct value) 15 for >> len(u"sch?nes M?dchen") whereas Fedora's Python says 17 (one more >> for each German umlaut, i.e. the len of the UTF-8 representation of >> the string; observe, that the file uses the coding cookie for UTF-8). >> Maybe Fedora's Python was compiled without Unicode support? > > Certainly not: It would not support u"" literals without Unicode. That's what I thought. > Please understand that you can use non-ASCII characters in source > code unless you also use the facilities described in > > http://www.python.org/peps/pep-0263.html > > So instead of "?", you should write "\xf6". But *I do use* the line # -*- coding: UTF-8 -*- from your PEP (directly after the shebang-line; s. the full source code in my earlier posting). I thought, that allows me to write u"?" (which - as described above - works in one of my two Pythons). ??? Nuff. From peter.maas at mplusr.de Fri Apr 2 10:25:06 2004 From: peter.maas at mplusr.de (Peter Maas) Date: Fri, 02 Apr 2004 17:25:06 +0200 Subject: Creating a matrix? In-Reply-To: References: Message-ID: Ivan Voras wrote: > Is there a nice(r) way of creating a list of uniform values? I'm > currently using: list('0'*N), which makes a string and then chops it up > into a list. I need it to create a NxN matrix: > > matrix = [list('0'*N) for i in range(N)] matrix = [['0']*N]*N Mit freundlichen Gruessen, Peter Maas -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Hubert-Wienen-Str. 24 Tel +49-241-93878-0 Fax +49-241-93878-20 eMail peter.maas at mplusr.de ------------------------------------------------------------------- From jbperez808 at yahoo.com Tue Apr 6 15:00:12 2004 From: jbperez808 at yahoo.com (Jon Perez) Date: Wed, 07 Apr 2004 03:00:12 +0800 Subject: Type checking inside a C extension... mystery solved In-Reply-To: References: <40712D9E.3050802@prescod.net> <407229F6.6080809@yahoo.com> Message-ID: Stephen Horne wrote: > Python exceptions aren't converted to C exceptions, and the Python C > API doesn't use C exceptions at all. There is a good reason for this. > C doesn't have exceptions - C++ does, but this is a C API. Ah... now I get this seemingly mysterious behaviour. If PyString_AsString() attempts to convert a non-string Python object to a C string, the exception is not thrown from within it, it only sets a flag indicating that such an exception should eventually be thrown. While the C extension function itself does need to return a NULL for said exception occur, it does need to to return to Python runtime first to trigger the exception. > Python C API functions often return zero for error IIRC, so... > > if (PyString_AsString(strobj) == 0) { return 0; } > > Should ensure that the Python exception raised by PyString_AsString is > propogated correctly. This also answers my earlier question. So there is no need to do a PyString_Check() before feeding a value to PyString_AsString(), just check the return value of PyString_AsString()... Thanks everyone. From godoy at ieee.org Mon Apr 26 12:15:40 2004 From: godoy at ieee.org (Jorge Godoy) Date: Mon, 26 Apr 2004 13:15:40 -0300 Subject: Parallel port interface References: Message-ID: On Seg 26 Abr 2004 00:03, Peter Hansen wrote: > http://pyserial.sourceforge.net/pyparallel.html might work. Says > "This module is still under developement. But it may be useful for > developers." You see... I must be blind or something like that :-) I was at the pyserial website but didn't see this. Thanks! -- Godoy. From paddy3118 at netscape.net Sat Apr 10 12:40:15 2004 From: paddy3118 at netscape.net (Paddy McCarthy) Date: 10 Apr 2004 09:40:15 -0700 Subject: Wrapper round x86 Assembler References: <8089854e.0404082353.7bf163a2@posting.google.com> Message-ID: <2ae25c6b.0404100840.10668dca@posting.google.com> michael at foord.net (Fuzzyman) wrote in message news:<8089854e.0404082353.7bf163a2 at posting.google.com>... > There might be a really good reason why this hasn't been done *or* > someone might have done it and I just can't find it..... *but* > > what about a wrapper to an assembler (presumably for x86 assembly !) > !! > I just wrote some code doing binary operations which would have been > about a zillion times faster in a few lines of assembly code. > > I also have fond memories of programming in BBC Basic which had an > inline assembler - so you could wrap your assembly program in Basic. > It meant some commercial games started with Basic ! > > Anyway - it would be easy to reserve some memory with a string like > object to pass to an 'assembly object' and allow some really nifty > (and fast) stuff ?? For simple algorithms it would be very neat. > Avoiding memory overflow etc would be up to the assembly code 'chunk' > of course. > > Regards, > > > Fuzzy > > http://www.voidspace.org.uk/atlantibots/pythonutils.html I.m sure that what I am about to suggest isn't as high tech as you were expecting , but I thought that Python already has a way of accessing functions in a Unix shared library, or Windows DLL. If you cancompile Python on the platform than you no doubt have an assembler handy too. So, you could put your assemble language in a string; write the string to a file; assemble the file to create a shered library or DLL, then call the function from Python! I don't think I'd do it that way though :-) Cheers, Pad. From claird at lairds.com Thu Apr 1 08:58:15 2004 From: claird at lairds.com (Cameron Laird) Date: Thu, 01 Apr 2004 13:58:15 -0000 Subject: But it still doesn't explain the joke (was: Python conference slogan) References: Message-ID: <106o7vn56fgmt85@corp.supernews.com> In article , Aahz wrote: . . . >IIRC, there's currently a court case to remove the "under God" part. . . . In the litigious US, court cases for everything are unceasing. What I suspect you have in mind is a Supreme Court hearing for a father who, if I understand correctly, claims his religious freedom as an atheist unconstitutionally impaired because of a requirement imposed by the public school his daughter attends that she recite The Pledge . More background appears at . -- Cameron Laird Business: http://www.Phaseit.net From bik.mido at tiscalinet.it Tue Apr 27 17:12:41 2004 From: bik.mido at tiscalinet.it (Michele Dondi) Date: Tue, 27 Apr 2004 23:12:41 +0200 Subject: Is Perl *that* good? (was: How's ruby compare to it older brother python) References: <108q51j4dscn7dc@corp.supernews.com> Message-ID: ?On Mon, 26 Apr 2004 16:55:02 -0400, "Ruby Tuesdays" wrote: >Would this super perl program of yours can convert the massive amount of >perl script to ruby or python? > >If it could, it would be great so ruby/python programmers does not have to >learn those cryptic perl-ish syntax and the non-OOish scripting language. Huh?!? Michele -- # This prints: Just another Perl hacker, seek DATA,15,0 and print q... ; __END__ From shalabh at cafepy.com Wed Apr 14 20:34:47 2004 From: shalabh at cafepy.com (Shalabh Chaturvedi) Date: Wed, 14 Apr 2004 17:34:47 -0700 Subject: Bug in eval function? In-Reply-To: References: Message-ID: Pascal wrote: >>>>eval('88200') > > 88200 > >>>>eval('00088200') > > > Traceback (most recent call last): > File "", line 1, in -toplevel- > eval('00088200') > File "", line 1 > 00088200 > ^ > SyntaxError: invalid token > As Graham answered, you're writing octal. And as you see here, it is not just eval: >>> print 08 File "", line 1 print 08 ^ Shalabh From rick.ratzel at magma-da.com Wed Apr 21 03:04:55 2004 From: rick.ratzel at magma-da.com (Rick L. Ratzel) Date: Wed, 21 Apr 2004 07:04:55 GMT Subject: Embedding Python in C References: <4039221c.0404201624.119476e9@posting.google.com> Message-ID: <408619B6.4010502@magma-da.com> I'm assuming you mean PyArg_Parse and PyArg_ParseTuple? I couldn't find any docs on Py_Parse or Py_ParseTuple... Anyway, maybe something like this might work for you (portions taken from example in http://elmer.sourceforge.net/PyCon04/elmer_pycon04.html): ... PyObject* evalModule; PyObject* evalDict; PyObject* evalVal; PyObject* tupleItem; unsigned char* my_c_array; int i; int tupleSize; PyRun_SimpleString( "result = pyFuncWhichReadsDevice()" ) evalModule = PyImport_AddModule( (char*)"__main__" ); evalDict = PyModule_GetDict( evalModule ); evalVal = PyDict_GetItemString( evalDict, "result" ); if( evalVal == NULL ) { PyErr_Print(); exit( 1 ); } else { if( !PyTuple_Check( evalVal ) ) { printf( "Error: pyFuncWhichReadsDevice() did not return a tuple" ); exit( 1 ); } my_c_array = (unsigned char*) malloc( sizeof( unsigned char ) * PyTuple_Size( evalVal ) ); tupleSize = PyTuple_Size( evalVal ); for( i=0; i < tupleSize; i++ ) { tupleItem = PyTuple_GetItem( evalVal, i ); if( !PyInt_Check( tupleItem ) ) { printf( "Error: pyFuncWhichReadsDevice() returned tuple with non-int value" ); exit( 1 ); } my_c_array[i] = (unsigned char) PyInt_AsLong( tupleItem ); } } ... I have no idea if this will work for you since I haven't even tried to compile it...consider it pseudo-code. -Rick. youngdubliner at hotmail.com wrote: > Hi All , > > Bit of a problem with Py_Parse or Py_ParseTuple ? > > I have a python script that reads a sector of flash in an embedded device. > it returns the value of each byte within the sector as a tuple. > > i.e. [255,255,255,255,255,255,255, .......etc etc for the whole sector ! > > We are using this script to read whats currently in any sector. > No problems there. > > Now I need to call our script from C. > > I want to copy each of the bytes within the sector into an C unsigned char *array > > Is there any way to do this using Py_ParseTuple or Py_Parse ??? > > something like this for instance ??? ...... > > Py_ParseTuple[pres,"??",&my_c_array] > > so now my_c_array[0] = 255 ,my_c_array[1] = 255 ,my_c_array[2] = 255 , etc etc > > > Thanks for the help ! From elainejackson7355 at home.com Wed Apr 7 16:15:26 2004 From: elainejackson7355 at home.com (Elaine Jackson) Date: Wed, 07 Apr 2004 20:15:26 GMT Subject: list comprehensions Message-ID: List comprehensions don't work the way you intuitively expect them to work. I realize many people have no intuitions about how list comprehensions 'should' work, so if you recognize yourself in this description, feel free to go back to whatever you were doing before. If you're still here, though, I invite you to consider the following definition: partitions = lambda n: [[n]]+[[k]+x for x in partitions(n-k) for k in range(1,n)] As defined above, the function raises an exception when you call it ('k' referenced before assignment). For the sake of clarity, here is workable code expressing the same intention: def partitions(n): reVal=[[n]] for k in range(1,n): for x in partitions(n-k): reVal.append([k]+x) return reVal So I guess what I want to ask is: Can somebody explain the semantics of list comprehensions to me? Or even better: Can somebody tell me where to look in the documentation to find out about list comprehensions? All donations gratefully received. Peace From bokr at oz.net Thu Apr 22 14:42:58 2004 From: bokr at oz.net (Bengt Richter) Date: 22 Apr 2004 18:42:58 GMT Subject: Convert hexadecimal string to binary References: Message-ID: On 22 Apr 2004 08:06:26 -0700, ekoome at yahoo.com (Eric) wrote: >Guys, >I have the following hexadecimal string - '\xff\xff\xff' which i need >to convert to binary. > >How would i go about doing this? > Assuming that string is the representation of a string of bytes whose binary values are 255 (or hex 0xff), and you want to view it like a big-endian number representation, and convert it to an integer (or long, if it gets big), >>> def s2i(s): return sum([ord(c)*256**i for i,c in enumerate(s[::-1])]) ... >>> s2i('\xff\xff\xff') 16777215 >>> hex(s2i('\xff\xff\xff')) '0xffffff' >>> hex(s2i('\x01\x02\x03')) '0x10203' >>> hex(s2i('\x01\x02\x03\x04')) '0x1020304' >>> hex(s2i('\x01\x02\x03\x04\x05')) '0x102030405L' >>> hex(s2i('\x01\x02')) '0x102' >>> s2i('\x01\x02') 258 Note that this is unsigned -- >>> hex(s2i('\xff\xff\xff\xff')) '0xFFFFFFFFL' >>> hex(s2i('\x80\x00\x00\x00')) '0x80000000L' You could do it other and faster ways... Regards, Bengt Richter From lbates at swamisoft.com Thu Apr 15 17:44:07 2004 From: lbates at swamisoft.com (Larry Bates) Date: Thu, 15 Apr 2004 16:44:07 -0500 Subject: newbie question References: Message-ID: <0JWdnRgNsdm7n-Ld4p2dnA@comcast.com> sdata may have additional characters in it. If so, there is no way it will ever equal "kill". You might want something like: if sdata.startswith("kill"): s.close() assuming that kill will be at the front of the data stream of 1024 characters. Larry Bates Syscon, Inc. "jeff" wrote in message news:Xns94CCA82D89C84plasticnospamplsxsin at 216.77.188.18... > Krzysztof Stachlewski wrote in > news:c5mtsl$dns$2 at absinth.dialog.net.pl: > > > jeff wrote: > > > >> ex: > >> > >> a = "text str" > >> if a == "text str": print a > >> > >> why doesn't that work? i couldn't find much help about variable > >> types in the manual, does it need a property like a.text? > > > > It works - at least on my computer. > > That is: it prints "text str" to the console. > > What did you expect it to do? > > > ok this is the bit i'm working with, i'm tinkering with sockets. > when the recieved text == kill, i want the socket to close. actually, the > example i posted worked for me too, but i don't understand why this > doesn't. > > while 1: > sdata = s.recv(1024) > if not sdata: break > if sdata == "kill": s.close() > print "Recieved:", sdata From theller at python.net Wed Apr 28 15:12:44 2004 From: theller at python.net (Thomas Heller) Date: Wed, 28 Apr 2004 21:12:44 +0200 Subject: wxpython + py2exe + innosetup References: <408eca0c$1@newsflash.abo.fi> <30260531.0404272030.3fe52362@posting.google.com> Message-ID: <3c6nor0z.fsf@python.net> sdahlbac at abo.fi (Simon Dahlbacka) writes: > simoninusa2001 at yahoo.co.uk (simo) wrote in message news:<30260531.0404272030.3fe52362 at posting.google.com>... >> "Simon Dahlbacka" wrote: >> >> > I'm "exefying" an application that uses wxpython, some com to control excel >> > and word and want to distribute this application. >> > >> > after creating the executable with py2exe, it still works fine (at least on >> > my development machine), however, if I create an installer package with >> > innosetup, install it and try to run it, I get a busy cursor for a split >> > second and then.. nothing. no errors no traceback no nothing.. viewing >> > dependencies does not reveal anything strange, and running the installed >> > program in a debugger just tells that the application has exited with code >> > 0. > another strange thing is that I tried to sprinkle "print I got here > statements" all over the place, but didn't see any of those, even > running from a console. If you build it as windows program (not console), sys.stderr is redirected to a logfile, and sys.stdout is redirected into the eternal bitsink. This is to prevent IO errors in your debug print statements, or when tracebacks are printed. The code which does this is in py2exe/boot_common.py for your inspection and/or improvements. You can also override this default behaviour by assigning your own objects to sys.stdout and sys.stderr. Unfortunately, this very code in py2exe 0.5.0 has a bug, which will be triggered when the sys module is *not* imported in your main script (the 'sys' symbol is deleted too early in boot_common.py). So, it could be that your program tries to report something, and then 'crashes' (meaning: fails to initialize). I will release py2exe 0.5.1 later this week, which should have fixed this and other bugs ;-). What I usually do to find out why a program behaves strange, is to build both a console *and* a windows version (with different names, say app_c.exe and app.exe). Then, you can (even on the target machine) run the console version to see the debug prints, and after you have found and fixed potential problems, run the windows version and delete the console version again. Or you simply don't create a shortcut for the console version. Hope that helps, Thomas From duncan-news at grisby.org Wed Apr 28 10:47:03 2004 From: duncan-news at grisby.org (Duncan Grisby) Date: Wed, 28 Apr 2004 16:47:03 +0200 Subject: omniorb, python and callbacks References: <108qul5he6cn1ba@corp.supernews.com> Message-ID: <42b2$408fc3e7$51604868$16406@nf3.news-service-com> In article <108qul5he6cn1ba at corp.supernews.com>, Melissa Wallis wrote: >I have a class with 5 callbacks. Two of the callbacks work fine but the >others don't. The main difference is that the callbacks that don't work are >composed of a sequence of structs. I noticed a comment about this same >problem on the web but no solution was noted. What makes the callbacks with >the sequences so different? It seems that when one of the callbacks with a >sequence is called it just hangs. I am talking to a TAO orb from omniORB. I suggest you subscribe and post to the omniORB mailing list rather than here. When you post, please give some details about what exactly you are doing, and what exactly goes wrong. Have you tried running omniORB with some tracing turned on? Cheers, Duncan. -- -- Duncan Grisby -- -- duncan at grisby.org -- -- http://www.grisby.org -- From claird at lairds.com Sat Apr 3 05:39:41 2004 From: claird at lairds.com (Cameron Laird) Date: Sat, 03 Apr 2004 10:39:41 -0000 Subject: simple popen question References: <1080965541.46978@yasure> Message-ID: <106t53d7spbgr3d@corp.supernews.com> In article <1080965541.46978 at yasure>, Donn Cave wrote: >Quoth Jim Benson : >| On Fri, 2 Apr 2004, Cameron Laird wrote: >... >|> In general, no; the reader doesn't control the buffering, the writer does. >| >| The reason i suspect popen is that when i run >| the executable from the unix shell...i see every >| output line ~ when expected. > >Well, the writer knows. When you run it "from the shell", that >really means its output device is /dev/tty. When you run it from >popen(), its output device is a pipe. C library I/O, and hence >most application I/O, automatically treats these two devices >differently. Or rather, it treats the tty specially, and treats >a pipe like any other file. For the tty it uses line buffering, >for everything else block buffering. > >There's a function that changes the policy - setbuffer I think may >be the contemporary standard, I think setbuf and setvbuf are historical >but don't count on me to get that straight. > > Donn Cave, donn at drizzle.com All true--and Python even has an answer, Pexpect, for those stuck with such subtleties. I repeat my advice, though, that Mr. Benson will likeliest find quick satisfaction simply by having his writer flush on newline. Also, Mr. Benson, are you *sure* you want to treat blank lines as end-of-message markers? -- Cameron Laird Business: http://www.Phaseit.net From hans at zephyrfalcon.org Fri Apr 9 15:54:48 2004 From: hans at zephyrfalcon.org (Hans Nowak) Date: Fri, 09 Apr 2004 15:54:48 -0400 Subject: module not callable - why not? In-Reply-To: References: Message-ID: <4076FF88.70504@zephyrfalcon.org> Diez B. Roggisch wrote: > Now I thought about defining a __call__ operator at module level to allow > this: > > import quaternion > > q = quaternion() > > > where the call looks like this: > > def __call__(*a, *kw): > return quaternion() > > But that doesn't work. > > Now my question is: Is there a way to make a module callable that way? And > wouldn't it make sense to allow the implementation of a call operator on > module level? Is is possible, if you use packages, and are willing to use some evil hackery. :-) Here's what to do: 1. Create a package 'quaternion'. 2. Create quaternion/__init__.py: # quaternion/__init__.py from types import ModuleType import os, sys class QuaternionModule(ModuleType): def __init__(self): import _quaternion self.__name__ = "_quaternion proxy" self.__file__ = __file__ self.__base = os.path.dirname(__file__) self.__module = sys.modules['quaternion'] def __call__(self): return _quaternion.quaternion() sys.modules['quaternion'] = QuaternionModule() del sys, os, ModuleType, QuaternionModule 3. Create quaternion/_quaternion.py: # _quaternion.py class quaternion: def foo(self, x): return x*2 (obviously a dummy implementation, but you get the idea) 4. Test it: Python 2.3.3 (#51, Dec 18 2003, 20:22:39) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import quaternion >>> q = quaternion() >>> q.foo(42) 84 >>> To be fair, this is an adaptation of some code sent to me by Olivier Poyen. It was originally a construct to add dynamic import to my Wax library (which currently imports a bunch of modules in its __init__.py, taking up time and space, whether you use them or not). Now, whether this good coding practice is something else entirely... :-) Cheers, -- Hans (hans at zephyrfalcon.org) http://zephyrfalcon.org/ From jbperez808 at wahoo.com Tue Apr 27 04:36:18 2004 From: jbperez808 at wahoo.com (Jon Perez) Date: 27 Apr 2004 08:36:18 GMT Subject: CPU usage of Python interpreter doing empty while loop under XP References: <7kpr805ou6g8ucm9rok4nodkolcp02viig@4ax.com> Message-ID: Dennis Lee Bieber wrote: > Stick a sleep(0) inside it, and no doubt you will see performance > return to "normal". Even though the 0 means no actual delay is wanted, > the task swap will occur, giving the OS a chance to respond to events. Great, it worked. So while 1: sleep(0) is a better alternative to while 1: pass (I'm using this for debugging purposes...) From nicolas.lehuen at thecrmcompany.com Wed Apr 21 06:36:22 2004 From: nicolas.lehuen at thecrmcompany.com (Nicolas Lehuen) Date: Wed, 21 Apr 2004 12:36:22 +0200 Subject: Python 2.3.3 super() behaviour References: <40863bd7$0$25528$afc38c87@news.easynet.fr> <40864674$0$24834$afc38c87@news.easynet.fr> Message-ID: <40864ea6$0$25528$afc38c87@news.easynet.fr> The only problem I have is that I want to build a multiple inheritance involving an object which does not cooperate, namely : class T(object): def __init__(self): super(T,self).__init__() class TL(list,object): def __init__(self) super(TL,self).__init__() In this case, T.__init__ is not called, because list.__init__ does not use super(). The only clean way to proceed is to change the inheritance order : TL(T,list). This way, both constructors are called. Here is another example which exhibits the behaviour : class A(object): def __init__(self): super(A,self).__init__() print 'A' class B(object): def __init__(self): print 'B' class C(B,A): def __init__(self): super(C,self).__init__() print 'C' class D(A,B): def __init__(self): super(D,self).__init__() print 'D' >>> C() B C <__main__.C object at 0x008F3D70> >>> D() B A D <__main__.D object at 0x008F39F0> The problem is that if you go further down the inheritance, the behaviour is even more complicated : class E(object): def __init__(self): super(E,self).__init__() print 'E' class F(C,E): def __init__(self): super(F,self).__init__() print 'F' class G(D,E): def __init__(self): super(G,self).__init__() print 'G' >>> F() B C F <__main__.F object at 0x008F3D70> >>> G() B A D G <__main__.G object at 0x008F3EF0> class H(E,C): def __init__(self): super(H,self).__init__() print 'H' class I(E,D): def __init__(self): super(I,self).__init__() print 'I' >>> H() B C E H <__main__.H object at 0x008F3E30> >>> I() B A D E I <__main__.I object at 0x008F3FD0> So the conclusion is : never do that :). Another more constructive conclusion would be : always put the most cooperative classes first in the inheritance declaration, provided that it doesn't interfere with your needs. A class which has an uncooperative ancestor is less cooperative than a class which has only cooperative ancestors. Regards, Nicolas "Nicolas Lehuen" a ?crit dans le message de news:40864674$0$24834$afc38c87 at news.easynet.fr... > OK, I get it now, thanks. > > super() method calls should only be used for method involved in > diamond-shaped inheritance. This is logical since in this case the base > classe (from which the diamond-shaped inheritance starts) defines the > interface of the method. > > This solves another question I was asking myself about super() : "how can it > work when the method signature differ between B and C ?". Answer : the > method signature should not change because polymorphic calls would be > greatly endangered. The base class defines the signature of the method which > must be followed by all its children, this way super() can work properly. > > The base method signature is not enforced by Python, of course, but you'd > better respect it unless you get weird result in polymorphic calls. > > Regards, > Nicolas > > "Peter Otten" <__peter__ at web.de> a ?crit dans le message de > news:c65fbo$1q4$05$1 at news.t-online.com... > > Nicolas Lehuen wrote: > > > > > Hi, > > > > > > I hope this is not a FAQ, but I have trouble understanding the behaviour > > > of the super() built-in function. I've read the excellent book 'Python > in > > > a Nutshell' which explains this built-in function on pages 89-90. Based > on > > > the example on page 90, I wrote this test code : > > > > > > class A(object): > > > def test(self): > > > print 'A' > > > > > > class B(object): > > > def test(self): > > > print 'B' > > > > > > class C(A,B): > > > def test(self): > > > super(C,self).test() > > > print 'C' > > > > > > print C.__mro__ > > > c=C() > > > c.test() > > > > > > The output is : > > > (, , , > > 'object'>) > > > A > > > C > > > > > > Whereas I was expecting : > > > (, , , > > 'object'>) > > > A > > > B > > > C > > > > > > Was I wrong to expect this (based on what I've read ?) > > > > As soon as a test() method without the super(...).test() is reached, no > > further test methods will be invoked. Only the first in the list of base > > classes will be invoked. If I'm getting it right you have to do something > > like: > > > > class Base(object): > > def test(self): > > print "base" > > > > class D1(Base): > > def test(self): > > super(D1, self).test() > > print "derived 1" > > > > class D2(Base): > > def test(self): > > super(D2, self).test() > > print "derived 2" > > > > class All(D1, D2): > > pass > > > > All().test() > > > > Here all cooperating methods have a super() call, and the base class acts > as > > a showstopper to prevent that Python tries to invoke the non-existent > > object.test(). > > > > Peter > > > > > > > > From rmanx at gmx.de Thu Apr 1 08:13:04 2004 From: rmanx at gmx.de (Robert) Date: Thu, 1 Apr 2004 15:13:04 +0200 Subject: Don't understand wxPython event handling References: Message-ID: I also have anouther question: which is the better way to register to events: eventManager.Register(self.OnPageDone,EVT_PAGE_DONE,self.pageContainer) or EVT_PAGE_DONE(self, self.OnPageDone) From grzegorz at ee.ualberta.ca Sat Apr 17 13:59:16 2004 From: grzegorz at ee.ualberta.ca (Grzegorz Dostatni) Date: Sat, 17 Apr 2004 13:59:16 -0400 Subject: Static Modules... In-Reply-To: References: Message-ID: On Sat, 17 Apr 2004, Peter Hansen wrote: > That's not entirely accurate, I think. With static typing, you > can't even use a variable if you don't predefine it, but predefining > it doesn't necessarily give it a value (or it gives it a benign > default value). With dynamic typing, just asking for a variable > doesn't (normally) magically create one with an appropriate value. Consider this imaginary python code: asdf.hello() The problem is that we don't know what asdf is. It could be a module, an object or even a function (eg. >>> def asdf(a="Hello", b="World"): ... print (a,b) ... >>> asdf.hello = asdf ) # closing the (eg. My claim here is that we don't "magically" create the variable. You are still required to explicitly ask for it (as in sys.setrecursionlimit - you're asking for sys), BUT that statement is based on a fact that I KNOW what sys is - a module. I think that is the root of this discussion. And no, I don't like the idea of changing syntax to accomodate it ;-) > This hack is a cool idea for interactive prompts, but in real > code and even at the prompt it could actually be quite "dangerous". > Importing a module can cause arbitrary code to execute, so it > makes some sense to _require_ the import statement. I somewhat agree with this. It is definitely a good idea to require imports of custom modules. It is quite easy to add that check into the code. This is a great hack for the interactive mode. > After all, what if I had a module called, perhaps inappropriately, > "launch" and it triggered the launch of my personal anti-aircraft > missile when imported? (Yes, bad style too, but I wrote this > control code long ago before I learned good style. ;-) Now in > one of my other modules, I have a subtle bug** which involves an > object named, perhaps unsurprisingly for this example, "launch". > > The code looks like this actually (pulled right out of the source > tree!), slightly edited to preserve national security: > > def checkLaunchPermission(self): > lunch = self.findLaunchController() > if launch.inhibited: > # code that doesn't launch anything... > > Now if I understand it properly, when your hack is in place > this would actually import the launch module and cause all hell > to break loose. Hmm.. In the interest of continual survival of human race I could include a warning whenever including a module. Or perhaps make the binding to sys.excepthook explicit (an extra statement), but extra statements is what I want to avoid. Another options would be to make this work *ONLY* for system libraries (sys,os,os.path,popen, etc.). One thing I can't get out of my head is that if your launch module is installed in PYTHONPATH, we're all in danger and should probably seek cover. Isn't it more likely that launch.py is somewhere deep under "NSA/development/python/missile" directory? So it should not be imported automatically. Generally only the system library and custom modules to the project you're working on are available to be imported. > Did I just make a case for static typing with Python? Well, > perhaps, but only in the relatively dangerous area of module > imports and there, unlike with simple variable names, Python > already requires explicit (i.e. static) definitions... > > -Peter > Greg From david at rebirthing.co.nz Fri Apr 23 02:48:49 2004 From: david at rebirthing.co.nz (David McNab) Date: Fri, 23 Apr 2004 18:48:49 +1200 Subject: ANN: PyBison - high-performance Python Parser Message-ID: <4088BC51.40208@rebirthing.co.nz> Hi, Announcing PyBison, a framework for writing high-performance, full LALR(1) parsers in Python, which automatically create and hook in to Bison/Yacc-generated C parser code. http://www.freenet.org.nz/python/pybison Same genre as packages like PLY, YAPPS etc. Users write a Parser class in Python. Upon instantiation of that class, the parent class loads (or generates) a shared library file containing the parser-specific C yyparse() code for the parser. The generation process automatically introspects the user's class, extracting grammar/lexer definitions from docstrings and attributes, creating .y and .l files, compiling these and linking these to the shared lib. All done automagically in the background. At the price of depending on the presence of a C compiler/linker, Python development libs/headers, Pyrex, plus bison and flex, PyBison delivers a parser framework offering the ease and comfort of Python, with the raw power and (most of) the speed of the raw C parser tools. Release status: Alpha, version 0.1.1 Distribution includes examples, walkthrough document and API reference. Bug reports, requests, patches etc, please send to me. Enjoy Cheers David From sadplanet at MAPS.chello.be Sat Apr 24 07:11:22 2004 From: sadplanet at MAPS.chello.be (mr.happy) Date: Sat, 24 Apr 2004 11:11:22 GMT Subject: walking a list References: Message-ID: On Fri, 23 Apr 2004 13:21:43 -0500, Jeff Epler wrote: > if isinstance(i, list): print_or_recurse(i) great! thanks, i didn't know 'isinstance' existed. what i did was the following: if 'list' in str(type(list)): it worked as well :) -- One monk said to the other, "The fish has flopped out of the net! How will it live?" The other said, "When you have gotten out of the net, I'll tell you." From OlafMeding at compuserve.com Wed Apr 28 16:15:02 2004 From: OlafMeding at compuserve.com (Olaf Meding) Date: 28 Apr 2004 13:15:02 -0700 Subject: COM, IDL, and enum Message-ID: <9e5ea2c4.0404281215.25a0f9b3@posting.google.com> How do I access the values of the enum "ERLockStatus" specified in the (abreviated IDL) file below? This code works fine and lets me call the methods of the user interface. import win32com.client ui = win32com.client.Dispatch('ERFile.User') ui.someMethod() Here is the (abreviated) IDL file: // This file will be processed by the MIDL tool to // produce the type library (ERFile.tlb) and marshalling code. import "oaidl.idl"; import "ocidl.idl"; [ uuid(bf79b6c5-47be-11d2-bacd-006008060a3a), version(1.0), helpstring("ERFile 1.0 Type Library") ] library ERFile { importlib("stdole32.tlb"); importlib("stdole2.tlb"); [ object, uuid(bf79b6c7-47be-11d2-bacd-006008060a3a), dual, helpstring("IERecord Interface"), pointer_default(unique), nonextensible, hidden ] interface IUser : IDispatch { code deleted here }; [helpstring("ER Lock Status")] enum ERLockStatus { ls_unlocked, ls_by_caller, ls_by_another, ls_not_locked }; more code deleted here }; Thanks much in advance for your help. Olaf From jonas at jonasgalvez.com Wed Apr 21 12:31:38 2004 From: jonas at jonasgalvez.com (Jonas Galvez) Date: Wed, 21 Apr 2004 13:31:38 -0300 Subject: Regex'ing null bytes References: Message-ID: > [Fredrik Lundh] > the "pre" (pcre) engine doesn't support null bytes in pattern > strings, but it does understand octal escapes. > > in other words, use double backslashes, or an "r" string: > > "\\000" > r"\0" > > As I said, I'm not going to use regexes anymore, but... good to know! Thanks a lot for the info. =- Jonas Galvez jonasgalvez.com/blog macromedia.com/go/team From xiaohua_sun at yahoo.com Mon Apr 5 01:46:05 2004 From: xiaohua_sun at yahoo.com (SunX) Date: 4 Apr 2004 22:46:05 -0700 Subject: write data file Message-ID: <337e6cd5.0404042146.6e39153c@posting.google.com> Question from a newbie. How do you write out a data file of floating point numbers? file.write only takes strings. Many thanks. From paul at prescod.net Sat Apr 3 18:07:55 2004 From: paul at prescod.net (Paul Prescod) Date: Sat, 03 Apr 2004 15:07:55 -0800 Subject: Pyrex list is down Message-ID: <406F43CB.9030505@prescod.net> It seems like nothing has gone in or out for days: http://lists.copyleft.no/pipermail/pyrex/2004-April/thread.html Paul Prescod From skip at pobox.com Fri Apr 23 15:49:43 2004 From: skip at pobox.com (Skip Montanaro) Date: Fri, 23 Apr 2004 14:49:43 -0500 Subject: Best way to add attributes to shelved objects? In-Reply-To: <20040423193951.GC27351@dogma.freebsd-uk.eu.org> References: <20040423193951.GC27351@dogma.freebsd-uk.eu.org> Message-ID: <16521.29527.356495.151656@montanaro.dyndns.org> jm> I'm working on an app that persists a few classes with shelve. But jm> if I load older saved classes, I get an exception in code that uses jm> the new attributes, of course. jm> What is the best way to load these older classes, check for the new jm> attributes, and add them so they will work with the new code? Why not check for those attributes in your __getstate__ method and add default (or computed) values for any missing attributes? Skip From nmkolev at uni-bonn.de Wed Apr 21 15:19:45 2004 From: nmkolev at uni-bonn.de (Nickolay Kolev) Date: Wed, 21 Apr 2004 21:19:45 +0200 Subject: Optimizing a text statistics function In-Reply-To: References: Message-ID: Peter Otten wrote: Thanks for taking the time to rewrite the whole thing. I will try to work through it as I do not understand what you are doing most of the time there. > Speed is not that important most of the time. Agreed. I am not looking for a magical solution that will shave some time off at the price of using things I do not understand and/or are not readable. > You might consider switching to 4-space indent. Not wanting to start a flame here (this is probably a much discussed topic): why? I write in VIM and use tabs. The default representation width of the tab char there is 8 spaces. If I do get many, many nested blocks, I could just set it to a lower width, no? Nicky From mwh at python.net Fri Apr 23 06:32:35 2004 From: mwh at python.net (Michael Hudson) Date: Fri, 23 Apr 2004 10:32:35 GMT Subject: bytecode JUMP_IF_* always followed by POP_TOP? References: Message-ID: "Robert Brewer" writes: > Tim Peters wrote: > > [Robert Brewer] > > > Playing around with bytecodes some more: > > > ... > > > I notice that, whether JUMP_IF_FALSE jumps or not, the next > > > instruction it executes is POP_TOP > > > ... > > > Are there any constructions whereby this does not happen for > > > JUMP_IF_FALSE and JUMP_IF_TRUE? > > > > Try > > > > x and y > > > > and > > > > x or y > > > > When those jump, they want to retain the tested value, so > > there's no POP_TOP > > at the branch target then. > > Ah. They only POP_TOP if they *don't* jump. Got it. Thanks! I think you may want to play around with chained comparisons, too, IIRC. We Have Been Here Before :-) Cheers, mwh -- The above comment may be extremely inflamatory. For your protection, it has been rot13'd twice. -- the signature of "JWhitlock" on slashdot From alloydflanagan at comcast.net Fri Apr 23 09:32:23 2004 From: alloydflanagan at comcast.net (A. Lloyd Flanagan) Date: 23 Apr 2004 06:32:23 -0700 Subject: Python use large scale projects References: <47fc6058.0404212327.24163290@posting.google.com> Message-ID: "Larry Bates" wrote in message news:... > > The ONLY knock I have against Python is in developing > pure GUI applications. My business partner is a > PowerBuilder developer. For pure GUI applications he > finds PowerBuilder superior to Python (actually this > is something that I cannot argue against), but he For what it's worth, I've had pretty good results so far with wxPython. There's a visual development environment called Boa Constructor that I'm not completely sold on, but then it's still in development. From mcfletch at rogers.com Sat Apr 10 20:40:01 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Sat, 10 Apr 2004 20:40:01 -0400 Subject: new-style class instance check In-Reply-To: References: Message-ID: <407893E1.5030408@rogers.com> Richard Gruet wrote: >Robert > >Thank you for your suggestion. >But unfortunately, isNewStyleClassInstance(o) must return False for >*everything but* an instance of a new-style class. If o is e.g. a function: >def foo(): pass >foo.__class__.rmo > > >so isNewStyleClassInstance(foo) would return True ! > > Your problem is that you are using "new style class" to describe what you want, and "new style classes" are all over Python, with methods, strings, lists, etceteras all being new-style classes in the "proper" sense of the term. So, the canonical "is it a new style class instance" function: def isNewStyleClassInstance( obj ): try: return isNewStyleClass( obj.__class__ ) except AttributeError: return False def isNewStyleClass( cls ): return isinstance( cls, type ) is going to fail your test because all sorts of things that *you* don't consider classes are going to be considered new-style classes (e.g. list, tuple, str, and functions) even though they really *are* new-style classes. So, your challenge is to define what *you* mean by new-style classes (as distinct from what everyone else means), possibly "new-style but not in the built-in module": def isRichardsNewStyle( obj ): return isNewStyleClassInstance( obj ) and type(obj).__module__ != '__builtin__' but that wouldn't catch array.ArrayType and the like which are coded in C but not stored in the builtins module. I'm guessing what you're looking for is "everything that would have had a type InstanceType in Python 2.1 and before", but I don't have time to track down all the little corner cases for how to implement that, and I'd guess you'll find that there's better ways to accomplish what you want than using it anyway. Type-class unification has forever blurred the line between class and type, and coding as if it hadn't is just going to cause pain IMO. Good luck, Mike _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From hungjunglu at yahoo.com Mon Apr 19 13:08:41 2004 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 19 Apr 2004 10:08:41 -0700 Subject: module not callable - why not? References: <7xsmf1fxd9.fsf@ruckus.brouhaha.com> <8ef9bea6.0404180956.cd1a152@posting.google.com> Message-ID: <8ef9bea6.0404190908.4b130d57@posting.google.com> aahz at pythoncraft.com (Aahz) wrote in message news:... > In article <8ef9bea6.0404180956.cd1a152 at posting.google.com>, > Hung Jung Lu wrote: > > > >(i) For getting attributes by string names, for attributes of > >instances you do getattr(self, 'name'), for module attributes you do > >globals()['name']. I mention this because every once a month or so a > >newbie would ask how to get module level attributes by name. > > That's not the only answer, and it's not the one I use: > > import foo > getattr(foo, 'name') You can't do this when you are inside the module itself. Similarly, unless I am inside a class, I wouldn't use getattr(self, 'name'). I was comparing apple to apple. You gave me an orange. :) Hung Jung From SeeBelow at SeeBelow.Nut Tue Apr 27 13:52:09 2004 From: SeeBelow at SeeBelow.Nut (SeeBelow at SeeBelow.Nut) Date: Tue, 27 Apr 2004 17:52:09 GMT Subject: Tkinter vs. wxPython? Message-ID: <408E9DCA.EC753FE6@shaw.ca> Do many people think that wxPython should replace Tkinter? Is this likely to happen? I ask because I have just started learning Tkinter, and I wonder if I should abandon it in favor of wxPython. Mitchell Timin -- "Many are stubborn in pursuit of the path they have chosen, few in pursuit of the goal." - Friedrich Nietzsche http://annevolve.sourceforge.net is what I'm into nowadays. Humans may write to me at this address: zenguy at shaw dot ca From project5 at redrival.net Tue Apr 27 14:37:34 2004 From: project5 at redrival.net (Andrei) Date: Tue, 27 Apr 2004 20:37:34 +0200 Subject: Tkinter vs. wxPython? References: <408E9DCA.EC753FE6@shaw.ca> Message-ID: <71thmlf6m3tv.fk5ufa40nrow.dlg@40tude.net> SeeBelow at SeeBelow.Nut wrote on Tue, 27 Apr 2004 17:52:09 GMT: > Do many people think that wxPython should replace Tkinter? Is this > likely to happen? >From my POV it would be a good idea since I don't use Tkinter/Tkinter apps but I do use wxPython. However, I don't think it will happen because things out of the standard distro don't get phased out that easily; programs count on Tkinter being there. Plus Idle would have to be removed as well, which is not very likely to happen since it's the standard Python IDE :). > I ask because I have just started learning Tkinter, and I wonder if I > should abandon it in favor of wxPython. If you like Tkinter, use it. If you like wxPython, use that - neither of them shows any signs of going away in the near or not so near future. BTW, there are several nice GUI builders for wxPython available which might be of assistance in using wxPython. Personally I prefer wxPython and I avoid Tk-based apps whenever I have an alternative, which is basically always :). -- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5 at jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From peholmst at abo.fi Thu Apr 15 07:07:25 2004 From: peholmst at abo.fi (=?ISO-8859-1?Q?Petter_Holmstr=F6m?=) Date: Thu, 15 Apr 2004 14:07:25 +0300 Subject: Getters and setters in python, common practise In-Reply-To: References: <407e402c$1@newsflash.abo.fi> Message-ID: <407e6cf9@newsflash.abo.fi> Peter Hansen wrote: >> Having a Delphi/Object Pascal-background, I'm very used to using >> getters and setters when designing my classes. What is the common >> practise in the Python world? Should one use them or not? > > Max described the common practice (don't use them until you actually > need them) but forgot to mention that in recent versions of Python > you can use "properties", in pretty much the same manner as Delphi > uses them. I have not found any documentation on this topic. Could you please point me to some? -Petter- From alloydflanagan at comcast.net Fri Apr 23 09:28:04 2004 From: alloydflanagan at comcast.net (A. Lloyd Flanagan) Date: 23 Apr 2004 06:28:04 -0700 Subject: Python-list, Exotic sex is urgently necessary for you! References: Message-ID: Timo Virkkala wrote in message news:... > [disgusting content snipped] > > I've heard of sex with lots of kinds of animals, but Pythons? Wouldn't > that be a) difficult b) VERY dangerous? > > *grin* I should think so. Perhaps they were proposing something involving the whole list of subscribers. The logistics boggle the mind... From maxm at mxm.dk Tue Apr 20 08:01:44 2004 From: maxm at mxm.dk (Max M) Date: Tue, 20 Apr 2004 14:01:44 +0200 Subject: CamelCase versus wide_names (Prothon) In-Reply-To: References: <6ee58e07.0404192141.2229efd6@posting.google.com> Message-ID: <40851128.8000400@mxm.dk> Gerrit wrote: > Mark Hahn wrote: > > I haven't followed the Prothon capitalization naming convention in > detail. But in my opinion, a multi-word name should read as a multi word > name. Underscores serve better to do so than capitalization does. I think you should go against the tide. Make . a normal letter. And make _ have the function that . has in Python, so that _ and . sort of switches meaning. Anybody in hteir right mind can see that, that is a good idea: From mwh at python.net Tue Apr 27 04:50:52 2004 From: mwh at python.net (Michael Hudson) Date: Tue, 27 Apr 2004 08:50:52 GMT Subject: Magic methods in extension types References: Message-ID: Jacek Generowicz writes: > Michael Hudson writes: > > > Jacek Generowicz writes: > > > > > Michael Hudson writes: > > > > > > > Not finding the tp_as_number->nb_inplace_add field? > > > > > > ( ... or tp_as_sequence ... ) > > > > > > I was afraid you (someone) was going to say that. > > > > Why? > > Because I'm too lazy to pollute my tiny extension type with a whole > thingy_as_number sturucture for the sake of just one maginc method :-) If __iadd__ is the *only* magic method you're adding, you deserve to lose... > > Well, the type of old-style classes has something in it's > > tp_as_number->nb_inplace_add slot that looks in the class dictionary > > for an __iadd__ method. > > > > If you'd made that a new-style class, you would be surprised! > > Don't follow ... you mean if I had done this: > > >>> class foo(object): > ... def __iadd__(self,other): > ... print "__iadd__ running" > ... return self > ... > >>> f = foo() > >>> f += 2 > __iadd__ running > > ? Yup: you've added something to a type object, something you'd said you'd be surprised to hear. > > > Python manages to map "+=" to the method called "__iadd__" in > > > user-defined classes, but not for extension types. What is the > > > essential difference that makes that mapping work in one case but > > > not in the other? > > > > Well, for old-style classes a whole bunch of code like: [...] > > and for new-style classes much hair in typeobject.c:type_new and > > therein called functions. Extension types don't go through type_new > > and are expected to go the other way round, in a sense: define > > something in tp_as_number->nb_inplace_add and a wrapper called > > __iadd__ will be created for you. > > Yuk. Why? > You are, in summary, saying that by _far_ the simplest way of adding > __iadd__ to an extenion type is via tp_as_number->nb_inplace_add, > aren't you. Yes. I'm surprised at your apparent surprise, but then I've had my head in the guts of Python's implementation for quite some time now... implementing types in C is really quite different from implementing them in Python, something which has only become surprising since 2.2... Cheers, mwh -- Gullible editorial staff continues to post links to any and all articles that vaguely criticize Linux in any way. -- Reason #4 for quitting slashdot today, from http://www.cs.washington.edu/homes/klee/misc/slashdot.html From fredrik at pythonware.com Fri Apr 16 06:12:16 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 16 Apr 2004 12:12:16 +0200 Subject: int('2.1') does not work while int(float('2.1')) does References: <40722555.66C70D40@alcyone.com><40722E98.253B5FF2@alcyone.com> Message-ID: Joe Mason wrote:int out of this string. > > So why can't int(string) mean round toward zero? because it isn't what it means. why so obsessed with breaking existing code? don't you have anything better to do with your life? From hwlgw at hotmail.com Thu Apr 22 12:02:04 2004 From: hwlgw at hotmail.com (Will Stuyvesant) Date: 22 Apr 2004 09:02:04 -0700 Subject: AOP use cases References: <84fc4588.0404140106.3fa0c55@posting.google.com> <0pydnSB4WYuieuLdRVn-hQ@powergate.ca> Message-ID: > [Peter Hansen ] > ... I appreciate the attempt to clarify, but so far it seems to > me that *everyone* who talks about AOP just talks in abstract terms > and isn't willing (or able?) to pin it down with *real* real-world > examples ... You got it. AOP somehow did get scientific impact in computing science. I had to read scientific papers about AOP and I had to listen to AOP conference presentations. It's all abstract chitchat about the benefits, and then they usually introduce yet another formalism or even mini-language to reason about. Formulas in ad-hoc formalisms. Forget about *real* real-world examples, these people just want to get papers published. Usability is considered of minor impportance. They are, with very few very rare exceptions, NOT able to show useful code in a high level language like Python. What they DO show is code in Java that solves Java problems, usually to do with the limitations imposed by the static typing system. It is a bad sign that so much crappy AOP papers get accepted. I have come to the conclusion that AOP is nothing more than what I expect from a decent programmer: a good, or at least reasonable, design of software in the first place. From fumanchu at amor.org Thu Apr 29 11:57:12 2004 From: fumanchu at amor.org (Robert Brewer) Date: Thu, 29 Apr 2004 08:57:12 -0700 Subject: Subclasses in Python Message-ID: Thomas Philips wrote: > I ... used self.__Class__. to access > the class attributes in the class and subclass. Works like a charm, > but I'm having some difficulty printing class names. I want > self.__class__ to return just the name of the class without some > ancillary stuff thrown in. Try self.__class__.__name__ FuManChu From peter at engcorp.com Mon Apr 26 19:47:27 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 26 Apr 2004 19:47:27 -0400 Subject: About generators In-Reply-To: <7eoq80ph28cbjj06hp2llab8acnsh2fmnc@4ax.com> References: <7eoq80ph28cbjj06hp2llab8acnsh2fmnc@4ax.com> Message-ID: Andrea Griffini wrote: > On Mon, 26 Apr 2004 09:42:18 -0400, Peter Hansen > wrote: >>Google Groups is always helpful for such questions: >>http://groups.google.com/groups?q=integer+range+syntax&meta=group%3Dcomp.lang.python.* >> >>This leads to various threads, such as the "Re: Thoughts on PEP284" >>which had the same proposal as yours and what is, I believe, an >>adequate reason for rejecting it. > > Thanx for the pointer, but I wasn't able to find a discussion > about the use of a "normal" range binary operator; You didn't read far enough. The one I mentioned above is item number 8 in the results from Google. In it, Sean Ross had asked about "for i in 0...10" and David Eppstein replies and points out the key problem with it. > Sure this would leave open a few problems, like how to specify > the step (how about the BASIC "step" ? Yes, exactly the problem he pointed out. He goes on to say "If that's all the loop syntax can do, why not just keep the current "for i in range(10):" syntax? "Explicit is better than implicit." And I agree with him. Don't introduce extra syntax for trivial gain... -Peter From fumanchu at amor.org Thu Apr 22 13:37:15 2004 From: fumanchu at amor.org (Robert Brewer) Date: Thu, 22 Apr 2004 10:37:15 -0700 Subject: Proper Way of checking for a collections class Message-ID: Gary Coulbourne wrote: > I've been trying to find a good idiom for testing if the input to a > function is one of the collections classes... the best I > could do is this: > > if hasattr(thing_to_test, '__iter__'): > ... The best way depends upon (and mirrors) exactly what you want to do with those classes. If you're going to call iter(thing), then the above is fine. If instead you want sequences, try operator.isSequenceType, etcetera. FuManChu From andrewm at object-craft.com.au Fri Apr 2 07:51:14 2004 From: andrewm at object-craft.com.au (Andrew McNamara) Date: Fri, 02 Apr 2004 22:51:14 +1000 Subject: Stackless Website down, Project gone, I'm dead. In-Reply-To: Message from Max M of "Fri, 02 Apr 2004 14:09:54 +0200." <406d5800$0$206$edfadb0f@dread12.news.tele.dk> References: <406d5800$0$206$edfadb0f@dread12.news.tele.dk> Message-ID: <20040402125114.A76893C027@coffee.object-craft.com.au> >Christian Tismer wrote: >> p.s.: I've taken the capsule, short time ago. >> p.p.s.: This message was sent to you on April 2, to make >> sure that it is not misinterpreted as a bad April 1 joke. >> The bad joke was about that bad intruder. See you soon, >> in heaven or somehwere else :-) > >If this is a joke, it is in poor taste. And if it isn't? The message headers are a good match with Christian's recent postings. I hope someone who knows Christian has been able to get in contact with him. -- Andrew McNamara, Senior Developer, Object Craft http://www.object-craft.com.au/ From tadmc at augustmail.com Tue Apr 27 17:52:07 2004 From: tadmc at augustmail.com (Tad McClellan) Date: Tue, 27 Apr 2004 16:52:07 -0500 Subject: Is Perl *that* good? (was: How's ruby compare to it older brother python) References: <108q51j4dscn7dc@corp.supernews.com> Message-ID: Michele Dondi wrote: > ?On Mon, 26 Apr 2004 16:55:02 -0400, "Ruby Tuesdays" > wrote: > >>Would this super perl program of yours can convert the massive amount of >>perl script to ruby or python? >> >>If it could, it would be great so ruby/python programmers does not have to >>learn those cryptic perl-ish syntax and the non-OOish scripting language. > > Huh?!? Simply make a killfile entry and move on. -- Tad McClellan SGML consulting tadmc at augustmail.com Perl programming Fort Worth, Texas From mark at prothon.org Fri Apr 30 14:33:27 2004 From: mark at prothon.org (Mark Hahn) Date: Fri, 30 Apr 2004 11:33:27 -0700 Subject: What is good about Prothon? References: <108t2tlo06j8vb9@corp.supernews.com> <69cbbef2.0404281446.4e0ab52e@posting.google.com> <69cbbef2.0404291609.72d391db@posting.google.com> <69cbbef2.0404300855.4dce5e5@posting.google.com> Message-ID: has wrote: > But to answer your question directly: no, simply adding a copy() > operation (the "trying to please everybody, and ultimately pleasing > no-one" strategy) won't make me happy; I have no use for another C++. You have a very warped mind. To say that having Python two-tier object construction and Self-like constructs in the same language is C++ is ludicrous. You have finally answered a question I have asked several times. Having anything but AS or Self in the language will keep you from being happy. Now that I know where you stand I can quit wasting my time trying to get you to help out. You keep pitching that you are such a creative artist, but if you were you'd be helping find a way to solve the conundrum of merging the Python and Self worlds and making positive contributions instead of just throwing stones. From usenet_spam at janc.invalid Sun Apr 18 20:13:13 2004 From: usenet_spam at janc.invalid (JanC) Date: Mon, 19 Apr 2004 00:13:13 GMT Subject: Pygame References: Message-ID: Alexander R?dseth schreef: > Besides, a huge amount of the power of Python-scripts > comes from knowing what other people has installed already. For most Windows users that would be: nothing, not even Python itself. -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From grigri9 at yahoo.com Sun Apr 18 15:37:51 2004 From: grigri9 at yahoo.com (Greg Grin) Date: 18 Apr 2004 12:37:51 -0700 Subject: imitating user input Message-ID: I need to imitate keyboard strokes in an active window inside of internet explorer, specifically I need my program to log on to a chatroom without me actually sitting in front of my computer. Also, once it has logged on to the program I need my program to "read" (search for strings, etc.) the text that's entered by other users in this "chatroom". The problem I have is actually logging in to the chatroom since I have not found a way to duplicate keyboard strokes. If someone could point me in the right direction on tutorials about this or show me a sample program that does this I would really appreciate it. --grigri9 P.S. I am a first semester programming student at my high school and Python is the only language I know. From rnikaREMOVEnder at adelphia.net Thu Apr 22 00:37:44 2004 From: rnikaREMOVEnder at adelphia.net (Rob Nikander) Date: Wed, 21 Apr 2004 21:37:44 -0700 Subject: How to get the ip addresses of a nic In-Reply-To: <2e262238.0404211825.2f6231b@posting.google.com> References: <2e262238.0404211825.2f6231b@posting.google.com> Message-ID: Justin Dubs wrote: >>>>socket.gethostbyname(socket.gethostname()) > > '192.168.0.18' > > Justin Dubs That always gives me this: >>> import socket >>> socket.gethostbyname(socket.gethostname()) '127.0.0.1' From jcarlson at uci.edu Sat Apr 3 20:22:04 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Sat, 03 Apr 2004 17:22:04 -0800 Subject: recursive file editing In-Reply-To: References: Message-ID: > for thing in os.walk('mydir'): > file(thing,mode=r+) for thing in os.walk('mydir'): filehandle = file(thing, 'r+') - Josiah From richie at entrian.com Wed Apr 7 10:47:22 2004 From: richie at entrian.com (Richie Hindle) Date: Wed, 07 Apr 2004 15:47:22 +0100 Subject: painful debugging: techniques? In-Reply-To: <8ef9bea6.0404070621.342c3b5d@posting.google.com> References: <8ef9bea6.0404070621.342c3b5d@posting.google.com> Message-ID: <7l4870tl7cchahdfsqjjaflt4kik86btnc@4ax.com> [Hung Jung] > The question now is: how can we stop this from happening to other people? > [...] So far, I think Peter Otten's approach (search through the source > code) may be the most practical way. Make weakref.ref() check that its second argument is a callable? (I know, "patches welcome" 8-) -- Richie Hindle richie at entrian.com From has.temp2 at virgin.net Wed Apr 28 18:46:00 2004 From: has.temp2 at virgin.net (has) Date: 28 Apr 2004 15:46:00 -0700 Subject: What is good about Prothon? References: <108t2tlo06j8vb9@corp.supernews.com> Message-ID: <69cbbef2.0404281446.4e0ab52e@posting.google.com> "Mark Hahn" wrote in message news:... > I've got Has on one side of me who says that having prototype references > instead of copies makes it too much like Python and therefore it isn't > prototype-based Not so. I've been saying it's not a proto-OO language because proto-OO behaves according to a single tier model where all objects are equal, whereas Prothon, like class-based OO languages, follows a two-tier model where some objects (classes/"prototypes") are more equal than others ("object" objects). I may not know much about programming, but I've a pretty damn good eye on me and can well tell the difference between stuff that's genuinely simple and stuff that merely thinks it is. I know how high to set the bar and, unlike some "real" programmers who think "simplicity" is something you can get from slapping an extra abstraction layer on top of the current complexity, I'm not afraid to rip everything down and start right over again if something fails to reach it; and keep doing so till it does. (Something a fair few professionals have yet to learn, IMHO.) You've asked for input on Prothon and FWIW I've given it. And while it's no skin off my nose whether you want/need/like it or not, I'd rather you didn't make it sound like the above is the best argument I could muster as it's a little embarrassing. (Yeah, I realise that sifting the wheat of my posts from the plentiful chaff can take some work, but hey, nothing in life worth doing is easy...) From alan.gauld at btinternet.com Fri Apr 9 19:42:47 2004 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 10 Apr 2004 00:42:47 +0100 Subject: Simple Class Question - need clarity please References: Message-ID: <2tce701vv505395hcr6dqtvc8ot0fdmkrk@4ax.com> On Sat, 10 Apr 2004 00:03:07 +0100, "Stevie_mac" wrote: > What is wrong with this?... > > import win32con, win32ui > from pywin.mfc import dialog #, window > class Window: > def MakeDlgTemplate(self): ... > def DoModal(self): > mw = win32ui.CreateDialogIndirect( self.MakeDlgTemplate() ) > mw.DoModal() > > # file test.py # > import mywindow > class MyClass(mywindow.Window): > def Show(self): > self.DoModal() > > t = MyClass() > t.Show() > > . . . I get > NameError: global name 'MakeDlgTemplate' is not defined ??? Its a good idea to post the entire error traceback so we see the actual line of code the error refers to. This error usually means you accessed a name from a module without prefixing it with the module name. But so far as I can see you haven't done that here. > another 1 I managed to clear up was . . . > TypeError: Show() takes no arguments (1 given) > . . . until I added 'self' to the Show function ??? Yes, every method of a class must have a parameter that refers to the instance at call time, usually called self (or maybe "this" if you come from Java or C++) At runtime Python effectively calls class.method(instance) > I'm also struggling with other things like... > Where do I save .py files? Anywhere you like! I have a folder called Projects\Python where I keep mine :-) So long as Python knows where to find them - either by modifying the sys.path value (explicitly or via the registry setting) or the PYTHONPATH environment variable... > Will 'import' find my files where ever they are? Yes if one of the two locations above are set. HTH, Alan G. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld From opengeometry at yahoo.ca Wed Apr 21 15:21:08 2004 From: opengeometry at yahoo.ca (William Park) Date: 21 Apr 2004 19:21:08 GMT Subject: Time References: Message-ID: Jonas Galvez wrote: > If I have a tuple like this: > > (year, month, day, hour, minute) > > Is there a way to automatically generate a string like this? > > "YYYY-MM-DDTHH:MM:00" > > I remember seeing something about it somewhere... wanted to be sure. Hint: '%02d' % 4 -- William Park, Open Geometry Consulting, Linux solution/training/migration, Thin-client From junkmail at solumslekt.org Fri Apr 2 13:10:08 2004 From: junkmail at solumslekt.org (Leif B. Kristensen) Date: Fri, 02 Apr 2004 20:10:08 +0200 Subject: String concatenation References: <7xisgi24fm.fsf@ruckus.brouhaha.com> <406D27A7.6550A00B@alcyone.com> <406D2CD5.878EBD4E@alcyone.com> <406D2FA2.6E5118CC@alcyone.com> Message-ID: Erik Max Francis wrote: > Maybe it's grabbing tabs, or obscure unprintable whitespace you can't > see. Certainly what you're pasting in to these posts is intended, > whether or not you did that manually. The problem is recognised and confirmed. I posted a description of the situation on comp.windows.x.kde, and received essentially this answer: "you will notice that the "space" is an ASCII space (20 hex) in the working version and ASCII space + 128 (A0 hex) in the non-working version. Just because the display looks the same does not mean it is the same." regards, -- Leif Biberg Kristensen http://solumslekt.org/ Validare necesse est From address at is.invalid Fri Apr 2 12:32:08 2004 From: address at is.invalid (Bill) Date: Fri, 2 Apr 2004 09:32:08 -0800 Subject: ANNOUNCE: 'goto' for Python References: Message-ID: "Richie Hindle" wrote in message news:mailman.210.1080803438.20120.python-list at python.org... --snip-- > 'comefrom' example: letting cleanup code take control after an error. > > from goto import comefrom, label > def bigFunction(): > setUp() > if not doFirstTask(): > label .failed > if not doSecondTask(): > label .failed > if not doThirdTask(): > label .failed > > comefrom .failed > cleanUp() Hello, Can you explain to me why you need comefrom? Couldn't you replace "label.failed" with "goto cleanup"? Thanks. Louis From faheem at email.unc.edu Thu Apr 8 11:52:31 2004 From: faheem at email.unc.edu (Faheem Mitha) Date: Thu, 8 Apr 2004 11:52:31 -0400 (EDT) Subject: problems with compiling and loading C++ extension Message-ID: Dear People, I have been having an odd problem with compiling and loading a simple C++ extension to python (as a .so file in Linux). Unfortunately, I'll need to include my files in here so I apologize in advance for the length of this message. You can download also the files below from http://www.stat.unc.edu/students/faheem/python/python.tar.gz in case that is more convenient. This needs blitz++ and python's distutils and numarray to compile. When I try to load arrmod.so into python I get In [1]: import arrmod --------------------------------------------------------------------------- ImportError Traceback (most recent call last) /tmp/wc/corrmodel/ex/ ImportError: ./arrmod.so: undefined symbol: _Z11py_to_blitzIdLi2EEN5blitz5ArrayIT_XT0_EEEP13PyArrayObject If I move the py_to_blitz routine from conv.cc back into arrmod.cc, the error disappears, arrmod loads in python, and everything works correctly. I'm not sure what is going on here. Can someone enlighten me? At first I thought it might have to do with the need for C linkage, but I tried that, and it does not appear to be the case. I also got the following compilation warning, which I don't understand. I don't know if that is relevant. --------------------------------------------------------------------- gcc -pthread -fno-strict-aliasing -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -fPIC -I/usr/include/python2.3 -c conv.cc -o /tmp/temp.linux-i686-2.3/conv.o -Wall /usr/include/python2.3/Numeric/arrayobject.h:286: warning: `void**PyArray_API' defined but not used --------------------------------------------------------------------- Thanks in advance for any enlightenment. Faheem. ********************************************************************** Makefile ********************************************************************** arrmod.so: arrmod.cc common.hh conv.cc python setup.py build --build-base=/tmp --build-lib=. # may not do the right thing for everyone clean: rm arrmod.so rm -r /tmp/temp.linux-i686-2.3 ********************************************************************** ********************************************************************** setup.py ********************************************************************** from distutils.core import setup, Extension module4 = Extension('arrmod', sources = ['arrmod.cc','conv.cc'],libraries=["blitz","m"], extra_compile_args = ['-Wall']) setup (name = 'arrmod', version = '1.0', description = 'This module performs different operations on arrays', ext_modules = [module4] ) ********************************************************************** ********************************************************************** common.hh ********************************************************************** #include "Python.h" #include "Numeric/arrayobject.h" #include using namespace std; using namespace blitz; template static Array py_to_blitz(PyArrayObject* arr_obj); ********************************************************************** ********************************************************************** conv.cc ********************************************************************** #include "common.hh" // Convert a Numpy array to a blitz one, using the original's data (no // copy) template static Array py_to_blitz(PyArrayObject* arr_obj) { int T_size = sizeof(T); TinyVector shape(0); TinyVector strides(0); int *arr_dimensions = arr_obj->dimensions; int *arr_strides = arr_obj->strides; for (int i=0;i((T*) arr_obj->data,shape,strides,neverDeleteData); } ************************************************************************ ************************************************************************ arrmod.cc ************************************************************************ #include "common.hh" template static Array py_to_blitz(PyArrayObject* arr_obj); static PyObject * arrmod_elem(PyObject *self, PyObject *args); static PyMethodDef arrmod_methods[] = { {"elem", (PyCFunction)arrmod_elem, METH_VARARGS, "Returns the trace of a two-dimensional array.\n"}, {NULL, NULL, 0, NULL} }; PyMODINIT_FUNC initarrmod(void) { (void) Py_InitModule3("arrmod", arrmod_methods, "Returns the Trace of a two-dimensional array.\n"); import_array(); } static PyObject * arrmod_elem(PyObject *self, PyObject *args) { PyObject *input, *result; PyArrayObject *array; double el; int i, j; if (!PyArg_ParseTuple(args, "Oii", &input, &i, &j)) return NULL; array = (PyArrayObject *) PyArray_ContiguousFromObject(input, PyArray_DOUBLE, 2, 2); if (array == NULL) return NULL; Array arr = py_to_blitz(array); el = arr(i,j); result = Py_BuildValue("d",el); return result; } ******************************************************************************** From fredrik at pythonware.com Tue Apr 20 09:31:03 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 20 Apr 2004 15:31:03 +0200 Subject: Good Python Tk overview References: Message-ID: "News User" wrote: > I'm comming from the background of being primarily a data processing > programmer (Python) and I'd like to do some GUI stuff for a comercial > project but I have quite a bit of time, nothing too complex but it has > to work on Windows98+ OSX and Solaris so I was thinking Tkinter. I was > wondering if there were some sites with a good overview of the whole > Python +Tk shpeal, I've got some code examples and "Programming Python > 2nd Edition" but that's more of a learn by example, rather than an > overview of concepts. Anyone have a good recommendation? start here: http://www.python.org/topics/tkinter/doc.html From smallbee at rediffmail.com Tue Apr 6 03:43:56 2004 From: smallbee at rediffmail.com (Somesh Bartakkay) Date: 6 Apr 2004 00:43:56 -0700 Subject: more Slow - gan ! Message-ID: <8f198e47.0404052343.4c5e4d77@posting.google.com> More Creativity evry Lines, thats why Python Shines ! From nospam at nospam.com Wed Apr 28 10:12:57 2004 From: nospam at nospam.com (Mark) Date: Wed, 28 Apr 2004 14:12:57 GMT Subject: A python telnet entry level question References: Message-ID: "Andrew Jones" wrote in message news:c67vo4$go4gt$1 at fido.engr.sgi.com... > It might be getting stuck on the Password part. > > Try this: > > tn.read_until("Password: ", 1) > > > Ethereal can be very helpful. Use it to see what is happening on the > wire. It has a "follow TCP stream" function. Obviously this will not > work for telneting to localhost so you will need to telnet to a remote host. I just discovered telnetlib yesterday and found "set_debuglevel" to be very useful to figure out what to read_until. -Mark > > Good luck. > Andy > > Jinming Xu wrote: > > Hello Everyone, > > > > I am trying to write a python script to telnet to a server and then do > > something there. As the first step, I practiced the python example in > > Lib Reference 11.13.2. But I am finding the script stops after I > > supplied the password. Does anyone know why? > > > > > > Thanks in advance! > > > > Jinming Xu > > > > PS: Here is the script: > > > > import getpass > > import sys > > import telnetlib > > > > HOST = "localhost" > > user = raw_input("Enter your remote account: ") > > password = getpass.getpass() > > > > tn = telnetlib.Telnet(HOST) > > > > tn.read_until("login: ") > > tn.write(user + "\n") > > if password: > > tn.read_until("Password: ") > > tn.write(password + "\n") > > > > tn.write("ls\n") > > tn.write("exit\n") > > > > print tn.read_all() > > > > _________________________________________________________________ > > MSN Toolbar provides one-click access to Hotmail from any Web page ? > > FREE download! http://toolbar.msn.com/go/onm00200413ave/direct/01/ > > > > > From michele.simionato at poste.it Sat Apr 3 03:03:17 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 3 Apr 2004 00:03:17 -0800 Subject: Simple text markup (-> HTML) References: Message-ID: <95aa1afa.0404030003.2b5b1b1f@posting.google.com> Jacek Generowicz wrote in message news:... I write everything in rst format and then convert to HTML,Latex,PS, PDF, etc. For what concerns the documentation, I write snippets and examples inside it, then I execute the text file using (a minor hack to) doctest and I get (additional) tests for free. Finally, I write the documentation (call it implementation proposal if you wish) before writing the actual code, so I get Documentation Driven Development ;) Way cool: it is something between literate programming and TDD. Most importantly it works. I have yet to implement the second step: the idea is to convert the documentation in HTML, put it on the Web and let the customer run the tests with a click on the browser as soon as he reads the documentation (or proposal of implementation) and see if he/she likes it. It is not difficult to implement though. I think you get the picture. doctest is still largely unexplored but it has enourmous potentiality in terms of easy of use and convenience. Think only to the fact that you get always updated documentation by definition. Michele Simionato From jjl at pobox.com Tue Apr 6 16:43:58 2004 From: jjl at pobox.com (John J. Lee) Date: 06 Apr 2004 21:43:58 +0100 Subject: shutil.move, permission denied, why ? References: Message-ID: <87wu4s25wx.fsf@pobox.com> "St?phane Ninin" writes: [...] > (I have removed most of the logic of the code here, so I am not sure > it's going to be helpful) [...] Post a short snippet of code that runs and demonstrates the problem. John From mlh at furu.idi.ntnu.no Wed Apr 14 16:43:16 2004 From: mlh at furu.idi.ntnu.no (Magnus Lie Hetland) Date: Wed, 14 Apr 2004 20:43:16 +0000 (UTC) Subject: ANN: Atox 0.4 released Message-ID: What is it? =========== Atox is a framework for automated markup. With it one can quite easily write custom scripts for converting plain text into XML in any way one wishes. Atox is normally used as a command-line script, using a simple XML language to specify the desired transformation from text to markup, but it is also possible to build custom parsers using the Atox library. The name (short for ASCII-to-XML) is inspired by such UNIX tools and system functions as atops and atoi. What can it do? =============== The examples in the distribution demonstrate how you can use Atox to: - Mark up a (relatively simple) technical document (the Atox manual); - Mark up code blocks only through indentation; - Nest lists through indentation - Discern between different indentation "shapes" (e.g. a block quote versus a description list item); - Transform simple LaTeX into XML; - Add XML "syntax highlighting" to Python code; - Mark up screenplays or stageplays, largely based on indentation; - Mark up simple fictional prose; - Mark up simple tables. What's new in 0.4? ================== These are the changes I've made: - Made the error handling slightly more user-friendly. - Added some basic improvements to the command-line interface (the '-e', '-f' and '-o' switches, as well the ability to use multiple input files or standard input). Note that the new calling convention is incompatible with the previous version, in that the format file is no longer supplied as an argument. - Normalized newline-handling. - Added the utility tags 'ax:block', 'ax:sob' (start-of-block) and 'ax:eob' (end-of-block). - Fixed an important bug in the indentation code, which affected 'ax:indented'. - Made empty sequences legal. - Added support for config files. Where can I get it? =================== Atox is hosted at SourceForge (http://atox.sf.net) and the current release (0.4) is available for download via its project page (http://sf.net/projects/atox). The Small Print =============== Atox is released under the MIT license. It comes with no warranty of any kind. Also, even though the current version works well, and the project is currently (as per early 2004) being actively developed, there is no guarantee of continued support. What you see is what you get. -- Magnus Lie Hetland "Oppression and harassment is a small price to pay http://hetland.org to live in the land of the free." -- C. M. Burns From Mike at DeleteThis.Geary.com Wed Apr 7 00:49:58 2004 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Tue, 6 Apr 2004 21:49:58 -0700 Subject: Cookies References: <40737a05$0$20085$afc38c87@news.optusnet.com.au> Message-ID: <107723mjkvkee9e@corp.supernews.com> > Trying to write a python script that does the same thing my browser > does when posting a form.(cgi) > > All works except for this. My browser has a cookie which it also sends, > and the server insists on getting. > > So how can I replicate this under python? I've looked at cookie > module but can't see how to use it to achieve this. Please help. That's right, the cookie module is for use on a server, not a client. Try the ClientCookie module: http://wwwsearch.sourceforge.net/ClientCookie/ I've used this successfully to do client-side things such as logging into Yahoo as a browser would. -Mike From james at ractive.ch Mon Apr 12 09:27:02 2004 From: james at ractive.ch (Jean-Pierre Bergamin) Date: Mon, 12 Apr 2004 15:27:02 +0200 Subject: How to get value of parent class Message-ID: Hello I have the following class structure: class MyServer: x= 0 class MyHandler(SocketServer.StreamRequestHandler): def handle(self): if x: # <---- How to get the X from the parent class? # Or how to pass a value to this class anyway? do_something() else: do_something_else() def start_server(self): s = SocketServer.TCPServer(('', 1234), self.MyHandler) s.server_forevert() server = MyServer server.x = 10 server.start_server() How is it possible to get the value of x from the class MyServer within the MyHandler class? The object of self.MyHandler is instantiated everytine the SocketServer.TCPServer calls handle, so it's not possible to create an instance of MyHandler an pass it the value. Or ist there any other possibility to pass the class MyHandler some values? Thanks in advance. James From mcfletch at rogers.com Wed Apr 14 11:33:21 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Wed, 14 Apr 2004 11:33:21 -0400 Subject: Difficulty Finding Python Developers In-Reply-To: <65cbc3dd.0404140641.3501fde8@posting.google.com> References: <65cbc3dd.0404140641.3501fde8@posting.google.com> Message-ID: <407D59C1.1090303@rogers.com> Paul Morrow wrote: >We've worked hard to convince our company to migrate our core >applications to Python, and now we're looking for a Python developer >in Atlanta to handle a short-term (approx. 3 month) project. But our >initial searches have been fairly unsuccessful. We haven't actually >posted a job on Monster, but we have been talking with various >headhunters in our area and they don't have many resumes that show >Python experience. An so now, of course, mgt is wondering whether >selecting Python was a mistake. > >As anyone had a similar experience? Suggestions? > > Suggestions: * Post on the python.org job-board, though honestly, I don't know how many of us contractor types actually check it regularly, since most postings there are for jobs as distinct from short-term contracts * Post here. Noisy is often a good strategy in advertising * Look up any Python Open Source project your respect and ask if the developer is available for contract work (they often are) * Convert any senior programmer to a Pythonista, approximately 2-3 weeks training * If looking for junior programmers (doesn't seem likely in this particular case, but just in case), advertise at a university, such as the University of Waterloo (in Canada), which has a lot of Python activity either for graduates or co-op students (caveat, I'm an alumni, so UofW is obviously not all it's cracked up to be ;) ) * Import from Canada, we've got dozens of Python coders in Toronto alone, of course, then you may have visa issues (particularly for such a short stint) * There are a number of firms around and about (ours (Vex) included) which offer contract Python programmers, I think Engenuity is also up for contract work these days... both of those are Toronto-based, so likely visa issues again. I think Michael Bernstein would likely be open to contract work, and he's down in the states and willing to travel, think he mostly focuses of web-site/app development. * There's at least one Python-specific job board the URL for which I haven't been able to put my finger on at the moment, owner of that will probably pipe up with the name * I think there's a Python/Zope group in the research triangle area, they might very well have (moderately (never took US geography in school, so my recollection of relative distance may be off)) local people interested in contract work Good luck, Mike _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From alejandro.sanchez at municipia.com Thu Apr 1 08:09:21 2004 From: alejandro.sanchez at municipia.com (Alejandro =?iso-8859-1?b?U+FuY2hleg==?= Acosta) Date: Thu, 1 Apr 2004 15:09:21 +0200 Subject: Blocking mouse/keyboard input. Message-ID: <1080824961.406c1481296c1@www.gobernalia.com> Hello, I have done a little aplication that does a remote connection to other machine and opens a vncclient to connect to the VNC in other machine (it's just for a network monitorization). Now I need that I can enable/disable the input of the keyboard/mouse both windows and Linux, any good idea about how to block the keyboard/mouse in python? any ioctl and win dll to do it? Thanks in advance, Alejandro. From grante at visi.com Thu Apr 29 12:46:08 2004 From: grante at visi.com (Grant Edwards) Date: 29 Apr 2004 16:46:08 GMT Subject: Don't understand wxPython ids References: <408ed938$0$17263$a1866201@newsreader.visi.com> <408f3061$0$17258$a1866201@newsreader.visi.com> <408fb665$0$17264$a1866201@newsreader.visi.com> Message-ID: <40913150$0$17257$a1866201@newsreader.visi.com> On 2004-04-28, Greg Krohn wrote: > Here we go. Use the attached module like this: > > #yourmodule.py > import wx > from event_kwargs import * Hmm. I guess it's time to upgrade to 2.5. -- Grant Edwards grante Yow! I'm in a twist at contest!! I'm in a visi.com bathtub! It's on Mars!! I'm in tip-top condition! From andrew-pythonlist at puzzling.org Wed Apr 21 20:27:22 2004 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Thu, 22 Apr 2004 10:27:22 +1000 Subject: Generator inside a class prevent __del__ ?? In-Reply-To: <4087031A.AEB67C72@free.fr> References: <4085BA96.651D2E4A@free.fr> <40866ECD.A45758B9@free.fr> <4087031A.AEB67C72@free.fr> Message-ID: <20040422002722.GA1929@frobozz> On Thu, Apr 22, 2004 at 01:26:18AM +0200, Emmanuel wrote: > > > Andrew Bennetts a ?crit : > > > On Wed, Apr 21, 2004 at 02:53:33PM +0200, Emmanuel wrote: > > > > > > Trouble is, I _would_ like not to care about the lifetime of the object, and I > > > don't know where it will be destroyed. > > > > Then don't use __del__. Python can and will automatically collect cycles > > when the objects *don't* define __del__ methods. > > > > Out of curiousity, why are you defining __del__ anyway? > > > > -Andrew. > > I don't want to use __del__, but I suspected I had an issue with the destruction of > my objects, and used a log in __del__ to monitor the destruction. Except that __del__ affects how they are destructed :) Weakrefs are probably a better choice for this, as they don't interfere with the lifecycle of the object you're interested in, unlike __del__. > But defining __del__ has also a lot of valuable utilisation, or so I think... It's only very very rarely useful, in my experience. Again, weakrefs are probably more useful for what you have in mind. -Andrew. From molitar at hotmail.com Thu Apr 15 14:11:41 2004 From: molitar at hotmail.com (molitar at hotmail.com) Date: Thu, 15 Apr 2004 18:11:41 GMT Subject: Help with combobox being invisible after upgrading python Message-ID: I have a problem with combobox not showing after updating to latest Python. Part of code below that worked fine until I updated. The combobox is there and you can click on the invisible combobox and see the dropdown but the combobox itself is invisible. import wx from wxPython.wx import * from wxPython import * from webbrowser import open_new from threading import Thread from filemanager import * from os import path from os.path import join from variable import * class GlobalUploadDialog(wxDialog): def __init__(self, parent, ID, title, pos=wxDefaultPosition, size=wxDefaultSize, style=wxDEFAULT_DIALOG_STYLE): pre = wxPreDialog() pre.Create(parent, ID, title, pos, size, style) self.this = pre.this self.parent = parent # GUI dialog for Global upload setting ######################################## loc_maxupload = self.parent.abcparams['maxupload'] loc_maxuploadrate = self.parent.abcparams['maxuploadrate'] loc_maxseeduploadrate = self.parent.abcparams['maxseeduploadrate'] loc_uploadopt = self.parent.abcparams['uploadoption'] loc_uploadtimeh = self.parent.abcparams['uploadtimeh'] loc_uploadtimem = self.parent.abcparams['uploadtimem'] loc_uploadratio = self.parent.abcparams['uploadratio'] ID_COMBOBOX_HTIME = wxNewId() ID_COMBOBOX_MTIME = wxNewId() ID_COMBOBOX_RATIO = wxNewId() self.cbhtime = wx.ComboBox(self,ID_COMBOBOX_HTIME, loc_uploadtimeh, wx.Point(150, 149), wx.Size(37, -1), htimeval, wx.CB_DROPDOWN|wx.CB_READONLY) self.cbmtime = wxComboBox(self, ID_COMBOBOX_MTIME, loc_uploadtimem, wxPoint(198, 149), wxSize(37, -1), mtimeval, wxCB_DROPDOWN|wxCB_READONLY) self.cbhtime.SetValue(loc_uploadtimeh) self.cbmtime.SetValue(loc_uploadtimem) ratioval = ['50', '75', '100', '125', '150','175','200','300', '400', '500'] self.cbratio = wxComboBox(self, ID_COMBOBOX_RATIO, loc_uploadratio, wxPoint(150, 173), wxSize(45, -1), ratioval, wxCB_DROPDOWN|wxCB_READONLY) self.cbratio.SetValue(loc_uploadratio) Before updating to the latest version the comboboxes showed up fine. From chris at simplistix.co.uk Sat Apr 3 12:02:43 2004 From: chris at simplistix.co.uk (Chris Withers) Date: Sat, 03 Apr 2004 18:02:43 +0100 Subject: Weird Python 2.3 subclassing thing with _mysql and MySQLdb In-Reply-To: <406EDE94.9000701@simplistix.co.uk> References: <406E9DE4.2000604@simplistix.co.uk> <406EDE94.9000701@simplistix.co.uk> Message-ID: <406EEE33.9050901@simplistix.co.uk> (cross posting to python list in case someone there can explain this bizarre behaviour...) Python 2.3.3 (#51, Dec 18 2003, 20:22:39) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import _mysql ...define kwargs... >>> c = _mysql.connection(**kwargs) >>> c <_mysql.connection open to 'localhost' at 7b8858> >>> c.server_capabilities Traceback (most recent call last): File "", line 1, in ? AttributeError: server_capabilities ...hmmm, okay, so no server_capabilties attribute... >>> class test(_mysql.connection): pass ... >>> c = test(**kwargs) >>> c <_mysql.connection open to 'localhost' at 82c2a0> >>> c.server_capabilities 8236 ...BWAGGGHH?! Chris -- Simplistix - Content Management, Zope & Python Consulting - http://www.simplistix.co.uk From hungjunglu at yahoo.com Sat Apr 17 11:58:27 2004 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 17 Apr 2004 08:58:27 -0700 Subject: AOP use cases References: <84fc4588.0404140106.3fa0c55@posting.google.com> <0pydnSB4WYuieuLdRVn-hQ@powergate.ca> Message-ID: <8ef9bea6.0404170758.49a69f43@posting.google.com> Shane Hathaway wrote in message news:... > > This discussion makes me wonder if Zope has been dabbling in AOP > concepts for years without knowing it. In addition to ZODB, Zope lets > you declare permissions for methods, wraps objects with proxies to give > them an environment, and inspects method signatures to make them > directly callable by URL. The AOP folks talk about very similar things. > Surely there is some common thread. You are right on there. :) Zope has plenty of places where it could use AOP or is using AOP-like techniques. I remember the days when I was using SiteAccess. SiteAcess is a perfect example of AOP. In that sense, Apache's ModRewrite is another prefect example. ZODB is transactional. But Zope < 3.0 is not enterprise-transactional a la MTS or EJB/J2EE. I am not experienced in the details of implementation of transactional architecture, but I would guess part of the difficulty in converting an existing application into a fully-transactional application is because you have to modify code all over too many places. This is the type of problems that AOP addresses. regards, Hung Jung From bror.johansson at saabtech.se Thu Apr 29 03:00:04 2004 From: bror.johansson at saabtech.se (Bror Johansson) Date: Thu, 29 Apr 2004 09:00:04 +0200 Subject: Arachno Python IDE References: Message-ID: "Bror Johansson" wrote in message news:c6q8tb$6q3$1 at newstree.wise.edt.ericsson.se... > I can't remember having seen anything in this forum about Arachno Python > IDE. (http://www.python-ide.com/arachno_python.php) > > Anyone tried it? Impressions? > > /BJ > > Follow up to myself. I just noticed that the trial version was for Ruby only. From lbates at swamisoft.com Tue Apr 13 10:07:19 2004 From: lbates at swamisoft.com (Larry Bates) Date: Tue, 13 Apr 2004 09:07:19 -0500 Subject: how to break tuple to separate variables References: Message-ID: Take a look at the built-in apply function: apply(datetime.date, date2tuple('2004-11-03')) Larry Bates Syscon, Inc. "Stano Paska" wrote in message news:mailman.572.1081846104.20120.python-list at python.org... > Hi. > > I need pass variables to function like tuple, but function accepts > separate variables. > > Is there some elegant solution? > > My example: > > # ------------------------------- > import datetime > > def date2tuple(aaa): > try: > y = int(aaa[:4]) > m = int(aaa[5:7]) > d = int(aaa[8:10]) > except: > y = m = d = 0 > return (y, m, d) > > # i need some like this > bbb = datetime.date(date2tuple('2004-11-03')) > > # but date requires > bbb = datetime.date(2004, 11, 03) > > # ------------------------------- > > Thanks. > > Stano Paska > > > From jepler at unpythonic.net Wed Apr 21 08:33:21 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 21 Apr 2004 07:33:21 -0500 Subject: Passing argument to setsockopt(socket.SOL_SOCKET, IN.SO_BINDTODEVICE, intr) In-Reply-To: <40866792$0$31708$fa0fcedb@lovejoy.zen.co.uk> References: <408640b7$0$31671$fa0fcedb@lovejoy.zen.co.uk> <40866792$0$31708$fa0fcedb@lovejoy.zen.co.uk> Message-ID: <20040421123320.GB9864@unpythonic.net> On Wed, Apr 21, 2004 at 12:22:41PM +0000, Richard Taylor wrote: > The answer is: > > s.setsockopt(socket.SOL_SOCKET,IN.SO_BINDTODEVICE,struct.pack("%ds" % > (len("eth0")+1,), "eth0")) > Richard Taylor wrote: Maybe this is simpler: #dev = "eth0" s.setsockopt(..., dev + '\0') I think it has the same effect as your code, but it is a little clearer to me that the setsockopt call needs a zero-terminated C string as its argument. Jeff From shane at zope.com Sat Apr 17 01:56:03 2004 From: shane at zope.com (Shane Hathaway) Date: Sat, 17 Apr 2004 01:56:03 -0400 Subject: AOP use cases In-Reply-To: References: <84fc4588.0404140106.3fa0c55@posting.google.com> <0pydnSB4WYuieuLdRVn-hQ@powergate.ca> Message-ID: <4080C6F3.5020309@zope.com> On 04/16/04 11:22, Daniel Dittmar wrote: > - persistence > - transactions: pass a transaction context through a call hierarchy spanning > several objects and let the transaction fail if certain methods fail Interesting you should mention these, since ZODB provides transactional, transparent object persistence. > It may very well be that these can be implemented in current Python, but > this only means that Python already has good support for AOP. This discussion makes me wonder if Zope has been dabbling in AOP concepts for years without knowing it. In addition to ZODB, Zope lets you declare permissions for methods, wraps objects with proxies to give them an environment, and inspects method signatures to make them directly callable by URL. The AOP folks talk about very similar things. Surely there is some common thread. Shane From jack at performancedrivers.com Fri Apr 30 13:59:44 2004 From: jack at performancedrivers.com (Jack Diederich) Date: Fri, 30 Apr 2004 13:59:44 -0400 Subject: Unification of Methods and Functions In-Reply-To: References: Message-ID: <20040430175944.GA22080@performancedrivers.com> On Fri, Apr 30, 2004 at 09:47:05AM -0700, David MacQuigg wrote: > I'm not getting any feedback on the most important benefit in my > proposed "Ideas for Python 3" thread - the unification of methods and > functions. Perhaps it was buried among too many other less important > changes, so in this thread I would like to focus on that issue alone. > ======= Syntax Examples ============= > > ## Proposed Syntax: > class Cat(Feline): > numCats = 0 > def __init__( n = "unknown", s = "Meow" ): > Feline.__init__() > Cat.numCats += 1 > .name = n # Set instance variables. > .sound = s > def show(): # Define a "static method". > Feline.show() > print " Cats:", Cat.numCats > def talk(): > print "My name is ...", .name > print "I am a %s from %s" % (.genus, .home) > Mammal.talk() # Call an unbound function. > print __self__ ### Diagnostic check. > > cat1 = Cat() # Create instance. > bf = cat1.talk # Make a bound function. > > > ## Equivalent Python: > class Cat(Feline): > numCats = 0 > def __init__(self, n = "unknown", s = "Meow" ): > Feline.__init__(self) > Cat.numCats += 1 > self.name = n > self.sound = s > def show(): > Feline.show() > print " Cats:", Cat.numCats > show = staticmethod(show) > def talk(self): > print "My name is ...", self.name > print "I am a %s from %s" % (self.genus, self.home) > Mammal.talk(self) > print self > > cat1 = Cat() # Create instance. > bf = cat1.talk # Make a bound function. > > ========= End of Examples ======= > Explicit is better than implicit. or Magic BAAAAAAAAD [Phil Hartman as Frankenstein] I suggest you check out perl to see mixing instance/class/static methods in practice. Becuase perl is weakly typed this 'makes sense' in perl, even if it causes problems[1]. What happens in practice is bad, people write functions that can be used in two or more ways. This makes type checking hard, and makes code unreadable. Functions frequently do slightly different things when called one way or another. For a python version you could do type checking on the function by doing static analysis of the code, but that would be unpythonic. I like it when a static function breaks badly when some yahoo tries to use self -- it breaks early and loudly. Your way might only break on a certain code path that tries to access '.name' and turns the method from static to instance. If you re-added staticmethod/classmethod to clear up the distinction then the above example just becomes a new syntax for implicit 'self'. A version of the ':vars: expression' lambda replacement gets suggested every so often (and that exact syntax once by me). It ain't going to happnen, labmda is more likely to be dropped than enhanced. -jackdied [1] standard perl interview question, what is the difference between these calls? All of these end up calling meow() with one argument, but they all behave differently - sometimes very subtly. $ob = new Cat; $ob->meow(); # intsance method Cat->meow(); # class method Cat::meow($ob); # static method with first argument a Cat instance From fumanchu at amor.org Wed Apr 21 03:10:29 2004 From: fumanchu at amor.org (Robert Brewer) Date: Wed, 21 Apr 2004 00:10:29 -0700 Subject: No built-in swap function? Message-ID: Simon Wittber wrote: > import time > def tupleSwap(a,b):a,b = b,a > def tempSwap(a,b): > t = a > a = b > b = t > def xorSwap(a,b): > a ^= b > b ^= a > a ^= b > 1 million tuple swaps in 1.78324228359 seconds. > 1 million temp swaps in 1.53032270861 seconds. > 1 million xor swaps in 2.17933312753 seconds. > > Interestingly, using psyco.full() produced these results: > 1 million tuple swaps in 3.06005958858 seconds. > 1 million temp swaps in 3.01621882111 seconds. > 1 million xor swaps in 3.03376686143 seconds. > > The xorswap function is not much use for anything other than numbers, > however, I would have expected a psyco'ed xorSwap to much faster than > the alternatives! Well, the xorswap does the same work as the tempswap, plus the xoring: >>> def ts(a, b): ... t = a ... a = b ... b = t ... >>> dis.dis(ts) 2 0 LOAD_FAST 0 (a) 3 STORE_FAST 2 (t) 3 6 LOAD_FAST 1 (b) 9 STORE_FAST 0 (a) 4 12 LOAD_FAST 2 (t) 15 STORE_FAST 1 (b) 18 LOAD_CONST 0 (None) 21 RETURN_VALUE That's 3 LOAD_FAST, and 3 STORE_FAST operations. >>> def xs(a, b): ... a ^= b ... b ^= a ... a ^= b ... >>> dis.dis(xs) 2 0 LOAD_FAST 0 (a) 3 LOAD_FAST 1 (b) 6 INPLACE_XOR 7 STORE_FAST 0 (a) 3 10 LOAD_FAST 1 (b) 13 LOAD_FAST 0 (a) 16 INPLACE_XOR 17 STORE_FAST 1 (b) 4 20 LOAD_FAST 0 (a) 23 LOAD_FAST 1 (b) 26 INPLACE_XOR 27 STORE_FAST 0 (a) 30 LOAD_CONST 0 (None) 33 RETURN_VALUE That's 6 LOAD_FAST, and 3 STORE_FAST operations, plus XOR'ing. Robert Brewer MIS Amor Ministries fumanchu at amor.org From des.small at bristol.ac.uk Tue Apr 20 10:15:39 2004 From: des.small at bristol.ac.uk (Des Small) Date: Tue, 20 Apr 2004 14:15:39 GMT Subject: Dollar sign ($) on foriegn keyboards? (prothon) References: Message-ID: "Mark Hahn" writes: > Can people from outside the U.S. tell me if typing the dollar sign often > would be a problem in writing code? Is it available and somewhat easy to > type on international keyboards? The dollar sign is used in extensively in Unix shells and Perl, which are both widely used (Perl also on Windows). It seems unlikely that any keyboard with a latin alphabet wouldn't include it. Des types in a wide variety of dollar-equipped iso encodings. -- "[T]he structural trend in linguistics which took root with the International Congresses of the twenties and early thirties [...] had close and effective connections with phenomenology in its Husserlian and Hegelian versions." -- Roman Jakobson From paul at prescod.net Sun Apr 11 11:38:04 2004 From: paul at prescod.net (Paul Prescod) Date: Sun, 11 Apr 2004 08:38:04 -0700 Subject: Python is the best and most popular general purpose scripting language; the universal scripting language In-Reply-To: <20040410232500.GB17123@vulcan.cprogrammer.org> References: <20040410225019.GA16891@vulcan.cprogrammer.org> <40788033.3030209@prescod.net> <20040410232500.GB17123@vulcan.cprogrammer.org> Message-ID: <4079665C.6010006@prescod.net> Jonathan Daugherty wrote: > # So which is Lisp? Prolog? Smalltalk? ML? > > I didn't claim that it necessarily holds for every language. :) But you didn't really answer the question. Is Lisp a scripting language or not? If not, why? > # A scripting language is a language that makes scripting (gluing together > # components) easy. > > You're defining it in terms of itself; what is scripting? The use of > scripting languages, or the accomplishment of tasks quickly and > easily? Some would argue the latter can be done with programming > languages. Scripting is the gluing together of components potentially written in a variety of languages. > # A programming language is a language that makes programming (including > # the creation of components) easy. > > By this metric many languages are both, since the definition is > subjective. Yes. The term is both historical and subjective. If you try to draw any line in the sand you will find outliers like Lisp and even Java (which is bytecode interpreted just as Python is) will cause you problems. There are compilers for Python and interpreters for C. Paul Prescod From jcarlson at uci.edu Wed Apr 21 11:36:01 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Wed, 21 Apr 2004 08:36:01 -0700 Subject: No built-in swap function? In-Reply-To: References: Message-ID: >>> The xorswap function is not much use for anything other than numbers, >>> however, I would have expected a psyco'ed xorSwap to much faster than >>> the alternatives! >> >> >> >> You are testing function calling overhead. Try the below... >> >> import time >> >> def tupleswap(a,b): >> t = time.time() >> for i in xrange(100000): >> a,b=b,a;a,b=b,a;a,b=b,a;a,b=b,a;a,b=b,a; >> a,b=b,a;a,b=b,a;a,b=b,a;a,b=b,a;a,b=b,a; >> print "1 million tuple swaps in", time.time()-t, "seconds." > > > AFAIK, this seems to be 10 thousand instead of 1 million (and 10 mil > instead of 100 mil for > the psyco test). You need to check your eyes. In tupleswap, the xrange is 100,000, and the body of the for loop contains 10 tuple swaps, where 'a,b=b,a;' is one tuple swap. Similarly for tempswap, the xrange is 100,000, and the body of the for loop contains 10 'swaps using a temporary variable', where 't=a;a=b;b=a;' is considered a single 'swap' of the a and b values, using 't' as a temporary value. This is also equivalent to the xor swap, where 'a^=b;b^=a;a^=b;' is a single xor swap, 10 in the body, etc. It should be trivial (by simple multiplication) that each conceptual swap is done 1 million times. For the big psyco test, I used a bigger xrange (100 times bigger in fact), which puts it at 100 million. Again, check your eyes. - Josiah From jason at tishler.net Fri Apr 30 16:54:47 2004 From: jason at tishler.net (Jason Tishler) Date: Fri, 30 Apr 2004 16:54:47 -0400 Subject: Python Image Library (PIL) build error on Cygwin In-Reply-To: <4092AB1C.8050101@holdenweb.com> References: <40928190.5060004@holdenweb.com> <20040430193031.GA1728@tishler.net> <4092AB1C.8050101@holdenweb.com> Message-ID: <20040430205447.GA1620@tishler.net> Steve, On Fri, Apr 30, 2004 at 03:38:04PM -0400, Steve Holden wrote: > Unfortunately that doesn't seem to help: The following may be helpful: http://www.cygwin.com/ml/cygwin/2003-06/msg01121.html 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 sdahlbac at abo.fi Fri Apr 23 03:25:35 2004 From: sdahlbac at abo.fi (Simon Dahlbacka) Date: 23 Apr 2004 00:25:35 -0700 Subject: from vh3 import virthost / AddVirtDomain / Ensim / Apache References: <2a9bf4b4.0404221415.4313d267@posting.google.com> Message-ID: arch at spyre.net (A. Y. Chen) wrote in message news:<2a9bf4b4.0404221415.4313d267 at posting.google.com>... > Hi, I'm trying to do the same thing and getting the exact same problem > as you. Have you had any luck? Part of the difficulty is that the > files virthost.py and virtutil.py are probably compiles (in .pyc > form), and not located in those directories shown in the trace. > However, I still get the same error after I chmod those files. > > > > "Dan Messenger" wrote in message news:... > > Hi, > > > > I'm new to python, and am trying to use some premade scripts on RedHat 7, > > but its giving me errors. > > > > The scripts are part of the Ensim hosting software, and when I run the > > command "AddVirtDomain" from a root shell, it works fine. > > > > However when I call it from my php page, and thus running under the apache > > user, I get the following error: > > > > Traceback (most recent call last): > > File "/usr/local/bin/AddVirtDomain", line 26, in ? > > from vh3 import virthost > > File "virtualhosting/virthost.py", line 46, in ? > > File > > "/home/build/qa/webppliance/3.1.11/2/lwp/vaishali2/WebGui/base/services/vh3/ > > virtualhosting/virtutil.py", line 14, in ? > > ImportError: No module named logging ..are you sure that php is running the same version of python as you from the command line. the logging module is a standard one, BUT it is only available in python >= 2.3 /Simon From project2501 at project2501.cor Thu Apr 8 04:21:44 2004 From: project2501 at project2501.cor (project2501) Date: Thu, 08 Apr 2004 09:21:44 +0100 Subject: python thread scheduler? References: Message-ID: at the bottom is a reply i got on the comp.prgramming.threads group... it sufggests there is no programmatic way to improve client request rate ona uni-processor machine... do you agree? i think i agree with the person suggesting the only solutionis more horsepower. will twisted help even after this consideration? i had a look at twisted a while back (re: asyncore) and it seemed overly complex... On Wed, 07 Apr 2004 16:20:19 +0000, exarkun wrote: > utilizes a global lock which prevents more than one Python thread from running at any particular time. You will not see performance scale well with large numbers of threads (indeed, performance will probably be worse). Subject: Re: threads not switching fast enough one a 1-cpu system? From: steve at nospam.Watt.COM (Steve Watt) Newsgroups: comp.programming.threads Date: Wed, 7 Apr 2004 19:31:31 GMT In article , project2501 wrote: >i'm trying to becnhmark a server software. simply throwing requests at it >sequentially, however small the interval, is not stressing the server. That means your server is able to serve whatever you're using as a test client. Probably good news. >forking() children to throw requests quickly fills up the memory and swap >until the client machine breaks. Why do you think making more processes will make more requests per unit time? >threading (using python and also stackless python for now) lets me have >plenty of threads (i've tried up to 100). however my responce time graphs >are flat (although more threads means higher flat graph)... Why do you think making more threads will make more requests per unit time? >... which indicates the that the bottleneck being measured is the thread >swicthing... and that not enough threads are actually running "parallel" >enough. No, it indicates that it takes no longer to service a request than it does to generate it. If you've got one client machine and one server machine, your server is probably faster than your client, or your requests are easy for the server. You need more client horsepower. It is not uncommon, when doing big load testing, to use a dozen or more machines against a single server to really exercise the overload behavior. Creating threads or processes does not create computing power. In fact, it ALWAYS* reduces the amount of CPU available to user code, because of the increased state maintenance. So you need to procure more CPU cycles from somewhere, or make requests that take the server longer to complete. * OK, SMP machines are allowed a thread/process per CPU. -- Steve Watt KD6GGD PP-ASEL-IA ICBM: 121W 56' 57.8" / 37N 20' 14.9" Internet: steve @ Watt.COM Whois: SW32 Free time? There's no such thing. It just comes in varying prices... From mwilson at the-wire.com Tue Apr 13 12:47:34 2004 From: mwilson at the-wire.com (Mel Wilson) Date: Tue, 13 Apr 2004 12:47:34 -0400 Subject: Random Numbers and a thought References: <107m6f0t4i0gnff@corp.supernews.com> <107m8qvphrjd303@corp.supernews.com> Message-ID: In article <107m8qvphrjd303 at corp.supernews.com>, "A Evans" wrote: >Basically I would like to create an application that takes a series of >random numbers generated by a computer and searches for the pattern inside >those numbers [ ... ] >I guess if the numbers were between say 1 and 1000 it would take 1000 inputs >to understand the pattern if not more I would like to solve it before that The canonical reference is Donald E. Knuth, _The Art of Computer Programming_, vol.II "Seminumerical Algorithms", probably from page 38. If you have the time and inclination, it should be fun, at least at the start. Good Luck. Mel. From jonas at jonasgalvez.com Wed Apr 21 14:22:50 2004 From: jonas at jonasgalvez.com (Jonas Galvez) Date: Wed, 21 Apr 2004 15:22:50 -0300 Subject: Stupid Regex Question References: Message-ID: > [Fredrik Lundh] > a few posts back, you "top-posted" a followup to your own post. Oh... saw that now. Sorry :-) Jonas From harry.g.george at boeing.com Tue Apr 20 12:51:09 2004 From: harry.g.george at boeing.com (Harry George) Date: Tue, 20 Apr 2004 16:51:09 GMT Subject: report generators References: <425cc8d1.0404200505.4bce8dc2@posting.google.com> Message-ID: mir4uu at yahoo.com (mir nazim) writes: > hi, > i wanted 2 know if there is any report generator for python/linux that > produces reports in variety of formats e.g html/images/jpeg/png etc. > i know about report lab but output is pdf. pdf is ok for printing but > u need a pdf viewer for viewing it. there should be some thing that > cen viewed from directly from application e.g gtkhtml for gtk, khtml > for kde etc. "directly from application" seems odd, since both pdf and html rely on viewers to get the text onto the display. I think most python-to-xyz-format tools go through some neutral format such as docbook or latex. The python tool is used to generate those neutral formats more easily from simpler markups. My Pdx (http://www.seanet.com/~hgg9140/comp/index.html) does that. It goes directly to html, goes via latex to ps, pdf, and html, and goes via docbook to ps, pdf, html, rtf. It is from the era of Perl POD. These days, I'd look at OpenOffice, which can directly generate many formats, and can be manipulated in xml format. Python could do that manipulation. Or, work with the UDK via python bindings http://udk.openoffice.org/ -- harry.g.george at boeing.com 6-6M21 BCA CompArch Design Engineering Phone: (425) 342-0007 From http Tue Apr 20 15:09:09 2004 From: http (Paul Rubin) Date: 20 Apr 2004 12:09:09 -0700 Subject: Difficulty Finding Python Developers References: <65cbc3dd.0404140641.3501fde8@posting.google.com> Message-ID: <7xekqi31re.fsf@ruckus.brouhaha.com> "Mike C. Fletcher" writes: > > You probably already realized this, but that should've been $45 to > > $55 per hour. > > *I* didn't realise that, I assumed $45,000/year to $55,000/year annual > rate, which would be a reasonable rate in Canada (in Canadian dollars > even) for a programmer with 1 or 2 years of experience. I'd forgotten > just how well Americans get paid for having fun... but at least our > taxes are higher :) . If you're a contractor, you get no employee benefits like health insurance, no paid vacation or paid time off if you get sick, and no expectation of having a steady job (the job is just for 3 months and then you expect to be looking for work again). Plus you pay more taxes (there's a FICA tax of about 14% that you and your employer each pay 50% of if you're an employee, but you pay 100% of it if you're a contractor), plus you have to file tax returns every 3 months instead of once a year. Because of all that, it's normal for the hourly rate for contract programmers to be about 2x the equivalent hourly rate for staff programmers, i.e. a $50/hour 3-month contract job is equivalent to about a $50k/year staff job. In the current economy where there's lots of unemployment, contract work is quite hard to find (contractors are usually the first to get chopped when a company needs to cut expenses, since it's much easier to just not renew a contract than to actually lay off an employee), so the contracting market is worse than usual, which means that $50/hour is pretty good, especially for an area like Atlanta, which has lower expenses (and lower wages) than an area like Silicon Valley. From mhammond at keypoint.com.au Thu Apr 29 01:02:42 2004 From: mhammond at keypoint.com.au (Mark Hammond) Date: Thu, 29 Apr 2004 15:02:42 +1000 Subject: COM, IDL, and enum In-Reply-To: <9e5ea2c4.0404281215.25a0f9b3@posting.google.com> References: <9e5ea2c4.0404281215.25a0f9b3@posting.google.com> Message-ID: Olaf Meding wrote: > How do I access the values of the enum "ERLockStatus" specified in the > (abreviated IDL) file below? You must ensure that makepy has been run for your object - this generally just means calling gencache.EnsureDispatch() to create your object. Once the makepy'd file for the IDL has been loaded, the constants will be available as "win32com.client.constants.constant_name" Mark From mikalzetTogli at interfree.it Tue Apr 6 07:58:00 2004 From: mikalzetTogli at interfree.it (TaeKyon) Date: Tue, 06 Apr 2004 11:58:00 GMT Subject: recursive file editing References: Message-ID: Il Sun, 04 Apr 2004 12:11:25 +0200, Peter Otten ha scritto: > The following code comes with no warranties. Be sure to backup valuable data > before trying it. You may need to edit the regular expressions. Call the > script with the directory you want to process. Seems to work all right ! I have a question: > class Path(object): # multiple function definitions follow, amongst which: > def files(rootfolder): > for folder, folders, files in os.walk(rootfolder): > for name in files: > yield Path(folder, name) So 'Path' is the name of a class and _contemporaneously_ the result of one of the functions the class contains ? Or are there really two separate 'Path' things which don't interfere because each has its own namepace ? I'm sorry for the repeated questions, maybe I should take this discussion over to the tutor mailing list ! -- Michele Alzetta From mab at iee Fri Apr 9 05:46:59 2004 From: mab at iee (Marco Bartel) Date: Fri, 09 Apr 2004 11:46:59 +0200 Subject: connection with MySQL with Python interface In-Reply-To: References: Message-ID: <407671d0$1@news.vo.lu> pengz1 at netzero.com wrote: > Hi! All > When I tried to connect with MySQL database which run on XP from shell. I got following error message. Has anyone get similar error message and provide any suggestion? Thanks in advance. > > Zhiyong > > > Traceback (most recent call last): > File "C:\Python22\databaseAccess.py", line 4, in ? > con=MySQLdb.connect(host="127.0.0.1",port=3306,user="pengz",passwd="zhiy4318",db="e_retail_store") > File "C:\PYTHON22\Lib\site-packages\MySQLdb\__init__.py", line 63, in Connect > return apply(Connection, args, kwargs) > File "C:\PYTHON22\Lib\site-packages\MySQLdb\connections.py", line 115, in __init__ > self._make_connection(args, kwargs2) > File "C:\PYTHON22\Lib\site-packages\MySQLdb\connections.py", line 41, in _make_connection > apply(super(ConnectionBase, self).__init__, args, kwargs) > OperationalError: (2003, "Can't connect to MySQL server on '127.0.0.1' (10061)") > Traceback (most recent call last): > File "C:\Python22\databaseAccess.py", line 4, in ? > con=MySQLdb.connect(host="127.0.0.1",port=3306,user="pengz",passwd="zhiy4318",db="e_retail_store") > File "C:\PYTHON22\Lib\site-packages\MySQLdb\__init__.py", line 63, in Connect > return apply(Connection, args, kwargs) > File "C:\PYTHON22\Lib\site-packages\MySQLdb\connections.py", line 115, in __init__ > self._make_connection(args, kwargs2) > File "C:\PYTHON22\Lib\site-packages\MySQLdb\connections.py", line 41, in _make_connection > apply(super(ConnectionBase, self).__init__, args, kwargs) > OperationalError: (1250, 'Client does not support authentication protocol requested by server; consider upgrading MySQL client') > > ________________________________________________________________ > The best thing to hit the Internet in years - NetZero HiSpeed! > Surf the Web up to FIVE TIMES FASTER! > Only $14.95/ month -visit www.netzero.com to sign up today! > Hi Zhiyong, I think this error is raised by an incompatible clientlibrary shipped with mysql. You have to know that a client needs to have a mysql-client library and a mysql-shared library, for accessing a mysql-database. Under windows I only used mysql with win2000 not with XP, but when i remember right, the client, and the shared-library are not part of the main mysql-package, and have to be downloaded and installed seperatly. Maybe I helped you a little bit, becaus e the code of your program looks fine. CU Marco From arigo at tunes.org Sat Apr 3 17:17:53 2004 From: arigo at tunes.org (Armin Rigo) Date: Sat, 3 Apr 2004 22:17:53 +0000 (UTC) Subject: Python is faster than C References: <406F0907.96F37EA1@tunes.org> Message-ID: <406F3A33.70FB70CC@tunes.org> Michel Claveau/Hamster wrote: > For the 1st April, it's finish. Check it for yourself. Find yourself an Intel machine and grab Psyco from http://psyco.sf.net. Here is the source of my test: # Python Quicksort Written by Magnus Lie Hetland # http://www.hetland.org/python/quicksort.html def _partition(list, start, end): pivot = list[end] bottom = start-1 top = end done = 0 while not done: while not done: bottom = bottom+1 if bottom == top: done = 1 break if pivot < list[bottom]: list[top] = list[bottom] break while not done: top = top-1 if top == bottom: done = 1 break if list[top] < pivot: list[bottom] = list[top] break list[top] = pivot return top def _quicksort(list, start, end): if start < end: split = _partition(list, start, end) _quicksort(list, start, split-1) _quicksort(list, split+1, end) def quicksort(list): if len(list) > 1: _quicksort(list, 0, len(list)-1) # ____________________________________________________________ import random, time, psyco l = range(100000) random.shuffle(l) #TIMEIT = "l.sort()" #TIMEIT = "quicksort(l)" TIMEIT = "psyco.proxy(quicksort)(l)" print TIMEIT, ':', t = time.time() exec TIMEIT print time.time() - t assert l == range(100000) From greg at cosc.canterbury.ac.nz Wed Apr 21 03:59:11 2004 From: greg at cosc.canterbury.ac.nz (greg) Date: Wed, 21 Apr 2004 19:59:11 +1200 Subject: Dollar sign ($) on foriegn keyboards? (prothon) References: Message-ID: <408629CF.30004@cosc.canterbury.ac.nz> Peter Otten wrote: > This starts with the name, by the way - it evokes the > association of prothotype, which looks quite, er, ungreek :-) Indeed. It sounds more like an alien race that's escaped from an upcoming StarCraft expansion pack... Greg From moosebumps at moosebumps.com Fri Apr 2 03:46:22 2004 From: moosebumps at moosebumps.com (Moosebumps) Date: Fri, 02 Apr 2004 08:46:22 GMT Subject: HTML writer Message-ID: Is there a standard solution for writing HTML web pages with Python? I don't know that much about web programming, but basically I want to generate some internal reports on a web page. It doesn't need to be fancy, just basic tables and linking, maybe indexing and navigation, but I want it to all look nice and I want to be able to change the formatting easily without combing through source code (hence my next question about CSS). I know there newer things like CSS and XHTML -- are these more or less effort to generate? i.e. are they more complicated, or do they have more uniform syntax? What do they necessarily buy you? I searched the python website and I have seen HTML parsers, but no examples of generators. I searched for "Python HTML" and "Python CSS" and found some stuff -- but it doesn't seem like there is a "standard" solution that is EASY for non-expert web programmers to use. I am an experienced programming, but I don't know that much about all the alphabet soup that is web programming. thanks, MB From goodger at python.org Tue Apr 27 19:58:03 2004 From: goodger at python.org (David Goodger) Date: Tue, 27 Apr 2004 19:58:03 -0400 Subject: Backticks: What up? In-Reply-To: References: Message-ID: <408EF38B.1040108@python.org> Backticks are equivalent to repr(). For any x: `x` == repr(x) Nothing to do with the return statement. -- David Goodger From lbates at swamisoft.com Tue Apr 6 21:18:00 2004 From: lbates at swamisoft.com (Larry Bates) Date: Tue, 6 Apr 2004 20:18:00 -0500 Subject: jpg, jpeg metadata References: <8a560941.0403301948.146d251@posting.google.com> Message-ID: Take a look a jhead.exe. You can easily use os.system to call it from python. http://www.sentex.net/~mwandel/jhead/usage.html Regards, Larry Bates Syscon, Inc. "helmi03" wrote in message news:8a560941.0403301948.146d251 at posting.google.com... > does anyone know how to get/set jpg or other image types metadata using Python. > I had search in vault of parnassus and PIL, but only can read the EXIF. > > Long live Python! From JimJJewett at yahoo.com Thu Apr 1 00:34:10 2004 From: JimJJewett at yahoo.com (Jim Jewett) Date: 31 Mar 2004 21:34:10 -0800 Subject: easylog alpha Message-ID: The standard library's logging package is very powerful, but it doesn't scale *down* well. easylog is an attempt to better serve one-liner and midweight usage. easylog is available from http://sourceforge.net/projects/easylog/ under the Python Software Foundation license. easylog relies on an underlying logging package, so it will benefit from future improvements to the core logging package. (Unfortunately, treating another module as a black box to inherit from left some of the internals ... ugly.) I would particularly appreciate feedback on what should be cleaned up before it leaves alpha/beta status. -jJ From faassen at infrae.com Fri Apr 23 11:34:08 2004 From: faassen at infrae.com (Martijn Faassen) Date: Fri, 23 Apr 2004 17:34:08 +0200 Subject: EuroPython update april 23 Message-ID: EuroPython news update ====================== EuroPython is the European Python and Zope Conference. This year in its third edition, we are holding the conference in the beautiful locale of G?teborg, Sweden. Hundreds of Python users and Zope users are expected. - If you still want to submit a talk, note that the talk submission deadline is approaching very rapidly. You have until monday the 26th of april to submit your talk proposal. As an extra incentive, note that speakers participate at a reduced fee. - The early bird registration deadline is also very near now; after may 1st the rate will go up by 60 euros from 160 to 220. We also still have (very) cheap accomodation available, but this is running out quickly. So please register now! - The conference program is really shaping up nicely! We'll have tracks on topics ranging from core python hacking to social skills, and of course Zope. There will be tutorials, BoFs, lightning talks and panel discussions. Many of us are arriving early and/or staying on after the conference for a couple of days for sprints or other activities. - Our keynote speakers will be Mark Shuttleworth and Guido van Rossum. Mark Shuttleworth was among other things what we think is the first Python programmer in space. He is also is the sponsor of the schooltool project to develop an open source school administration system in Python. More about about him can be found at http://www.markshuttleworth.com/ If you don't know who Guido van Rossum is, you really need to come to EuroPython to find out and meet him. More information can be found at http://www.europython.org. See you at EuroPython 2004! From deetsNOSPAM at web.de Tue Apr 13 11:12:12 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Tue, 13 Apr 2004 17:12:12 +0200 Subject: 3D Graphics Engine References: <8089854e.0404130639.3eb0db62@posting.google.com> Message-ID: > Can anyone reccomend a 3d engine for me to 'muck around with'. Didn't check it myself, but blender migth be what you are looking for.... -- Regards, Diez B. Roggisch From daniel.dittmar at sap.com Thu Apr 8 06:09:01 2004 From: daniel.dittmar at sap.com (Daniel Dittmar) Date: Thu, 8 Apr 2004 12:09:01 +0200 Subject: why is python better than eg. smalltalk?? no one has any solid arguments! you should all go to church with all that religious talk! References: <20031028061245.12451.00000133@mb-m01.aol.com> Message-ID: Carlo v. Dango wrote: > OK, I'm on the python wagon as well, but I do not really se much > improvement over JAVA... especially when it comes to maintaining and > reusing code (e.g. API's)... here the types are really helpful. So If you name a post with a subject about 'python and smalltalk' and then start about 'python and java', then bondage and discipline languages are definitely the right thing for you ;-) The topic of static vs. dynamic types been discussed a lot here and elsewhere. > Also, I see all this advocacy of python which to me seems more like > religion.. there is no concretenes in it, and I completely fail to > see how python beats any of the other dynamically typed languages > such as smalltalk or self... what is it with you guys? :) When I started using Python, there were two reasons: - no good free eimplementation of Smalltalk - Smalltalk doesn't scale well to small tasks Point 1 has probably changed with Squeak. But I'd really have to use it for a while to be confident enough to inflict it upon others. Don't know about point 2: When I had a new version of some small 'script', I had only the alternatives * to distribute full images * to distribute source which the users had to integrate into their images Maybe this has changed as well. Daniel From peter at engcorp.com Mon Apr 19 08:07:57 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 19 Apr 2004 08:07:57 -0400 Subject: AOP use cases In-Reply-To: References: <84fc4588.0404140106.3fa0c55@posting.google.com> <0pydnSB4WYuieuLdRVn-hQ@powergate.ca> <35qdnT4kNsX1kB3dRVn-gg@powergate.ca> Message-ID: Michael Hudson wrote: > Peter Hansen writes: >>Peter Hansen wrote: >> >>>I would be very interested to hear some real-world and real useful >>>use cases for AOP as well. So far, the logging example seems to >>>be put forth so often that I'm starting to suspect that's the >>>*only* "useful" thing people are doing with it. :-) >>> From direct personal experience, could some AOP folks please >>>point out some compelling use cases so that the doubting >>>Thomases (and Wills, and Peters) can better understand and >>>accept the idea of AOP as being more than just a few fringe >>>cases? >> >>Thanks for the replies so far, but what concerns me is that >>almost no one seems to have actually used AOP in their code. > > What do you understand "AOP" to mean? One meaning of "AOP" seems to > be a collection of techniques and tools to make programming in the > Java environment a pleasanter experience. This meaning hardly applies > to programming in Python... I have no predefined meaning. I'm not about to run out and spend a lot of time researching something for which I have no reason (yet) to believe there is a practical use which would solve any problems I have. I'm hoping that someone here can point out such uses and help define the meaning for Python folks such as me. Yours is at least the second comment suggesting that AOP is a somewhat Java-specific, or at least shows more obvious use in the Java world (of heavy static typing) than in the Python world. -Peter From junkmail at solumslekt.org Fri Apr 2 04:30:28 2004 From: junkmail at solumslekt.org (Leif B. Kristensen) Date: Fri, 02 Apr 2004 11:30:28 +0200 Subject: String concatenation References: <7xisgi24fm.fsf@ruckus.brouhaha.com> <406D27A7.6550A00B@alcyone.com> <406D2CD5.878EBD4E@alcyone.com> <406D2FA2.6E5118CC@alcyone.com> Message-ID: Erik Max Francis wrote: > Maybe it's grabbing tabs, or obscure unprintable whitespace you can't > see. Certainly what you're pasting in to these posts is intended, > whether or not you did that manually. It may be a bug in KWrite. As I entered it manually, I noticed that the pasted text wasn't syntax highlighted. Yeah, I know -- I should use a real editor, like vi or emacs ;-) regards, -- Leif Biberg Kristensen http://solumslekt.org/ Validare necesse est From lbates at swamisoft.com Tue Apr 6 21:13:37 2004 From: lbates at swamisoft.com (Larry Bates) Date: Tue, 6 Apr 2004 20:13:37 -0500 Subject: Reading binary using a struct - behavour not as expected? References: <40712544$1@mail.hmgcc.gov.uk> Message-ID: <4cudnTewUMQjyO7dRVn-ig@comcast.com> Rich, Ok, your problem is this: When you define attributes immediately after the class definition they are SHARED among all instances of the class. Basically they are global (actually this can come in handy if you want to keep counters across class instances). You were copying into lastcopy, but everytime you unpacked, you overwrote your shared attributes. Try this instead: class PCAPPacketHdr: # # Attributes defined here are global across # instances of this class. # FormatString = "LLLL" def __init__(self): # # Attributes defined here are local to # the class instance. # self.TSSec = None self.TSUSec = None self.InclclLen = None self.OrigLen = None return This will share FormatString (it doesn't change), but have individual attributes for the other values you wish to be unique between two different instances of the class. Regards, Larry Bates Syscon, Inc. "richardd" wrote in message news:40712544$1 at mail.hmgcc.gov.uk... > Hi, > I am writing code to deal with PCAP files. I have a PCAP dump and I am > looking at the timestamps in the PCAP packet headers to see if they are in > the correct order in the file. To do this I have a class called > PCAPPacketHdr as follows > > import struct > > class PCAPPacketHdr: > FormatString = "LLLL" > TSSec = None > TSUSec = None > InclLen = None > OrigLen = None > > def Pack(self): > return struct.pack( self.FormatString, self.TSSec, self.TSUSec, > self.InclLen, self.OrigLen ) > > def Unpack(self, buffer): > self.TSSec, self.TSUSec, self.InclLen, self.OrigLen = > struct.unpack( self.FormatString, buffer ) > > def Size(self): > return struct.calcsize (self.FormatString) > > > I then have code which opens up the file (skipping the PCAP file magic > number and PCAP file header), and reads in each packet header as follows: > > while not eof: > #read in PCAPPacketHdr > buf = curFile.read(packetHdr.Size()) > if len(buf) == packetHdr.Size(): > packetHdr.Unpack(buf) > if lastPacketHdr != None: > if lastPacketHdr.TSSec > packetHdr.TSSec: > outputFile.write("ERROR: Packet TSSec earlier than last > one: \n") > outputFile.write(" Last Packet > "+repr(lastPacketHdr.TSSec)+"."+repr(lastPacketHdr.TSUSec)+"\n") > elif lastPacketHdr.TSSec == packetHdr.TSSec: > if lastPacketHdr.TSUSec > packetHdr.TSUSec: > outputFile.write("ERROR: Packet TSUSec earlier than > last one\n") > outputFile.write(" Last Packet > "+repr(lastPacketHdr.TSSec)+"."+repr(lastPacketHdr.TSUSec)+"\n") > outputFile.write(" Packet > "+repr(packetHdr.TSSec)+"."+repr(packetHdr.TSUSec)+"\n") > lastPacketHdr = copy.deepcopy(packetHdr) > #skip packet payload > packetPayload = curFile.read(packetHdr.InclLen) > else: > eof = True > > > This code appears to work fine for extracting the timestamps from the file, > the repr( ) calls on the timestamps allow me to write them to the output > file correctly, it's just the comparison operators don't appear to be > working as I would expect. It appears than when the TSUSec timestamp is the > same as the previous one in the data I input, it reports "ERROR: Packet > TSUSec earlier than last one". > > This makes me think that the comparison operators aren't acting on the data > as longs as I expected. > > Can anyone shed some light on what I'm doing wrong, I'm still very new to > Python. > > Thanks in advance, > > Rich > > From bignose-hates-spam at and-benfinney-does-too.id.au Sun Apr 4 23:19:18 2004 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 5 Apr 2004 13:09:18 +0950 Subject: How to assign a default constant value in a function declaration References: Message-ID: On Sun, 4 Apr 2004 19:26:30 -0400, Vineet Jain wrote: > The following does not work although it seems like something you > should be able to do. > > def someFunction(option=Constants.DEFAULT_VALUE): That's not a question. Is there something that isn't behaving as you expect? If so, please explain what you expect, and what you're actually experiencing. -- \ "I took a course in speed waiting. Now I can wait an hour in | `\ only ten minutes." -- Steven Wright | _o__) | Ben Finney From grante at visi.com Wed Apr 28 21:04:05 2004 From: grante at visi.com (Grant Edwards) Date: 29 Apr 2004 01:04:05 GMT Subject: Don't understand wxPython ids References: <408ed938$0$17263$a1866201@newsreader.visi.com> <408f3061$0$17258$a1866201@newsreader.visi.com> <408fb665$0$17264$a1866201@newsreader.visi.com> Message-ID: <40905485$0$17251$a1866201@newsreader.visi.com> On 2004-04-28, Greg Krohn wrote: > Here we go. Use the attached module like this: > > #yourmodule.py > import wx > from event_kwargs import * > > ... your code ... > > self.ok_button = wx.Button(self, -1, "Ok", EVT_BUTTON=self.OnOk) > > ...more code... I _like_ it. Very clever! > The only testing I've done is in the "if __name__ == '__main__'" part of > the module. I *haven't* tested all the widgets and events, but they > should theoretically work. I'll certainly give it a try. Thanks! -- Grant Edwards grante Yow! I'm in LOVE with at DON KNOTTS!! visi.com From m.boeren at guidance.nl Fri Apr 2 05:39:40 2004 From: m.boeren at guidance.nl (Marc Boeren) Date: Fri, 2 Apr 2004 12:39:40 +0200 Subject: Simple text markup (-> HTML) Message-ID: <0C77C7530EA52A4EBD1C47C80D1D291E07F849@sbs.GuidanceBV.local> > :::Title::: A simple text markup utility :::/Title::: or: A simple text markup utility ============================ Compare this: http://docutils.sourceforge.net/docs/rst/quickstart.txt with this: http://docutils.sourceforge.net/docs/rst/quickstart.html and start thinking about reStructuredText... Cheerio, Marc. From a at a.invalid Fri Apr 23 01:37:40 2004 From: a at a.invalid (Timo Virkkala) Date: Fri, 23 Apr 2004 05:37:40 GMT Subject: Python-list, Exotic sex is urgently necessary for you! In-Reply-To: References: Message-ID: [disgusting content snipped] I've heard of sex with lots of kinds of animals, but Pythons? Wouldn't that be a) difficult b) VERY dangerous? *grin* -- WT From justin at justinclarke.com Mon Apr 12 11:40:22 2004 From: justin at justinclarke.com (Justin Clarke) Date: Mon, 12 Apr 2004 11:40:22 -0400 Subject: Internet Explorer extensions in Python Message-ID: Has anyone got any example Internet Explorer browser help objects or extensions? I have several examples in C++ and C#, but I would like to find out how to do this in Python if possible. Also, I know I need to implement a COM server with IObjectWithSite (GetSite and SetSite). I'm planning on using the universal interface as per the excel and outlook plugins, but does anyone have any idea where I can find this object with makepy? I'm wondering what the data it passes will look like in Python. Thanks Justin From donn at drizzle.com Wed Apr 7 01:37:41 2004 From: donn at drizzle.com (Donn Cave) Date: Wed, 07 Apr 2004 05:37:41 -0000 Subject: A beginner's question on thread References: Message-ID: <1081316259.664569@yasure> Quoth Timothy Wu : | I'm writing a small utility that listens for socket connections, and | also repond to user inputs via a text menu selection. | | In order to respond to both the user and the incoming connections I | figure I need to use thread. | | I think I would use the main thread to handle the menu and spawn a | thread which listens on a socket. | | Now my question is, how do I terminate the server thread if user wants | to exit the application? If the server just sit there and listen the | thread would never terminate by itself. What kind of inter-thread | communications are available and where would I find info/tutorial on that? Well, that's the deal. Use threads to solve a problem, and now you have two problems. I'd probably do it the way Aurelio Martin proposed, with I/O to the socket thread. It's much neater than whacking the thread, which is the alternative. I wouldn't necessarily use threads in the first place, though. I think it really depends on the user interface - usually that has to be the dispatch core of the application, and if it's built for threads, then there you go. Typically there will be some provision for dispatch on an I/O channel like a socket. If you're writing your own user interface, probably just reading and writing to the tty, and the socket thread is going to be the one and lonely extra thread - then don't do it, I'd say. Use select.select, or a package like asyncore or twisted or whatever (not very familiar with that territory, I just use select.) Donn Cave, donn at drizzle.com From bokr at oz.net Sat Apr 24 18:10:51 2004 From: bokr at oz.net (Bengt Richter) Date: 24 Apr 2004 22:10:51 GMT Subject: Why we will use obj$func() often References: <8AWhc.23114$dZ1.11070@fed1read04> <40883BFE.B381518A@alcyone.com> <27_hc.23801$dZ1.2716@fed1read04> <40887145.789A2FE8@alcyone.com> <7cki80hj976bia36lhf9er97v073o1pqvm@4ax.com> <1082783076.585831@yasure> <108l6fvhl7fq29c@corp.supernews.com> Message-ID: On Sat, 24 Apr 2004 09:46:54 -0700, "Michael Geary" wrote: >David MacQuigg wrote: >> How about instead of decorating variables with special >> symbols or capitalization, we have a rule that says any >> variables with unusual scope must be declared in a >> statement at the top of the function where they are used. >> So for example >> >> def func( x, y ): >> global a, b, c ### module level >> external d, e, f ### one level up >> ... >> >> This would avoid the need for new and unique symbols, >> would unclutter the code in the body of the function, would >> provide a single place where you could see the scope of any >> unusual variable, and would answer the question "What >> external dependencies does this function have?" Does it >> satisfy the need you are seeing for & variables? > >Hey, that is a great idea, David. I definitely like it better than the & >notation. It would work in Python as well as Prothon, and give me clean and >readable closures like I have in JavaScript. > >I would want it to mean: > > external d, e, f # # # search up the scope chain external has been suggested before ;-) http://groups.google.com/groups?selm=bmdelc%24rsf%240%40216.39.172.122&rnum=25 > >because I often want to use variables from scopes more than one level up. >And maybe another word would be better than 'external' (although I don't >have one in mind). But the idea is terrific. > >> Python added "read access" to external variables, so they >> must have considered "write access" as well. I don't know >> the history, but I would guess the reason they didn't allow >> this is the same as the reason they don't allow GOTO. Yes >> it is powerful, but it might encourage bad programming. > >We're both speculating, of course, but my guess is simply that automatic >creation of variables by assignment conflicts with writing to variables from >outer scopes. The global statement solves this for global variables, but no >one thought it important enough to do something for nested scopes as well. >Just my guess. > I think if we break down the uses of names, separating the determination of what namespace they belong to from lookup and binding operations, we can identify some simple possibilities. I.e., for a = b the current rules (which can't change w/o code breakage) are first of all different for the left and right side of the '=': On the left, it always means the local namespace, unless declared global. And it always means bind, whether a current binding exists or not. On the right, unless declared global, it means search the chain of scopes[1] and find the existing binding (or raise an exception if none). The problem is binding and rebinding in external scopes. IMO limiting that just to _re_binding would not be a serious limitation, and then we would only need a simple spelling for find-in-the-chain-of-scopes-and-rebind. I would suggest a := b to mean that. I.e., find b as usual, then find a as if it were on the right (raising an exception if not found), and rebind it in the namespace where it was found. Then Mark's example would be written simply as def getFunc(): counter = 0 def count(): counter := counter + 1 # or perhaps counter +:= 1 print counter return count [1] BTW, "external" scopes could be defined in more general ways than only lexical scoping. E.g., IIRC postscript lets you push (and pop) dictionaries on a stack, and bare names are searched for through that. It might be interesting to be able to push a dictionary to work like a new local namespace without the control stack being changed. To get really general, you could dynamically define an explicit sequence of name spaces in some kind of ns path analogous to sys.path. ... just BF'ing ;-) Hm ... more: what about applying find-and-rebind to an mro path? Thus self.classvar_or_instvar := 123 could rebind a class variable unless shadowed by an instance variable. This would be a concise way of getting to a class variable without using the global class name, and an easy way to share a variable amongst instances. Regards, Bengt Richter From erlendga at tva.ifi.uio.no Thu Apr 1 14:12:32 2004 From: erlendga at tva.ifi.uio.no (Erlend Andreas Garberg) Date: Thu, 1 Apr 2004 19:12:32 +0000 (UTC) Subject: Travelling salesman variation in python References: <7xhdw3zfb2.fsf@ruckus.brouhaha.com> Message-ID: In article <7xhdw3zfb2.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: > Erlend Andreas Garberg writes: >> An approximate solution would be good enough, do you have any >> suggestions about how do do that? > > Is it just an arbitrary graph? Most TSP approximation algorithms > depend e.g. on the triangle inequality, i.e. d(A,C) <= d(A,B) + d(B,C). > > Papadimitriou and Stieglitz, "Combinatorial Optimization" was a > standard textbook on this stuff, though is pretty old by now. The graph is arbitrary, yes.. -- mvh Erlend Garberg erlendga at ifi.uio.no From manpreet_nehra at hotmail.com Wed Apr 7 06:14:53 2004 From: manpreet_nehra at hotmail.com (Manpreet) Date: 7 Apr 2004 03:14:53 -0700 Subject: Conflux Message-ID: I am not a python programmer and could not decide where to post this so this seemed to be the best place. I have trying to use conflux lite groupware and I have been through the documentation a couple of times....I am able to open the index page but as soon as I try to login I get the following error I don't know what to do with this Mod_python error: "PythonHandler _Publisher" Traceback (most recent call last): File "/usr/lib/python2.3/site-packages/mod_python/apache.py", line 338, in HandlerDispatch result = object(req) File "/var/www/html/conflux/lib/_Publisher.py", line 217, in handler module = apache.import_module(module_name, req.get_config(), [path]) File "/usr/lib/python2.3/site-packages/mod_python/apache.py", line 493, in import_module f, p, d = imp.find_module(parts[i], path) ImportError: No module named index From peter9547 at btinternet.com Sun Apr 4 16:07:25 2004 From: peter9547 at btinternet.com (Peter MacKenzie) Date: Sun, 4 Apr 2004 20:07:25 +0000 (UTC) Subject: emergent/swarm/evolutionary systems etc References: <106um6hcr363u14@corp.supernews.com> <1070gv5586u8mc2@corp.supernews.com> Message-ID: Looking at it, I don't think it's for me. I'll keep it in mind for future tasks, but this dissertation would be better served by text coding and a raster display. The flow chart code and vector graphics output of LabVIEW might be useful if I was doing sociological work, as that uses a lot of flow chart stuff to model the inter-linkages between people, but I'm not really a people person. Another minute, another thing I've learned. It's not quite as exciting as following the 'thinking' tutorial though. >>> fruit = "bannana" >>> bakedfood = " nut bread" >>> fruit + bakedfood 'bannana nut bread' >>>message = "What's up, doc?" >>> fruit *len(fruit) 'bannanabannanabannanabannanabannanabannanabannana' >>> fruit *len(message) 'bannanabannanabannanabannanabannanabannanabannanabannanabannanabannanabanna nabannanabannanabannanabannana' It took me a bit to figure out this one: >>>fruit * pow(len(message),1) 'bannanabannanabannanabannanabannanabannanabannanabannanabannanabannanabanna nabannanabannanabannanabannana' (I won't take it to >>>fruit * pow(len(message),2)) There's such a thing a too much fibre. :-) Cameron Laird wrote in message news:1070gv5586u8mc2 at corp.supernews.com... > In article , > Peter Hansen wrote: > . > . > . > >> LISP brought it to mind. Although LISP doesn't look that much better than > >> Python code, are there any programs out there that let you program, um, > >> programs, using various shapes, colours etc? Just thinking about it brings > >> up all manner of difficulties that would be encountered if you tried to > >> create such a thing, but it would be nice if there was some immediately > >> obvious graphical connection between pieces of code [...] > > > >Using the "G" graphical language of LabVIEW, all code ends up > >_literally_ looking like spaghetti... would that help? ;-) > > > >-Peter > > LabVIEW's the first example that came to my mind, although > perhaps Prograph or JavaBeans (!) could be argued as more > commercially successful. > > I've worked on VPLs a couple of cycles in my career already, > in process-control contexts. My enthusiasm is tepid--but > then I've exceedingly text-oriented. > -- > > Cameron Laird > Business: http://www.Phaseit.net From ahaas at airmail.net Wed Apr 28 14:52:45 2004 From: ahaas at airmail.net (Art Haas) Date: Wed, 28 Apr 2004 13:52:45 -0500 Subject: ANNOUCE: Thirteenth release of PythonCAD now available Message-ID: <20040428185245.GH20535@artsapartment.org> I'd like to announce the thirteenth 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 or Python 2.3. 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 thirteenth release of PythonCAD is the first release to offer undo/redo abilities. The undo/redo work is in its initial stage, and upcoming releases will enhance the robustness of the code. The long term goal with undo/redo work is to make both as unlimited as possible, but for the first release the functionality works best if only the last action is undone or redone. Undoing and redoing multiple operations works in certain cases, but not not in others. Development efforts for the next release will concentrate on enhancing the undo/redo abilities of the program. This release also has the ability to save the current background and foreground colors, and offers the user the ability to specify the color for boxes drawn around points. As for code cleanups, a number of deprecated methods have been removed, and several existing methods are now deprecated. An assortment of bug fixes and code improvements have been added as well. The mailing list for the development and use of PythonCAD is available. Visit the following page for information about subscribing and viewing the mailing list archive: http://mail.python.org/mailman/listinfo/pythoncad 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, and Happy New Year to everyone! 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 peter at engcorp.com Fri Apr 2 10:13:07 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 02 Apr 2004 10:13:07 -0500 Subject: Making the Zen of Python more useful In-Reply-To: References: <106qp0uivlefo40@corp.supernews.com> Message-ID: <-5ydnTEmxfuZHvDdRVn-iQ@powergate.ca> Andrew Henshaw wrote: > In article , peter at engcorp.com says... >>I'm not sure why you had to do quite all that. The following is >>sufficient, and you don't need a custom ROT-13 thingie: >> >>>>>import StringIO, sys >>>>>s = StringIO.StringIO() >>>>>sys.stdout = s >>>>>import this >>>>>sys.stdout = sys.__stdout__ >>>>>s.getvalue() >> >>"The Zen of Python, by Tim Peters\n\nBeautiful is ... > > Much better. Still pretty awkward for the purpose I described. Perhaps, the > best solution, overall. Okay then, how about this one? :-) >>> import this The Zen of Python, by Tim Peters\n\nBeautiful is ... >>> this.s.decode('rot-13') u"The Zen of Python, by Tim Peters\n\nBeautiful is ... -Peter From aahz at pythoncraft.com Mon Apr 19 20:55:03 2004 From: aahz at pythoncraft.com (Aahz) Date: 19 Apr 2004 20:55:03 -0400 Subject: unexpected performance from threads and network client benchmarking References: Message-ID: In article , Project2501 wrote: > >the wisdom says that you will not see any performance increase from the >use of threads on the client side trying to it a server (high request rate). > >this is explained in terms of the GIL.. Huh? Where did you see this "wisdom"? This is precisely one of the prime use cases for threading. See http://pythoncraft.com/OSCON2001/index.html -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I used to have a .sig but I found it impossible to please everyone..." --SFJ From mark at prothon.org Thu Apr 1 01:23:41 2004 From: mark at prothon.org (Mark Hahn) Date: Wed, 31 Mar 2004 22:23:41 -0800 Subject: Prothon, metaclasses, Zope [Was: A 'Python like' language] References: <95aa1afa.0403272243.78d60724@posting.google.com> <95aa1afa.0403280258.41dc5cd9@posting.google.com> <8y8ac.68250$cx5.51296@fed1read04> Message-ID: "Greg Ewing (using news.cis.dfn.de)" wrote in message news:c4dkg2$2gsuda$1 at ID-169208.news.uni-berlin.de... > Mark Hahn wrote: > > > But presumably he wants the check done only once, when a subclass is > > > defined, *not* every time said subclass is instantiated. > > > > You can have a different __init__ for an object and it's prototpe.So the > > Prothon equivalent of a subclass can easily have different __init__ > > behaviour than it's child (what you call instance). > > Can you post some code illustrating how you would do this > in Prothon? I still can't see how, at the point where you > do > > X = Base() > > anything can tell whether you're intending to use X as > an instance of Base or whether you're going to go on to > say > > with X: > def ... > > and use X as a prototype which inherits behaviour from > Base. In both cases, Base.__init__ is going to get invoked > before you have a chance to define any other __init__ that > might override it. You don't have to use the obj = proto() technique to create an object. The following code is identical to saying subproto = topproto() except no __init__() will be called: subproto = Object() subproto.set_proto(topproto) # switch prototype on the fly Does this give you the missing piece you need or is there something else missing in Prothon? If you explain the overall goal better I'll write the complete code for you. > > -- > Greg Ewing, Computer Science Dept, > University of Canterbury, > Christchurch, New Zealand > http://www.cosc.canterbury.ac.nz/~greg > From grzegorz at ee.ualberta.ca Sat Apr 17 12:38:43 2004 From: grzegorz at ee.ualberta.ca (Grzegorz Dostatni) Date: Sat, 17 Apr 2004 12:38:43 -0400 (EDT) Subject: Static Modules... In-Reply-To: References: Message-ID: Please don't use that snippet. It has some problems, the chief of which is that it does not differentiate between different types of exceptions. This one behaves in a lot more sane way. There are still a few problems, like: 1. If an exception occurs inside the module (either of the exec statements) : the original exception is executed. This *could* be a feature - as in: "I tried, now you fix your own bugs!". 2. Multiple module NameError exceptions inside the same code object will not work. Greg Advice is what we ask for when we already know the answer but wish we didn't. -- Erica Jong (How to Save Your Own Life, 1977) On Sat, 17 Apr 2004, Jeff Epler wrote: > I tossed this in my PYTHONSTARTUP file, to see how I like it. > No complaints so far, and it might make the interactive prompt even > easier to use. > > Jeff > > -------------- next part -------------- # # Autoload - v. 0.2 # Dynamically load modules as they are referenced. # # by Grzegorz Dostatni on April 17, 2003 # import sys def autoload_exc(type, value, traceback): if type == NameError: modulename = value.args[0].split()[1][1:-1] f_locals = traceback.tb_frame.f_locals f_globals = traceback.tb_frame.f_globals # simple way of handling errors for now: # If this fails in any way - display the original exception try: exec "import " + modulename in f_locals, f_globals exec traceback.tb_frame.f_code in f_locals, f_globals except: sys.__excepthook__(type, value, traceback) else: sys.__excepthook__(type, value, traceback) sys.excepthook = autoload_exc From ed-no at spam-eepatents.com Thu Apr 15 03:38:31 2004 From: ed-no at spam-eepatents.com (Ed Suominen) Date: Thu, 15 Apr 2004 00:38:31 -0700 Subject: Goodbye TCL Message-ID: <0LudnSads6NmpuPdRVn-vw@centurytel.net> I have debated about the wisdom of posting this message, knowing that a lot of people whom I respect may not like what I have to say. On the other hand, I wish that the person who told me "TCL is dead, try Python" two weeks ago had somehow been able to get that message through to me much earlier. As a longtime member of comp.lang.tcl who reluctantly considered that advice but wound up finding its results incredibly illuminating and productive, it seems only fair to pass it on. I am dictating this posting into a Linux application window using speech recognition software that is running under Windows in a VMware virtual machine. Every time I dictate a bit of text into a Tk text widget on the Windows side, that text is transmitted via a (virtual) TCP connection to a daemon on the Linux side that generates fake keystrokes via X events. I wrote the software that accomplishes this [1] over the course of the last week or so, one week after beginning my study of object-oriented and test-driven programming in general, more specifically of Python, and even more specifically of the Twisted network application framework for Python [2]. There was a lot of reading and head-scratching involved, but it was a fascinating experience. I have had extensive experience doing network application development with TCL, most visibly with Privaria [3]. That experience involved a great deal of low-level programming using the socket built-in function and its companions. In both cases, I searched far and wide for suitable TCL packages to do what I wanted but wound up just writing the stuff at a low level because the packages seemed inactive, demonstrated buggy behavior, or just didn't seem to do what I wanted. I spent many interesting but frustrating hours sniffing packets and working out the details of TCP-level communications -- buffer flushing, newline inconsistencies, blocking vs. non-blocking reads, etc. With this latest project, I was determined to see if Python was as widely supported and powerful as its advocates claimed. I was not disappointed. After quite a few hours of intense study (my first real exposure to object-oriented programming, see above) I found the language itself incredibly powerful, without the need for any external packages (which do you choose, itcl, snit, or what?) to tack OOP capability onto a language that is as procedural as the name of its function construct ("proc") implies. Namespaces in Python just happen; they don't need definition. If you "import" a "module," all of its "attributes," which are classes, methods (few), and variables (fewer) live in that module's name space unless you indicate otherwise (which you can easily do). The number of globals floating around is truly minimal, because defining classes that instantiate objects making things happen in methods of objects is the default in the way the language and its documentation (current and extensive) encourage you to program. But most significantly, I found, is that trying to reuse code that others have written is no longer a frustrating exercise in skipping past "Error 404: Page Not Found" messages, pages that are found but haven't been updated in three years and feature code that only links to tclsh8.1, and packages that are TCL-only or manage to link but seem dangerously inactive, buggy, and unused. For my first Python application (written just before the one I'm using to dictate this) I needed to generate highly structured, highly specialized HTML from various bits of data in text files here and there. I found the HTML generation package in Python's standard library (yes, there is one, is extensive, and it comes with the interpreter) to be intuitive and powerful, in contrast to the tcllib tool that I wound up having to extend with my own hacks on too many occasions. (There's a more powerful TCL tool, but it doesn't seem to be active or widely used...) For this dictation application, I used the twisted application framework, which turns Python into an incredibly powerful networking and multitasking machine. It was very difficult to learn because its documentation does not keep up with its depth, and I wound up having to print and pore over a lot of source files to understand how it works. But once I overcame that learning curve I found that I could do amazing things with a few lines of highly modular code. I never even got close to the TCP packets. I just invoked a method of the "reactor" object that runs the whole show to listen for TCP connections on one side and make connections on the other and implemented various methods to send the data I needed. When new text materializes in the text widget, a periodically-polled method senses it and sends it to the other side. The other side tells its keystroke-typing object about the new text and lets that object take care of calling its own objects. All those objects' classes and method were unit tested concurrently with their development, based on a testing framework someone else wrote and is supporting. The whole things takes up about 800 lines of code, including extensive "docstrings" (essentially documentation-generating comments). I'm not writing all of this to rub it in, to thumb my noses at those left behind. But I think at some point people (like me, two weeks ago) should question why their particular programming language, operating system kernel (see, e.g., the Hurd), editor, etc. does not seem to be receiving as much attention as they would like. Sure, such people can tout the benefits of their particular choice and shake their heads in wonder at why others haven't discovered it or have left it behind, but they might well take an honest look at the question "why"? Perhaps there is a reason why Python has several dozen books with recent publication dates and nothing new seems to have been written about TCL for years. Perhaps there is a reason why the comp.lang.python newsgroup has several times the volume of this one and the typical Linux distribution has many times more Python-based applications than TCL-based ones. The reason may be that many people are finding one choice superior to the other. Finally, let me add that some of my observations may be inaccurate. Any such inaccuracies are unintentional and open to correction here. Hopefully this lengthy message will be received in the constructive spirit in which it was written. Ed Suominen [1] Very much in pre-release state, but available at http://www.ossri.org/projects.php [2] http://www.twistedmatrix.com/ [3] http://www.privaria.org From noemail at noemail4u.com Thu Apr 22 13:14:51 2004 From: noemail at noemail4u.com (Daniel 'Dang' Griffith) Date: Thu, 22 Apr 2004 17:14:51 GMT Subject: This is very simple question References: <108dbd1aftmkc48@corp.supernews.com> <4087a0f6$0$25552$afc38c87@news.easynet.fr> <108fl7h8oocmm5c@corp.supernews.com> <4087dc83$0$24703$afc38c87@news.easynet.fr> Message-ID: <921e8fdcd6a79c676abcf213410c9d85@news.teranews.com> On Thu, 22 Apr 2004 16:53:55 +0200, "Nicolas Lehuen" wrote: >> > return result.reverse() # if you really want it reversed >> >> I agree that divmod() improves the algorithm, and thank >> you for pointing that out. >> >> I'm reasonably certain that the return value of reverse() >> is not what you believe it to be. >> -- >> >> Cameron Laird >> Business: http://www.Phaseit.net > >Ooops indeed, reverse() always returns None, because the reverse is made in place. I did test the program without the reverse, so I missed this mistake. Thanks ! > >BTW, I've been bitten by this behaviour a lot since I've switched to Python a year ago (coming from C++ and Java)... I would feel much better if reverse(), sort() and so on returned the list itself ; but then maybe other people would think the reversing/sorting etc. would not be done in place... > >Regards, >Nicolas You probably already do this, but in case someone else wants an easy workaround: def reversed(lst): lst2 = lst[:] lst2.reverse() return lst2 def sorted(lst): lst2 = lst[:] lst2.sort() return lst2 Then you can do things like: mylst = reversed(mylst) Which is not as pretty as mylst = mylist.reversed() But it is less punctuation! ;-) There's been talk about adding this type of method to the builtin list object. --dang From greg at cosc.canterbury.ac.nz Fri Apr 16 00:42:25 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Fri, 16 Apr 2004 16:42:25 +1200 Subject: Mac: How to receive AppleEvents with creator IDs In-Reply-To: References: Message-ID: Jean-Pierre Bergamin wrote: > I'm wondering if it's possible to receive AppleEvents with python that are > addressed only by the creator ID (= application signature) which is a usual > OSType four character code. You need to build an applet from your Python code (a utility for doing this is provided with MacPython). Then give the applet a unique creator code, and other applications will be able to address AppleEvents to it. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From nicksjacobson at yahoo.com Thu Apr 29 15:20:36 2004 From: nicksjacobson at yahoo.com (Nick Jacobson) Date: 29 Apr 2004 12:20:36 -0700 Subject: static keyword References: Message-ID: > >>> i = [10 ,11] > >>> firstcall = True > >>> > >>> def foo(): > ... global i > ... global firstcall > ... if firstcall: > ... print "First pass" > ... firstcall = False > ... i[0] += 1 > ... print i[0] > ... > >>> foo() > First pass > 11 > >>> foo() > 12 Hmm. I would like it, but it pollutes the global namespace. Two functions might want to use firstcall, for example (if they want to just do something on the first pass). That's an error at most, and renaming issues at the least. Thanks for the idea, though.. From avera at coes.org.pe Mon Apr 5 11:35:22 2004 From: avera at coes.org.pe (Alberto Vera) Date: Mon, 5 Apr 2004 10:35:22 -0500 Subject: accented chars make an error Message-ID: <001a01c41b23$9bf1d8e0$1603a8c0@pc22> Hello I'm using win32com.client to get information from a database. The problem occurs with accented chars like ?,?,?,?,?. when a program get a string containing these accented chars from the database, Python shows an error like : UnicodeEncodeError: 'ascii' codec can't encode character u'\xc1' in position 22: ordinal not in range(128) Could you tell me How I can avoid this error? Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From jwsacksteder at ramprecision.com Mon Apr 19 11:10:31 2004 From: jwsacksteder at ramprecision.com (jwsacksteder at ramprecision.com) Date: Mon, 19 Apr 2004 11:10:31 -0400 Subject: outline-style sorting algorithm Message-ID: <71650A6F73F1D411BE8000805F65E3CB3B3A51@SRV-03> Am I understanding correctly that python has an implict notion that position in a list denotes order of magnitude? Batteries included- Big Win! -----Original Message----- From: Max M [mailto:maxm at mxm.dk] Sent: Monday, April 19, 2004 10:58 AM To: Jeff Sacksteder Cc: python-list at python.org Subject: Re: outline-style sorting algorithm jwsacksteder at ramprecision.com wrote: > I have a need to sort a list of elements that represent sections of a > document in dot-separated notation. The built in sort does the wrong thing. Not really. You are giving it a list of strings, and it sort those alphabetically. That seems like the right thing to me ;-) > This seems a rather complex problem and I was hoping someone smarter than me > had already worked out the best way to approach this. For example, consider > the following list- >>>>foo > > ['1.0', '1.0.1', '1.1.1', '1.2', '1.9', '1.10', '1.11', '1.20', '1.20.1', > '1.30'] You need to convert them to another datatype first. Your best bet here would be a list or a tuple, as they can map directly to your data. '1.0.1'.split('.') == [1,0,1] But list are a bit easier here. foo_as_tuples = [f.split('.') for f in foo] foo_as_tuples.sort() Then you must convert it back to strings again. foo = ['.'.join(f) for f in foo_as_tuples] There is a standard way of sorting quickly in python, called decorate-sort-undecorate. It is allmost the same example as before: decorated = [(itm.split('.'),itm) for itm in foo] decorated.sort() foo = [d[-1] for d in decorated] regards Max M From osv at javad.ru Wed Apr 21 08:06:12 2004 From: osv at javad.ru (Sergei Organov) Date: 21 Apr 2004 16:06:12 +0400 Subject: CamelCase versus wide_names (Prothon) References: <6ee58e07.0404192141.2229efd6@posting.google.com> Message-ID: <1082549174.163233@ns.topconrd.ru> Gerrit writes: > Mark Hahn wrote: > > "William Park" wrote ... > > > > Someone else already mentioned this > > > > problem: > > > > > > > > smtp_message <-> SMTPMessage <-> SmtpMessage > > > > If you consider the capital letter as just a replacement for the underbar, > > then the answer is definitely smtpMessage. I don't see any problem. > > SMTP is an acronym. Because it's an acronym, it's most often spelled in > allcaps. Yet nobody mentioned that we don't have lower-case digits ;) usb201_driver <-> usb201Driver <-> usb2??Driver -- Sergei. From dippyd at yahoo.com.au Wed Apr 14 03:34:58 2004 From: dippyd at yahoo.com.au (Steve) Date: Wed, 14 Apr 2004 17:34:58 +1000 Subject: maximum length of a list & tuple References: Message-ID: <407CE9A2.2040209@yahoo.com.au> Lupe wrote: > I just would like to know if there is any limit to a list or tuple. Yes. Since the universe only contains something like 10**85 particles of matter, the upper limit to a list is roughly 2**(10**85) bits. Sorry, I couldn't resist :-D You can store as many things in a list as you have memory for. I suppose there is probably some fundamental limit due to 32 bit addressing issues, but are you sure you are really storing so many items you are hitting that limit? I'd guess you aren't. For example, the other day I was playing around with Python, and just for a lark I created a list with 300,000,000 instances of None. It took about five minutes, but it worked :-) Going back to your original problem: > Each time the function is called, it compares an > element of a list (which is a list too) to other > elements, which all amounts to millions of > comparisons. Are you sure there isn't a more efficient algorithm for what you are trying to do? > The program is working for short lists but not for > longer ones. What do you mean it is working? It doesn't finish? It is too slow? Or it gives the wrong answer? If it is giving a wrong answer, there is a bug in your code. If it is running too slowly, chances are there is a better algorithm that will fix it. -- Steven D'Aprano From peter at engcorp.com Sun Apr 4 22:46:41 2004 From: peter at engcorp.com (Peter Hansen) Date: Sun, 04 Apr 2004 22:46:41 -0400 Subject: How to assign a default constant value in a function declaration In-Reply-To: References: Message-ID: Vineet Jain wrote: > The following does not work although it seems like something you should be > able to do. > > def someFunction(option=Constants.DEFAULT_VALUE): Please post the actual error traceback you are getting, and a better description of "does not work". Your problem could be just about anything at this point... -Peter From jbperez808 at wahoo.com Tue Apr 27 00:45:21 2004 From: jbperez808 at wahoo.com (Jon Perez) Date: 27 Apr 2004 04:45:21 GMT Subject: CPU usage of Python interpreter doing empty while loop under XP Message-ID: When you run an empty while loop under Python [with the interpreter at its default Normal Priority], it slows down the rest of the system. Is this normal? And should it be something that needs to be corrected? [Note: I'm using ActiveState Python 2.3.2 Build 232] From no.mail at available.net Sun Apr 25 14:33:24 2004 From: no.mail at available.net (Georgy) Date: Sun, 25 Apr 2004 18:33:24 GMT Subject: Andreas' practical language comparison References: Message-ID: Quick'n'dirty translation of Algol-68 solution: # N queens task * translation from Algol-68 (C) 2004 Georgy # Algol-68; http://www.kochandreas.com/home/language/cases/8QUEENS_A68G.HTM # All: http://www.kochandreas.com/home/language/matrix.htm def solve( n, all_solutions=False ): # solve n-queens problem class Done(Exception): pass n1 = n-1 # some optimization :-) column = [True]*n # available columns diaga = [True]*(n+n1) # available tr-bl diags (c+r) diagb = [True]*(n+n1) # available tl-br diags (c-r) + n-1 position = [0] * n def print_row( q ): # print a row stars = ['*']*n stars[q] = 'Q' for s in stars: print s, print def try_row(r): """try_row(r) -- the first r-1 queens have been placed in the top rows, # column/diaga/diagb record which columns and diagonals are still available. """ for c in range(n): if r >= n: print_row( position[c] ) if c == n1: if all_solutions: print '-'*(n+n1) return else: raise Done elif column[c] and diaga[c+r] and diagb[c-r + n-1]: column[c] = diaga[c+r] = diagb[c-r + n1] = False position[r] = c try_row( r+1 ) column[c] = diaga[c+r] = diagb[c-r + n1] = True try: try_row(0) except Done: pass solve( 8 ) # find one solution; for all solutions: solve( 8, True ) "Andreas Koch" wrote in message news:c6glig$phm$07$4 at news.t-online.com... | Hi all, | | i started a little "practical language comparison" - practical | in the sense that i compare how actual distributions and versions | and their libraries (not abstract language specifications) solve small | test cases like the 8 queens problem. | | Currently there are contributions for 17 different languages, and | none for Phyton (and Lisp. And Forth. And many others ). | If someone is interested in contributing a few implementations, | please have a look at: | | http://www.kochandreas.com/home/language/lang.htm | | and mail me your code snippets (or critics) or post them here. | | thanks a lot, | -- | Andreas | He screamed: THIS IS SIG! From roy at panix.com Fri Apr 9 09:42:01 2004 From: roy at panix.com (Roy Smith) Date: Fri, 09 Apr 2004 09:42:01 -0400 Subject: List vs tuples References: <107bf8q8fhsmg5e@news.supernews.com> <7in05lfpqt.fsf@enark.csis.hku.hk> Message-ID: Isaac To wrote: > And you can use a list here as well. Indeed, if you want to emulate C > struct, you probably will use list instead of tuples, since in C, structs > are mutable. It's a bit of a misnomer to say that tuples (or lists) emulate C structs. You access the elements of a struct by name, but you access the elements of a tuple by index. A much better emulation of a C struct is a degenerate class with no methods. If I wanted to emulate: struct myData { int x; int y; } datum = {1, 42}; I'd do something like: class myData: pass datum = myData() datum.x = 1 datum.y = 42 The reason people sometimes think of tuples as struct-like is because they are often used to return multiple values from functions. To use the example often cited, you might do: x, y = getCoordinates() where getCoordinates() returns a tuple of two numbers. It sort of looks like a struct because it's got x an y "members", but the x and y names are assigned in the unpacking operation, they're not inherent in the object returned. A more "struct-like" way of doing it would be to have getCoordinates() return something like the myData object shown above. Then you'd have: point = getCoordinates() and you could make use of point.x and point.y in your code. I'm not saying that the idea of returning a tuple and immediately unpacking it isn't handy. It certainly is, and I use it often in the code that I write. But, I think saying that it emulates a C struct gives people the wrong idea of what's going on. From http Sat Apr 3 21:23:11 2004 From: http (Paul Rubin) Date: 03 Apr 2004 18:23:11 -0800 Subject: Python is faster than C References: <406F0907.96F37EA1@tunes.org> <7xy8pcogaa.fsf@ruckus.brouhaha.com> <406F454B.C4CC8063@tunes.org> <7xekr4vdek.fsf@ruckus.brouhaha.com> <406F5E95.EBE6D3E8@tunes.org> Message-ID: <7x65cgqy5s.fsf@ruckus.brouhaha.com> Armin Rigo writes: > Ideally: If you do x=range(100); x[50]='hi' then the interpreter first > builds this optimized range representation and assigns it to x; and when > in the next statement you modify this list x it says 'oops! i cannot do > that with this representation', so it reverts to an array-like > representation (i.e. it creates all 100 elements) and then changes the > 50th. No gain here. If on the other hand you only ever do 'easy' > things with your list, like iterate over it or read elements, then it > can all be done with the range representation, without falling back to > the array representation. Maybe there is something to this. From fredrik at pythonware.com Mon Apr 19 11:10:44 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 19 Apr 2004 17:10:44 +0200 Subject: Threats to the: Daily Python URL! References: <2ae25c6b.0404182250.4c5bc870@posting.google.com> Message-ID: Paddy McCarthy wrote: > Please don't stop the excellent work that you do. > I don't know what threats and insults you suffered but I would like to > ensure you that I for one read the column and value it. the daily URL won't go away. we'll continue to provide fresh links to potentially interesting stuff for as long as we possibly can (if you want old links, use google or gigablast). and in the future, we'll just redirect abusive posts to /dev/null (and it's up to us to decide what's abusive). no need to upset our readers just because we got upset... thanks /F From aahz at pythoncraft.com Fri Apr 2 15:09:37 2004 From: aahz at pythoncraft.com (Aahz) Date: 2 Apr 2004 15:09:37 -0500 Subject: Python conference slogan References: <406D57FF.4040601@mplusr.de> Message-ID: In article , Peter Maas wrote: > >- Unbrace yourself with Python. > >- Python - think without braces Someone (ESR? -- I know I've seen him wear it) made a t-shirt that says, "Life's better without braces". -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "usenet imitates usenet" --Darkhawk From alloydflanagan at comcast.net Fri Apr 23 09:26:50 2004 From: alloydflanagan at comcast.net (A. Lloyd Flanagan) Date: 23 Apr 2004 06:26:50 -0700 Subject: Why we will use obj$func() often References: <84Uhc.22278$dZ1.5087@fed1read04> <8AWhc.23114$dZ1.11070@fed1read04> <40883BFE.B381518A@alcyone.com> <27_hc.23801$dZ1.2716@fed1read04> <40887145.789A2FE8@alcyone.com> Message-ID: "Mark Hahn" wrote in message news:... > I guess I'll go back to the Prothon mailing lists with my tail between my > legs.... Don't do that. It appears that this list is currently hosting even more really grumpy people than usual. :P Don't pay them any attention, maybe they'll go away. From cygnus at cprogrammer.org Sat Apr 10 19:25:00 2004 From: cygnus at cprogrammer.org (Jonathan Daugherty) Date: Sat, 10 Apr 2004 19:25:00 -0400 Subject: Python is the best and most popular general purpose scripting language; the universal scripting language In-Reply-To: <40788033.3030209@prescod.net> References: <20040410225019.GA16891@vulcan.cprogrammer.org> <40788033.3030209@prescod.net> Message-ID: <20040410232500.GB17123@vulcan.cprogrammer.org> # So which is Lisp? Prolog? Smalltalk? ML? I didn't claim that it necessarily holds for every language. :) # A scripting language is a language that makes scripting (gluing together # components) easy. You're defining it in terms of itself; what is scripting? The use of scripting languages, or the accomplishment of tasks quickly and easily? Some would argue the latter can be done with programming languages. # A programming language is a language that makes programming (including # the creation of components) easy. By this metric many languages are both, since the definition is subjective. -- _ ,^. _ ,'/ -' '- \`. / | \ / | \ Jonathan Daugherty | | | | | | | \_,' `._/ | http://www.cprogrammer.org | | \ / `. .' `--._.--' From max_powers280 at hotmail.com Wed Apr 28 04:19:53 2004 From: max_powers280 at hotmail.com (Max Powers) Date: 28 Apr 2004 01:19:53 -0700 Subject: Embedding OCaml within Python Message-ID: <37aad18.0404280019.500e2841@posting.google.com> I've spent an interesting day searching the web for help with calling OCaml functions from a python program and have come to the newsgroup for some advice (unfortunately I'm learning both languages at the same time, so maybe I've missed something obvious!) The situation is this; I've got a large legacy program that is written in ocaml, within which there's a parser. I'd like to be able to call that parser from my python program (actually it's really a GUI using wxPython), rather than reimplement it (and then have to maintain two parsers into the future). I've come across Viper, which looks like a python compiler/interpreter implemented in OCaml, so I imagine that I could get it to do some magic tricks to call a ocaml library from python, but I think that's doomed to failure because of the C extensions of wxPython. I've stumbled across Pycaml, but don't quite understand how to use it to call ocaml from python. Alternatively I think I can wrap the ocaml library in a C wrapper and then call that from python. Can anyone give advice/share experiences? Is combining OCaml with python relatively straightforward with a bit more effort, or am I in for a world of pain? Thanks, Max From simoninusa2001 at yahoo.co.uk Wed Apr 14 14:31:43 2004 From: simoninusa2001 at yahoo.co.uk (simo) Date: 14 Apr 2004 11:31:43 -0700 Subject: Difficulty Finding Python Developers References: <65cbc3dd.0404140641.3501fde8@posting.google.com> Message-ID: <30260531.0404141031.3415b975@posting.google.com> pm_mon at yahoo.com (Paul Morrow) wrote: > We've worked hard to convince our company to migrate our core > applications to Python, and now we're looking for a Python developer > in Atlanta to handle a short-term (approx. 3 month) project. But our > initial searches have been fairly unsuccessful. We haven't actually > posted a job on Monster, but we have been talking with various > headhunters in our area and they don't have many resumes that show > Python experience. An so now, of course, mgt is wondering whether > selecting Python was a mistake. Yes, I'm beginning to think Python isn't as accepted as we think ;o) I'm actually looking for a Python job now (in CA, not Atlanta) and it seems that there's only a few out there, mostly at Google doing SysAdmin stuff! Barely anyone actually lists Python as a main requirement, more like a "nice to have" alongside Perl or C++. I've seen no web development positions or prototyping/testing at all, which seems strange to me, as I mainly use Python for RAD, prototyping C++/Qt apps etc. Guess I'm stuck with the old Perl/PHP etc.... From jacek.generowicz at cern.ch Thu Apr 8 07:35:20 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 08 Apr 2004 13:35:20 +0200 Subject: Indent testers needed (Prothon) References: Message-ID: Jon Perez writes: > Perhaps the pro-spaces people can explain how they deal > with it. Emacs From piotrus at sympatico.ca Sun Apr 11 16:30:08 2004 From: piotrus at sympatico.ca (peter) Date: Sun, 11 Apr 2004 20:30:08 GMT Subject: Best IDE? References: Message-ID: i like eric3 "Stevie_mac" wrote in message news:c5bg1k$25vq$1 at news.wplus.net... > This has prolly been asked 100 times - so please refrain from flaming if you can... > > What's the best MSwindows editor for python? I'm currently using PythonWin (ActiveState) at the moment, its a bit > buggy - but not too bad. I mean, its got autocomplete & tips & help & autoindentaion (not always good tho). > > Thing is, I'm sure there is something better. Is there? > > (is there a VS.NET addin?) > > From guettli at thomas-guettler.de Fri Apr 16 09:09:40 2004 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Fri, 16 Apr 2004 15:09:40 +0200 Subject: (For gurus) Embed functions in webpages like in PHP? References: <5eq4l1-9vm.ln1@pilz.hasos.com> Message-ID: Am Fri, 16 Apr 2004 12:38:16 +0200 schrieb Robert Ferber: > Hi, > > I'm a PHP-programmer who evaluates Python for a new project. > I really like a lot of concepts of Python, especially the shell, but there > is one great feature of PHP which I don't know how to replace in Python: > > For database-intensive webpages, I like to cache the HTML-output on the fly > in the filesystem and put out the file later whenever the same URL is > requested again, for example: The problem with caching: When is the data outdate? You could use this approach: Run a cron-job every hour which does the complicated query which needs long to compute. Dump the result into a file (Look for "pickle" in the module index of the docs). Load this file for every request and insert this into the template. HTH, Thomas From rkern at ucsd.edu Thu Apr 29 17:30:57 2004 From: rkern at ucsd.edu (Robert Kern) Date: Thu, 29 Apr 2004 14:30:57 -0700 Subject: MATLAB2Python In-Reply-To: References: <3064b51d.0404290654.58e59124@posting.google.com> Message-ID: Sarge wrote: >>I have found numerous cases where Python programs run 10-100 >>times slower or more than a comparable Fortran 95 program. > > > Uh-oh. This is not fine. > I want to switch to py in order to achieve more flexibility > especially in the areas of GUIs, distributed computing, and oo- > programming. But I don't want my programs run 100 times slower! > Is it possible to integrate some fortran compiled routines in order > to speed up the more time-consuming steps? Why, yes! http://cens.ioc.ee/projects/f2py2e/ In my experience, the 10-100 factor only arises when you are doing all the looping in Python. If you can utilize Numeric arrays sufficiently, most of the looping goes down into fast C. So be wary of premature optimization: sometimes the Python code will run just as fast or fast enough (or faster!) than calling out to FORTRAN or C or C++. > Thanx, > Sarge > > P.S. I have already tried Fortran95 for a while, but I found it's a > very old-fashioned language, more than Matlab itself, I didn't like > it very much. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From usenet at datahansa.com Tue Apr 20 23:02:27 2004 From: usenet at datahansa.com (Oleg Paraschenko) Date: 20 Apr 2004 20:02:27 -0700 Subject: Python GUI wrapper for a long operation References: <9396ba6f.0404160520.364699c4@posting.google.com> Message-ID: Hello Stewart, stewart at midwinter.ca (Stewart Midwinter) wrote in message news:<9396ba6f.0404160520.364699c4 at posting.google.com>... > good stuff! > > I'll study your app for some clues for my own situation. I want to > continually get data from a remote server, and then graph values that > I have received, probably using Tkinter canvas widget. Understanding > threads will be helpful for me, so I'll study how you used threads in > your app. I hope that the app will help you. Please beware that documentation describes how things are done, but does not explain why. It is so because some advanceed knowledge is assumed: * threads, * master-view-controller pattern (it is partially used in the code), * logging in a log4j style. > You may want to post your idea on the tkinter mailing list Thanks for the suggestion. Regards, Oleg From newsgroups at jhrothjr.com Fri Apr 9 08:16:24 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Fri, 9 Apr 2004 08:16:24 -0400 Subject: List vs tuples References: <107bf8q8fhsmg5e@news.supernews.com> <7in05lfpqt.fsf@enark.csis.hku.hk> Message-ID: <107d52rib5bfrd7@news.supernews.com> "Isaac To" wrote in message news:7in05lfpqt.fsf at enark.csis.hku.hk... > >>>>> "John" == John Roth writes: > > John> It's a common question. A list is a data structure that is > John> intended to be used with homogenous members; that is, with members > John> of the same type. > > I feel you argument very strange. Even that it might be the original > intention, I see nothing in the language that support your argument. Python is an extremely flexible and dynamic language. There's very little specialized support for a lot of things. That doesn't mean that the language designers didn't have that usage in mind. > In particular, nothing says that tuples cannot be used (or is troublesome to > use) when members are of the same type. And nothing says that lists cannot > be used (or is troublesome to use) when members are of different types. Quite true. So what? Python, by design, does not get in your way when you try to do strange and absurd things. For some people in some situations, those things are undoubtedly going to be the most obvious and reasonable way to approach their problem. > If getTime() give you a list instead, then [hours, minute, second] = > getTime() would still give you the hours, minute and second variables > assigned. True. Again, so what? The basic conceptual issue, which Don Cave explained much better than I did, is that any subsequence of a list is of the same *conceptual* type as the list itself. A subset of the fields of a struct is not of the same conceptual type as the original struct. You cannot take the third element of that time tuple and claim it is the same type (a time of day) as the original. > And you can use a list here as well. Indeed, if you want to emulate C > struct, you probably will use list instead of tuples, since in C, structs > are mutable. By the time I want to actually change the elements, I'm going to want a full fledged object where I can refer to the various elements by name. As far as I'm concerned, tuples serve a fairly well defined niche. I don't think they're all that successful a language feature for a number of reasons, among which are that I much prefer to deal with struct-like constructs by name, not by index position, and growing a tuple into an object is a rather messy proposition for exactly that reason. The other major issue here is that you seem to be trying to argue that tuples are unnecessary because lists can do everything that tuples can, and more (except be used as keys in dicts, besides they take up more memory and they're slower.) I don't buy that line of arguement. A large part of programming is finding ways of expressing intent in the program so you don't wonder what you did six months later. Tuples and lists serve such different conceptual issues that they help expressiveness. John Roth > > Regards, > Isaac. From newsgroups at jhrothjr.com Sun Apr 4 18:41:16 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Sun, 4 Apr 2004 18:41:16 -0400 Subject: Difference between default arguments and keyword arguments References: Message-ID: <10713rf4bjl1bab@news.supernews.com> "Edward Diener" wrote in message news:UmTbc.9904$NL4.4809 at newsread3.news.atl.earthlink.net... > In the tutorial on functions there are sections on default arguments and > keyword arguments, yet I don't see the syntactic difference between them. > For default arguments the tutorial shows: > > def ask_ok(prompt, retries=4, complaint='Yes or no, please!'): > > while for keyword arguments the tutorial shows: > > def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'): > > The syntax 'keyword = value' is used for both as far as I can see. How does > one distinguish between them or are they both part of the same combined > concept, which is: if one calls the function with less than the required > number of arguments but does specify keyword values, those values are used, > else the defaults are supplied. Or is there really a syntactic difference > between default arguments and keyword arguments which I have missed above ? The difference (from the tutorial) is that default arguements apply to the function *definition*, while keyword arguements apply to the function *call*. It's a subtle difference that does seem to be quite easy to miss. In going through the tutorial I also noticed that it explained the * notation, but not the ** notation. I think this also needs to be repaired - if one is in the tutorial, both should be. John Roth From ramen at lackingtalent.com Sat Apr 17 18:43:43 2004 From: ramen at lackingtalent.com (Dave Benjamin) Date: Sat, 17 Apr 2004 22:43:43 -0000 Subject: CamelCase versus wide_names (Prothon) References: Message-ID: In article , Paramjit Oberoi wrote: > * the real problem is the absence of a character for > indicating non-breaking spaces---that's why we have > to use all these damn_WorkArounds. That's so funny; I was just thinking the same thing myself. After all these years, they couldn't just make it easier to press? That's the only problem here, IMHO; I *much* prefer reading lowercase_with_underscores. I never noticed how much until I read this thread, because I have a slight hangover and all these capWordsAreLiterallyGivingMeAHeadache. ;) Out of curiosity, do most of us prefer CamelCaps for class names, regardless of our opinions on variables, functions, methods, etc.? I almost never see class names defined in lowercase unless they're built-in or user-defined types meant to look like they're built-in. -- .:[ dave benjamin: ramen/[sp00] -:- spoomusic.com -:- ramenfest.com ]:. : please talk to your son or daughter about parametric polymorphism. : From missive at frontiernet.net Wed Apr 7 16:40:56 2004 From: missive at frontiernet.net (Lee Harr) Date: Wed, 07 Apr 2004 20:40:56 GMT Subject: Zope - how to import whole folder at once? References: Message-ID: On 2004-04-07, Lukasz Indyk wrote: > im's sorry if it's wrong group to ask this question, but i could not > find any that seems to be better ... > > i have existing web site (written in html and javascript only, no php > etc.), and i want to integrate it with zope. i can add every page, image > etc. one by one using import, but i would like to add it at once. > You might try ZipFolder. Requires you to zip first, but it would work. Or, you could use FTP or WebDAV to do the import. Either way, you may have trouble getting methods to be methods and not just plain files. You can fix that with customized import filters. You are probably best off asking this question on the zope at zope.org mailing list. From Vincent.Raaijmakers at ge.com Mon Apr 5 10:09:28 2004 From: Vincent.Raaijmakers at ge.com (Raaijmakers, Vincent (GE Infrastructure)) Date: Mon, 5 Apr 2004 09:09:28 -0500 Subject: Looking for cookbook/recipe generating multipart web data Message-ID: <971323274247EB44B9A01D0A3B424C8507F5AFA3@FTWMLVEM02.e2k.ad.ge.com> My web server (apache+mod_python) needs to reply on some session with a multipart connection. My idea is to use the content-type of multipart/mixed; boundary=--myboundary The data that I would like to send is a continuous stream of data, divided by that boundary. Well, there are tons of examples on the web how to encode such a stream on the client side, but I can't find an example how to generate this data using mod_python. So for now in the very simple example, my code looks like: req.content_type("multipart/mixed; boundary=--myboundary") while forever: data = "--myboudary\r\n%s" % getData() req.write(data) However, for every req.write, len(data) + lfcr + boundary/data + lfcr is send out and I just want to send boudary/data like I see in existing applications on the web and described in the w3 norms of multipart. What is the correct way of doing this? Where can I find the proper cookbook? Thanks, Vincent From fumanchu at amor.org Wed Apr 7 16:41:38 2004 From: fumanchu at amor.org (Robert Brewer) Date: Wed, 7 Apr 2004 13:41:38 -0700 Subject: list comprehensions Message-ID: Elaine Jackson wrote: > List comprehensions don't work the way you intuitively expect > them to work. > > partitions = lambda n: [[n]]+[[k]+x for x in partitions(n-k) for k in > range(1,n)] > > As defined above, the function raises an exception when you > call it ('k' > referenced before assignment). For the sake of clarity, here > is workable code > expressing the same intention: > > def partitions(n): > reVal=[[n]] > for k in range(1,n): > for x in partitions(n-k): > reVal.append([k]+x) > return reVal > > So I guess what I want to ask is: Can somebody explain the > semantics of list comprehensions to me? Try reversing the loops: >>> partitions = lambda n: [[n]]+[[k]+x for k in range(1,n) for x in partitions(n-k)] >>> partitions(3) [[3], [1, 2], [1, 1, 1], [2, 1]] When writing combined comprehensions, you write the "for" elements in the same order they would be in the expanded code. Robert Brewer MIS Amor Ministries fumanchu at amor.org From no.mail at available.net Thu Apr 29 11:26:07 2004 From: no.mail at available.net (Georgy) Date: Thu, 29 Apr 2004 15:26:07 GMT Subject: static keyword References: Message-ID: "Nick Jacobson" wrote in message news:f8097096.0404290607.78aa9ce3 at posting.google.com... | I believe the following "static" command would be useful in Python. | | def foo(): | static i = [10, 11] | static firstcall = True | if firstcall: | print "First pass" | firstcall = False | i[0] += 1 | print i[0] | foo() | foo() | | | This would output: | | First pass | 11 | 12 | | Just like in C, the variables i and firstcall are only assigned the | first time foo() is called. To get this effect currently, one could | use default arguments or wrapping the whole thing in a class. Both of | these solutions seem like hacks, the above method IMO is more | Pythonic. :) "Pythonic" way is to use the oddity of default arguments: def foo( static_vars = {'i':[10, 11],'firstcall':True} ): if static_vars['firstcall']: print "First pass" static_vars['firstcall'] = False static_vars['i'][0] += 1 print static_vars['i'][0] foo() foo() -- Georgy From michele.simionato at poste.it Tue Apr 6 07:14:52 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 6 Apr 2004 04:14:52 -0700 Subject: Using function parameters to determine method kind References: <4qrzym6e.fsf@telus.net> <95aa1afa.0404050417.2d11b369@posting.google.com> Message-ID: <95aa1afa.0404060314.7bc4541b@posting.google.com> Gon?alo Rodrigues wrote in message news:... > On 5 Apr 2004 05:17:39 -0700, michele.simionato at poste.it (Michele > Simionato) wrote: > > [text snipped] > > >I am also waiting for a better "super" but it seems nobody is talking > >about it. > > Well then, here is your chance: what are the problems of super? I also > found that it has a couple of glitches, but I'd like to know more. > > With my best regards, > G. Rodrigues I wrote once an essay collecting all the shortcomings of "super" I found in my explorations; maybe one day or another I will finish it and post it somewhere. But it requires a good amount of work, so do not expect it too soon. Michele Simionato From joe at notcharles.ca Tue Apr 20 17:09:42 2004 From: joe at notcharles.ca (Joe Mason) Date: Tue, 20 Apr 2004 21:09:42 GMT Subject: Dollar sign ($) on foriegn keyboards? (prothon) References: Message-ID: In article , Fredrik Lundh wrote: > Mark Hahn wrote:? > >> We are considering switching to the dollar sign ($) for self, instead of the >> period ( . ) we are using now in Prothon. > > any reason you cannot set up a mailing list for your little pet > project? you're generating tons of off-topic traffic, and frankly, > I don't think I'm the only one who couldn't care less about your > pre-alpha hack with minimum capabilities. There is a mailing list, it's got tons of traffic, and I think Mark's being pretty judicious in what he posts here. Joe From aku at europe.com Wed Apr 7 05:26:34 2004 From: aku at europe.com (aku) Date: 07 Apr 2004 09:26:34 GMT Subject: design by contract versus doctest References: <407174ea$0$5066$4d4ebb8e@news.nl.uu.net> <4072977b$0$1699$afc38c87@news.easynet.co.uk> <4072a7d3$0$23314$afc38c87@news.easynet.co.uk> <4072c7f0$0$23294$afc38c87@news.easynet.co.uk> Message-ID: <4073c94a$1$5066$4d4ebb8e@news.nl.uu.net> On 2004-04-06, Peter Hickman wrote: > Colin Blackburn wrote: > > Aku is correct, no checks are (necessarily) made by the function in > > installed code. It is the caller's responsibility to satisfy the > > pre-conditions. > > True but the caller does not check the pre-conditions, that is done in > the called. The called does not trust the caller to get things right, > hence the contract. > > > In the installed code the pre-conditions are not necessarily > > implemented therefore the function cannot refuse to run since it does > > not know its pre-condition at this stage. > > I can think of no good reason to turn off checking of the pre and post > conditions unless you can guarantee that the live system will never > encounter a combination of inputs and states that have not already been > tested for. You hardly need DbC for such hubris. Isn't that where doc/unit tests can serve a purpose? In other words: These tests will test many combinations of states and inputs , so that in the live system the DBC can be turned off. > >> Getting the require section to pass is no guarantee that the > >> post-conditions (ensure section) will be met, the do section is code > >> like anything else and may get things wrong. > > > > In correctly developed DbC that is precisely what is guaranteed. The > > post-condition is *guaranteed* if the pre-condition is met. It is a > > design tool. > > Not sure I would want to state that, or rely on it. I would only go as > far as saying what I have tested is guaranteed. But then I am paranoid. "program testing can best show the presence of errors but never their absence" -- E. Dijkstra His formal methods indeed *proved* and *guaranteed* that the postcondition(s) are met IF the precondition(s) were true. From ptmcg at austin.rr._bogus_.com Mon Apr 12 19:12:15 2004 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Mon, 12 Apr 2004 23:12:15 GMT Subject: String + number split References: <2SAec.70005$Id.6002@news-binary.blueyonder.co.uk> Message-ID: "Stevie_mac" wrote in message news:c5epc8$1scu$1 at news.wplus.net... > > It's impossible to say if it's more elegant, since you didn't > > post your attempt. > Yeh, sorry bout tha! > > > (Homework? I'll assume not.) > Only a student of life! > > Heres my solution... > > import string > def makefont(sFontName): > num = [] > nam = [] > acnt = 0 > #reverse it > l = list(sFontName); l.reverse(); ''.join(l) > sFontName = string.join(l,'') > #now loop it while isdigit(), store number, then store alphas > for c in sFontName: > if c.isdigit() and acnt == 0: > num.append(c) > elif c.isalpha() or acnt > 1: > acnt += 1 > nam.append(c) > nam.reverse() > num.reverse() > return (string.join( nam, '' ), int(string.join( num, '' ))) > > Now you see why i was asking for a more elegant solution! > > PS, the number on the end may vary & the _ could be any non alpha char! > > font12 becomes ('font',12) > arial_14 becomes ('arial',14) > arial__8 becomes ('arial',8) > times 6 becomes ('times',6) > (You might find using pyparsing a little more readable than regexp...) ------------------------------------------- # download pyparsing at http://pyparsing.sourceforge.net from pyparsing import Word, alphas, CharsNotIn, nums, Optional str2int = lambda s,l,t: [int(t[0])] fontNameSpec = ( Word(alphas).setResultsName("font") + Optional( CharsNotIn(alphas+nums).suppress() ) + Word(nums).setParseAction(str2int).setResultsName("size") ) testdata = [ "font12", "arial_14", "arial__8", "times 6" ] for fname in testdata: results = fontNameSpec.parseString( fname ) print results for k in results.keys(): print "-", "results."+k, ":", results[k] print ------------------------------------------- prints: ['font', 12] - results.font : font - results.size : 12 ['arial', 14] - results.font : arial - results.size : 14 ['arial', 8] - results.font : arial - results.size : 8 ['times', 6] - results.font : times - results.size : 6 From arigo at tunes.org Sat Apr 3 17:31:59 2004 From: arigo at tunes.org (Armin Rigo) Date: Sat, 3 Apr 2004 23:31:59 +0100 Subject: Python is faster than C In-Reply-To: References: Message-ID: <20040403223159.GA7715@vicky.ecs.soton.ac.uk> Hello Robert, On Sat, Apr 03, 2004 at 12:30:38PM -0800, Robert Brewer wrote: > > enumerate() should return a normal list, and > > it should be someone else's job to ensure that it is > > correctly optimized away if possible > > I'd like to think I'm not understanding your point, but you made it so > danged *clear*. > > Enumerate should absolutely *not* return a normal list. You missed my point indeed. There are two levels here: one is the language specification (the programmer's experience), and one is the CPython implementation. My point is that with some more cleverness in the implementation, iterators would be much less needed at the language specification level (I'm not saying never, I think generators are great, for example). > The use case I think you're missing is when I do not want the enumeration > optimized at all; I want it performed on-the-fly on purpose: This is what I mean by "optimized": done lazily, on-the-fly. I want better implementations of lists, callbacks-on-changes, static bytecode analysis, and more. I don't want another notion than lists at the language level. Your example: > for i, line in enumerate(file('40GB.csv')): is among the easiest to optimize, even if the language specification said that enumerate returns a list. I can think of several ways to do that. For example, because the result of enumerate() is only ever used in a for loop, it knows it can internally return an iterator instead of the whole list. There are some difficulties, but nothing critical. Another option which is harder in CPython but which we are experimenting with in PyPy would be to return a Python object of type 'list' but with a different, lazy implementation. > Forcing enumerate to return a list would drag not only the entire > 40GB.csv into memory, but also the entire set of i. Using an iterator in > this case instead of a list *is* the optimization. Yes, and I'm ranting against the idea that the programmer should be bothered about it, when it could be as efficient automatically. From the programmer's perspective, iterators are mostly like a sequence that you can only access once and in order. A better implementation can figure out for itself when you are only accessing this sequence once and in order. I mean, it is just like range(1000000) which is a list all right, but there is just no reason why this list should consume 4MB of CPython's memory when the same information can be encoded in a couple of ints as long as you don't change the list. The language doesn't need xrange() -- it is an implementation issue that shows up in the Python language. Armin From anton at vredegoor.doge.nl Thu Apr 8 16:59:46 2004 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Thu, 08 Apr 2004 22:59:46 +0200 Subject: Working with bytes. References: <406EE606.4000604@yahoo.com> <406f33b6$0$30963$3a628fcd@reader1.nntp.hccnet.nl> <4071273d$0$132$3a628fcd@reader1.nntp.hccnet.nl> <4071539F.718DBD1A@pobox.com> <40759a1c$0$140$3a628fcd@reader1.nntp.hccnet.nl> Message-ID: <4075bd7d$0$137$3a628fcd@reader2.nntp.hccnet.nl> anton at vredegoor.doge.nl (Anton Vredegoor) wrote: > http://www.faqs.org/rfcs/rfc1924.html Replying to my own post. I was using lowercase letters before uppercase and did some other non compliant things. Because I was using random data I didn't notice. The code below should reproduce the rfc1924 example. Anton from binascii import hexlify from string import digits, ascii_lowercase, ascii_uppercase _rfc1924_letters = ascii_uppercase + ascii_lowercase _rfc1924_chars = digits+_rfc1924_letters+'!#$%&()*+-;<=>?@^_`{|}~' _rfc1924_table = dict([(c,i) for i,c in enumerate(_rfc1924_chars)]) _rfc1924_bases = [85L**i for i in range(19,-1,-1)] def bytes_to_rfc1924(sixteen): res = [] i = 0L for byte in sixteen: i <<= 8 i |= ord(byte) for j in range(20): i,k = divmod(i,85) res.append(_rfc1924_chars[k]) res.reverse() return "".join(res) def rfc1924_to_bytes(twenty): res = [] i = 0L for b,byte in zip(_rfc1924_bases,twenty): i += b * _rfc1924_table[byte] for j in range(16): i,k = divmod(i,256) res.append(chr(k)) res.reverse() return "".join(res) def bytes_as_ipv6(bytes): addr = [bytes[i:i+2] for i in range(0,16,2)] return ":".join(map(hexlify,addr)) def test(): s = "4)+k&C#VzJ4br>0wv%Yp" bytes = rfc1924_to_bytes(s) check = bytes_to_rfc1924(bytes) assert s == check addr = bytes_as_ipv6(bytes) print addr if __name__=='__main__': test() output: 1080:0000:0000:0000:0008:0800:200c:417a From paddy3118 at netscape.net Wed Apr 21 19:23:50 2004 From: paddy3118 at netscape.net (Paddy McCarthy) Date: 21 Apr 2004 16:23:50 -0700 Subject: [PROTHON] Subject groupings Message-ID: <2ae25c6b.0404211523.4d153393@posting.google.com> Hi, I have noticed the use of '['']' in the far left of the subject field to denote a grouping of threads in other newsgroups and I propose that starters of threads on prothon might start the subject with [PROTHON] ... Over time, other newsgroups have collected a few such group headings and publish them in their FAQ. P.S. it is a *suggestion* . Cheers, Pad. From FBatista at uniFON.com.ar Mon Apr 19 12:27:44 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Mon, 19 Apr 2004 13:27:44 -0300 Subject: Problems using modulo Message-ID: [Brian Gough] #- > Results: #- > 5.9 mod 2.0 = 1.9 #- > 6.0 mod 2.0 = 2.0 !!!!!! #- > 6.1 mod 2.0 = 0.1 #- > #- > I don't know much about how Python does its floating point, but it #- > seems like a bug to me ? #- #- This is a common "feature" of floating-point arithmetic. #- 0.1 does not #- have an exact machine representation in binary, so the numbers #- displayed are not exact (e.g. 6.0 is actually 5.9999999... with a #- difference O(10^-15)). There is an appendix in the Python tutorial #- which discusses this, with more examples. You can read also PEP 327 where I propose the Decimal data type, a decimal floating point. #- > What is the best workaround so that I can get my code working as #- > desired ? #- > (ie I just want to tell whether my time "t" is an exact multiple of #- > the time interval, 2.0 seconds in this case). #- #- For exact arithmetic, work with integers (e.g. in this case multiply #- everything 10) or compute the difference from zero in the modulus, d, #- #- s = t % interval #- d = min (s, interval-s) #- #- and compare it with a small tolerance, e.g. 1e-10 or something #- appropriate to your problem. HTH. ...or work with Decimal. . Facundo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA La informaci?n contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener informaci?n confidencial o propietaria, cuya divulgaci?n es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no est? autorizado a divulgar, copiar, distribuir o retener informaci?n (o parte de ella) contenida en este mensaje. Por favor notif?quenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magn?tico) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telef?nica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electr?nicos pueden ser alterados, motivo por el cual Telef?nica Comunicaciones Personales S.A. no aceptar? ninguna obligaci?n cualquiera sea el resultante de este mensaje. Muchas Gracias. -------------- next part -------------- An HTML attachment was scrubbed... URL: From matthew at coredumps.net Thu Apr 15 06:47:06 2004 From: matthew at coredumps.net (Matthew) Date: 15 Apr 2004 03:47:06 -0700 Subject: [Newbie Q on String & List Manipulation] Message-ID: <567a7c35.0404150247.7809bef5@posting.google.com> Hello All, today is the first day i try to programming in Python, my assignment is, write a silly script that probably will run a few times a day to check if the Gmail services is ready or not. ;) however, i encountered some problem when playing with the list and string. i'm using Python 2.2.2 on Redhat. if i write something like: a = "one" b = "two" a += b print a i will get: onetwo ok, seems quite ok, however, not sure why it doesn't work on my silly Gmail script (pls refer to my script belows): for item in thecookies: mycookies += item print mycookies i have exactly 4 items in the "thecookies" list, however, when printing out "mycookies", it just show the last item (in fact, seems the 4 items have been overlapped each others). could somebody pls kindly take a look at my silly script and gimme some advise? thanks very much in advance! :) --- matthew import re import string import sys import urllib user = "da at email.address" pswd = "dapassword" schm = "https://" host = "www.google.com" path = "/accounts/ServiceLoginBoxAuth" qstr = {"service" : "mail", \ "continue" : "http://gmail.google.com/", \ "Email" : user, \ "Passwd" : pswd} qstr = urllib.urlencode(qstr) url = schm + host + path + "?" + qstr conn = urllib.urlopen(url) headers = conn.info().headers response = conn.read() thecookies = [] # # extract all the Set-Cookie from the HTTP response header and put it in thecookies # for header in headers: matches = re.compile("^Set-Cookie: (.*)$").search(header) if matches: thecookies.append(matches.group(1)) # # make sure we've grep the SID or die # foundsessionid = 0 for item in thecookies: if re.compile("^SID").search(item): foundsessionid = 1 break if not foundsessionid: print "> Failded to retrieve the \"SID\" cookie" sys.exit() # # grep the GV cookie from the HTTP response or die # matches = re.compile("^\s*var cookieVal= \"(.*)\";.*", re.M).search(response) if matches: thecookies.append("GV=" + matches.group(1)) else: print "> Failed to retrieve the \"GV\" cookie" sys.exit() print thecookies mycookies = "" for item in thecookies: mycookies += item print mycookies # # still got many things to do right here... # sys.exit() From ep at epoz.org Fri Apr 9 05:29:48 2004 From: ep at epoz.org (Etienne Posthumus) Date: Fri, 9 Apr 2004 11:29:48 +0200 Subject: xmlrpc, httplib and SSL (HTTP 1.1 XMLRPC client) In-Reply-To: <56vtj1-2rp.ln1@home.rogerbinns.com> References: <56vtj1-2rp.ln1@home.rogerbinns.com> Message-ID: <71CA9CAF-8A08-11D8-8D68-0003935458F6@epoz.org> On Apr 1, 2004, at 7:13 PM, Roger Binns wrote: > Are you sure you are actually getting persistent connections? The > code will auto-close and auto-open the connection even just keeping > the same HTTP connection object. Yes, I definitely get persistent connections. I sat staring at the server logs, the requests kept coming from the same source-port. Which code do you refer to that auto-closes, and auto-opens the connection? If you use that Persistent transport it skips the .close() after each request part. > In order for the connection to not be auto-closed, the remote end > must return a HTTP/1.1 response (see > httplib.HTTPResponse._check_close). Also remember to include a Content-Length header. That one bit me before, in some of my replies I had forgotten to include it in my server. You can then very clearly see the clients dropping the connection, and rightly so. > If your server end is Python, then it will always close the connection > unless the request was HTTP/1.1 *and* a 'Connection: keep-alive' header > was sent, which the Python client does not do. Which Python client do you refer to? I presume you mean the standard xmlrpclib client, and then yes, it explicitly does HTTP 1.0. BTW, in HTTP 1.1 keeping connections open is the default, so you do NOT have to specify Connection: keep-alive in the header. Although it is the default to keep the connections open, the client or the server can close them at any time. --- Etienne Posthumus Amsterdam, Nederland Python, Zope, Quixote - programmer for hire... but not for sale. From dek at pabst.lbl.gov Mon Apr 5 16:28:38 2004 From: dek at pabst.lbl.gov (David E. Konerding DSD staff) Date: Mon, 5 Apr 2004 20:28:38 +0000 (UTC) Subject: allocate TWO interpreters in a C program? References: <4Vicc.16932$lt2.13201@newsread1.news.pas.earthlink.net> Message-ID: In article <4Vicc.16932$lt2.13201 at newsread1.news.pas.earthlink.net>, Andrew Dalke wrote: > Torsten Mohr: >> i can embed Perl into a C program and allocate MORE THAN ONE >> interpreter if i want to. They are independent from each other. >> >> Is this also possible in Python? > > As no one else has answered, I'll take a stab at it, on the assumption > that a wrong answer will be corrected. > > No, it isn't possible. Various bits of state, like exceptions, are stored > in global variable (actually thread global I think). I think there is other > global state, like sys.modules which contains all of the imported modules. > > There are experimental systems like PyPy which can provide > independent interpreters but I know little about them. > > Andrew > dalke at dalkescientific.com > > Actually, more than one *sub*-interpreter can be instantiated in a single C program. http://python.org/doc/current/api/initialization.html However, upon close reading, it's hardly as independent as you might hope. But for fun also read: http://www.python.org/peps/pep-0311.html since it seems to imply that multiple subinterpreters are not a frequently used feature. Dave From ramen at lackingtalent.com Mon Apr 19 12:55:23 2004 From: ramen at lackingtalent.com (Dave Benjamin) Date: Mon, 19 Apr 2004 16:55:23 -0000 Subject: Difficulty finding Python employer References: <407e9164$0$122$3a628fcd@reader3.nntp.hccnet.nl> <40824dca$0$136$3a628fcd@reader1.nntp.hccnet.nl> Message-ID: In article <40824dca$0$136$3a628fcd at reader1.nntp.hccnet.nl>, Anton Vredegoor wrote: > Dave Benjamin: > >>> Will send no resume. Can't stand hype. Must telecommute. >> >>That could explain your difficulty... > > Yes, my resume is less than useless. An academic education as a social > scientist, a few years work at a university followed by a lot of years > of unemployment, very lightly sprinkled by short term programming > jobs. You could always invent a programming language; it seems to have helped Guido segue into the commercial work force. =) The light sprinkling of temporary work will probably hurt you. I got a hard time from employers for that, even though a) I was in school, b) short-term job-hopping was practically the norm for the tech industry until a few years ago. But in any case, I didn't mean to mock you, I honestly thought you were either joking or that I was misreading or misunderstanding your message. > The other conditions I also can't do much about except switching > identity and relocating. Well, if you truly must telecommute, I can't say that you picked a particularly bad field. =) Also, keep in mind that an open source project can make a nice resume builder, and give you experience, and give you the opportunity to network (in the social sense) and meet people that just might be instrumental to your future. Best wishes, Dave -- .:[ dave benjamin: ramen/[sp00] -:- spoomusic.com -:- ramenfest.com ]:. : please talk to your son or daughter about parametric polymorphism. : From JimJJewett at yahoo.com Mon Apr 5 20:36:21 2004 From: JimJJewett at yahoo.com (Jim Jewett) Date: 5 Apr 2004 17:36:21 -0700 Subject: ANN: easylog Message-ID: The standard library logging package is very powerful, but does not scale *down* well. Any configuration -- even just saving messages to a file rather than the console -- requires a fair amount of setup or glue code. easylog wraps the standard library, to minimize the amount of logging-specific code in your own script or application. >>> from easylog import critical, error, warning, debug, info >>> debug("getFoo requesting %d %s", 42, "answers") >>> error("getFoo says %d of those %s are lousy!", 19, "answers") ERROR:easylog.easylog:getFoo says 19 of those answers are lousy! Both messages are captured in the logfile, but only the error is shown onscreen. If you want to change the logfile name/which messages are captured/the output format, etc, you can do that with a single call. Alpha version 0.2.0 is available under the Python Software Foundation License at http://sourceforge.net/projects/easylog/ Please send comments to JimJJewett at yahoo.com.

easylog 0.2.0 works with the standard logging package to minimize logging-specific code in your application.. (05-04-04) From j.ezequiel at spitech.com Wed Apr 28 01:41:32 2004 From: j.ezequiel at spitech.com (Ezequiel, Justin) Date: Wed, 28 Apr 2004 13:41:32 +0800 Subject: wxpython + py2exe + innosetup Message-ID: <2484E6467140254CB22A328F5E18A23501574C11@SPI-MAIL2003.SPITECH.COM> FWIW, I had a similar problem but was not using INNO; just py2exe, COM, anygui, and easygui. My problem was fixed when I included PythonCOM22.dll in the distribution. Python 2.2.2 (#37, Oct 14 2002, 17:02:34) [MSC 32 bit (Intel)] on win32 py2exe version 0.4.0 From __peter__ at web.de Wed Apr 21 13:05:08 2004 From: __peter__ at web.de (Peter Otten) Date: Wed, 21 Apr 2004 19:05:08 +0200 Subject: Optimizing a text statistics function References: Message-ID: Nickolay Kolev wrote: > I am currently writing some simple functions in the process of learning > Python. I have a task where the program has to read in a text file and > display some statistics about the tokens in that file. > > The text I have been feeding it is Dickens' David Copperfield. > > It is really simple - it reads the file in memory, splits it on > whitespace, strips punctuation characters and transforms all remaining > elements to lowercase. It then looks through what has been left and > creates a list of tuples (count, word) which contain each unique word > and the number of time it appears in the text. > > The code (~30 lines and easy to read :-) can be found at > http://www.uni-bonn.de/~nmkolev/python/textStats.py > > I am now looking for a way to make the whole thing run faster. I have > already made many changes since the initial version, realising many > mistakes. As I do not think of anything else, I thought I would ask the > more knowledgeable. > > I find the two loops through the initial list a bit troubling. Could > this be avoided? > > Any other remarks and suggestions will also be greatly appreciated. I'd probably do this with regular expressions, either with r.split() where r matches the spaces between the words or r.finditer() where r matches the words. But since you were asking for speed, another approach might be faster. First I normalize all non-word characters to space and all alpha-chars to lowercase. Note that this may yield different word frequencies as e.g. "two.words" will be 2 words with my and one word with your approach. from __future__ import division import string, sys def main(filename): # caveat: assumes one byte per character repl = string.whitespace + string.punctuation tr = string.maketrans(repl, len(repl)*" ").lower() assert len(tr) == 256 words = file(filename).read().translate(tr).split() histogram = {} wordCount = len(words) for word in words: histogram[word] = histogram.get(word, 0) + 1 wordCountList = [(c, w) for w, c in histogram.items()] wordCountList.sort() wordCountList.reverse() print for freq, word in wordCountList[:10]: print '%15r %5d %5.2f%%' % (word, freq, freq / wordCount * 100) print if __name__ == "__main__": main(sys.argv[1]) Other remarks: Speed is not that important most of the time. Psyco offers speed for free. You might consider switching to 4-space indent. Peter From cliechti at gmx.net Wed Apr 28 17:16:41 2004 From: cliechti at gmx.net (Chris Liechti) Date: Wed, 28 Apr 2004 21:16:41 +0000 (UTC) Subject: Parallel port interface References: Message-ID: Les Smithson wrote in news:m31xm8vy96.fsf at hare.demon.co.uk: > Would ioport.py help? See: > http://www.hare.demon.co.uk/ioport/ioport.html. > > Its Linux only atm, but it wouldn't be hard to port to Windows. I > might even do it myself! you need to make a compiled extension with the inb and outb functions. i have done that for pyparallel. thats the easy part, then you have to find a driver that allows io port access on win NT/2k/XP. i used giveio.sys and you'll find it on the page below too. http://pyserial.sf.net/pyparallel.html chris -- Chris http://pyserial.sf.net From jbore at tjtech.com Tue Apr 13 12:52:08 2004 From: jbore at tjtech.com (Joseph T. Bore) Date: Tue, 13 Apr 2004 16:52:08 GMT Subject: interpreter limits Message-ID: I'm embedding python in my app, and I'm using it as a scripting language for it, everything works great. My only concern is how to handle the possibility that a user accidentally puts an infinite loop in the code that gets called by the app. Something as simple as a function that has as it's body: while 1: pass would require the application to be killed. Hopefully this will rarely happen, but it's a *real* and unacceptable possibility. Looking around, it seems that this has occasionally been brought up by others, but no solution has been arrived at. I even looked at grail, figuring that perhaps there were some controls put in for the python applets it would load, but no luck there either it seems. I dont know a heck of a lot about the implementation of the interpreter/vm but would it be possible to implement exec or eval with an optional argument, that argument would be a maximum number of byte codes the interpreter would execute before throwing an exception. this would eliminate the out of control case where a function runs the above code and never returns. you could make the value large enough to handle just about everything except for infinite loops. something like: try: exec(codeToExecute, maxTicks = 100000) except InterpreterLimitReached: print "your code ran too long" Anyone have any idea if this is at all implementable? jbore From cookedm+news at physics.mcmaster.ca Thu Apr 8 16:07:37 2004 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Thu, 08 Apr 2004 16:07:37 -0400 Subject: surface fitting library for Python? References: <40748902$0$17253$a1866201@newsreader.visi.com> Message-ID: At some point, Grant Edwards wrote: > I'm looking for a surface fitting library for Python. > > Something like the least-squares module in scientific python, > except I want to fit a surface (z = f(x,y)) instead of a curve > (y = f(x)). You mean Konrad Hinsen's ScientificPython? Scientific.Functions.LeastSquares.leastSquaresFit should still work for you. You just need to make your data a list of tuples of (x,y) and z. Example: from Scientific.Functions.LeastSquares import leastSquaresFit data = [ ((x1,y1), z1), ((x2,y2), z2), ...] parameters = [initialc0, initialc1, initialc2] def model(params, xy): c0, c1, c2 = params x, y = xy return c0*x + c1*sin(c2*y) params, chisquared = leastSquaresFit(model, parameters, data) If your model isn't amiable to having derivatives taken, you might check out the wrapping by Robert Kern of ODRPACK: http://starship.python.net/crew/kernr/Projects.html I've used this successfully. -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From grey at despair.dmiyu.org Mon Apr 26 16:22:26 2004 From: grey at despair.dmiyu.org (Steve Lamb) Date: Mon, 26 Apr 2004 20:22:26 GMT Subject: How's ruby compare to it older brother python References: <108pvmgl0h7m3ea@news.supernews.com> Message-ID: On 2004-04-26, Phil Tomson wrote: > Well, there is one big difference syntactically: Python uses indentation > as syntax and Ruby doesn't. Personally I don't prefer Python's > 'indentation-as-syntax' since it means that syntactically significant > pieces of my code are invisible and if the tab settings in my editor are > not the same as yours it can make it difficult to share code (or even Why is this trotted out every time? I guarentee that my code will look perfectly fine in your editor. I cannot guarentee the reverse as while you might have a penchant for tabs I do not. I am not alone in that regard. Here's a snippet from the Python style guide: Tabs or Spaces? Never mix tabs and spaces. The most popular way of indenting Python is with spaces only. The second-most popular way is with tabs only. Code indented with a mixture of tabs and spaces should be converted to using spaces exclusively. (In Emacs, select the whole buffer and hit ESC-x untabify.) When invoking the python command line interpreter with the -t option, it issues warnings about code that illegally mixes tabs and spaces. When using -tt these warnings become errors. These options are highly recommended! So unless your tab setting is 0 syntactically significant pieces of code should always have a different indention level. Furthermore if the program(mers) follow the style guide then that is a non-issue. -- Steve C. Lamb | I'm your priest, I'm your shrink, I'm your PGP Key: 8B6E99C5 | main connection to the switchboard of souls. -------------------------------+--------------------------------------------- From solution88pro at hotmail.com Mon Apr 5 21:48:06 2004 From: solution88pro at hotmail.com (88Pro) Date: 5 Apr 2004 18:48:06 -0700 Subject: Can someone give me a short explanation? References: Message-ID: <98cb6fab.0404051748.465489da@posting.google.com> Thanks all of you explained me. Now I understand more clearly than every before. Regards Senthoor "Daniel Dittmar" wrote in message news:... > Senthoorkumaran Punniamoorthy wrote: > > I found this code in the book text processing with Python. But having > > little difficulty understanding how exactly it works and what should > > be passed as argument? Can someone decode this for me please? > > > > apply_each = lambda fns, args=[]: map(apply, fns, [args]*len(fns)) > > def apply_each (fns, args = []): > return map (apply, fns, [args]*len(fns)) > > map(...) > map(function, sequence[, sequence, ...]) -> list > > Return a list of the results of applying the function to the items of > the argument sequence(s). If more than one sequence is given, the > function is called with an argument list consisting of the corresponding > item of each sequence, substituting None for missing values when not all > sequences have the same length. If the function is None, return a list > of > the items of the sequence (or a list of tuples if more than one > sequence). > > so apply_each ([func1, func2, func3], [arg1, arg2]) > is the same as > [func1 (arg1, arg2), func2 (arg1, arg2), func3 (arg1, arg)] > > or using list comprehension > [func (arg1, arg2) for func in [func1, func2, func3]) > > Daniel From grante at visi.com Wed Apr 28 00:17:37 2004 From: grante at visi.com (Grant Edwards) Date: 28 Apr 2004 04:17:37 GMT Subject: Don't understand wxPython ids References: <408ed938$0$17263$a1866201@newsreader.visi.com> Message-ID: <408f3061$0$17258$a1866201@newsreader.visi.com> In article , Greg Krohn wrote: > AFAIK, yes. But then again, I don't know much. Note that you can use -1 > as the id and the button will create it's own unique id for you. Then > all you have to do is call button.GetId() whenever you need it. Ya know, now that you mention it, I think I actually new that once a couple years back. >> Can somebody clue me in on the advantages of the >> progrmmer-generated integer id numbers for objects? > > In the new wxPython (2.5.1.5) there's an easier way to bind events > without using ids at all using widget.Bind, like this: > > import wx > > class MyFrame(wx.Frame): > def __init__(self, *args, **kwargs): > wx.Frame.__init__(self, *args, **kwargs) > > self.button = wx.Button(self, -1, "What's my id?") > self.button.Bind(wx.EVT_BUTTON, self.OnButtonPress) That's definitely getting closer to what I would expect in something designed in the last 15-20 years, though passing the binding as a parameter to wx.Button() sure seems like the obvious solution for 90% of the cases I run into. Perhaps I'm too used to Tk. > I can only think of one reasn why they chose to use ids in the first > place. Assigning many objects the same id allows you to use one EVT_* > call for those objects. But is that really a useful feature? Who knows? That's about the only thing I could think of. The few situations where I'd have wanted to do someting like that I'd gladly put a for-loop iterating over a list of objects in exchange for being able to use single-line of code the other 90% of the time. -- Grant Edwards grante Yow! I'm young... I'm at HEALTHY... I can HIKE visi.com THRU CAPT GROGAN'S LUMBAR REGIONS! From jjl at pobox.com Thu Apr 29 16:30:33 2004 From: jjl at pobox.com (John J. Lee) Date: 29 Apr 2004 21:30:33 +0100 Subject: 404 errors References: <408dcc25$0$16577$5a62ac22@freenews.iinet.net.au> Message-ID: <87fzam5xxy.fsf@pobox.com> Ivan Karajas writes: > On Tue, 27 Apr 2004 10:46:47 +0200, Tut wrote: > > > Tue, 27 Apr 2004 11:00:57 +0800, Derek Fountain wrote: > > > >> Some servers respond with a nicely formatted bit of HTML explaining the > >> problem, which is fine for a human, but not for a script. Is there some > >> flag or something definitive on the response which says "this is a 404 > >> error"? > > > > Maybe catch the urllib2.HTTPError? > > This kind of answers the question. urllib will let you read whatever it > receives, regardless of the HTTP status; you need to use urllib2 if you > want to find out the status code when a request results in an error (any > HTTP status beginning with a 4 or 5). This can be done like so: FWIW, note that urllib2's own idea of an error (ie. something for which it throws a response object as an HTTPError exception rather than returning it) is: 'anything other than 200 is an error'. The only exceptions are where some responses happen to be handled by urllib2 handlers (eg. 302), or at a lower level by httplib (eg. 100). > import urllib2 > try: > asock = urllib2.urlopen("http://www.foo.com/qwerty.html") > except urllib2.HTTPError, e: > print e.code > > The value in urllib2.HTTPError.code comes from the first line of the web > server's HTTP response, just before the headers begin, e.g. "HTTP/1.1 200 > OK", or "HTTP/1.1 404 Not Found". > > One thing you need to be aware of is that some web sites don't behave as > you would expect them to; e.g. responding with a redirection rather than a > 404 error when you when you request a page that doesn't exist. In these > cases you might still have to rely on some clever scripting. The following kind of functionality is in urllib2 in Python 2.4 (there are some loose ends, which I will tie up soon). It's slightly simpler in 2.4 than in my ClientCookie clone of that module, but (UNTESTED): import ClientCookie from ClientCookie._Util import response_seek_wrapper class BadResponseProcessor(ClientCookie.BaseProcessor): # Convert apparently-successful 200 OK or 30x redirection responses to 404s # iff they contain tell-tale text that indicates failure. def __init__(self, diagnostic_text): self.diagnostic_text = diagnostic_text def http_response(self, request, response): if not hasattr(response, "seek"): response = response_seek_wrapper(response) if response.code in [200, 301, 302, 303, 307]: ct = response.info().getheaders("content-type") if ct and ct[0].startswith("text/html"): try: data = response.read(4096) if self.diagnostic_text in data: response.code = 404 finally: response.seek(0) return response https_response = http_response brp = BadResponseProcessor("Whoops, an error occurred.") opener = ClientCookie.build_opener(brp) r = opener.open("http://nonstandard.com/bad/url") assert r.code == 404 Hmm, looking at that, I suppose it would be better done *after* redirection (which is quite possible, with the modifications I've made, without needing any heavy subclassing or other hacks -- use the processor_order attribute). You'd then just check for 200 rather than 200 or 30x in the code above. A similar problem: as I mention above, by default, urllib2 only returns 200 responses, and always raises an exception for other HTTP response codes. Occasionally, it's much more convenient to have an OpenerDirector that behaves differently: class HTTPErrorProcessor(ClientCookie.HTTPErrorProcessor): # return most error responses rather than raising an exception def http_response(self, request, response): code, msg, hdrs = response.code, response.msg, response.info() category = divmod(code, 100)[0] # eg. 200 --> 2 if category not in [2, 4, 5] or code in [401, 407]: response = self.parent.error( 'http', request, response, code, msg, hdrs) return response https_response = http_response John From python at simon.vc Fri Apr 9 06:54:46 2004 From: python at simon.vc (SimonVC) Date: 9 Apr 2004 03:54:46 -0700 Subject: getattr() in default namespace. References: <60dfb6f6.0404081110.5218466b@posting.google.com> Message-ID: That worked nicely. Cheers Carl. (and everyone else who replied.) > >>> a = 1 > >>> namespace = __import__(__name__) > >>> getattr(namespace,'a') > 1 From premshree_python at yahoo.co.in Fri Apr 2 14:32:00 2004 From: premshree_python at yahoo.co.in (=?iso-8859-1?q?Premshree=20Pillai?=) Date: Fri, 2 Apr 2004 20:32:00 +0100 (BST) Subject: makeExe.bat - An explanation Message-ID: <20040402193200.3055.qmail@web8312.mail.in.yahoo.com> Hello, An explanation of makeExe.bat (http://premshree.resource-locator.com/j/post.php?id=152) has been appended to (http://www.devx.com/opensource/Article/20247/0/page/3) "Create Python Executables Automatically" (http://www.devx.com/opensource/Article/20247/). -Premshree Pillai ===== -Premshree [http://www.qiksearch.com/] ________________________________________________________________________ Yahoo! India Insurance Special: Be informed on the best policies, services, tools and more. Go to: http://in.insurance.yahoo.com/licspecial/index.html From peter at engcorp.com Tue Apr 27 14:40:57 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 27 Apr 2004 14:40:57 -0400 Subject: Is Perl *that* good? In-Reply-To: <108t1tlhnhi46ee@corp.supernews.com> References: <108t1tlhnhi46ee@corp.supernews.com> Message-ID: Michael Geary wrote: > Robert Brewer wrote: > >>I wish Python had won, as well. But time is linear (in >>my mind). I now wish only that we could leverage the >>similarity of JS and Python (execution and binding >>models) into more Python users. Marketing needs >>to run with the line, "So you know Javascript? Then >>you know Python!" > > That was my impression of Python when I started using it after some > extensive JavaScript work: "Cool! It's just like JavaScript but with a lot > more goodies!" The two languages struck me as very similar. Even though > JavaScript *looks* like C, it *works* much more like Python. I learned Javascript after learning Python. (That is, up until that point, I coded Javascript like a script kiddie, copying and tweaking without understanding.) It was the similarities with Python that actually let me start to respect it somewhat. I thought "Cool! It's just like Python but with less power and an uglier syntax!" :-) -Peter From hwlgw at hotmail.com Tue Apr 20 04:38:36 2004 From: hwlgw at hotmail.com (Will Stuyvesant) Date: 20 Apr 2004 01:38:36 -0700 Subject: AOP use cases References: <84fc4588.0404140106.3fa0c55@posting.google.com> <0pydnSB4WYuieuLdRVn-hQ@powergate.ca> <1082n594lndh27f@news.supernews.com> <87pta6qnw4.fsf@pobox.com> <1083nja30c9s2a4@news.supernews.com> <1087i9rgum1g2cb@news.supernews.com> Message-ID: > [Daniel Dittmar] > class SynchronizedCall: > def __init__ (self, lock, method): > self.lock = lock > self.method = method > > def __call__ (self, *args, **keywargs): > self.lock.acquire () > try: > self.method (*args, *keywargs) > finally: > self.lock.release () > > obj.append = SynchronizedCall (obj.lock, obj.append) > # the following calls to obj.append () will be synchronized That is a nice example. People (Peter Hansen, me, ...) asked earlier in this and the previous thread for AOP usage examples/patterns/... and this is one. The academic AOP examples I saw could not convince me, but perhaps somebody who uses AOP-like techniques a lot in practice (not me) can collect such code examples like the above for something like a Python aop-module? I think that would be interesting and possibly highly useful. the-size-of-the-python-aop-module-would-convert-more-java-peeps-ly y'rs - will From reverse.ku.oc.issolok at nothypgnal.delrest.co.uk Tue Apr 27 09:00:17 2004 From: reverse.ku.oc.issolok at nothypgnal.delrest.co.uk (Paul Sweeney) Date: Tue, 27 Apr 2004 13:00:17 +0000 (UTC) Subject: sending an object - twisted or what? Message-ID: I wish to send an object (only one class, but many objects) from python running on one computer to python on another. It will be over the internet, so needs to be 'secure'. Is twisted the only way to go, or is there something simpler for my app? The code for twisted is fairly simple (I found http://twistedmatrix.com/documents/current/howto/pb-copyable) but the library is a bit heavy and I don't want to go through the hassle of dependencies/compiling etc if there's a simpler way. thx in advance Paul From miki.tebeka at zoran.com Sun Apr 18 04:43:18 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Sun, 18 Apr 2004 10:43:18 +0200 Subject: Catching console output interactively In-Reply-To: References: Message-ID: <40823FA6.2040502@zoran.com> Hello Rob, > I'd like to be able to trap console output as the user writes interactively. > For example if the user press the up or down keys I'd like to be able to > catch this and return the last executed command (a bit like the bash_history > idea). Can anyone point me in the right direction? Depending on what you'd like to do you can try: "curses" module (available only on unix like systems) wxPython PyGame HTH. Miki From stuff at allthingswriting.com Wed Apr 14 15:38:27 2004 From: stuff at allthingswriting.com (Zanke) Date: 14 Apr 2004 12:38:27 -0700 Subject: Very Interesting Project for Python Person Message-ID: <854e9e55.0404141138.416c9ab1@posting.google.com> This is part of an open source project at SourceForge. The Python program would have to call some methods that were compiled from C source code. We need someone to add 2D graphics & GUI to an existing C program. The main program, graphics, & GUI would be python/tKinter. The graphics would show the path of a virtual sailboat, which has a robot at the helm. The robot is actually an Artificial Neural Network (ANN). We use neuroevolution to discover a competent ANN yachtsman. Visit http://annevolve.sourceforge.net to learn more; especially the sourceforge link. Mitchell Timin From adalke at mindspring.com Thu Apr 1 10:48:16 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Thu, 01 Apr 2004 15:48:16 GMT Subject: From python-dev, space vs. tab controversy finally settled References: Message-ID: <4RWac.11136$lt2.2060@newsread1.news.pas.earthlink.net> Josiah Carlson: > Great april fools joke, but no such conversation has gone on in > Python-Dev in the last 3 months. You're right, there was a typo. It should have been python-internals. That started last fall because there was too much noise and riff-raff on python-dev. Andrew dalke at dalkescientific.com From nemesis at nowhere.invalid Sun Apr 25 11:14:06 2004 From: nemesis at nowhere.invalid (Nemesis) Date: Sun, 25 Apr 2004 15:14:06 GMT Subject: [ANN] XPN 0.2.6 References: <7kbd6c.fu1.ln@nemesis.homeinvalid> Message-ID: <13jg6c.pv1.ln@nemesis.homeinvalid> Mentre io pensavo ad una intro simpatica "Ed Suominen" scriveva: >> XPN is a newsreader written in Python+GTK with unicode support. > I was very impressed by this application. It's a great testimony to the > power of Python. Thank you very much. :-) Python is a GREAT tool. -- Im not as think as you drunk i am. |\ | |HomePage : http://nem01.altervista.org | \|emesis |XPN (my nr): http://xpn.altervista.org From "schwartz+ at usenet " at bio.cse.psu.edu Tue Apr 13 23:22:06 2004 From: "schwartz+ at usenet " at bio.cse.psu.edu (Scott Schwartz) Date: 13 Apr 2004 23:22:06 -0400 Subject: print u"\u0432": why is this so hard? UnciodeEncodeError References: Message-ID: <8gbrlvz1k1.fsf@galapagos.bx.psu.edu> =?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?= writes: > > Why is Python not respecting my locale? > > It is: however, your locale only tells Python the encoding of your > terminal, not the encoding of an arbitrary file you may write to. That's not the usual interpretation of locale. It's not about terminals, it's about everything, especially files. From adwser at hotmail.com Wed Apr 28 10:42:25 2004 From: adwser at hotmail.com (jtd) Date: 28 Apr 2004 07:42:25 -0700 Subject: Non-blocking connect BLOCKS References: Message-ID: "Dave Brueck" wrote in message news:... > > I'm using asyncore to download a large list of web pages, and I've > > noticed dispatcher.connect blocks for some hosts. I was under the > > impression that non-blocking sockets do not block on connects, in > > addition to reads and writes. My connect code is essentially the same > > as the asyncore example: > > > > http://docs.python.org/lib/asyncore-example.html > > > > It seems unlikely that I am the first to encounter this problem, can > > someone explain what's wrong and suggest a remedy? > > Most likely the connect call is doing a DNS lookup, which means your execution > pauses while some other (non-Python) code goes and talks to the DNS server. Thank you, that was exactly the problem. Instead of messing around with DNS lookup protocols, I rewrote the program using threads. Now the lookups take O(1) rather than O(number of threads/user threads) time :) From apocalypznow at yahoo.com Wed Apr 7 04:16:46 2004 From: apocalypznow at yahoo.com (jason willows) Date: Wed, 07 Apr 2004 08:16:46 GMT Subject: test Message-ID: this is a test. From jcarlson at uci.edu Sat Apr 3 17:07:42 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Sat, 03 Apr 2004 14:07:42 -0800 Subject: recursive file editing In-Reply-To: References: Message-ID: > I'm a python newbie; here are a few questions relative to a > problem I'm trying to solve; I'm wandering if python is the best > instrument or if awk or a mix of bash and sed would be better: > > 1) how would I get recursively descend > through all files in all subdirectories of > the one in which my script is called ? Check out os.path.walk. > 2) each file examined should be edited; IF a string of this type is found > > foo.asp=dev?bar (where bar can be a digit or an empty space) > > it should always be substituted with this string > > foo-bar.html (if bar is an empty space the new string is foo-.html) Check out the re module. > 3) the names of files read may themselves be of the sort foo.asp=dev?bar; > the edited output file should also be renamed according to the same rule > as above ... or would this be better handled by a bash script ? Do it however you feel more comfortable, Python can do it. - Josiah From tjreedy at udel.edu Thu Apr 8 09:51:08 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 8 Apr 2004 09:51:08 -0400 Subject: list comprehensions References: Message-ID: "Elaine Jackson" wrote in message news:i56dc.46224$Pk3.1562 at pd7tw1no... > But I stand by my complaint about unintuitiveness, Which I already agreed with, which I why I said, "Don't try to intuit!";-) > because I've discovered that you get an error from > > x = [(i,j) for i in range(7-j) for j in range(3)] because the i loop is outside/before the j loop. The problem with trying to intuit is that list comps move the appended expression from inside to outtermost while otherwise leaving the order outside-in. You were expecting the order to be uniformly reversed, and it is not. If the syntax had specified the above to be written as [for i in range(7-j): for j in range(3): (i,j)] which more obviously abbreviates the corresponding statements, the error would be more obvious. Moving the expression to the front was, of course, intentional -- to make it stand out more -- but I can be somewhat confusing at first until one gets used to it. > while > > y = [[(i,j) for i in range(7-j)] for j in range(3)] > > works fine. because now the i-loop, as part of the appended expression, gets executed inside the j loop. y=[] for j in range(3): y.append([(i,j) for i in range(7-j)]) Terry J. Reedy From __peter__ at web.de Tue Apr 27 05:53:14 2004 From: __peter__ at web.de (Peter Otten) Date: Tue, 27 Apr 2004 11:53:14 +0200 Subject: Default Argument Inconsistency? References: Message-ID: Paul Sweeney wrote: > The python tutorial gives the following example to demonstrate the fact > that default args are only evaluated once: > > def f(a,L=[]): > L.append(a) > return L > > print f(1),f(2),f(3) > [1] [1,2] [1,2,3] > > now I'm confident I understand this, but I do not understand how changing > to the following (whatever the merits of so doing, it was an accidental > typo) > results in the output displayed: > > def f(a,L=[]): > if not L: L=[] The first thing in f() is to check if L evaluates to False, i. e. is empty. If L is empty the L "the object" is left alone, but L "the identifier" is bound to a new empty list. So > L.append(a) will never operate on the empty list that was provided as default parameter. > return L > >>>> print f(1),f(2),f(3) > [1] [2] [3] > > surely on second entry to f, L == [1], so the "if not L:" should not > fire?! While the above works, there is one pitfall that will sooner or later bite you: >>> def f(a, L=[]): ... if not L: L = [] ... L.append(a) ... return L ... >>> l1 = ["old"] >>> f("new", l1) ['old', 'new'] >>> l1 ['old', 'new'] >>> l2 = [] >>> f("new", l2) ['new'] >>> l2 [] >>> Did you predict the values of l1 and l2 correctly? Congratulations. I recommend that you adopt the common practice and initialize mutable parameters with None as the default, which gives you consistent behaviour: >>> def f(a, L=None): ... if L is None: L = [] ... L.append(a) ... return L ... >>> l1 = ["old"] >>> f("new", l1) ['old', 'new'] >>> l1 ['old', 'new'] >>> l2 = [] >>> f("new", l2) ['new'] >>> l2 ['new'] >>> Peter From skchim0 at engr.uky.edu Thu Apr 8 10:28:52 2004 From: skchim0 at engr.uky.edu (Satish Chimakurthi) Date: Thu, 8 Apr 2004 10:28:52 -0400 Subject: Embedding python in ANSYS: Anyone tried it? References: Message-ID: <007401c41d75$d112dcf0$559ea380@D4XN6B41> Hi Anand, I am interested to know the details of your Python-FE coupling application. Would you please let me know ? Thanks Regards, Satish ----- Original Message ----- From: "anand k Rayudu" To: Cc: Sent: Thursday, April 08, 2004 9:54 AM Subject: Re: Embedding python in ANSYS: Anyone tried it? > Hi Berthold, > > You can embed python into any application very easily. > Also you have to extend python to understand your applications APIs and objects. > There are so many tools [Eg: SWIG, Boost ] to do this. > > Also python allows you to have 2 way communication between c/c++ & python, > using that you can have call back mechanism, > By embedding your application will have rich set of utilities. [ Remember python has very big list of modules ] > To deploy your application you need not have to have python as pre installed at your customer location. > You may supply python with your application. [ Some thing similar to JRE for JAVA] > > I hope this information helps you. > Recently I embedded python into one FE application, > if you want to know some specific details I can try to help you out. > Please let me know. > > Best Wishes, > > Anand > > > > > ____________________________________________________________ > Find what you are looking for with the Lycos Yellow Pages > http://r.lycos.com/r/yp_emailfooter/http://yellowpages.lycos.com/default.asp?SRC=lycos10 > > -- > http://mail.python.org/mailman/listinfo/python-list From hungjunglu at yahoo.com Sun Apr 18 12:23:33 2004 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 18 Apr 2004 09:23:33 -0700 Subject: module not callable - why not? References: <107dras2heahcb6@news.supernews.com> <8ef9bea6.0404122025.36efc84e@posting.google.com> <7xsmf1fxd9.fsf@ruckus.brouhaha.com> Message-ID: <8ef9bea6.0404180823.7a3bc189@posting.google.com> Paul Rubin wrote in message news:<7xsmf1fxd9.fsf at ruckus.brouhaha.com>... > Josiah Carlson writes: > > I think of modules as a namespace. Why? Because that is what they > > are. They contain a space of names, some of which may be useful to > > you, otherwise you wouldn't have imported the module. > > Is a class instance not also a namespace? After all, it contains a > space of names, some of which you must have wanted or else you > wouldn't have instantiated it. > > And yet, you can call a class instance if it has a __call__ operation > defined. I don't see why modules shouldn't be the same. Exactly. Another thing people have complained about is the lack of getters/setters for module properties. For classes, you can have properties. For modules, you can't. Look, here is a partial list of the symptoms of the illness of using class-and-module-based OOP: (a) You need metaclasses. You have special syntax for usage of metaclasses: you need to use the __metaclass__ name tag, in specific places. (b) Singletons become a "design pattern", since classes usually cannot be used as instances directly. (c) You have to create staticmethod and/or classmethod to make a class functional. (d) Modules can't have properties, nor are callable. (e) You often need to create three objects: module, class, instance, to do the job of one single object. Hence you often see usage of the same name for all three of them, weird as it may seem. (f) Module inheritance ('import' for containment, 'from ... import' for inheritance) differs in syntax with class inheritance ('class A(B):') (g) Module functions and class methods become two distinct types of objects. In prototype-based OOP, you don't have any of these problems. You can see that the usage of modules and classes introduces a whole lot of repeated/redundant concepts and/or inconsistencies. That's the price you pay. It's just an unfortunate historical development that lead us to where we are today. regards, Hung Jung From segphault at sbcglobal.net Sat Apr 10 13:00:47 2004 From: segphault at sbcglobal.net (Ryan Paul) Date: Sat, 10 Apr 2004 10:00:47 -0700 Subject: Changing the default string object used by the interpreter Message-ID: <1081616447.15063.92.camel@atrus> > I'm wondering if anyone can suggest a way, short of directly hacking > the > python interpreter, to change the default str class to a different > one. > ie. So that every time a str instance is created, it uses *my* class > instead of the built-in python string. Is there anything hidden away > that can be overloaded that might make this possible to do? I would also like to be able to overwrite built-in classes, and alter them at run time, but Guido clearly doesnt like the idea. If you want to do it, you will have to modify the interpreter to allow it. If you end up doing that, I'd love to see how. FYI, this is what Guido says about it: "For the curious: there are two reasons why changing built-in classes is disallowed. First, it would be too easy to break an invariant of a built-in type that is relied upon elsewhere, either by the standard library, or by the run-time code. Second, when Python is embedded in another application that creates multiple Python interpreters, the built-in class objects (being statically allocated data structures) are shared between all interpreters; thus, code running in one interpreter might wreak havoc on another interpreter, which is a no-no." (from http://python.org/2.2/descrintro.html) From R.E.Jones at kent.ac.uk Thu Apr 29 12:02:13 2004 From: R.E.Jones at kent.ac.uk (Richard Jones) Date: 29 Apr 2004 12:02:13 -0400 Subject: Summer School on Garbage Collection & Memory Management Message-ID: <04-04-096@comp.compilers> Garbage Collection & Memory Management Summer School 20-21 July 2004, Canterbury, UK The performance of today's memory-hungry applications depends on efficient dynamic memory management, whether managed explicitly through new/delete or automatically by a garbage collector. With the increasing use of managed code, whether Java Virtual Machines or Microsoft's Common Language Runtime, the economic importance of automatic memory management has never been greater. The Summer Schoool provides participants with an opportunity to hear leading practitioners from both industry and universities. The school is directed at postgraduate research students, academics who wish to get involved in this field and industrial researchers and developers who want to apply state of the art memory management techniques to real problems. The presenters include David Bacon (IBM TJ Watson Research Center), Emery Berger (U. Massachusetts), Robert Berry (IBM Hursley), Hans Boehm (HP), Dave Detlefs (Sun Microsystems), Rick Hudson (Intel), Richard Jones (U. Kent, Canterbury), Eliot Moss (U. Massachusetts). The registration fee for the 2 day Summer School is 130 GBP (free of VAT) and includes all workshop materials, lunches and refreshments, and the Summer School Dinner on 20th July. Bed and breakfast accommodation is also available in en-suite accommodation on campus at a rate of 30 GBP per night. For more details, see http://www.mm-net.org.uk/school/ or mail school at mm-net.org.uk The Summer School is organised by the UK Memory Management Network (http://www.mm-net.org.uk). We are grrateful for the kind support of the Engineering and Physical Sciences Research Council (http://www.epsrc.ac.uk). -- Richard Jones From irmen at -nospam-remove-this-xs4all.nl Fri Apr 30 09:51:40 2004 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Fri, 30 Apr 2004 15:51:40 +0200 Subject: Tkinter: focus/text selection problem with tkFileDialog Message-ID: <409259ed$0$574$e4fe514c@news.xs4all.nl> Hi, I'm having trouble with the code below. It's just a regular Tk text widget in which you can type and select text as expected, however the call to tkFileDialog.askopenfilename() seems to screw things up. After the file dialog, I can no longer use the Text widget (typing, selecting, it doesn't work anymore!) What am I doing wrong? TIA, --Irmen de Jong -----test.py---- import Tkinter, tkFileDialog window=Tkinter.Tk() txt=Tkinter.Text(window) txt.insert(Tkinter.END,"Choose a file, then try to select me") txt.pack() name=tkFileDialog.askopenfilename() txt.insert(Tkinter.END,"\nFile chosen: "+name) window.mainloop() From mcfletch at rogers.com Mon Apr 26 13:04:43 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Mon, 26 Apr 2004 13:04:43 -0400 Subject: Zip with sequences of diffrent length In-Reply-To: References: Message-ID: <408D412B.7090901@rogers.com> Use map( None, l, l[1:] ) HTH, Mike Nickolay Kolev wrote: ... > Wanted tuples: > > (1, 2) > (2, 3) > (3, None) > > I can get the first two tuples using zip(l, l[1:]). How do I get the > last one? ... _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From dontbotherworld at yahoo.com Fri Apr 30 06:35:51 2004 From: dontbotherworld at yahoo.com (dont bother) Date: Fri, 30 Apr 2004 03:35:51 -0700 (PDT) Subject: Where to put the HTMLgen files Message-ID: <20040430103551.66564.qmail@web60803.mail.yahoo.com> Hi, I have downloaded the HTMLgen for generating web pages with python. However I untared and unzipped it. I tried to link it with my path like this: Heres my .bashrc file -------------------------------------- GAIM=/usr/bin/ YAHOO=/usr/bin/ PYTHON=/usr/bin HTMLgenPYTHON=/usr/local/HTMLgen PATH=$PATH:$GAIM/gaim:$YAHOO/ymessenger:$PYTHON/python:$HTMLgenPYTHON export PATH GAIM YAHOO PYTHON HTMLgenPYTHON --------------------------------------- It does not work. When I write a python program and include : import HTMLgen it does not finds this module. Can anyone tell me where should I place this HTMLgen directory? and how to make it work? Thanks Dont __________________________________ Do you Yahoo!? Win a $20,000 Career Makeover at Yahoo! HotJobs http://hotjobs.sweepstakes.yahoo.com/careermakeover From irmen at -nospam-remove-this-xs4all.nl Wed Apr 28 14:00:42 2004 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Wed, 28 Apr 2004 20:00:42 +0200 Subject: sending an object - twisted or what? In-Reply-To: References: <20040427152051.50234c65.mutah@NOSPAM-libertysurf.fr> Message-ID: <408ff14b$0$571$e4fe514c@news.xs4all.nl> Paul Sweeney wrote: > It's quite likely this is going the way of xml-rpc over ssh. I'm sorry I forgot to mention in my other reply, that Pyro supports SSL by itself (using the m2crypto module). No SSH needed to set up a secure shell session. --Irmen de JOng From tkpmep at hotmail.com Thu Apr 29 10:39:53 2004 From: tkpmep at hotmail.com (Thomas Philips) Date: 29 Apr 2004 07:39:53 -0700 Subject: Subclasses in Python References: Message-ID: I followed Shalabh's suggestion and rewrote Alien as a subclass of Player, and used self.__Class__. to access the class attributes in the class and subclass. Works like a charm, but I'm having some difficulty printing class names. I want self.__class__ to return just the name of the class without some ancillary stuff thrown in. A snippet of code follows: class Player(object): #Class attributes for class Player threshold = 50 initial_strength=100 n=0 #Private methods for class Player def __init__(self,name): self.name = name self.strength = self.__class__.initial_strength self.__class__.n +=1 print self.__class__ class Alien(Player): #Class attributes for subclass Alien threshold = 30 initial_strength=150 n=0 When a new object is instantiated, the print statement in __init__ gives me or How can I just get it to return Player or Alien Interestingly, if I do a class comparison of the form if self.__class__== Alien: foo elif self.__class__== Player bar The comparison proceeds correctly. How can I get it to print the class name cleanly? Do I have to convert to a string and then use one or more string functions to clean it up? Thomas Philips From ptmcg at austin.rr._bogus_.com Tue Apr 27 08:36:09 2004 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Tue, 27 Apr 2004 12:36:09 GMT Subject: How Would You Do: Parsing and Expression Evaluation References: <108rren1js1hn71@corp.supernews.com> Message-ID: "Al Christians" wrote in message news:108rren1js1hn71 at corp.supernews.com... > I've got an idea for an application, and I wonder how much of what it > takes to create it is available in open source python components. > > My plan is this -- I want to do a simple spreadsheet-like application: > I've used a wxGrid, so I expect that wxPython will do fine for the user > interface. The spreadsheet can be organized vertically, one item per > line. It might need no more than 100 rows or so. On each line, the > user will enter in one column an item (variable) name and, in another > column, a formula or expression for computing the item's value. A > third column will show the computed value. There will usually be some > circular references between the items, but their values will converge > quickly with repeated evaluation. > > The final feature is a button that the user can click when they have the > sheet set up correctly -- it will translate the formulas into simple C > and python code to perform the same calculations as the spreadsheet. > > The formulas should be pretty easy -- add, subtract, multiply, divide, > log, exponential, and perhaps some user-defined functions. > > Are there any off-the-shelf python libraries that would make this kind > of app much easier? I don't have any special experience related to such > things, so I surely don't want to re-invent the wheel out of pure > ignorance -- should I try the parsing tools in the standard python > library, or will something else work better for me? > > TIA for any advice, > > > Al One of the examples that comes with pyparsing is a simple 4-function expression parser and evaluator, that is easily extendable to add exponentiation and user-defined functions. Download pyparsing at http://pyparsing.sourceforge.net . -- Paul From me at privacy.net Fri Apr 30 23:13:23 2004 From: me at privacy.net (Heather Coppersmith) Date: 30 Apr 2004 23:13:23 -0400 Subject: silent raw_input for passwords References: Message-ID: On Fri, 30 Apr 2004 21:26:40 -0500, Stephen Boulet wrote: > I need a password for a script and I would like to not have it > stored in a file or shown in a terminal. > "passphrase = raw_input()" still lets you see the input on the > screen. Is there a way to have it be hidden? It's my gpg > passphrase, so I don't want it anywhere except in my head. See the getpass module; it's part of the standard library. Most GUI's have similar functionality. HTH,, Heather -- Heather Coppersmith That's not right; that's not even wrong. -- Wolfgang Pauli From erlendga at tva.ifi.uio.no Thu Apr 1 13:19:30 2004 From: erlendga at tva.ifi.uio.no (Erlend Andreas Garberg) Date: Thu, 1 Apr 2004 18:19:30 +0000 (UTC) Subject: Travelling salesman variation in python Message-ID: Hi! I'm trying to code a implementation of a variation of the travelling salesman problem. The problem is the following. I have X nodes. Each node has a number assosiated with each of the other nodes. The problem is then: Construct a ring of the nodes so that the sum of the numbers is the highest possible. Example: Nodes: A with numbers B->1200, C->2000 B with numbers A->3000, C->4000 C with numbers A->9000, B->5000 The optimal ring is in this case can f.ex. be: A->1200->B->4000->C->9000->A with sum 14200. I have implemented this in python in the following way: hash is a dictionary with node-name as key and node-object as value. Each node-object has a dictionary speeds with node-name as key and a number as value. this dict stores the numbers associated with the other nodes. ------------------------------------------------------------------- # method xcombinations def xcombinations(items, n): if n==0: yield [] else: for i in xrange(len(items)): for cc in xcombinations(items[:i]+items[i+1:],n-1): yield [items[i]]+cc # help function func = lambda x,y: int(hash[x].speeds[y]) # code starts here: bestcomb = [] bestspeed = 0 for comb in xcombinations(hash.keys(),len(hash)): speed = sum(map(func,comb,comb[1:] + comb[:1])) if speed > bestspeed: bestcomb = comb bestspeed = speed ----------------------------------------------------------------- My implementation generate all combinations, and check which gives the highest result. My problem is that when the number of nodes is higher than 8, the algorithm slows to a crawl (because of O(n!) complexity). I wonder if there is some way I can optimize my algorithm to make it run faster? Currently it takes 20 seconds to compute the best combination with 9 nodes on my hardware. I would appreciate some comments on this :) -- Regards Erlend Garberg From peter.maas at mplusr.de Fri Apr 2 07:10:58 2004 From: peter.maas at mplusr.de (Peter Maas) Date: Fri, 02 Apr 2004 14:10:58 +0200 Subject: Python conference slogan In-Reply-To: <406D57FF.4040601@mplusr.de> References: <30260531.0404010833.1b834032@posting.google.com> <406C4DDF.5000907@zope.com> <406D57FF.4040601@mplusr.de> Message-ID: Peter Maas wrote: > [stolen from: Your cat would by Whiskas :)] correction: [stolen from: Your cat would BUY Whiskas :)] :) Mit freundlichen Gruessen, Peter Maas -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Hubert-Wienen-Str. 24 Tel +49-241-93878-0 Fax +49-241-93878-20 eMail peter.maas at mplusr.de ------------------------------------------------------------------- From peter at engcorp.com Thu Apr 15 08:02:19 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 15 Apr 2004 08:02:19 -0400 Subject: Getters and setters in python, common practise In-Reply-To: References: <407e402c$1@newsflash.abo.fi> <407e6cf9@newsflash.abo.fi> Message-ID: Yermat wrote: > Petter Holmstr?m wrote: >> I have not found any documentation on this topic. Could you please >> point me to some? > > see "property" at http://www.python.org/doc/2.3.3/lib/built-in-funcs.html > > You could also look at > http://users.rcn.com/python/download/Descriptor.htm to understand how it > does really work. Also helpful: http://www.python.org/2.2/descrintro.html#property From nospam at kochandreas.com Sun Apr 25 14:01:05 2004 From: nospam at kochandreas.com (Andreas Koch) Date: Sun, 25 Apr 2004 20:01:05 +0200 Subject: Andreas' practical language comparison In-Reply-To: <408BF601.30004@engcorp.com> References: <408BF601.30004@engcorp.com> Message-ID: Peter Hansen wrote: > The Java implementation of Bubble Sort doesn't follow the > specification for the algorithm. It fails to use a "swapped" > flag to determine when to terminate the loop. Thanks Peter - for a quick solution i corrected the problem myself (and corrected sort order, too), and added your python examples. -- Andreas He screamed: THIS IS SIG! From mrchameleon at hotmail.com Sun Apr 4 07:09:55 2004 From: mrchameleon at hotmail.com (Chris Reay) Date: 4 Apr 2004 04:09:55 -0700 Subject: OT (was Re: But it still doesn't explain the joke) References: <106o7vn56fgmt85@corp.supernews.com> <406F3C29.6030504@freedom.place> Message-ID: <7652139e.0404040309.50a1055d@posting.google.com> Josiah Carlson wrote in message news:... > > You tell me, who'se the traitor? > > - Josiah I can't; but I can tell who's grammatically confused, and whose opinions may also be so. From jepler at unpythonic.net Tue Apr 20 11:32:12 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Tue, 20 Apr 2004 10:32:12 -0500 Subject: closing file In-Reply-To: <4085366B.2020407@attglobal.net> References: <4085366B.2020407@attglobal.net> Message-ID: <20040420153211.GB2937@unpythonic.net> A file object is automatically closed by its destructor. In CPython, an object's destructor (a method called __del__) is called when its refcount equals zero. This rule is a little different in Jython, and the rule I just gave also doesn't explain what happens when there is a cycle (A holds a reference to B holds a reference to A). In both examples below, there is a single reference to the recently created Marcello object, which has the single reference to a Noisy object. So when m is deleted (explicitly or implicitly), the refcount of the Noisy instance m.o also drops to zero and its __del__ is called. The opened file in your original example would be closed at the same times as Noisy prints "del". Jeff class Noisy: def __del__(self): print "del" class Marcello: def f(self): self.o = Noisy() print "Example 1: using del to collect objects" m = Marcello() m.f() del m print "Example 2: the locals of a function are implicitly deleted at return" def g(): m = Marcello() m.f() g() From bo at systemhouse.dk Wed Apr 21 18:18:34 2004 From: bo at systemhouse.dk (Bo Jacobsen) Date: Thu, 22 Apr 2004 00:18:34 +0200 Subject: How to get the ip addresses of a nic References: <2sKdnSP1MpnEaRjd4p2dnA@adelphia.com> Message-ID: > > Is there a simple way to get all the ip addresses of a nic, beyound parsing > > /etc/sysconfig/..... > > > > ------------------------------------------------- > > Bo Jacobsen > > > > > > I just had to do deal with this BS a couple days ago. I couldn't get > the socket module to give it to me. The only ways I found were parsing > the output of ifconfig (or equivalent on other platforms) or connecting > to server and then looking at your socket. I don't like either one. > > Rob > > # Method 1 > > s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > s.connect(('somewebserver', 80)) > return s.getsockname()[0] > > # Method 2 > > if sys.platform == 'linux2': > out = commands.getoutput('/sbin/ifconfig') > return re.search('inet addr:(.+?)\s', out).group(1) > elif sys.platform == 'win32': > si, so = os.popen4('route print') > out = so.read() > ipPatt = r'\d+\.\d+\.\d+.\d+' > return re.search(r'0\.0\.0\.0\s+0\.0\.0\.0\s+' + ipPatt + r'\s+(' + > ipPatt + ')', out).group(1) > elif sys.platform == 'freebsd5': > out = commands.getoutput('/sbin/ifconfig') > return re.search('inet (\S+)\s', out).group(1) > else: > raise Exception('unsupported platform: %s' % sys.platform) And the parsing gets much more difficult with multiple nics and aliases. Bo From skip at pobox.com Sun Apr 11 08:28:09 2004 From: skip at pobox.com (Skip Montanaro) Date: Sun, 11 Apr 2004 07:28:09 -0500 Subject: solaris install of python In-Reply-To: References: Message-ID: <16505.14809.376948.850935@montanaro.dyndns.org> gotcha> has anyone installed pythong on solaris 8 before, Yes, plenty of times. gotcha> i am getting erors when i do a ./configure any ideas why ? Perhaps you have an incomplete GCC installation or don't have /usr/ccs/bin in your PATH. Skip From xslt-admin at gnome.org Sat Apr 10 02:24:01 2004 From: xslt-admin at gnome.org (xslt-admin at gnome.org) Date: Sat, 10 Apr 2004 02:24:01 -0400 Subject: Your message to xslt awaits moderator approval Message-ID: <20040410062401.3830.33987.Mailman@moniker.gnome.org> Your mail to 'xslt' with the subject Re: Excel file Is being held until the list moderator can review it for approval. The reason it is being held: Post by non-member to a members-only list Either the message will get posted to the list, or you will receive notification of the moderator's decision. From tzot at sil-tec.gr Mon Apr 5 05:46:58 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Mon, 05 Apr 2004 12:46:58 +0300 Subject: An attempt at guessing the encoding of a (non-unicode) string References: <80j3k1-ijc.ln1@home.rogerbinns.com> Message-ID: On Sat, 3 Apr 2004 12:22:05 -0800, rumours say that "Roger Binns" might have written: >Christos TZOTZIOY Georgiou wrote: >> This could be implemented as a function in codecs.py (let's call it >> "wild_guess"), that is based on some pre-calculated data. >Windows already has a related function: > >http://msdn.microsoft.com/library/default.asp?url=/library/en-us/intl/unicode_81np.asp As far as I understand, this function tests whether its argument is a valid Unicode text, so it has little to do with the issue I brought up: take a python string (8-bit bytes) and try to guess its encoding (eg, iso8859-1, iso8859-7 etc). There must be a similar function used for the "auto guess encoding" function of the MS Internet Explorer, however: 1. even if it is exported and usable under windows, it is not platform independent 2. its guessing success rate (until IE 5.5 which I happen to use) is not very high Thanks for your reply, anyway. -- TZOTZIOY, I speak England very best, Ils sont fous ces Redmontains! --Harddix From davidw at dedasys.com Fri Apr 16 11:01:51 2004 From: davidw at dedasys.com (David N. Welton) Date: Fri, 16 Apr 2004 15:01:51 GMT Subject: Goodbye TCL References: <0LudnSads6NmpuPdRVn-vw@centurytel.net> <21ccedf1.0404160639.14c2d852@posting.google.com> Message-ID: <87n05cge7o.fsf@dedasys.com> pedietz at west.com (Phil Dietz) writes: > Forget OO... TCL still doesn't have a standard database API in the > core yet.... That could go in this lib too. nstcl and DIO are probably the contenders here. -- David N. Welton Consulting: http://www.dedasys.com/ Personal: http://www.dedasys.com/davidw/ Free Software: http://www.dedasys.com/freesoftware/ Apache Tcl: http://tcl.apache.org/ From has.temp2 at virgin.net Thu Apr 29 16:09:13 2004 From: has.temp2 at virgin.net (has) Date: 29 Apr 2004 13:09:13 -0700 Subject: Is classless worth consideration References: <69cbbef2.0404290259.fd8d71c@posting.google.com> Message-ID: <69cbbef2.0404291209.7a98a799@posting.google.com> Peter Hansen wrote in message news:... > has wrote: > > > Well, as far as Python itself is concerned, it'd go a long way in > > eliminating the hideously baroque and increasingly brittle OO model it > > I find it especially hard to find the enthusiasm to read past > the highly inflammatory phrase "hideously baroque". I had to > do a double-take just to confirm that the poster is indeed > talking about Python. Compared to C++, I expect it's a real breath of fresh air. But compared to how something like Self does OO, it is indeed hideously baroque. > If you think it's baroque**, say so. Adding "hideous" just tells us > you are already highly biased against Python and poisons anything > else you were about to say... Oh, puh-leez. Now I'll not take you to task for such a dopey comment this time around 'cos I'm not a regular here and I'm a right bugger to Google for by my initials, so it's hard to figure out exactly who I am. But let me remedy this by providing my web address so you can go check my credentials: http://freespace.virgin.net/hamish.sanderson/ If you still want to accuse me of such childish nonsense afterwards, bring barbeque sauce. :) > ** Please double-check the definition of "baroque" that you are > using as well. "Feature-encrusted; complex; gaudy; verging on excessive." > Terms more like "elegant" and "simple" have come to mind, however, > which is quite at odds with your perception. Strange, that. Yes it is. However, I got my observation skills from several years' art school training, so I don't think the fault lies there. I may not have the formal CS training and deep programming knowledge and experience that many folks here have, but neither am I burdened by the religous and political baggage that all too often seems to accompany it. Oh, and another skill I've learn is saying exactly what I think, and being none too shy about how I say it. Just so you know. :) From sean_berry at cox.net Mon Apr 12 20:40:45 2004 From: sean_berry at cox.net (Sean Berry) Date: Mon, 12 Apr 2004 17:40:45 -0700 Subject: Escaping characters in MySQLdb query References: Message-ID: It doesn't work. If I have a value with a ', it creates an error. "Michael Walter" wrote in message news:c5fb0o$131c4$1 at ID-88904.news.uni-berlin.de... > Sean Berry wrote: > > I wrote a little script that is inserting thousands of records into a mysql > > database. > > > > How do I escape characters like ' in my insert statements? > > > > I have something like the following (much shorter) example: > > > > c.execute("INSERT INTO records (var1, var2) values ('%s', '%s')" %(value1, > > value2)) > > > > My problem is when value1 is something like "Tom's auto supply". The ' in > > Tom's needs to be escaped. How can I do this? > > > > Thanks. > > > > > I suppose you do like: > > c.execute("INSERT INTO records (var1, var2) values ('%s', '%s')", > (value1,value2)) > > and have all magic done for you. > > Cheers, > Michael From theller at python.net Wed Apr 14 11:04:13 2004 From: theller at python.net (Thomas Heller) Date: Wed, 14 Apr 2004 17:04:13 +0200 Subject: ctypes.com - unable to call function, read property References: <2D89F6C4A80FA547BF5D5B8FDDD04523060C65@exchange.adrembi.com> Message-ID: "Roman Yakovenko" writes: > Hi. I am trying for the first time to use ctypes.com module. > I have question: I have reference to object that implements IDiaSession interface. > > IDiaSession._methods_ = IUnknown._methods_ + [ > STDMETHOD(HRESULT, "_get_loadAddress", POINTER(c_ulonglong)), > STDMETHOD(HRESULT, "getEnumDebugStreams", POINTER(POINTER(IDiaEnumDebugStreams))), > > I can't find out how I call _get_loadAddress and getEnumDebugStreams methods. > I know that in com "get_" is a prefix for property. What should I do ? > Also "_get_loadAddress" defined as property. > So far, ctypes.com does not try to expose a higher level interface. So properties are exposed as getter and setter methods, with _get_ and _set_ prepended to the property name. You call the methods exactly as you would do in C (or raw C++, maybe): from ctypes import c_ulonglong, byref load_address = c_ulonglong() obj._get_loadAddress(byref(load_address)) # now access load_address.value to get the numerical value Calling getEnumDebugStreams is only slightly more complicated: enum_streams = POINTER(IDiaEnumDebugStreams)() obj.getEnumDebugStreams(byref(enum_streams)) Now you can call methods on the enum_streams object in the same way: retval = c_long() enum_streams.count(byref(retval)) print retval.value I hope you get the idea - most of the time you can literally convert C code to Python code. Thomas PS: I would like to clarify two additional things: 1. POINTER(IDiaEnumDebugStreams) creates a *class*. POINTER(IDiaEnumDebugStreams)() creates an instance of this class, which is actually a NULL pointer to a IDiaEnum... interface. This latter corresponds to this C code: IDiaEnumDebugStreams *p; 2. COM refcounting is automatic for probably 95% of the cases, although the rules are pretty complicated. The largest sample program for client dies com is probably the readtlb.py tool itself. PPS: There is a ctypes mailing list, which is the best place to answer questions like these ;-) Also available via nntp through gmane.org. From peter at engcorp.com Tue Apr 6 11:38:36 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 06 Apr 2004 11:38:36 -0400 Subject: Does Python compete with Java? In-Reply-To: References: <8b336527.0404051337.51bb4a1b@posting.google.com> <1073su4etm95p35@news.supernews.com> Message-ID: <_r6dnUARpa5hU-_dRVn-tw@powergate.ca> Roy Smith wrote: > The difference is that Java exposes the compilation step to the user > while Python hides it. If you really wanted to, you could hack up a > "Python compiler" which takes .py files, imports them to force > generation of the corresponding .pyc files, and then exits without > executing anything. You could then execute the .pyc files in a distinct > "execute phase". Not sure why you would want to do that, though :-) python -c "import py_compile as p; p.compile('mymodule.py')" From kirk at strauser.com Mon Apr 12 20:25:16 2004 From: kirk at strauser.com (Kirk Strauser) Date: Tue, 13 Apr 2004 00:25:16 GMT Subject: Random Numbers and a thought References: <107m6f0t4i0gnff@corp.supernews.com> <107m8qvphrjd303@corp.supernews.com> Message-ID: <87fzb84tf4.fsf@strauser.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 At 2004-04-12T23:16:39Z, "A Evans" writes: > Well from what I understand about my last post numbers computers generate > aren't truly random That is absolutely true. However, the periodicity will be measured in values like "2^128". > it may be a bit of work for us to actually sit down and do the figuring, > but it is always possible. Not true. First, although computers aren't truly random, a good cryptographic pseudorandom number generator (PRNG) collects "entropy pools" to mix the results of the output sequence. The unmixed sequence is more scattered than you could ever possibly hope to crack with a computer built by civilians. > Basically I would like to create an application that takes a series of > random numbers generated by a computer and searches for the pattern inside > those numbers So would the National Security Agency. > I guess if the numbers were between say 1 and 1000 it would take 1000 > inputs to understand the pattern if not more I would like to solve it > before that Not enough close. Sorry. - -- Kirk Strauser The Strauser Group Open. Solutions. Simple. http://www.strausergroup.com/ -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.4 (GNU/Linux) iD8DBQFAezMS5sRg+Y0CpvERAoi2AJ970RCE1F/GT+Doz4c5+yjKWLjKEgCbBaNk +hEcC27+5d92pILUN8XPVzg= =CKAa -----END PGP SIGNATURE----- From ed-no at spam-eepatents.com Tue Apr 20 15:21:02 2004 From: ed-no at spam-eepatents.com (Ed Suominen) Date: Tue, 20 Apr 2004 12:21:02 -0700 Subject: block ciphers References: <7L_gc.53134$Gn6.49963@newssvr25.news.prodigy.com> <7x3c6zqvdy.fsf@ruckus.brouhaha.com> Message-ID: Nick Efford wrote: > On Tue, 20 Apr 2004 02:41:58 +0000, Trevor Perrin wrote: > >> Me neither, exactly... ;-) I'm just trying to gauge the interest or >> resistance to this, and see if there's any way I could help. > > I would definitely like to see better crypto in the standard library. > > > N. Agreed. See http://privaria.org for an example of what I might do with it. From no_spam at terastat.com Tue Apr 27 13:48:33 2004 From: no_spam at terastat.com (bap) Date: Tue, 27 Apr 2004 17:48:33 GMT Subject: help: py2exe and com server References: <408a78f5$0$41761$5fc3050@dreader2.news.tiscali.nl> Message-ID: I had the sample problem -- using the lastest version of pywin32 (version 201 -- they've changed the numbering system) allows the com server to work fine Bruce Peterson "Thomas Heller" wrote in message news:mailman.14.1082966096.25742.python-list at python.org... > "Paul Mayal" writes: > > > Hi, > > > > I have written a com server in python 2.3 (ActiveState distribution). I have > > build the dll with py2exe. > > First of all, py2exe complain he can't find pythoncom module. > > I can register the dll with regsvr32 on my development workstation. But when > > I try to register the com dll on an another workstation, the registration > > fail. > > I think you have to use a newer build of pywin32 (formerly called > win32all) than that included with ActiveState python. > > Thomas > > From eldiener at earthlink.net Mon Apr 26 18:27:30 2004 From: eldiener at earthlink.net (Edward Diener) Date: Mon, 26 Apr 2004 22:27:30 GMT Subject: Uploading files from a server Message-ID: What is the easiest way in Python in a web server to upload a client file, once the file name on the client's machine has been entered, to a directory on the server ? From mwh at python.net Mon Apr 19 06:48:13 2004 From: mwh at python.net (Michael Hudson) Date: Mon, 19 Apr 2004 10:48:13 GMT Subject: Automatic, portable optimization of global access References: <5d83790c.0404150721.46a3b5d0@posting.google.com> Message-ID: python at rcn.com (Raymond Hettinger) writes: > FWIW, I've posted a brief, but powerful recipe for a bytecode > optimization that saves known globals as constants: > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/277940 You seem to have reimplemented: http://bytecodehacks.sourceforge.net/bch-docs/bch/module-bytecodehacks.closure.html :-) Indeed the first "bytecodehack" was very similar to this. Cheers, mwh -- ZAPHOD: Listen three eyes, don't try to outwierd me, I get stranger things than you free with my breakfast cereal. -- The Hitch-Hikers Guide to the Galaxy, Episode 7 From andrew-pythonlist at puzzling.org Thu Apr 1 06:33:19 2004 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Thu, 1 Apr 2004 21:33:19 +1000 Subject: Fetching websites with Python In-Reply-To: References: Message-ID: <20040401113319.GA14703@frobozz> On Wed, Mar 31, 2004 at 07:33:45PM +0200, Markus Franz wrote: > Hi. > > How can I grab websites with a command-line python script? I want to start > the script like this: > > ./script.py ---xxx--- http://www.address1.com http://www.address2.com > http://www.address3.com > > The script should load these 3 websites (or more if specified) in parallel > (may be processes? threads?) and show their contents seperated by ---xxx---. > The whole output should be print on the command-line. Each website should > only have 15 seconds to return the contents (maximum) in order to avoid a > never-ending script. > > How can I do this? You could use Twisted : from twisted.internet import reactor from twisted.web.client import getPage import sys def gotPage(page): print seperator print page def failed(failure): print seperator + ' FAILED' failure.printTraceback() def decrement(ignored): global count count -= 1 if count == 0: reactor.stop() seperator = sys.argv[1] urlList = sys.argv[2:] count = len(urlList) for url in urlList: getPage(url, timeout=15).addCallbacks(gotPage, failed).addBoth(decrement) reactor.run() It will grab the sites in parallel, printing them in the order they arrive, and doesn't use multiple processes, or multiple threads :) -Andrew. From jcarlson at uci.edu Thu Apr 1 19:25:50 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Thu, 01 Apr 2004 16:25:50 -0800 Subject: Method for providing a trail period on a program In-Reply-To: References: Message-ID: > I'm searching for a good way to provide a "trail > period" (something like 90 days) for a commercial > application that I'm writing. I'd like something > that can easily stop working 90 days after > installation. Can anyone point me to something > that exists already? Using windows registry pseudo-code if stoptime_not_in_registry: stoptime = time.time() + 90*24*3600 store_stoptime_in_registry(stoptime) if time.time() < stoptime: continue working else: give registration warning and quit FYI: most (if not all) methods for restricting users to some limited trial period are flawed in some major way; users can take a snapshot of their machine before installation and after installation and single run, and determine what has changed to determine exactly what is necessary to remove such protections. - Josiah From jdhunter at ace.bsd.uchicago.edu Mon Apr 19 10:47:47 2004 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Mon, 19 Apr 2004 09:47:47 -0500 Subject: datetimes, tzinfo and gmtime epoch In-Reply-To: (John Hunter's message of "Fri, 16 Apr 2004 15:25:01 -0500") References: Message-ID: >>>>> "John" == John Hunter writes: John> No goddawgy, I'm still off by an hour. Basically, I need to John> go from datetime -> gm epoch time -> and back while properly John> accounting for dst. Ok, for future generations of google-groupers looking for a free ride, I think I finally got this one figured out. The problem arose from the fact that I wanted to be able to support dates in any timezone but obviously the mktime offset needs to be in localtime. In my example, the tz was Eastern but my localtime is Central which accounts for the 1 hour discrepancy. The key is to use the arbitrary tzinfo in the datetime constructor but the Local tzinfo instance in computing the mktime offset. Obvious once you realize it. Thanks Tim Peters for defining all these nice tzinfo classes! Why aren't these part of the standard datetime module, or are they lurking somewhere in there? from your_timezone_module import Eastern, Pacific, Central, Local import time from datetime import datetime SEC_PER_DAY = 24*3600 class PyDatetimeConverter: """ Convert python2.3 datetime instances to/from epoch gmtime """ def __init__(self, tz=Eastern): self.tz = tz self.local = Local def epoch(self, x): 'convert userland datetime instance x to epoch' offset = self.local.utcoffset(x).days*SEC_PER_DAY + \ self.local.utcoffset(x).seconds return time.mktime( x.timetuple() ) + offset def from_epoch(self, e): 'return a datetime from the epoch' y,month,d,h,m,s,wd,jd,ds = time.gmtime(e) return datetime(y,month,d,h,m,s, tzinfo=self.tz) tz = Pacific dt1 = datetime(2004, 03, 01, tzinfo=tz) # before dst dt2 = datetime(2004, 04, 15, tzinfo=tz) # after dst dtc = PyDatetimeConverter(tz) assert( dtc.from_epoch( dtc.epoch(dt1) ) == dt1 ) assert( dtc.from_epoch( dtc.epoch(dt2) ) == dt2 ) From fumanchu at amor.org Sat Apr 10 19:27:52 2004 From: fumanchu at amor.org (Robert Brewer) Date: Sat, 10 Apr 2004 16:27:52 -0700 Subject: new-style class instance check Message-ID: Richard Gruet wrote: > How to determine that an object o is for sure an instance of > a new-style > class, without knowing of which specific class ? > That is, if I define a function: > > def isNewStyleClassInstance(o): > pass ## to be completed > > .. I want to pass the following test: > > def C: pass > def CNew(object): pass I assume you meant "class C" instead of "def C" ;) If it's new-style, it'll have an "mro" attribute: >>> class OldStyle: pass ... >>> class NewStyle(object): pass ... >>> NewStyle.mro >>> NewStyle.mro() [, ] >>> OldStyle.mro() Traceback (most recent call last): File "", line 1, in ? AttributeError: class OldStyle has no attribute 'mro' Hope that helps, Robert Brewer MIS Amor Ministries fumanchu at amor.org From mwh at python.net Thu Apr 22 06:34:13 2004 From: mwh at python.net (Michael Hudson) Date: Thu, 22 Apr 2004 10:34:13 GMT Subject: Cell objects and their values References: Message-ID: "Robert Brewer" writes: > Jeff Epler wrote: > > This seems to work, but it's undocumented (specifically, > > func_closure as > > an argument to new.function is undocumented) and makes my tummy feel > > funny when I think about it. > > > > >>> import new > > >>> def cell_get(cell): > > ... def f(): return cell > > ... return new.function(f.func_code, {}, "f", (), (cell,))() > > ... > > Rock. On. > > That is frickin' brilliant in at least three ways I never would have > thought of. :) Thanks! Looking back over Raymond's bytecode hack in PEP > 329, I notice he also used func_closure as an arg to function(). In > addition, he avoided importing the "new" module by just calling > type(f)(). That wouldn't work in Python 2.2, I don't know what Jeff is using these days... Cheers, mwh -- On the other hand, the following areas are subject to boycott in reaction to the rampant impurity of design or execution, as determined after a period of study, in no particular order: ... http://www.naggum.no/profile.html From NO-SPAM-PLEASEdanmessenga at hotmail.com Wed Apr 7 18:52:35 2004 From: NO-SPAM-PLEASEdanmessenga at hotmail.com (Dan Messenger) Date: Wed, 7 Apr 2004 23:52:35 +0100 Subject: from vh3 import virthost / AddVirtDomain / Ensim / Apache Message-ID: Hi, I'm new to python, and am trying to use some premade scripts on RedHat 7, but its giving me errors. The scripts are part of the Ensim hosting software, and when I run the command "AddVirtDomain" from a root shell, it works fine. However when I call it from my php page, and thus running under the apache user, I get the following error: Traceback (most recent call last): File "/usr/local/bin/AddVirtDomain", line 26, in ? from vh3 import virthost File "virtualhosting/virthost.py", line 46, in ? File "/home/build/qa/webppliance/3.1.11/2/lwp/vaishali2/WebGui/base/services/vh3/ virtualhosting/virtutil.py", line 14, in ? ImportError: No module named logging The first file mentioned is the one I am running, and 2nd two dont even exist - tho the script runs fine under a root shell. To me this indicates a permissions problem - but permissions to what? The files mentioned dont exist ! Anybody got any ideas ? Thanks in advance -Dan From jepler at unpythonic.net Fri Apr 23 14:21:43 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Fri, 23 Apr 2004 13:21:43 -0500 Subject: walking a list In-Reply-To: References: Message-ID: <20040423182143.GD2150@unpythonic.net> def print_or_recurse(l): for i in l: if isinstance(i, list): print_or_recurse(i) else: print i print_or_recurse([1,2,[3,2],5,[6,5,4]]) Jeff From gulliver at atr.co.jp Fri Apr 9 01:21:25 2004 From: gulliver at atr.co.jp (Roberto Lopez-Gulliver) Date: 8 Apr 2004 22:21:25 -0700 Subject: New PIL user : How to merge images References: <4075b940$0$1963$ba620e4c@news.skynet.be> Message-ID: <26b7aa41.0404082121.50a27a03@posting.google.com> try this, import Image RED = (255, 0, 0) GREEN = (0, 255, 0) BLUE = (0, 0, 255) # create/read your images bg = Image.new('RGB', (800, 600), RED) img = Image.new('RGB', (400, 400), GREEN) ## paste it W, H = bg.size w, h = img.size xo, yo = (W-w)/2, (H-h)/2 bg.paste(img, (xo, yo, xo+w, yo+h)) ## voila! bg.show() you may also consider using ImageMagick (www.imagemagick.org) for this special case. hope this helps. --r From peter at engcorp.com Sun Apr 25 18:15:38 2004 From: peter at engcorp.com (Peter Hansen) Date: Sun, 25 Apr 2004 18:15:38 -0400 Subject: DDE using the Windows version of Python In-Reply-To: References: Message-ID: Chaos Master wrote: > Is there any "module" to do communication between a Python program and other > software, using DDE protocol? Google is your friend, leading to this: http://www.faqts.com/knowledge_base/view.phtml/aid/5111 -Peter From jepler at unpythonic.net Wed Apr 21 11:31:03 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 21 Apr 2004 10:31:03 -0500 Subject: Python GUI wrapper for a long operation In-Reply-To: References: <108cnp89aedqp82@corp.supernews.com> Message-ID: <20040421153103.GA10591@unpythonic.net> Cameron is right. In my other life, I frequently curse at places in code where a programmer has added a call to "update" for the wrong reason--usually, the code I run into needs to know the size of a newly created widget, and "update" followed by "wm geometry" or "winfo" was regarded as the way to get it. It doesn't happen so much any more, over the past few *years* I've rooted out most of the bad calls, or more frequently converted them to "update idletasks" because it's easier than completely fixing the code. Using the word "simply" does a disservice to the potential subtleties of this approach, which include race conditions (they're not just for threaded programs!) or a growing stack. (where "update" calls a binding which calls "update" to arbitrary levels of nesting). In my example program, I made sure that the "start calculation" button was always disabled after it was pressed and before a call to "update", so there's no race condition there. The "interrupt calculation" button is only disabled during calculation (and it's the only thing enabled during that time), and it doesn't call "update", so there's no arbitrary nesting. For any non-trivial program, you'll get this thought process wrong. Heck, I wouldn't be surprised to hear that I got it wrong in this case, despite the apparent simplicity. However, even if you make the calculation run in an event-driven way, or using threads (or abusing generators to act as coroutines), there's still something modal about "a long-running calculation is happening now", and it takes care to make sure the user can never do something inappropriate for the program in its current state. Jeff From no.email at please.com Mon Apr 12 05:54:23 2004 From: no.email at please.com (Stevie_Mac) Date: Mon, 12 Apr 2004 10:54:23 +0100 Subject: pythonwin crash (used to work) - please help quick. References: <5Reec.62668$Id.61067@news-binary.blueyonder.co.uk> Message-ID: I think seen somthing like this on net somewhere when i was searching. So if I understand this, a python GUI can't debug a script that uses code from any other GUI implementation (like wx for example)? If so, dang! Whats my options - different IDE - or - no debug! wait, im sure when I tried to run the script direct (through python and pythonw) it still bombed - but in pyShell it didn't - hows that? Stevie_Mac :confused: "Paul Prescod" wrote in message news:mailman.537.1081743469.20120.python-list at python.org... > Stevie_mac wrote: > > > OS=XP, Python 2.3, wx2.5.1.5u > > Not sure what's to blame here - or to be more precise, how to fix it!... > > > > If I do this in PythonWin... > > import wx > > d = wx.Dialog(None, -1, 'title') > > BANG - IDE crashes > > It typically doesn't work to have two GUIs in one process. PythonWin > uses MFC. Wx is a totally different GUI. > > Paul Prescod > > > From xpythonist at yahoo.com.br Fri Apr 2 20:18:59 2004 From: xpythonist at yahoo.com.br (=?iso-8859-1?q?Aloysio=20Figueiredo?=) Date: Fri, 2 Apr 2004 22:18:59 -0300 (ART) Subject: Making the Zen of Python more useful In-Reply-To: Message-ID: <20040403011859.1088.qmail@web61008.mail.yahoo.com> --- Peter Hansen escreveu: > Aloysio, it's often helpful that sys.__stdout__ preserves a reference > to the original sys.stdout (similarly with sys.__stdin__ and > sys.__stderr__) so you don't have to preserve it manually like > that. > I didn't know that! Thank you very much for the information. > -Peter > -- Aloysio > http://mail.python.org/mailman/listinfo/python-list ______________________________________________________________________ Yahoo! Mail - O melhor e-mail do Brasil! Abra sua conta agora: http://br.yahoo.com/info/mail.html From cpl.19.ghum at spamgourmet.com Sat Apr 17 03:57:05 2004 From: cpl.19.ghum at spamgourmet.com (Harald Massa) Date: Sat, 17 Apr 2004 09:57:05 +0200 Subject: Initializing Python in Optimized mode from C++ References: <4080635b$0$46515$39cecf19@news.twtelecom.net> Message-ID: > I was viewing this thread from Google groups and didn't see your > response before I replied. This is exactly what I was looking > for...thanks! Out of curiosity, what does the -OO flag do on top of > the normal optimizations? Strip """ Doc-Strings """ Harald From asdf at asdf.com Fri Apr 30 22:31:59 2004 From: asdf at asdf.com (asdf sdf) Date: Sat, 01 May 2004 02:31:59 GMT Subject: calling functions at the same time In-Reply-To: References: Message-ID: bart_nessux wrote: > I need a script to call several functions at the same time. How does one > call more than one function simultaneously? > > > i just added my first thread to a wxpython program today. simple. in fact my first threaded program of any kind. as indicated, threads might help you. you didn't mention your platform but probably it has real thread support. nevertheless, this might not be for you if you are running in a Unix environment with a multiprocessing (forking) program. you launch your threads: import thread # create a lock you can use to block the threads until you are ready mymutex = thread.allocate_lock() def MyConcurrentFunction(): # important concurrent stuff pass def ThreadThing(): # thread will hang on 'acquire' until mutex is released mymutex.acquire() # release lock for the next thread mymutex.release() # now do your stuff MyConcurrentFunction() mymutex.acquire() # launch your threads thread.start_new_thread(ThreadThing, ()) thread.start_new_thread(ThreadThing, ()) thread.start_new_thread(ThreadThing, ())... # your threads are all hung on the 'acquire' statement # release the lock, unblocking the threads mymutex.release() # now all your threads are grabbing and releasing the mutex # all done I just made that whole thing up. But i think that's more or less how you launch threads. you have to consider that the thread may run as soon as you launch it. each thread could complete your special function before the rest of the threads get launched. i think you address that problem by creating a mutex or semaphore that each thread must acquire before it can proceed. That is, the thread will block (hang) waiting for the mutex to become available. (think of a mutex as an abstract lock resource). when all your threads are launched, the main program can release the mutex(es), unblocking the threads. The threads will unhang, and do your concurrent thing, more or less concurrently. Understand that concurrency is not guaranteed (as i understand it). the OS controls which thread runs when, and it is not deterministic. you could use an list of mutexes, to get an iota more concurrency. all this i learned this very day from Programming Python, pg 104. so take my advice with a shovel of salt. but it sounds like the way to go to me. From jjl at pobox.com Sat Apr 17 18:30:48 2004 From: jjl at pobox.com (John J. Lee) Date: 17 Apr 2004 23:30:48 +0100 Subject: Difficulty Finding Python Developers References: <65cbc3dd.0404140641.3501fde8@posting.google.com> <5d83790c.0404150701.605782a7@posting.google.com> <7xpta8hqe7.fsf@ruckus.brouhaha.com> <7xsmf4kbac.fsf@ruckus.brouhaha.com> <7x7jwg7ipn.fsf@ruckus.brouhaha.com> Message-ID: <87vfjy5jaf.fsf@pobox.com> Peter Hansen writes: > Fredrik Lundh wrote: > > > Peter Hansen wrote. > > > >>>They're not, but the discussion was serious production projects. > >> > >>I thought the discussion was a 3-month project. To me, that's > >>definitely not something I would classify as a "serious production > >>project". I know, I know, the length alone shouldn't be enough > >>to call it serious or production or not. It's just not the term > >>I would apply to something that short. "Experiment", maybe, or > >>"quickie", or "co-op student project" or something... > > > hmm. have I been posting to the wrong newsgroup? > > Maybe, but not in this thread, so far, unless my news providers > is dropping messages. > > (I'm sure there's a subtle point you're making, but it's too > subtle for my simple brain; forgive me.) [...] I assume Fredrik's point was that one can get a lot done in 3 months with Python. John From sweeney.2 at wright.edu Mon Apr 5 23:20:55 2004 From: sweeney.2 at wright.edu (Deacon Sweeney) Date: Mon, 5 Apr 2004 23:20:55 -0400 Subject: tear-off buttons for Tkinter Text objects? Message-ID: Hi. I've embedded some buttons in a Text object, and I would like these buttons to perform a 'tear-off' of that line when clicked. That is, when the button is clicked, I would like a new Toplevel to appear with a new Text object which contains the text. Creating a 'pop-off' button, where the Toplevel appears at some predetermined (or calculatable) point would be easy, I'd just create the Toplevel, position it, and pass the info to it. The difference would be that the 'tear-off' button would automatically 'grab' the new Toplevel so that it could be easily repositioned in the same motion of the mouse. There are three benefits to this that make it worthwhile. One, obviously repositioning is one mouse click easier. Two, I'll also add code to dock the lines, so re-docking a mistaken tear-off would be easier as well. Three, its just cool. So is there maybe some way to trick the window manager into thinking there's been a mouse click? It would be easy enough to position the title bar of the new Toplevel under the cursor. Or can the new window just be (magically) bound to the cursor until the button-pressing click is released? Any help would be appreciated. Thanks, Deacon Sweeney From eltronic at juno.com Tue Apr 13 11:50:33 2004 From: eltronic at juno.com (eltronic at juno.com) Date: Tue, 13 Apr 2004 11:50:33 -0400 Subject: Making urllib2 work with proxy urls Message-ID: <20040413.144604.-204255.0.eltronic@juno.com> On 13 Apr 2004 04:51:56 -0700 pythonguy at Hotpop.com (Anand Pillai) writes: > My company uses an automatic proxy configuration url of the form > http://server.company.com/department/proxy.pac . > I don't have a solution, but thanks for adding spaces after the url at the end of a sentance. why this convention is taking so long to catch on is a real puzzler. could you not use another proxy to log & monitor the progress of your connection? e ________________________________________________________________ The best thing to hit the Internet in years - Juno SpeedBand! Surf the Web up to FIVE TIMES FASTER! Only $14.95/ month - visit www.juno.com to sign up today! From has.temp2 at virgin.net Fri Apr 30 05:15:27 2004 From: has.temp2 at virgin.net (has) Date: 30 Apr 2004 02:15:27 -0700 Subject: What is good about Prothon? References: <108t2tlo06j8vb9@corp.supernews.com> <69cbbef2.0404281446.4e0ab52e@posting.google.com> <69cbbef2.0404291609.72d391db@posting.google.com> Message-ID: <69cbbef2.0404300115.574d93e7@posting.google.com> Greg Ewing wrote in message news:... > > # Create objects 'b' and 'c' > > b = a() > > c = a() > > You've mistranslated your example. Not at all. I was arguing these issues long before Prothon got its copy() method. I'm aware of its recent addition, but it doesn't really change anything: the canonical Prothon way to create new objects is still b = a(), not b = a.copy(). [FWIW, at least Prothon's not as confusing as Io, whose misleadingly named "clone()" doesn't in fact clone at all, but does the make-new-empty-object-that-delegates-to-the-existing-one thing that Prothon's __call__ does.] Anyway, this leads me to my next question: how many ways should one need to create new objects? I now count three in Prothon, which is certainly one too many. And what's it going to do about it? The art of great software design isn't adding features, it's getting rid of them. From rogerb at rogerbinns.com Fri Apr 23 05:34:55 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Fri, 23 Apr 2004 02:34:55 -0700 Subject: Multi-threaded printing and IOErrors in Windows References: <10nll1-rt5.ln1@home.rogerbinns.com> Message-ID: David Fraser wrote: > sys.stdout is not threadsafe - try wrapping each call with a mutext and > see if that fixes it... Having to wrap hundreds of random print statements just using for debugging seems really silly. Note that I don't care if the output gets garbled. (It doesn't on Mac or Linux ever). And I am only hitting this problem on Windows when wrapped with py2exe. If running outside of py2exe there is never any problem. When using py2exe, the stdout doesn't go anywhere anyway (it is gui app not a console app). The bizarre thing is that the IOError is very infrequent, but very annoying when it happens. Roger From bram at nospam.sara.nl Wed Apr 14 07:49:10 2004 From: bram at nospam.sara.nl (Bram Stolk) Date: Wed, 14 Apr 2004 13:49:10 +0200 Subject: spherical coordinates References: <20040414111334.34b5d225@pistache.sara.nl> <7x1xmqua94.fsf@ruckus.brouhaha.com> Message-ID: <20040414134910.5c4d9ec7@pistache.sara.nl> On Wed, 14 Apr 2004 11:06:49 GMT "Paul McGuire" wrote: > > I can imagine that all these conversions could be a performance killer if > done entirely in Python, and could stand to be done as a C extension. This > is probably why the OP was asking if such a package already exists. > Well, performance is not my first concern. I just want encapsulated classes for convenience, that handle all sorts of spherical coordinate specifics. For instance... interpolation between spherical coordinates. You can avoid going to/from cartesian if you properly handle the wrap-around at 180 and 360 degrees. Also, I want to be able to recursively subdivide the theta,phy space, and do stratification in theta,phy space, and al sorts of other operations, on the surface of a given sphere. An encapsulating class for these kind of coordinates would be a help, I thought. Bram -- ------------------------------------------------------------------------------ Bram Stolk, VR Engineer. SARA Academic Computing Services Amsterdam, PO Box 94613, 1090 GP AMSTERDAM email: bram at nospam.sara.nl Phone +31-20-5923059 Fax +31-20-6683167 "For the costs of subsidized agriculture in the EU, we can have all 56 million European cows fly around the world. First Class." - J. Norberg ------------------------------------------------------------------------------ From dude at fastchevy.com Wed Apr 21 16:52:33 2004 From: dude at fastchevy.com (Mike) Date: 21 Apr 2004 13:52:33 -0700 Subject: CamelCase versus wide_names (Prothon) References: Message-ID: <6e0680ac.0404211252.7f7b4358@posting.google.com> "Mark Hahn" wrote in message news:... > Of course in the Python world you alread have wide_names as your standard, > but could you for the moment pretend you were picking your standard from > scratch (as we are doing in the Prothon world) and give your vote for which > you'd prefer? Since Python has removed the need for the ';' character, how about using that as a word separator? It's very easy to type, as it is right next to the 'L' key on a qwerty keyboard. Here;is;a;test;paragraph.;What;do;you;think?;Is;it;the;greatest;programming;language;invention;since;the ;curly;brace? - Mike From junkmail at solumslekt.org Fri Apr 2 07:54:13 2004 From: junkmail at solumslekt.org (Leif B. Kristensen) Date: Fri, 02 Apr 2004 14:54:13 +0200 Subject: Python conference slogan References: <30260531.0404010833.1b834032@posting.google.com> <406C4DDF.5000907@zope.com> <406D57FF.4040601@mplusr.de> Message-ID: "Python - where whitespace matters" "Python - king of the snake pit" regards, -- Leif Biberg Kristensen http://solumslekt.org/ Validare necesse est From reverse.ku.oc.issolok at nothypgnal.delrest.co.uk Tue Apr 27 06:31:12 2004 From: reverse.ku.oc.issolok at nothypgnal.delrest.co.uk (Paul Sweeney) Date: Tue, 27 Apr 2004 10:31:12 +0000 (UTC) Subject: Default Argument Inconsistency? References: Message-ID: That's a great gotcha! The typo I knew about was that I should have had def f(a, L=None): but as you point out also the 'if' should be more explicitly if L is None: L = [] As I said in reply to Diez, I'm new to Python and had switched in general from my initial style of if L is None or L==[]: to if not L: which was clearly wrong here. As always, "a little knowledge is a dangerous thing" :-) Thanks, (to me ;-) an interesting problem and explanations Paul "Peter Otten" <__peter__ at web.de> wrote... > ... there is one pitfall that will sooner or later bite > you: > > >>> def f(a, L=[]): > ... if not L: L = [] > ... L.append(a) > ... return L > ... > >>> l1 = ["old"] > >>> f("new", l1) > ['old', 'new'] > >>> l1 > ['old', 'new'] > >>> l2 = [] > >>> f("new", l2) > ['new'] > >>> l2 > [] > >>> > > Did you predict the values of l1 and l2 correctly? Congratulations. > ... From joe at notcharles.ca Fri Apr 16 02:45:45 2004 From: joe at notcharles.ca (Joe Mason) Date: Fri, 16 Apr 2004 06:45:45 GMT Subject: [Newbie Q on String & List Manipulation] References: <567a7c35.0404150247.7809bef5@posting.google.com> Message-ID: In article <567a7c35.0404150247.7809bef5 at posting.google.com>, Matthew wrote: > ok, seems quite ok, however, not sure why it doesn't work on > my silly Gmail script (pls refer to my script belows): > > for item in thecookies: > mycookies += item > > print mycookies > > i have exactly 4 items in the "thecookies" list, however, when > printing out "mycookies", it just show the last item (in fact, > seems the 4 items have been overlapped each others). I had to comment out the SID and GV tests, because they kept failing, but then I got: ['=en_CA; Expires=Sat, 16-Apr-05 06:35:14 GMT; Path=/\r', 'Session=en_CA\r'] Session=en_CAes=Sat, 16-Apr-05 06:35:14 GMT; Path=/ Note the "\r" at the end of each cookie. That's carriage return, which moves the cursor back to the beginning of the line. mycookies actually contains all the data you want, but the print statement interprets the control character so they overwrite each other. Tip for future debugging: you don't need to do "sys.exit" at the end. It will automatically exit for you. And if you don't do that, you can run your script with "python -i" and get an interactive prompt when the script is finished, so you can examine the variables directly instead of going through print: >>> mycookies '=en_CA; Expires=Sat, 16-Apr-05 06:44:23 GMT; Path=/\rSession=en_CA\r' Joe From lbates at swamisoft.com Tue Apr 20 16:37:59 2004 From: lbates at swamisoft.com (Larry Bates) Date: Tue, 20 Apr 2004 15:37:59 -0500 Subject: Easily convert unicode tuple to python string tuple??? References: Message-ID: <5dmdnW0bd_C5FxjdRVn-vw@comcast.com> I always just used: myuTuple=(u'USER', u'NODE', u'HASH', u'IDNBR') mysTuple=[str(x) for x in myuTuple] Larry Bates Syscon, Inc. "Michal Mikolajczyk" wrote in message news:mailman.802.1082474513.20120.python-list at python.org... > Is there a quick way to convert a unicode tuple to a tuple containing python > strings? > > (u'USER', u'NODE', u'HASH', u'IDNBR') > > to this: > > ('USER', 'NODE', 'HASH', 'IDNBR') > > I need to be able to do this for a lot of tuples, not just one. > > Thanks, > Michael > > _________________________________________________________________ > Watch LIVE baseball games on your computer with MLB.TV, included with MSN > Premium! > http://join.msn.com/?page=features/mlb&pgmarket=en-us/go/onm00200439ave/direct/01/ > > From Mike at DeleteThis.Geary.com Fri Apr 9 13:28:00 2004 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Fri, 9 Apr 2004 10:28:00 -0700 Subject: Debugging extensions under VS .NET 2003 References: Message-ID: <107dn91j2908rce@corp.supernews.com> Gus Tabares wrote: > If you want to be able to debug your extensions, you will > [need] to build a debug version of the Python interpreter. I'm very curious about this: Can anyone explain why it is necessary? (And is it *really* necessary?) It's a very unusual requirement. In ordinary Windows coding, one DLL is independent from another. You can mix and match debug and nondebug DLLs with no problem. For example, suppose you are developing an Adobe Acrobat plug-in. You don't have a debug version of Acrobat nor debug versions of the other plug-ins and DLLs that Acrobat uses. But that doesn't matter. You can still build a debug version of your own plug-in. For that matter, consider any ordinary Windows application or DLL. You don't have debug versions of the numerous standard Windows DLLs that will be loaded alongside your code. But that has no effect on whether you can debug your own code or not. So what's going on with Python that it would require a debug version of pythonxx.dll in order to debug your own extension DLL? Obviously, if you want to trace through the pythonxx.dll code, you'd want a debug version of that code. Is that the reason? Other than that, the only possible reason would be if there are #if's in the Python headers that compile different and incompatible data structures or APIs depending on whether DEBUG is defined. If that is the problem, you could easily work around it by building a *release* version of your DLL, and in your project settings turn off optimization and turn on symbols. -Mike From hoel at gl-group.com Mon Apr 5 08:33:40 2004 From: hoel at gl-group.com (Berthold =?iso-8859-15?q?H=F6llmann?=) Date: Mon, 05 Apr 2004 14:33:40 +0200 Subject: Embedding python in ANSYS: Anyone tried it? Message-ID: Hello, We are thinking about embedding python in ANSYS. We have lots of tools written for howngrown FE programs which we woule like to see in python. Is there anyone who has experience to share? Kind regards Berthold H?llmann -- Dipl.-Ing. Berthold H?llmann __ Address: hoel at GL-Group.com G / \ L Germanischer Lloyd phone: +49-40-36149-7374 -+----+- Vorsetzen 32/35 P.O.Box 111606 fax : +49-40-36149-7320 \__/ D-20459 Hamburg D-20416 Hamburg From eppstein at ics.uci.edu Fri Apr 30 01:00:18 2004 From: eppstein at ics.uci.edu (David Eppstein) Date: Thu, 29 Apr 2004 22:00:18 -0700 Subject: Feedback on Sets, and Partitions References: Message-ID: In article , "Steve" wrote: > For my current project, I need to generate partitions of sets up to size > 25. I am rather hopeless it will ever be feasible, and I have begun > looking for a different approach. Thanks for any replies! There are 4638590332229999353 partitions of an 25 item set. So, I think generating them all is a little out of the question. -- David Eppstein http://www.ics.uci.edu/~eppstein/ Univ. of California, Irvine, School of Information & Computer Science From matthew at coredumps.net Sat Apr 24 00:51:02 2004 From: matthew at coredumps.net (Matthew) Date: 23 Apr 2004 21:51:02 -0700 Subject: [Newbie Q on String & List Manipulation] References: <567a7c35.0404150247.7809bef5@posting.google.com> Message-ID: <567a7c35.0404232051.733c645d@posting.google.com> Hello David &Joe, thanks very much for David's information about the "newline" and thanks very much for Joe's tips on sys.exit() and the "-i" parameter for debugging. =) --- matthew From OlafMeding at noSpam.compuserve.com Tue Apr 13 20:39:40 2004 From: OlafMeding at noSpam.compuserve.com (Olaf Meding) Date: Tue, 13 Apr 2004 19:39:40 -0500 Subject: Logging Stacktrace To File References: <407bcbca$1_2@newspeer2.tds.net> Message-ID: <407c8856$1_1@newspeer2.tds.net> Thanks to all of you. Olaf From rogerb at rogerbinns.com Sun Apr 18 00:31:07 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Sat, 17 Apr 2004 21:31:07 -0700 Subject: Python Documentation Blows! References: <40699A31.8000708@yahoo.com> <20040330161531.GA17112@vulcan.cprogrammer.org> <86uu70phciv8arhieh3gv51dbf0i33f9ir@4ax.com> Message-ID: <8tc9l1-4eb.ln1@home.rogerbinns.com> Will Stuyvesant wrote: > > [Terry Carroll] > > The state of wxPython's documentation is the major factor that's kept > > me from trying it. > > Short and elegant code examples. Preferably about what you want to > do. That is always the kind of documentation I am looking for. And the wxPython core ships with one which everyone seems to be ignoring. Run the demo! It includes code that sets up every control type, demonstrates threads, printing etc. It hooks into almost event type, and prints what you get. The tabs take you between a description of what is being shown, the actual code, and it running. I far prefer this over some trivial examples in the doc. Roger From sean_berry at cox.net Thu Apr 29 22:24:44 2004 From: sean_berry at cox.net (Sean Berry) Date: Thu, 29 Apr 2004 19:24:44 -0700 Subject: How to read a file from another server? Newbie References: <%Oejc.16$ph.9@fed1read07> <9ugjc.3709$g31.1370@newsread2.news.atl.earthlink.net> Message-ID: I have resolved the issue. I am just going to run the cgi script from the server the file is on. If anyone out there is interested I am getting close to finishing a script that does recursive digs for MX, A, and NS records for a given domain, or list of domains. Sean "bobb" wrote in message news:v4hkc.4707$wY.813 at nwrdny03.gnilink.net... > Sean, what kind of server are you trying to get at where the file exists? > > bobb > > "Sean Berry" wrote in message > news:Yyjjc.2071$Jy3.1146 at fed1read03... > > ssh I think. > > > > > > "Ivan Voras" wrote in message > > news:c6k9fh$3t9$1 at bagan.srce.hr... > > > Edward Diener wrote: > > > > > > > Sean Berry wrote: > > > > > > > >>I am trying to read in a file from another server. > > > >> > > > >>If I try > > > >>x = open("servername:/path/to/file", "r") > > > > > > > > > > > > x = open("servername://path/to/file", "r") > > > > > > Um, what does this to? What protocol does it use? > > > > > > From aku at europe.com Wed Apr 7 09:33:21 2004 From: aku at europe.com (aku) Date: 07 Apr 2004 13:33:21 GMT Subject: design by contract versus doctest References: <407174ea$0$5066$4d4ebb8e@news.nl.uu.net> <4072977b$0$1699$afc38c87@news.easynet.co.uk> <4073c94a$0$5066$4d4ebb8e@news.nl.uu.net> <4073cf1b$0$18217$afc38c87@news.easynet.co.uk> Message-ID: <40740321$0$5063$4d4ebb8e@news.nl.uu.net> On 2004-04-07, Peter Hickman wrote: > aku wrote: > > If someone deserves the title "father of DBC" it surely must > > be E. W. Dijkstra, the one who teached me in college;) > > How come? This is obviously some bit of CS history I have missed, do tell. Well, probably anyone back in those who also studied mathematics and computer science and took classes in mr Dijkstra's "programming 1" and "programming 2" will remember it. When I read "OO software construction" from B. Meyer years later - an excellent book btw - I think that, when I recall correctly, the author himself mention's that DBC is squarely based on dijkstra's earlier theoretical basis..... The funny thing is that in those times most students were wondering: How can this proof-that-a-program-does-what-it's-supposed-to-do thing ever be practically applied? The real usefullness however only became clear to me more and more as the years went by. From eastier at free.fr Tue Apr 20 20:04:38 2004 From: eastier at free.fr (Emmanuel) Date: Wed, 21 Apr 2004 02:04:38 +0200 Subject: Generator inside a class prevent __del__ ?? Message-ID: <4085BA96.651D2E4A@free.fr> Hi, I run across this problem, and couldn't find any solution (python 2.2.2) : Code : =========== from __future__ import generators >>> class titi: def __init__(self): print "init" def __del__(self): print "del" def Gen(self): yield 1 >>> c = titi() init >>> c = [] del ============== Here, everything is normal... But creating a generator : Code : =========== >>> class toto: def __init__(self): print "init" self.Coroutine = self.Gen() def __del__(self): print "del" def Gen(self): yield 1 >>> a = toto() init >>> c = [] <--- Nothing there !!! ============== I can't understand why the destructor is not called when a generator is created, and what I should do to have a "correct" behavior. (perhaps I missed something obvious, but I can't find it ) Thank you for any help, Emmanuel From tjreedy at udel.edu Fri Apr 9 14:10:25 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 9 Apr 2004 14:10:25 -0400 Subject: module not callable - why not? References: Message-ID: "Diez B. Roggisch" wrote in message news:c56jph$rrk$05$1 at news.t-online.com... > Hi, > > I just thought about creating a module for quaternions (as an personal > exercise, so I'm not after pointers to classlibs here). > > Now usually I'd create a file called "quaternion.py", define my quaternion > class in there and then import and create an instance like this: > > import quaternion > q = quaternion.quaternion() > > Thats a lot to type. doing a which is why I might add 'as q' to the import > from quaternion import quaternion > would solve that - but AFAIK thats considered bad for some reasons. By who? and why would you let whoever override your preference ;-) I have only read suggestions that one be careful with from x import *. > Now my question is: Is there a way to make a module callable that way? No. And I believe Guido has said he doesn't want modules to be classes, or more classlike. >And wouldn't it make sense to allow the implementation > of a call operator on module level? To you it seems to ;-) Terry J. Reedy From cgsex68 at hotmail.com Fri Apr 2 06:15:34 2004 From: cgsex68 at hotmail.com (test test) Date: Fri, 02 Apr 2004 11:15:34 +0000 Subject: configuring ODBC DSN with a python script Message-ID: An HTML attachment was scrubbed... URL: From Mike at DeleteThis.Geary.com Fri Apr 30 17:26:53 2004 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Fri, 30 Apr 2004 14:26:53 -0700 Subject: Simple prototyping in Python References: <69cbbef2.0404300855.20dd436b@posting.google.com> Message-ID: <1095h4vc89hmcf@corp.supernews.com> > Dave Benjamin wrote: > > JavaScript has a syntax for this: > > > > var o = {a: 5, b: 6} has wrote: > Looks on the surface like AppleScript's record type, which > is roughly analogous to C structs... and useless for anything > more than struct-style usage. While I did read about JS > programming in the dim-n-distant past - it was one of a > number of languages I looked at when learning proto-OO > on AS, which lacked any decent learning material on the > topic - I've pretty much forgotten everything since. So can > I ask: is the JS structure more flexible; e.g. can one add > functions to it to operate like methods on the other data in > the structure? Or does it have to provide a second structure > for proto-OO use, as AS does? A JavaScript object literal is simply a convenient way to construct an object. You can put anything in that object that you can put in any other object. This object literal: var o = { a: 5, b: 6 } is just a shorthand for: var o = new Object o.a = 5 o.b = 6 In fact, if you do o.toSource() after either of those, you'll get the same result: ({a:5, b:6}) As with any other object, you can put functions as well as data in an object literal, e.g.: var o = { a: 5, incr: function() { return ++this.a }, } o.incr() will return 6, 7, 8, etc. if you call it repeatedly. As Dave mentioned, you can also use closures, as in this example which uses both a closure and a property in the object literal: function F() { var c = 105; return { a: 5, incr: function() { return [ ++this.a, ++c ] }, } } var x = new F var y = new F x.incr() y.incr() -Mike From beliavsky at 127.0.0.1 Fri Apr 30 15:45:41 2004 From: beliavsky at 127.0.0.1 (beliavsky@aol.com) Date: 30 Apr 2004 14:45:41 -0500 Subject: Numeric speed Message-ID: <4092ace5_1@news.binaries.net> I have been looking at the speed of Python with the Numeric module by simulating some random numbers and computing some statistics. Here is the code. Line (1) is replaced as shown in the table. from RandomArray import random from Numeric import sum n = 1000000 m = 10 for i in range(m): xx = random(n) print xx[n-1] # (1) The times shown are in seconds and are the lowest values from several runs. line (1) Python Fortran xx[n-1] 1.33 0.52 sum(xx) 1.43 0.54 sum(xx**1) 3.76 0.54 sum(xx**2) 3.71 0.54 sum with explicit loop 11.79 0.54 My conclusions are that (1) Using the sum function of Numeric is much faster than an explicit loop. (2) Python with Numeric does not recognize that sum(xx**1) reduces to sum(xx), and this should be fixed. Obviously one would not write xx**1 explicitly in code, but it is possible that a variable exponent could equal 1. (3) The range of Fortran/Python speeds here is 2.5 to 7.0, when the Numeric module is used. The Fortran code is below. Line (1) is replaced as appropriate. The Python version is 2.3.3 , the Fortran compiler is Compaq Visual Fortran 6.6c, and the platform is an Intel Pentium 4 2.80 GHz on Windows XP. program xran_sum integer, parameter :: n = 1000000, m = 10 real :: xx(n) integer :: i call random_seed() do i=1,m call random_number(xx) print*,xx(n) ! (1) end do end program xran_sum From mark at prothon.org Fri Apr 30 14:46:25 2004 From: mark at prothon.org (Mark Hahn) Date: Fri, 30 Apr 2004 11:46:25 -0700 Subject: Why we will use obj$func() often References: <40887145.789A2FE8@alcyone.com> <7cki80hj976bia36lhf9er97v073o1pqvm@4ax.com> <1082783076.585831@yasure> Message-ID: A. Lloyd Flanagan wrote: > Actually, when I tried the code I got a NameError. I don't see why I > would want to access a variable defined in an inner scope from an > outer scope; this seems like a great way to clutter up the namespace > and confuse the issue of what the variable actually refers to. I assume you are talking about running that code in Python after removing the & from &x? That was supposed to be Prothon code that somehow defined x in function f from the statement &x = 42, even though that statement was in the inner function h. The equivalent python code would have the statement x = 42 inside the function f. Greg was asking if I was claiming that Prothon could do this "magic" somehow from function h (which Prothon cannot). We were always talking about an x local to f being referred to in h. From newsgroups at jhrothjr.com Tue Apr 6 18:49:23 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Tue, 6 Apr 2004 18:49:23 -0400 Subject: what is happening here? References: Message-ID: <1076d2psj7qde2f@news.supernews.com> "dan miller (moderator, s.p.d)" wrote in message news:c4vaum$q39$1 at nntp.ece.cmu.edu... > trying to figure out scoping of 'globals' in modules. So I have test.py: > > glob = 1 > > def setglob(v): > global glob > glob = v > > def getglob(): > return glob > > > and I do this: > > >>> from test import * > >>> glob > 1 > >>> getglob() > 1 > >>> glob=2 > >>> glob > 2 > >>> getglob() > 1 > >>> setglob(3) > >>> getglob() > 3 > >>> glob > 2 > > > Seems to me like the first time I invoke glob, it creates a new global > in my namespace, and initializes it to the value of the glob in test.py. > Seems counterintuitive! Sure seems wierd. What it looks like to me is that your import is binding three objects, but the actual functions are still refering to whatever object is bound in the "test" module, not in the interpreter's namespace. In other words, they are using the global dictionary they were compiled with, not their caller's global dictionary. Make sense? John Roth > From mcfletch at rogers.com Fri Apr 23 14:50:15 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Fri, 23 Apr 2004 14:50:15 -0400 Subject: Why we will use obj$func() often In-Reply-To: References: <84Uhc.22278$dZ1.5087@fed1read04> <8AWhc.23114$dZ1.11070@fed1read04> Message-ID: <40896567.6060806@rogers.com> Mark Hahn wrote: >"Mike C. Fletcher" wrote ... > > > >>$ is basically a character as far as glyphs go, it's a >>full-height glyph with ascenders and descenders, is very similar to a >>capital S, and generally makes reading code much harder as it obscures >>word-shape; .this or even self.this is much easier to read because you >>can pick out the words using your learned vocabulary of word-shapes. >> >> > >Well I have a problem now. I gave people on my mailing list a choice >between $var, `var, ~var, and ^var. The current tally is four votes for >$var and none for any of the others. According to your criteria, $var is >the worst and ~var should be the best. Am I correct? > > Depends on the font ;) . Certainly $ is going to have the most (negative) impact on readability, but the other three are all basically lightweight enough that they don't read as characters (basically any glyph that fills the same space as a lower-case o is going to markedly change the shape of a word. ` is the least likely to be read as a character, but is really hard to distinguish from ', so likely not a great choice. ^ doesn't occupy the middle space, so doesn't get read as a character either. ~ doesn't read as one either because it doesn't touch the baseline. $, however, is going to be familiar to your PERL aficionados, and familiarity counts a lot for those who are familiar with it, regardless of whether it's technically easier to read. The other three are basically just arbitrary punctuation, so people don't have any associations built up with them (they don't look at them and automatically think "attribute access"). The dot character does have lots of attribute-access associations; hence a leading dot (which doesn't read as a character) will tend to test favourably on both scales (practical and familiar). Have fun, Mike _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From siggy2 at supereva.it Fri Apr 2 05:04:01 2004 From: siggy2 at supereva.it (PiErre) Date: 2 Apr 2004 02:04:01 -0800 Subject: win32all 162 installation error [dr watson] Message-ID: <33a15593.0404020204.688b85df@posting.google.com> Hi All, I am trying to install win32 extension 162 on python 2.2.3 on a virtual (vmware) machine with win2k server sp3 (but I tested that the same happens on either win2k sp2 or win2ksp3 on a real biprocessor). I keep getting the drwatson error reported below during win32all 162 installation (during the compiling step, near the end of the progression bar - it can pass unnotice, but some symptoms are that you don't have a finish button - just the installation window abruptly disappears and if you try to uninstall win32all you get an error about missing INSTALL.LOG). I read somewhere that it could be related with a windows error registering the activex script engine (that actually is also the last info message that appears above the compiling progression bar before the crash). Anyway since we don't care for activex script and I had to ship the win32all installer in a big installshield setup kit for our clients I am not looking for a workaround: my main concern is how to avoid this error to show up in the event viewer or on drwtsn32... TIA! bye, PiErre Application exception occurred: App: (pid=1236) When: 4/2/2004 @ 10:49:17.900 Exception number: c0000005 (access violation) *----> System Information <----* Computer Name: NVS User Name: Administrator Number of Processors: 1 Processor Type: x86 Family 15 Model 2 Stepping 9 Windows 2000 Version: 5.0 Current Build: 2195 Service Pack: 3 Current Type: Uniprocessor Free Registered Organization: our company Registered Owner: our owner *----> Task List <----* 0 Idle.exe 8 System.exe 172 SMSS.exe 200 CSRSS.exe 224 WINLOGON.exe 252 SERVICES.exe 264 LSASS.exe 376 termsrv.exe 480 svchost.exe 504 spoolsv.exe 532 msdtc.exe 636 svchost.exe 656 LLSSRV.exe 700 regsvc.exe 708 mstask.exe 792 VMwareService.e.exe 824 WinMgmt.exe 856 svchost.exe 876 dfssvc.exe 896 inetinfo.exe 1244 svchost.exe 844 explorer.exe 1224 VMwareTray.exe 1100 wuauclt.exe 1312 mmc.exe 1236 win32all-162.ex.exe 516 DRWTSN32.exe 0 _Total.exe (00400000 - 00407000) (77F80000 - 77FFB000) (77E80000 - 77F36000) (77E10000 - 77E75000) (77F40000 - 77F7C000) (77DB0000 - 77E0D000) (77D30000 - 77DA1000) (10000000 - 1002B000) (76B30000 - 76B6D000) (77C70000 - 77CBA000) (77B50000 - 77BD9000) (782F0000 - 78536000) (78000000 - 78046000) (77820000 - 77827000) (759B0000 - 759B6000) (76620000 - 76630000) (77570000 - 775A0000) (76B20000 - 76B25000) (772B0000 - 7731C000) (77A50000 - 77B45000) (779B0000 - 77A4B000) (775A0000 - 77625000) (75A00000 - 75A13000) (76710000 - 76719000) (76FA0000 - 76FAF000) (773E0000 - 773F5000) (75170000 - 751BF000) (77BE0000 - 77BEF000) (751C0000 - 751C6000) (75150000 - 75160000) (75030000 - 75043000) (75020000 - 75028000) (77950000 - 7797A000) (77980000 - 779A4000) (75050000 - 75058000) (00F60000 - 00F67000) (1E000000 - 1E0D1000) (1E200000 - 1E211000) (1E600000 - 1E613000) (1E340000 - 1E396000) (1E790000 - 1E7A3000) (1E1E0000 - 1E1ED000) State Dump for Thread Id 0x270 eax=00000000 ebx=00000000 ecx=1e0a4660 edx=00000000 esi=1e0a4660 edi=00000000 eip=1e03a73a esp=0012cc2c ebp=018def90 iopl=0 nv up ei ng nz na po cy cs=001b ss=0023 ds=0023 es=0023 fs=0038 gs=0000 efl=00000287 function: PyNode_Future 1e03a72a 90 nop 1e03a72b 90 nop 1e03a72c 90 nop 1e03a72d 90 nop 1e03a72e 90 nop 1e03a72f 90 nop 1e03a730 8b4c2404 mov ecx,[esp+0x4] ss:0094a1ff=???????? 1e03a734 8b01 mov eax,[ecx] ds:1e0a4660=014f0d60 1e03a736 3bc1 cmp eax,ecx 1e03a738 740c jz PyInt_FromUnicode+0x1d6 (1e043246) FAULT ->1e03a73a 8b5010 mov edx,[eax+0x10] ds:0081d5d2=326e6f68 1e03a73d 895008 mov [eax+0x8],edx ds:0081d5d2=326e6f68 1e03a740 8b00 mov eax,[eax] ds:00000000=???????? 1e03a742 3bc1 cmp eax,ecx 1e03a744 75f4 jnz PyLong_AsUnsignedLong+0x4a (1e046b3a) 1e03a746 c3 ret 1e03a747 90 nop 1e03a748 90 nop 1e03a749 90 nop 1e03a74a 90 nop 1e03a74b 90 nop 1e03a74c 90 nop *----> Stack Back Trace <----* FramePtr ReturnAd Param#1 Param#2 Param#3 Param#4 Function Name 018DEF90 0012D044 01400E48 011E9CF8 01826198 011E9D90 !PyNode_Future 00000001 00000000 00000000 00000000 00000000 00000000 *----> Raw Stack Dump <----* 0012cc2c 5b a5 03 1e 60 46 0a 1e - 00 00 00 00 90 ef 8d 01 [...`F.......... 0012cc3c 00 00 00 00 00 00 00 00 - 00 00 00 00 ec da 81 00 ................ 0012cc4c 10 fb 09 1e 00 00 00 00 - d2 96 27 01 e0 ff 12 00 ..........'..... 0012cc5c b8 ff 00 78 38 32 03 78 - ff ff ff ff 90 ef 8d 01 ...x82.x........ 0012cc6c 45 10 00 78 20 00 00 00 - f7 b0 03 1e 60 46 0a 1e E..x .......`F.. 0012cc7c 70 46 0a 1e a8 68 37 01 - d9 af 03 1e f0 b0 0a 1e pF...h7......... 0012cc8c 0d b1 03 1e f0 b0 0a 1e - 00 00 00 00 d0 68 37 01 .............h7. 0012cc9c 73 47 04 1e f0 b0 0a 1e - ec da 81 00 d0 68 37 01 sG...........h7. 0012ccac 00 00 00 00 e3 21 07 1e - 00 00 00 00 c8 96 27 01 .....!........'. 0012ccbc c8 65 8c 01 90 ef 8d 01 - c8 96 27 01 e0 32 02 1e .e........'..2.. 0012cccc 90 ef 8d 01 c8 96 27 01 - 03 01 00 00 53 00 00 00 ......'.....S... 0012ccdc 90 ef 8d 01 03 00 00 00 - 48 0e 40 01 95 37 02 1e ........H. at ..7.. 0012ccec 90 ef 8d 01 c8 96 27 01 - 03 01 00 00 53 00 00 00 ......'.....S... 0012ccfc 90 ef 8d 01 c0 06 4f 01 - 90 ef 8d 01 c8 96 27 01 ......O.......'. 0012cd0c 02 00 00 00 90 ef 8d 01 - f8 28 1b 01 03 00 00 00 .........(...... 0012cd1c 3c 00 00 00 4c 39 02 1e - 90 ef 8d 01 ac 3c 04 01 <...L9.......<.. 0012cd2c 90 ef 8d 01 d8 4e f9 00 - 10 68 37 01 00 00 00 00 .....N...h7..... 0012cd3c 6a 38 02 1e 90 ef 8d 01 - f8 28 1b 01 90 ef 8d 01 j8.......(...... 0012cd4c 10 68 37 01 3c 01 00 00 - 40 00 00 00 90 ef 8d 01 .h7.<... at ....... 0012cd5c 18 8a 1c 01 0b 00 00 00 - dc 00 00 00 4c 39 02 1e ............L9.. From no.email at please.com Mon Apr 12 15:13:09 2004 From: no.email at please.com (Stevie_mac) Date: Mon, 12 Apr 2004 20:13:09 +0100 Subject: String + number split References: <2SAec.70005$Id.6002@news-binary.blueyonder.co.uk> Message-ID: now thats what im talking about! note to self, learn reg exp! Thing is, dont understand it one bit! any chance you comment it! (tell me where to go if you want!) I'd appreciate it if you could - ta. "Graham Breed" wrote in message news:YjBec.70215$Id.61871 at news-binary.blueyonder.co.uk... > Stevie_mac wrote: > > > Hello again, I can do this, but I'm sure there is a much more elegant way... > > > > A string, with a number on the end, strip off the number & discard any underscores > > > > eg... > > > > font12 becomes ('font',12) > > arial_14 becomes ('arial',14) > > Hmm, well, there's always > > >>> import re > >>> def fsplit(s): > matcher = re.compile('\d+$|_') > return matcher.sub('', s), int(matcher.findall(s)[-1]) > > >>> fsplit('font12') > ('font', 12) > >>> fsplit('arial14') > ('arial', 14) > >>> fsplit('__arial__bold_1_14') > ('arialbold1', 14) > > I'm scary enough that I probably would do it this way. > > > Graham From derek at hiredgoons.org Wed Apr 7 11:12:47 2004 From: derek at hiredgoons.org (Derek Thomson) Date: Thu, 08 Apr 2004 01:12:47 +1000 Subject: Are line continuations needed? In-Reply-To: References: <407409ef.82801353@news.eircom.net> <40740f99@duster.adelaide.on.net> Message-ID: <40741b6e$1@duster.adelaide.on.net> Mark Jackson wrote: > > This ought to work: > > class ParticleDistributionBehaviorServer( > Microphysics__POA.ParticleDistributionBehavior): > In fact it does work - I should have thought of that. I've just checked in the change to CVS. Thanks! Now I'll have to think of another case ... I'm sure there was another ... Regards, Derek. From claird at lairds.com Wed Apr 28 07:59:03 2004 From: claird at lairds.com (Cameron Laird) Date: Wed, 28 Apr 2004 11:59:03 -0000 Subject: Is Perl *that* good? References: Message-ID: <108v74768o9sb9f@corp.supernews.com> In article , Carl Banks wrote: . . . >If you do stuff recursively (as I often do) or break up code into >smaller functions (as I often do) so that the functions with these >regexps get called numerous times, it can help performance to move the >compile step out of the functions. > >The point is, the existence re.compile encourages people to make >regexp objects global so they only need to be compiled once, when the >module is loaded. Because of this, and especially because regexps are >prone to being used in recursive functions and such, it's dangerous to >allow them to have state. . . . I wrote the subject line for this subthread. Here's my provisional conclusion: my past attempts to track down claims of the "Perl is tops for string-handling" sort generally reinforced the proposition that the speaker simply meant, "Perl privileges REs" (and that the speaker had no familiarity with Python, let alone Icon or Prolog). Now I see there's a likelihood of definite attraction to the hidden-variable, dangerous implicitness goop so characteristic of Perl. That's good to understand. Thanks, Carl; good analysis. -- Cameron Laird Business: http://www.Phaseit.net From johnbunderwood at yahoo.ca Mon Apr 5 16:38:08 2004 From: johnbunderwood at yahoo.ca (John Underwood) Date: Mon, 05 Apr 2004 16:38:08 -0400 Subject: Using python23 to develop an extension for an application that has python22 embedded References: <1073eeubflmchd5@corp.supernews.com> Message-ID: On Mon, 5 Apr 2004 12:56:14 -0700, "Michael Geary" wrote: >John Underwood wrote: >> Can I use python23_d and python23 to develop an extension for a >> commercial application uses python22.dll? (Providing that I do not use >> any new features found only in 2.3.) >> >> I would bulld version 2.2 but I am having trouble doing this with >> Visual Studio .NET Standard. (There is a well documented problem with >> version 2.2 (involving largeint.h) and VS.NET but none of the >> solutions that I found have worked.) >> >> On the other hand, I have successfully built release and debug >> versions of pythoncore with VS.NET. > >Why don't you just install the binary version of 2.2? That would be easier. >You can have 2.2 and 2.3 installed on the same machine with no problem. > >http://www.python.org/2.2.3/ > >If 2.3 is the version you use most often, you may want to reinstall it after >installing 2.2, so that your Windows file associations point to it. You can >just reinstall 2.3 on top of your previous 2.3 installation. (Or maybe >there's an easier way to do this.) > >-Mike > I have both 2.2 and 2.3 installed on my computer. My problem has to do with Visual Studio .NET which will build 2.3 but will not build 2.2. (MS removed largeint.h which is required by pythoncore in 2.2 when they went from Visual C++ 6 to VS.NET. I tried supplying largeint.h to VS.NET but that did not work.) Since I cannot build 2.2, I do not have python22.dll or python22_d.dll (the debug version). (They are not shipped with python you have to produce them yourself.) The commercial application to which I need to add an extension has python22.dll in its runtime folder. I have no control over this application and have to use whichever version they have chosen. Since I do have python23.dll and python23_d.dll (from a successful build of 2.3), can I use these to develop an extension for the aforementioned commercial application if I stay away from any new features in 2.3 (but not in 2.2)? -John From garryknight at gmx.net Wed Apr 14 16:36:50 2004 From: garryknight at gmx.net (Garry Knight) Date: Wed, 14 Apr 2004 21:36:50 +0100 Subject: Difficulty Finding Python Developers References: <65cbc3dd.0404140641.3501fde8@posting.google.com> Message-ID: <1081975009.10988.2@ersa.uk.clara.net> In message , Mike C. Fletcher wrote: > I'm an alumni, so UofW is obviously not all it's cracked up to be ;) Apparently not. 'Alumni' is the plural form. You're an alumnus. :o) -- Garry Knight garryknight at gmx.net ICQ 126351135 Linux registered user 182025 From FBatista at uniFON.com.ar Tue Apr 27 14:03:19 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Tue, 27 Apr 2004 15:03:19 -0300 Subject: Tkinter vs. wxPython? Message-ID: [SeeBelow at SeeBelow.Nut] #- I ask because I have just started learning Tkinter, and I wonder if I #- should abandon it in favor of wxPython. I'm in the self dilemma. I wrote a small application in wxPython, then I searched something more "natural". I found Tkinter, and I'm pleased with it. But, I read somewhere that Tkinter is simpler, but difficult so make big complicated stuff. wxPython is more difficult at start, but more scalable. And I read Alex Martelli saying that Tkinter is easier and simpler, but if you want to write "big commercial" applications, you'll prefer wxPython (well, actually don't remember if those are his words, but I got that idea). So, I'm writing a small (but professional) application in Tkinter. And then I'll write it in wxPython. Then I'll decide in what I'll wrote a bigger application I'm building. . Facundo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA La informaci?n contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener informaci?n confidencial o propietaria, cuya divulgaci?n es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no est? autorizado a divulgar, copiar, distribuir o retener informaci?n (o parte de ella) contenida en este mensaje. Por favor notif?quenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magn?tico) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telef?nica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electr?nicos pueden ser alterados, motivo por el cual Telef?nica Comunicaciones Personales S.A. no aceptar? ninguna obligaci?n cualquiera sea el resultante de este mensaje. Muchas Gracias. -------------- next part -------------- An HTML attachment was scrubbed... URL: From piedmontbiz at aol.com Sun Apr 11 17:07:07 2004 From: piedmontbiz at aol.com (PiedmontBiz) Date: 11 Apr 2004 21:07:07 GMT Subject: Python is the best and most popular general purpose scripting References: Message-ID: <20040411170707.13360.00000139@mb-m18.aol.com> > You're defining it in terms of itself; what is scripting? The use of >> scripting languages, or the accomplishment of tasks quickly and >> easily? Some would argue the latter can be done with programming >> languages. > >Scripting is the gluing together of components potentially written in a >variety of languages. > >> # A programming language is a language that makes programming (including >> # the creation of components) easy. >> >> By this metric many languages are both, since the definition is >> subjective. > >Yes. The term is both historical and subjective. If you try to draw any >line in the sand you will find outliers like Lisp and even Java (which >is bytecode interpreted just as Python is) will cause you problems. >There are compilers for Python and interpreters for C. > > Paul Prescod > I have the answer. Scripts are concatenated sequences of instructions to the computer operating system to perfom a certain task. The script I create for my own purposes and my own personal use (or my work group) will always be known as a script. If my script is needed and used by others (outside my workgroup), it will now be called an application. The source code of applications is not changed by the user. My script is subject to refinements as required to suit my needs. If the user of an application needs the app to be modified, he must go to a programmer who then makes the changes to the script. The modified script is then given back to the user as an modified application. I am working on the chicken and egg thing also. Here is an overview of JCL. This is the archetypical scripting language perhaps. ===================== http://www.okstate.edu/cis_info/cis_manual/jcl_over.html What is JCL? Job Control Language (JCL) is a means of communicating with the IBM 3090 MVS Operating System. JCL statements provide information that the operating system needs to execute a job. -------------------------------------------------------------------------- ------ A job is something that you want to accomplish with the aid of a mainframe computer, e.g. copy a data set, execute a program, or process multiple job steps. You need to supply the information that the job requires and instruct the computer what to do with this information. You do this with JCL statements. A job step consists of statements that control the execution of a program or procedure, request resources, and define input and/or output. -------------------------------------------------------------------------- ------ This includes information about: the program or procedure to be executed input data output data output reports A JCL statement also provides information about who the job belongs to and which account to charge for the job. ======== allen From OlafMeding at noSpam.compuserve.com Tue Apr 27 18:05:25 2004 From: OlafMeding at noSpam.compuserve.com (Olaf Meding) Date: Tue, 27 Apr 2004 17:05:25 -0500 Subject: MS COM early and late binding References: <9e5ea2c4.0404271039.2da829b5@posting.google.com> Message-ID: <408ed8e5$1_1@newspeer2.tds.net> Thomas What you suggest might work, but does not look to elegant. Can anyone else perhaps suggest a more elegant solution? Thanks. Olaf try: excel.visible except AttributeError: print "late bound" else: print "early bound" Hint: Attributes are case sensitive when early bound ;-) From me at privacy.net Thu Apr 8 04:42:07 2004 From: me at privacy.net (Duncan Booth) Date: 8 Apr 2004 08:42:07 GMT Subject: Pyrex list is down References: <74jek1-3qs.ln1@snout.lairds.org> Message-ID: Kyler Laird wrote in news:74jek1- 3qs.ln1 at snout.lairds.org: > Paul Prescod writes: > >>It seems like nothing has gone in or out for days: > >>http://lists.copyleft.no/pipermail/pyrex/2004-April/thread.html > > I hate mailing lists anyway. I'd much rather use Usenet. So why don't you just run a local news-server and filter any mailing list messages through to locally generated newsgroups? That's what I do: I'm a windows user so I use Hamster to amalgamate several external news servers and all my mailing lists into a single local news server. From edwardt_tril at yahoo.com Mon Apr 5 13:27:32 2004 From: edwardt_tril at yahoo.com (ed) Date: 5 Apr 2004 10:27:32 -0700 Subject: Registry Key extraction and migration Message-ID: <7d7e723a.0404050927.12611c86@posting.google.com> Hi I want to write a tool to do the following: 1. extract and display registry keys under abritrary starting point, for example: source are: HKey_Local_machine\software\old_lcoation or HKey_current_user\software\XXX\YYY a) then, I can specify where the Keys can be copied and compare the new location to the new location. For example: destination are: HKEY_local_mahcine\software\New_location. b) if the keys are not there flags error message how canI do that? From uzairaqeel at yahoo.com Thu Apr 22 02:23:13 2004 From: uzairaqeel at yahoo.com (Uzair) Date: 21 Apr 2004 23:23:13 -0700 Subject: Naming conventions Message-ID: <5a88ee0a.0404212223.15f50fe9@posting.google.com> Why aren't the names of the modules in the standard library fixed so that they follow some actual naming convention? That is probably the biggest deterrent for new users -- having to dig through several sources to find the module they're interested in. And, as with urllib and urllib2, it isn't even clear at first glance which is more useful and when it should be used... Just curious...I've read a lot about the Python community's collective determination to maintain the purity of the language and ease-of-use, and their willingness to fix 'broken' elements rather than gloss over them in the name of backward compatibility, as Sun often does with Java :) Best, Uzair From mark at prothon.org Fri Apr 2 22:41:40 2004 From: mark at prothon.org (Mark Hahn) Date: Fri, 2 Apr 2004 19:41:40 -0800 Subject: Indent testers needed (Prothon) Message-ID: We're proud to say that Prothon has grown out of the indent space/tab flame war stage and has moved on to more serious discussions. We've decided to allow space-based indents and tab-based indents but not in the same file. We are also adding some improvements in the area of line continuations (see the algorithm at the end of the message). Since there were zillions of messages here on c.l.py about spaces vs. tabs and Guido has said he wants to remove tab support, I thought maybe some of you might help us test our implementation of this indentation algorithm. Can I get a few space lovers and tab lovers to download this windows executable and tell us if this makes them happy? If you keep your Python code simple and free of class statements, you don't have to learn Prothon to try it. You can't use the interactive console to evaluate the algorithm, you will need to write *.pr code files and run them. Note: This is not a real Prothon release. It has not been through normal testing. Use it only for indent testing. The zip file (350K) is at: http://prothon.org/pub/prothon/Prothon-unstable-b255-win32.zip Unzip the file which will make a folder called win32. Drop your .pr file into the folder. Open a dos command window. CD to the win32 folder and run the prothon.exe file with the .pr file name: prothon.exe code.pr Features: 1) You must use only tabs or only spaces for indents in any one file. You cannot mix them. 2) Each indent level can have any number of characters more than the previous level, whether you are using tabs or spaces. If you drop back to the left to dedent, and your column position does not match any level above, you will get a lexer error. 3) If you increase the indentation level above the previous line by even one space, and that previous line does not end in a colon, then the new line will be considered a continuation of the previous line. 4) If a line contains an active (not quoted or commented) (, {, or [ without a matching end character, then the following line is always a continuation, no matter what that following line contains. 5) There is still support for using the trailing backslash ( \ ) to indicate that the next line is a continuation. This may be removed in the future if everyone agrees to do so. From loic at fejoz.net Fri Apr 2 09:00:25 2004 From: loic at fejoz.net (Yermat) Date: Fri, 02 Apr 2004 16:00:25 +0200 Subject: Verifying temporal properties. Need problems. In-Reply-To: <68771ca.0404010839.39b0c24f@posting.google.com> References: <68771ca.0404010839.39b0c24f@posting.google.com> Message-ID: Bjorn Heimir Bjornsson wrote: > Hello all > > As part of a thesis, I am model checking Python programs (a limited > subset anyway). > > I have a very rough prototype that can deal with temporal properties > (LTL), that is statically prove properties of the kind: "if A happens, > then B should follow" or "if A happens, then B must not follow unless > C happens first". A,B,C here being function calls (system or other > library). The idea is that this might complement testing or manual > auditing during development. > > So the solution now requires a problem. > Basically I'm trying to find interesting areas where a programmer is > supposed to call specific functions in a particular order, but where > coding errors might prevent this. > I would be most happy with distinctively Python-related problems, like > some tricky-to-use system calls or something from Zope or > security-related issues, etc. > > So if any of you have ideas (specific function calls) where this kind > of tool would be useful, I would welcome feedback. > If replying privately, use bjornhb2_hotmail.com (more or less). > > Thanks a lot :) > Bjorn Hi, I do not have any python program to check but I'm interested in publications you might already have writen or pointers to python related problem. I'm working as engineer in a research team in formal methods area (http://www.loria.fr/equipes/model/). Did you look at similar project with Java (like http://bandera.projects.cis.ksu.edu/) ? I think you will find similar problem, no ? Did your prototype recognize use of the thread standard library (lock, etc) ? If you look at mailman (http://www.list.org/), you can check security property like "a non-members cannot send messages to the list", etc. Do you look at rather small or big project ? Sorry if I ask more question than I answer... ;-) The last one : When will you finish your Phd ? Lo?c From deetsNOSPAM at web.de Tue Apr 27 05:36:46 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Tue, 27 Apr 2004 11:36:46 +0200 Subject: Default Argument Inconsistency? References: Message-ID: Paul Sweeney wrote: > The python tutorial gives the following example to demonstrate the fact > that default args are only evaluated once: > > def f(a,L=[]): > L.append(a) > return L > > print f(1),f(2),f(3) > [1] [1,2] [1,2,3] > > now I'm confident I understand this, but I do not understand how changing > to the following (whatever the merits of so doing, it was an accidental > typo) > results in the output displayed: > > def f(a,L=[]): > if not L: L=[] > L.append(a) > return L > >>>> print f(1),f(2),f(3) > [1] [2] [3] > > surely on second entry to f, L == [1], so the "if not L:" should not > fire?! No, its not. As [] is logically false, the if not L: L = [] rebinds L with a fresh list. So the append is made to that list, not to the one L is bound to as default argument. -- Regards, Diez B. Roggisch From nospam at nopes Sun Apr 4 21:47:16 2004 From: nospam at nopes (Steve) Date: Mon, 05 Apr 2004 11:47:16 +1000 Subject: Session variables? Message-ID: <4070bad0$1@clarion.carno.net.au> Hi, I'm trying to find a clean way of sharing variables across different python webpages and scripts and I need something like a session variable for each user. Is this possible in Python? I've been "pickling" stuff and this doesn't work at all with mutliple users as things get mixed up. Is there any clean way of doing this? Thanks, Steve From fperez528 at yahoo.com Tue Apr 13 20:33:56 2004 From: fperez528 at yahoo.com (Fernando Perez) Date: Tue, 13 Apr 2004 18:33:56 -0600 Subject: plot+interaction References: Message-ID: John Hunter wrote: >>>>>> "Mark" == Mark Alford writes: > > Mark> I have been using the gnuplot.py package for simple 2D > Mark> plots. Works great. But I would like to have a tiny bit of > Mark> interactivity: > > Mark> I would like the program to know where (in terms of the plot > Mark> variables x and y) the user has mouse-clicked on the plot > Mark> window. > > Mark> Is there any other plotting package that offers this > Mark> functionality? With CVS gnuplot, I have code around (written by Arnd Baecker) which does this. Mail me directly if you are interested. Cheers, f From Use-Author-Supplied-Address at [127.1] Mon Apr 5 11:06:18 2004 From: Use-Author-Supplied-Address at [127.1] (Anonymous) Date: 5 Apr 2004 15:06:18 -0000 Subject: slightly OT: BUT NEEDs to be said Message-ID: <491Z9C8Y38082.4210416667@anonymous.poster> Hi I downloaded this document about Python recently: http://datamining.anu.edu.au/~ole/publications/python.pdf I loved the cute little Snake graphic. I think it would be great for Python.org/people behind Python to adopt this as an official mascot and DROP the god awful references to Monty Pythons's Flying Circus. It is the later which is causing a slow take up and reluctance of many individuals using Python. MPFC is a very very dated concept and because of it's strange whacky 'humour' has dubious extreme and loony left wing allegiences is not a good backdrop for Python. You should never bring politics into your product. Understand that in the UK a lot of people don't find MPFC amusing, and many of the 'comedians' have become extremely dispised (like Michael Palin who is universally recognised as a figure of great nauseum) and have become objects of ridicule. Let me put it this way Python as a languge and product is *damaged* by the references littered everywhere to MPFC. It colours the experience of it and when I think what scripting language shall I use to get x task done I think Python could do that and then oh no I'm not paying homage to the ghastly awful MPFC shit which I hate and will use Perl or PHP instead which are considerably more artistically 'neutral' I quite like Python as a language (apart from the tabbing replacing curly brackets which I'm not sure about) and think it stands up well to Perl and PHP but I cannot abide the nauseating, puke enducing, gut-wrenching, toe-curling references to Monty Python's shitty flying circus which is very much part of the *past* of an era in British comedy and should not be part of any software package's image. Please adopt the cute Python graphic as your official logo and mascot which works much better because it conjures up a *much more* positive metaphor of a powerfully slippery creature wrapping itself round numbers and strings etc. regards From grante at visi.com Wed Apr 28 09:42:02 2004 From: grante at visi.com (Grant Edwards) Date: 28 Apr 2004 13:42:02 GMT Subject: Don't understand wxPython ids References: <408ed938$0$17263$a1866201@newsreader.visi.com> <408f3061$0$17258$a1866201@newsreader.visi.com> Message-ID: <408fb4aa$0$17264$a1866201@newsreader.visi.com> On 2004-04-28, Doug Holton wrote: >>>I can only think of one reasn why they chose to use ids in the >>>first place. Assigning many objects the same id allows you to >>>use one EVT_* call for those objects. But is that really a >>>useful feature? Who knows? >> >> That's about the only thing I could think of. The few >> situations where I'd have wanted to do someting like that I'd >> gladly put a for-loop iterating over a list of objects in >> exchange for being able to use single-line of code the other >> 90% of the time. > > Right, there a couple of special cases to think of when > designing event bindings for a gui toolkit. One is where you > want multiple controls to share the same event handler (like a > button and a menu item that do the same thing). Just pass the same function to both of them when you create them? > Another case is allowing people to change event bindings "on > the fly", after a window constructor has already been called > and the window set up. Provide a method to set the action for an object instance after it's been created. Both of these have been SOP in other GUI toolkits for a dog's age, and I can't figure out any benefit to the ID scheme. Using an outside function to reach in and torque on the object's internals seems so un-Pythonesque. But, all sorts of smart people rave about wxPython, so I thought there must be some benefit to the ID scheme that I'm missing. > I proposed some changes similar to you, see this thread: > http://lists.wxwidgets.org/cgi-bin/ezmlm-cgi?11:sss:23979:200311:dcgnanikkojpgmpdpmio#b > but nothing came out of it. I did code up an implementation > for Wax (http://wiki.wxpython.org/index.cgi/Wax ), but I don't > know if it was included. -- Grant Edwards grante Yow! Nice decor! at visi.com From claird at lairds.com Mon Apr 26 14:47:37 2004 From: claird at lairds.com (Cameron Laird) Date: Mon, 26 Apr 2004 18:47:37 -0000 Subject: Is Perl *that* good? (was: How's ruby compare to it older brother python) References: <108qi5opkrfnv56@corp.supernews.com> Message-ID: <108qma9385hvg27@corp.supernews.com> In article , Leif B. Kristensen wrote: >Cameron Laird rose and spake: . . . >> I continue to conclude that all these languages are >> roughtly equally competent at managing strings. > >Perhaps, but right now I think that I'm in love with Python. Consider >these two equivalent routines in PHP and Python: . [marvelous, if slightly unfair, example] . . >My PHP coding may be suboptimal, but in terms both of codability and >readability as well as in sheer elegance, I find the Python version >superior in any way. . . . I consider infatuation with Python entirely healthy. In fact, I often *do* argue just the same position as you take here: that Python is strongly and demonstrably superior to PHP. I just want to be as precise as I can about what the differences are. -- Cameron Laird Business: http://www.Phaseit.net From nospam at brasnet.org Sun Apr 25 17:23:12 2004 From: nospam at brasnet.org (Chaos Master) Date: Sun, 25 Apr 2004 18:23:12 -0300 Subject: DDE using the Windows version of Python Message-ID: Hello people Is there any "module" to do communication between a Python program and other software, using DDE protocol? Thanks. -- Chaos Master? - Posting from Brazil MSN: wizard_of_yendor at hotmail.com BRASNET: wizard_of_yendor "A Elbereth Gilthoniel, silivren penna miriel o menel aglar elenath!" From fumanchu at amor.org Fri Apr 23 13:00:02 2004 From: fumanchu at amor.org (Robert Brewer) Date: Fri, 23 Apr 2004 10:00:02 -0700 Subject: Generic constructors and duplication of internal Python logic Message-ID: Peter Otten wrote: > def setLocals(d, selfName="self"): > self = d.pop(selfName) > for n, v in d.iteritems(): > setattr(self, n, v) > > class Demo(object): > def __init__(self, foo, bar, baz=2, bang=3): > setLocals(locals()) *Very* nice and clean. John, if you still want the mixin (to avoid have to call setLocals in every __init__, you could try a mixin like this (tested just enough to post without egg on my face): class ArgMixin(object): def __new__(cls, *args, **kwargs): inst = object.__new__(cls, *args, **kwargs) initargs = list(cls.__init__.func_code.co_varnames) # Remove 'self' from initargs initargs.pop(0) defaults = list(cls.__init__.func_defaults) # Set provided positional arguments as attributes of instance for arg in args: name = initargs.pop(0) setattr(inst, name, arg) # Set keyword arguments as attributes of instance, # using defaults if no value was passed. while initargs: name = initargs.pop(0) default = defaults.pop(0) setattr(inst, name, kwargs.get(name, default)) return inst class Demo(ArgMixin): def __init__(self, foo, bar, baz=2, bang=3): pass ...you would have to be careful when/if overriding __new__ in a subclass. Also, __init__ can still change those attributes. I'm sure someone will find something wrong with it* ;) but the idea is sound, and uses some of Python's "internal logic" that you mentioned. Robert Brewer MIS Amor Ministries fumanchu at amor.org * For example, I didn't chase down funky calls like Demo(bar=3, foo="d'oh!"), which exhaust the defaults list. From elainejackson7355 at home.com Sun Apr 4 15:34:50 2004 From: elainejackson7355 at home.com (Elaine Jackson) Date: Sun, 04 Apr 2004 19:34:50 GMT Subject: splitting a long token across lines References: Message-ID: why can't you just write it like this: MODULUS = A*pow(10,a) + \ B*pow(10,b) + \ C "Nakamura" wrote in message news:ef0c9173.0404032349.742f59e6 at posting.google.com... | Hi all, | | Say, I have a very long integer constant , how can | I split across lines ? | I tried something like | MODULUS = 7567567567567567567567567567567\ | 7567507546546986094860986094860\ | 2345646986598695869548498698989\ | ... | but it doesn't compile. | Is there another way to write a long numeric constant besides writing | it as a string and then converting to long? I also wouldn't like to put | it all on one very long line. | | Thanks! From jcarlson at uci.edu Mon Apr 5 18:50:29 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Mon, 05 Apr 2004 15:50:29 -0700 Subject: query regarding OOP functionality in python In-Reply-To: References: <407153BD.9080203@students.iiit.net> Message-ID: > If you absolutely must have these features, stick to C++ or Java. Or do something crazy like this... Error = '''\ Received signature of: %s Expected one of: %s''' class polymorpher(object): def __init__(self): self._dict = {} def add_funct(self, funct, *argtypes): self._dict[argtypes] = funct def __call__(self, *args, **kwargs): t = tuple(map(type, args)) try: f = self._dict[(t,)] except KeyError: raise TypeError(Error%(t, self._dict.keys())) return f(*args, **kwargs) >>> funct = polymorpher() >>> funct.add_funct(lambda *args:str(args), (int, int)) >>> funct.add_funct(lambda *args:str(args), (float, int)) >>> funct(1,2) (, ) '(1, 2)' >>> funct(1.5, 6) (, ) '(1.5, 6)' >>> funct(1, 1.5) (, ) Traceback (most recent call last): File "", line 1, in ? File "", line 12, in __call__ TypeError: Received signature of: [, ] Expected one of: [((, ),), ((, ),)] >>> Ahh, polymorphism. - Josiah From mwh at python.net Sat Apr 10 13:16:28 2004 From: mwh at python.net (Michael Hudson) Date: Sat, 10 Apr 2004 17:16:28 GMT Subject: print u"\u0432": why is this so hard? UnciodeEncodeError References: Message-ID: "Martin v. L?wis" writes: > David Eppstein wrote: > > Py2.3 sure doesn't discover the encoding of my terminal automatically: > > hyperbolic ~: python > > Python 2.3 (#1, Sep 13 2003, 00:49:11) [GCC 3.3 20030304 (Apple > > Computer, Inc. build 1495)] on darwin > > Ah, Darwin. You lose. > > If anybody can tell me how to programmatically discover the encoding > of Terminal.App, I'll happily incorporate a change into a 2.3.x release. The user can set it per-terminal, at runtime, with no notification to the running process that it has done so! You can't even find out the encoding in use via apple events, which is a bit of surprise. Filing a bug with apple might get that changed for 10.4... Cheers, mwh -- Reading Slashdot can [...] often be worse than useless, especially to young and budding programmers: it can give you exactly the wrong idea about the technical issues it raises. -- http://www.cs.washington.edu/homes/klee/misc/slashdot.html#reasons From peter at engcorp.com Tue Apr 13 08:51:54 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 13 Apr 2004 08:51:54 -0400 Subject: Wrapper round x86 Assembler In-Reply-To: <8089854e.0404122329.5dfe5ce1@posting.google.com> References: <8089854e.0404082353.7bf163a2@posting.google.com> <4dKdnQlIXMIXIevdRVn-gg@powergate.ca> <8089854e.0404100204.504186a0@posting.google.com> <8089854e.0404122329.5dfe5ce1@posting.google.com> Message-ID: Fuzzyman wrote: > Right ? I got confused by the mention that they could handle inline > assembler.... so many of the compilers include an assembler as well... > purely for 'inline assembly'.... ?? That's correct. Of course, many also do the CC+AS thing, but I think that's no longer the most common approach. > My past experience of assembly was using an operating system that > handled multitasking 'behind the scenes' (pre-emptive multitasking) - > so there was no performance hit on the rest of your system from > writing crappy assembly - and the internal architecture of the > processor was useful enough to make coding fun..... The 68K was certainly assembly-friendly, compared to anything yet produced by Intel. :-) > It does occur to me that for a certain subset of a 'pseudo assembly > language' a 'cross-platform assembler' could work I really think that in most ways that matter (not quite all, but most) this is exactly what C was designed to be and is. It is only a very thin layer on top of assembly, really. You can think of it is a pseudo-high-level language designed to allow assembly programmers to write code roughly the way they would if they were not just hacking. The Amiga's huge variety of STRUCT macros, for example, are practically field-for-field identical to how C structs work, mostly just providing an efficient method for specifying the offsets of each field. Pointers are nothing more than a more concise way of expressing the "indirect" addressing mode. Heck, C even has (or had) the "goto" statement and labels! And the for loop syntax is basically just how assembly loops are done, but again in a more concise and readable fashion. I think anyone who attempted to do a "cross-platform assembler" would quickly find themselves heading in the direction of something like C. (I know such things have actually been attempted, and even exist, by the way. They just aren't mainstream and clearly C has greater success.) Any attempt to stay at the level of hardware registers would immediately prevent the term "cross-platform" from applying. -Peter From cmkleffner at gmx.de Thu Apr 15 15:31:32 2004 From: cmkleffner at gmx.de (cmkl) Date: 15 Apr 2004 12:31:32 -0700 Subject: Python for Presentations References: <2322284.zRWg8i6zR0@id-216798.user.uni-berlin.de> Message-ID: <3b091a1c.0404151131.4454912a@posting.google.com> Karsten Heymann wrote in message news:<2322284.zRWg8i6zR0 at id-216798.user.uni-berlin.de>... > Chris wrote: > > > Is anyone aware of Python packages/software for generating > > "presentations"-- something that can generate a nice XHTML/CSS or PDF > > presentation would be cool. I am looking for a better alternative to > > PowerPoint for building presentation slides, and if that alternative > > used Python, that would be even better. > > > > Otherwise I could use LaTeX or something, I suppose. > > honestly, use latex! especially latex-beamer is awesome > (latex-beamer.sf.net) if you have at least a little knowledge of latex. I > use python for nearly all programming tasks, but presentations are another > are. > > Karsten If you want to impress your auditorium and program your presentation in python take a look at slithy http://isotropic.org/uw/slithy/ Regards Carl From imbosol at aerojockey.invalid Wed Apr 28 01:29:06 2004 From: imbosol at aerojockey.invalid (Carl Banks) Date: Wed, 28 Apr 2004 05:29:06 GMT Subject: Is Perl *that* good? References: <87fzaqmm8t.fsf@strauser.com> <38ec68a6.0404262308.50029919@posting.google.com> Message-ID: Roy Smith wrote: > Carl Banks wrote: >> especially because regexps are >> prone to being used in recursive functions and such > > Why are regexps prone to being used in recursive functions? Prone was probably a bit too strong a word, but using regexps inside a recursive function is far from an obscure use. It can show up in functions that parse arbitrarily nested text, which typically use recursion to handle the arbitrarily nested part. -- CARL BANKS http://www.aerojockey.com/software "If you believe in yourself, drink your school, stay on drugs, and don't do milk, you can get work." -- Parody of Mr. T from a Robert Smigel Cartoon From nc-jantzegu at netcologne.de Fri Apr 23 01:12:58 2004 From: nc-jantzegu at netcologne.de (Günter Jantzen) Date: Fri, 23 Apr 2004 07:12:58 +0200 Subject: Regexp optimization question References: Message-ID: "Magnus Lie Hetland" schrieb im Newsbeitrag news:slrnc8gal3.9da.mlh at furu.idi.ntnu.no... > > Any ideas? > Maybe Plex is helpful. I did not use it already, but it seems to adress your problem The author of Plex is Greg Ewing. He build Pyrex on top of Plex The documentation http://www.cosc.canterbury.ac.nz/~greg/python/Plex/version/doc/index.html contains """ Plex is designed to fill a need that is left wanting by the existing Python regular expression modules. If you've ever tried to use one of them for implementing a scanner, you will have found that they're not really suited to the task. You can define a bunch of regular expressions which match your tokens all right, but you can only match one of them at a time against your input. To match all of them at once, you have to join them all together into one big r.e., but then you've got no easy way to tell which one matched. This is the problem that Plex is designed to solve. """ Hope I could help you Guenter From sarge at arena.invalid Thu Apr 29 16:13:30 2004 From: sarge at arena.invalid (Sarge) Date: Thu, 29 Apr 2004 20:13:30 GMT Subject: MATLAB2Python References: <3064b51d.0404290654.58e59124@posting.google.com> Message-ID: > I have found numerous cases where Python programs run 10-100 > times slower or more than a comparable Fortran 95 program. Uh-oh. This is not fine. I want to switch to py in order to achieve more flexibility especially in the areas of GUIs, distributed computing, and oo- programming. But I don't want my programs run 100 times slower! Is it possible to integrate some fortran compiled routines in order to speed up the more time-consuming steps? Thanx, Sarge P.S. I have already tried Fortran95 for a while, but I found it's a very old-fashioned language, more than Matlab itself, I didn't like it very much. From aahz at pythoncraft.com Sat Apr 10 10:10:17 2004 From: aahz at pythoncraft.com (Aahz) Date: 10 Apr 2004 10:10:17 -0400 Subject: Function args References: Message-ID: In article , Jean-Michel Caricand wrote: > >I'm new in Python. I have a problem with function args. I want to pass >args by reference because the function must modify this arg. How I do >that in Python. Here's something else that should help: http://starship.python.net/crew/mwh/hacks/objectthink.html -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Why is this newsgroup different from all other newsgroups? From rmunn at pobox.com Thu Apr 1 12:03:59 2004 From: rmunn at pobox.com (Robin Munn) Date: Thu, 01 Apr 2004 17:03:59 GMT Subject: [OT] Top posting is a PITA References: <569c605ld1cj8fc1emolk08ete0s1prls1@4ax.com> <106di86neu1qh4d@news.supernews.com> <4069a001$0$4237$afc38c87@news.easynet.co.uk> <4069e9d9$0$8915$636a15ce@news.free.fr> <406a98ee$0$290$edfadb0f@dread12.news.tele.dk> <106lh64rda8t9d4@news.supernews.com> Message-ID: <3YXac.5683$406.5360@newssvr15.news.prodigy.com> Roy Smith wrote: > Jacek Generowicz wrote: >> top-posters tend to write codswallop more often that those who trim >> and organize their replies carefully. >> >> This is partly because the process of trimming the original post, >> forces you to identfy the relevant points being made > > What makes you think people who top post don't also put a lot of effort > into carefully organizing their replies and trimming the original post > down to the most relevant points? Bitter, hard-earned experience. Some people do so, as you demonstrated, but IMB,H-EE the vast majority do not. Another problem that occurs when some people top-post and some do not is that the conversation thread quickly becomes unreadable unless someone takes the time to rearrange it into a consistent form (as I did in composing this reply). -- Robin Munn rmunn at pobox.com From vineet at eswap.com Sun Apr 11 23:00:28 2004 From: vineet at eswap.com (Vineet Jain) Date: Sun, 11 Apr 2004 23:00:28 -0400 Subject: Is there a boolean(somestring) equivalent of int(somestring). bool('false') -> True In-Reply-To: <20040411223514.GA30373@unpythonic.net> Message-ID: Thanks for the code suggestion. >From what I've read, most people (including me) are attracted to Python because of how natural it is. Give that is a high priority for the language designers: How can anyone argue that bool('false') = True is more natural (and what you would expect) than bool('false') = False Having just got over the surprise that int('2.1') fails while int(float('2.1')) works the above surprises me even more. If the int case was rejected because it is 'better to be explicit than not' then how can you bool('false') be allowed?? I still think int('2.1') should return 2. If the programmer is using int then he should know that what he will get out of the result is an int regardless of what comes in. Especially since int accepts a float object in any case. It seems a waste of resources to have to first convert a string to a float object and then convert it to an int object. Booleans are associated with (True, on, 1 and yes) and bool() on any them should return True. VJ -----Original Message----- From: Jeff Epler [mailto:jepler at unpythonic.net] Sent: Sunday, April 11, 2004 5:35 PM To: Vineet Jain Cc: python-list at python.org Subject: Re: Is there a boolean(somestring) equivalent of int(somestring). bool('false') -> True The reason that >>> bool('false') returns True is the same reason that >>> not 'false' is False: A non-empty string, when treated as a boolean, is true. Changing the meaning of bool() is not likely to happen. Here's one piece of code you might try to get the behavior you desire: true_values = '1 yes true on'.split() false_values = '0 no false off'.split() def parse_boolean_value(s): if s in true_values: return True if s in false_values: return False raise ValueError 'i in seq' is just like checking whether any item in seq is equal to i. If seq is a dictionary or a set (or defines __contains__), this test can be a little more efficient, but the efficiency is unlikely to matter when there are only 4 items. Jeff From skip at pobox.com Thu Apr 29 22:34:55 2004 From: skip at pobox.com (Skip Montanaro) Date: Thu, 29 Apr 2004 21:34:55 -0500 Subject: Why cannot jump out the loop? In-Reply-To: References: Message-ID: <16529.47951.692940.903411@montanaro.dyndns.org> Jinming> I have a very simple python program, which includes a while Jinming> loop. But to my surprise, it cannot jump out the while Jinming> loop. Does anyone know why? Jinming> Here is the program: Jinming> ___________________________ Jinming> #!/usr/bin/env python Jinming> import sys Jinming> n=sys.argv[1] Jinming> i=0 Jinming> while i print "i=",i," n=",n Jinming> i+=1 Jinming> ----------------------------------------------------- You need to convert sys.argv[1] to an integer. Try this instead: #!/usr/bin/env python import sys n = int(sys.argv[1]) i = 0 while i < n: print "i=", i, " n=", n i += 1 Comparisons between any two objects generally always succeed (this facilitates sorting of heterogenous lists), but doesn't always sort in useful ways: >>> "1" > 1000 True Skip From p_s_oberoi at hotmail.com Mon Apr 26 01:03:41 2004 From: p_s_oberoi at hotmail.com (Paramjit Oberoi) Date: Mon, 26 Apr 2004 00:03:41 -0500 Subject: CamelCase versus wide_names (Prothon) References: <6e0680ac.0404211252.7f7b4358@posting.google.com> <4086DFA7.9736E7D3@alcyone.com> Message-ID: >> If the language 'knew' that identifiers potentially consisted of >> multiple words, maybe it could detect a few different kinds of >> styles and automatically do the right thing? > > That could be achieved by making it case-insensitive and > underscore-ignoring. That would cause aliasing if the two words that form the identifier also form a third word when put together. For example: if sys.platform = 'Windows CE': win_ce = True if feeling_pain: wince() From iv at an.voras.fer Mon Apr 19 15:34:48 2004 From: iv at an.voras.fer (Ivan Voras) Date: Mon, 19 Apr 2004 21:34:48 +0200 Subject: Processes with timeout In-Reply-To: References: Message-ID: Markus Franz wrote: > How can I make it sure that every child-process terminates after x senconds > (wether it has finished or not)? You can toy around with signals. From outside the child process, you can send it SIGTERM after some time has passed (and catch it in the process). From inside the process, you can use SIGALARM to track when the time has expired. Or you can combine the two. Or, you can start a "watchdog thread" (a thread that mostly sleep()-s, but now and then checks the time) From fredrik at pythonware.com Tue Apr 20 09:36:46 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 20 Apr 2004 15:36:46 +0200 Subject: Dollar sign ($) on foriegn keyboards? (prothon) References: Message-ID: Mark Hahn wrote:? > We are considering switching to the dollar sign ($) for self, instead of the > period ( . ) we are using now in Prothon. any reason you cannot set up a mailing list for your little pet project? you're generating tons of off-topic traffic, and frankly, I don't think I'm the only one who couldn't care less about your pre-alpha hack with minimum capabilities. (if I posted hundreds of messages for every pre-alpha hack I've ever made, people would quickly label me as an annoying crack- pot.) From usenet at -OBFUSCATION-joefrancia.com Tue Apr 27 11:41:57 2004 From: usenet at -OBFUSCATION-joefrancia.com (Joe Francia) Date: Tue, 27 Apr 2004 15:41:57 GMT Subject: creating an python function with DCoracle2 module References: <46a86393.0404270242.60fe9b35@posting.google.com> Message-ID: <41679251.UDvaYHOLQI@joefrancia.com> pepericou wrote: > I'm trying to developp an application which use Zope and DCOracle2 > module to access Oracle database. I've install the DCOracle2 product > on Windows XP, but when I create a python function to access my > database, I' have the following error when I test it : > import DCOracle2 is unauthorized > Can You help me ? > Thank you I'm assuming you're creating a Python Script in Zope via the ZMI. Zope forbids the importing of all but a few modules in the ZMI, for security reasons. You will need to use an External Method or, even better, find a Zope Oracle Product that will allow you to create a connection in one of your folders and allow you to use Z SQL Methods. BTW: You should probably post further questions about Zope to either the Zope-General or Zope-Database list. -- Soraia: http://www.soraia.com From colin.blackburn at durham.ac.uk Tue Apr 6 09:51:00 2004 From: colin.blackburn at durham.ac.uk (Colin Blackburn) Date: Tue, 06 Apr 2004 14:51:00 +0100 Subject: design by contract versus doctest References: <407174ea$0$5066$4d4ebb8e@news.nl.uu.net> <4072977b$0$1699$afc38c87@news.easynet.co.uk> <4072a7d3$0$23314$afc38c87@news.easynet.co.uk> Message-ID: On Tue, 06 Apr 2004 13:51:29 +0100, Peter Hickman wrote: > Colin Blackburn wrote: > >> Only while checking is turned on. It is a design philosophy. You >> specify the pre and post-conditions before code is even thought of, it >> is part of the design. > > Sure but the checks are still made by the function that is called not by > the caller of the function. Which was my point and contrary to what aku > said. > > aku wrote: > > But in "design by contract" this responsibility is squarely > > on the shoulders of the caller, and is *not* checked in > > the function. Aku is correct, no checks are (necessarily) made by the function in installed code. It is the caller's responsibility to satisfy the pre-conditions. >> This says that *if* the pre-conditions are met (by the caller) *then* >> the post-conditions will be guaranteed to be met (by the called >> method.) > > No this is not entirely true, the require and ensure and both parts of > the contract. The function will not be called if the require section is > found to be false (such as count being greater than capacity). In the installed code the pre-conditions are not necessarily implemented therefore the function cannot refuse to run since it does not know its pre-condition at this stage. > Then after the function is executed (the do portion) then second half of > the contract is checked, the ensure section. If these conditions fail > then the contract is broken and the call fail just as if the require had > failed. Again, not necessarily in the installed code since the post-conditions are not known. However, the result will be guaranteed if the preconditions are met even in the installed code since the code wil have been designed properly. > Take this as an example (hacked at the keyboard, probably wont work) > > double (x: ELEMENT) is > require > x > 0 > do > x = x * -2 > ensure > x > 0 > end > > If you call it with double(-12) then the require section fails. If you > call it with double(12) then the require section passes but the do > section is creating a negative number and so the ensure section fails. Your post-condition is incorrect. The method must ensure that the result is double the input parameter if that parameter is greater than zero. Howver, yes in this case the ensure will barf but this is at the design stage and is there to ensure you get the method right in the first place. When you deliver this routine the ensure will not be implement but by then you will have corrected your typo. > Getting the require section to pass is no guarantee that the > post-conditions (ensure section) will be met, the do section is code > like anything else and may get things wrong. In correctly developed DbC that is precisely what is guaranteed. The post-condition is *guaranteed* if the pre-condition is met. It is a design tool. Colin -- From jbperez808 at yahoo.com Tue Apr 6 23:50:05 2004 From: jbperez808 at yahoo.com (Jon Perez) Date: Wed, 07 Apr 2004 11:50:05 +0800 Subject: Type checking inside a C extension... doesn't throw exception on failure In-Reply-To: References: <40712D9E.3050802@prescod.net> <407229F6.6080809@yahoo.com> Message-ID: Andrew MacIntyre wrote: > First rule of using the Python C API: _always_ check the return value of > API functions. This only applies to API functions which return PyObject*, right? From p_s_oberoi at hotmail.com Tue Apr 27 14:15:58 2004 From: p_s_oberoi at hotmail.com (Paramjit Oberoi) Date: Tue, 27 Apr 2004 13:15:58 -0500 Subject: Is Perl *that* good? References: <108q51j4dscn7dc@corp.supernews.com> <87fzaqmm8t.fsf@strauser.com> <38ec68a6.0404262308.50029919@posting.google.com> Message-ID: > Asun> Regex is much more 'immediate' in Perl. > > Sure, it's syntactically bound into the language. There will always be an > extra constant overhead to enable regular expressions in Python. That If only compiled regular expression objects allowed easy access to the last match object, python regxes would become significantly more convenient. For example, today you have to write: m = myregex.match(line) if (m): xyz = m.group('xyz') It would be much easier to do: if myregex.match(line): xyz = myregex.lastm.group('xyz') Having to introduce a new variable name for a match object just muddles the code unnecessarily in common regex usage scenarios. -param From jepler at unpythonic.net Wed Apr 14 20:06:05 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 14 Apr 2004 19:06:05 -0500 Subject: Python 2.2.x core dumping In-Reply-To: References: Message-ID: <20040415000605.GA13706@unpythonic.net> You could use sys.setrecursionlimit() to lower the recursion limit (if it's recursion in Python code). That's the only Python-specific thing that comes to mind as easily tweakable which might turn the segv into a debuggable backtrace. When I ran a simple recursive C program under gdb, the stack was intact when the program stopped. Have you tried this? If you can return to most any Python API call in the stack trace and return NULL, you may be able to get a Python exception as a result. just a few ideas, Jeff From cm at leetspeak.org Fri Apr 30 08:30:22 2004 From: cm at leetspeak.org (Michael Walter) Date: Fri, 30 Apr 2004 14:30:22 +0200 Subject: Ideas for Python 3 In-Reply-To: References: Message-ID: Ville Vainio wrote: >>>>>>"Michael" == Michael Walter writes: > > > Michael> Almost. Or write mapc ("map currying") and have: > > Note - the name mapc is very misleading, because it looks too much > like Lisp mapc (mapcar, equicalent to normal python map). > True. L = map(curry(pow),range(2,6)) might be more intelligent, anyway, what do you think? Cheers, Michael From jacobsmail at postmark.net Mon Apr 26 17:01:33 2004 From: jacobsmail at postmark.net (Jacob H) Date: 26 Apr 2004 14:01:33 -0700 Subject: Is there a Python library that packs binary data into one file? Message-ID: <85b54e91.0404261301.69d5c1e9@posting.google.com> Hello all, Today I began writing a utility script that takes given binary files and puts them all into one datafile. My idea is to be able to access any binary data I want by indexing the datafile, e.g. wanted_image_data = datafileobj[IMAGE_DATA]. The purpose is to hide external image files from the user in a simple game I'm writing. Though I have a good idea of how to implement this, before I begin I am curious to know if some Python master out there has already come out with a library that does the same. Anyone? :) From tdelaney at avaya.com Thu Apr 29 19:33:05 2004 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Fri, 30 Apr 2004 09:33:05 +1000 Subject: outline-style sorting algorithm Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE016BCCC9@au3010avexu1.global.avaya.com> Thorsten Kampe wrote: > You DSU approach took about 43 s and mine took about 86 s. > Than I tested range(1000000) in reverse order: > Your sorted program took about 24 s and mine about 5! I've taken the code that you posted in response to Terry, fixed it (there were some extra parentheses and I don't have the `colour` module). I didn't modify any of the functions. Windows XP SP1 P4 3GHz (HT enabled) Python 2.3.3 a = range(1000000); a.reverse() b = randseq(1, 1000000, 1000000, 'repeat') cpu: 3.610, total: 3.609 # timer(funcsort, a, lambda x: x, 'dsu') cpu: 1.387, total: 1.390 # timer(funcsort, a, lambda x: x, 'pass') cpu: 9.050, total: 9.047 # timer(funcsort, b, lambda x: x, 'dsu') cpu: 26.459, total: 26.469 # timer(funcsort, b, lambda x: x, 'pass') These results are in stark contrast to yours. What version of Python were you using? > So you cannot simply state that DSU is faster than passing a function > if the structure of the input you want to sort is unknown... That's why I said "almost all cases preferred". In the first run above, it's obvious that the additional overhead of generating the keys, etc exceeds the time spent comparing. Most likely because the 2.3 sort is very efficient for partially-ordered lists (like a reversed list) and therefore the comparison function doesn't get called many times. Now, when randomness is introduced the comparison function ends up being called a lot more and it's overhead is far greater than with DSU. Tim Delaney From paul at prescod.net Sun Apr 4 22:52:09 2004 From: paul at prescod.net (Paul Prescod) Date: Sun, 04 Apr 2004 19:52:09 -0700 Subject: Advocacy opportunity In-Reply-To: <1071eiaddi7mo95@news.supernews.com> References: <10719mdp83juif4@corp.supernews.com> <1071eiaddi7mo95@news.supernews.com> Message-ID: <4070C9D9.4080704@prescod.net> John Roth wrote: > > I wouldn't. To me, a root class is a common class that is **the** > root of the object hierarchy, in some useful sense such as > contributing numerous common methods. Granted, new style > classes are rooted in object, but object doesn't seem to > contribute much except for __getattribute__. >>> isinstance(5, object) True >>> dir(object) ['__class__', '__delattr__', '__doc__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__'] >>> dir(5) ['__abs__', '__add__', '__and__', '__class__', '__cmp__', '__coerce__', '__delattr__', '__div__', '__divmod__', '__doc__', '__float__', '__floordiv__', '__getattribute__', '__getnewargs__', '__hash__', '__hex__', '__init__', '__int__', '__invert__', '__long__', '__lshift__', '__mod__', '__mul__', '__neg__', '__new__', '__nonzero__', '__oct__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__str__', '__sub__', '__truediv__', '__xor__'] Paul Prescod From peter at engcorp.com Sat Apr 17 15:11:16 2004 From: peter at engcorp.com (Peter Hansen) Date: Sat, 17 Apr 2004 15:11:16 -0400 Subject: Static Modules... In-Reply-To: References: Message-ID: Grzegorz Dostatni wrote: >>"import this" -> "Explicit is better than implicit." > > This is exactly my point. My way will only work when you reference the > name explicitly, as in: > > sys.setrecursionlimit(500) > > You're referencing the sys module explicitly. Other than that this > "problem" exactly parallels the discussion between static and dynamic > typing. And we know which way python chooses to go. That's not entirely accurate, I think. With static typing, you can't even use a variable if you don't predefine it, but predefining it doesn't necessarily give it a value (or it gives it a benign default value). With dynamic typing, just asking for a variable doesn't (normally) magically create one with an appropriate value. This hack is a cool idea for interactive prompts, but in real code and even at the prompt it could actually be quite "dangerous". Importing a module can cause arbitrary code to execute, so it makes some sense to _require_ the import statement. After all, what if I had a module called, perhaps inappropriately, "launch" and it triggered the launch of my personal anti-aircraft missile when imported? (Yes, bad style too, but I wrote this control code long ago before I learned good style. ;-) Now in one of my other modules, I have a subtle bug** which involves an object named, perhaps unsurprisingly for this example, "launch". The code looks like this actually (pulled right out of the source tree!), slightly edited to preserve national security: def checkLaunchPermission(self): lunch = self.findLaunchController() if launch.inhibited: # code that doesn't launch anything... Now if I understand it properly, when your hack is in place this would actually import the launch module and cause all hell to break loose. Did I just make a case for static typing with Python? Well, perhaps, but only in the relatively dangerous area of module imports and there, unlike with simple variable names, Python already requires explicit (i.e. static) definitions... -Peter ** Thanks to Greg for starting this discussion as otherwise I would not have discovered this bug in time to save you all... From fxn at hashref.com Thu Apr 1 11:25:10 2004 From: fxn at hashref.com (Xavier Noria) Date: 1 Apr 2004 08:25:10 -0800 Subject: outline.el usage? References: <31a13074.0404010226.6aba9509@posting.google.com> Message-ID: <31a13074.0404010825.fb379e7@posting.google.com> fxn at hashref.com (Xavier Noria) wrote in message news:<31a13074.0404010226.6aba9509 at posting.google.com>... > A Google search here for folding Python code in Emacs pointed to > outline.el I am sorry, I meant the question to be about outdent.el, not outline.el. -- fxn From jjl at pobox.com Thu Apr 22 17:37:14 2004 From: jjl at pobox.com (John J. Lee) Date: 22 Apr 2004 22:37:14 +0100 Subject: Generic constructors and duplication of internal Python logic References: <87ekqq41ya.fsf@pobox.com> <87oepnzlbp.fsf@pobox.com> Message-ID: <87k707elth.fsf@pobox.com> Peter Otten <__peter__ at web.de> writes: > John J. Lee wrote: > > > Peter Otten <__peter__ at web.de> writes: > > > >> John J. Lee wrote: > > [...] > >> You could use a noop method check_attrs() to define the argspec. > >> check_attrs() is then called from the mixin's __init__() just to check > >> that the parameters comply. > >> > >> import inspect > >> > >> def make_attrspec(f): > >> a = inspect.getargspec(f) > >> names = a[0] > >> if names[0] in ["self", "cls"]: > >> # XXX for now relies on naming convention > >> del names[0] > >> defaults = a[3] > >> for i in range(-1, -len(defaults)-1, -1): > >> names[i] = names[i], defaults[i] > >> return names > >> > >> class ArgsMixin: > >> def __init__(self, *args, **kwds): > >> self.check_attrs(*args, **kwds) > >> > >> class Blah(ArgsMixin): > >> def check_attrs(self, foo, bar, baz, optional1="first", > >> optional2="second"): > >> pass > >> attr_spec = make_attrspec(check_attrs) > > > > Clever. But how to get __init__ to assign the arguments to the > > instance? > > > > b = Blah(foo=1, bar=2, optional1=4) > > assert b.foo, b.bar, b.optional1 = 1, 2, 4 > > > > > > That half of the problem is missing in your solution. > > I'll give it a try (untested): > > class ArgsMixin: > def __init__(self, *args, **kwds): > self.check_attrs(*args, **kwds) > # positionals provided > for n, v in zip(self.attr_spec, args): > setattr(self, n, v) But the actual args may (quite legally) be longer than the args part of attr_spec, and then: >>> attr_spec = ["foo", "bar", ("a", "b")] >>> args = [1, 2] >>> zip(attr_spec, args) [('foo', 1), ('bar', 2)] >>> args = [1, 2, 3] >>> zip(attr_spec, args) [('foo', 1), ('bar', 2), (('a', 'b'), 3)] # wrong, can't do setattr! >>> This can be fixed, but then we move towards my clumsy-but-correct (I hope) implementation. I'm disappointed there's no simple solution that makes better use of Python's own knowledge of argument specifications. > # positionals using defaults > for nv in self.attr_spec[len(args):]: > if not isinstance(nv, basestring): > n, v = nv > if not n in kwds: > setattr(self, n, v) > # keyword args > for n, v in kwds.iteritems(): > setattr(self, n, v) [...] John From loic at fejoz.net Thu Apr 29 03:10:42 2004 From: loic at fejoz.net (Yermat) Date: Thu, 29 Apr 2004 09:10:42 +0200 Subject: Is classless worth consideration In-Reply-To: References: <1090r77d97k0tb1@news.supernews.com> Message-ID: Michael wrote: > >> It's just occured to me that backing into that particular >> issue might work: use class methods and never bother >> with instantiating the classes at all. I'm not sure what >> we'd lose. (possibly descriptors?) >> > You can already use: > > class test: > x = 1 > > t = test > print t.x > > > Is there any way to to call a class method without making an instance of > that class? To me that would be useful because you could mimic modules > without having to create a sepperate file. Or is there already a way to > do that? > this way ? ! ? >>> class Test(object): ... x = 1 ... def incX(cls, inc): ... cls.x += inc ... incX = classmethod(incX) ... >>> >>> >>> t = Test >>> t.x 1 >>> t.incX(2) >>> t.x 3 But is it really usefull ? If you really want something per instance look at the following code... >>> def attach(inst, fct, attrName): ... setattr(inst, attrName, fct.__get__(inst, inst.__class__)) ... >>> >>> class Test(object): ... pass ... >>> >>> t = Test() >>> t.x = 2 >>> >>> def incX(self, inc): ... self.x += inc ... >>> >>> attach(t, incX, 'incX') >>> >>> t.x 2 >>> t.incX(3) >>> t.x 5 >>> >>> t1 = Test() >>> hasattr(t1, 'x') False >>> hasattr(t1, 'incX') False From jdhunter at ace.bsd.uchicago.edu Fri Apr 16 11:54:29 2004 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Fri, 16 Apr 2004 10:54:29 -0500 Subject: a little math problem Message-ID: I have a number base, float or int. I need routines that return the largest multiple of base < x, largest multiple of base <=x, smallest multiple of base > x and smallest multiple of base >= x. For integer base, I have been doing def nearest_geq(base, x): if x%base!=0: return nearest_gt(base, x) else: return x def nearest_leq(base, x): return int(x)//base * base def nearest_gt(base, x): return int(x+base)//base * base def nearest_lt(base, x): return int(x-base)//base * base Is there a more elegant solution that works well for floats too? JDH From michaelmossey at yahoo.com Thu Apr 8 21:22:43 2004 From: michaelmossey at yahoo.com (Michael Mossey) Date: 8 Apr 2004 18:22:43 -0700 Subject: Intermittant slow startup References: <9badaf0.0404051033.9fec2db@posting.google.com> <4071A86D.97CA6CAE@alcyone.com> <9badaf0.0404051445.5b26b945@posting.google.com> <9badaf0.0404081413.5cc83413@posting.google.com> Message-ID: <9badaf0.0404081722.69cd11c0@posting.google.com> michaelmossey at yahoo.com (Michael Mossey) wrote in message news:<9badaf0.0404081413.5cc83413 at posting.google.com>... > Michael Hudson wrote in message news:... > > michaelmossey at yahoo.com (Michael Mossey) writes: > > > > > Erik Max Francis wrote in message news:<4071A86D.97CA6CAE at alcyone.com>... > > > > Michael Mossey wrote: > > > > > > > > > Runnng python 2.2 on HP-UX, I get intermittant slow startup. > > > > > Sometimes python starts up in a small fraction of a second, and > > > > > sometimes takes 3-5 seconds. This applies to any script I run, or > > > > > just typing 'python' at the prompt. > > > > > > > > > > I also observed something similar on Linux. > > > > > > > > > > Any ideas what would cause *intermittant* slow startup? > > > > > > > > Caching? Is it a long time between invocations that it takes a long > > > > time to start up? > > > > > > It is quite intermittant without much of a pattern I can see. One > > > thing that is definitely true is that if I start up python several > > > times in a row one right after the other, some can be slow and some > > > fast. I just observed it start fast twice, then start slow. I don't > > > remember if it ever does the other way around but I think it does. > > > > Does HP-UX have a version of strace/truss/ktrace? > > > > Cheers, > > mwh > > Yes, it has strace. What do I do with that? > > -Mike Okay, the thousands of people who have dropped everything to work on this for me, you can go back to what you were doing. ;) My shared library load path included an AFS directory that wasn't necessary. When I took that out, it worked fine. Thanks everyone, Mike From peter at engcorp.com Wed Apr 28 08:42:27 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 28 Apr 2004 08:42:27 -0400 Subject: Is Perl *that* good? In-Reply-To: References: <108q51j4dscn7dc@corp.supernews.com> <87fzaqmm8t.fsf@strauser.com> <38ec68a6.0404262308.50029919@posting.google.com> Message-ID: Roy Smith wrote: > In article , > Peter Hansen wrote: >>Wouldn't that be a fairly trivial class to write, and use >>in your own code? > > It would be. And everybody would invent their own flavor. Putting it > into the core means everybody does it the same way, so everybody's code > is easier to understand and maintain. Which is the same tired argument that people always seem to use, thinking it somehow justifies putting something into the core. The "to keep people from inventing their own flavor" argument is only useful if lots of folks are already doing this! This is actually the first time in recent years that I can recall that someone has complained about having to make up a new variable (which is as good as free) to hold the result of a match. If lots more people do it and we start getting a situation where there are a half dozen ways to spell the same thing, *then* it's time to consider a PEP or something, or standardizing one of the approaches and putting it in the core. -Peter From adalke at mindspring.com Thu Apr 8 17:58:22 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Thu, 08 Apr 2004 21:58:22 GMT Subject: ANN: Bioinformatics Open Source Conference Message-ID: <2Wjdc.2095$A_4.580@newsread1.news.pas.earthlink.net> I know there's many people here using Python for bioinformatics (including people who don't use Biopython :) If you're planning to be at ISMB this summer you might want to check out BOSC, the Bioinformatics Open Source Conference http://www.open-bio.org/bosc2004/ which takes place two days before ISMB starts. It's a great time to talk about your software project either a full talk (up to 30 minutes), a lighting talk (about 5 minutes) or during one of our demo sessions. The deadline for full-talk proposals is next week, but we will accept lighting talks and demos until we run out of space, even during the conference itself. I hope to have a good showing by Python people! Andrew dalke at dalkescientific.com From peter at luciak.org Tue Apr 20 04:04:20 2004 From: peter at luciak.org (Peter Luciak) Date: Tue, 20 Apr 2004 10:04:20 +0200 Subject: eval() and local variables Message-ID: <20040420080420.GA2178@avalon> Hi, I need to do something like this: def my(): a,b=1,2 func = "lambda x: a*x+b" map(eval(func),[1,2,3]) my() NameError: global name 'a' is not defined Why do I have to make a,b global for this to work? Thanks, P. -- Peter `cuco' Luciak jabber://cuc0 at jabber.sk peter at luciak.org http://www.luciak.org/ From kkto at csis.hku.hk Fri Apr 9 05:46:18 2004 From: kkto at csis.hku.hk (Isaac To) Date: Fri, 09 Apr 2004 17:46:18 +0800 Subject: List vs tuples References: <107bf8q8fhsmg5e@news.supernews.com> Message-ID: <7in05lfpqt.fsf@enark.csis.hku.hk> >>>>> "John" == John Roth writes: John> It's a common question. A list is a data structure that is John> intended to be used with homogenous members; that is, with members John> of the same type. I feel you argument very strange. Even that it might be the original intention, I see nothing in the language that support your argument. In particular, nothing says that tuples cannot be used (or is troublesome to use) when members are of the same type. And nothing says that lists cannot be used (or is troublesome to use) when members are of different types. John> You've probably used tuples without realizing it. For example, the John> following idiom involves a tuple: John> hours, minute, second = getTime() John> where John> def getTime(.....) #some calc return hour, minute, second John> While it looks like return is returning multiple objects, it John> actually isn't. It's returning one object: a tuple of three John> elements which is then being unpacked on the receiving end. If getTime() give you a list instead, then [hours, minute, second] = getTime() would still give you the hours, minute and second variables assigned. John> You could call the same routine this way as well: John> result = getTime() John> and result would be a tuple of three elements. And if getTime() give you a list of course result would be a list instead. Nothing magic. John> Another way of thinking about it is that you would use a tuple the John> same way you would use a struct in a language like C, if you John> didn't want to go to the trouble of creating a full-fledged object John> for it. And you can use a list here as well. Indeed, if you want to emulate C struct, you probably will use list instead of tuples, since in C, structs are mutable. Regards, Isaac. From jacek.generowicz at cern.ch Tue Apr 27 05:49:27 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 27 Apr 2004 11:49:27 +0200 Subject: Magic methods in extension types References: Message-ID: Michael Hudson writes: > Jacek Generowicz writes: > > > Michael Hudson writes: > > > > > Jacek Generowicz writes: > > > > > > > Michael Hudson writes: > > > and for new-style classes much hair in typeobject.c:type_new and > > > therein called functions. Extension types don't go through type_new > > > and are expected to go the other way round, in a sense: define > > > something in tp_as_number->nb_inplace_add and a wrapper called > > > __iadd__ will be created for you. > > > > Yuk. > > Why? Partly because I misread (thinking that *I* had to write hairy stuff for it to work), and partly because the dichotomy offends my sense of symmetry, beauty, coherence, cleanlyness etc. > > You are, in summary, saying that by _far_ the simplest way of adding > > __iadd__ to an extenion type is via tp_as_number->nb_inplace_add, > > aren't you. > > Yes. I'm surprised at your apparent surprise, but then I've had my > head in the guts of Python's implementation for quite some time > now... ... while I try to keep out of there. (I appreciate Python for its ability to hide unimportant low-level details, not for it being a C program; if I wanted to program in a low-level language, I wouldn't need Python ... unless it would be to play with implementation details of Python itself: you realize that I'm eagerly waiting for PyPy to deliver :-) > implementing types in C is really quite different from > implementing them in Python, something which has only become > surprising since 2.2... Yes, I was blindly hoping that type-class unification would have made implementing extension types look more like implementing Python types. Anyway, it's clear what I have to do. Thanks. From roy at panix.com Thu Apr 15 18:26:37 2004 From: roy at panix.com (Roy Smith) Date: Thu, 15 Apr 2004 18:26:37 -0400 Subject: Difficulty Finding Python Developers References: <65cbc3dd.0404140641.3501fde8@posting.google.com> <5d83790c.0404150701.605782a7@posting.google.com> <7xpta8hqe7.fsf@ruckus.brouhaha.com> Message-ID: In article <7xpta8hqe7.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: > Roy Smith writes: > > I would put it slightly differently. > > > > With Python, you can learn a useful subset of the language in a weekend. > > Control flow, statement syntax, and how to define and use functions. > > Assuming you're already familiar with the concepts of classes and > > exceptions (and just need to learn how python implements them), those > > are probably another weekend. > > I think anyone using Python in a serious production project has to be > ready to extend or debug the library modules and/or write new C > extensions. I guess it depends on what you mean by "serious production project". I've played with several of the extension APIs just to get a feel for what they're like, but I've never actually used any of them in anger. Of course, I've used plenty of add-on modules (DB, LDAP, SNMP, etc), but I just downloaded them and started using them. Certainly, *somebody* had to muck about in the C API (or SWIG, or Boost, or whatever) to get that done, but I've never felt the need. Of course, I learned C in the days when it was assumed that anybody doing any "serious production project" in C would have to be able to dive into assembler once in a while :-) > There are just too many surprising little gaps in the > standard library and you run into them when you least expect it. I'm sure there are, but can you give some examples of ones you've run up against? > And the C API is quite cumbersome and not something a typical > programmer can really come up to speed on in a weekend. No debate about that, but the C API is (IMHO) a very advanced topic and something that only a small fraction of Python programmers would ever need even know exists. You certainly don't need to know about it to get useful work done with a basic subset of the language. From deetsNOSPAM at web.de Tue Apr 20 08:20:38 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Tue, 20 Apr 2004 14:20:38 +0200 Subject: Problems using modulo References: Message-ID: Gonzalo Sainz-Tr?paga (GomoX) wrote: > On Mon, 19 Apr 2004 17:51:53 +0200, Diez B. Roggisch wrote: >> AFAIK modulo is mathematically only properly defined on >> integers - so you should stick to them. > > Modulo is fine for any number (even irrational ones). For example, > acos(sqrt(3)/2) is congruent to pi/6 mod 2*pi. Technically, two numbers > are congruent mod n when the rest of the division by n is the same, it > doesn't matter whether n is an integer or not. Hum - usually, division in fields like Q or R doesn't yield a rest, doesn't it? Thats what I meant. Of course if you define division as a / b := subtract b from a until a is < b and count the iterations, you can have modulo. So I stand corrected that the modulo op in python then makes sense (even if numerical problems arise, but thats a different topic). -- Regards, Diez B. Roggisch From matthew at coredumps.net Fri Apr 16 01:02:45 2004 From: matthew at coredumps.net (Matthew) Date: 15 Apr 2004 22:02:45 -0700 Subject: [Newbie Q on String & List Manipulation] References: <567a7c35.0404150247.7809bef5@posting.google.com> Message-ID: <567a7c35.0404152102.66fae5a2@posting.google.com> hello all, thanks very much for you guys' replies. :) i guess i already have properly indented the code, and i also tried the string.join() method. i changed the script a bit to test both the a+=b and the string.join(). pls kindly take a look at the output and the script below. thanks in advance. --- matthew ########## # OUTPUT # ########## === the content of the "thecookies" list === ['=zh_HK; Expires=Sat, 16-Apr-05 04:57:58 GMT; Path=/\r', 'Session=zh_HK\r', 'SID=AejhWhifAlWLXGi3lnBd3PiLeNUkoasZRP9kKXc0Es_o;Domain=.google.com;Path=/\r', 'GV=fbf1ad9eb8-4bbb676189c513f10bfa42556f57c6ac'] === the content of the string: "mycookies" === GV=fbf1ad9eb8-4bbb676189c513f10bfa42556f57c6ac_o;Domain=.google.com;Path=/ === use the string.join(): "".join(thecookies) === GV=fbf1ad9eb8-4bbb676189c513f10bfa42556f57c6ac_o;Domain=.google.com;Path=/ ############ # Gmail.py # ############ # # A Python script that would logging into the Gmail services and check # if the message is still the "Sorry, Gmail is in limited test mode..." # # Matthew Wong 2004-04-15 # import re import string import sys import urllib user = "matthew at coredumps.net" pswd = "maddog4096" schm = "https://" host = "www.google.com" path = "/accounts/ServiceLoginBoxAuth" qstr = {"service" : "mail", \ "continue" : "http://gmail.google.com/", \ "Email" : user, \ "Passwd" : pswd} qstr = urllib.urlencode(qstr) url = schm + host + path + "?" + qstr conn = urllib.urlopen(url) headers = conn.info().headers response = conn.read() thecookies = [] # # extract all the Set-Cookie from the HTTP response header and put it in thecookies # for header in headers: matches = re.compile("^Set-Cookie: (.*)$").search(header) if matches: thecookies.append(matches.group(1)) # # make sure we've grep the SID or die # foundsessionid = 0 for item in thecookies: if re.compile("^SID").search(item): foundsessionid = 1 break if not foundsessionid: print "> Failded to retrieve the \"SID\" cookie" sys.exit() # # grep the GV cookie from the HTTP response or die # matches = re.compile("^\s*var cookieVal= \"(.*)\";.*", re.M).search(response) if matches: thecookies.append("GV=" + matches.group(1)) else: print "> Failed to retrieve the \"GV\" cookie" sys.exit() # # dump the content of the list: thecookies # print "=== the content of the \"thecookies\" list ===" print thecookies print "\n" # # join the items in the "thecookies" list to # the "mycookies" string by using the a += b # mycookies = "" for item in thecookies: mycookies += item print "=== the content of the string: \"mycookies\" ===" print mycookies print "\n" # # join the items in the "thecookies" list to # the "mycookies" string by using the string.join() # print "=== use the string.join(): \"\".join(thecookies) ===" print "".join(thecookies) print "\n" # # still got many things to do right here... # sys.exit() From meyer at acm.org Wed Apr 7 10:56:39 2004 From: meyer at acm.org (Andre Meyer) Date: 7 Apr 2004 07:56:39 -0700 Subject: Dynamic creation of an object instance of a class by name Message-ID: <10f99b0f.0404070656.5960e2c8@posting.google.com> Hi all I have been searching everywhere for this, but have not found a solution, yet. What I need is to create an object that is an instance of a class (NOT a class instance!) of which I only know the name as a string. This what I tried: class A: def __init__(self, id): self.id = id def getID(self): print self.id ca = new.classobj('A', (), {}) oa1 = ca() oa2 = new.instance(ca) oa1 <__main__.A instance at 0x007E8AF8> oa1.getID() Traceback (most recent call last): File "", line 1, in ? AttributeError: A instance has no attribute 'getID' oa2 <__main__.A instance at 0x007E8AF8> oa2.getID() Traceback (most recent call last): File "", line 1, in ? AttributeError: A instance has no attribute 'getID' Thus, both ways only produce a class instance, but NOT an object of that class!!! How can I get a new object instance??? What else needs to be filled in for base_classes and __dict__ in new.classobj? Any help is appreciated, this is driving me nuts! kind regards Andre From __peter__ at web.de Wed Apr 7 11:41:48 2004 From: __peter__ at web.de (Peter Otten) Date: Wed, 07 Apr 2004 17:41:48 +0200 Subject: Dynamic creation of an object instance of a class by name References: <10f99b0f.0404070656.5960e2c8@posting.google.com> Message-ID: Andre Meyer wrote: > I have been searching everywhere for this, but have not found a > solution, yet. > > What I need is to create an object that is an instance of a class (NOT a > class instance!) of which I only know the name as a string. This what I > tried: > > class A: > def __init__(self, id): > self.id = id > def getID(self): > print self.id > > ca = new.classobj('A', (), {}) > oa1 = ca() > oa2 = new.instance(ca) > > oa1 > <__main__.A instance at 0x007E8AF8> > > oa1.getID() > Traceback (most recent call last): > File "", line 1, in ? > AttributeError: A instance has no attribute 'getID' > > oa2 > <__main__.A instance at 0x007E8AF8> > > oa2.getID() > Traceback (most recent call last): > File "", line 1, in ? > AttributeError: A instance has no attribute 'getID' > > > Thus, both ways only produce a class instance, but NOT an object of that > class!!! How can I get a new object instance??? > What else needs to be filled in for base_classes and __dict__ in > new.classobj? > > > Any help is appreciated, this is driving me nuts! > > kind regards > Andre Don't listen to the voices whispering "Use eval()" or "globals() are the way to go", make it clean and explicit with a dictionary containing all classes you want to expose: >>> class A: pass ... >>> class B: pass ... >>> class C: pass ... >>> exposed = dict(A=A, B=B, C=C) >>> exposed["A"]() :-) Peter From python at rcn.com Sun Apr 4 00:44:38 2004 From: python at rcn.com (Raymond Hettinger) Date: 3 Apr 2004 21:44:38 -0800 Subject: Python is faster than C References: <406F0907.96F37EA1@tunes.org> Message-ID: <5d83790c.0404032144.482787bd@posting.google.com> [Armin Rigo] > >>> enumerate([6,7,8,9]) # uh ? > This got me thinking about how much I would like to see the contents of an iterator at the interactive prompt. I wonder if the read-eval-print loop could be trained to make a better display: # rough pseudo-code sketch while 1: command = raw_input() result = eval(command) if result is None: continue if is_iterator(result): result, copy = itertools.tee(result) print "<%s object at 0x%8x:" % (type(result).__name__, id(result)), for elem in itertools.islice(copy, 3): print repr(elem), else: print '...', print '>' else: print repr(result) _ = result # intended result >>> enumerate('abcdefgh') >>> list(_) [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e'), (5, 'f'), (6, 'g'), (7, 'h'), (8, 'i'), (9, 'j'), (10, 'k'), (11, 'l'), (12, 'm'), (13, 'n')] Raymond Hettinger From http Fri Apr 16 01:57:48 2004 From: http (Paul Rubin) Date: 15 Apr 2004 22:57:48 -0700 Subject: Python CPU? (Re: Python OS) References: <107j4eu6ffn2c68@corp.supernews.com> Message-ID: <7xisg0a2hv.fsf@ruckus.brouhaha.com> Greg Ewing writes: > In one of my wilder daydreaming moments recently, I got to wondering > what a machine designed from the ground up to run Python code might > be like. I got a vision of a Python interpreter implemented in > microcode, with a few extra bytecodes for low-level hardware access, > with an OS written in Python running on top of it. Been done already, more or less. http://www.faqs.org/faqs/lisp-faq/part2/section-20.html http://fare.tunes.org/LispM.html From mhammond at keypoint.com.au Thu Apr 29 20:17:48 2004 From: mhammond at keypoint.com.au (Mark Hammond) Date: Fri, 30 Apr 2004 10:17:48 +1000 Subject: COM Interface Question In-Reply-To: <9e5ea2c4.0404291130.72e81c2e@posting.google.com> References: <9e5ea2c4.0404291130.72e81c2e@posting.google.com> Message-ID: Olaf Meding wrote: > I am having trouble with the 'User' property (get and put), found near > the bottom of the IDL file listed below. The user get call seems to > return None, not sure why. Possibly as the property has no value yet. After a successful set, you may find it works. > More importantly, is there another way to get the 'IUser' value > required for the user put call? (Perhaps I need to make the put call > before the get call). It depends on the application - there will generally be either a progid (so Dispatch() can create one), or some technique in the object model for creating one. The last alternative is that they expect you to implement this interface, but with the limited information available here, that sounds unlikely. Mark. From skip at pobox.com Thu Apr 15 13:09:27 2004 From: skip at pobox.com (Skip Montanaro) Date: Thu, 15 Apr 2004 12:09:27 -0500 Subject: Error with trace.py In-Reply-To: <9396ba6f.0404131907.bc6280@posting.google.com> References: <87brlvcwvv.fsf@news2.ososo.de> <9396ba6f.0404131907.bc6280@posting.google.com> Message-ID: <16510.49607.371438.753284@montanaro.dyndns.org> Stewart> I tried the example under Windows, since under Linux I only Stewart> have Python 2.2 which doesn't have trace.py. I believe it's there, just under Tools/scripts. Skip From claird at lairds.com Mon Apr 26 14:55:25 2004 From: claird at lairds.com (Cameron Laird) Date: Mon, 26 Apr 2004 18:55:25 -0000 Subject: A python telnet entry level question References: <108lr8jmr2u1202@corp.supernews.com> Message-ID: <108qmotbhcauu84@corp.supernews.com> In article , Eddie Corns wrote: . . . >And then you get unhelpful router manufacturers that put code in to check >whether passwords are typed too fast (or regularly spaced) and ignore them >because they're obviously not dealing with a human! Took me ages to figure >out why my scripts were failing (then about 10 seconds to defeat it). > >Yes, using telnet is more art than science but it's a lot better now than >before we had expect (for heavy duty jobs) and telnetlib (for simpler jobs). > >Eddie I entirely agree. Expect and telnetlib definitely *do* ease life's burdens. The examples you cite are common enough that Don Libes, creator and maintainer of the original Expect, became sufficiently expert in timing issues to make development of "drunken typist" applications simple . -- Cameron Laird Business: http://www.Phaseit.net From pepster at users.sourceforge.net Fri Apr 23 03:36:08 2004 From: pepster at users.sourceforge.net (Joseph Heled) Date: 23 Apr 2004 00:36:08 -0700 Subject: python extension, -pthreads and speed Message-ID: <4fd1aa5e.0404222336.2a1347a8@posting.google.com> Hi, My python module is built using the recommended distutils.core, which uses the -pthread flag. To my amazement this slows down the (-O3) code by a factor of two (!2) My gcc documentation says pthread is a PowerPC flag, but I guess this is wrong. Would my code fail if I drop this flag (Assuming I don't use threads at all)? Why would there be such a speed penalty? Anyone can shed some light on that? Thanks, Joseph >python -V Python 2.3 >gcc -v Reading specs from /usr/local/lib/gcc-lib/i686-pc-linux-gnu/3.3/specs Configured with: ../gcc-3.3/configure : (reconfigured) ../gcc-3.3/configure --enable-languages=c,c++ Thread model: posix gcc version 3.3 From stewart at midwinter.ca Tue Apr 13 23:15:51 2004 From: stewart at midwinter.ca (Stewart Midwinter) Date: 13 Apr 2004 20:15:51 -0700 Subject: ANN: Snakelets 1.24 (simple-to-use web app server with dynamic pages) References: <407c6d15$0$562$e4fe514c@news.xs4all.nl> Message-ID: <9396ba6f.0404131915.7cef8607@posting.google.com> Interesting! There is definitely a niche for an app server that is simpler to use than Zope. Could this be used for a simple CMS, i.e. simpler than Plone? If so, are you aware of any examples of such a use? thanks Stewart From sean_berry at cox.net Mon Apr 12 14:20:27 2004 From: sean_berry at cox.net (Sean Berry) Date: Mon, 12 Apr 2004 11:20:27 -0700 Subject: Easy question on error catching Message-ID: I am still relativly new to python. I have written a pretty extensive program that works like a charm, doing a lot of operations on all incomming email. My problem is this: I have a portion of code that does some stuff with the date of the email. However, beacause so many people forge things like dates in spam emails I am getting an error when the program gets to the following line. x = int(t) In a couple of cases, people have forged the date to include words that have nothing to do with the date. I get a: ValueError: invalid literal for int(): So, how do I catch this error so that I can do something else with it? Is it as simple as try: x = int(t) except: something else or do I need to catch a ValueError specifically? Sorry about the easy question. Thanks in advance. From flgr at ccan.de Mon Apr 26 15:58:07 2004 From: flgr at ccan.de (Florian Gross) Date: Mon, 26 Apr 2004 21:58:07 +0200 Subject: How's ruby compare to it older brother python In-Reply-To: References: Message-ID: Hunn E. Balsiche wrote: > [Ruby, Python] > I've given up on Perl for its ugly syntax and it is not the easiest language > to learn. How about PHP? All these suck. You guys should grow up and start programming in *real* programming languages like Befunge. Oh, and you forgot to cross post to all the other 54 comp.lang groups. And now: Can we please never have threads like this one ever again? We're getting them on a twice-per-month base right now which makes these topics get old and very uninteresting quickly. PS: Don't take this too personal, but all this wouldn't have happened if you had searched in other resources before posting here. Regards, Florian Gross From thorsten at thorstenkampe.de Thu Apr 29 08:38:37 2004 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Thu, 29 Apr 2004 14:38:37 +0200 Subject: How to find the length of an iterator? Message-ID: <1a6oinf1xl5ui$.dlg@thorstenkampe.de> What is the best way to find out the length of an iterator? len() doesn't work. In the above code snippet[1] I am only interested in the index (= length of the iterator), so I'm using len(list(iterator))... Anything better? Thanks, Thorsten [2] def part(seq, func): from itertools import takewhile index = len(list(takewhile(func, seq))) return [seq[:index], seq[index:]] From wweston at att.net Thu Apr 29 11:14:49 2004 From: wweston at att.net (wes weston) Date: Thu, 29 Apr 2004 15:14:49 GMT Subject: why an exception Message-ID: Group, When I run the example, do File/New, and double click a line in the list box; I get: Exception in Tkinter callback Traceback (most recent call last): File "/usr/local/Python/lib/python2.3/lib-tk/Tkinter.py", line 1345, in __call__ return self.func(*args) File "/home/wes/jbproject/python/bowling/test.py", line 60, in EditSimpleText str = tkSimpleDialog.askstring('','enter str') File "/usr/local/Python/lib/python2.3/lib-tk/tkSimpleDialog.py", line 303, in askstring d = _QueryString(title, prompt, **kw) File "/usr/local/Python/lib/python2.3/lib-tk/tkSimpleDialog.py", line 281, in __init__ _QueryDialog.__init__(self, *args, **kw) File "/usr/local/Python/lib/python2.3/lib-tk/tkSimpleDialog.py", line 179, in __init__ Dialog.__init__(self, parent, title) File "/usr/local/Python/lib/python2.3/lib-tk/tkSimpleDialog.py", line 64, in __init__ self.grab_set() File "/usr/local/Python/lib/python2.3/lib-tk/Tkinter.py", line 521, in grab_set self.tk.call('grab', 'set', self._w) TclError: grab failed: window not viewable I'm running redhat 9.0 and Python 2.3.3 Another user had a similar problem. Any ideas? #----------------------------------------------------------------------------- from Tkinter import * import time import tkSimpleDialog class MainWindowClass: def __init__(self): self.Top = Tk() self.Top.minsize( 200,200 ) mainmenu = Menu(self.Top) submenu = Menu( mainmenu, tearoff=0 ) submenu.add_command( label = "New" , command = self.NewB ) mainmenu.add_cascade( label = "File",menu = submenu ) self.Top.config( menu=mainmenu ) self.Top.mainloop() #-------------------------------------------------------------------- def NewB(self): ball = Ball(self.Top) #---------------------------------------------------------- class Ball: def __init__(self,top,ball=None): self.Top = Toplevel(top) self.Top.columnconfigure(0,weight=1) self.Top.rowconfigure(1 ,weight=1) self.vscrol = Scrollbar(self.Top,orient="vertical") self.vscrol.grid(row=1,column=1,sticky="ns") self.hscrol = Scrollbar(self.Top,orient="horizontal") self.hscrol.grid(row=2,column=0,sticky="ew") self.listbox = Listbox( self.Top, font='system.fixed 12', width=60, height=20, xscrollcommand=self.hscrol.set, yscrollcommand=self.vscrol.set, exportselection=0, selectmode=SINGLE ) self.listbox.grid(row=1,column=0,sticky="nesw") self.vscrol.config(command=self.listbox.yview) self.hscrol.config(command=self.listbox.xview ) label = Label(self.Top,anchor='w',font='system.fixed 12',text='heading') label.grid(row=0,column=0,sticky="ew") self.listbox.bind( "",self.EditSimpleText ) self.LabelList = [ ( "Last Name :","",self.EditSimpleText), ( "First Name :","",self.EditSimpleText), ] for x in self.LabelList: self.listbox.insert(END,x[0]+ " " + x[1]) #-------------------------------------------------------------------- def EditSimpleText( self, event ): str = tkSimpleDialog.askstring('','enter str') #---------------------------------------------------------- if __name__ == '__main__': w = MainWindowClass() From jepler at unpythonic.net Wed Apr 21 07:22:24 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 21 Apr 2004 06:22:24 -0500 Subject: Still trying to compile Ming (Flash) for windows :( In-Reply-To: <3d06fae9.0404201243.92f176@posting.google.com> References: <3d06fae9.0404201243.92f176@posting.google.com> Message-ID: <20040421112224.GD5589@unpythonic.net> If you type simply gcc at the command prompt, do you get an error that it's not found, or a message like gcc: no input files ? If you get a "not found" error, then you need to set your "PATH" variable to include the directory where gcc.exe and other mingw executables reside. Jeff From rnichol_rrc at yahoo.com Thu Apr 15 01:50:11 2004 From: rnichol_rrc at yahoo.com (Reid Nichol) Date: 14 Apr 2004 22:50:11 -0700 Subject: Saving a Canvas as other than PS Message-ID: Hello, I have been looking for a way to save a Canvas as a jpeg. I know that there is PIL but I need to draw polygons and the ImageDraw module doesn't have the smooth option for its draw.polygon method and I need that. I'm on OpenBSD 3.4 with Python 2.2.1. Please help! From afriere at yahoo.co.uk Tue Apr 27 03:08:19 2004 From: afriere at yahoo.co.uk (Asun Friere) Date: 27 Apr 2004 00:08:19 -0700 Subject: Is Perl *that* good? References: <108q51j4dscn7dc@corp.supernews.com> <87fzaqmm8t.fsf@strauser.com> Message-ID: <38ec68a6.0404262308.50029919@posting.google.com> Kirk Strauser wrote in message news:<87fzaqmm8t.fsf at strauser.com>... > I haven't noticed much of a different between Perl's regex and Python's > re.py module, other than I'm now typing: > > pattern.match(string) > > instead of > > string ~= pattern How does pattern (in the python example) come to have a 'match' method? Wouldn't you need to import the re module and compile the pattern first? (And wouldn't you use 'search' rather than 'match'?) And other steps, depending on what you want to do with the resulting match object. Regex is much more 'immediate' in Perl. Probably the only time I would reach for Perl rather than for python is when I knew a task involved a lot of regex (and no object orientation). From anton at vredegoor.doge.nl Thu Apr 22 22:46:05 2004 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Fri, 23 Apr 2004 04:46:05 +0200 Subject: AOP use cases References: <0pydnSB4WYuieuLdRVn-hQ@powergate.ca> Message-ID: <40888443$0$126$3a628fcd@reader3.nntp.hccnet.nl> "Terry Reedy" wrote: >Hmmm. When I started this reply, I was going to emphasize that 'separating >concerns' is much less efficient than more directly writing The problem is *which* concerns are to be separated. def fgen(): #generate fibonacci sequence a,b = 0,1 while 1: a,b = b,a+b yield a def fib(n, L = [], g = fgen()): #interface with fibonacci generator if n < 0 : return 1 while len(L) <= n: L.append(g.next()) return L[n] def test(): print fib(500) if __name__=='__main__': test() Anton From asdf at asdf.com Thu Apr 22 18:05:39 2004 From: asdf at asdf.com (asdf sdf) Date: Thu, 22 Apr 2004 22:05:39 GMT Subject: python web programming / CMS In-Reply-To: <9YWhc.82882$%l7.5377160@phobos.telenet-ops.be> References: <0kVhc.54316$eB7.29255@newssvr25.news.prodigy.com> <9YWhc.82882$%l7.5377160@phobos.telenet-ops.be> Message-ID: > Well, i'm assigned a project where i have to choose a intranet sollution > and a platform for future webbased tools development. > I'm trying to get a clear idea of what is possible. > For the moment 2 kinds of setup are considered > OpenCMS - JBoss - Apache - Tomcat > or > Plone - Zope - Apache - Spyce / modpython > with modpython/spyce you can use your own python objects. There's been a lot of discussion of Plone and Zope. Check Slashdot. Both have a lot of rapid fans, but naysayers say they are too complicated and too slow. Some say you're buy end user ease-of-use at the cost of administrative complexity. you'll have to let me know what you find out. From max at alcyone.com Sun Apr 11 23:29:23 2004 From: max at alcyone.com (Erik Max Francis) Date: Sun, 11 Apr 2004 20:29:23 -0700 Subject: Is there a boolean(somestring) equivalent of int(somestring).bool('false') -> True References: Message-ID: <407A0D13.38FF952E@alcyone.com> Vineet Jain wrote: > How can anyone argue that > > bool('false') = True > > is more natural (and what you would expect) than > > bool('false') = False Because at some point in programming you (I mean the general "you," not you specifically) actually have to hit the books and learn what functions do. A natural language that works simply and reasonably is always a good thing, but that's not a _substitute_ for learning, it's an assistant. > Booleans are associated with (True, on, 1 and yes) and bool() on any > them > should return True. No, because bool doesn't do this. bool tests whether or not the argument passed in is true according to the Python language, and returns True if so; otherwise it returns False. This is not the behavior you want; you want to test whether or not the argument is a string which looks like it might represent the concept of true. That's for a function you might call doesStringLookTrue, but not the bool function/type. After all, are you disturbed by this: if 'false': print "This should never happen since the test is false" executes the "then" statement? If you are, then you don't understand Python's concept of Booleans. If you aren't, then you're trying to _introduce_ an inconsistency, not solve one, because if x: ... should always behave the same as if bool(x): ... -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis \__/ Whoever named it necking was a poor judge of anatomy. -- Groucho Marx From jcarlson at uci.edu Wed Apr 7 00:43:10 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Tue, 06 Apr 2004 21:43:10 -0700 Subject: Capturing stdout incrementally In-Reply-To: References: Message-ID: >>>I am on Windows by the way, so the utilities are printing to the windows >>>command shell. >> >>By default, popen in Windows buffers everything coming from the called >>app. I believe you can use various Windows system calls in pywin32 in >>order to get line buffered output, but I've never done it, so have >>little additional advice other than "check out pywin32". > > > Typically this behavior on Windows (and at least in my experience on > Unix) comes not from popen buffering its input from the called > program, but the called program buffering its output when it isn't a > normal console. I'm not sure if this is default behavior from the C > library, but it's particularly true of cross-platform code that often > uses isatty() to check. Your experience in unix has colored your impression of popen on Windows. The trick with Windows is that pipes going to/from apps are not real file handles, nor do they support select calls (Windows select comes from Windows' underlying socket library). If they did, then the Python 2.4 module Popen5 would not be required. Popen5 is supposed to allow the combination of os.popen and os.system on all platforms. You get pollable pipes and the signal that the program ended with. As for how they did it on Windows, I believe they are using pywin32 or ctypes. - Josiah From peholmst at abo.fi Thu Apr 15 03:56:17 2004 From: peholmst at abo.fi (=?ISO-8859-1?Q?Petter_Holmstr=F6m?=) Date: Thu, 15 Apr 2004 10:56:17 +0300 Subject: Getters and setters in python, common practise Message-ID: <407e402c$1@newsflash.abo.fi> Hello, Having a Delphi/Object Pascal-background, I'm very used to using getters and setters when designing my classes. What is the common practise in the Python world? Should one use them or not? Thanks in advance, -Petter- From joe at notcharles.ca Wed Apr 14 20:26:42 2004 From: joe at notcharles.ca (Joe Mason) Date: Thu, 15 Apr 2004 00:26:42 GMT Subject: Aspect Programming Module References: <84fc4588.0404140106.3fa0c55@posting.google.com> Message-ID: In article , Donn Cave wrote: > Have you been through the materials referred to there? > [http://www.logilab.org/projects/aspects/] I didn't spend much time on > it, but I didn't immediately recognize anything from the last time I > heard about AOP, so I was led to wonder if it's a different notion > going by the same name. No - I don't have any particular need or interest in AOP at the moment, so I haven't really looked at it. > The one I remember allows objects to inherit from containers, > more or less. Your widget for example might inherit some > drawing parameters from the window it belongs to. I'm probably > getting it mostly wrong, but then I wasn't very excited about > the idea. OOP is scary enough without compounding it this way. The only example I've read was an intro using AspectJ (http://www-106.ibm.com/developerworks/library/j-aspectj/) which logs every function call. That doesn't seem too scary. Joe From ptmcg at austin.rr._bogus_.com Wed Apr 7 19:51:44 2004 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Wed, 07 Apr 2004 23:51:44 GMT Subject: list comprehensions References: Message-ID: "Elaine Jackson" wrote in message news:yjZcc.42823$Pk3.9547 at pd7tw1no... > > List comprehensions don't work the way you intuitively expect them to work. I > realize many people have no intuitions about how list comprehensions 'should' > work, so if you recognize yourself in this description, feel free to go back to > whatever you were doing before. If you're still here, though, I invite you to > consider the following definition: > > partitions = lambda n: [[n]]+[[k]+x for x in partitions(n-k) for k in > range(1,n)] > > As defined above, the function raises an exception when you call it ('k' > referenced before assignment). For the sake of clarity, here is workable code > expressing the same intention: > > def partitions(n): > reVal=[[n]] > for k in range(1,n): > for x in partitions(n-k): > reVal.append([k]+x) > return reVal > > So I guess what I want to ask is: Can somebody explain the semantics of list > comprehensions to me? Or even better: Can somebody tell me where to look in the > documentation to find out about list comprehensions? All donations gratefully > received. > > Peace > > Elaine - I suspect you wrote your listcomp by thinking this is an inversion of the nested for loops. That is, if you think of some arbitrary nesting of loops as: for i in firstRange: for j in secondRange: for k in thirdRange: ...... then you looked at the list comp as working its way inside out, since it starts with the part. But as the other posters have already stated, even though the listcomp starts with the most deeply nested body, the remaining 'for... for ... for... ' clauses match the nested loops, as if you had just removed the colons and copied them all onto one line. So the listcomp ends up looking like: [ for i in firstRange for j in secondRange for k in thirdRange...] If you want some kind of model for how to conceptualize this, then I'd say that a listcomp starts with its most important part being the actual list element assembly/definition, followed by the iteration specifiers in successive outer-to-inner order, that will get the loop variables to the necessary values to satisfy the list assembly code. You also asked for doc references. The Python Tutorial includes an obscure example (you have do a bit of in-your-head multiplication to get it), but try these other articles describing listcomps when they were a new feature: http://www-106.ibm.com/developerworks/linux/library/l-py20.html http://python.org/2.0/new-python.html#SECTION000600000000000000000 Perhaps the tutorial could lift some of the examples from these other pages, as I'm sure people don't necessarily go back to the "What's New" pages for version x-2, x-3, etc. HTH, -- Paul From kraus at hagen-partner.de Thu Apr 1 03:44:48 2004 From: kraus at hagen-partner.de (Wolfram Kraus) Date: Thu, 01 Apr 2004 10:44:48 +0200 Subject: From python-dev, space vs. tab controversy finally settled In-Reply-To: References: Message-ID: Heyho! Carl Banks wrote: > Here's a summary of the final decision Guido made concerning how > Python will indent code in the future, from python-dev: > > Guido had been planning to deprecate tabs in favor of spaces for > awhile, although there have been good arguments for both tabs and > spaces. But he was never really comfortable pulling the rug out from > half the user base. However, today he finally decided on a compromise > that has all the benefits of both spaces and tabs. > [...] > So, you should start using Unicode character 0009 to indent right > away. Python 2.4 will deprecate all indentation not using the new > indent character, and Python 3.0 will not support any other > indentation. > Nah, this sucks! This will be the death of Python! I'm switching to Whitespace: http://compsoc.dur.ac.uk/whitespace/ Stay Rude! Wolfram From jepler at unpythonic.net Sat Apr 10 11:10:37 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Sat, 10 Apr 2004 10:10:37 -0500 Subject: Static Data? In-Reply-To: <2FTdc.56817$Id.5813@news-binary.blueyonder.co.uk> References: <2FTdc.56817$Id.5813@news-binary.blueyonder.co.uk> Message-ID: <20040410151036.GA22719@unpythonic.net> class Counted: _ID = 0 def __init__(self): Counted._ID += 1 self._ID = Counted._ID >>> o1, o2, o3 = [Counted() for i in range(3)] >>> [o._ID for o in (o1, o2, o3)] [1, 2, 3] Jeff From opengeometry at yahoo.ca Mon Apr 26 14:11:10 2004 From: opengeometry at yahoo.ca (William Park) Date: 26 Apr 2004 18:11:10 GMT Subject: How to debug CGI scripts with simulated variables from server? References: <670jc.100949$U83.74356@fed1read03> Message-ID: Sean Berry wrote: > I want to debug a script that has a line like the following: > if len(os.environ["QUERY_STRING"]) > 0: > > How do I debug this from the command line. I tried > QUERY_STRING='sized=72&shaped=3' ./aqua_getShapes > > But that returns: > QUERY_STRING=sized=72&shaped=3: Command not found. Works fine here (Slackware-9.1 Linux, bash-2.05b). Try export QUERY_STRING=... ./aqua_getShapes -- William Park, Open Geometry Consulting, Linux solution/training/migration, Thin-client From db3l at fitlinxx.com Fri Apr 23 15:16:50 2004 From: db3l at fitlinxx.com (David Bolen) Date: 23 Apr 2004 15:16:50 -0400 Subject: Multi-threaded printing and IOErrors in Windows References: <10nll1-rt5.ln1@home.rogerbinns.com> Message-ID: "Roger Binns" writes: > David Fraser wrote: > > sys.stdout is not threadsafe - try wrapping each call with a mutext and > > see if that fixes it... > > Having to wrap hundreds of random print statements just using for > debugging seems really silly. Note that I don't care if the > output gets garbled. (It doesn't on Mac or Linux ever). To follow up on this point to my previous reply - I've never found sys.stdout not to be threadsafe, at least in terms of how I mean "threadsafe" - that is generating exceptions or crashes. If instead, threadsafe is meant to imply atomic I/O (guaranteed output of entire I/O as a unit) which is a broader definition, then yes, it is definitely true that multiple threads all using sys.stdout may have their output interleaved, particularly when you are using the 'print' statement, since a single print statement generates multiple individual writes to sys.stdout, generally for each argument, as well as the trailing newline. -- David From Kuser-admin at kde.gr.jp Wed Apr 7 01:32:43 2004 From: Kuser-admin at kde.gr.jp (Kuser-admin at kde.gr.jp) Date: Wed, 7 Apr 2004 14:32:43 +0900 Subject: Fml status report (Kuser ML) References: <20040407053233.4E9611F8035@mail.kde.gr.jp> Message-ID: <200404071432.FMLAAB30905.Kuser@kde.gr.jp> ATTENTION! Your mail is too big, so not processed!!! This ML restricts the maximum mail size, so pay attention to the mail with e.g. attachments. --Kuser at kde.gr.jp, Be Seeing You! ************************************************************ Help: Unsubscribe: If you have any questions or problems, please contact Kuser-admin at kde.gr.jp or send e-mail with the body "help"(without quotes) to Kuser-ctl at kde.gr.jp (here is the automatic reply, so more preferable) e.g. on a Unix Machine (shell prompt)% echo "help" |Mail Kuser-ctl at kde.gr.jp ************************************************************ From peter at engcorp.com Thu Apr 15 05:52:18 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 15 Apr 2004 05:52:18 -0400 Subject: Difficulty Finding Python Developers In-Reply-To: <1081975009.10988.2@ersa.uk.clara.net> References: <65cbc3dd.0404140641.3501fde8@posting.google.com> <1081975009.10988.2@ersa.uk.clara.net> Message-ID: Garry Knight wrote: > In message , Mike C. > Fletcher wrote: > >> I'm an alumni, so UofW is obviously not all it's cracked up to be ;) > > Apparently not. 'Alumni' is the plural form. You're an alumnus. :o) (He was using the _royal_ "alumnus", as they say... ;-) Actually the Fletcher-bot combines experimental technologies (note the plural ;-) of the PSU which simulate combining the programming patterns of the other extent bots. The Fletch-bot is still in beta form since it has not managed to produce the sheer verbosity required from a bot, though it does successfully emulate managing a large number of open source projects simultaneously. The PSU has plans to use the time machine to incorporate the Fletch-bot into From mwh at python.net Wed Apr 28 07:50:45 2004 From: mwh at python.net (Michael Hudson) Date: Wed, 28 Apr 2004 11:50:45 GMT Subject: Embedding OCaml within Python References: <37aad18.0404280019.500e2841@posting.google.com> Message-ID: max_powers280 at hotmail.com (Max Powers) writes: > Alternatively I think I can wrap the ocaml library in a C wrapper > and then call that from python. Not knowing much about the situation, this is probably the simplest thing to do... depends on how complicated the data you want to pass between the two parts of the program is. Cheers, mwh -- ... Windows proponents tell you that it will solve things that your Unix system people keep telling you are hard. The Unix people are right: they are hard, and Windows does not solve them, ... -- Tim Bradshaw, comp.lang.lisp From peter at engcorp.com Mon Apr 26 11:56:28 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 26 Apr 2004 11:56:28 -0400 Subject: AOP use cases In-Reply-To: References: <84fc4588.0404140106.3fa0c55@posting.google.com> <0pydnSB4WYuieuLdRVn-hQ@powergate.ca> Message-ID: Eric Eide wrote: > Should we > consider Python's support for OOP evidence that Python is defective in some way > with respect to Scheme, and that Scheme is therefore "a better designed > programming language" because it "needs" neither AOP nor OOP? But isn't that exactly true? <0.1 wink only> -Peter From rnikaREMOVEnder at adelphia.net Tue Apr 20 23:54:12 2004 From: rnikaREMOVEnder at adelphia.net (Rob Nikander) Date: Tue, 20 Apr 2004 20:54:12 -0700 Subject: Dealing with multiple versions of packages... In-Reply-To: <62c819a5.0404201235.c1649c5@posting.google.com> References: <62c819a5.0404201235.c1649c5@posting.google.com> Message-ID: I haven't heard of a standard way to do it. I downloaded PyGTK 2.0.x a while back and I remember looking at a package structure that looked like it was designed to do this. You might want to check that for ideas. (I don't have it on my machine now.) Also I was using a python module today that behaved differently upon import, depending on a property of "sys". Like: import sys sys.coinit_flags = 0 import pythoncom # initializes COM with sys.coinit_flags In your case wx could be a package with an __init__.py that imported subpackages depending on what version was set (with a default of course). To import packages based on a string variable you have to use __import__. You could also set PYTHONPATH to the version you want. ? Rob From maxm at mxm.dk Tue Apr 20 03:44:56 2004 From: maxm at mxm.dk (Max M) Date: Tue, 20 Apr 2004 09:44:56 +0200 Subject: CamelCase versus wide_names (Prothon) In-Reply-To: <6ee58e07.0404192141.2229efd6@posting.google.com> References: <6ee58e07.0404192141.2229efd6@posting.google.com> Message-ID: <4084d50a$0$209$edfadb0f@dread12.news.tele.dk> Lothar Scholz wrote: > "Mark Hahn" wrote in message news:... > After writing a few hundert thousands lines of code in Eiffel and a > few ten thousands lines in Java i must say that lowercase wide_names > are much much better to read. Someone else already mentioned this > problem: > > smtp_message <-> SMTPMessage <-> SmtpMessage I would like to add that while I started out being enthisiastic about camelcase I have switched to using wide names for variable and attributes. So my code mostly looks like class ThisIsAClass thisIsAMethod() this_is_a_variable self.and_a_paramater But lately I have noticed that i am switching to wide names for methods too. This has not been a concious choice, just the way I have come to like it. So I guess that my favourite is wide names. regards Max M From piet at cs.uu.nl Sat Apr 3 12:53:09 2004 From: piet at cs.uu.nl (Piet van Oostrum) Date: 03 Apr 2004 19:53:09 +0200 Subject: Working with bytes. References: Message-ID: >>>>> "Adam T. Gautier" (ATG) wrote: ATG> I have been unable to solve a problem. I am working with MD5 signatures ATG> trying to put these in a database. The MD5 signatures are not generated ATG> using the python md5 module but an external application that is producing ATG> the valid 16 byte signature formats. Anyway, these 16 byte signatures are ATG> not nescarrally valid strings. How do I manipulate the bytes? I need to ATG> concatenate the bytes with a SQL statement which is a string. This works ATG> fine for most of the md5 signatures but some blow up with a TypeError. ATG> Because there is a NULL byte or something else. So I guess my ultimate ATG> question is how do I get a prepared SQL statement to accept a series of ATG> bytes? How do I convert the bytes to a valid string like: ATG> 'x%L9d\340\316\262\363\037\311\345<\262\357\215' ATG> that can be concatenated? Depends what the database accepts. If it supports BLOBs you could use that. Otherwise convert them to hex, or base64. See for example the the codecs module or the binascii module. -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP] Private email: P.van.Oostrum at hccnet.nl From ivoras at __geri.cc.fer.hr Mon Apr 26 20:28:32 2004 From: ivoras at __geri.cc.fer.hr (Ivan Voras) Date: Tue, 27 Apr 2004 02:28:32 +0200 Subject: How to read a file from another server? Newbie In-Reply-To: <9ugjc.3709$g31.1370@newsread2.news.atl.earthlink.net> References: <%Oejc.16$ph.9@fed1read07> <9ugjc.3709$g31.1370@newsread2.news.atl.earthlink.net> Message-ID: Edward Diener wrote: > Sean Berry wrote: > >>I am trying to read in a file from another server. >> >>If I try >>x = open("servername:/path/to/file", "r") > > > x = open("servername://path/to/file", "r") Um, what does this to? What protocol does it use? From jdhunter at ace.bsd.uchicago.edu Mon Apr 12 22:32:02 2004 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Mon, 12 Apr 2004 21:32:02 -0500 Subject: plot+interaction In-Reply-To: (Mark Alford's message of "Mon, 12 Apr 2004 17:17:27 -0500 (CDT)") References: Message-ID: >>>>> "Mark" == Mark Alford writes: Mark> I have been using the gnuplot.py package for simple 2D Mark> plots. Works great. But I would like to have a tiny bit of Mark> interactivity: Mark> I would like the program to know where (in terms of the plot Mark> variables x and y) the user has mouse-clicked on the plot Mark> window. Mark> Is there any other plotting package that offers this Mark> functionality? You can do this in matplotlib, albeit with a little extra work. matplotlib has different backends, and the way you do this is dependent on the backend. Ie, if you are using Tk versus GTK versus WX the approach is somewhat different, but this will probably be unified in the near future. Here is an example showing how to connect mouse move or mouse click to return the data coordinates of the mouse location using the GTK backend. """ An example of how to interact with the plotting canvas by connecting to move and click events """ import matplotlib matplotlib.use('GTK') from matplotlib.matlab import * t = arange(0.0, 1.0, 0.01) s = sin(2*pi*t) ax = subplot(111) ax.plot(t,s) canvas = get_current_fig_manager().canvas def on_move(widget, event): # get the x and y coords, flip y from top to bottom height = canvas.figure.bbox.y.interval() x, y = event.x, height-event.y if ax.in_axes(x, y): # transData transforms data coords to display coords. Use the # inverse method to transform back t = ax.xaxis.transData.inverse_positions(x) val = ax.yaxis.transData.inverse_positions(y) print t, val def on_click(widget, event): # get the x and y coords, flip y from top to bottom height = canvas.figure.bbox.y.interval() x, y = event.x, height-event.y if event.button==1: if ax.in_axes(x, y): # transData transforms data coords to display coords. Use the # inverse method to transform back t = ax.xaxis.transData.inverse_positions(x) val = ax.yaxis.transData.inverse_positions(y) print t, val canvas.connect('motion_notify_event', on_move) canvas.connect('button_press_event', on_click) show() From news at woody.datatailors.com Thu Apr 22 09:35:24 2004 From: news at woody.datatailors.com (Peter van Kampen) Date: Thu, 22 Apr 2004 15:35:24 +0200 Subject: python web programming / CMS References: Message-ID: In article , news.telenet.be wrote: > Hi, > > i'm looking at python to do programming for the new intranet > here at the company. I'm looking at plone/zope also. > Before, I've used jsp for webprogramming but i'm considering > python for this. > One thing that isn't clear to me is if it's possible to include python > code in a html page like you would do with jsp and then have zope > "translate" that to html. With jsp, one could use an apache/tomcat > combo to accomplish this. Look at PSP. See www.modpython.org for mor information. > If one can't include python in html, is Zope the only alternative and > how does code look like then? By no means. For more info start here: http://www.python.org/sigs/web-sig/ Hth, PterK -- Peter van Kampen pterk -- at -- datatailors.com From jcarlson at uci.edu Wed Apr 21 02:59:59 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Tue, 20 Apr 2004 23:59:59 -0700 Subject: No built-in swap function? In-Reply-To: References: Message-ID: > The xorswap function is not much use for anything other than numbers, > however, I would have expected a psyco'ed xorSwap to much faster than > the alternatives! You are testing function calling overhead. Try the below... import time def tupleswap(a,b): t = time.time() for i in xrange(100000): a,b=b,a;a,b=b,a;a,b=b,a;a,b=b,a;a,b=b,a; a,b=b,a;a,b=b,a;a,b=b,a;a,b=b,a;a,b=b,a; print "1 million tuple swaps in", time.time()-t, "seconds." def tempswap(a,b): s = time.time() for i in xrange(100000): t=a;a=b;b=a;t=a;a=b;b=a;t=a;a=b;b=a;t=a;a=b;b=a;t=a;a=b;b=a; t=a;a=b;b=a;t=a;a=b;b=a;t=a;a=b;b=a;t=a;a=b;b=a;t=a;a=b;b=a; print "1 million temp swaps in", time.time()-s, "seconds." def xorswap(a,b): t = time.time() for i in xrange(100000): a^=b;b^=a;a^=b;a^=b;b^=a;a^=b;a^=b;b^=a;a^=b;a^=b;b^=a;a^=b; a^=b;b^=a;a^=b;a^=b;b^=a;a^=b;a^=b;b^=a;a^=b;a^=b;b^=a;a^=b; a^=b;b^=a;a^=b;a^=b;b^=a;a^=b; print "1 million xor swaps in", time.time()-t, "seconds." a = 2**30-1 b = 2**16-1 tupleswap(a,b) tempswap(a,b) xorswap(a,b) Without Psyco (on a celeron 400): 1 million tuple swaps in 1.10899996758 seconds. 1 million temp swaps in 0.703000068665 seconds. 1 million xor swaps in 2.14099979401 seconds. With Psyco (on a celeron 400): 1 million tuple swaps in 0.0 seconds. 1 million temp swaps in 0.0 seconds. 1 million xor swaps in 0.0 seconds. Having 100 times as many loops for the Psyco run (xrange(10000000))... 1 million tuple swaps in 0.125 seconds. 1 million temp swaps in 0.125 seconds. 1 million xor swaps in 1.04699993134 seconds. Looks like a big win for Psyco to me. - Josiah From kfast at poczta.onet.pl Wed Apr 14 17:11:41 2004 From: kfast at poczta.onet.pl (Jakub Fast) Date: Wed, 14 Apr 2004 23:11:41 +0200 Subject: Does Python compete with Java? In-Reply-To: References: <8b336527.0404051337.51bb4a1b@posting.google.com> Message-ID: <407DA90D.3000307@poczta.onet.pl> > Certainly. Write a PEP, and an implementation. I cosider myself silenced :). [but then, i'd have trouble filling the "Disadvantages" section in the PEP...] > Alternatively, write a different parser front end that converts your > enriched language into standard Python. i did think of that :). kuba From loic at fejoz.net Fri Apr 9 05:10:57 2004 From: loic at fejoz.net (Yermat) Date: Fri, 09 Apr 2004 11:10:57 +0200 Subject: Function args In-Reply-To: References: Message-ID: Michel Claveau/Hamster wrote: > Bonjour ! > > >>>>En gros, tous les types primitifs de python sont "expans?s", autrement > > dit quand on les affecte ? une autre variable, c'est une copie. Tous les > types complexes sont des r?f?rences. > > Je comprend, mais, dans mon esprit, je pr?f?re me dire qu'il y a copie de ce > qui est point?. Pour une variable simple (e.g. a=2) c'est l'objet '2' qui > est point?, et donc, copi?. Dans le cas d'une liste, la liste pointe sur un > ensemble de pointeurs vers diff?rents objets, et donc, on copie ces > pointeurs (qui sont point?s). > > Malheureusement, mon point de vue accroche sur les tuples (non modifiables). > Je me dis alors que les tuples sont non modifiables par exception... > > > Cela revient un peu au m?me que ce que tu as exprim?, avec une image mentale > un peu diff?rente. > > > @-salutations > -- > Michel Claveau > > Oui je comprends bien mais si j'ai bien compris votre repr?sentation que devrait faire ceci : >>> l = ['a','b','c'] >>> >>> d = l >>> d.append('d') >>> d ['a', 'b', 'c', 'd'] Que devrait valoir l maintenant ? Python fait : >>> l ['a', 'b', 'c', 'd'] votre repr?sentation ferait : ['a','b','c'] Mais bon. L'important est d'avoir compris ;-) Yermat From limorh at Spediant.com Thu Apr 22 03:27:02 2004 From: limorh at Spediant.com (limor) Date: 22 Apr 2004 00:27:02 -0700 Subject: Python use large scale projects Message-ID: <47fc6058.0404212327.24163290@posting.google.com> Hi, I am considering using Python in a new testing tool application we intend to build for out product. I must get references before starting develope in this language , since although lots of good things are said about this language , I still have my doubts how can it compete with languages like C++ and Java. I have found te sytax and some features if the language not as problematic in maintenance prospective (although I keep reading the contrary everywhere I read somthing about python) . For people who are used to write in C and C++ I think the python being typless makes the code hard to maintain. But still, In many prespective the language seems to really suit my needs and I would really like to talk with people who are using Python in their company to medium-large scale project. I'd really like to talk with someone who is using this language in his work for large scale projects. 10x allot for whoe ever reply me on that. With Regards, limor. Spediant Systems Ltd. Igal Alon 126 TA, Israel. From max at alcyone.com Fri Apr 16 07:02:53 2004 From: max at alcyone.com (Erik Max Francis) Date: Fri, 16 Apr 2004 04:02:53 -0700 Subject: (For gurus) Embed functions in webpages like in PHP? References: <5eq4l1-9vm.ln1@pilz.hasos.com> Message-ID: <407FBD5D.7BC197F@alcyone.com> Robert Ferber wrote: > As far as I've seen, there is no way to embed Python-code in a webpage > with > "" or anything equivalent and I don't see any other way to solve > this > problem. There are a number of templating systems available in Python. EmPy is one of them: http://www.alcyone.com/software/empy/ -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis \__/ A wise man never loses anything if he have himself. -- Montaigne From maredudd at tiscali.co.uk Wed Apr 14 12:25:53 2004 From: maredudd at tiscali.co.uk (John) Date: Wed, 14 Apr 2004 17:25:53 +0100 Subject: Unable to find libraries after installing with RPM and then with source code Message-ID: <407d6b22_2@mk-nntp-2.news.uk.tiscali.com> I'm using RedHat Fedora and installed Python 2.2 using an RPM. I then built and installed Python 2.3 using "./configure", "make" and "make install". A lot of programs won't run now and give me the following error message: Could not find platform independent libraries Could not find platform dependent libraries Consider settint $PYTHONHOME to ] ..... ImportError: No module named getopt (or some other module name) The reason for this is that it is trying to import from /usr/lib/python2.2 but these modules are now in /usr/local/lib/python2.3. Is there any way of getting these programs to look in the right place for these modules? Did I install the latest version incorrectly? Do I perhaps need to uninstall all the packages that use python2.2 and reinstall them? Thanks for any help From asldfkjasldfj at asldfkjasldkfjasdf.com Sat Apr 17 12:53:03 2004 From: asldfkjasldfj at asldfkjasldkfjasdf.com (Jason) Date: Sat, 17 Apr 2004 16:53:03 GMT Subject: os.path.dirname adds unremoveable spaces? Message-ID: Here's the code I'm using: #################################### import os, string for root, dirs, files in os.walk('/home/_Comedy'): for file in files: str = os.path.dirname(file) print root, str.strip(), "/", file.strip() #################################### The problem is that even after using strip(), it still prints a list like this: /home/_Comedy/ISIRTA / ISIRTA - 1966.03.28 - s02e03 - Ali Baba.mp3 /home/_Comedy/ISIRTA / ISIRTA - 1966.04.04 - s02e04 - Nelson.mp3 /home/_Comedy/ISIRTA / ISIRTA - 1966.04.18 - s02e06 - Angus Prune.mp3 ^^^^^ ^^^^^ I can't remove these mystery spaces that I'm pointing to no matter what I try. Neither the directories or filenames have spaces before or after them. Even if they did, they should've been removed when I used the strip command. Any ideas? From sean_berry at cox.net Wed Apr 28 20:50:27 2004 From: sean_berry at cox.net (Sean Berry) Date: Wed, 28 Apr 2004 17:50:27 -0700 Subject: sorting a list References: <17i4tmtsfvae9$.dlg@thorstenkampe.de> Message-ID: >>> a = ['A', 'D', 'F', 'a', 'f'] >>> a.sort(lambda x, y: cmp(string.lower(x), string.lower(y))) >>> a ['a', 'A', 'D', 'f', 'F'] this will work too, if lower can come before upper. But Thor "Thorsten Kampe" wrote in message news:17i4tmtsfvae9$.dlg at thorstenkampe.de... > * ketulp_baroda at yahoo.com (2004-03-10 01:13 +0100) > > I want to sort a list. > > My problem is: > > > >>>> a=['a','f','F','A','D'] > >>>> a.sort() > >>>> a > > ['A','D', 'F', 'a', 'f'] > > > > But I am actually looking for an output: > > ['A','a','D','F','f'] > > > > Is there any module to sort a list this way? > > You need a general approach: > > def funcsort(seq, func): > """ sort seq by func(item) """ > seq = seq[:] > seq.sort(lambda x, y: cmp(func(x), func(y))) > return seq > > funcsort(a, lambda x: ord(x.upper()) + x.islower()/2.0) > > > Thorsten From donn at drizzle.com Fri Apr 2 23:12:22 2004 From: donn at drizzle.com (Donn Cave) Date: Sat, 03 Apr 2004 04:12:22 -0000 Subject: simple popen question References: None Message-ID: <1080965541.46978@yasure> Quoth Jim Benson : | On Fri, 2 Apr 2004, Cameron Laird wrote: ... |> In general, no; the reader doesn't control the buffering, the writer does. | | The reason i suspect popen is that when i run | the executable from the unix shell...i see every | output line ~ when expected. Well, the writer knows. When you run it "from the shell", that really means its output device is /dev/tty. When you run it from popen(), its output device is a pipe. C library I/O, and hence most application I/O, automatically treats these two devices differently. Or rather, it treats the tty specially, and treats a pipe like any other file. For the tty it uses line buffering, for everything else block buffering. There's a function that changes the policy - setbuffer I think may be the contemporary standard, I think setbuf and setvbuf are historical but don't count on me to get that straight. Donn Cave, donn at drizzle.com From jacek.generowicz at cern.ch Fri Apr 2 10:15:24 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 02 Apr 2004 17:15:24 +0200 Subject: [OT] Top posting is a PITA [was : Prothon Prototypes vs Python Classes] References: <569c605ld1cj8fc1emolk08ete0s1prls1@4ax.com> <106di86neu1qh4d@news.supernews.com> <4069a001$0$4237$afc38c87@news.easynet.co.uk> <4069e9d9$0$8915$636a15ce@news.free.fr> <406a98ee$0$290$edfadb0f@dread12.news.tele.dk> <_QUac.63300$1A6.1594640@news20.bellglobal.com> <1Vdbc.20271$j57.1135407@news20.bellglobal.com> Message-ID: Markus Wankus writes: > Let's all sit in our sensory deprivation tanks! That sounds like fun! > Who here can construct metaclasses in the dark, in their head? No problem. That's easy. It's typing them into an editor after I get out where it always goes wrong :-) From vineet at eswap.com Mon Apr 5 20:44:52 2004 From: vineet at eswap.com (Vineet Jain) Date: Mon, 5 Apr 2004 20:44:52 -0400 Subject: How to assign a default constant value in a function declaration In-Reply-To: Message-ID: Thanks for all the repsonses. It turns out that the following actually works: def someFunction(option=Constants.DEFAULT_VALUE): I did want the evaluate "Constants.DEFAULT_VALUE" function definition time. If that changes at function call time then it should not be in Constants. So all in all it works as expected and I have changed all hard coded default arguments in my functions to Constant.* values. Thanks for all your help. VJ -----Original Message----- From: python-list-bounces+vineet=eswap.com at python.org [mailto:python-list-bounces+vineet=eswap.com at python.org]On Behalf Of rzed Sent: Monday, April 05, 2004 3:52 PM To: python-list at python.org Subject: Re: How to assign a default constant value in a function declaration Scott David Daniels wrote in news:4071a362 at nntp0.pdx.net: > Marco Bartel wrote: > >> rzed wrote: >> [...] >>> Do you mean in a context like this? >>> class Const: >>> someVal=255 >>> otherVal=0 >>> >>> def blip(Const.someVal): > Should be: > def blip(test=Const.someVal): >> >> i checked this out, and i think its the name you were using: >> Const > Nope, it is the missing arg name. > Well, not so much that as an incorrectly formed parameter name. I can legally do this: def blip( someVal ): ... but not this: def blip( x.someVal ): => SyntaxError aimed at the dot. Since there is no argname to assign a value to, "Const.someVal" is taken as an identifier for a passed-in parameter. But it seems (sensibly enough) that an identifier can't contain a '.' character, which evidently is reserved for a qualifier separator (or some such term) in that context. -- rzed -- http://mail.python.org/mailman/listinfo/python-list From michaelmossey at yahoo.com Mon Apr 5 14:33:19 2004 From: michaelmossey at yahoo.com (Michael Mossey) Date: 5 Apr 2004 11:33:19 -0700 Subject: Intermittant slow startup Message-ID: <9badaf0.0404051033.9fec2db@posting.google.com> Runnng python 2.2 on HP-UX, I get intermittant slow startup. Sometimes python starts up in a small fraction of a second, and sometimes takes 3-5 seconds. This applies to any script I run, or just typing 'python' at the prompt. I also observed something similar on Linux. Any ideas what would cause *intermittant* slow startup? -Mike From garry at sage.att.com Thu Apr 8 10:26:34 2004 From: garry at sage.att.com (Garry Hodgson) Date: Thu, 8 Apr 2004 14:26:34 GMT Subject: does commands.getoutput() use nice()? Message-ID: <2004040810261081434393@k2.sage.att.com> a friend is trying to track down the source of a mysterious slowdown that's happening in a webware app he's doing. he's got an external precompiled application that he invokes from python using commands.getoutput(). usually it runs quickly (1-2 secs), but sometimes it take much longer (80-90 secs). he's instrumented the program to verify that it's the query invocation that's spending all the time. he's run the query in a test rig outside of python, and it seems to run normally all the time. but when run from python, via webware, he gets this wide performance variations. his current hypothesis is that when python runs his command, it "nices" it down in priority, so it's more susceptible to other load on the machine. i searched the python source, and don't see anyplace that appears to do this. but i thought i'd check here anyway. can anyone support or reject his theory? thanks ---- Garry Hodgson, Technology Consultant, AT&T Labs Be happy for this moment. This moment is your life. From eric at zomething.com Sun Apr 4 14:55:05 2004 From: eric at zomething.com (Eric @ Zomething) Date: Sun, 4 Apr 2004 10:55:05 -0800 Subject: OT: e-mail filter failed on "python" Message-ID: <20040404105505.1845488747.eric@zomething.com> Bloomba misfiled a DICE Job Alert into my Python e-mail folder... why, why, why? Could it be? Someone mentioning "Python" in a job listing? ''' Senior SW Engineer-Front End COMPANY: Tablus SKILLS REQUIRED: Linux, apache, python, C, C++, Web Interface LOCATION: San Mateo, CA RATE: Market AREA: 650 LENGTH: Regular Full Time TERM: FULLTIME SUMMARY: Tablus, Inc. is an exciting, stable, 2-year old company that is quickly becoming a force to be reckoned with in the area of content security products. Our flagship product, Content Alarm 1.0, is a security appliance designed to protect intellectual propert ''' And ahead of C & C++. :-) Eric Pederson http://www.songzilla.blogspot.com From vineet at eswap.com Mon Apr 12 00:47:14 2004 From: vineet at eswap.com (Vineet Jain) Date: Mon, 12 Apr 2004 00:47:14 -0400 Subject: Is there a boolean(somestring) equivalent of int(somestring). bool('false') -> True In-Reply-To: <407A14B7.2030603@prescod.net> Message-ID: > For most (all?) built-in types there is one and only one false value. > If you start to accept multiple false values then you run into the > types of problems Perl programmers run into. You write code like this: That makes sense (even though bool('false') == True is counter-intuitive). I'll stick with my checkStringForBoolean function. VJ From __peter__ at web.de Wed Apr 21 05:36:56 2004 From: __peter__ at web.de (Peter Otten) Date: Wed, 21 Apr 2004 11:36:56 +0200 Subject: Python 2.3.3 super() behaviour References: <40863bd7$0$25528$afc38c87@news.easynet.fr> Message-ID: Nicolas Lehuen wrote: > Hi, > > I hope this is not a FAQ, but I have trouble understanding the behaviour > of the super() built-in function. I've read the excellent book 'Python in > a Nutshell' which explains this built-in function on pages 89-90. Based on > the example on page 90, I wrote this test code : > > class A(object): > def test(self): > print 'A' > > class B(object): > def test(self): > print 'B' > > class C(A,B): > def test(self): > super(C,self).test() > print 'C' > > print C.__mro__ > c=C() > c.test() > > The output is : > (, , , 'object'>) > A > C > > Whereas I was expecting : > (, , , 'object'>) > A > B > C > > Was I wrong to expect this (based on what I've read ?) As soon as a test() method without the super(...).test() is reached, no further test methods will be invoked. Only the first in the list of base classes will be invoked. If I'm getting it right you have to do something like: class Base(object): def test(self): print "base" class D1(Base): def test(self): super(D1, self).test() print "derived 1" class D2(Base): def test(self): super(D2, self).test() print "derived 2" class All(D1, D2): pass All().test() Here all cooperating methods have a super() call, and the base class acts as a showstopper to prevent that Python tries to invoke the non-existent object.test(). Peter From newsgroups at jhrothjr.com Thu Apr 8 16:57:25 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Thu, 8 Apr 2004 16:57:25 -0400 Subject: List vs tuples References: Message-ID: <107bf8q8fhsmg5e@news.supernews.com> "Mitja" wrote in message news:c54cjb$5fs$1 at planja.arnes.si... > A neewbie's question here, probably discussed before: > what's the purpose of having both lists AND tuples? > At the first (and second and third, to be honest) glance lists are just > tuples with extended functionality, so why have tuples around? > I've been working with Python for a few months now but haven't yet come > across a problem that would really require tuples. It's a common question. A list is a data structure that is intended to be used with homogenous members; that is, with members of the same type. You've probably used tuples without realizing it. For example, the following idiom involves a tuple: hours, minute, second = getTime() where def getTime(.....) #some calc return hour, minute, second While it looks like return is returning multiple objects, it actually isn't. It's returning one object: a tuple of three elements which is then being unpacked on the receiving end. You could call the same routine this way as well: result = getTime() and result would be a tuple of three elements. Another way of thinking about it is that you would use a tuple the same way you would use a struct in a language like C, if you didn't want to go to the trouble of creating a full-fledged object for it. John Roth > > Thanks in advance, > Mitja > > From crap1234 at hotmail.com Sat Apr 17 07:27:57 2004 From: crap1234 at hotmail.com (Stefan Axelsson) Date: Sat, 17 Apr 2004 13:27:57 +0200 Subject: Kuhlman's tutorials pretty good In-Reply-To: References: <407E1E20.D0216E92@doe.carleton.ca> <200404150710.i3F7A0Hw010978@locutus.doe.carleton.ca> <407E40CC.C06FA9E3@doe.carleton.ca> Message-ID: Dave Kuhlman wrote: > The fonts in the ps files are not so good, and the fonts in the pdf > files are terrible. Maybe they will appear better on your system. > If you look at them, please let me know. Well, that's a known problem with LaTeX/dvips (they'll print out nicely though). Try pdflatex instead, and you'll get beautiful pdf files with nice embedded fonts. There's some incompatibility (but I've honestly never run into it) and everybody I know have made the switch. Stefan, -- Stefan Axelsson (email at http://www.cs.chalmers.se/~sax) From mlh at furu.idi.ntnu.no Fri Apr 9 15:04:55 2004 From: mlh at furu.idi.ntnu.no (Magnus Lie Hetland) Date: Fri, 9 Apr 2004 19:04:55 +0000 (UTC) Subject: ANN: Atox 0.3 released Message-ID: What is it? =========== Atox is a framework for automated markup. With it one can quite easily write custom scripts for converting plain text into XML in any way one wishes. Atox is normally used as a command-line script, using a simple XML language to specify the desired transformation from text to markup, but it is also possible to build custom parsers using the Atox library. The name (short for ASCII-to-XML) is inspired by such UNIX tools and system functions as atops and atoi. What can it do? =============== The examples in the distribution demonstrate how you can use Atox to: - Mark up a (relatively simple) technical document (the Atox manual) - Mark up code blocks only through indentation; - Nest lists through indentation - Discern between different indentation "shapes" (e.g. a block quote versus a description list item); - Transform simple LaTeX into XML; - Add XML "syntax highlighting" to Python code; - Mark up screenplays or stageplays, largely based on indentation; - Mark up simple fictional prose; - Mark up simple tables. What's new in 0.3? ================== Some examples were added to the demo directory, highlighting the new features: The 'ax:indented' tag This tag allows you to match an indent and a dedent easily, even if there is a lot of indentation between the two. The 'ax:try' tag You can indicate that a portion of the format is to be parsed with backtracking by wrapping it in a 'try' tag. This can be very useful for the places were a single-token lookahead just won't cut it. The 'ax:glue' attribute This replaces the experimental 'glued' attribute. The 'glue' attribute can contain a regular expression that much then match the skipped text before a glued element. Using an empty string makes it equivalent to 'glued="yes"'. Where can I get it? =================== Atox is hosted at SourceForge (http://atox.sf.net) and the current release (0.3) is available for download via its project page (http://sf.net/projects/atox). The Small Print =============== Atox is released under the MIT license. It comes with no warranty of any kind. Also, even though the current version works well, and the project is currently (as per early 2004) being actively developed, there is no guarantee of continued support. What you see is what you get. -- Magnus Lie Hetland "Oppression and harassment is a small price to pay http://hetland.org to live in the land of the free." -- C. M. Burns From http Tue Apr 13 05:10:52 2004 From: http (Paul Rubin) Date: 13 Apr 2004 02:10:52 -0700 Subject: how to break tuple to separate variables References: Message-ID: <7xzn9gw8df.fsf@ruckus.brouhaha.com> Stano Paska writes: > # i need some like this > bbb = datetime.date(date2tuple('2004-11-03')) > > # but date requires > bbb = datetime.date(2004, 11, 03) use: bbb = datetime.date(*date2tuple('2004-11-03')) the '*' before the arg means convert the tuple to an arg list. From peter at engcorp.com Tue Apr 6 18:37:49 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 06 Apr 2004 18:37:49 -0400 Subject: shutil.move, permission denied, why ? In-Reply-To: References: Message-ID: St?phane Ninin wrote: > I just do not understand what could cause this "permissions denied" for this > file. Any idea of what stupid thing I could have done somewhere in the code > that could cause that ? Can you do exactly the same thing successfully from the command line? That is, do a "move a b" with the same paths that you are trying to use in your code? From lesstif-admin at lesstif.org Wed Apr 7 02:34:56 2004 From: lesstif-admin at lesstif.org (lesstif-admin at lesstif.org) Date: Wed, 07 Apr 2004 02:34:56 -0400 Subject: Request to mailing list Lesstif rejected Message-ID: Your request to the Lesstif mailing list Posting of your message titled "Mail Delivery (failure lesstif at hungry.com)" has been rejected by the list moderator. The moderator gave the following reason for rejecting your request: "Non-members are not allowed to post messages to this list." Any questions or comments should be directed to the list administrator at: lesstif-admin at lesstif.org From joe at notcharles.ca Fri Apr 16 00:26:14 2004 From: joe at notcharles.ca (Joe Mason) Date: Fri, 16 Apr 2004 04:26:14 GMT Subject: CamelCase versus wide_names (Prothon) References: <1XIfc.245$GN6.197@fe2.columbus.rr.com> Message-ID: In article <1XIfc.245$GN6.197 at fe2.columbus.rr.com>, Carl Banks wrote: > I'm not so sure. All this markup has got to take a lot longer to type > than plain text to input. It would take a pretty slick interface just > to match the ease of typing plain text, and then the programmer would > have to spend a lot of time learning the slick interface. ISTR LyX making this really easy. Joe From adim at nospam.com Fri Apr 16 12:20:16 2004 From: adim at nospam.com (Adrien Di Mascio) Date: Fri, 16 Apr 2004 18:20:16 +0200 Subject: AOP use cases References: <84fc4588.0404140106.3fa0c55@posting.google.com> <0pydnSB4WYuieuLdRVn-hQ@powergate.ca> Message-ID: Le Fri, 16 Apr 2004 17:22:08 +0200, Daniel Dittmar a ?crit?: > Not from personal experience, but these have been mentioned: > - multithreading > - persistence > - transactions > It may very well be that these can be implemented in current Python,but > this only means that Python already has good support for AOP. All the examples you mentioned can be implemented in Python. Maybe we could also add "profiling", "security" ... IMHO, what's great (in this context) with Python is that it's possible to weave code (or adapt code) dynamically wherever you want quite easily. And that's (*only*) a part of AOP. Doing this by using metaclasses, PEAK aspects, Pythius aspects, Logilab aspects, etc. this does not really matter. I think, and I might be wrong since I'm still a bit new to AOP, that there is nothing that you can do with AOP that you could not do with a plain OO program. (And any OO program could also be written in a non object-oriented way). But AOP is here to let you improve reusability by giving some new ways to factorize code. Someone in this thread (I think it is Hung Jung Lu) defined AOP as being a kind of Fourier Transform of OOP, and I like this way of defining it. Cheers, Adrien. From __peter__ at web.de Sat Apr 3 03:20:14 2004 From: __peter__ at web.de (Peter Otten) Date: Sat, 03 Apr 2004 10:20:14 +0200 Subject: String concatenation References: <7xisgi24fm.fsf@ruckus.brouhaha.com> <406D27A7.6550A00B@alcyone.com> <406D2CD5.878EBD4E@alcyone.com> <406D2FA2.6E5118CC@alcyone.com> Message-ID: Leif B. Kristensen wrote: > The "feature" is also submitted to the KDE bugtrack, see > . > > Apparently, "real programmers" don't cut and paste code samples from > KNode. Go figure. I doubt that KNode is to blame. The problem you encountered occured to me only sporadically. Therefore I guess that the culprit is elsewhere in the toolchain. In the meantime, whenever an apparent whitespace generates a syntax error: #!/usr/bin/env python import string, sys, os transTable = string.maketrans(chr(160), " ") if __name__ == "__main__": for filename in sys.argv[1:]: s = file(filename).read() if chr(160) in s: print "cleaning", filename os.rename(filename, filename + ".160") file(filename, "w").write(s.translate(transTable)) else: print "skipping", filename Peter PS: I'm not sure if the above reaches you without those vicious blanks, but I'm confident :-) From mark at prothon.org Wed Apr 28 20:09:44 2004 From: mark at prothon.org (Mark Hahn) Date: Wed, 28 Apr 2004 17:09:44 -0700 Subject: What is good about Prothon? References: <108t2tlo06j8vb9@corp.supernews.com> <69cbbef2.0404281446.4e0ab52e@posting.google.com> Message-ID: has wrote: > "Mark Hahn" wrote in message > news:... > >> I've got Has on one side of me who says that having prototype >> references instead of copies makes it too much like Python and >> therefore it isn't prototype-based > > Not so. I've been saying it's not a proto-OO language because proto-OO > behaves according to a single tier model where all objects are equal, > whereas Prothon, like class-based OO languages, follows a two-tier > model where some objects (classes/"prototypes") are more equal than > others ("object" objects). I apologize. I accidently stated what I once thought you were claiming. I do know now that you are claiming that it's not prototype based if it is two-tiered with templates and instances. My position (which is basicly in agreement with Lieberman's paper) is that having multiple tiers is inherent in all programming and is a natural result of factoring the problem of making many copies of the same thing. We will continue to agree to disagree. I have learned a lot in my arguing with you though and do appreciate the time you've spent wearing out your keyboard. You might be interested to know that the first benefits of classlesness are starting to appear in Prothon, however minor. A small example is that in my Pickle replacement (called Prosist) instead of having a Prototype called DB that you load with the Prosist module to instantiatate your db, you can use the module object itself as the prototype: # typical Python setup import Pickle db = Pickle.DB("filename.db") # Prothon import Prosist db = Prosist("filename.db") I know it's tiny, but it's a beginning to show how things can be simpler when you don't have to have classes. Maybe you could show how your one-tier approach would make this even simpler? From moosebumps at moosebumps.com Sat Apr 3 03:49:21 2004 From: moosebumps at moosebumps.com (Moosebumps) Date: Sat, 03 Apr 2004 08:49:21 GMT Subject: HTML writer References: <406D3C97.7020006@livinglogic.de> Message-ID: "Walter D?rwald" wrote in message news:406D3C97.7020006 at livinglogic.de... > Moosebumps wrote: > > > Is there a standard solution for writing HTML web pages with Python? I > > don't know that much about web programming, but basically I want to generate > > some internal reports on a web page. > > There are several possible HTML generators for Python: > HTMLgen http://starship.python.net/crew/friedrich/HTMLgen/html/main.html > HyperText http://dustman.net/andy/python/HyperText/ > XIST http://www.livinglogic.de/Python/xist/ Thanks for those links, they look like what I'm looking for. Does anyone have any comment on which one of these requires you to have the least amount specific web programming knowledge? i.e. I know basic HTML, and I am an experienced C programmer, but haven't really delved into the specifics of it... never really wanted to clutter up my mind with the alphabet soup of web programming : ). I was thinking that there was some Python library that would wrap the functionality of these languages in some nice consistent OO python interface. It looks like all of these are exactly that, from what I gather, which is great. That is, I would not like any specific HTML tags anywhere in my own code, and it seems like that is what they will allow me to do. But I would be interested to hear opinions/experiences with these packages. thanks, MB From http Sun Apr 18 05:28:50 2004 From: http (Paul Rubin) Date: 18 Apr 2004 02:28:50 -0700 Subject: module not callable - why not? References: <107dras2heahcb6@news.supernews.com> <8ef9bea6.0404122025.36efc84e@posting.google.com> Message-ID: <7xsmf1fxd9.fsf@ruckus.brouhaha.com> Josiah Carlson writes: > I think of modules as a namespace. Why? Because that is what they > are. They contain a space of names, some of which may be useful to > you, otherwise you wouldn't have imported the module. Is a class instance not also a namespace? After all, it contains a space of names, some of which you must have wanted or else you wouldn't have instantiated it. And yet, you can call a class instance if it has a __call__ operation defined. I don't see why modules shouldn't be the same. From gumuz at NO_looze_SPAM.net Mon Apr 26 10:39:54 2004 From: gumuz at NO_looze_SPAM.net (Guyon Morée) Date: Mon, 26 Apr 2004 16:39:54 +0200 Subject: interfacing to a remote excel app References: <20040426150428.69010a3c@pistache.sara.nl> Message-ID: <408d1f29$0$5065$4d4ebb8e@news.nl.uu.net> Let me start by saying, that I don't have a 'solution-to-go' on this, but I'll give it a go anyway. An idea would be to investigate on DCOM (Distributed COM) and accessing that from Unix. I have no clue on how to do this, so I leave that as an exercise for yourself. Otherwise... If you have no problem having 2 seperate interpeters, It's fairly easy to come up with a small xml-rpc interface and acces it through that. just my 2 cents, ps. de groeten aan Gijs en Bas :) "Bram Stolk" wrote in message news:20040426150428.69010a3c at pistache.sara.nl... > pyHello, > > > Google helped me find a nice package to interface python with MS Excel. > "win32all", or sometimes called by the name "pywin32". > > http://starship.python.net/crew/mhammond/ > > However, this win32all extension seems to be specifically built for the > windows platform only. > > What could I use if I want to interface to excel from a python interpreter > running on a remote UNIX machine? > > The specific task I want to accomplish is as follows: > I want python on UNIX to be able to make selections in excel (highlight rows). > Also, I want to have changes in the selected (highlighted) items in excel > to be communicated to the python running on UNIX. > > What would be the best way to do this? > > Thanks, > > Bram > > PS: A possible approach would be to run two interpreters, one on both > platforms, and have the MS python talk to excel. However, I would like a > solution with low-impact to the MS platform, and want to get away without > having to install python and win32all on the MS machine. > > -- > -------------------------------------------------------------------------- ---- > Bram Stolk, VR Engineer. > SARA Academic Computing Services Amsterdam, PO Box 94613, 1090 GP AMSTERDAM > email: bram at nospam.sara.nl Phone +31-20-5923059 Fax +31-20-6683167 > > "For the costs of subsidized agriculture in the EU, we can have all 56 million > European cows fly around the world. First Class." - J. Norberg > -------------------------------------------------------------------------- ---- From peter at engcorp.com Fri Apr 23 16:55:33 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 23 Apr 2004 16:55:33 -0400 Subject: Why we will use obj$func() often In-Reply-To: References: <84Uhc.22278$dZ1.5087@fed1read04> <8AWhc.23114$dZ1.11070@fed1read04> Message-ID: Mike C. Fletcher wrote: > Mark Hahn wrote: > ... >> Peter: You were making fun of how of fast I'm changing things in Prothon, >> right? I was going along with that humour in my message. Someone in a >> private message accused me of making fun of you, which I was >> definitely not doing. >> > Ah, too bad, you might have fit in if you did ;) . He's just *so* much > fun to poke fun at. For crimminy's sake, he's from Canada, and you know > how ridiculous they all are... blubber-eating igloo-wardens every last > one of them. It's practically impossible to take one of them seriously > as a computer programmer, I mean, really, a modern computer would just > melt the igloo down around their heads. See you downtown at the PyGTA meeting on Tuesday, Mike. And remember your snowshoes this time, for heaven's sake. It's still *April*, for cryin' out loud! -Peter From amireallyfat at yahoo.com.au Thu Apr 8 21:01:12 2004 From: amireallyfat at yahoo.com.au (mr_vocab) Date: Fri, 9 Apr 2004 11:01:12 +1000 Subject: program distribution Message-ID: <4075f5bb_1@news.iprimus.com.au> Hi im new to python but have made a few applications how can i save them and get the to run sort of like an application thanks Nathan From nelson at monkey.org Wed Apr 7 22:02:07 2004 From: nelson at monkey.org (Nelson Minar) Date: Thu, 08 Apr 2004 02:02:07 GMT Subject: print u"\u0432": why is this so hard? UnciodeEncodeError Message-ID: I have a simple goal. I want the following Python program to work: print u"\u0432" This program fails on my US Debian machine: UnicodeEncodeError: 'ascii' codec can't encode character u'\u0432' in position 0: ordinal not in range(128) Actually, I have a complex goal: I want my SOAPpy program to work when SOAPpy is in debug mode and is printing XML messages out to stdout. Solving the simple problem will solve the complex one. Since I'm using third party code, I can't go modify every print statement to call encode() explictly. The simplest solution I've come up with is this: $ LANG=en_US.UTF-8 python2.3 -c 'print u"\u0432"' That seems to work reasonably well in Python 2.3 (but not 2.2!). But then for some obscure reason if I redirect stdout in my shell it fails. $ LANG=en_US.UTF-8 python2.3 -c 'print u"\u0432"' > /dev/null Why is that? The only solution I've found that really works is reassigning sys.stdout at the top of the script. That's an awful lot of work, but it's the best I can do for now. Why is Python not respecting my locale? Here's my test program: ---------------------------------------------------------------------- #!/bin/bash -x # Obliterate locale for e in LANG LC_CTYPE LC_NUMERIC LC_TIME LC_COLLATE LC_MONETARY LC_MESSAGES LC_PAPER LC_NAME LC_ADDRESS LC_TELEPHONE LC_MEASUREMENT LC_IDENTIFICATION LC_ALL; do unset $e done # Doing the obvious thing has nonobvious effects python2.3 -c 'print u"\u0432"' # fails, OK. LC_ALL=en_US.utf8 python2.3 -c 'print u"\u0432"' # works! LC_ALL=en_US.utf8 python2.3 -c 'print u"\u0432"' > /dev/null # fails, huh? # These both work, but what a pain! python2.3 -c 'import sys, codecs; sys.stdout = codecs.getwriter("utf-8")(sys.__stdout__); print u"\u0432"' python2.3 -c 'import sys, codecs; sys.stdout = codecs.getwriter("utf-8")(sys.__stdout__); print u"\u0432"' > /dev/null ---------------------------------------------------------------------- And sample output: ---------------------------------------------------------------------- ~/src/python/testUnicode.sh + unset LANG + unset LC_CTYPE + unset LC_NUMERIC + unset LC_TIME + unset LC_COLLATE + unset LC_MONETARY + unset LC_MESSAGES + unset LC_PAPER + unset LC_NAME + unset LC_ADDRESS + unset LC_TELEPHONE + unset LC_MEASUREMENT + unset LC_IDENTIFICATION + unset LC_ALL + python2.3 -c 'print u"\u0432"' Traceback (most recent call last): File "", line 1, in ? UnicodeEncodeError: 'ascii' codec can't encode character u'\u0432' in position 0: ordinal not in range(128) + LC_ALL=en_US.utf8 + python2.3 -c 'print u"\u0432"' ?? + LC_ALL=en_US.utf8 + python2.3 -c 'print u"\u0432"' Traceback (most recent call last): File "", line 1, in ? UnicodeEncodeError: 'ascii' codec can't encode character u'\u0432' in position 0: ordinal not in range(128) + python2.3 -c 'import sys, codecs; sys.stdout = codecs.getwriter("utf-8")(sys.__stdout__); print u"\u0432"' ?? + python2.3 -c 'import sys, codecs; sys.stdout = codecs.getwriter("utf-8")(sys.__stdout__); print u"\u0432"' From nc-jantzegu at netcologne.de Thu Apr 1 15:20:46 2004 From: nc-jantzegu at netcologne.de (Günter Jantzen) Date: Thu, 1 Apr 2004 22:20:46 +0200 Subject: Travelling salesman variation in python References: Message-ID: Hello Erlend, in my opinion its not a TSP. In TSP problems a minimum is searched, you search the maximum And TSP is usually formulated for undirected graphs. So (for me) its not so clear if the problem is NP Did you think about trying a greedy algorithm. Start at some point and go always the way with the highest value and eliminate the previous note If you want better results, try it with more combinations. For example choose the three highest values from every node and follow this ways if possible Use backtracking with recursive calls (explained in many textbooks about discrete mathematics. Typical example - the 8 queens problem) Of course I have no idea if this approch will be helpful G?nter "Erlend Andreas Garberg" schrieb im Newsbeitrag news:slrnc6on9h.spl.erlendga at tva.ifi.uio.no... > Hi! > > I'm trying to code a implementation of a variation of the travelling > salesman problem. > > The problem is the following. > > I have X nodes. > Each node has a number assosiated with each of the other nodes. > > The problem is then: > Construct a ring of the nodes so that the sum of the numbers is the > highest possible. > > Example: > Nodes: > A with numbers B->1200, C->2000 > B with numbers A->3000, C->4000 > C with numbers A->9000, B->5000 > > The optimal ring is in this case can f.ex. be: > A->1200->B->4000->C->9000->A with sum 14200. > > I have implemented this in python in the following way: > > hash is a dictionary with node-name as key and node-object as value. > Each node-object has a dictionary speeds with node-name as key and a > number as value. this dict stores the numbers associated with the other > nodes. > > ------------------------------------------------------------------- > # method xcombinations > def xcombinations(items, n): > if n==0: yield [] > else: > for i in xrange(len(items)): > for cc in xcombinations(items[:i]+items[i+1:],n-1): > yield [items[i]]+cc > > # help function > func = lambda x,y: int(hash[x].speeds[y]) > > > # code starts here: > bestcomb = [] > bestspeed = 0 > > for comb in xcombinations(hash.keys(),len(hash)): > speed = sum(map(func,comb,comb[1:] + comb[:1])) > if speed > bestspeed: > bestcomb = comb > bestspeed = speed > > ----------------------------------------------------------------- > > My implementation generate all combinations, and check which gives the > highest result. > > My problem is that when the number of nodes is higher than 8, the > algorithm slows to a crawl (because of O(n!) complexity). I wonder if > there is some way I can optimize my algorithm to make it run faster? > Currently it takes 20 seconds to compute the best combination with 9 > nodes on my hardware. > > > I would appreciate some comments on this :) > > -- > Regards > Erlend Garberg > From mhammond at keypoint.com.au Thu Apr 29 10:30:28 2004 From: mhammond at keypoint.com.au (Mark Hammond) Date: Fri, 30 Apr 2004 00:30:28 +1000 Subject: makepy generating a file versus a directory In-Reply-To: <9e5ea2c4.0404290556.35c51c64@posting.google.com> References: <9e5ea2c4.0404290556.35c51c64@posting.google.com> Message-ID: Olaf Meding wrote: > When does the makepy utility generate a .py file and when a directory? > And what decided if a directory or a file is generated? Whenever 'bForDemand' is passed to the gencache/makepy functions. Currently EnsureDispatch passes True here. > What is the difference between a file and a directory (both named > after the uuid in the IDL file)? I am moving towards the directory version. In this case, only the package itself (with the __init__.py) is generated when the tlb is loaded. Interfaces etc referenced in the typelib are then generated 'on demand', as they are referenced. The benefit is for huge type-libraries, when only one or 2 interfaces are used. A good example is Excel - often you just use 2 or 3 interfaces, but the .tlb, and generated .py file, is huge. The cost of bringing in the .pyc can be quite high for these typelibs, let alone the generation of it first time around. Mark. From moughanj at tcd.ie Sat Apr 24 04:06:26 2004 From: moughanj at tcd.ie (James Moughan) Date: 24 Apr 2004 01:06:26 -0700 Subject: deleting items within a for loop - mutable indices References: <4089cb21$1_2@mk-nntp-2.news.uk.tiscali.com> Message-ID: <16752bcc.0404240006.491ec7e3@posting.google.com> SnuSnu wrote in message news:<4089cb21$1_2 at mk-nntp-2.news.uk.tiscali.com>... > Okay - here's a (probably) really easy question: > > I can't do the following, so what's the best way to handle this > case of wanting to delete within a loop? > > x = [0,1,2,3,4,5,6,7,8] > deletion_list = [2,7,8] > > for i in deletion_list: > del x[i] > > This obviously doesn't work because the list keeps changing > each time I delete something, so the indices are no longer valid > after the first delete (so I get an IndexError on teh last delete). > > My hack is to do this first (which makes sure that the higher indices > are deleted first), but this is not very elegant or quick: > > deletion_list.sort() > deletion_list.reverse() > # BTW: It's a shame I can't do deletion_list.sort().reverse() > > Is there a simple solution? > > (It would be nice to do something like > del x[2,7,8] # or.. > del [*deletion_list] > ) > > Thanks. Eh, do you want to delete the elements in the deletion list from x, or delete the elements in x which are at the location indicated in the deletion list? Your example doesn't differentiate. Anyhow, this is advice from a newbie :-) but in the first case x = [y for y in x if not y in deletion_list] works well enough. otherwise tmp = [x[i] for i in range(len(x)) if not i in deletion_list] x = tmp you could speed either up for largish lists with hashing; dict = {} for d in deletion_list: dict[d] = 1 tmp = [x[i] for i in range(len(x)) if not dict.has_key(i)] x = tmp alternatively you could make it linear in time for the number of deletion elements, but the performance hit from creating a bunch of lists hurts a bit too much, unless you don't care about order. Which I'm guessing you do. Jam From peter at engcorp.com Mon Apr 12 17:29:35 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 12 Apr 2004 17:29:35 -0400 Subject: How to kill a SocketServer? In-Reply-To: References: Message-ID: <86GdndxCWrGil-bdRVn-gw@powergate.ca> Jean-Pierre Bergamin wrote: > The accept() call still won't get interrupted. :-( > > Other ideas? You have three choices. 1. Run your server as a separate process, communicating with it via some kind of RPC, and just kill it when desired. 2. Use non-blocking sockets. This is the standard and simplest approach in many ways. 3. Arrange to have one thread open a socket connection to the application, waking up your accept()ing thread. Then check a flag which tells the server thread to exit. By definition, blocking calls block, and you can't safely kill a thread in Python so pick one from the above and run with it... -Peter From newsuser at itgoesclick.com Wed Apr 21 16:15:53 2004 From: newsuser at itgoesclick.com (Noah from IT Goes Click) Date: Wed, 21 Apr 2004 20:15:53 GMT Subject: Maybe Komodo might do it In-Reply-To: References: Message-ID: I haven't actually checked if it does it for PHP but it says it has autocomplete, weather it explores your classes or not I don't know. http://www.activestate.com/Products/Komodo/index.plex From greg at cosc.canterbury.ac.nz Thu Apr 15 02:03:48 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Thu, 15 Apr 2004 18:03:48 +1200 Subject: Does Python compete with Java? In-Reply-To: References: Message-ID: Robert Brewer wrote: > Greg Ewing was thinking specifically on getting "and", "or" and "not" to > be overridable: > http://groups.google.com/groups?group=comp.lang.python.*&selm=c1bobu%241 > g1p9e%241%40ID-169208.news.uni-berlin.de&rnum=1 > I'm not sure how far he got, but I'd still appreciate it myself (Greg? > <:) I haven't found time to do anything on it yet, but I still intend to. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From tjreedy at udel.edu Tue Apr 13 02:10:16 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 13 Apr 2004 02:10:16 -0400 Subject: Once-only evaluation of default parameter values functiondefinitions References: <407B79D7.424F65A1@doe.carleton.ca> Message-ID: "Fred Ma" wrote in message news:407B79D7.424F65A1 at doe.carleton.ca... > Hello, > Example#1 > --------- > def f(a, L=[]): > L.append(a) > return L > > Instead, one should use: > > Example#2 > --------- > def f(a, L=None): > if L is None: > L = [] > L.append(a) > return L > > print f(1) > print f(2) > print f(3) > > prints > > [1] > [1, 2] > [1, 2, 3] >= > The alternative explanation that I could think of is that L is bound > to the unnamed object [], and the object itself changes values to > reflect changes to L i.e. L is now a persistent variable, retaining > its value between function calls unless a value is provided for L in > the function call's argument list. More or less correct except that it is the object that you should think of as persistent. The variable L only exists during the function call. In the latter case, one can > imagine L simply being overwritten with the value provided. When one is provided. > The problem with this picture is that Example#2 should fail for the > same reasons as Example#1. That is, L will not get the value of None > on the 2nd call to f() without a value specified for L. L gets bound to None whenever not overriden, on a per call basis. > Hence, L will not be reset to []. Hence L *will* be reset to [] From mark at prothon.org Thu Apr 22 17:14:39 2004 From: mark at prothon.org (Mark Hahn) Date: Thu, 22 Apr 2004 14:14:39 -0700 Subject: Why we will use obj$func() often References: <84Uhc.22278$dZ1.5087@fed1read04> Message-ID: <8AWhc.23114$dZ1.11070@fed1read04> Mike C. Fletcher wrote: > This isn't really a very clear description of what's going on in > Python. It won't matter to the Prothon users, but don't want any > Python users to get confused... My inability to understand this stuff is what drove me to do Prothon . All the hidden wrapped this and wrapped that confused me to no end. > By the way, the modern Python idiom is: > > super( klass2, self ).func( ) > You're kidding. That seems like a big leap backwards in friendliness. Kind of a syntax castor oil. That's explains why Joe Mason did his proposal for Prothon delegation using that same idiom for Prothon. I thought he was somewhat crazy wanting us to type all that each time. What problem caused Python to want to switch to such a general operation? What is the usage case that is so important that it is making eveyone wear out their keyboards typing that monstrosity? Oh well, I guess it gives me one more argument to pitch for Prothon... From pirx at python.net Sun Apr 4 22:54:20 2004 From: pirx at python.net (Christian Tismer) Date: Mon, 05 Apr 2004 04:54:20 +0200 Subject: Python is faster than C In-Reply-To: References: <406F0907.96F37EA1@tunes.org> <7xy8pcogaa.fsf@ruckus.brouhaha.com> <406F454B.C4CC8063@tunes.org> <7xekr4vdek.fsf@ruckus.brouhaha.com> <406F5E95.EBE6D3E8@tunes.org> Message-ID: Christian Tismer wrote: > Armin Rigo tunes.org> writes: > > >>Again I'm not saying it is trivial to implement it, but that not having >>to expose for optimization purposes 'xrange' and the whole 'iterator' >>part of the language would be worth it, in my opinion. Responding to myself, after chatting with Armin: > In general, I share Armin's impression, that iterators are nothing else > but an explicit way to spell optimizations. > While explicit is better than implicit, in the case of optimizations, > I believe it is an over-specification, and almost completely in the false > direction. We have to prove this in a known project, still. ... > instead you can do it this way: > > it = iter(sequence) > can_continue = 1 > while can_continue: > try: > for each in it: > do_something_with(each) > exceptSomeThingWrongWithThis > can_continue = some_recovery(each) > continue Well, I agree that this is no excuse for the need for iterators. Under the assumption that iterators are almost for speed, which could be gathered otherwise, then my use case is also a hack for speed. It would not be needed if exceptions in tight loop weren't expensive. Actually, with a different layout of exceptions, they could come at no cost if they are not thrown and slightly more cost if they are thrown. This is not exactly my idea but came from Armin. Maybe the blcok stack is going to be optimized away. cheers - chris From Andreas.Ames at tenovis.com Fri Apr 23 09:29:30 2004 From: Andreas.Ames at tenovis.com (Ames Andreas (MPA/DF)) Date: Fri, 23 Apr 2004 15:29:30 +0200 Subject: [Q] C-api: string|int|... construction Message-ID: <788E231C269961418F38D3E360D165259B408F@tndefr-ws00021.tenovis.corp.lan> Duncan Booth writes: > Why are you wrapping the ODBC api instead of using one of the > existing wrappings? I just know about mxODBC and pyodbc (from pywin32, but it's easily ported to posix as it seems, there's something on Gnu's savannah I think). Please tell me if there are others, I'd be glad to use existing ones to save time. Both of the above don't fit my needs both license-wise and technically (easy access to meta-data/schema, thread-safety etc.). I actually like the idea of a low-level python wrapper around ODBC. A dbi wrapper might be easier to write in python itself. > Sorry, I thought you said large. 1024 bytes isn't large. My first job was programming some embedded system where 1024 bytes was (and I think still is although I'm no longer there) huuuuge, but as usual YMMV ;-). In python's context you are right, it's tiny and the time to copy it may be meaningless, but I'm not sure that's one of the things I really like about python. Anyway, I didn't want to say the strings I expect are only 1024 bytes long but that's the threshold I may chose for my first attempt to call the said api. > Use PyString_FromStringAndSize(NULL, size) to create a new Python > string with an empty buffer, then PyString_AsString(s) to get a > pointer to the buffer. Pass that to your C api, then call > _PyString_Resize to set the length correctly. That's just great advise, thanks very much. > Python has to control the lifetime of the buffer. By copying into > its own buffer it avoids issues over ownership. To be able to use the C api I need to learn to get the reference counting straight, so I will certainly be able to learn about the ownership of buffers that are used to construct python objects. Thank you very much, andreas From peter at engcorp.com Fri Apr 23 16:52:30 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 23 Apr 2004 16:52:30 -0400 Subject: Why we will use obj$func() often In-Reply-To: References: <84Uhc.22278$dZ1.5087@fed1read04> <8AWhc.23114$dZ1.11070@fed1read04> Message-ID: Mark Hahn wrote: > "Mark Hahn" wrote in message > news:Pedic.28731$dZ1.11479 at fed1read04... > >>"Peter Hansen" wrote ... >>>Mike, you haven't been keeping up with the other thread. I think the >>>decision is now: >>> >>> fish_height$some_where() >> >>That is like SO two-hours-ago. Marcia like, told me that Biff like, said >>that Trish like, said camelCase was SO out, can you BELIEVE IT???? > > Peter: You were making fun of how of fast I'm changing things in Prothon, > right? I was going along with that humour in my message. Someone in a > private message accused me of making fun of you, which I was definitely not > doing. No offense taken, nor thought to be intended. (Best to include a smiley next time, however, just in case. I think the newsgroup needs more of those right now. I think it's those damn crows outside my window that are getting everyone on edge. You can hear them, right? They're very loud... where's a kid with a BB gun when you need him?) -Peter From peter9547 at btinternet.com Sun Apr 4 12:05:14 2004 From: peter9547 at btinternet.com (Peter MacKenzie) Date: Sun, 4 Apr 2004 16:05:14 +0000 (UTC) Subject: emergent/swarm/evolutionary systems etc References: <106ugk2brruis3a@corp.supernews.com> Message-ID: Von Thunen? I had to look that one up, but I realised upon finding it that I'd been taught it way back in first year geography in high school. It's not something they refer to anymore, except as an absolute first step to understanding settlement structure and distribution. Looking over it again, it's easy to see why. The criteria required for it to work are almost impossible in the real world, so the models that are taught after it are generally refinements and novel applications of the basic Von Thunen concepts. To take a couple of examples, the bid/rent model of land use is a modern version that incorporates lines of communication (roads, rails, etc) when considering land uses, which convert the concentric structure of the Von Thunen model into something more reminiscent of a spider web. Models that address sociological phenomenon bring in another layer of refinement. Particularly notable are those models that focus on 'quartered' cities, with self-contained micro-cities serving distinct groups. These structures were commonplace during the colonial era, when trade cities were often a multi-nucleated patchwork of white, indigenous and 'miscellaneous' societies. It's common, when addressing any location, to apply a Von Thunen framework to the layout of the area and use any discrepancies with the idealised theory as a focus of the study. Generally though, it's something so ingrained in the geographer's conscious that it never really gets much thought. Cameron Laird wrote in message news:106ugk2brruis3a at corp.supernews.com... > In article , > Josiah Carlson wrote: > >> rules. Given that I have only a basic foothold on the language, does > >> anybody foresee difficulties for me learning enough to impliment simple and > >> experimentally flexible sim-city style simulations (minus fancy graphics and > >> llamas) in no more than 2 months (to allow for time to conduct actual > >> experiments + field observations etc)? I would be able to engender aid from > >> various staff, and the university library should carry titles on the > >> subject. Failing that, I could do it the old fashioned way and buy a how-to > >> book, but I'd like some opinions on the difficulty of the goal from people > >> who've already trancended the non-programmer/programmer barrier. > > > > > >Two months is a pretty tight schedule. If you're on your toes, I would > >bet you could learn enough of the langauge to support your ideas in 2 > >months. Actually programming the thing in 2 months; I wouldn't be able > >to make that kind of judgement about your abilities. > . > . > . > Bluntly, I'd bet against it. There's a daunting amount > of new material you'll need to learn. My advice: we can > help you refine your project so that the computing part is > less overwhelming. > > 'You read von Thunen, by the way? > -- > > Cameron Laird > Business: http://www.Phaseit.net From a_salnikov at yahoo.com Thu Apr 1 20:47:54 2004 From: a_salnikov at yahoo.com (Andy Salnikov) Date: Thu, 1 Apr 2004 17:47:54 -0800 Subject: Timeline plots with Python Message-ID: Hi all, does anybody knows any plotting library which can do nice timeline plots? Python is preffered, but not strictly necessary. Standalone utility might also be OK if one can feed some data from a script into it. I feel that I will have to do it myself using some low-level plottin library, but I have no time now to spend on this thing. And I hate this low-level stuff, scaling, date/time formatting, etc. Cheers, Andy. From peter9547 at btinternet.com Fri Apr 2 11:21:08 2004 From: peter9547 at btinternet.com (Peter MacKenzie) Date: Fri, 2 Apr 2004 16:21:08 +0000 (UTC) Subject: emergent/swarm/evolutionary systems etc References: Message-ID: Peter Hansen + Mickel Gr?nroos, (unsure of a more suitable intro protocol for this environment + situation) Oh the joy! It makes life worth living when things click into place and make sense. My style of learning seems ill suited to the material available on the subject, so although I had indeed read all that I could find on making files, it was presented in a manner that I couldn't quite comprehend. To elaborate, I process linguistic information in a holistic, intuitive manner; a quality that requires for me to develop a 'feel' for the language in question, rather than a literal understanding of the rules. Because of this, I need full-yet-simple working examples to deconstruct and process. Most of the examples I've come across have been fragmented and incomplete, which leaves me grasping at loose ends and the countless possibilities therein. It's as though somebody had handed me at birth a dictionary and a set of grammatical rules, with the expectation that I would be able to piece it all together and learn to communicate. Conversely, my search for the working examples I craved only turned up applications of the process that were too bound up in more complex matters to be decipherable, the analogy this time being that of getting handed a copy of 'Moby Dick' from which to start my education. Being presented with an isolated, sterilised 'specimen' has helped me to form a better understanding of the language, being of the right mix of information bandwidth vs. complexity to allow me to capture the 'flavour' in the code. If there are any teachers reading this, I hope it might engender you to consider the varying needs of students in your classes. By being an outlier on the mental demographic, I've long suffered from problems arising from my minority neurology. The cause, however, has generally been from communicative frictions, rather than from the relative merits and demerits of that mental architecture. Thank you both for your help (spreadsheets in the next message). From bjornhb3 at yahoo.se Thu Apr 1 11:39:08 2004 From: bjornhb3 at yahoo.se (Bjorn Heimir Bjornsson) Date: 1 Apr 2004 08:39:08 -0800 Subject: Verifying temporal properties. Need problems. Message-ID: <68771ca.0404010839.39b0c24f@posting.google.com> Hello all As part of a thesis, I am model checking Python programs (a limited subset anyway). I have a very rough prototype that can deal with temporal properties (LTL), that is statically prove properties of the kind: "if A happens, then B should follow" or "if A happens, then B must not follow unless C happens first". A,B,C here being function calls (system or other library). The idea is that this might complement testing or manual auditing during development. So the solution now requires a problem. Basically I'm trying to find interesting areas where a programmer is supposed to call specific functions in a particular order, but where coding errors might prevent this. I would be most happy with distinctively Python-related problems, like some tricky-to-use system calls or something from Zope or security-related issues, etc. So if any of you have ideas (specific function calls) where this kind of tool would be useful, I would welcome feedback. If replying privately, use bjornhb2_hotmail.com (more or less). Thanks a lot :) Bjorn From tkpmep at hotmail.com Thu Apr 29 20:02:58 2004 From: tkpmep at hotmail.com (Thomas Philips) Date: 29 Apr 2004 17:02:58 -0700 Subject: Subclasses in Python References: Message-ID: Perfect! But tell me, how did you know to use __name__? I typed dir(object) and dir(Player) in IDLE, and in neither case did __name__ show up. >>> dir(object) gives me ['__class__', '__delattr__', '__doc__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__'] dir(Player) gives me a few more things - the object's methods and class variables, and some additional stuff: __dict__, __hash__, __module__ and __weakref__. Neither sight nor sound of __name__ - __module__is as close as I get to the magical __name__. What gives? And, before I forget, thanks for all the help - I wouldn't have solved it without you. Thomas Philips From newsgroups at jhrothjr.com Sat Apr 17 12:34:39 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 17 Apr 2004 12:34:39 -0400 Subject: AOP use cases References: <84fc4588.0404140106.3fa0c55@posting.google.com> <0pydnSB4WYuieuLdRVn-hQ@powergate.ca> Message-ID: <1082n594lndh27f@news.supernews.com> "Peter Hansen" wrote in message news:0pydnSB4WYuieuLdRVn-hQ at powergate.ca... > Will Stuyvesant wrote: > > > What are good usage examples? > > I would be very interested to hear some real-world and real useful > use cases for AOP as well. So far, the logging example seems to > be put forth so often that I'm starting to suspect that's the > *only* "useful" thing people are doing with it. :-) > > From direct personal experience, could some AOP folks please > point out some compelling use cases so that the doubting > Thomases (and Wills, and Peters) can better understand and > accept the idea of AOP as being more than just a few fringe > cases? > > (The logging one actually annoys me: the only time I've ever > wanted such logging was when debugging very complicated problems, > and since switching to TDD I have never encountered anything > that even remotely made me consider writing such logging wrappers > again.) > > -Peter I suspect you're not going to get any really compelling ones. The reason I say this is a lot of experience I had about 30 years ago, when I was supporting an installation with IBM mainframes, using MFT and MVT (the predecessors to MVS.) One of my favorite methods of installing patches and modifications was to insert code in the call paths between modules, using patches and link editor gyrations. Why? Because I couldn't get the source code to change it, and even if I could have done so, changing it would have exposed me to horrendous integration problems with upgrades (something I had to learn the hard way.) When you're supporting a monolithic proprietary application, sometimes you have to do what you have to do, but today the entire idea simply smells of a high-tech way to do ad-hoc patching where a really well designed application would not need it (and I don't really care if the design is up front or emergent.) John Roth From cy.fbp.eryvtvne at ncbybtrglxn.pbz Fri Apr 16 08:14:19 2004 From: cy.fbp.eryvtvne at ncbybtrglxn.pbz (JZ) Date: Fri, 16 Apr 2004 14:14:19 +0200 Subject: MySQLdb error for sql >64K Message-ID: <11vs3qm7platj$.e7an576g31z5.dlg@40tude.net> I cannot execute insert data into TEXT field if that data is bigger than 64KB. :( >>> cursor.execute("INSERT INTO table (field) VALUES(%s) WHERE id=1", myValue) Traceback (most recent call last): File "", line 1, in ? File "C:\opt\PYTHON~1\lib\site-packages\MySQLdb\cursors.py", line 95, in execute return self._execute(query, args) File "C:\opt\PYTHON~1\lib\site-packages\MySQLdb\cursors.py", line 114, in _execute self.errorhandler(self, exc, value) File "C:\opt\PYTHON~1\lib\site-packages\MySQLdb\connections.py", line 33, in defaulterrorhandler raise errorclass, errorvalue Warning: Rows matched: 1 Changed: 0 Warnings: 1 The same sql query executed using MySQLFront client works without any problems. So, I think the problem must be with MySQLdb 0.9.2 module. Any suggestions? -- JZ From beliavsky at aol.com Thu Apr 29 10:54:01 2004 From: beliavsky at aol.com (beliavsky at aol.com) Date: 29 Apr 2004 07:54:01 -0700 Subject: MATLAB2Python References: Message-ID: <3064b51d.0404290654.58e59124@posting.google.com> Sarge wrote in message news:... > Hi, everybody! > I'm a moderately experienced programmer in Matlab, and looking for a > free computational language (Matlab is *REALLY* expensive for an > individual, like me). You should consider the (compiled) F programming language, which is a free subset of Fortran 95 -- see http://www.fortran.com/F/index.html. F and F95 both have array operations comparable to Matlab. You can get a syntax comparison of Matlab and Fortran at http://www.owlnet.rice.edu/~mech517/F90_Overview.html . Fortran 95 compilers are not in general free but much are less expensive than Matlab. The Intel Fortran 95 compiler is free on Linux for noncommercial use, and the open-source G95 compiler on Linux is usable (but not yet mature) -- see http://g95.sourceforge.net/ . > I came across Python (actually Scipy) and immediately felt > comfortable with the interface and syntax. > I'm still a newbe, so, before attempting a serious work on it, I'd > like to hear any opinion about migration from Matlab to Python, and > also a rough comparison between these two languages. I have found numerous cases where Python programs run 10-100 times slower or more than a comparable Fortran 95 program. Look up my previous posts here. Although both Matlab and Python are scripting languages, much more effort has gone into optimizing the former for speed. If execution time is more important than scripting convenience, I recommend Fortran over Python. An indication that Python takes the interests of beginning programmers more seriously than those of experienced scientific programmers is that integer division is going to be redefined in future versions of the language -- 2/3 = 1 now but will equal 1.5 in the future. (I think you are supposed to use 2//3). The Fortran standards committee takes backwards compatibility much more seriously, so that code you write now will not take on a new meaning in future versions of the language. From chrish at cryptocard.com Tue Apr 6 08:36:53 2004 From: chrish at cryptocard.com (Chris Herborth) Date: Tue, 06 Apr 2004 08:36:53 -0400 Subject: Does Python compete with Java? In-Reply-To: References: <8b336527.0404051337.51bb4a1b@posting.google.com> <1073su4etm95p35@news.supernews.com> Message-ID: Roy Smith wrote: [... JSP example ...] > 13 lines of code instead of the original 26! This 2:1 ratio seems to be > pretty typical in my experience. It's not that I'm cramming more > application logic onto each line in the Python version, it's that I'm > getting rid of the fluff that takes up lines without adding anything > useful. I've experienced the same thing with the XML applications I tend to write at work; the Python version is much smaller than the Java version, much easier to read, and it was much easier to write. And tends to run about as quickly. Strangely enough, I've had the same results with C# and .NET XML apps; smaller, with less extraneous text in the code. And very fast. If Mono and/or GNU Portable.NET were further along, I'd port my XML apps to C# (I need to run on OS X and, eventually, Linux as well as Windows)... > The end result is that it's harder to write, and the effort that goes > into making the compiler happy is that much less effort that I can put > into making sure I really understand how my application should be > designed, and testing it. It's a seeing the forest for the trees kind > of issue. One of Python's most awesome features (IMHO at least) is that you can fire up an interactive interpreter while you're writing your code, and try things out as you go... using this technique, I've unit tested methods and algorithms interactively and ended up with useful, non-trivial applications that run and work properly the first time. With compiled languages (Java, C#, C++), I find I'm writing a bit of code, taking a break to compile it, figuring out how to unit test the method... Python saves me a huge amount of time in the prototype and development cycles. -- Chris Herborth chrish at cryptocard.com Documentation Overlord, CRYPTOCard Corp. http://www.cryptocard.com/ Never send a monster to do the work of an evil scientist. Postatem obscuri lateris nescitis. From beatboxx83 at aol.com Fri Apr 16 01:15:20 2004 From: beatboxx83 at aol.com (BeatBoxx83) Date: 16 Apr 2004 05:15:20 GMT Subject: Aspect Programming Module References: <84fc4588.0404140106.3fa0c55@posting.google.com> Message-ID: <20040416011520.14072.00000420@mb-m05.aol.com> please, give me some pointers on begenning. I would love to learn how to start. thank you From roy at panix.com Tue Apr 6 11:29:10 2004 From: roy at panix.com (Roy Smith) Date: Tue, 06 Apr 2004 11:29:10 -0400 Subject: Does Python compete with Java? References: <8b336527.0404051337.51bb4a1b@posting.google.com> <1073su4etm95p35@news.supernews.com> Message-ID: Chris Herborth writes: >> With compiled languages (Java, C#, C++), I find I'm writing a bit of >> code, taking a break to compile it, figuring out how to unit test the >> method... Python saves me a huge amount of time in the prototype and >> development cycles. Jacek Generowicz wrote: > Please note that this has nothing to do with compilation per-se. There > are languages with to-native-binary compilers which give you all the > instant turnaround flexibility that Python does. Even more interesting is the fact that Java and Python both have very similar architectures (similar enough, in fact, that things like Jython are possible). Both compile your source code text into an intermediate "byte code" form, and both then run this intermediate form on a virtual machine. The difference is that Java exposes the compilation step to the user while Python hides it. If you really wanted to, you could hack up a "Python compiler" which takes .py files, imports them to force generation of the corresponding .pyc files, and then exits without executing anything. You could then execute the .pyc files in a distinct "execute phase". Not sure why you would want to do that, though :-) From jcarlson at uci.edu Wed Apr 7 00:54:56 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Tue, 06 Apr 2004 21:54:56 -0700 Subject: A beginner's question on thread In-Reply-To: References: Message-ID: Timothy Wu wrote: > I'm writing a small utility that listens for socket connections, and > also repond to user inputs via a text menu selection. > > In order to respond to both the user and the incoming connections I > figure I need to use thread. > > I think I would use the main thread to handle the menu and spawn a > thread which listens on a socket. > > Now my question is, how do I terminate the server thread if user wants > to exit the application? If the server just sit there and listen the > thread would never terminate by itself. What kind of inter-thread > communications are available and where would I find info/tutorial on that? No need for threads. If you have your server set up properly with asyncore, the below link will give you an example using wxPython that will just work... http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&c2coff=1&safe=off&threadm=c35daa%24ka7%241%40news.service.uci.edu&rnum=1&prev=/groups%3Fhl%3Den%26lr%3D%26ie%3DISO-8859-1%26safe%3Doff%26c2coff%3D1%26q%3Djosiah%2Bsocket%2Bwxpython%26btnG%3DSearch%26meta%3Dgroup%253Dcomp.lang.python.* Enjoy. - Josiah From mark at prothon.org Fri Apr 23 17:03:05 2004 From: mark at prothon.org (Mark Hahn) Date: Fri, 23 Apr 2004 14:03:05 -0700 Subject: Why we will use obj$func() often References: <84Uhc.22278$dZ1.5087@fed1read04> <8AWhc.23114$dZ1.11070@fed1read04> Message-ID: "Peter Hansen" wrote ... > I have to go with Mike on the problem with $ however... I think he makes sense also, which means my democracy is in trouble. I put it out for a vote and everyone is voting for $. I should have figured this would happen. More people use Perl than Python also :) (Just kidding -- no flames please -- just kidding). From heikowu at ceosg.de Tue Apr 27 05:55:33 2004 From: heikowu at ceosg.de (Heiko Wundram) Date: Tue, 27 Apr 2004 11:55:33 +0200 Subject: Default Argument Inconsistency? In-Reply-To: References: Message-ID: <200404271155.34205.heikowu@ceosg.de> I guess I'll best describe this behavior when commenting directly in the code. Am Dienstag, 27. April 2004 11:24 schrieb Paul Sweeney: > def f(a,L=[]): > if not L: L=[] It checks whether not L (in this context, meaning that the list is empty). The list is (initialized with []), so the action is triggered. The action creates a new empty list, whose reference is now stored in L. The list which is constructed as the default argument is unbound from L, but still referenced in the function object for f (as the default argument for L, if it isn't present). > L.append(a) The append appends an item to the newly created empty list. > return L The append returns the new list. Hope this sheds light on this behavior. When calling in for the second time, the default argument is still empty, a new list is created, etc. The default argument thus never changes from being the empty list. Heiko. From hwlgw at hotmail.com Sat Apr 10 04:25:44 2004 From: hwlgw at hotmail.com (Will Stuyvesant) Date: 10 Apr 2004 01:25:44 -0700 Subject: Python for MPG Message-ID: Is there Python software for dealing with MPG movies? I am not interested in visual effects etc. but in cutting scenes from big MGP files and creating new files with those scenes. From jdhunter at ace.bsd.uchicago.edu Fri Apr 16 15:05:46 2004 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Fri, 16 Apr 2004 14:05:46 -0500 Subject: a little math problem In-Reply-To: <20040416164439.GD26865@unpythonic.net> (Jeff Epler's message of "Fri, 16 Apr 2004 11:44:39 -0500") References: <20040416164439.GD26865@unpythonic.net> Message-ID: >>>>> "Jeff" == Jeff Epler writes: Jeff> math.fmod might help Jeff Doesn't seem to. Eg, >>> 25.2%.2 0.1999999999999979 >>> math.fmod(25.2,2) 1.1999999999999993 >>> math.fmod(25.2,.2) 0.1999999999999979 Here is what I have so far - hasn't solved the floating point problem though class Base: 'this solution has floating point inaccuracies' def __init__(self, base): assert(base>0) self.base = base def lt(self, x): 'return the largest multiple of base < x' d,m = divmod(x, self.base) if m==0: return (d-1)*self.base else: return d*self.base def le(self, x): 'return the largest multiple of base <= x' d,m = divmod(x, self.base) return d*self.base def gt(self, x): 'return the largest multiple of base > x' d,m = divmod(x, self.base) return (d+1)*self.base def ge(self, x): 'return the largest multiple of base >= x' d,m = divmod(x, self.base) if m==0: return x return (d+1)*self.base def get_base(self): return self.base def closeto(x,y): print x,y,abs(x-y), abs(x-y) < 1e-12 b = Base(.2) closeto(b.lt(25.3), 25.2) closeto(b.lt(25.2), 25.0) closeto(b.le(25.3), 25.2) closeto(b.le(25.2), 25.2) print closeto(b.gt(25.3), 25.4) closeto(b.gt(25.2), 25.4) closeto(b.ge(25.3), 25.4) closeto(b.ge(25.2), 25.2) print print b = Base(4) closeto(b.lt(12), 8) closeto(b.lt(13), 12) closeto(b.le(12), 12) closeto(b.le(13), 12) print closeto(b.gt(12), 16) closeto(b.gt(13), 16) closeto(b.ge(12), 12) closeto(b.ge(13), 16) From newsgroups at jhrothjr.com Thu Apr 22 12:19:29 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Thu, 22 Apr 2004 12:19:29 -0400 Subject: AOP use cases References: <84fc4588.0404140106.3fa0c55@posting.google.com> <0pydnSB4WYuieuLdRVn-hQ@powergate.ca> <108f99vgg6ub501@news.supernews.com> Message-ID: <108fs4skm6qud8b@news.supernews.com> "Jacek Generowicz" wrote in message news:tyf3c6wusc8.fsf at pcepsft001.cern.ch... > "John Roth" writes: > > > there are no, and I mean no, examples of composable programs where > > there was no planning on making it happen. > > Aaah, yes, Proof by Ignorance[*], one of my favourite logical tools :-) > > > [*] I don't know a programming language whose name starts with "P" and > ends with "n", therefore none exist. QED[+] > > > [+] Best used in conjunction with Proof by Projection: None exist now, > therefore none have existed in the past, and none will exist in > the future. Ignorance is a powreful tool. Thus sayeth the Zealot, who, when he no longer has a leg to stand on, resorts to cutsi-poo mindreading. If you will come up with an example, I will stand by to show you exactly where the planning happened that allowed it to be composed. John Roth From claird at lairds.com Fri Apr 16 18:13:52 2004 From: claird at lairds.com (Cameron Laird) Date: Fri, 16 Apr 2004 22:13:52 -0000 Subject: Goodbye TCL References: <0LudnSads6NmpuPdRVn-vw@centurytel.net> <21ccedf1.0404160639.14c2d852@posting.google.com> Message-ID: <1080ml0hdpp6tdf@corp.supernews.com> In article <21ccedf1.0404160639.14c2d852 at posting.google.com>, Phil Dietz wrote: >Forget OO... >TCL still doesn't have a standard database API in the core yet.... Was this intended as a contrast with Python? 'Different way to say this: "database", in this sense, is a dirty subject, in that it's far more tied to grungy details of specific implementations than the masses generally realize, or than either Python or Tcl, both of which prize purity in their own ways, generally support. A general database abstraction is about as rarefied as a general GUI abstraction. -- Cameron Laird Business: http://www.Phaseit.net From moosebumps at moosebumps.com Sat Apr 3 16:06:17 2004 From: moosebumps at moosebumps.com (Moosebumps) Date: Sat, 03 Apr 2004 21:06:17 GMT Subject: Capturing stdout incrementally Message-ID: I have a large set of Python scripts that interface with command line utilities (primarily Perforce). I am currently capturing ALL the text output in order to get results and such. I am using the popen functions to get the stdout, stderr streams. However, some of the operations take a really long time (copying large files over the network). If you run Perforce directly (or through os.system, which doesn't return text output), it shows which files are getting copied, one at a time. However, if I'm calling it through Python's popen, it appears to hang while it copies all the files, then suddenly all the text output appears at once after the operation is done. Does anyone know a way around this? It is problematic because people think that the program has hung, when it is really just taking a long time. I would like the normal stdout to be printed on the screen as it is normally (but also captured by my Python script simultaneously). I am on Windows by the way, so the utilities are printing to the windows command shell. thanks for any advice, MB From fumanchu at amor.org Tue Apr 27 15:41:19 2004 From: fumanchu at amor.org (Robert Brewer) Date: Tue, 27 Apr 2004 12:41:19 -0700 Subject: Is Perl *that* good? Message-ID: I wrote: > >>I wish Python had won, as well. But time is linear (in > >>my mind). I now wish only that we could leverage the > >>similarity of JS and Python (execution and binding > >>models) into more Python users. Marketing needs > >>to run with the line, "So you know Javascript? Then > >>you know Python!" and Peter Hansen replied: > I learned Javascript after learning Python. (That is, up until that > point, I coded Javascript like a script kiddie, copying and tweaking > without understanding.) It was the similarities with Python that > actually let me start to respect it somewhat. I thought "Cool! It's > just like Python but with less power and an uglier syntax!" :-) I had a similar experience. I was just starting to appreciate Javascript and write some more powerful applications (here and there, not exclusively ;) when I found Python. I agree that Python has improved my appreciation for JS: I just finished a much nicer 2.0 version of Lyrica (a web slideshow tool*), and although I miss some of Python's clarity in JS, I've learned a lot about how to make JS cleaner and better by learning Python. Robert Brewer MIS Amor Ministries fumanchu at amor.org * IE only: http://www.aminus.org/rbre/music/lyrica It's mostly a way to get the fun of stylesheets out to the average user, without making them learn XHTML, CSS, JS, and the DOM in all their powerful, confusing expressiveness. I use it at church for song lyrics, but it can be used for almost any content. From eldiener at earthlink.net Sat Apr 3 21:47:13 2004 From: eldiener at earthlink.net (Edward Diener) Date: Sun, 04 Apr 2004 02:47:13 GMT Subject: Typing \n in strings Message-ID: Python 2.3.3 on Win2K. In the Python tutorial it says that typing \n in string literals is the new-line character. I open the interpreter and type a string with a \n in it but instead of outputting a string with a new line, it outputs the \n as literal characters of the string. Is the tutorial wrong, is the interpreter broken, or what is happening ? From adalke at mindspring.com Mon Apr 5 15:49:43 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Mon, 05 Apr 2004 19:49:43 GMT Subject: Python is faster than C References: <406F0907.96F37EA1@tunes.org> <5d83790c.0404032144.482787bd@posting.google.com> <6y1cc.1346$Qv6.482@fe2.columbus.rr.com> <5d83790c.0404042306.497e0384@posting.google.com> Message-ID: Raymond Hettinger: > Likewise, I program in a less hostile world than Andrew Dalke who has > to contend with pandora's box iterators which ruin the lives of mortal > men who think they can call .next() with impunity ;-) I did say "Should be rare though." :) Andrew dalke at dalkescientific.com (And now you've got me thinking about the Tomb Raider II movie. Not a bad thing.) From youngdubliner at hotmail.com Tue Apr 20 20:24:00 2004 From: youngdubliner at hotmail.com (youngdubliner at hotmail.com) Date: 20 Apr 2004 17:24:00 -0700 Subject: Embedding Python in C Message-ID: <4039221c.0404201624.119476e9@posting.google.com> Hi All , Bit of a problem with Py_Parse or Py_ParseTuple ? I have a python script that reads a sector of flash in an embedded device. it returns the value of each byte within the sector as a tuple. i.e. [255,255,255,255,255,255,255, .......etc etc for the whole sector ! We are using this script to read whats currently in any sector. No problems there. Now I need to call our script from C. I want to copy each of the bytes within the sector into an C unsigned char *array Is there any way to do this using Py_ParseTuple or Py_Parse ??? something like this for instance ??? ...... Py_ParseTuple[pres,"??",&my_c_array] so now my_c_array[0] = 255 ,my_c_array[1] = 255 ,my_c_array[2] = 255 , etc etc Thanks for the help ! From none at none.com Mon Apr 26 22:31:08 2004 From: none at none.com (JDR) Date: Tue, 27 Apr 2004 02:31:08 GMT Subject: Using a single module of Pygame Message-ID: Would anyone happen to know of a way to strip out the joystick module of Pygame? I've written a console based application that doesn't need X, mixer, fonts, etc. and I can't get my application to run without X11 libs installed. I've been searching google for the past hour without luck. If anyone knows of any good informational sites, please let me know. I'll keep digging through Python's docs. Thanks! From simoninusa2001 at yahoo.co.uk Fri Apr 9 01:54:44 2004 From: simoninusa2001 at yahoo.co.uk (simo) Date: 8 Apr 2004 22:54:44 -0700 Subject: wx.SystemSettings - GTK/Win32/Python variances References: <30260531.0404081003.136f8759@posting.google.com> <30260531.0404081529.195b033e@posting.google.com> Message-ID: <30260531.0404082154.1befc57a@posting.google.com> [snip] > > On my machine (WinXP) it contains: > > > > >>> wx.PlatformInfo > > ('__WXMSW__', 'wxMSW', 'ascii') Same as my Windows 2000 machine. My RedHat9 (with Unicode) box returns ('__WXGTK__', 'wxGTK', 'ascii', 'gtk1') [...] > wx.SystemSettings_GetMetric(wx.SYS_VSCROLL_X) across all platforms as > they're deprecating the other forms - which seem to be aliases for > backwards compatibility. Just tested this, and it works on Linux using 2.4.2.4 and 2.5.1.5 and WinXP/2K running 2.5.1.5 From skjj at earthlink.net Thu Apr 15 17:25:07 2004 From: skjj at earthlink.net (John Smith) Date: Thu, 15 Apr 2004 14:25:07 -0700 (GMT-07:00) Subject: Arbitary VTABLE/Python Message-ID: <31031138.1082064308101.JavaMail.root@kermit.psp.pas.earthlink.net> Sorry if these question has been answered already, our Web searches/FAQs left us with more questions than answers. Few of us at a very large corporation are struggling to figure out if Python stable & scalable for our needs. (Sorry if this question has been answered already, our Web searches/FAQs left us with more questions than answers) We have very,very large C++ applications that talk to third part COM based server(s), both in-proc & out-of-proc - For large arbitary vtable based interfaces, what is the best approach from Python? We looked at FAQs, DOCs (including ActiveState), WEB searches, and saw references to SWIG, PythonCOM extensions BOOST.Python etc, and some problems people have reported using arbitary vtable interfaces from PythonCOM (BTW: where is are DOCs on one using/creating PythonCOM extensions? From our WEB searhces, it looks like 'makepy' may not work under all situations?) What combinations of tools/modules does one recommend for transitioning to Python based environment where large third party COM+ based infrastructure (C++) already exists? How stable/scalable/fast are these solutions? Our existing C++ code base runs both on Windows & Unix and we don't have to worry about supporting .NET right now. Thanks. From peter.maas at mplusr.de Tue Apr 13 05:35:00 2004 From: peter.maas at mplusr.de (Peter Maas) Date: Tue, 13 Apr 2004 11:35:00 +0200 Subject: Python OS In-Reply-To: <107j4eu6ffn2c68@corp.supernews.com> References: <107j4eu6ffn2c68@corp.supernews.com> Message-ID: A Evans wrote: > I have a question concerning the development of Python Based Operating > System. You see I have had sort of a dream to develop an Open Source > Operating System that would revolutionize the OS market and Since I started > using Python I have fallen in love with the language. The first step would probably be to define a Python OS. Surely no CPU speaks Python :) so this is a level where you have to use machine language. A viable definition could be an OS whose high level functions are provided by Python scripts. You could start with e.g. www.linuxfromscratch.org and write all scripts in Python. Twisted (www.twistedmatrix.com) would probably fit well to such a project because it provides a lot of network services. I have no idea how deep you can go but I think that a lot of C in between is necessary. Mit freundlichen Gruessen, Peter Maas -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Hubert-Wienen-Str. 24 Tel +49-241-93878-0 Fax +49-241-93878-20 eMail peter.maas at mplusr.de ------------------------------------------------------------------- From amakeler at bezeqint.net Wed Apr 21 18:37:30 2004 From: amakeler at bezeqint.net (Avraham Makeler) Date: Wed, 21 Apr 2004 15:37:30 -0700 Subject: from newbie: how specify # of times to invoke a regex; conv tuple to string Message-ID: <40866ae1$1@news.bezeqint.net> Hi all, Question 1: Summary of Question: How do you specify the number of times to run a reg ex search using a complex reg ex? The reg _expression I wrote goes like this: MyRE = re.compile('([k-z])(?:\'{6,9})(64|32|16|8|4|2|1)(\.)?') I ran it using this: tplstFound = MyRE.findall(InputStr) The problem is that this solution processes the whole input string. I only need the first matches notes. (I don't know if this is going to make any practical difference, since the name generation is a one-time thing, and anyway PCs are very fast these days.) I could not see a way of writing the reg ex so that it specifies only the first 25 matches. I tried putting the {m,n} construct (ie {0,25}) at the end of the re ex but it did not work. Alternatively, realizing that reg exs are probably not supposed to be used that way anyway, the responsibility for the number of executions should probably rather be put on some method of the MyRE object. However, I could not find a method that specifies the number of times that the reg ex search should be performed on the input file. Question 2: Summary of Question: How do you convert a tuple to a string? When I get the list of notes returned from the MyRE.findall() function, it is returned as a list of tuples, where each musical note is represented by one tuple. The tuple contains a set of strings where each string is the result of the reg ex match per group. For example: the raw input is matched and returned as the following tuple: ('e', '', '8', '.') I could not find a function that converts a tuple to a string. Please tell me where it is and in which module it is. Yes, I can loop through the tuples, and then loop through the string components of the tuple to build the result string, but isn't there a single function that does it? Thanks. Avraham Makeler. From claird at lairds.com Sun Apr 4 17:38:39 2004 From: claird at lairds.com (Cameron Laird) Date: Sun, 04 Apr 2004 21:38:39 -0000 Subject: What's missing from python? References: <405ee0d0$0$63627$5a6aecb4@news.aaisp.net.uk> <405ff7f4$0$63620$5a6aecb4@news.aaisp.net.uk> <899f842.0403230845.70e26735@posting.google.com> Message-ID: <107102vh15c8380@corp.supernews.com> In article <899f842.0403230845.70e26735 at posting.google.com>, Anthony_Barker wrote: >> > Encryption - AES and 3DES. Possibly RSA and Certificate processing. >> > DNS - Something better than gethostbyaddr for looking up other record >> > types. >> > Database - Something suitable for small projects / prototypes like >> > pysqlite or something in pure python even. >> > SSL/TLS - Some useful support... > >I agree and would add the ldap module. > >My feeling is that once a module is included in the standard library >the level of documentation and testing improves significantly. I've >always prefered the python way of including libraries over perl. > >If the distro is too large you could always modify the installer to >allow users to choose which modules to include(like ms office does >with apps). Heh-heh: "you could always ..." Installers can be bigger investments than whole collections of modules. I am fond of LDAP, by the way. -- Cameron Laird Business: http://www.Phaseit.net From No.Spam.mc at No.Spam.mclaveau.No.Spam.com Fri Apr 9 02:17:40 2004 From: No.Spam.mc at No.Spam.mclaveau.No.Spam.com (Michel Claveau/Hamster) Date: Fri, 9 Apr 2004 08:17:40 +0200 Subject: Function args References: Message-ID: Bonjour ! En Python, les variables sont des sortes de pointeurs sur des objets. Tout passage de variable comme param?tres se fait forc?ment par r?f?rence (en fait, on passe la r?f?rence ? l'objet). De plus l'affectation d'une variable cr?e un autre objet, car la plupart des objets ne sont pas modifiables. Seuls le sont les listes et les dictionnaires sont modifiables. Une cha?ne de caract?res n'est pas modifiable non plus. Cependant, il existe des modules contenant d'autres types ayant des comportement diff?rents. Il est ?galement possible de d?finir ses propres classes, dont on (re)-d?finira le comportement. PS : il existe aussi un newsgroup fr.comp.lang.python @-salutations -- Michel Claveau m?l : http://cerbermail.com/?6J1TthIa8B site : http://mclaveau.com From steve at ferg.org Tue Apr 20 13:17:59 2004 From: steve at ferg.org (Stephen Ferg) Date: 20 Apr 2004 10:17:59 -0700 Subject: Threats to the: Daily Python URL! References: <2ae25c6b.0404182250.4c5bc870@posting.google.com> Message-ID: > 'Daily Python' is the first > thing I read each morning. Me too! From jacek.generowicz at cern.ch Mon Apr 5 04:03:01 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 05 Apr 2004 10:03:01 +0200 Subject: [maybe OT] Making posters References: <95aa1afa.0404030143.58c32975@posting.google.com> Message-ID: michele.simionato at poste.it (Michele Simionato) writes: > I am looking for a tool taking a postscript file and enlarging it to > make a poster. It's called "Postscript". You could start by looking here: http://www.cs.indiana.edu/docproject/programming/postscript/operators.html#scale From huggiepython at graffiti.idv.tw Sun Apr 11 12:03:59 2004 From: huggiepython at graffiti.idv.tw (Timothy Wu) Date: Mon, 12 Apr 2004 00:03:59 +0800 Subject: GUI Frameworks in Python? In-Reply-To: References: <930ba99a.0404030246.786455f5@posting.google.com> <8ef9bea6.0404041009.26ae2683@posting.google.com> Message-ID: <40796C6F.2030104@graffiti.idv.tw> Greg Ewing wrote: > The basic idea is fairly similar in both, but event handlers > ("signal handlers" in Gtk terminology) seem more straightforward > to set up in PyGtk. In wxPython, for example, you have to get the > ID number of the widget and pass that to an event-binding function; > in PyGtk, you just pass the widget itself. I don't know wxPython really well and know nothing on other toolkit for any language. But doesn't calling wxWindow::GetId() on a widget quite similar to passing in the widget itself? Timothy From f29 at gazeta.pl Thu Apr 1 07:24:59 2004 From: f29 at gazeta.pl (f29) Date: 1 Apr 2004 04:24:59 -0800 Subject: Fetching websites with Python References: <_6Fac.9377$He5.187843@bgtnsc04-news.ops.worldnet.att.net> <30260531.0403311608.6cda48c5@posting.google.com> Message-ID: > > Markus, > > I think there's a timeout in urllib; not sure. > > No there isn't, bit of a shame that. There is in httplib. Sure there is, use urllib or urllib2 as usual, but also import socket module and call "socket.setdefaulttimeout(secs)" before requesting any pages with urlopen. f29 From opengeometry at yahoo.ca Mon Apr 12 18:05:05 2004 From: opengeometry at yahoo.ca (William Park) Date: 12 Apr 2004 22:05:05 GMT Subject: String + number split References: <2SAec.70005$Id.6002@news-binary.blueyonder.co.uk> Message-ID: Stevie_mac wrote: > Heres my solution... > > import string > def makefont(sFontName): > num = [] > nam = [] > acnt = 0 > #reverse it > l = list(sFontName); l.reverse(); ''.join(l) > sFontName = string.join(l,'') > #now loop it while isdigit(), store number, then store alphas > for c in sFontName: > if c.isdigit() and acnt == 0: > num.append(c) > elif c.isalpha() or acnt > 1: > acnt += 1 > nam.append(c) > nam.reverse() > num.reverse() > return (string.join( nam, '' ), int(string.join( num, '' ))) > > Now you see why i was asking for a more elegant solution! > > PS, the number on the end may vary & the _ could be any non alpha char! > > font12 becomes ('font',12) > arial_14 becomes ('arial',14) > arial__8 becomes ('arial',8) > times 6 becomes ('times',6) Assuming you only have 2 fields to worry about, play around with 1. re.split('[^a-z0-9]+', '...') 2. re.findall('[a-z]+|[0-9]+', '...') Essentially, you want to pickout '[a-z]+' first and then '[0-9]+', ie. ([a-z]+)[^0-9]+([0-9]+) -- William Park, Open Geometry Consulting, Linux solution/training/migration, Thin-client From a-steinhoff at web.de Fri Apr 2 14:54:34 2004 From: a-steinhoff at web.de (Armin Steinhoff) Date: Fri, 02 Apr 2004 21:54:34 +0200 Subject: Just magic ... In-Reply-To: References: Message-ID: root wrote: > Jeff Epler wrote: > >> I don't know, and since the code you posted doesn't run I can't find >> out. > > > #it's only a subset of the code ... > > class SlaveParSet(QDialog): > def __init__(self,parent = None, name=None, modal = 0, fl = 0, > Conf='PROFIBUS', saddr= 0): > > if name == None: > self.setName('SlaveParSet') > > self.config_name=conf > self.slave_addr = saddr > > self.gsd_connect = sqlite.connect("gsd_db") > self.gsd_curs = self.gsd_connect.cursor() > > # open project data base > self.prj_connect = sqlite.connect("proj_db") > self.prj_curs = self.prj_connect.cursor() > > self.ID = '' > self.IMpos = 0 > > > # insert selected module into installed modules > def ModuleSelectionval(self, nr): > module = str(self.ModuleSelection.text(nr)) > > #rebuild pos/module relationship > Sel = str("""select mod_pos, mod_name, proj, saddr, > mod_config_data, mod_prm_data > from INSTMODULE where proj= %s and saddr = %s""") > Key = (self.config_name, self.slave_addr) > self.prj_curs.execute(Sel, Key) > ins_list = self.prj_curs.fetchall() > > #ins_list is a list and contains now one tuple > > if len(ins_list): > self.IMpos +=1 > InsPos = self.IMpos > > Ins = str("""insert into INSTMODULE(mod_pos, mod_name, proj, > saddr, mod_config_data, mod_prm_data) > values (%s, %s, %s, %s, %s, %s)""") > > self.IMpos =0 > for set in ins_list: > setdata = (self.IMpos,) + set[1:] > > # set should reference a tuple but it refers to class instance .. WHY?? However ... my work around looks like: for set in ins_list: lset = () for i,val in enumerate(set): lset = lset+ (val,) self.setdata = (self.IMpos,) + lset[1:] self.prj_curs.execute(Ins, self.setdata) self.InstModules.insertItem(lset[1], self.IMpos) Is there a better solution ?? Armin > > self.prj_curs.execute(Ins, setdata) > self.InstModules.insertItem(set[1], self.IMpos) > self.IMpos +=1 > if InsPos == self.IMpos: > self.InstModules.insertItem(new_item[1], self.IMpos) > self.prj_curs.execute(self.Ins, new_item) > self.IMpos +=1 > if self.IMpos > 0: > self.IMpos -= 1 > > self.InstModules.setCurrentItem(self.IMpos) > self.prj_connect.commit() > else: > self.IMpos = 0 > self.InstModules.clear() > self.InstModules.insertItem(module, self.IMpos) > self.InstModules.setCurrentItem(self.IMpos) > > > >> >> >>>>> self.IMpos =0 >> >> >> Traceback (most recent call last): >> File "", line 1, in ? >> NameError: name 'self' is not defined >> >> Jeff >> From mark at prothon.org Wed Apr 21 14:14:00 2004 From: mark at prothon.org (Mark Hahn) Date: Wed, 21 Apr 2004 11:14:00 -0700 Subject: Dollar sign ($) on foriegn keyboards? (prothon) References: Message-ID: "Peter Otten" <__peter__ at web.de> wrote in message news:c65fkf$1q4$05$2 at news.t-online.com... > You seem to be both determined and open to critique - a good combination > IMHO. Well, thank you very much. Why don't you come over and help? (Always pitching the cause... :) From jjl at pobox.com Thu Apr 29 17:06:14 2004 From: jjl at pobox.com (John J. Lee) Date: 29 Apr 2004 22:06:14 +0100 Subject: urllib2 timeout?? References: Message-ID: <877jvy5wah.fsf@pobox.com> "Doug Gray" writes: [...] > request = > urllib2.Request("http://fantasygames.sportingnews.com/crs/home_check_reg.htm > l",data='username=penngray1&password=testpwd') > > response = ClientCookie.urlopen(request) > > #return response.info() > > request2 > =urllib2.Request("http://fantasygames.sportingnews.com/baseball/fullseason/u > ltimate/game/frozen_roster.html?user_id=6208") > > resp2 = ClientCookie.urlopen(request2) > > return resp2.read() Looks fine. No need to have an explicit Request object every time, though: just pass the URL to urlopen. > The ClientCookie is a 3rd party software that handles the Set-cookie stuff > on the client for me. This allows me to login into a site then access other > webpages from that site that need cookies set. The problem is that 50% of > the time it works and 50% of the time it fails. I assume this problem is a > time out problem As they used to say in Parliament: I refer the Honourable Gentleman to the answer I gave some moments ago (in a thread with subject "urllib2 request blocks"). I'm not sure it's a timeout problem, though. > Is there a time out problem here, why is the connection so slow in the first > place. Is it my unix server? Looks like some relatively low-level problem (some socket error that httplib's not catching). Not sure precisely what, though. [...] > Traceback (most recent call last): [...] > File "/usr/lib/python2.3/site-packages/ClientCookie/_urllib2_support.py", > line 612, in do_open > raise URLError(err) > > URLError: I'm not sure why you're not getting a more informative error message here. URLError here is wrapping a socket.error. Try catching it and printing the socket error directly: try: response = urllib2.OpenerDirector.open(self, req, data) except urllib2.URLError, e: print "e.reason", e.reason John From grzegorz at ee.ualberta.ca Sat Apr 17 12:50:56 2004 From: grzegorz at ee.ualberta.ca (Grzegorz Dostatni) Date: Sat, 17 Apr 2004 12:50:56 -0400 Subject: Static Modules... In-Reply-To: References: Message-ID: > "import this" -> "Explicit is better than implicit." This is exactly my point. My way will only work when you reference the name explicitly, as in: sys.setrecursionlimit(500) You're referencing the sys module explicitly. Other than that this "problem" exactly parallels the discussion between static and dynamic typing. And we know which way python chooses to go. > you dont easily see what exetrnal modules a program uses. that makes it > more difficult to debug, and it makes neat things like py2exe/installer > impossible. Alright. I haven't even though of py2exe/installer problem. Still a solution to that is not outside the realm of possibility. The easiest hack would be for the autoload to save the "imports" file in the same directory or display a warning (which is trivially done with the warning module). > a slight missconception is also there, as variables dont exist out of > nothing, they start apearing when you assign something to them. (appart > from that i dont like to say "variable" in python, more like binding names > to objects.) Here I would argue that the variables did not get created out of nothing. It's equivalent to this code: --- BEGIN HERE --- import Tkinter, sys Tkinter.Button(text="Quit", command=sys.exit).pack() --- END HERE --- Which is representative of another python philosophy. Don't specify things you don't need. If you can resonably figure out (without ambiguity) what the user wants do to - just do it. Don't pester him/her with unnecessary questions. > so something similar to using "variables" would be: > > sys = __import__("sys") > > which is already possible without any hack ;-) > > however, it could be a nice little hack for interactive sessions when > playing around in the interpreter. but i'd like to see a message when it > imports something, so that later when copy&pasting something to a file, i > dont forget the imports. That's a good idea. Greg From dave at pythonapocrypha.com Mon Apr 5 11:46:11 2004 From: dave at pythonapocrypha.com (Dave Brueck) Date: Mon, 5 Apr 2004 09:46:11 -0600 Subject: slightly OT: BUT NEEDs to be said References: <4078daf265c69e9353e8af72542da703@dizum.com> Message-ID: <01f901c41b25$1f0dbb30$6700a8c0@YODA> Nomen wrote: > I think it would be great for Python.org/people behind Python to adopt this > as an official mascot and DROP the god awful references to Monty Pythons's > Flying Circus. It is the later which is causing a slow take up and reluctance > of many individuals using Python. [snip] > Let me put it this way Python as a languge and product is *damaged* by the > references littered everywhere to MPFC. Well, I'll probably get in big trouble for revealing this, but the references to Monty Python are the result of a very conscious decision on the part of Python's authors, and they make up but a small part of an elaborate set of user filters that ensure that only a certain subset of programmers will ever use the language. For example, the real reason flame wars on c.l.py are quite tame by Usenet standards isn't because programming in Python makes you a happier, and in turn a nicer person, but it's because the group / mailing list regulars are more or less ALL THE SAME TYPE OF PEOPLE - they are all people who were not removed by the user filters, and therefore make up a more or less homogeneous bunch. To hide this fact occasionally someone will get a private email instructing them to bring up American politics or some other topic sure to incite controversy. Sure, they obey and bring it up in a thread, but it dies off so quickly because it's hard to put one's heart into it. I remember that one time the user filters were suspected by some outsiders, and Guido privately threatened to introduce mandatory curly braces around code blocks if we as a group didn't convince people "on the outside" that the filters didn't exist - hence the big conditional operator debate of '03. We actually got assigned sides in that debate - didn't even get to pick them ourselves. Anyway, the Monty Python references filter out people that are too uptight humor-wise, but there are many others. For example, if you ask about significant whitespace you'll get a hand-waving answer about some mysterious usability study in the ABC language, but nobody's actually ever seen it. In reality, it's just the filter that gets rid of people who fall apart upon learning that tedious work they diligently performed in the past was detrimental to their health (this filter does not work 100% of the time, thus the more reliable no-variable-type-declarations filter). The whole "Guido is Dutch" thing is another one - this time used to eliminate those who fear the unknown. He was born and raised in Quebec, and the accent is actually French, but so few of us Americans know the difference that it never gets him in trouble. There are more filters in place, all of them organized and perpetuated by the Python Secret Underground - a dark, time-machine wielding organization about which little is known. Occasionally some details of its work slip through to the public (http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&oe=UTF-8&selm=9jah18%24fqu% 241%40newshost.accu.uu.nl), but often I can't tell if such snafus are honest mistakes, bait to throw us off-track, or encrypted recruitment messages. Somebody's at my door - better send this off quick. Before I do though, I do want to shed light on the all-time greatest user filter put in place by the PSU - the autocoding project by Ti.*%^ NO CARRIER From vardhman at students.iiit.net Mon Apr 5 08:40:29 2004 From: vardhman at students.iiit.net (Vardhman Jain) Date: Mon, 05 Apr 2004 18:10:29 +0530 Subject: query regarding OOP functionality in python Message-ID: <407153BD.9080203@students.iiit.net> Hi, I tried searching a bit about this on the net, but couldn't get much help, so I am posting it here. Could someone tell me, what kind of polymorphisms does python allows? Does it allow multiple functions with same name and different arguments? Does it allow multiple functions with same name but different return types. I have tried this with constructors and failed, So I suppose I might need to compile the code or something like that to gain this feature if it exists. I know it allows default values to function arguments but that is not sufficient for my purpose. From aahz at pythoncraft.com Fri Apr 9 13:30:56 2004 From: aahz at pythoncraft.com (Aahz) Date: 9 Apr 2004 13:30:56 -0400 Subject: Zope + Python thread safety References: Message-ID: In article , wrote: > >In Delphi, or C, with threaded application I must acquire/release a >lock, when I check/set/read any variable (except integer), like this >(pseudo): > >lock=Lock >func ReadVar():string; > lock.Enter; > try > Result:=GlobalVar; > finally > lock.Leave; >end; > >proc WriteVar(val:string); > lock.Enter; > try > GlobalVar:=val; > finally > lock.Leave; >end; Python is wonderful: readable and usable pseudocode is almost exactly the same as real Python code: import threading lock = threading.RLock() def ReadVar(): lock.acquire() Result = GlobalVar lock.release() return Result Note that I'm doing this just to show you how similar it is -- this is *NOT* how I'd recommend doing it (e.g. poor practice to use a global variable like that). -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Why is this newsgroup different from all other newsgroups? From __peter__ at web.de Thu Apr 1 06:41:01 2004 From: __peter__ at web.de (Peter Otten) Date: Thu, 01 Apr 2004 13:41:01 +0200 Subject: test for nan References: Message-ID: Peter Maas wrote: > def isNaN(x): > return (x == 0) and (x == 1) This works here. Do you have an idea what the rationale behind this behaviour (i. e. any number == nan) is? Peter From fumanchu at amor.org Thu Apr 1 12:41:03 2004 From: fumanchu at amor.org (Robert Brewer) Date: Thu, 1 Apr 2004 09:41:03 -0800 Subject: splitting one dictionary into two Message-ID: [jsaul] > > I have to split a dict into two dicts. Depending on their values, > > the items shall remain in the original dict or be moved to another > > one and at the same time be removed from the original dict. > > > > dict1 = { "a":1, "b":3, "c":5, "d":4, "e":2 } > > dict2 = {} > > klist = [] > > > > for key in dict1: > > if dict1[key] > 3: # some criterion > > dict2[key] = dict1[key] > > klist.append(key) > > > > for key in klist: > > del dict1[key] > > > > print dict1 > > print dict2 > > > > That means that I store the keys of the items to be removed from > > the original dict in a list (klist) and subsequently remove the > > items using these keys. > > > > Is there an "even more pythonic" way? ---- cleave.py ---- def cleave(mapping, truthfunc): """Solution by Robert Brewer.""" dict1, dict2 = {}, {} while mapping: key, value = mapping.popitem() if truthfunc(key, value): dict2[key] = value else: dict1[key] = value return dict1, dict2 def extractbykey(mapping, truthfunc): """Solution by Peter Otten.""" dict2 = {} for key in mapping: if truthfunc(key, mapping[key]): dict2[key] = mapping[key] for key in dict2: del mapping[key] return mapping, dict2 def inplace(mapping, truthfunc): """Solution by wes weston.""" dict2 = {} for key, value in mapping.items(): if truthfunc(key, value): # some criterion dict2[key] = value del mapping[key] --- end cleave.py --- >>> t1 = timeit.Timer("cleave.cleave(m, lambda k, v: v % 2)", "import cleave\nm = {}\nfor i in xrange(100):\n m[i] = i") >>> t2 = timeit.Timer("cleave.extractbykey(m, lambda k, v: v % 2)", "import cleave\nm = {}\nfor i in xrange(100):\n m[i] = i") >>> t3 = timeit.Timer("cleave.inplace(m, lambda k, v: v % 2)", "import cleave\nm = {}\nfor i in xrange(100):\n m[i] = i") >>> t1.timeit(100000) 0.28098654996654204 >>> t2.timeit(100000) 5.6455228248282765 >>> t3.timeit(100000) 6.3886250906189161 ...this also holds for larger dicts: >>> t1 = timeit.Timer("cleave.cleave(m, lambda k, v: v % 2)", "import cleave\nm = {}\nfor i in xrange(1000000):\n m[i] = i") >>> t2 = timeit.Timer("cleave.extractbykey(m, lambda k, v: v % 2)", "import cleave\nm = {}\nfor i in xrange(1000000):\n m[i] = i") >>> t3 = timeit.Timer("cleave.inplace(m, lambda k, v: v % 2)", "import cleave\nm = {}\nfor i in xrange(1000000):\n m[i] = i") >>> t1.timeit(10) 2.1568995500824828 >>> t2.timeit(10) 7.0625512460382538 >>> t3.timeit(10) 34.820299227974488 [wes weston] > I'll have a hack with small code. Nice that you can > iterate while removing. ...yes, but you quickly pay a price by using .items(), which IIRC creates an intermediate dict to hold the k/v pairs. I'm not a master on the internal workings of dict, but I *believe* cleave() will scale better, since it neither introduces an intermediary structure, nor is a key/value pair ever present in more than one dict at the same time. Someone correct me if I'm wrong. Robert Brewer MIS Amor Ministries fumanchu at amor.org From parker at gol.com Thu Apr 15 04:28:36 2004 From: parker at gol.com (Ian Parker) Date: Thu, 15 Apr 2004 09:28:36 +0100 Subject: Method for providing a trail period on a program References: <407CF4F0.4020604@yahoo.com.au> Message-ID: In article , Roger Binns writes >> I am however, not prepared to >> let them run it forever for free. If it provides >> value to them, I believe they should purchase a >> license. This may put me in the minority on >> a Python site, but that's the way I feel. > >Keep a counter of how many times the program has been >run, and how long a time period it has been used for. >Start whining once they get past a reasonable trial >period. > >I would store the counters in the registry or somewhere >similar. The user could go in and edit them back down >to zero, but at that point they are trying to immorally >alter the software function to get around the period. >There is no real point trying to deal with people who >are absolutely determined to steal. They will always >succeed. People who have to make minor changes >to circumvent stuff know they are doing wrong. > >You can also add in a weekly check for updates (with >the users permission). That will remind people that >they get to pay for the software's continued improvement >(unless 1.0 happens to be perfect and user requirements >never change :-) > >Roger > > I second this. People may accept a copy of software from an associate, or be pleasantly surprised that a visiting engineer has installed some software on one of their computers. They may gloss over the fact that it is not licensed. However, if the only way they can keep the software working is to reset the date on the PC or to clear some registry entries, they tend to recognise that this is at least immoral and perhaps criminal abuse. So give the potential user fully functioning trial software but include a timed expiry. If it is useful to them, they may well buy it. Regards -- Ian Parker From krehbiel3 at comcast.net Sun Apr 11 07:16:47 2004 From: krehbiel3 at comcast.net (Richard Krehbiel) Date: Sun, 11 Apr 2004 07:16:47 -0400 Subject: Python is the best and most popular general purpose scripting language; the universal scripting language In-Reply-To: References: Message-ID: Roy Smith wrote: > rstephens at vectron.com (Ron Stephens) wrote: > >>Python is the best and most popular general purpose scripting >>language. > > > Which raises the question, exactly what makes something a "scripting" > langauge? When I tell people I do Python, they often say something > like, "that's a scripting language, right?". My usual response is > something along the lines of "Well, I suppose that depends on who you > ask" and I'm not sure what to say after that. > > So, what makes something a "scripting language" as opposed to a > "programming language"? There isn't one big thing that makes the distinction, but there are "clues:" Scripting Languages are "interpreted", not compiled to machine code. (Having a JIT engine like Psyco doesn't change my opinion on this; the code deployed is the source, or an intermediate form like .pyc.) Scripting languages do not have variable type declaration statements. Variables in scripting languages are dynamically-typed, and hold whatever type you assign to them. Scripting languages put a lot of emphasis on string manipulation, and usually have regular-expression support built in. They usually have a "big raw string literal" syntax, by which a string literal spanning multiple lines and containing most of the usual escape characters can be expressed simply. From jcarlson at uci.edu Fri Apr 2 15:44:44 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Fri, 02 Apr 2004 12:44:44 -0800 Subject: emergent/swarm/evolutionary systems etc In-Reply-To: References: Message-ID: > fh = open(file, "r+") ## Do you need "b" (binary) for a text file? Of course not, but keeping that binary flag allows you to get all the information from a file when you are on windows. Depending on the contents, this is not always the case. Inserting the binary flag in *nix doesn't hurt anything. - Josiah From peter at engcorp.com Fri Apr 16 15:22:51 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 16 Apr 2004 15:22:51 -0400 Subject: Error copying a file In-Reply-To: References: Message-ID: Stephen Boulet wrote: > Krzysztof Stachlewski wrote: >> Stephen Boulet wrote: >>> >>> print myfile >>> E:\Fritz Reiner\Rimsky-Korsakov--Scheherazade.Debussy--La Mer\01 >>> Symphonic Suite after "A Thousand and One Nights" - The Sea and >>> Sinbad's Ship.ogg >> >> It seems you are on Windows box. >> What filesystem do you use? >> I have just tried to create such a file, but the filesystem (NTFS) >> refuses to use " as part of the name. > > I'm on win2000. The file is on a CD I burned, and I wanted to copy it to > a file name that doesn't have any quotation marks in it. The problem is > that I can't reference the file to begin with. The command: > > shutil.copy2(myfile,r'D:\foo.ogg') Krzysztof's idea was excellent, because the quotation marks *are* the source of the problem. I don't know why, and maybe it should be considered a bug on Windows (note I don't say *in* Windows or *in* Python, because it could be either), but I can get the same behaviour by creating a file manually on Linux and then trying to access it through a file share from Windows. In the following, drive G: is my Samba-shared drive: G:\>python >>> import os >>> os.path.isfile('This is a "test" file') True >>> os.path.isfile('This is a "test" filex') # just testing False >>> import shutil >>> shutil.copy('This is a "test" file', r'c:\test.txt') Traceback (most recent call last): File "", line 1, in ? File "c:\a\python23\lib\shutil.py", line 71, in copy copyfile(src, dst) File "c:\a\python23\lib\shutil.py", line 37, in copyfile fsrc = open(src, 'rb') IOError: [Errno 2] No such file or directory: 'This is a "test" file' Perhaps your only option for now, since it seems shutil.copy uses the underlying OS copy and that barfs on Windows, is to open the file and copy it the hard way: >>> data = file('This is a "test" file').read() Traceback (most recent call last): File "", line 1, in ? IOError: [Errno 2] No such file or directory: 'This is a "test" file' Ouch! That doesn't work either. ;-) Okay, any reason not to call this a bug in the Windows version of Python, when os.path.isfile can handle the name but Python can't open or copy the file? Note that os.listdir() on my machine shows the 8.3 format name even though apparently on Stephen's CD it does not: >>> os.listdir('.') ['peter', 'im', 'THISI~LT', 'quicken.old'] (Stephen, I think therein lies your solution for now though, which is to find the 8.3 format name with, say, "DIR /x" or maybe win32api.GetShortPathName (if that even works) and copy it that way.) -Peter From ChrisSorisio at PeakTechnical.com Fri Apr 23 14:40:36 2004 From: ChrisSorisio at PeakTechnical.com (Sorisio, Chris) Date: Fri, 23 Apr 2004 14:40:36 -0400 Subject: mx.DateTime.Error: cannot convert value to a time value Message-ID: Ladies and gentlemen, I've imported some data from a MySQL database into a Python dictionary. I'm attempting to tidy up the date fields, but I'm receiving a 'mx.DateTime.Error: cannot convert value to a time value' error. It's related to glibc returning an error to a pre-1970 date, I think. My question: /how/ do I go through the Python direction I've created to remove the pre-1970 date objects? Ideally, I would be able to iterate through the dict and remove any DateTime objects that cause int() to fail. Unfortunately, the DateTime error causes my script to abort entirely. Ex: >>> report["COMPANY X"][1][2] -------------- next part -------------- An HTML attachment was scrubbed... URL: From skip at pobox.com Tue Apr 27 12:44:26 2004 From: skip at pobox.com (Skip Montanaro) Date: Tue, 27 Apr 2004 11:44:26 -0500 Subject: Is Perl *that* good? (was: How's ruby compare to it older bro In-Reply-To: References: <108qcobc4m8g972@corp.supernews.com> Message-ID: <16526.36330.478942.860629@montanaro.dyndns.org> Greg> I suspect that, 20 years from now, there will still be a language Greg> called Python, and it will still be quietly and unobtrusively Greg> kicking all its competitors' backsides. Greg> Whether it will bear any resemblance to the Python of today is Greg> another matter... Perhaps look back ten years to see what's happened since then. Does Python more-or-less look the same as it did in 1994 (or even earlier)? I suspect the answer is "yes". There has been some new syntax (*args/**kwds, listcomps, complex numbers, raw strings, packages, assert statement, loss of access statement) and a whole lot of new library functionality, but the core language is pretty much the same. Skip From gordonisnz at yahoo.co.nz Sat Apr 10 12:04:30 2004 From: gordonisnz at yahoo.co.nz (gordonisnz) Date: Sat, 10 Apr 2004 16:04:30 -0000 Subject: New user - Now what ? Message-ID: Hi there Im a new user to python (although not new to CGI (Perl) / PHP ) Ive installed Python on my home server (testing)... Now what ? Any tutorials I can use to utilise Python on my web-pages ? G From matt at themattfella.zzzz.com Sun Apr 11 15:16:13 2004 From: matt at themattfella.zzzz.com (Matt) Date: Sun, 11 Apr 2004 19:16:13 GMT Subject: Python OS In-Reply-To: <107j4eu6ffn2c68@corp.supernews.com> References: <107j4eu6ffn2c68@corp.supernews.com> Message-ID: <1Qgec.287$cW3.171@news02.roc.ny> A Evans wrote: > I have a question concerning the development of Python Based Operating > System. You see I have had sort of a dream to develop an Open Source > Operating System that would revolutionize the OS market I can't say that it is impossible. I can say that you won't be able to do it alone. Get started. You will learn a lot of useful stuff before you are disillusioned. From vineet at eswap.com Thu Apr 8 19:52:36 2004 From: vineet at eswap.com (Vineet Jain) Date: Thu, 8 Apr 2004 19:52:36 -0400 Subject: Problem with using singleton receip in python Message-ID: I started off doing the following: Class someClass(Singleton): This worked fine but was not elegant. I'm using a large number of Singleton classes. And Having to create a new object and discard it millions of times added up. My functions get called many many times. So I decided to use a GlobalMadules class which has all my global classes and resources. I initialize this at the begining of my program. The problem is that in the main program I have to do: from GlobalModules import initGlobalModule from GlobalModules.someGlobalClass import someGlobalClass def someFunction: initGlobalModule() someGlobalClass.conn(qry) does not work since someGlobalClass has not been initialized, so I have to do the following: def someFunction: initGlobalModule() from GlobalModules.someGlobalClass import someGlobalClass someGlobalClass.conn(qry) Somehow I like all my import at the top of the file and this does not seem right. Is there some other way to do this? Thanks, From __peter__ at web.de Tue Apr 20 08:01:52 2004 From: __peter__ at web.de (Peter Otten) Date: Tue, 20 Apr 2004 14:01:52 +0200 Subject: eval() and local variables References: Message-ID: Peter Luciak wrote: > Hi, > I need to do something like this: > > def my(): > a,b=1,2 > func = "lambda x: a*x+b" > map(eval(func),[1,2,3]) > > my() > > NameError: global name 'a' is not defined > > Why do I have to make a,b global for this to work? You don't: >>> def my(): ... a, b = 1, 2 ... return map(eval("lambda x: a*x+b", locals()), [1,2,3]) ... >>> my() [3, 4, 5] That makes my's local variables eval's globals. However, it's not clear to me why you need eval() at all: >>> def my(): ... a, b = 1, 2 ... func = lambda x: a*x+b ... return map(func, [1,2,3]) ... >>> my() [3, 4, 5] Peter From http Fri Apr 16 02:58:08 2004 From: http (Paul Rubin) Date: 15 Apr 2004 23:58:08 -0700 Subject: CamelCase versus wide_names (Prothon) References: <7xekqo36ia.fsf@ruckus.brouhaha.com> <107v08mopdgr9e9@corp.supernews.com> Message-ID: <7x1xmo76kf.fsf@ruckus.brouhaha.com> "Michael Geary" writes: > I edit my Python code with Slick_edit and Active_state Komodo. I use an IBM > Think_pad, largely because I like its Track_point pointing device. I enjoy > taking pictures with my Canon Power_shot camera, and I use a Pre_sonus > Blue_tube preamp when I play harmonica. Today I drove by Office_max, and I > saw ads for the Double_tree hotel and Lufthansa's Private_beds and Fly_net. > > Is that easier to read? Except for Private_beds, those are all basically single words that some marketroid put capital letters in the middle of. They'd be better off written as single words, which is how must people write them outside of advertising copy: Slickedit, Activestate, Thinkpad, Powershot. From iamlevis3 at hotmail.com Fri Apr 2 10:39:38 2004 From: iamlevis3 at hotmail.com (Chris) Date: 2 Apr 2004 07:39:38 -0800 Subject: Using ST_ATIME to watch for files being read Message-ID: <939f49f8.0404020739.70a7750a@posting.google.com> I need to monitor a bunch of files to see what is being opened, read, and closed, with no modifications being made. This is being done first on Windows machines, and later on Solaris. Looking through Python Programming on Win32, I saw the ST_ATIME (page 311) which looked promising, but when I did a little test, the results weren't good (read: sucked): # from the i.shell. st_atime date is inside >>><<< >>> os.stat("c:\\devtemp\\python\\1.txt") (33206, 0L, 2, 1, 0, 0, 3L, >>>1080919329<<<, 1080919329, 1080918583) # now i open c:\devtemp\python\1.txt, close it, and rerun >>> os.stat("c:\\devtemp\\python\\1.txt") (33206, 0L, 2, 1, 0, 0, 3L, >>>1080919329<<<, 1080919329, 1080918583) The Win32 books states that stat.ST_ATIME is "the time the file was last accessed or zero if the filesystem doesn't support this information". Obviously I'm missing something, or maybe atime isn't the best thing for me to use in this situation. Hoping someone can provide guidance. TIA -cjl From joewong at mango.cc Fri Apr 2 04:47:04 2004 From: joewong at mango.cc (Joe Wong) Date: Fri, 2 Apr 2004 17:47:04 +0800 Subject: IPC share queue Message-ID: <01c801c41897$75468260$7f00a8c0@scl01.siliconcreation.com> Hi, the buildin Queue() class is good to use among multiple threads in the program. Is there anything similar to this across process boundary? Regards, -- Wong -------------- next part -------------- An HTML attachment was scrubbed... URL: From franck.lepoutre at caramail.com Thu Apr 22 13:17:57 2004 From: franck.lepoutre at caramail.com (francois lepoutre) Date: Thu, 22 Apr 2004 19:17:57 +0200 Subject: Paris python user group? References: <408795ee$0$25893$79c14f64@nan-newsreader-02.noos.net> Message-ID: <4087fd81$0$635$79c14f64@nan-newsreader-02.noos.net> > Il y a longtemps que j'attendais qu'une personne se propose > de monter une assoc autour de python, d'autant que ?a existe > d?ja sur d'autres continents... > Tous mes encouragements Merci > Habitant la banlieue Nord je suis pas certain d'etre > disponible pour la 'taverne' mais en tout cas je trouve > l'id?e ? creuser :-))) R?publique est en effet un peu excentr?. On doit pouvoir trouver un ?quivalent sur les Halles ? deux pas du RER. A+ From beliavsky at aol.com Mon Apr 5 12:10:37 2004 From: beliavsky at aol.com (beliavsky at aol.com) Date: 5 Apr 2004 09:10:37 -0700 Subject: array of class attributes Message-ID: <3064b51d.0404050810.62617907@posting.google.com> Suppose I define a trivial class composed of x and y coordinates and create a Numeric array of instances of that class. class xy: def __init__(self,x=0.0,y=0.0): self.x = x self.y = y def __repr__(self): return ("%6.2f" % self.x) + (",%6.2f" % self.y) from xy import xy from Numeric import zeros,array,PyObject n = 3 aa = array([xy() for i in xrange(n)], PyObject) aa[1] = xy(5.0,25.0) print aa # not legal -- print aa.x The output of this program is [ 0.00, 0.00 5.00, 25.00 0.00, 0.00 ] . I would like to be able to get an array [0.00 5.00 0.00] corresponding to the x component of array aa using the syntax aa.x, but this is not correct Python. Array slices of components would also be nice. I could write a function to return such an array, but I doubt that this would be efficient in CPU time or memory. I wonder if this capability could be added to Numarray, the successor of Numeric. Otherwise, it may be better to write numerical codes using parallel arrays (one for x, one for y) instead of classes, and the benefits of classes are lost. Below is a program showing how this is done in Fortran 95. module xy_mod implicit none type, public :: xy real :: x = 0.0, y = 0.0 end type xy end module xy_mod program xxy use xy_mod, only: xy implicit none integer, parameter :: n = 3 type(xy) :: aa(n) character (len=*), parameter :: fmt_r="(100(2f6.2,4x))" aa(2) = xy(5.0,25.0) print fmt_r,aa print fmt_r,aa%x print fmt_r,aa(1:2)%x end program xxy The output is 0.00 0.00 5.00 25.00 0.00 0.00 0.00 5.00 0.00 0.00 5.00 From newsuser at itgoesclick.com Tue Apr 20 02:02:17 2004 From: newsuser at itgoesclick.com (News User) Date: Tue, 20 Apr 2004 06:02:17 GMT Subject: Good Python Tk overview Message-ID: I'm comming from the background of being primarily a data processing programmer (Python) and I'd like to do some GUI stuff for a comercial project but I have quite a bit of time, nothing too complex but it has to work on Windows98+ OSX and Solaris so I was thinking Tkinter. I was wondering if there were some sites with a good overview of the whole Python +Tk shpeal, I've got some code examples and "Programming Python 2nd Edition" but that's more of a learn by example, rather than an overview of concepts. Anyone have a good recommendation? From mwh at python.net Thu Apr 1 09:38:29 2004 From: mwh at python.net (Michael Hudson) Date: Thu, 1 Apr 2004 14:38:29 GMT Subject: From python-dev, space vs. tab controversy finally settled References: Message-ID: Josiah Carlson writes: > Great april fools joke, but no such conversation has gone on in > Python-Dev in the last 3 months. You just didn't get those mails. Cheers, mwh -- > It might get my attention if you'd spin around in your chair, > spoke in tongues, and puked jets of green goblin goo. I can arrange for this. ;-) -- Barry Warsaw & Fred Drake From andymac at bullseye.apana.org.au Tue Apr 27 19:47:57 2004 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Wed, 28 Apr 2004 09:47:57 +1000 (EST) Subject: What is good about Prothon? In-Reply-To: References: <108t2tlo06j8vb9@corp.supernews.com> Message-ID: <20040428094446.M64229@bullseye.apana.org.au> On Tue, 27 Apr 2004, Mark Hahn wrote: > I knew I couldn't please them all, but I thought I'd be able to please > one or two :) Big mistake! Set out only to please yourself! After all, this is your itch... -- 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 me at privacy.net Fri Apr 23 08:45:18 2004 From: me at privacy.net (Duncan Booth) Date: 23 Apr 2004 12:45:18 GMT Subject: [Q] C-api: string|int|... construction References: Message-ID: "Ames Andreas (MPA/DF)" wrote in news:mailman.955.1082720706.20120.python-list at python.org: > "Fredrik Lundh" writes: > >> (but note that unless you're talking about strings in the 100+ >> megabyte range, or run on relatively old hardware, chances are that >> you're wasting your time. modern computers can copy things really, >> really fast). > > I'm currently wrapping some low-level C-api (FWIW, it's the ODBC api) > and what I'm concerned about is that some api functions require a > buffer to output (i.e. copy) a string into. I present those buffers > to the python users as strings created by PyString_FromString and > friends. So that's two copies for each call. Why are you wrapping the ODBC api instead of using one of the existing wrappings? > > As this is a database access api looong strings are quite possible. > > To make things worse there are many microsoftisms in the api (which > isn't surprising as ODBC was specified by MS). One such microsoftism > is that the caller is responsible to prepare a buffer for string > output from api functions without being able to determine the required > length of that buffer ahead of the api call. My strategy of > mitigation is here to always specify a fixed length buffer which is > relatively large (say like 1024 bytes or something) in the Sorry, I thought you said large. 1024 bytes isn't large. > first call. Only if this buffer is too short (and the api function > has returned the required length) I dynamically allocate a second > buffer and call the api again. Together with the final > PyString_FromString these are three copies of a long string in the > worst case which is sort of ugly, as far as I am concerned. > Use PyString_FromStringAndSize(NULL, size) to create a new Python string with an empty buffer, then PyString_AsString(s) to get a pointer to the buffer. Pass that to your C api, then call _PyString_Resize to set the length correctly. > How is the lack of a PyString_FROM_STRING (i.e. construction of a > python string object from a C string or a char pointer plus size > without copy) motivated? > Python has to control the lifetime of the buffer. By copying into its own buffer it avoids issues over ownership. From jason at tishler.net Thu Apr 29 17:02:57 2004 From: jason at tishler.net (Jason Tishler) Date: Thu, 29 Apr 2004 17:02:57 -0400 Subject: Python Image Library (PIL) build error on Cygwin In-Reply-To: References: Message-ID: <20040429210257.GA1636@tishler.net> Steve, On Thu, Apr 29, 2004 at 04:31:54PM -0400, Steve Holden wrote: > Does anyone know the workaround for this error, encountered when > trying to build PIL 1.1.4 from source under cygwin (Python 2.3.3)? Rebasing your system should fix the problem. See the following: http://www.tishler.net/jason/software/rebase/rebase-2.3.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 jcarlson at uci.edu Mon Apr 5 18:33:47 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Mon, 05 Apr 2004 15:33:47 -0700 Subject: import question In-Reply-To: References: Message-ID: > So, how to avoid this? How can I refer back to a module higher in the "hierarchical" path. > Up is so easy.. just say import foo.foo2.foo3. But up, what is the correct way of doing that? > Something to put in __init__.py, like sys.path.apppend('..')? Looks ugly to me.... PEP 328, Relative imports should take care of your issue. In the meantime... #in main.py import lib #in foo1.py and foo2.py import sys lib = sys.modules['lib'] Now both of them will refer to the same 'lib' that main.py imported. - Josiah From eder at tttech.com Thu Apr 1 03:30:10 2004 From: eder at tttech.com (Christian Eder) Date: Thu, 01 Apr 2004 10:30:10 +0200 Subject: __nonzero__ of iterators Message-ID: Hi, I just discovered the following pitfall in Python 2.3. Consider the following code : >>> a = {} >>> bool (a.keys ()) False >>> bool (a.iterkeys ()) True So, an "empty" iterator evaluates to True in boolean context. At a first glance, this is not what one would expect. This causes several problems, e.g. if you operate on something expected to be sequence, and you guard your code with "if seq :" to avoid crashing into an empty sequence, you still crash if you get an empty iterator, even if the rest of your code is able to deal with an iterator as well as with any other sequence type. At a second glance, the behaviour is clear, since the iterator object does not know wheter it is able to provide the next element, before having done so. Anyway, although I don't know how the iterator protocol is implemented in Python 2.3, I suppose the __nonzero__ could be changed to check whether a next element can be provided without actually consuming it. I would like to read some comments on this topic as I'm sure that I'm not the first one wondering whether the current behaviour should be that way. thanks chris From rawbobb at hotmail.com Sun Apr 18 22:57:54 2004 From: rawbobb at hotmail.com (bobb) Date: Mon, 19 Apr 2004 02:57:54 GMT Subject: os.system help References: <78lgc.3445$AL1.7744@news1.mts.net> Message-ID: "Reid Nichol" wrote in message news:78lgc.3445$AL1.7744 at news1.mts.net... > Hello, > I have made a program that works wonderfully on OpenBSD but it uses > os.system to get ghostscript to convert ps to jpeg. But, I wish this > program to run on Windows as well. Is there any way I can snag where > the gs executable is on Windows? What it is named? And so forth. > I test my gs things through cygwin on my windows box. hth bobb From webmaven at lvcm.com Fri Apr 2 20:11:43 2004 From: webmaven at lvcm.com (Michael Bernstein) Date: 2 Apr 2004 17:11:43 -0800 Subject: Python conference slogan References: <30260531.0404010833.1b834032@posting.google.com> <406C4DDF.5000907@zope.com> Message-ID: Peter Maas wrote in message news:... > > [snip] As I understand this thread there is a need for a slogan > that is short, not too hard to understand and unforgettable > (probably a definition of the word slogan). Python insiders > don't need a slogan at all. Well, this is a bit more than just a slogan, I'm envisioning this on a t-shirt (where the last line is significantly bigger than the rest): Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Python is BETTER. (with thanks and/or apologies to Tim Peters) - Michael R. Bernstein From mogmios at mlug.missouri.edu Thu Apr 1 06:37:00 2004 From: mogmios at mlug.missouri.edu (Michael) Date: Thu, 01 Apr 2004 03:37:00 -0800 Subject: [OT] Top posting is a PITA In-Reply-To: References: <569c605ld1cj8fc1emolk08ete0s1prls1@4ax.com> <106di86neu1qh4d@news.supernews.com> <4069a001$0$4237$afc38c87@news.easynet.co.uk> <4069e9d9$0$8915$636a15ce@news.free.fr> <406a98ee$0$290$edfadb0f@dread12.news.tele.dk> <868yhhhv1u.fsf@igor.home.mkp.ca> Message-ID: <406BFEDC.3000106@mlug.missouri.edu> >Given the time this must leave you to read, understand, and >thoughtfully reply to any given article ... I'll let you draw your own >conclusions about what effect this might have on the quality of your >contributions. > > Actually I'm a major contributor to many lists. Obviously I just watch most. Or decide a thread interests me at random points in whichI decide to follow a list more closely for a few days. Also obvious, it's not always the threads that have actual value that interest me.. since I've participated in this one. I'm just amused to see this same argument repeated pointlessly year after year. >... yup, if you are really not interested in _understanding_ what is >going on, then top-posting is for you. > > I understand by having read the thread and remembered it. If I need a context hint I can peek below but that is usually only needed with complex interwoven threads. Which isn't the majority.. which is why I think top-posting is good for a majority of messages but inline bottom-posting is good other times. Use what is best for the given message. From __peter__ at web.de Fri Apr 23 04:51:29 2004 From: __peter__ at web.de (Peter Otten) Date: Fri, 23 Apr 2004 10:51:29 +0200 Subject: Generic constructors and duplication of internal Python logic References: <87ekqq41ya.fsf@pobox.com> <87oepnzlbp.fsf@pobox.com> <87k707elth.fsf@pobox.com> Message-ID: Peter Otten wrote: > But will I stop trying to come up with something better? no way. Here's my > next try, and I'm likely to present something completely different again > if you don't like it - not sure if that's a promise or a threat :-) A threat. def setLocals(d, selfName="self"): self = d.pop(selfName) for n, v in d.iteritems(): setattr(self, n, v) class Demo(object): def __init__(self, foo, bar, baz=2, bang=3): setLocals(locals()) Peter From jtdubs at eos.ncsu.edu Wed Apr 21 22:25:08 2004 From: jtdubs at eos.ncsu.edu (Justin Dubs) Date: 21 Apr 2004 19:25:08 -0700 Subject: How to get the ip addresses of a nic References: Message-ID: <2e262238.0404211825.2f6231b@posting.google.com> "Bo Jacobsen" wrote in message news:... > Is there a simple way to get all the ip addresses of a nic, beyound parsing > /etc/sysconfig/..... Depending on your needs: >>> socket.gethostbyname(socket.gethostname()) '192.168.0.18' Justin Dubs From Pieter.Claerhout at Creo.com Sun Apr 4 12:01:37 2004 From: Pieter.Claerhout at Creo.com (Pieter Claerhout) Date: Sun, 4 Apr 2004 18:01:37 +0200 Subject: PIL and windows ico files Message-ID: <490316A24CC5D411ACD700B0D078F7F0069659E2@cseexch01.cse.creoscitex.com> Hi all, I'm trying to use PIL to convert windows icon files to PNG. This mostly works, but it doesn't preserve the transparancy. Any tips or tricks on how to preserve the transparancy? Currently, my code looks as follows: from PIL import Image from PIL import IcoImagePlugin from PIL import GifImagePlugin Image._initialized = 1 im = Image.open( 'xplane.ico' ) im.save( 'xplane.gif' ) thanks in advance, pieter From mikalzetTogli at interfree.it Sat Apr 3 17:42:11 2004 From: mikalzetTogli at interfree.it (TaeKyon) Date: Sat, 03 Apr 2004 22:42:11 GMT Subject: recursive file editing References: Message-ID: Il Sat, 03 Apr 2004 22:35:30 +0200, Leif B. Kristensen ha scritto: > This is a Perl one-liner: > > perl -p -i -e 's/foo/bar/gi' `find ./` Didn't work; however I realized I could just repeatedly run variations of sed -i s/foo/bar/g * and then rename the files with a bash script called renna. I'm sure python could do it but I got stuck - for file in os.walk('mydir'): print file[2] gives me the names of all files but how do I open each with r+ mode ? for thing in os.walk('mydir'): file(thing,mode=r+) is invalid syntax -- Michele Alzetta From fredrik at pythonware.com Fri Apr 16 08:07:58 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 16 Apr 2004 14:07:58 +0200 Subject: md5.hexdigest() converting unicode string to ascii References: <77b925de.0404151450.5c1f720a@posting.google.com> Message-ID: Krzysztof Stachlewski wrote: > The md5() function is defined on character strings > not on unicode strings. An unicode string is a sequence > of integers. Such sequence may be converted to a character > string message.replace("character", "byte") (unicode characters are characters too, you know...) From cookedm+news at physics.mcmaster.ca Thu Apr 15 17:25:15 2004 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Thu, 15 Apr 2004 17:25:15 -0400 Subject: curses and unicode References: Message-ID: At some point, "A.M. Kuchling" wrote: > On Thu, 15 Apr 2004 08:46:55 +0200, > Gandalf wrote: >> But I do not know how to do this from Python. I only have the curses >> module and the addstr method. The addstr method does not support unicode. > > There's a separate set of interfaces for wide-character curses support, with > functions such as addwstr(). Unfortunately the Python curses module doesn't > support these functions, and they may or may not be available on your > platform. (For example, they don't seem to be available in the version of > ncurses in Debian unstable.) You want the libncursesw5 library (ncurses compiled with wide character support). I suppose there's two libraries as ncurses-with-wide-chars is API but not ABI compatible with ncurses-w/o-wide-chars. But, no Python interface with wide characters. -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From mikalzetTogli at interfree.it Wed Apr 7 18:45:15 2004 From: mikalzetTogli at interfree.it (TaeKyon) Date: Wed, 07 Apr 2004 22:45:15 GMT Subject: recursive file editing References: Message-ID: Il Wed, 07 Apr 2004 23:04:51 +0200, Peter Otten ha scritto: > # using your variable names > for folders, folder, filelist in os.walk(target_folder): > os.chdir(folders) > for line in fileinput.input(filelist, inplace=1): > print re.sub(original_pattern,result_pattern,line), I thought it might not work on files contained in subdirectories but it does. The comma solved the problem with newlines too. If we leave out the exception checking that's 5 lines of code: import os, sys, re, fileinput targetf, original, result = (sys.argv[1]), (sys.argv[2]), (sys.argv[3]) for folders, folder, filelist in os.walk(targetf): os.chdir(folders) for line in fileinput.input(filelist,inplace=1): print re.sub(original,result,line), Compact and elegant ! Tomorrow I'll go about adding the change filename stuff. -- Michele Alzetta From roy at panix.com Tue Apr 27 13:06:16 2004 From: roy at panix.com (Roy Smith) Date: Tue, 27 Apr 2004 13:06:16 -0400 Subject: Is Perl *that* good? References: <108q51j4dscn7dc@corp.supernews.com> <87fzaqmm8t.fsf@strauser.com> <38ec68a6.0404262308.50029919@posting.google.com> Message-ID: Skip Montanaro wrote: > In addition, as Jamie Zawinski suggests, regular expressions > are not always the best choice. Regular expressions are like duct tape. They may not be the best tool for everything, but they usually get the job done. From alf at calvin.fayauffre.org Fri Apr 16 11:23:01 2004 From: alf at calvin.fayauffre.org (Alexandre Fayolle) Date: Fri, 16 Apr 2004 15:23:01 +0000 (UTC) Subject: AOP use cases References: <84fc4588.0404140106.3fa0c55@posting.google.com> <0pydnSB4WYuieuLdRVn-hQ@powergate.ca> Message-ID: Le 16-04-2004, Peter Hansen a ?crit?: > Will Stuyvesant wrote: > >> What are good usage examples? > > I would be very interested to hear some real-world and real useful > use cases for AOP as well. > (The logging one actually annoys me: the only time I've ever > wanted such logging was when debugging very complicated problems, > and since switching to TDD I have never encountered anything > that even remotely made me consider writing such logging wrappers > again.) I agree that TDD helps a lot. However, the logging module can be useful when * debugging a legacy/3rd party application or library * trying to understand the data flow of a 3rd party library Another "common" use of logilab.aspect is the contract aspect which enables to specify pre and post conditions for methods as well as class invariants. Of course, you generally don't need contracts when using TDD, but when working with a distributed team on complex projects, it can be a great time saver when diagnosing weird crashes. Especially if some partners have not yet been test infected. :-) It is easy to disable contract checking once the project is said to be stable enough and goes into production, or to re-enable the checks on one offensive module or class if something weird happens. Of course, it is possible to do this without AOP, and the flexibility and introspection abilities of Python make it very easy to achieve, on an ad hoc basis. It's just that using an AOP framework can save some typing, as well as facilitate non invasive changes to existing code. -- Alexandre Fayolle LOGILAB, Paris (France) http://www.logilab.com http://www.logilab.fr http://www.logilab.org From hellprout at yahoo.com Thu Apr 1 09:07:48 2004 From: hellprout at yahoo.com (hellprout) Date: 1 Apr 2004 06:07:48 -0800 Subject: problem with wxtextctrl References: <5b8834c2.0403302358.2698f8f3@posting.google.com> Message-ID: <5b8834c2.0404010607.10c72ccb@posting.google.com> Thanks the option wxTE_RICH is the solution thanks a lot and let's go python sylvain Robin Dunn wrote in message news:... > hellprout wrote: > > hi , i have a problem with a wxtextctrl with multiline option. > > i want to write a file , line after line , in my wxtextctrl . > > But my file is too longer , and the wxtextctrl can't write the end of > > the file , i miss 100 lines of my file ... > > What can i do to have all data file ? > > > > If you are on Windows then add the wxTE_RICH style when constructing the > wxTextCtrl. This will switch to a native control that can handle more > than 64k of text. From bror.johansson at saabtech.se Thu Apr 29 02:57:25 2004 From: bror.johansson at saabtech.se (Bror Johansson) Date: Thu, 29 Apr 2004 08:57:25 +0200 Subject: Arachno Python IDE Message-ID: I can't remember having seen anything in this forum about Arachno Python IDE. (http://www.python-ide.com/arachno_python.php) Anyone tried it? Impressions? /BJ From tzot at sil-tec.gr Fri Apr 2 10:39:35 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Fri, 02 Apr 2004 18:39:35 +0300 Subject: OT: FTP sync program? References: Message-ID: <7v1r60dq2sdiieouuc53nikj0u10lgv9ej@4ax.com> On Mon, 29 Mar 2004 14:03:13 +0200, rumours say that Miki Tebeka might have written: >Hello All, > >I'm looking for a *free* program to synchronize files over ftp (like rsync). > >Any suggestions? Take a look at this script which I use for linux package downloads during the night: http://www.sil-tec.gr/~tzot/python/sync_ftp.py You want to edit the ftp_sites tuple (it works on a directory-per-directory basis, so you might want to make it recursive), and then you might need the TupleStruct.py, which you can take from http://www.sil-tec.gr/~tzot/python/ -- TZOTZIOY, I speak England very best, Ils sont fous ces Redmontains! --Harddix From michaelmossey at yahoo.com Mon Apr 5 18:45:40 2004 From: michaelmossey at yahoo.com (Michael Mossey) Date: 5 Apr 2004 15:45:40 -0700 Subject: Intermittant slow startup References: <9badaf0.0404051033.9fec2db@posting.google.com> <4071A86D.97CA6CAE@alcyone.com> Message-ID: <9badaf0.0404051445.5b26b945@posting.google.com> Erik Max Francis wrote in message news:<4071A86D.97CA6CAE at alcyone.com>... > Michael Mossey wrote: > > > Runnng python 2.2 on HP-UX, I get intermittant slow startup. > > Sometimes python starts up in a small fraction of a second, and > > sometimes takes 3-5 seconds. This applies to any script I run, or > > just typing 'python' at the prompt. > > > > I also observed something similar on Linux. > > > > Any ideas what would cause *intermittant* slow startup? > > Caching? Is it a long time between invocations that it takes a long > time to start up? It is quite intermittant without much of a pattern I can see. One thing that is definitely true is that if I start up python several times in a row one right after the other, some can be slow and some fast. I just observed it start fast twice, then start slow. I don't remember if it ever does the other way around but I think it does. -Mike From mcfletch at rogers.com Fri Apr 2 10:27:52 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Fri, 02 Apr 2004 10:27:52 -0500 Subject: Creating a matrix? In-Reply-To: References: Message-ID: <406D8678.2080307@rogers.com> N*N matrix of lists... [ [0]*N for i in range( N ) ] Seems clearer to me, anyway (and stores actual 0 values, not '0' in the result). Have fun, Mike Ivan Voras wrote: > Is there a nice(r) way of creating a list of uniform values? I'm > currently using: list('0'*N), which makes a string and then chops it > up into a list. I need it to create a NxN matrix: > > matrix = [list('0'*N) for i in range(N)] > > (elements need to be mutable afterwards, a shallow copy is bad) > > While this is short and concise, it also feels odd :) _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From sandeep182 at hotmail.com Fri Apr 30 13:42:29 2004 From: sandeep182 at hotmail.com (Sandeep Gupta) Date: 30 Apr 2004 10:42:29 -0700 Subject: Building python on Linux with no X Message-ID: I have tried using the source rpm and the tarball to build python on RH9. In both cases I get a build failure on tkinter because I don't have X installed. Since I only care about the core python and the devel rpms, is there any way to only have those two rpms built from the source rpm? Thanks Sandeep From peter at engcorp.com Fri Apr 2 10:42:40 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 02 Apr 2004 10:42:40 -0500 Subject: Creating a matrix? In-Reply-To: References: Message-ID: Peter Maas wrote: > Ivan Voras wrote: > >> Is there a nice(r) way of creating a list of uniform values? I'm >> currently using: list('0'*N), which makes a string and then chops it >> up into a list. I need it to create a NxN matrix: >> > > matrix = [list('0'*N) for i in range(N)] > > matrix = [['0']*N]*N Sorry, Peter, but that's a rookie mistake: >>> matrix = [['0'] * 4] * 4 >>> matrix [['0', '0', '0', '0'], ['0', '0', '0', '0'], ['0', '0', '0', '0'], ['0', '0', '0 ', '0']] >>> matrix[1][2] = '1' >>> matrix [['0', '0', '1', '0'], ['0', '0', '1', '0'], ['0', '0', '1', '0'], ['0', '0', '1 ', '0']] Notice that each of the inner lists contains four seperate references to the string '0', but the outer repetition simply copies the inner list four times, resulting in four references to the same inner list! Changing any one element affects the same entry in each of the other three lists... -Peter From http Tue Apr 20 17:48:45 2004 From: http (Paul Rubin) Date: 20 Apr 2004 14:48:45 -0700 Subject: Difficulty Finding Python Developers References: <65cbc3dd.0404140641.3501fde8@posting.google.com> Message-ID: <7xekqigw1u.fsf@ruckus.brouhaha.com> Paul Morrow writes: > Yes, that's our ad. I guess hr wasn't as careful as they should've > been when they authored it (there's also a mispelled word)... :-( > > You probably already realized this, but that should've been $45 to $55 > per hour. I don't remember if anyone's mentioned this in the thread yet, but you might also list the job on the Python jobs board: http://python.org/Jobs.html From aahz at pythoncraft.com Fri Apr 2 01:15:03 2004 From: aahz at pythoncraft.com (Aahz) Date: 2 Apr 2004 01:15:03 -0500 Subject: From python-dev, space vs. tab controversy finally settled References: Message-ID: In article , Carl Banks wrote: >Wolfram Kraus wrote: >> Carl Banks wrote: >>> >>> So, you should start using Unicode character 0009 to indent right >>> away. Python 2.4 will deprecate all indentation not using the new >>> indent character, and Python 3.0 will not support any other >>> indentation. >> >> Nah, this sucks! This will be the death of Python! I'm switching to >> Whitespace: http://compsoc.dur.ac.uk/whitespace/ > >You people are missing it. Look at what the new indent character is. >(It's always funnier when you have to explain it.) You didn't check Wolfram's URL, did you? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "usenet imitates usenet" --Darkhawk From kkto at csis.hku.hk Mon Apr 26 00:08:05 2004 From: kkto at csis.hku.hk (Isaac To) Date: Mon, 26 Apr 2004 12:08:05 +0800 Subject: Trouble Understanding O'Reilly Example References: <108p21f7asq1cc8@corp.supernews.com> Message-ID: <7iad0z4c0q.fsf@enark.csis.hku.hk> >>>>> "slyraymond" == slyraymond writes: slyraymond> On page 214 of _Learning Python_, the following function is slyraymond> described as one that will return the smallest item in a slyraymond> group of arguments: slyraymond> def min1(*args): res = args[0] for arg in args[1:]: if arg < slyraymond> args: res = arg return res Should be, if arg < res. Regards, Isaac. From jluc_yvr at yahoo.com Fri Apr 2 14:01:00 2004 From: jluc_yvr at yahoo.com (Jean-Luc) Date: 2 Apr 2004 11:01:00 -0800 Subject: Troubleshooting pickle errors Message-ID: <6eb6da99.0404021101.1f755f19@posting.google.com> Hi I am grafing pickling functionality on a big dictionary of object instances and I am having numerous problems. I think understand the notion of what can/can't be pickled and I know how to use __getstate__ / __setstate__ to weed out offending references. But I am finding it very hard to identify _which_ reference is causing exceptions like: File "C:\UserApps\Python23\Lib\copy_reg.py", line 69, in _reduce_ex raise TypeError, "can't pickle %s objects" % base.__name__ TypeError: can't pickle function objects PrettyPrinting the exception gets me: {'args': ("can't pickle function objects",)}. The exception includes no references to the guilty party! How do I know _which_ object caused the issue? Though my current objects (i.e. the stuff I am trying to pickle) are new, its instances hold references to a lot of instances of existing utility classes of mine that are database aware. I would not like to modify those utility classes any more than I _have_ to since I use them elsewhere. I have already stripped out database Connection references, as well as File references. Those were obvious. How do I identify the remaining issues? If I work with a smaller data set, I often miss problems entirely, so reducing the pickling scope is not an easy option to implement. The best I have managed so far is to open the pickle file and look near the end, where the exception presumably occurred. But I would expect there to be a more obvious way to troubleshoot this stuff. Cheers JLuc From sean_berry at cox.net Fri Apr 23 01:31:50 2004 From: sean_berry at cox.net (Sean Berry) Date: Thu, 22 Apr 2004 22:31:50 -0700 Subject: Python CGI: how to retrieve variables passed by URL Message-ID: If I go to my cgi python script with localhost/cgi-bin/script-name.cgi?variable=value How do I gather this value? Thanks in advance. From lbates at swamisoft.com Fri Apr 9 10:50:58 2004 From: lbates at swamisoft.com (Larry Bates) Date: Fri, 9 Apr 2004 09:50:58 -0500 Subject: program distribution References: <4075f5bb_1@news.iprimus.com.au> Message-ID: Nathan, You didn't mention your platform. So I'm going to give you instructions for Windows. You will need to additional programs. 1) py2exe - This will run your program through a process that gathers up all you imported modules and creates a .EXE file and supporting .pyd and .dll files. This can be distributed to computers that do NOT have Python installed. http://starship.python.net/crew/theller/py2exe/ 2) Some installer. I personally like Inno. You provide Inno with a list of files that should be installed (both program and data files) and it creates one big "setup.exe" file that can be distributed. http://www.jrsoftware.org/isinfo.php If your platform is Linux take a look at McMillan Installer. This page seems to be down at this time: http://www.mcmillan-inc.com/install1.html Regards, Larry Bates Syscon, Inc. "mr_vocab" wrote in message news:4075f5bb_1 at news.iprimus.com.au... > Hi im new to python but have made a few applications how can i save them > and get the to run sort of like an application > > thanks > > Nathan > > From rob02omni at vodafone.it Tue Apr 20 12:16:30 2004 From: rob02omni at vodafone.it (Roberto) Date: Tue, 20 Apr 2004 18:16:30 +0200 Subject: Getting output from embedded python program References: <2aa196bb.0404190554.74631058@posting.google.com> <4084B179.6020807@magma-da.com> Message-ID: With more try i can run "PyRun_SimpleFile" ! Anyway cant do the same with "PyRun_File" because it will crash my app : PyRun_File(fpIn,"temp.py",Py_file_input,evalModule ,evalDict); evalModule = PyImport_AddModule( (char*)"__main__" ); evalDict = PyModule_GetDict( evalModule ); evalVal = PyDict_GetItemString( evalDict, "result" ); This will crash the app :( Bye -- Roberto "Rick L. Ratzel" ha scritto nel messaggio news:4084B179.6020807 at magma-da.com... > Kim wrote: > > Hi everyone, > > I'm writing a embeded python program, and I want to evaluate some > > expression by calling function: > > > > PyRun_SimpleString("print 'hello'") > > > > I don't want to output it to stdout but putting it into string somehow > > sothat I can process it. > > > > Here is a way to get the result of a Python expression eval from C > (derived from example at > http://elmer.sourceforge.net/PyCon04/elmer_pycon04.html ) ...obviously, > if you evaluate a print statement, you will still get output on stdout > though: > > ... > PyObject* evalModule; > PyObject* evalDict; > PyObject* evalVal; > char* retString; > > PyRun_SimpleString( "result = 'foo' + 'bar'" ) > > evalModule = PyImport_AddModule( (char*)"__main__" ); > evalDict = PyModule_GetDict( evalModule ); > evalVal = PyDict_GetItemString( evalDict, "result" ); > > if( evalVal == NULL ) { > PyErr_Print(); > exit( 1 ); > > } else { > /* > * PyString_AsString returns char* repr of PyObject, which should > * not be modified in any way...this should probably be copied for > * safety > */ > retString = PyString_AsString( evalVal ); > } > ... > > In this case, you need to know that the expression will evaluate to > a string result in order to call PyString_AsString(). If you don't know > this, you will have to check the type of the PyObject first. > > > From dave at graniteweb.com Sun Apr 25 02:05:58 2004 From: dave at graniteweb.com (David Rock) Date: Sun, 25 Apr 2004 01:05:58 -0500 Subject: compiling Python 2.3.3 Solaris 9 x86 question In-Reply-To: <7Axec.931$_B6.234@reader1.news.jippii.net> References: <7Axec.931$_B6.234@reader1.news.jippii.net> Message-ID: Stefan wrote: > Hi, > > I am trying to build Python 2.3.3 on Solaris 9 x86. Everything goes fine > except that I have some issues with curses module ... Is compiling necessary? I have found the packages for python 2.3.3 and ncurses on www.sunfreeware.com for Solaris 9 to work very well. The Solaris 8 packages were horribly wrecked for curses-based apps, but the Solaris 9 ones seem to work. -- David From jepler at unpythonic.net Fri Apr 23 13:53:13 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Fri, 23 Apr 2004 12:53:13 -0500 Subject: CamelCase versus wide_names (Prothon) In-Reply-To: References: <6e0680ac.0404211252.7f7b4358@posting.google.com> <4086DFA7.9736E7D3@alcyone.com> Message-ID: <20040423175313.GC2150@unpythonic.net> Do you have a use picked out for '@', '!' or '?'? A new use for ``? I think those are all either meaningless in Python, or tagged for eventual deprecation in Python 3.0 in the case of ``. Python already allows comments and strings to be in unicode or other encodings, and may allow unicode names in the future. Unicode defines a lot of mathematical symbols. Perhaps both languages should reserve the special __uNNNN__ and __ruNNNN__ (where NNNN is the unicode character value in hex), with __u0043__ being an alias for __add__ (etc) during a transitional period. I think that __u2261__ will be particularly useful to those who wanted to express "is substitutable for", without breaking the meaning of "==" or "is" operators to do it. (if you recall that recent thread) One possible problem with this approach is that you have to know at parse time whether an operator is a unary prefix operator (like __u222b__) or a binary operator (like __u2261__). On the other hand, this is already solved for + and -, so it must be OK. Is it possible for Prothon to innovate here? Unfortunately I'll have little internet access for the next two weeks, but it'll be interesting to see how prothon evolves over this time. Jeff From james at ractive.ch Thu Apr 15 13:06:12 2004 From: james at ractive.ch (Jean-Pierre Bergamin) Date: Thu, 15 Apr 2004 19:06:12 +0200 Subject: Socket error: 10053 software caused connection abort References: Message-ID: Jean-Pierre Bergamin wrote: > I'd be glad if someone could test theses scripts to see if this error > also occurs on other coputers and systems. > > Or is there anything wrong with the code? Could anyone reproduce this error? Regards James From skip at pobox.com Wed Apr 7 12:37:03 2004 From: skip at pobox.com (Skip Montanaro) Date: Wed, 7 Apr 2004 11:37:03 -0500 Subject: getting from code object to class/function Message-ID: <16500.11823.670207.707497@montanaro.dyndns.org> The trace module allows you to print all functions which were called at least once during a program's run. I just checked in a change to also track caller/callee relationships and display then at program exit. Both types of output suffer from the fact that all the trace function gets is the current frame. From there it can find the code object and then the source filename and function name. There is, however, no direct way back from the code object to (for example) the class and method which "own" that object. I didn't see anything obvious in the inspect module that would allow me to worm around this problem. A not perfect solution would seem to be: if the first element of the code's co_varnames attribute is "self" and the object in question is an instance, work back to the class and grab the class name (which is only available indirectly via str()), then use it to embellish the function name found in the code object. I'm open to other suggestions. Thx, Skip From piet at cs.uu.nl Wed Apr 7 05:10:27 2004 From: piet at cs.uu.nl (Piet van Oostrum) Date: 07 Apr 2004 11:10:27 +0200 Subject: OFF-TOPIC:: Why Lisp is not my favorite programming language References: <165b3efa.0403030443.4d591f04@posting.google.com> <40460dd5$0$5916$7a628cd7@news.club-internet.fr> <6in670lrldbjkuujle68a526293j57a7mn@4ax.com> Message-ID: >>>>> Stephen Horne (SH) wrote: SH> It wouldn't surprise me. LISP is normally interpreted - maybe always, SH> though I'm not certain of that. This is one of the misconceptions about Lisp. Many Lisp systems do have an interpreter on board, for interactive use but also most do have compilation. There are some that don't even have an interpreter, nand even for interactive use compile things without the user being aware of it. The speed of compiled Lisp programs can approximate the speed of equivalent C programs. -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP] Private email: P.van.Oostrum at hccnet.nl From jzgoda at gazeta.usun.pl Sat Apr 10 16:38:04 2004 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Sat, 10 Apr 2004 20:38:04 +0000 (UTC) Subject: why is python better than eg. smalltalk?? no one has any solid arguments! you should all go to church with all that religious talk! References: Message-ID: Jon Perez pisze: > For the past 10 years, I have been in search for a 'holy grail' of a text > editor and a language. Something I could absolutely devote myself to using. > After the dozens and dozens I've tried and looked at, I can now say to > myself that I have found what I've been looking for with SciTE and Python. I didn't found *the editor* yet (although Eric3 looks very promising), but my opinion on Python is very similar. -- Jarek Zgoda http://jpa.berlios.de/ From fredrik at pythonware.com Wed Apr 21 16:22:14 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 21 Apr 2004 22:22:14 +0200 Subject: Dollar sign ($) on foriegn keyboards? (prothon) References: Message-ID: Mark Hahn wrote: > In my defense, who would have thought that asking if international keyboards > had trouble typing a dollar sign would be a troll question? I'd say it's more of a bike shed question, not a troll. (if you don't know what I mean, google for "bike shed effect"). From jwsacksteder at ramprecision.com Mon Apr 26 10:18:18 2004 From: jwsacksteder at ramprecision.com (jwsacksteder at ramprecision.com) Date: Mon, 26 Apr 2004 10:18:18 -0400 Subject: Is Perl *that* good? (was: How's ruby compare to it older bro ther python) Message-ID: <71650A6F73F1D411BE8000805F65E3CB3B3A7D@SRV-03> >>getting dynamic HTML pages up and running quickly. Perl is great for >>its string-handling abilities. (On my Web pages, I actually call a Perl >>script from PHP precisely for this reason.) >I hear this more often than I understand it. Perl certainly >does support many string-oriented operations. What's a speci- >fic example, though, of an action you feel more comfortable >coding in external Perl? I suspect there's something I need >to learn about PHP's deficiencies, or Perl's power. I suspect the perl is the first place many people get exposed to regexes and when they understand the utility of that, some of the glow rubs off on perl. Someone actually said to me once "I program in perl because I can't live without regex." Now when someone says "perl text-processing", I hear "regex". (If I was motivated, I would include the above substitution in regex notation here...) The php/mysql crowd gives me this feeling as well, but that's a discussion for another day and another list. From skip at pobox.com Tue Apr 27 12:51:29 2004 From: skip at pobox.com (Skip Montanaro) Date: Tue, 27 Apr 2004 11:51:29 -0500 Subject: Is Perl *that* good? In-Reply-To: <38ec68a6.0404262308.50029919@posting.google.com> References: <108q51j4dscn7dc@corp.supernews.com> <87fzaqmm8t.fsf@strauser.com> <38ec68a6.0404262308.50029919@posting.google.com> Message-ID: <16526.36753.13192.577823@montanaro.dyndns.org> Asun> Regex is much more 'immediate' in Perl. Sure, it's syntactically bound into the language. There will always be an extra constant overhead to enable regular expressions in Python. That doesn't make them any less powerful than the Perl variety. It's simply a pair of different design decisions Guido and Larry made (along with a few others). Asun> Probably the only time I would reach for Perl rather than for Asun> python is when I knew a task involved a lot of regex (and no Asun> object orientation). Why? I write non-object-oriented Python code all the time. To make the Python/Perl switch you'd still have to shift your mental gears to deal with a different syntax, different way of getting at and using functionality that isn't builtin, etc. Even with lots of regex fiddling to do, I think the extra overhead of using regexes in Python would be swamped by the other differences. In addition, as Jamie Zawinski suggests, regular expressions are not always the best choice. Skip From hungjunglu at yahoo.com Tue Apr 6 14:51:03 2004 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 6 Apr 2004 11:51:03 -0700 Subject: GUI Frameworks in Python? References: <930ba99a.0404030246.786455f5@posting.google.com> <8ef9bea6.0404041009.26ae2683@posting.google.com> <930ba99a.0404060104.fdf2605@posting.google.com> Message-ID: <8ef9bea6.0404061051.1a167b37@posting.google.com> sridharinfinity at yahoo.com (Sridhar R) wrote in message news:<930ba99a.0404060104.fdf2605 at posting.google.com>... > Wrong. GTK apps do look with native look and feel. For Windows, > look at the screenshots from the wimp project First of all, thanks for all the pointers. But from GTK-Wimp I read: News: GTK-Wimp 0.5.4 released (Thursday, 11 March 2004) GTK-Wimp 0.5.3 released (Sunday, 25 January 2004) GTK-Wimp 0.5.2 released (Wednesday, 19 November 2003) > But, those people wouldn't have used PyGTK (or GTK) before. Don't > get a mind-shift just bcoz of some famous personality has said it. > Usually I will try out the possiblities and then choose from the > domain. If you have time, sure. Being guinea pig is a great way to learn. :) I did that with Java. After that, I swore I would never be another guinea pig again. :) I've done my share. Jokes aside. The easiest way of being taller than giants is to stand on their shoulders. The problem nowadays is there are all too many things to learn in life, and life unfortunately is short. Who you spend time talking to, and whose opinion you rely on, makes a big difference. Nowadays I realize I must relying on words of expert friends that have been there, done that. It's much more effective. Anyway, these are lessons that people learn, sooner or later. See also: http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&oe=UTF-8&selm=axa6b.64498%240u4.46413%40news1.central.cox.net "I have to concur with Cameron on the immaturity of Gtk under win32..." "Unless running on win32 is of secondary importance, I don't think Gtk would is a good choice until some of the Gtk/win32 bugs and other issues are worked out..." Your opinion, and opinions like the above, are the types of comments that I take into account. So, I have nothing against GTK in Windows per se, but it just seems to need a bit more time. Python did not start this good either. regards, Hung Jung From Mike at DeleteThis.Geary.com Sun Apr 11 03:43:08 2004 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Sun, 11 Apr 2004 00:43:08 -0700 Subject: Python is the best and most popular general purpose scripting language; the universal scripting language References: <107gttk8j6or775@news.supernews.com> Message-ID: <107htodblk16s83@corp.supernews.com> John Roth wrote: > The distinction isn't "scripting" versus "programming" > language, it's "scripting" versus something that doesn't > really have a name. Scripts are executed from the top > down once. In other languages (such as Java and C++) > there's a designated starting point (main()) that the > compiler locates. > > Python is a scripting language because each module > is executed from the top down as its loaded. By that definition, these would be scripting languages: Algol 60 Algol 68 APL Basic (traditional) BCPL Focal Forth Fortran Intel 8086 assembly in a "com" format executable Lisp Pascal PostScript Simula Snobol Turing (language) Turing (machine) I may have one or two of those wrong, but you get the idea... ;-) Wikipedia has a pretty good article on scripting languages: http://en.wikipedia.org/wiki/Scripting_language Even as informative as the article is, in the end it nearly gives up on the idea of distinguishing between scripting and other languages: "However, the boundary between scripting languages and regular programming languages tends to be vague, and is blurring ever more with the emergence of new languages and integrations in this fast-changing area." -Mike From paul at prescod.net Tue Apr 27 03:15:47 2004 From: paul at prescod.net (Paul Prescod) Date: Tue, 27 Apr 2004 00:15:47 -0700 Subject: Is Perl *that* good? In-Reply-To: References: <108qcobc4m8g972@corp.supernews.com> Message-ID: <408E08A3.6070609@prescod.net> Roger Binns wrote: > > Tcl also had a shot at stardom. I added it to the Mosaic browser where > it was used in a similar capacity to JavaScript today. Details are in > the proceedings of the 2nd WWW conference. (The audience were in awe > of a demo that printed an entire book based on following the rel links > in web page headers, got everything in the right order, loaded the pages > and printed). Python had a shot too: http://ksi.cpsc.ucalgary.ca/archives/WWW-TALK/www-talk-1994q3/1066.html And I think Python has a claim to the first Web robot: http://www.webhistory.org/www.lists/www-talk.1993q1/0060.html > To solve the same problems, Netscape invented yet another language and > put "marketing flavour of the day" in front, blessing us with Javascript. > I really wish Tcl had won that one. I wish Python had won. ;) Paul From ville at spammers.com Sat Apr 3 03:26:44 2004 From: ville at spammers.com (Ville Vainio) Date: 03 Apr 2004 11:26:44 +0300 Subject: Indent testers needed (Prothon) References: Message-ID: >>>>> "Mark" == Mark Hahn writes: Mark> I first said tabs-only since I'm a tabs lover and the Mark> tabs-haters came out and crucified me. Because of that and Mark> the fact that I found out that Guido wants to pull tabs from Mark> Python, I said we were going to spaces-only and then the Mark> space-haters did the same. I don't think Guido has a chance Mark> in hell of ever pulling tab support from Python. Just allow both spaces and tabs, but not in the same block. If someone with a crippled editor (e.g. non-programmers which might default to notepad, or someone not on his own computer) tries to create a new function in a spaces-only file, he's going to be so pissed because he has to hit spacebar 4 times instead of one tab to make the code look the same. -- Ville Vainio http://tinyurl.com/2prnb From alloydflanagan at comcast.net Fri Apr 30 10:14:54 2004 From: alloydflanagan at comcast.net (A. Lloyd Flanagan) Date: 30 Apr 2004 07:14:54 -0700 Subject: Possible problem with popen2 module Message-ID: OK, I've got a weird one I haven't been able to figure out yet. Admittedly I haven't had time to dig into the library source, but this behavior certainly doesn't seem right. Here's a test case: """Test program to demonstrate problem with popen2 module.""" import popen2 def main (argv): mycmd = 'python2.3 -c "for i in range(100000):\n print i"' p = popen2.Popen3(mycmd) print 'result code is %d' % p.wait() for line in p.fromchild.xreadlines(): print line, if __name__ == '__main__': import sys main(sys.argv) As you can see I'm using the popen2.Popen3 class to run a process which prints a lot of output. Here's the problem: for small values of the constant in the range() call, e.g. 1000, this works as expected. For larger values, e.g. 100,000, the program never returns from the p.wait() call after the child process completes. It appears tbe waiting forever on the waitpid() call. This is occuring on a Sun server: > uname -a SunOS fred 5.8 Generic_108528-29 sun4u sparc SUNW,Sun-Fire-880 and I've seen the exact same behavior under HP-UX: > uname -a HP-UX hpserver B.11.11 U 9000/800 2243344530 unlimited-user license I don't see this behavior with calling os.popen(). I DO see it with the current implementation of popen5() from the PEP. Does anyone know why this is occurring? Is this a bona-fide bug? Or am I just being stupid somehow? Thanks! A. Lloyd Flanagan Contract Programmer Richmond, VA From Mike at DeleteThis.Geary.com Mon Apr 5 13:18:48 2004 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Mon, 5 Apr 2004 10:18:48 -0700 Subject: recursive file editing References: Message-ID: <10735882vsuk1ca@corp.supernews.com> > for filetuple in os.walk('foo'): > ... for filename in filetuple[2]: > ... fileopen = file(filename, 'r+') > fileopen.write("This works !") > fileopen.close() > > which seems a bit of a clumsy way to do it. You have the right idea, although this would be a bit cleaner: for root, dirs, files in os.walk( 'foo' ): for name in files: etc... You might want to take a look at the documentation for os.walk. It explains all this and has a couple of good code samples. > And besides it only works if I run python from directory foo, > otherwise it tells me "no such file or directory". You mean if you run Python from the *parent* directory of foo, right? 'foo' is a relative path, not an absolute one, so it gets appended to the current directory. -Mike From imbosol at aerojockey.invalid Wed Apr 28 23:20:16 2004 From: imbosol at aerojockey.invalid (Carl Banks) Date: Thu, 29 Apr 2004 03:20:16 GMT Subject: Is Perl *that* good? References: <108q51j4dscn7dc@corp.supernews.com> <87fzaqmm8t.fsf@strauser.com> <38ec68a6.0404262308.50029919@posting.google.com> Message-ID: Peter Otten wrote: > Wallclimber wrote: > >> I have to agree with the original poster. My *only* complaint about >> Python are not regex search, but regex search and replace operations. >> Perl : s =~ s/(\w+)\s*=\s*(\d+)/$2 <= $1/g; >> Python : regex.sub(s, "(\w+)\s*=\s*)\d+)", (lambda m: m.group(2)+" <= >> "+m.group(1))) >> >> I didn't try this out so there might be some syntax problems in there, >> but you get the idea. Is there a 'nicer' way to do this in python? > > Your example suggests that the Python equivalent for $1 is \1: > >>>> re.sub(r"(\w+)\s*=\s*(\d+)", r"\2 <= \1", "a=1 b = 3 c = d") > '1 <= a 3 <= b c = d' You can do that? LSNED. -- CARL BANKS http://www.aerojockey.com/software "If you believe in yourself, drink your school, stay on drugs, and don't do milk, you can get work." -- Parody of Mr. T from a Robert Smigel Cartoon From mwh at python.net Sun Apr 11 12:12:22 2004 From: mwh at python.net (Michael Hudson) Date: Sun, 11 Apr 2004 16:12:22 GMT Subject: painful debugging: techniques? References: <8ef9bea6.0404070621.342c3b5d@posting.google.com> Message-ID: Richie Hindle writes: > [Hung Jung] > > The question now is: how can we stop this from happening to other people? > > [...] So far, I think Peter Otten's approach (search through the source > > code) may be the most practical way. > > Make weakref.ref() check that its second argument is a callable? > > (I know, "patches welcome" 8-) I *believe* that in current CVS python, a None second argument to weakref.ref() is treated as if there was no argument (i.e. how the OP expected). Someone who's not behind a modem and several layers of terminal emulation (none of which agree on the encoding being used) should check :-) Cheers, mwh -- 34. The string is a stark data structure and everywhere it is passed there is much duplication of process. It is a perfect vehicle for hiding information. -- Alan Perlis, http://www.cs.yale.edu/homes/perlis-alan/quotes.html From has.temp2 at virgin.net Thu Apr 29 06:59:32 2004 From: has.temp2 at virgin.net (has) Date: 29 Apr 2004 03:59:32 -0700 Subject: Is classless worth consideration References: Message-ID: <69cbbef2.0404290259.fd8d71c@posting.google.com> David MacQuigg wrote in message news:... > >> Example of Simplified Classes ( Prototypes ) > >> ============================================ > > > >[SNIP] > > > >Class-based OOP by any other name. But then, I've pointed this out > >already. See Emperor, clothes; lack of. > > > >Here; while I don't claim them to be paragons of programming, I > >suggest taking a look at my old AppleScript libraries [...] Might lend > >some useful perspective. > > The problem we Python programmers are having is understanding the > fundamental advantage of eliminating classes and working only with > instances. Well, as far as Python itself is concerned, it'd go a long way in eliminating the hideously baroque and increasingly brittle OO model it currently has. But that's by-the-by; the real problem isn't with Python itself but in the "we Python programmers". And here one might as well argue the benefits of untyped variables with a C/C++/Java-head, or the advantages of a strong functional type inference system with a Perl/Python user. If they are curious, open to new ideas, keen to explore, challenge and change their existing ones, they will seek out and find these questions and answers themselves. If they aren't, then no amount of outside argument is ever going to shake them from their current position; if anything, it'll only be used to strengthen those defences against change. So I'm sorry, but the fact you've already mastered Python means that - short of investigating the alternatives out of your own desire for learning, or being forced into it by unavoidable circumstance - of course you can't see what the advantages might be. Having familiarised and mastered its complexities, where's the advantage in throwing away those skills and knowledge for something unfamiliar? Just as a big cat born and raised on a safari park can have no notion of what it's like to run the Serengeti. You're so comfortable where you are, why would/should you want/need to change? > The theoretical discussions put me to sleep. I can't see > the point of the examples above. What we need is a simple use case. Ah, you mean a clever party trick to dazzle and astound and thereby prove its superiority, yes? Sorry, no will do. I mean, sure, yes, prototype OO lets you do some very cool and clever things. But then, so does something like metaclass programming - and you won't ever find me claiming this means MCP is a good thing. I'm sorry that my trivial proto-OO stack object example is too mundane, but, you know, that's kinda like the _whole_point_. Boring is GOOD. Deadly dull is GREAT. Too often, programmers and complexity are like crack addicts and cocaine - they just can't help themselves, I guess. So, let's look at it again: begin procedure(initialstate) begin object _state = initialstate begin method(params) ... end method end object end procedure and compare to: begin class specialmethod init(initialstate) newinstance._state = initialstate end specialmethod begin method(params) ... end method end class In the first, I call the procedure and it executes the statement[s] contained within and returns the result. In the second, I call the behind-the-scenes class constructor, which creates a new instance, calls the special init() method to initialise the instance's state, and returns it. Now, in both examples the source code itself is approximately the same length and density: 1. Which of these was easier for me to explain? 2. Which of these was less "magical"? (And what has your Uncle Guido taught you about "Explicit [being] better than Implicit" again?) 3. Which is more linear, spending less time looping in and around itself while creating a new object? 4. Which requires fewer special/unique constructs added to the language? 5. Which maps to more easily and directly from simple procedural thinking? 6. Which should scale further without need for additional support features? 7.. Ah hell, why don't you write some questions for yourself here and try answering than make me do all the work? > Here is what I have so far in the Pros and Cons on this feature: > > Pro: Allows "on-the-fly" programming style with no classes. > Con: Can lead to more undisciplined programming. > > Perhaps you can help us here. Seriously, I don't think I can help anyone if their idea of an argument against Arbitrary Feature X is "Can lead to more undisciplined programming"... except by taking away their keyboard, along with all electrical appliances, sharp objects, plastic bags and anything else they might potentially hurt themselves on if they really have a mind [or not] to. But, you know, I simply don't think it's my business, or problem, to be saving folks from themselves. Like the old adage: Never try to teach a pig a sing. It wastes your time and annoys the pig. Better for me to say: why not do as I did, and look for the answers yourself? If you truly want to find them, you will. If you don't, then don't worry, you won't. From paul at prescod.net Sun Apr 4 14:00:54 2004 From: paul at prescod.net (Paul Prescod) Date: Sun, 04 Apr 2004 11:00:54 -0700 Subject: Difference between default arguments and keyword arguments In-Reply-To: References: <406FFEAF.3080400@netscape.net> Message-ID: <40704D56.9070206@prescod.net> Marco Herrn wrote: > On 2004-04-04, DoubleM wrote: > >>All arguments are keyword arguments. They may or may not have a default >>value. In your example, voltage is a keyword argument, but it has no >>default. > > > But what does this mean?: > > >>> __import__(name="eggs") > Traceback (most recent call last): > File "", line 1, in ? > TypeError: __import__() takes no keyword arguments Functions implemented in C do not always have the property that every argument is a keyword argument. Functions implemented in Python do have that property. It's an implementation quirk. Paul Prescod From alloydflanagan at comcast.net Fri Apr 30 09:51:39 2004 From: alloydflanagan at comcast.net (A. Lloyd Flanagan) Date: 30 Apr 2004 06:51:39 -0700 Subject: String formatting (%) References: <3281a460.0404291301.3c3c647d@posting.google.com> Message-ID: padhia at yahoo.com (P Adhia) wrote in message news:<3281a460.0404291301.3c3c647d at posting.google.com>... > Another version of a more compact function would be, > > def commafy(s): > return len(s) > 3 and "%s,%s" % (commafy(s[:-3]), s[-3:]) or s > > Note that this function accepts string representation of an integer > (without checks of course). > > P Adhia And it seeems to work beautifully. Thanks, that's a great improvement. From peter at engcorp.com Wed Apr 28 09:05:23 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 28 Apr 2004 09:05:23 -0400 Subject: Backticks: What up? In-Reply-To: References: Message-ID: Steven Brent wrote: > I was wondering why the backticks in the following fragment: > > return 'Here's the result: ' + `self.data` > > My guess is that in a return statement (as opposed to a print statement) > it's necessary to do this in order to get the self.data instance attribute > as a string, so it can be concatenated with the 'Here's the result: ' > string. > > What exactly do the backticks do, then? Just return the result of an > expression as a string? Does my guess make sense and / or is it correct? > Elucidations and gentle ridicule welcome. The above is equivalent to return "Here's the result: %r" % self.data Note that someone doing the `self.data` thing might really have wanted to do the string representation instead (though the two are often the same), so return "Here's the result: %s" % self.data would be more appropriate. -Peter From Kyler at news.Lairds.org Wed Apr 28 08:08:31 2004 From: Kyler at news.Lairds.org (Kyler Laird) Date: Wed, 28 Apr 2004 12:08:31 GMT Subject: sending an object - twisted or what? References: <20040427152051.50234c65.mutah@NOSPAM-libertysurf.fr> Message-ID: SSH is typically available (and already running as a daemon) on most computers I touch these days. It would provide for the secure transport needed. Any reason not to use it? --kyler From mark at prothon.org Tue Apr 27 13:15:57 2004 From: mark at prothon.org (Mark Hahn) Date: Tue, 27 Apr 2004 10:15:57 -0700 Subject: What is good about Prothon? References: <108t2tlo06j8vb9@corp.supernews.com> Message-ID: "Michael Geary" wrote ... > I thought you'd already solved the problem anyway? David has been insisting for weeks that we don't need the obj$func() form if the interpreter just recognizes that obj is a prototype as Python does with classes. This is a never-ending argument that I am trying to end, especially since he has been using his argument to make claims about Prothon being too complex. I've got Has on one side of me who says that having prototype references instead of copies makes it too much like Python and therefore it isn't prototype-based and then David who thinks prototypes should be handled internally like classes (which would actually make them classes) and an occasional Lisper who thinks Prothon should be like Lisp. I knew I couldn't please them all, but I thought I'd be able to please one or two :) From peter at engcorp.com Sat Apr 24 08:50:47 2004 From: peter at engcorp.com (Peter Hansen) Date: Sat, 24 Apr 2004 08:50:47 -0400 Subject: [OT] Plone In-Reply-To: <408a2351$1@news.highway1.com.au> References: <6ukic.84257$cd.5573763@phobos.telenet-ops.be> <408a2351$1@news.highway1.com.au> Message-ID: Tim Hoffman wrote: > Really I don't understand a lot of peoples complaints about Zopes > complexity. I'd be interested to hear what products you have written on Zope, and which of the available techniques (e.g. Python scripts, Python products, DTML, TAL, or whatever else there is now) you used to write them. This might also tell us something about why you don't understand the complaints of those of us who have struggled greatly with such things in the past... -Peter From peter at engcorp.com Sun Apr 25 23:03:59 2004 From: peter at engcorp.com (Peter Hansen) Date: Sun, 25 Apr 2004 23:03:59 -0400 Subject: Parallel port interface In-Reply-To: References: Message-ID: Jorge Godoy wrote: > We're doing a research project that involves controlling mini-windtrap > speeds and we're reading/writing data from the parallel port. > > What I've found so far on a fast Google search for "python parallel port" > showed me some stuff that I'd have to interface with Python through SWIG. > > If the program could be portable in Windows and Linux it would be a big > plus. We're thinking --- if it can't be written entirely in Python or with > modules that already have binaries for Windows --- in using a Linux only > approach (we, the programmers, use Linux only). > > Any hints for modules I should take a look at? http://pyserial.sourceforge.net/pyparallel.html might work. Says "This module is still under developement. But it may be useful for developers." -Peter From officers-bounces at satlug.org Thu Apr 15 16:50:45 2004 From: officers-bounces at satlug.org (officers-bounces at satlug.org) Date: Thu, 15 Apr 2004 15:50:45 -0500 Subject: Your message to Officers awaits moderator approval Message-ID: Your mail to 'Officers' with the subject REGISTRATION CONFIRMATION Is being held until the list moderator can review it for approval. The reason it is being held: Post by non-member to a members-only list Either the message will get posted to the list, or you will receive notification of the moderator's decision. If you would like to cancel this posting, please visit the following URL: http://www.satlug.org/mailman/confirm/officers/6a9c3afb14d5b53e4479a4f87e2b2f1d8c4859e3 From claird at lairds.com Wed Apr 28 20:27:41 2004 From: claird at lairds.com (Cameron Laird) Date: Thu, 29 Apr 2004 00:27:41 -0000 Subject: MATLAB2Python References: Message-ID: <1090ivtaa0b2e26@corp.supernews.com> In article , Sarge wrote: >Hi, everybody! >I'm a moderately experienced programmer in Matlab, and looking for a >free computational language (Matlab is *REALLY* expensive for an >individual, like me). >I came across Python (actually Scipy) and immediately felt >comfortable with the interface and syntax. >I'm still a newbe, so, before attempting a serious work on it, I'd >like to hear any opinion about migration from Matlab to Python, and >also a rough comparison between these two languages. . . . 1. I run into quite a few people making a transition from Matlab to Python; invariably they say that the change is working out better than they expected. Very roughly speaking, Python allows for more abstraction and expressive power that expands their horizons beyond what they achieved with Matlab. 2. They're different, though, and Matlab certainly boasts a massive collection of special-purpose add-ons that will take a while to replace. Also, for some functions, Matlab is much faster (and for others, Python is much faster). 3. For the most conservative transition, you'll want to learn about Octave. A reference to Octave and more appear at . -- Cameron Laird Business: http://www.Phaseit.net From sp at sunguru.com Mon Apr 12 10:21:42 2004 From: sp at sunguru.com (Stefan) Date: Mon, 12 Apr 2004 17:21:42 +0300 Subject: compiling Python 2.3.3 Solaris 9 x86 question Message-ID: <7Axec.931$_B6.234@reader1.news.jippii.net> Hi, I am trying to build Python 2.3.3 on Solaris 9 x86. Everything goes fine except that I have some issues with curses module ... I had to fix configure script in order to get it running by changing SunOS/5.6 in SunOS/5.* eg. " case $ac_sys_system/$ac_sys_release in # On OpenBSD, select(2) is not available if _XOPEN_SOURCE is defined, # even though select is a POSIX function. Reported by J. Ribbens. # Reconfirmed for OpenBSD 3.3 by Zachary Hamm, for 3.4 by Jason Ish. OpenBSD/2.* | OpenBSD/3.[01234]) define_xopen_source=no;; # On Solaris 2.6, sys/wait.h is inconsistent in the usage # of union __?sigval. Reported by Stuart Bishop. SunOS/5.6) " Im building python using 2.95 the GNU compiler. The configure command was something like: ./configure --prefix=/usr/local --with-threads --enable-shared My LD_LIBRARY_PATH is defined as: /opt/sfw/lib:/usr/sfw/lib --- I have found that after compilation there are some warnings about curses module ... *** WARNING: renaming "_curses" since importing it failed: ld.so.1: ./python: fatal: relocation error: file build/lib.solaris-2.9-i86pc-2.3/_curses.so: symbol newscr: referenced symbol not found building '_curses_panel' extension *** WARNING: renaming "_curses_panel" since importing it failed: No module named _curses ... which, I think, will end by having no curses module available. From help() found out these: help> modules Please wait a moment while I gather a list of all available modules... ... _curses_failed getpass py_compile _curses_panel_failed ... Anyone any ideas about this error? Do I have to instruct configure script to pick up some libcurses at the first run ... or my LD_LIBRARY_PATH is not correct ? thanks stefan From nick.carter at roke.co.uk Thu Apr 29 06:45:22 2004 From: nick.carter at roke.co.uk (Nick Carter) Date: Thu, 29 Apr 2004 11:45:22 +0100 Subject: MATLAB2Python References: <1090ivtaa0b2e26@corp.supernews.com> <40904EDE.9060407@erols.com> Message-ID: <715kc.3$i6.251@psinet-eu-nl> Also look at Matplotlib for Matlab-like plotting: http://matplotlib.sourceforge.net/ Nick "Edward C. Jones" wrote in message news:40904EDE.9060407 at erols.com... > Cameron Laird wrote: > > In article , > > Sarge wrote: > > > >>Hi, everybody! > >>I'm a moderately experienced programmer in Matlab, and looking for a > >>free computational language (Matlab is *REALLY* expensive for an > >>individual, like me). > >>I came across Python (actually Scipy) and immediately felt > >>comfortable with the interface and syntax. > >>I'm still a newbe, so, before attempting a serious work on it, I'd > >>like to hear any opinion about migration from Matlab to Python, and > >>also a rough comparison between these two languages. > > > > . > > . > > . > > 1. I run into quite a few people making a transition > > from Matlab to Python; invariably they say that > > the change is working out better than they expected. > > Very roughly speaking, Python allows for more > > abstraction and expressive power that expands their > > horizons beyond what they achieved with Matlab. > > 2. They're different, though, and Matlab certainly > > boasts a massive collection of special-purpose > > add-ons that will take a while to replace. Also, > > for some functions, Matlab is much faster (and for > > others, Python is much faster). > > 3. For the most conservative transition, you'll want > > to learn about Octave. > > > > A reference to Octave and more appear at > http://phaseit.net/claird/comp.programming/open_source_science.html >. > > Also check out numarray and PIL. From richie at entrian.com Fri Apr 2 10:02:12 2004 From: richie at entrian.com (Richie Hindle) Date: Fri, 02 Apr 2004 16:02:12 +0100 Subject: Nonsense (was: Stackless Website down, Project gone, I'm dead.) In-Reply-To: <406D6AF5.1060809@stackless.com> References: <406CD030.5010506@stackless.com> <406D6AF5.1060809@stackless.com> Message-ID: [Chris] > No idea which fool tried to make fun of me. But it was in very bad taste, and we're glad to know you're still around! > I'd like to know how they faked my emails. I'm no expert, but it looks like a very good forgery to me. Perhaps when they said "some bad intruder has broken into our [...] server" they weren't kidding? -- Richie Hindle richie at entrian.com From roy at panix.com Thu Apr 22 14:17:14 2004 From: roy at panix.com (Roy Smith) Date: Thu, 22 Apr 2004 14:17:14 -0400 Subject: equivalent to Tcl 'after' command? References: Message-ID: In article , Mark Harrison wrote: > I'm writing some event-driven programs, and I would like > to do the equivalent of the Tcl 'after' command, e.g.: > > after 1000 {puts "one second has elapsed"} You want to took at the Timer objects that are part of the threading module http://www.python.org/doc/current/lib/timer-objects.html From nmkolev at uni-bonn.de Wed Apr 21 12:18:16 2004 From: nmkolev at uni-bonn.de (Nickolay Kolev) Date: Wed, 21 Apr 2004 18:18:16 +0200 Subject: Optimizing a text statistics function In-Reply-To: References: Message-ID: Dennis Lee Bieber wrote: > ## for x in strippedWords: > ## unique[x] = 0 > ## > ## for x in strippedWords: > ## unique[x] += 1 > > for x in strippedWords: > unique[x] = unique.get(x, 0) + 1 Just the thing I was looking for. :-) To clarify: unique.get(x, 0) This says *give me the value of unique[x] if it exists, else give me 0*. Correct? From mikalzetTogli at interfree.it Mon Apr 5 12:40:25 2004 From: mikalzetTogli at interfree.it (TaeKyon) Date: Mon, 05 Apr 2004 16:40:25 GMT Subject: recursive file editing References: Message-ID: Il Sat, 03 Apr 2004 17:22:04 -0800, Josiah Carlson ha scritto: > for thing in os.walk('mydir'): > filehandle = file(thing, 'r+') I'm such a newbe I can't get it to work. Here is an example: in empty directory foo I touch a b c d; suppose I want to write "This works !" in each of these files. I run python >>> import os >>> for thing in os.walk('foo'): ... thingopen = file(thing,'r+') ... thingopen.write("This works !") ... thingopen.close() ... Traceback (most recent call last): File "", line 2, in ? TypeError: coercing to Unicode: need string or buffer, tuple found And in fact: >>> for thing in os.walk('foo'): ... print thing ... ('foo', [], ['a', 'b', 'c', 'd']) which is a tuple, I suppose. Selecting thing[2] doesn't help, because it now complains of it being a list. In the end I get this to work: for filetuple in os.walk('foo'): ... for filename in filetuple[2]: ... fileopen = file(filename, 'r+') fileopen.write("This works !") fileopen.close() which seems a bit of a clumsy way to do it. And besides it only works if I run python from directory foo, otherwise it tells me "no such file or directory". -- Michele Alzetta From mogmios at mlug.missouri.edu Sat Apr 24 17:29:52 2004 From: mogmios at mlug.missouri.edu (Michael) Date: Sat, 24 Apr 2004 14:29:52 -0700 Subject: command-line args In-Reply-To: <200404242040.i3OKeKjj032092@mlug.missouri.edu> References: <200404242040.i3OKeKjj032092@mlug.missouri.edu> Message-ID: <408ADC50.404@mlug.missouri.edu> >It's definitely always worked that way, at least since >long before either of us started using Python. The problem >must have been between the keyboard and the chair. :-) > > Thanks for the help. I might suggest, if anyone is listening, that this would be a good tidbit to include in the docs somewhere obvious. Surely I'm not the only person that has gotten this messed up. I am left with a useless but pretty nifty lil module for creating temp files, named by the process id, that remove themselves when Python exits. Maybe I'll find another use for it. Sounds like the type of thing that should have been in tempfile. :) From peter at engcorp.com Thu Apr 15 14:39:21 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 15 Apr 2004 14:39:21 -0400 Subject: Does Python compete with Java? In-Reply-To: <8b336527.0404151019.14b93502@posting.google.com> References: <8b336527.0404051337.51bb4a1b@posting.google.com> <407deb56$1@news.unimelb.edu.au> <8b336527.0404151019.14b93502@posting.google.com> Message-ID: <5KydnYqkwP1ES-PdRVn-vA@powergate.ca> kk wrote: > That is exactly my point! Uh, sorry, but what point? The email address and initials you are using here (kkennedy65 at yahoo.com and kk) have not posted before in this thread, as far as I can see. So who are you? :-) -Peter From fgeiger at datec.at Tue Apr 13 12:18:49 2004 From: fgeiger at datec.at (F. GEIGER) Date: Tue, 13 Apr 2004 18:18:49 +0200 Subject: [wxPython] wxListCtrl_virtual crashes and I can't find what I'm doing wrong Message-ID: [Posted to comp.soft-sys.wxwindows and comp.lang.python] Hi all, in my MainFrame class I have def'ed a method which is called on idle. There I retrieve the frame's title for further processing: currentTitle = self.GetTitle(). No problem so far. I have a wxNotebook containing several pages. Those pages contain controls updating themselves, using a wxTimer for that. No problem so far. I have added another page containing a control derived from wxListCtrl, virtual style. And now I have problems: This control is named VipAPSpooler. It first used a wxTimer, to update itself periodically: If the underlying model had changed in the number of items, it exec'ed a DeleteAllItems() and a SetItemCount(). This did not work: The debugger halted in the MainFrame's(!) on-idle-method in line currentTitle = self.GetTitle() saying "Inappropriate argument type: an integer is required". I thought, that using too many wxTimer-s could cause this problem (other controls used timers too to update themselves). So I decided to eliminate all timers and to write an update method for all controls that should be able to update themselves. This update-method were then called from the MainFrames's on-idle-method. The rationale: No more timers and only one on-idle-method. But that did not solve the problem. The same and sometimes other weired errors popped up now in code called by OnGetItemAttr() ans OnGetItemText() of the virtual wxListCtrl. Example: def __str__(self): if self._value: # <- "Inappropriate argument type: an integer is required". return str(self._value) return '' Or this: def OnGetItemAttr(self, item): if item == self.model().currentLineNbr(): # <- "Inappropriate argument type: an integer is return self._attr return None Executing the offending line in the Debug Probe (yes, it's WingIDE) in each case passes w/o problems - weird. Looking at the stack data doesn't show any data corruption, everything seems okay. I commented out this and that and seem to have found out, that as soon SetItemCount() is called, the control is no more able to do its job. I'm stuck in the middle. Despite the fact that my code is cut & pasted from the demo I am sure to overlook something. Any idea? Kind regards Franz GEIGER P.S.: Python 2.3.2 and wxPython 2.4.2.4u on Win2k. and Python 2.3.2 and wxPython 2.5.1.5u on WinXP. From cm at leetspeak.org Fri Apr 23 07:54:25 2004 From: cm at leetspeak.org (Michael Walter) Date: Fri, 23 Apr 2004 13:54:25 +0200 Subject: AOP use cases In-Reply-To: <4087D662.6010209@yahoo.com> References: <84fc4588.0404140106.3fa0c55@posting.google.com> <0pydnSB4WYuieuLdRVn-hQ@powergate.ca> <4087D662.6010209@yahoo.com> Message-ID: Bryan wrote: >> >> Those of you using XML might want to visualize the program as a DOM >> tree and >> AOP as applying a XSLT stylesheet. (Now visualize applying several >> different >> stylesheets in arbitrary order) >> >> >> Daniel >> > > > thank you for this explanation... it's the best explanation i've heard > yet and now i have a grasp and can visualize what AOP is. > > bryan That sounds like a description of (CL/Scheme-style) macros :) Cheers, Michael From jcarlson at uci.edu Wed Apr 21 11:46:31 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Wed, 21 Apr 2004 08:46:31 -0700 Subject: how to calculate correctly the cluster size In-Reply-To: References: Message-ID: > Josiah> The Windows 2k "Disk Administrator" software for > Josiah> 2K always uses 4k cluster sizes by default. > Josiah> I believe your varied cluster sizes are the > Josiah> result of using Partition Magic to create them. > > FWIW, the FORMAT command does offer the possibility of selecting > different cluster sizes. I've never used it personally (and I'm > not about to try it on this machine, either!) Indeed, you can change the cluster sizes using the command-line format command. However, when formatting a fresh drive using the format command at the command line, I would expect that it would do the same thing as the Disk Administrator, user cluster sizes of 4k if possible. For a FAT 32 drive, that range is 256 megabytes ... 8 terabytes. Why 4k? I don't know, maybe it strikes a nice balance between not having enough and having too many clusters, or maybe it is to mirror the 4k/page size of many paging schemes in modern operating systems. A filesystem designer would probably be quite helpful at this moment. - Josiah From eastier at free.fr Wed Apr 21 08:53:33 2004 From: eastier at free.fr (Emmanuel) Date: Wed, 21 Apr 2004 14:53:33 +0200 Subject: Generator inside a class prevent __del__ ?? References: <4085BA96.651D2E4A@free.fr> Message-ID: <40866ECD.A45758B9@free.fr> Terry Reedy a ?crit : > "Emmanuel" wrote in message > news:4085BA96.651D2E4A at free.fr... > > I run across this problem, and couldn't find any solution (python 2.2.2) > ... > > Here, everything is normal... > > But creating a generator : > > You both defined generator function and called it to create generator > iterator. Yes, I don't have all the generators vocabulary yet... > > > > > > Code : > > =========== > > > > >>> class toto: > > def __init__(self): > > print "init" > > self.Coroutine = self.Gen() > > This creates a reference loop. Delete this (and correct typo below) and > 'problem' will disappear. > > > def __del__(self): > > print "del" > > def Gen(self): > > If you do not really use self in the resulting iterator, define this > outside of the class without self as a parameter, and problem will > disappear. I didn't use self in order to provide a simple example. In my real class, self is used... > > > > yield 1 > > > > >>> a = toto() > > did you mean 'c = toto()'? Yes, sorry for that... > > > > init > > >>> c = [] > > <--- Nothing there !!! > > ============== > > > > I can't understand why the destructor is not called when a generator is > > created, and what I should do to have a "correct" behavior. > > Either do not create reference loop or break it with del c.Coroutine. > > Terry J. Reedy Thank you very much for your answer, but I'm still not sure I understand it. If I understand your words right, creating self.Coroutine as an iterator on the generator function will create a reference on self, so if I want to use a generator in a class ( and I really want to ), I must delete explicitly the iterator before I destroy the object. Trouble is, I _would_ like not to care about the lifetime of the object, and I don't know where it will be destroyed. Should I encapsulate this object in another one, like this : import toto class TotoCapsule: def __init__( self ): self.toto = toto.toto() def __del__(self): del self.toto.Coroutine self.toto = None And use TotoCapsule ? But it means I have to write a lot of more code to access toto's method. Is there a pattern I missed to dea l with that ? Thanks a lot, Emmanuel From nhodgson at bigpond.net.au Mon Apr 12 08:24:53 2004 From: nhodgson at bigpond.net.au (Neil Hodgson) Date: Mon, 12 Apr 2004 12:24:53 GMT Subject: pythonwin crash (used to work) - please help quick. References: <5Reec.62668$Id.61067@news-binary.blueyonder.co.uk> Message-ID: Stevie_Mac: > So if I understand this, a python GUI can't debug a script that uses code > from any other GUI implementation (like wx for example)? The problems often occur when a GUI debugger is trying to run in the same process as the target and there are clashes. > If so, dang! Whats my options - different IDE - or - no debug! Running the target in another process as is done by some debuggers is often more robust. IIRC, the current version of Idle, HAP Debugger, Wing IDE, and Komodo can work in this manner. I'd recommend having a look at HAP Debugger which works on Windows, is free and fairly simple. Then if you need something more comprehensive look at the commercial products. Neil From db3l at fitlinxx.com Tue Apr 6 17:07:33 2004 From: db3l at fitlinxx.com (David Bolen) Date: 06 Apr 2004 17:07:33 -0400 Subject: Capturing stdout incrementally References: Message-ID: Josiah Carlson writes: > > I am on Windows by the way, so the utilities are printing to the windows > > command shell. > > By default, popen in Windows buffers everything coming from the called > app. I believe you can use various Windows system calls in pywin32 in > order to get line buffered output, but I've never done it, so have > little additional advice other than "check out pywin32". Typically this behavior on Windows (and at least in my experience on Unix) comes not from popen buffering its input from the called program, but the called program buffering its output when it isn't a normal console. I'm not sure if this is default behavior from the C library, but it's particularly true of cross-platform code that often uses isatty() to check. You can even see this behavior with Python itself (e.g., if you pipe a copy of python to run a script). In general, the only way to fix this is through the program being called, and not the program doing the calling. In some cases, the problem may have a way to disable buffering (for example, the "-u" command line option with Python), or if it's something you have source for you can explicitly disable output buffering. For example, Perl has no command line option, but you can add code to the script to disable output buffering. On Unix, a classic way around code for which you have no source is to run it under expect or some other pty-simulating code rather than a simple pipe with popen. I'm not sure if there's a good pty/expectish module that works well under Windows (where simulating what a "console" is can be tougher). I've only got an evaluation copy of perforce lying around, but I don't immediately see any way to control its buffering via command line options. -- David From nid_oizo at yahoo.com_remove_the_ Fri Apr 30 13:50:08 2004 From: nid_oizo at yahoo.com_remove_the_ (Nicolas Fleury) Date: Fri, 30 Apr 2004 13:50:08 -0400 Subject: Unification of Methods and Functions In-Reply-To: References: Message-ID: David MacQuigg wrote: > I'm especially interested in feedback from users who are now learning > or have recently learned Python. I already know these changes seem > trivial to many experts. I've also heard plenty from the people who > think Python is so complex that we need to start a whole new language > ( www.prothon.org ). I'm looking for a middle ground. I believe it > is possible to adopt what is good about Prothon, and not lose ten > years of software and community development. I don't think Python is too complex and to me your suggestion adds more complexity rather than simplying. Your proposal is also not backward-compatible at all, so I don't see it can ever be accepted. I agree that avoiding self make code lighter, but I don't think it unify things or simplify them. It adds a magic and hidden parameter. The good thing about the current syntax is that it shows what is really happening. Actually, I find the statu quo more unified. I would prefer self to be a keyword and be used to determine if the function is static, but I guess we have to live with things like that. I have given some python courses and the self parameter seems to be clear for everybody. I think it even helps comprehension. Regards, Nicolas From rzantow at ntelos.net Sat Apr 3 00:10:23 2004 From: rzantow at ntelos.net (rzed) Date: Sat, 03 Apr 2004 05:10:23 GMT Subject: Indent testers needed (Prothon) References: Message-ID: "Mark Hahn" wrote in news:b5rbc.132699$cx5.63133 at fed1read04: > This was a bit premature. Some of our test cases give > indentation errors. I'll post another file when it is really > ready for testing. > > Meanwhile comments on our intended solution would be greatly > appreciated. > > > Some odd-looking things can happen, as it stands. These two loops parse correctly: alist = [3,7,11] blist = [1,2, 3] # loop 1 ix = 2 for item in blist: alist[ix] = alist[ix] + item print alist[ix] ix = ix - 1 /* loop 2 */ ix = 2 for item in blist : alist[ix] = alist[ ix ] + item print alist[ix] ix = ix - 1 -- rzed From bkc at Murkworks.com Mon Apr 12 14:35:43 2004 From: bkc at Murkworks.com (Brad Clements) Date: Mon, 12 Apr 2004 14:35:43 -0400 Subject: embedding python References: Message-ID: I compiled Python 2.3.2(alpha2) on uClinux and linked it with libxml2 and libxslt. This ran on a Arcturus 68K board with 2meg flash and 8meg ram. Barely fit, was very slow. We abandoned the platform. I've been promised an ARM board with 64 meg ram (uh, that was 6 months ago). Haven't seen it arrive yet. Anyway, it works.. I just cross compiled as part of the uClinux dev chain. You didn't mention which OS you want. -- Novell DeveloperNet Sysop #5 _ "Andrea Fino" wrote in message news:fg6qk1-jac.ln1 at netzen.intra.faino.org... > Hi, > > I am studying how to get a python 2.3 interpreter running in a small > embedded system ie. 8MB flash ans 32MB ram, > > after some search with google on thiw newgroup looks like others already > did this kind of stuff, > > Could I have some hints how to proceed, and/or url to read about it? > > there is any doc? > > Thanks, > Andrea > > -- > Andrea Fino 8-) - "Sistemi su misura di qualita' industriale" > "Handcrafted systems with industrial quality" > > [Phone: +39 071 2070104]+[Fax: +39 071 2077919]+[iaxtel:17002876594] > [Web: http://www.faino.org]+[Email: af at faino.org] > > -----BEGIN GEEK CODE BLOCK----- > Version: 3.1 > GCS: d- s: a+ C+++ UL++++ P++ L++++ E--- W++ N++ o? K w--- O M V > PS++ PE+ Y+ PGP t+ 5? X-- R* tv- b-- DI+++ D G++ e* h r y+ > ------END GEEK CODE BLOCK------ > -- > http://mail.python.org/mailman/listinfo/python-list > From piet at cs.uu.nl Fri Apr 30 13:21:17 2004 From: piet at cs.uu.nl (Piet van Oostrum) Date: 30 Apr 2004 19:21:17 +0200 Subject: uuid generator References: Message-ID: >>>>> Marcello Pietrobon (MP) wrote: MP> Hello, MP> I need to read newly generated uuid from Python MP> but I am not sure if MP> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/163604 MP> is the right code There's another one at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/213761 -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP] Private email: P.van.Oostrum at hccnet.nl From sean at sands.beach.net Wed Apr 28 16:22:32 2004 From: sean at sands.beach.net (Sean Berry) Date: Wed, 28 Apr 2004 20:22:32 GMT Subject: How to add an attachment with smtplib module Message-ID: I have the sample script that uses the smtplib module that is available at python.org. How can I use this to send an attachment? Help is greatly appreciated. Thanks. -- From pbaldanta at yahoo.com Thu Apr 1 03:01:21 2004 From: pbaldanta at yahoo.com (Pedro Baldanta) Date: 1 Apr 2004 00:01:21 -0800 Subject: Python conference slogan References: Message-ID: Shane Hathaway wrote in message news:... > Here's a Python slogan suggestion by Ken Manheimer. > > One Nation Under Under Python > > I thought it was pretty funny. I don't know if international folks will > get it, though. :-) > > Shane Bite the python. From junkmail at solumslekt.org Fri Apr 2 03:36:09 2004 From: junkmail at solumslekt.org (Leif B. Kristensen) Date: Fri, 02 Apr 2004 10:36:09 +0200 Subject: String concatenation References: <7xisgi24fm.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Not tested: > > tmp = [x for x in res if x and x[0] != '-'] > return ', '.join(tmp) Paul, that looks a lot more like the examples in "Dive Into Python" which I'm reading at the moment. But the snake won't swallow: tmp?=?[x?for?x?in?res?if?x?and?x[0]?!=?'-'] ^ SyntaxError: invalid syntax I wonder what it's really trying to tell me? regards, -- Leif Biberg Kristensen http://solumslekt.org/ Validare necesse est From a at a.invalid Tue Apr 20 14:54:19 2004 From: a at a.invalid (Timo Virkkala) Date: Tue, 20 Apr 2004 18:54:19 GMT Subject: Pygame book In-Reply-To: References: Message-ID: Lucas Raab wrote: > I was at the bookstore the other day and I noticed a book that dealt with > making games with Pygame. As I recall the book title was "Game Programming > with Python." I have an interest in making games, so I was wondering if any > of you have this book and if you do, could you please give me a nice > overview and whether I should buy the book or not. I own the book, and I liked it a lot. During the book the author develops a game framework. Sure, there's some things I'd like to do differently, but overall it seemed like solid work. There are also chapters on extending and embedding Python. I'd suggest you take a closer look at the book, and if you like it, buy it. I haven't regretted spending my money on it =) -- Timo Virkkala From ajsiegel at optonline.com Thu Apr 8 21:11:41 2004 From: ajsiegel at optonline.com (Arthur) Date: Fri, 09 Apr 2004 01:11:41 GMT Subject: List vs tuples References: <107bf8q8fhsmg5e@news.supernews.com> Message-ID: On Thu, 8 Apr 2004 16:57:25 -0400, "John Roth" wrote: >It's a common question. A list is a data structure that is >intended to be used with homogenous members; that is, >with members of the same type. As succeint and comforting as the explanation is.... I have consulted the Python Desgin Manual: Occult Edition, and if my search of the list archives is true, the statement: """ A list is a data structure that is intended to be used with homogenous members; that is,with members of the same type. """ is still 6 incantaions shy of becoming meaningful. 5 now actually. Art From tuure at laurinolli.net Sat Apr 3 09:27:08 2004 From: tuure at laurinolli.net (Tuure Laurinolli) Date: Sat, 03 Apr 2004 17:27:08 +0300 Subject: HTML writer In-Reply-To: References: <406D3C97.7020006@livinglogic.de> Message-ID: Moosebumps wrote: > That is, I would not like any specific HTML tags anywhere in my own code, > and it seems like that is what they will allow me to do. But I would be > interested to hear opinions/experiences with these packages. I spent a couple of days last week getting to know each of these. I found HTMLgen as I was getting desperate with the tag soup in my code and quickly converted the code to use it. Then I found out it only does HTML 3.2, missing end tags of elements and such. Some parts of the model also weren't as generic as they should have been. Next I stumbled upon HyperText, which seemed to fix all the incosistencies of HTMLgen, and also output XHTML 1.0. THe problem was that I found no way to use web forms with it. The 'name'-attribute of an input tag seemed to be impossible to set(ie. foo.name didn't do the right thing, foo['name'] was illegal and there weren't any obvious false names like klass <-> class). Fixing this would have been easy, but I decided to look for alternatives. The final option seemed to be XIST, of which HTML seems to be only small part. It seems to implement HTML in a consistent fashion, allowing all the necessary tag attributes to be set and otherwise providing a nice interface to the horrible world of web :) -- Tuure Laurinolli From knight at baldmt.com Sat Apr 10 01:48:19 2004 From: knight at baldmt.com (Steven Knight) Date: 9 Apr 2004 22:48:19 -0700 Subject: automatically generating file dependency information from python tools References: <107eag4pnl2ar35@news.supernews.com> Message-ID: > > I'm not entirely clear on what the purpose of this is. I normally > > think of "makefile" type information as something needed to compile > > a program. This is something that isn't usually needed for Python > > unless you're dealing with C extensions. Then I'd suggest looking at > > SCons (www.scons.org). > > Well sorry for being so abstract, let me be a little more concrete. I am > working at a video game company, and I have had some success using Python > for tools. I am just thinking about ways to convince other people to use > it. One way would be to improve the build processes, and be able to do > incremental builds of art assets without any additional effort from > programmers. Basically I'm trying to find a way to do some work for free > with python. > > The idea is that there are many different types of assets, e.g. 3D models, > textures/other images, animations, audio, spreadsheet data, etc. Each of > these generally has some tool that converts it from the source format to the > format that is stored in the game on disk / in memory. Hence they are > usually simple command line data crunchers. They take some files as input > and just produce other files as output. Check out SCons; it's specifically designed to be extensible in just this way to handle different utilities for building different file types, as well as allowing you to write scanners to return dependencies based on any mechanism you can code up in Python. SCons is already in use by a number of gaming companies to speed up and improve their builds. --SK From rick.lawson at rbc.com Wed Apr 21 12:53:26 2004 From: rick.lawson at rbc.com (rick.lawson at rbc.com) Date: Wed, 21 Apr 2004 12:53:26 -0400 Subject: tkinter widget collection project Message-ID: <12C2B8E4DF512A408A4D0BA223AF032F0C6DAD51@SEW80008.palm.fg.rbc.com> I, like a lot of developers, have collected a homegrown set of widgets for Tkinter. Any thoughts on a central repository for Tkinter widgets or widget extensions? Stuff that's not in Tkinter or standard extensions like Pmw. It would be nice if you could go to sourceforge and download a package instead of hunting the Vaults, the Activestate cookbook, googling, etc. If there's enough interest I'd be willing to set the project up on sourceforge and provide some (limited) manpower towards packaging submitted widgets. Thanks, Rick Lawson ------------------------------------------------------------This e-mail may be privileged and/or confidential, and the sender does not waive any related rights and obligations. Any distribution, use or copying of this e-mail or the information it contains by other than an intended recipient is unauthorized. If you received this e-mail in error, please advise me (by return e-mail or otherwise) immediately. ============================================================ -------------- next part -------------- An HTML attachment was scrubbed... URL: From newsgroups at jhrothjr.com Mon Apr 26 14:22:45 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 26 Apr 2004 14:22:45 -0400 Subject: How's ruby compare to it older brother python References: <108pvmgl0h7m3ea@news.supernews.com> Message-ID: <108qksd83igmn6f@news.supernews.com> "Phil Tomson" wrote in message news:c6jg7404m at enews4.newsguy.com... > In article <108pvmgl0h7m3ea at news.supernews.com>, > John Roth wrote: > > > >"Hunn E. Balsiche" wrote in message > >news:c6ich0$c5mee$1 at ID-205437.news.uni-berlin.de... > >> in term of its OO features, syntax consistencies, ease of use, and their > >> development progress. I have not use python but heard about it quite > >often; > >> and ruby, is it mature enough to be use for developing serious > >application, > >> e.g web application as it has not many features in it yet. > > > >As another poster has mentioned, Ruby is more closely related > >to Perl than to Python. While I don't use it, people I respect who > >have moved to Ruby say it has a couple of real killer features; > >in particular the way blocks and the pervasive use of the visitor > >pattern come together change the way one writes programs for > >the better. > > > >As far as syntax is concerned, there doesn't seem to be a > >huge amount of difference. Syntax is syntax, and every language > >has it's little pecularities. > > Well, there is one big difference syntactically: Python uses indentation > as syntax and Ruby doesn't. Personally I don't prefer Python's > 'indentation-as-syntax' since it means that syntactically significant > pieces of my code are invisible and if the tab settings in my editor are > not the same as yours it can make it difficult to share code (or even > worse, it might look like everything is OK when we share code, but the > code which looks exactly the same to each of us, might not be depending > on how tabs are or are not expanded). It would also seem to be a pain for > cutting & pasting code as well. As I said in another post, indentation is the reason I learned Python in the first place, but it's not the reason I stay with the language. In fact, I've come to the very heretical view that the indentation sensitivity is a language design mistake. It should be the editor's job to handle that level of detail in a manner that the developer finds workable. One reason I think it's a language design mistake is that it's not recursive. That is, it's not possible to shift from expression level indentation back to statement level indentation without major disruptions. This is needed for embedded blocks. I think Ruby has a reasonable middle ground here: its use of 'end' is fairly unobtrusive compared to, for example, C, C++, C# or Java. Even so, I think that a reasonable programming editor would get them out of my face while I was programming. The tab issue is one of those relatively inconsequential things that people seem to love to argue about: I'd rather be able to tell the editor how I want the program formatted, and have done with it. > Phil From junkmail at solumslekt.org Mon Apr 26 14:28:13 2004 From: junkmail at solumslekt.org (Leif B. Kristensen) Date: Mon, 26 Apr 2004 20:28:13 +0200 Subject: Is Perl *that* good? (was: How's ruby compare to it older brother python) References: <108q51j4dscn7dc@corp.supernews.com> <108qi5opkrfnv56@corp.supernews.com> Message-ID: Cameron Laird rose and spake: > Long ago, I was myself involved in a tiny way with > parish records for Finnmark and Troms. I wish I'd > been able to do more ... That's very interesting from my point of view. Starting this autumn, by the way, the Norwegian National Archive will begin to publish scanned images of parish records on the Web. They plan to finish this job in a couple of years, and then go on to other popular sources for genealogists, such as probates, court records, and land transactions. > I'm glad things are working for you. I'm all for > not-duplicating effort. Do you realize you can use > PHP from the command line? As I understand your > explanation, it doesn't reflect AT ALL on a defici- > ency in PHP string-handling; to my eye, PHP can do > the operation just about as well as Perl. It probably could, but at the time I wrote my FoxPro extraction script I was very much into Perl. I was very happy to find the XBase module, and besides, I have been unable to find something similar in any other language that I have more than a nodding aquaintance with. > I continue to conclude that all these languages are > roughtly equally competent at managing strings. Perhaps, but right now I think that I'm in love with Python. Consider these two equivalent routines in PHP and Python: PHP: function get_place($x) { $query = "select pl1, pl2, pl3, pl4, pl5 from places where place_id = $x"; $handle = mysql_query($query); $row = mysql_fetch_row($handle); $pl_string = ''; if ($p_num == 1) return ''; $i = 0; for ($j = 0; $j<5; $j++) { if ($row[$j] != '' && substr($row[$j], 0, 1) != '-') { $pl[$i] = $row[$j]; $i++; } } for ($j = 0; $j < ($i-1); $j++) $pl_string .= $pl[$j].', '; $pl_string .= $pl[$i-1]; return ltrim(rtrim($pl_string)); } Python: def get_place(x): c=db.cursor() c.execute("select pl1, pl2, pl3, pl4, pl5 from place where place_id = %d" % (x)) result=c.fetchone() return ', '.join([p for p in result if p and p[0] != '-']) Consider that my entire Web site is written in PHP. I stumbled across Python just a few weeks ago, and got substantial help with the latter version of the routine from Paul Rubin on this list. My PHP coding may be suboptimal, but in terms both of codability and readability as well as in sheer elegance, I find the Python version superior in any way. regards, -- Leif Biberg Kristensen http://solumslekt.org/ Validare necesse est From no.email at please.com Sun Apr 11 13:01:01 2004 From: no.email at please.com (Stevie_mac) Date: Sun, 11 Apr 2004 18:01:01 +0100 Subject: pythonwin crash (used to work) - please help quick. Message-ID: <5Reec.62668$Id.61067@news-binary.blueyonder.co.uk> OS=XP, Python 2.3, wx2.5.1.5u Not sure what's to blame here - or to be more precise, how to fix it!... If I do this in PythonWin... import wx d = wx.Dialog(None, -1, 'title') BANG - IDE crashes If I do this in PyShell... import wx d = wx.Dialog(None, -1, 'title') d.ShowModal() # Excellent - no problem! Thing is, it used to work! So I reinstalled PythonWin & wxPython - but still No Good. '******************* Errors when PythonWin crashes ************************* Faulting application pythonwin.exe, version 2.3.2.163, faulting module wxbase251uh_vc.dll, version 0.0.0.0, fault address 0x0003560a. Faulting application pythonwin.exe, version 2.3.2.163, faulting module mfc42.dll, version 6.0.8665.0, fault address 0x00001c65. From wweston at att.net Wed Apr 21 13:31:21 2004 From: wweston at att.net (wes weston) Date: Wed, 21 Apr 2004 17:31:21 GMT Subject: This is very simple question In-Reply-To: References: Message-ID: Eric wrote: > I would want to obtain a list of factors (multiples of 2) given a > prime number in python. > > For example 13=[8,4,1], 5=[4,1], 7=[4,2,1], 15=[8,4,2,1] > > I would appreciate a fuction which would do this. > > Eric Eric, To be less illustrative and somewhat more efficient. wes import math def ListOfPowersLessThan(n): list = [] i = 0 while True: x = int(math.pow(2,i)) if x <= n: list.append(x) else: break i += 1 return list TEST = [13,5,7,15,17,33] powers = ListOfPowersLessThan( max(TEST) ) powers.reverse() for x in TEST: sum = 0 list = [] for s in powers: if (sum + s) <= x: sum += s list.append(s) if sum >= x: break print x,list >>> 13 [8, 4, 1] 5 [4, 1] 7 [4, 2, 1] 15 [8, 4, 2, 1] 17 [16, 1] 33 [32, 1] >>> From d00roth at dtek.chalmers.se Wed Apr 14 23:05:05 2004 From: d00roth at dtek.chalmers.se (Daniel Roth) Date: Thu, 15 Apr 2004 05:05:05 +0200 Subject: 7bit to 8bit Message-ID: Hi all! seems like I've searched the whole net but still not found an answer to this question: how do one easy convert a 8bit-text, which by python seems to be in 7bit, to 8bit? I want to convert '=F6' to '?', '=E4' to '?' and so on. of course without doing a replace for all those characters. Daniel From peter at engcorp.com Tue Apr 6 15:05:01 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 06 Apr 2004 15:05:01 -0400 Subject: Richards bench benchmark In-Reply-To: <6748553f.0404060802.6e0d708c@posting.google.com> References: <6748553f.0403291446.27fb7b93@posting.google.com> <6748553f.0403300836.744e3e22@posting.google.com> <6748553f.0403302317.4595844@posting.google.com> <6748553f.0404060802.6e0d708c@posting.google.com> Message-ID: Duncan Lissett wrote: > Peter Hansen wrote in message news:... > > >>The code should be available with >> >> svn co svn://fortress.engcorp.com/public/bench >> >>I don't really expect anyone to check it out at this stage, but if you >>happen to have a free moment, I wouldn't mind knowing if subversion >>is properly visible through my firewall. > > > What do we use to browse that? Subversion, the replacement for CVS. See http://subversion.tigris.org/ for a start, and grab the command line version for whatever OS you are using and after an appropriate installation, the above command should grab the source into the "public/bench" folder under your current directory. There's also TortoiseSVN (integrated with Win Explorer shell) or RapidSVN from the same place. -Peter From sholden at holdenweb.com Thu Apr 29 15:42:20 2004 From: sholden at holdenweb.com (Steve Holden) Date: Thu, 29 Apr 2004 15:42:20 -0400 Subject: PYTHONSTARTUP and Cygwin In-Reply-To: <9c1c646f.0404291107.5a6137dc@posting.google.com> References: <9c1c646f.0404291107.5a6137dc@posting.google.com> Message-ID: <%Sckc.8205$f_5.1627@lakeread01> Dwi Sianto Mansjur wrote: > I tried to set up PYTHONPATH in cygwin but it doesn't work. > Any clue why ? > The following is my session. > > $ echo $PYTHONPATH > /home/Cherna/86_DevelopingTools:/home/Cherna/87_TestingCorpus > > $ echo $PYTHONSTARTUP > /home/Cherna/86_DevelopingTools:/home/Cherna/87_TestingCorpus > > $ python > Python 2.3.3 (#1, Dec 30 2003, 08:29:25) > [GCC 3.3.1 (cygming special)] on cygwin > Type "help", "copyright", "credits" or "license" for more information. > >>>>import sys >>>>sys.path > > ['', '/usr/lib/python23.zip', '/usr/lib/python2.3', > '/usr/lib/python2.3/plat-cygwin', '/usr/lib/python2.3/lib-tk', > '/usr/lib/python2.3/lib-dynload', '/usr/lib/python2.3/site-packages', > '/usr/lib/python2.3/site-packages/Numeric'] > > thanks. You probably forgot to export them to put them in the environment? $ export PYTHONPATH=/c/testwebapp:/c/Steve sholden at DELLBOY /c/testwebapp/views $ echo $PYTHONPATH /c/testwebapp:/c/Steve sholden at DELLBOY /c/testwebapp/views $ python Python 2.3.3 (#1, Dec 30 2003, 08:29:25) [GCC 3.3.1 (cygming special)] on cygwin Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> sys.path ['', '/c/testwebapp', '/c/Steve', '/usr/lib/python23.zip', '/usr/lib/python2.3', '/usr/lib/python2.3/plat-cygwin', '/usr/lib/python2.3/lib-tk', '/usr/lib/python 2.3/lib-dynload', '/usr/lib/python2.3/site-packages'] >>> Certainly works for me, anyhow ... regards Steve From gabriel.cooper at mediapulse.com Mon Apr 19 10:41:46 2004 From: gabriel.cooper at mediapulse.com (Gabriel Cooper) Date: Mon, 19 Apr 2004 10:41:46 -0400 Subject: equivalent to Java's toString()? Message-ID: <4083E52A.3030207@mediapulse.com> What is the python equivalent to java's toString()? When debugging I want to be able to basically be able to do this: print MyObjectInstance or print str(MyObjectInstance) and have it print out formatted output along the lines of: Object properties: Red=0 Yellow=0 Blue=255 currently I get something like this: In java it would look like this: class SomeClass { [...] String toString() { return new String("Object properties: Red=" + red + " Yellow: " + yellow + " Blue: " + blue); } } From mark at prothon.org Sat Apr 3 13:48:10 2004 From: mark at prothon.org (Mark Hahn) Date: Sat, 3 Apr 2004 10:48:10 -0800 Subject: Indent testers needed (Prothon) References: Message-ID: "Ville Vainio" wrote > Just allow both spaces and tabs, but not in the same block. This is a good idea. I could reset the flag for the indent type whenever the indentation goes to zero. I'll pitch this on the Prothon list. "rezed" wrote ... > I don't show visible tab marks in my editors, and I don't want to > have to, but if I don't, I haven't any good way to know whether a > piece of code contains tabs or spaces. Until I run it, at least. I agree this is a problem, but the whole problem we are trying to solve, that of mixed spaces and tabs, would cause you the same grief, or worse, right? From ods at strana.ru Fri Apr 16 11:24:48 2004 From: ods at strana.ru (Denis S. Otkidach) Date: Fri, 16 Apr 2004 19:24:48 +0400 (MSD) Subject: (For gurus) Embed functions in webpages like in PHP? In-Reply-To: Message-ID: On Fri, 16 Apr 2004, Thomas Guettler wrote: TG> The problem with caching: When is TG> the data outdate? TG> TG> You could use this approach: TG> Run a cron-job every hour which does the complicated TG> query which needs long to compute. Dump TG> the result into a file (Look for "pickle" TG> in the module index of the docs). TG> TG> Load this file for every request TG> and insert this into the template. Similar approach is used in QPS (http://ppa.sf.net/#qps), where static and semi-static pages are generated with cron job and/or on data update events. It is successfully used for several large (>2Gb of HTML files) heavy loaded (millions of requests/day) frequently udated (thousands of updates/day). Unfortunately it lacks documentation (at least in English) so you need to read source and ask for support in mail list. -- Denis S. Otkidach http://www.python.ru/ [ru] From claird at lairds.com Sat Apr 3 20:59:06 2004 From: claird at lairds.com (Cameron Laird) Date: Sun, 04 Apr 2004 01:59:06 -0000 Subject: simple popen question References: Message-ID: <106uqvaodeemo7a@corp.supernews.com> In article , Jim Benson wrote: . . . >> Also, Mr. Benson, are you *sure* you want to treat blank lines as >> end-of-message markers? >> > >Perhaps not...but it seems to work. It doesn't stop on >lines that contain only a '\n\0' for example. Hence >on the write side i can print out apparently blank lines.. >to make the reading of the output easier....and the >readline loop keeps piping them and only stops when the >executable stops. . . . You're right, I was wrong; I thought I'd spotted a common error, and didn't make the time to think carefully. Your usage *is*, in fact, consistent. I apologize for the confusion. -- Cameron Laird Business: http://www.Phaseit.net From reverse.ku.oc.issolok at nothypgnal.delrest.co.uk Wed Apr 28 11:34:42 2004 From: reverse.ku.oc.issolok at nothypgnal.delrest.co.uk (Paul Sweeney) Date: Wed, 28 Apr 2004 15:34:42 +0000 (UTC) Subject: sending an object - twisted or what? References: <20040427152051.50234c65.mutah@NOSPAM-libertysurf.fr> Message-ID: "Kyler Laird" wrote in message news:ucj4m1-5a5.ln1 at snout.lairds.org... > SSH is typically available (and already running as a daemon) on most > computers I touch these days. It would provide for the secure > transport needed. Any reason not to use it? > > --kyler It's quite likely this is going the way of xml-rpc over ssh. Good call, thx Paul From donn at u.washington.edu Mon Apr 12 17:15:58 2004 From: donn at u.washington.edu (Donn Cave) Date: Mon, 12 Apr 2004 14:15:58 -0700 Subject: How to kill a SocketServer? References: Message-ID: In article , "Jean-Pierre Bergamin" wrote: > ... The problem is the following: > The server waits for a connection and it calls in > SocketServer.TCPServer.handle_request() the function self.socket.accept(). > This call blocks until a connections is made. > > I have no chance to interrupt this call. I also tried: > > def stop_server: > self.socket.shutdown(2) > self.socket.close() > self.run_me = False > > The accept() call still won't get interrupted. :-( > > Other ideas? I seem to recall a very similar question last week, so you might look around to see what answers that one got. There was at least one that proposed a connection to the service. That makes a lot of sense to me, especially if you're in a position to change the service protocol if necessary. Donn Cave, donn at u.washington.edu From get at bent.com Mon Apr 12 19:29:33 2004 From: get at bent.com (nobody) Date: Tue, 13 Apr 2004 09:29:33 +1000 Subject: Non-math-geek needs help with CRCs (binascii.crc32) References: <4073c865$0$27642$61ce578d@news.syd.swiftdsl.com.au> <40751603$0$27643$61ce578d@news.syd.swiftdsl.com.au> <4076ff3d$0$27642$61ce578d@news.syd.swiftdsl.com.au> Message-ID: <407b2461$0$27644$61ce578d@news.syd.swiftdsl.com.au> > >> >Somehow, depending on how the numbers are massaged, the old code based on > >> >$EDB88320 is compatible with what the above site documents as $04C11DB7. > >> Did you notice that those two numbers are mirror images of each other? > >> Could just be a difference in interpretation. > > > >How does one get the same result with a reflected and non-reflected > >algorithm using the exact same input? > > Well, what I was saying was that perhaps the two algorithms are doing their > computations in the opposite order. It's just suspicious that they are > reflections of each other. Errr... according to the document referenced earlier, the reflected algorithm is due to hardware UARTs supplying the bits in reverse order, so hardware CRC implementations started doing their calculations in reverse, hence the back-arsewards $EDB88320 poly. However, pretty much every software based algorithm I've seen up to recently has been the reversed one.. with normal data.. so no need for the backwards poly.. so I dunno WTF is going on there. From reneaguirre at yahoo.com Fri Apr 30 14:48:03 2004 From: reneaguirre at yahoo.com (Rene Aguirre) Date: 30 Apr 2004 11:48:03 -0700 Subject: sending email notification Message-ID: <18e22d94.0404301048.35e0e701@posting.google.com> Hello, I'd like to make a sort of web tracking system for internal stuff at my office. But I'm having problems about how to add email notification to my script. I already tried to send email by using the 'email' module, with no success (the connection can't be stablished). I think my case is a very specific enviroment (may be very common): * Local /corporate intranet controlled through NTFS proxy. * I don't have access to a regular SMTP mail server, regular email access is through outlook email server, so, I'll have to send emai messages to the corporate outlook server. * Desktop / server enviroment is windows (if I make a cgi script the server where it'll run is a regular Windows XP machine here in the office running Apache). Any ideas, is it possible? Rene From remi at cherrypy.org Tue Apr 27 13:22:41 2004 From: remi at cherrypy.org (Remi Delon) Date: 27 Apr 2004 10:22:41 -0700 Subject: CherryPy-0.10 released Message-ID: <585c0de9.0404270922.16d849b8@posting.google.com> Hello everyone, I am pleased to announce the release of CherryPy-10. It's been a while since I last announced a CherryPy release on this newsgroup but a lot has happened since then: - The cherrypy.org site now has a nice forum and a wiki - Sessions are now fully thread-safe and they work great in production environments with the thread-pool HTTP-server - Jython compatibility has been restored - Lots of new HowTos have been added to the documentation, including one HowTo about best practices for deploying a demanding production website. - Plus many bugfixes and improvements ... ------------------------------------------ About CherryPy: CherryPy is a Python based web development toolkit. It provides all the features of an enterprise-class application server while remaining light, fast and easy to learn. CherryPy allows developers to build web applications in much the same way they would build any other object-oriented Python program. This usually results in smaller source code developed in less time. Remi. http://www.cherrypy.org From alexanro at stud.ntnu.no Wed Apr 14 09:22:42 2004 From: alexanro at stud.ntnu.no (Alexander Rødseth) Date: Wed, 14 Apr 2004 15:22:42 +0200 Subject: Pygame Message-ID: Hi! Why isn't Pygame a part of Python? Cheers, Alexander R?dseth From timr at probo.com Fri Apr 2 18:36:29 2004 From: timr at probo.com (Tim Roberts) Date: Fri, 02 Apr 2004 15:36:29 -0800 Subject: address a port References: <9eabe547.0403232100.501b8bbe@posting.google.com> <9eabe547.0403242038.4e453ae3@posting.google.com> Message-ID: <2ptr6098oj0kih7b215lfrs8hng2177oqd@4ax.com> Dennis Lee Bieber wrote: >On Thu, 25 Mar 2004 23:34:08 -0800, Tim Roberts >declaimed the following in comp.lang.python: > > >> For the 16-bit systems (Win98 and Win95), you can use the VERY handy >> ctypes.py module to call the inp/inpw/inpd/outp/outpw/outpd APIs in >> MSVCRT.DLL. >> > Pardon? W9x /is/ 32-bit... The last 16-bit was WfW3.11 You have been seduced by Microsoft's marketing. I put it the way I did partly to be a smart-aleck, but what I said is largely true. The core of Windows 98 is not substantially different from Windows for Workgroups plus Win32s. USER and GDI (and GDI drivers, like displays and printers) are still 16-bit DLLs. When a 32-bit process calls a USER or GDI API, it thunks to the 16-bit side to execute. > Oh, and ME is also a W9x variant. Yes, a very slightly modified version of Win98SE, and not necessarily improved: in my opinion, Win98SE was the best of that product line. > But yes, the NON-NT systems, to support old MS-DOS programs and >games, did allow applications to do direct hardware port addressing. There's more to it than that. Display drivers in 95/98/ME are plain, ordinary, user-mode, 16-bit DLLs. In order to allow display drivers to work, the system MUST allow user-mode processes to touch I/O ports. >There are a number of library/driver utilities around that allow NT >systems to access the ports -- with the overhead, usually, of DLL calls. Yes, PLUS a transition to kernel-mode and back for each transfer. It is painful. There are also a couple of slimy drivers that alter the I/O port permissions mask, thereby eliminating the kernel-mode transition, but they rely on undocumented structures. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From nospam at nospam.com Mon Apr 12 13:31:19 2004 From: nospam at nospam.com (Mark Tolonen) Date: Mon, 12 Apr 2004 10:31:19 -0700 Subject: Problem with dates and daylight savings... References: Message-ID: "John Taylor" wrote in message news:c5ebq7$nls$1 at cronkite.cc.uga.edu... > I was wondering if some one could explain this anomaly. I wrote a program to add/subtract > dates. For example, > > ./ComputeDay.py 2004/04/12 -7 %Y/%m/%d > 2004/04/05 > > Here is the anomaly.... > ./ComputeDay.py 2004/04/12 -8 %Y/%m/%d > 2004/04/03 > > I would have thought this would have returned the 4th. I have a feeling that daylight savings > has something to do with this, as the time changed on the 3rd. > Can someone explain this? How can I correct this problem? > > ./ComputeDay.py 2004/04/12 -9 %Y/%m/%d > 2004/04/02 > > > > Thanks, > -John > > > Here is the code: > > #!/usr/bin/env python2 > > ## > ## ComputeDay.py > ## John Taylor, Apr 12, 2004 > ## > > import time > import sys > > ############################################################################ > > def Usage(): > print > print "Usage: %s [ t1 ] [ n ] [ format string ]" % sys.argv[0] > print "Given arguments t1 and n, where n is a positvie or negative number," > print "return the date +/- t1" > print """format should be a date format string, such as: %Y/%m/%d""" > print "See the man page for strptime for formatting options" > print > print "Example:", sys.argv[0], "2004/03/01 -1 %Y/%m/%d" > print > sys.exit() > > > ############################################################################ > > def main(): > if len(sys.argv) != 4: > Usage() > > fmt = sys.argv[3] > > try: > t1 = time.strptime(sys.argv[1], fmt) > except ValueError, e: > print "Error for t1: ", e > return > > try: > n = int(sys.argv[2]) > except ValueError, e: > print "Error for n: ", e > return > > oneday = 60 * 60 * 24 * 1.0 > diff = time.mktime(t1) + (n * oneday) > diff = time.localtime(diff) When crossing a daylight savings boundary an hour is added or subtracted. If you display diff at this point, you can see the error: >>> diff (2004, 4, 3, 23, 0, 0, 5, 94, 0) It is 2004/4/3 11:00pm instead of 2004/4/4 12:00am. One thing the time.mktime() will do is normalize an invalid date/time specification. In C it will correct the structure passed to it, but in Python you have to call time.localtime() to see the correction. If you subtract the number of days directly from the date field the time will be corrected for you. Example: >>> t1 = list(time.strptime("2004/4/12","%Y/%m/%d")) >>> t1 [2004, 4, 12, 0, 0, 0, 0, 103, -1] # 2004/4/12, 103rd day of year, DST unknown >>> t1[2] -= 8 >>> t1 [2004, 4, 4, 0, 0, 0, 0, 103, -1] # 2004/4/4, invalid weekday and yearday, DST unknown >>> time.localtime(time.mktime(t1)) # mktime normalizes values (2004, 4, 4, 0, 0, 0, 6, 95, 0) # 95th day of year, standard time >>> t1[2] -= 8 # another 8 days earlier >>> t1 [2004, 4, -4, 0, 0, 0, 0, 103, -1] # date, weekday, yearday invalid. DST unknown >>> time.localtime(time.mktime(t1)) # normalize (2004, 3, 27, 0, 0, 0, 5, 87, 0) # 2004/3/27, 87th day of year, standard time. Mark > > try: > result = time.strftime(fmt, diff) > except ValueError, e: > print "Error for result: ", e > return > > print "%s" % ( result ) > > ############################################################################ > > main() > > > -- end of code > From kfast at poczta.onet.pl Thu Apr 29 04:36:30 2004 From: kfast at poczta.onet.pl (Jakub Fast) Date: Thu, 29 Apr 2004 10:36:30 +0200 Subject: sorting a list In-Reply-To: References: <17i4tmtsfvae9$.dlg@thorstenkampe.de> Message-ID: <4090BE8E.7090300@poczta.onet.pl> >>>I want to sort a list. [...] >>>But I am actually looking for an output: >>>['A','a','D','F','f'] >>> >>>Is there any module to sort a list this way? Sean Berry wrote: >>>>a = ['A', 'D', 'F', 'a', 'f'] >>>>a.sort(lambda x, y: cmp(string.lower(x), string.lower(y))) >>>>a > > ['a', 'A', 'D', 'f', 'F'] > > this will work too, if lower can come before upper. > > > If you feel adventurous, try the new sort() in Python 2.4. Here's the doc: http://www.python.org/dev/doc/devel/whatsnew/node5.html Also note that the DSU way will probably be faster than the "general" solution (?). Kuba From toby at rcsreg.com Fri Apr 9 11:14:36 2004 From: toby at rcsreg.com (Tobiah) Date: Fri, 09 Apr 2004 15:14:36 GMT Subject: regex help for a newbie In-Reply-To: References: Message-ID: > > I have the following string in my program: > > string= "aaa%(BBB%(CCC)BBB)aaa%(DDD)aaa" > > Now I need to extract the parts that are enclosed in %(). #!/usr/bin/python ### I realize that this will not serve you in all of the cases ### that you are likely to need to handle, but just to show ### that the case that you mention can be handled with regular ### expressions, I submit the following: import re string = "aaa%(BBB%(CCC)BBB)aaa%(DDD)aaa" m = re.search('([^%]*)%\(([^%]*)%\(([^)]*)\)([^)]*)\)([^)]+)%\(([^)]*)\)(.*)', string) print (m.groups()) ### This yields: ### ### ('aaa', 'BBB', 'CCC', 'BBB', 'aaa', 'DDD', 'aaa') ### ### ### ### Tobiah From jcarlson at uci.edu Mon Apr 5 19:23:13 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Mon, 05 Apr 2004 16:23:13 -0700 Subject: Module import problems In-Reply-To: <30260531.0404051335.27cabd5d@posting.google.com> References: <30260531.0404041725.746befa0@posting.google.com> <30260531.0404051335.27cabd5d@posting.google.com> Message-ID: > I had to resort to "from login import *" in main.py and then "import > wx" (and other modules like urllib/webbrowser etc) in login.py and it > all seems to work. Sounds ugly. I would stick with... #in main.py import login import wx #in login.py and others... import wx > I didn't occur to me that I'd have to import the modules used in each > module file, I thought it would work just from the parent (main.py) > file. You were misunderstanding modules, namespaces, etc. > I've also stopped myself from calling classes instead of defs (I had > the whole class in the __init__ def previously) and removed most of my > global variables. What do you mean "calling classes"? Show an example of what you were doing before, and what you are doing now, and I'm sure someone will tell you which is more "Pythonic" and/or which is a better design. > Now I have twelve 1-6Kb files like login.py, plus an 18Kb main.py, > instead of one 38Kb main.py to grep through! > > So it was worth the struggle to clean up a bit.... Congrats. - Josiah From rmb25612 at yahoo.com Mon Apr 12 15:58:06 2004 From: rmb25612 at yahoo.com (Richard James) Date: 12 Apr 2004 12:58:06 -0700 Subject: pythonwin crash (used to work) - please help quick. References: <5Reec.62668$Id.61067@news-binary.blueyonder.co.uk> Message-ID: <2c60f0e0.0404121158.1b79a3fc@posting.google.com> "Stevie_Mac" wrote in message news:... > I think seen somthing like this on net somewhere when i was searching. > > So if I understand this, a python GUI can't debug a script that uses code > from any other GUI implementation (like wx for example)? > > If so, dang! Whats my options - different IDE - or - no debug! > > wait, im sure when I tried to run the script direct (through python and > pythonw) it still bombed - but in pyShell it didn't - hows that? > > Stevie_Mac :confused: > If you are still desperate and can't find something and if you don't mind using old fashioned print statements to debug your code. I like to use the SciTE editor. http://www.scintilla.org/SciTE.html A nice version by Bruce Dodson with Windows Installer and extra tools. http://gisdeveloper.tripod.com/scite.html You enter your code in one panel, press F5 to run, and Scite captures the program's print statement output and Python errors in a second panel. Edit code errors and repeat. Note: Press Shift F5 to clear output panel. -- R.J. From python at rcn.com Thu Apr 15 22:03:36 2004 From: python at rcn.com (Raymond Hettinger) Date: 15 Apr 2004 19:03:36 -0700 Subject: Automatic, portable optimization of global access References: <5d83790c.0404150721.46a3b5d0@posting.google.com> <7xvfk17zeg.fsf@ruckus.brouhaha.com> Message-ID: <5d83790c.0404151803.598c1807@posting.google.com> [Raymond Hettinger] > > FWIW, I've posted a brief, but powerful recipe for a bytecode > > optimization that saves known globals as constants [Paul] > This looks important and will clean up a lot of code, but what happens > if the function calls exec or eval, or assigns something into > globals(), or whatever? Quoth the recipe: """ Binding should be applied selectively to those functions where speed is important and dynamic updates are not desired (i.e. the globals do not change). In more dynamic environments, a more conservative approach is to set builtin_only to True so that only the builtins get optimized (this includes functions like len(), exceptions like IndexError, and constants like True or False). """ Raymond From luis_ at iname.com Thu Apr 8 19:05:40 2004 From: luis_ at iname.com (Lupe) Date: Fri, 09 Apr 2004 00:05:40 +0100 Subject: maximum length of a list & tuple Message-ID: hi, I'm finishing a small program which uses recursion for less than 100 levels. Each time the function is called, it compares an element of a list (which is a list too) to other elements, which all amounts to millions of comparisons. The program is working for short lists but not for longer ones. I think there are two possible problems: either disk space is not enough to save lists as the program is executed or there is a finite manageable list lenght that is reached by the program. hence my question: is there a limit? which one? I'm using list.append() what about for tuples? I'll rewrite that part of the code and will overcome the problem, since I only need a few elements of the list generated, but I'm still curious about the answers Thanks in advanve Lupe From james at ractive.ch Thu Apr 15 15:12:15 2004 From: james at ractive.ch (Jean-Pierre Bergamin) Date: Thu, 15 Apr 2004 21:12:15 +0200 Subject: Socket error: 10053 software caused connection abort References: <407eda4e$0$576$e4fe514c@news.xs4all.nl> Message-ID: Hi Irmen >> I'm getting an error on Windows XP when I send big data chunks over >> a socket connection. The exception I get is: "socket.error: (10053, >> 'Software caused connection abort')" >> This happens in the socket.recv function. > > I have the same error here, and it is NOT because of a bug in > Windows' TCP stack. (even though the problem does not occur on Linux). > > The problem is in your code. > > You are receiving chunks of data like this: > [....] > But this code is flawed: recv() CAN return less than block_size, > *even* if there is more data to be read on the socket. > > So, you should not check if the length of the received chunk > is less than the length argument passed to recv(). > > Instead, you should count the total number of bytes you > received and check that with the expected total amount. But how can I know the amout of data I will receive? There's no way to do that, since it's totally random how large the sent data will be. Could you show me how you did it? Thanks James From tzot at sil-tec.gr Wed Apr 21 08:05:00 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Wed, 21 Apr 2004 15:05:00 +0300 Subject: CamelCase versus wide_names (Prothon) References: <407ec022$0$54153$1b2cd167@news.wanadoo.nl> Message-ID: On Thu, 15 Apr 2004 11:05:29 -0700, rumours say that "Mark Hahn" might have written: >Users on the Prothon mailing list were asking me (I'm the BDFL there) If I may add a humourous note: you're the BCPFL of Prothon (Benevolent Council President For Life), since, in the few months that Prothon exists, you probably have asked the opinion of your current and potential users more times than Guido did in the whole Python's existence... Prothon is not a dictatorship for sure :) Seriously: It's good that you want to please as many as you can, and I am sure --without checking-- that initially Guido did that too for Python; I'm also sure that this process led him to many decisions that he later regretted. I can guess that there are matters over which you don't bother deciding (eg identifier case), but you'll have to be more firm and decisive, I hope you know that... -- TZOTZIOY, I speak England very best, Ils sont fous ces Redmontains! --Harddix From andymac at bullseye.apana.org.au Wed Apr 7 09:52:18 2004 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Wed, 7 Apr 2004 23:52:18 +1000 (EST) Subject: python thread scheduler? In-Reply-To: References: Message-ID: <20040407234459.F4163@bullseye.apana.org.au> On Wed, 7 Apr 2004, project2501 wrote: > this suggests to me that the barrier i'm hitting is the python thread > schedular, not the server software being tested. As Python uses native OS threads, it doesn't have its own thread scheduler. What you might be seeing is an effect of the number of bytecode instructions executed between the Global Interpreter Lock (GIL) being released/reacquired by a particular thread - see sys.setcheckinterval(). -- 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 noemail at noemail4u.com Wed Apr 14 07:36:18 2004 From: noemail at noemail4u.com (Dang Griffith) Date: Wed, 14 Apr 2004 11:36:18 GMT Subject: Best IDE? References: <4ace7f9f.0404111147.3120288a@posting.google.com> Message-ID: On Tue, 13 Apr 2004 18:11:05 GMT, asdf sdf wrote: ... >Check out Visual SlickEdit from Slickedit.com. > >I would say this is an editor rather than an IDE. But it is certainly >an IDE if vi is one. > >It emulates several other editors, including vi. It can generate tag >libraries, supporting autocomplete and function help for numerous >languages with syntax coloring. It can run build scripts. Available on >multiple platforms. It is scriptable and extensible. > >Too many features to mention. If anyone can suggest a tool that is as >powerful, that is not specific to a single language, please mention it. > >Python, Javascript, HTML, C, C++, Perl, Java, TCL, ksh, bsh, COBOL, >CFML, PL/SQL, PHP, Fortran, ADA ... > >It must have support for 50 languages. CodeWright, now available from Borland. AFAIK, it's feature compatible with Visual SlickEdit, though I think it's available only on multiple Windows platforms. ;-) --dang From lbates at swamisoft.com Tue Apr 27 10:16:13 2004 From: lbates at swamisoft.com (Larry Bates) Date: Tue, 27 Apr 2004 09:16:13 -0500 Subject: How Would You Do: Parsing and Expression Evaluation References: <108rren1js1hn71@corp.supernews.com> Message-ID: I may not be understanding what you want to do but here goes: You might just want to use eval() function and have the expression evaluated by Python. That way your expression could be any Python expression and you don't have to parse the expression at all (e.g eval parses and executes it and returns the value). You also don't have to "translate" the formulas. They are already Python expressions. Python expression syntax is pretty much like what you would want. Larry Bates Syscon, Inc. "Al Christians" wrote in message news:108rren1js1hn71 at corp.supernews.com... > I've got an idea for an application, and I wonder how much of what it > takes to create it is available in open source python components. > > My plan is this -- I want to do a simple spreadsheet-like application: > I've used a wxGrid, so I expect that wxPython will do fine for the user > interface. The spreadsheet can be organized vertically, one item per > line. It might need no more than 100 rows or so. On each line, the > user will enter in one column an item (variable) name and, in another > column, a formula or expression for computing the item's value. A > third column will show the computed value. There will usually be some > circular references between the items, but their values will converge > quickly with repeated evaluation. > > The final feature is a button that the user can click when they have the > sheet set up correctly -- it will translate the formulas into simple C > and python code to perform the same calculations as the spreadsheet. > > The formulas should be pretty easy -- add, subtract, multiply, divide, > log, exponential, and perhaps some user-defined functions. > > Are there any off-the-shelf python libraries that would make this kind > of app much easier? I don't have any special experience related to such > things, so I surely don't want to re-invent the wheel out of pure > ignorance -- should I try the parsing tools in the standard python > library, or will something else work better for me? > > TIA for any advice, > > > Al From peter at engcorp.com Sat Apr 17 12:39:22 2004 From: peter at engcorp.com (Peter Hansen) Date: Sat, 17 Apr 2004 12:39:22 -0400 Subject: Creating function object from text In-Reply-To: <40815ab3$0$16479$61fed72c@news.rcn.com> References: <40815ab3$0$16479$61fed72c@news.rcn.com> Message-ID: Edward C. Jones wrote: > Suppose I have a piece of text that defines a function: > > text ="""\ > def fun(i): > return i + 2 > """ > > How do I turn this into a function object, f, which can be called or > passed around? exec text If you need to do this other than in the global namespace of the module, read up on the exec statement and how you can pass in a dictionary of your own. -Peter From t-meyer at ihug.co.nz Mon Apr 5 21:10:31 2004 From: t-meyer at ihug.co.nz (Tony Meyer) Date: Tue, 6 Apr 2004 13:10:31 +1200 Subject: How to do [1]*4 for a tuple In-Reply-To: <1ED4ECF91CDED24C8D012BCF2B034F1305CE43B2@its-xchg4.massey.ac.nz> Message-ID: <1ED4ECF91CDED24C8D012BCF2B034F1304677BD5@its-xchg4.massey.ac.nz> > I'm not sure I understand why [1]*4 and (1)*4 work differently? [1]*4 > results in [1, 1, 1, 1] while (1)*4 results in 4. (1) isn't a tuple, it's a 1 in parentheses. >>> (1) * 4 4 >>> (1,) * 4 (1, 1, 1, 1) =Tony Meyer From goodger at python.org Mon Apr 5 14:23:57 2004 From: goodger at python.org (David Goodger) Date: Mon, 05 Apr 2004 14:23:57 -0400 Subject: query regarding OOP functionality in python In-Reply-To: <407153BD.9080203@students.iiit.net> References: <407153BD.9080203@students.iiit.net> Message-ID: <4071A43D.6050607@python.org> Vardhman Jain wrote: > Could someone tell me, what kind of polymorphisms does python > allows? According to FOLDOC (http://foldoc.doc.ic.ac.uk): In object-oriented programming, the term [polymorphism] is used to describe a variable that may refer to objects whose class is not known at compile time and which respond at run time according to the actual class of the object to which they refer. Python fully supports this definition of polymorphism. Python also supports "ad-hoc polymorphism" (a.k.a. operator overloading), and parametric polymorphism, as described on the FOLDOC page for "polymorphism". > Does it allow multiple functions with same name and different > arguments? No, Python does not support "function overloading". > Does it allow multiple functions with same name but > different return types. No. Python only allows one object to be bound to a name at a time. A single function may return multiple different types if it wishes though. > I have tried this with constructors and failed, > So I suppose I might need to compile the code or something like > that to gain this feature if it exists. Won't help. Python is a simple language, with little implicit magic. There is no support for what you are describing in the language, no matter how you compile it. > I know it allows default values to function arguments but that is > not sufficient for my purpose. You're approaching Python with a C++/Java mindset. Don't do that. If you try Python seriously, you'll find that you don't really need these features. If you absolutely must have these features, stick to C++ or Java. -- David Goodger From Mike at DeleteThis.Geary.com Sat Apr 3 18:27:25 2004 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Sat, 3 Apr 2004 15:27:25 -0800 Subject: Indent testers needed (Prothon) References: <2Msbc.136673$cx5.2385@fed1read04> <106tqq5e6gn8aaf@corp.supernews.com> Message-ID: <106ui2vl86a617@corp.supernews.com> > > I could write a long Python program that uses no functions, classes, or > > anything else to break it into smaller understandable pieces. Just one big > > long piece of code that is indented to twenty levels. While I'm at it, I'll > > use variable names that obscure what the code does. > > > > Does that imply that there should be a maximum length to a Python source > > file, a limit on the level of indenting, and restrictions on what variable > > names I can use? Of course not. > You're going a few steps beyond what I was saying. I stated that it > makes sense to discourage ugly code. The code that you are describing > is functionally impossible to maintain (unless it was generated by > inlining all module-level function calls, something that you, I, or > anyone else could technically do, or even write a program to do). I > think that by people using Python (or in this case Prothon), by > definition it is implied that we should be writing maintainable code. Oh man, you caught me there: I used a strawman to argue against your strawman! :-0 > Personally, I don't find implicitly continued lines to be more > maintainable than explicitly continued lines, and because explicit > continuations (with '\') do the job already, if this were Python, it > would violate both the "flat is better than nested" and "there should be > one-- and preferably only one --obvious way to do it" zens. I don't see how automatic continuation violates "flat is better than nested". When I use \ continuation in Python, I indent the continuation lines anyway--I don't usually put them at the same level as the first line. foo = \ bar() not foo = \ bar() (Obviously, I wouldn't use line continuation at all in that specific code--it's just an illustration.) Python has already broken the "one way to do it" and "explicit is better than implicit" zens on this anyway, by allowing both explicit (\) and implicit (parens, brackets, braces) continuation. > As for whether Mark wants to follow the Zen of Python, that is up to > him. However, considering that he's using the c.l.py newsgroup to > discuss Prothon, using a very large portion of the syntax of Python, and > has talked about translating a large portion of the standard library of > Python to Prothon via some sort of automatic method, I would say that > violating the Zen is a foolish "early optimization". Mark has talked about dropping \ continuation from Prothon, but your point about converting Python libraries may convince him not to--or to make sure that any automatic translator handles this conversion. Anyway, I rather like the automatic line continuation. It doesn't seem to me that it would encourage people to write unreadable code when they would otherwise write readable code, and it seems cleaner than \ continuation. But I'd be happy enough with either, especially considering that I don't continue lines that often anyway--I'm more inclined to split up a long statement when I can. Thank goodness Python doesn't use curly braces like C and C++. That way we can argue about spaces and tabs and line continuation instead! ;-) -Mike From __peter__ at web.de Mon Apr 19 10:07:20 2004 From: __peter__ at web.de (Peter Otten) Date: Mon, 19 Apr 2004 16:07:20 +0200 Subject: Tkinter Button command query References: Message-ID: Paul A. Wilson wrote: > I'm new to Tkinter programming and am having trouble creating a > reusable button bar... I want to be able to feed my class a dictionary > of button names and function names, which the class will make. > > My button bar is implemented a Frame subclass, which takes the button > dictionary as an argument and displays the buttons on the screen: > > class OptionsBar(Frame): > def __init__(self, buttonDict, parent=None) > Frame.__init__(self, parent) > parent.someFunction() # This works fine > for (name, command) in buttonDict.items(): > Button(self, text=name, command=command).pack(side=TOP, > fill=BOTH) > > and then another Frame subclass, e.g. MyWindow, uses the bar as > follows: > > self.buttonDict = {'Button1':'someFunction', > 'Button2':'otherFunction'} > ... > myBar = OptionsBar(parent=self, buttonDict=self.buttonDict) > myBar.pack(side=RIGHT) > ... > > def someFunction(): > do button stuff > > My problem is that the Button instances aren't calling the correct > functions when pressed. Is there anyway I get Button to call its > parent frame's parent frame's functions? I've tried using > > self.buttonDict = {'Button1':'parent.someFunction', > 'Button2':'parent.otherFunction'} > > but to no avail. Hope my explanations make sense. > > Any suggestions? Use the function identifier directly instead of a string to identify the commands, e. g: import Tkinter class OptionsBar(Tkinter.Frame): def __init__(self, buttonDict, parent=None): Tkinter.Frame.__init__(self, parent) parent.someMethod() # This works fine only if parent is not None for (name, command) in buttonDict.items(): Tkinter.Button(self, text=name, command=command).pack(side=Tkinter.TOP, fill=Tkinter.BOTH) def aFunction(): print "a function" class MyWindow(Tkinter.Frame): def __init__(self, parent): Tkinter.Frame.__init__(self, parent) self.buttonDict = {'Button1': self.someMethod, 'Button2': aFunction} #... myBar = OptionsBar(parent=self, buttonDict=self.buttonDict) myBar.pack(side=Tkinter.RIGHT) #... def someMethod(self): print "some method" root = Tkinter.Tk() MyWindow(root).pack() root.mainloop() You can pass self.someMethod around as if it were a function. Python will take care that the method is invoked with the instance denoted by self. Note how I changed e. g. Button to Tkinter.Button. As you are already creating reusable components you should also start to care about namespace cluttering. If you are too lazy to type Tkinter in full beauty, use an alias import Tkinter as tk and then tk.Button() etc. Peter PS: Do us - and yourself - the favour of using *4*-space indents. The more people use it as a standard, the better you can tuck pieces of code from different sources together. From michael at foord.net Fri Apr 9 10:34:44 2004 From: michael at foord.net (Fuzzyman) Date: 9 Apr 2004 07:34:44 -0700 Subject: CGI Problems With Xitami References: <8089854e.0404072356.7f33f440@posting.google.com> Message-ID: <8089854e.0404090634.34d3f2b7@posting.google.com> Dang Griffith wrote in message news:... > On 8 Apr 2004 00:56:59 -0700, michael at foord.net (Fuzzyman) wrote: > > >All of a sudden the 'POST' method has stopped working - when I specify > >'POST' as the method in forms... the CGI gets no data... and I really > >don't want to use 'GET' as it makes the password visible in the URL... > > > >I've looked in the CGI options of the Xitami config and I can't find > >anything amiss, or even especially relevant. The Xitami docs say > >'POST' should work fine (of course they don't mention python). > > > >Anyone any suggestions or experience. > >(Yes I've checked the form construction in the hTML templates - it's > >fine. The values don't even make it to Fieldstorage...) > > Try capturing the generated HTML source and run it through TidyHTML. > > http://tidy.sourceforge.net/ > http://www.w3.org/People/Raggett/tidy/ > > It could be something in that page is causing the browser not to post > the data. > > --dang Will try it - Thanks Regards, Fuzzy http://www.atlantibots.org.uk/pythonutils.html From peter at engcorp.com Tue Apr 6 06:55:40 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 06 Apr 2004 06:55:40 -0400 Subject: ANNOUNCE : dataenc.py and Pythonutils In-Reply-To: <8089854e.0404052348.15e3a04e@posting.google.com> References: <8089854e.0404052348.15e3a04e@posting.google.com> Message-ID: Fuzzyman wrote: > http://www.voidspace.org.uk/atlantibots/pythonutils.html > > Various Python Resources > > Dateutils : > Version 1.0.2 > > This is a set of functions for dealing with dates - written for a > little tool called 'Victory Days'. They are particularly useful for > dealing with appointments - e.g. the second Tuesday in March etc... > > The functions will tell you what day of the week a date is, work out > the 'Julian day number' of a date is, correctly add numbers of days > (weeks, months etc) to a date and tell you the number of days between > a date, format a datestring etc. Full correction for leap years and > much more. No tests? :-( How do you know it works? -Peter From wroozee at hotmail.com Tue Apr 6 11:05:47 2004 From: wroozee at hotmail.com (Wroozee) Date: 6 Apr 2004 08:05:47 -0700 Subject: Calling python module in cgi script Message-ID: <77516416.0404060705.1f671d90@posting.google.com> hi, I am pretty new to python and i came up with this problem. What i'm trying to do is call a python module from my cgi script, which is inovked by a html form. First the cgi script gets a value from the form and sends it to the python module which takes that value and processes it and sends the result back to the cgi script which again processes it and show the result.How do i do that? Any suggestion is greatly appreciated. Thanks, Wroozee PS: I can post my code if anyone wants to see it. From project5 at redrival.net Tue Apr 27 14:47:42 2004 From: project5 at redrival.net (Andrei) Date: Tue, 27 Apr 2004 20:47:42 +0200 Subject: Trying to write comments after escaping newline References: Message-ID: <25x8uhesk1iz$.1n7qy34n2fdhy.dlg@40tude.net> p brian wrote on Tue, 27 Apr 2004 19:38:14 +0100: > Weirdly enough i do not think I have come across this before. Perhaps I do > not use enough comments.... > > mystring = "hello " + someVariable + \ > "multiple lines 4 clarity" + \ > someothervariable Concatenating strings is not very efficient, you should avoid it. > The above works , but if I add comments > > mystring = "hello " + someVariable + \ #comment > "multiple lines 4 clarity" + \ #comment > someothervariable #comment > > it stops working because instead of escaping a newline I am now just > escaping a space or tab. '\' is not an escape char if it's not inside a string - and it isn't in this case, since there's no quotes around it. Plus you can't escape spaces/tabs anyway, since "\ " simply means "backslash followed by space", which when printed shows up as '\\ '. In this case it's a line continuation character, meaning that you're saying "this line ends here, but pretend it continues on the next one"... and then you try to fool the parser by not making that line end there after all. A different way to do this could be: mystring = "hello %s multiple lines 4 clarity %s" % \ (somevariable, someothervariable) -- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5 at jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From ryanlowe0 at msn.com Tue Apr 27 18:09:00 2004 From: ryanlowe0 at msn.com (Ryan Lowe) Date: Tue, 27 Apr 2004 22:09:00 GMT Subject: parallel for loops Message-ID: <0SAjc.12421$Gd3.3093654@news4.srv.hcvlny.cv.net> maybe its just me, but the behavior of parallel lists in for loops seems backwards. why doesnt it mirror parallel assignment? i think tuple-unpacking should take precedence, but instead iteration happens along the first dimension and unpacking comes second, forcing the use of zip. >>> a, b = [1,2,3], [4,5,6] # a = [1,2,3], b = [4,5,6] >>> for a, b in zip([1,2,3], [4,5,6]): print a, b instead of: >>> for a, b in [1,2,3], [4,5,6]: print a, b # illegal im sure there is a good reason why the former was chosen, and i know its way too late to switch, but i cant think of many examples of when you would use parallel iteration *without* zip. not even dictionaries since you have to use .items() anyway (another thing that should be default in my mind). of course, using zip is no big deal but im just curious, from a design perspective why the choice was made. From imbosol at aerojockey.com Wed Apr 28 18:59:45 2004 From: imbosol at aerojockey.com (Carl Banks) Date: 28 Apr 2004 15:59:45 -0700 Subject: Is Perl *that* good? References: <108v74768o9sb9f@corp.supernews.com> Message-ID: <60dfb6f6.0404281459.21675af4@posting.google.com> claird at lairds.com (Cameron Laird) wrote in message news:<108v74768o9sb9f at corp.supernews.com>... > In article , > Carl Banks wrote: > . > . > . > >If you do stuff recursively (as I often do) or break up code into > >smaller functions (as I often do) so that the functions with these > >regexps get called numerous times, it can help performance to move the > >compile step out of the functions. > > > >The point is, the existence re.compile encourages people to make > >regexp objects global so they only need to be compiled once, when the > >module is loaded. Because of this, and especially because regexps are > >prone to being used in recursive functions and such, it's dangerous to > >allow them to have state. > . > . > . > I wrote the subject line for this subthread. Here's > my provisional conclusion: my past attempts to track > down claims of the "Perl is tops for string-handling" > sort generally reinforced the proposition that the > speaker simply meant, "Perl privileges REs" (and that > the speaker had no familiarity with Python, let alone > Icon or Prolog). Now I see there's a likelihood of > definite attraction to the hidden-variable, dangerous > implicitness goop so characteristic of Perl. That's > good to understand. Thanks, Carl; good analysis. In file x.pl: sub muck() { $_ = "sucker\n"; } while(<>) { if (/^abc/) { muck(); print $_; } } Command line: echo abcdefg | perl x.pl Output: sucker I had actually thought it restored $_. It never ceases to amaze me how bad Perl is. -- CARL BANKS From pedronis at bluewin.ch Mon Apr 19 09:49:25 2004 From: pedronis at bluewin.ch (Samuele Pedroni) Date: Mon, 19 Apr 2004 15:49:25 +0200 Subject: [Python-Dev] PEP 329: Treating Builtins as Constants in the Standard Library In-Reply-To: <00cb01c4260d$80b9b120$e841fea9@oemcomputer> Message-ID: <5.2.1.1.0.20040419154633.02d12be8@pop.bluewin.ch> At 08:54 19.04.2004 -0400, Raymond Hettinger wrote: >Comments are invited on a new pep: > > http://www.python.org/peps/pep-0329.html > > > >Based on feedback received so far, there were several changes to the >original draft: > >* The module is public > >* The module name reflects its nature as a bytecode hack > >* There is a flag to disable binding > >* Added summaries of how it works, when it is called, and the effect on >startup time (near zero). > >* Included a reference to Jython FAQs supporting the means for >automatically doing nothing in environments without bytecodes. Raymond, could you please try to tame your speed obsession without devising even more hacks and pissing in other people's pool. Thanks. From agriff at tin.it Mon Apr 26 16:17:37 2004 From: agriff at tin.it (Andrea Griffini) Date: Mon, 26 Apr 2004 20:17:37 GMT Subject: About generators References: Message-ID: <7eoq80ph28cbjj06hp2llab8acnsh2fmnc@4ax.com> On Mon, 26 Apr 2004 09:42:18 -0400, Peter Hansen wrote: >Google Groups is always helpful for such questions: > >http://groups.google.com/groups?q=integer+range+syntax&meta=group%3Dcomp.lang.python.* > >This leads to various threads, such as the "Re: Thoughts on PEP284" >which had the same proposal as yours and what is, I believe, an >adequate reason for rejecting it. Thanx for the pointer, but I wasn't able to find a discussion about the use of a "normal" range binary operator; I found things like for x in 0<= x < 10: for x in 10: for x in integers[0,1,...,10]: for x in integers[0:10]: I personally find all those forms not better than (x)range; the first one looks a test, not a definition of an iteration and in math it doesn't imply any order, the others are at least as obscure to me as (x)range. Something that would be very similar to what is used in math is probably for x in 1...10: May be it's my math background, but I find things like squares = [x*x for x in 1...100] quite readable And yes, I also used to write a lot of Pascal code so the ".." is more natural to me (I've also to confess that I use PERL, even if this probably means I'll be mailbombed from readers of this NG ;-) ). But in math three are used, and the three-dot ellipsis is already present in Python (even if I've still to understand what's used for); so asking by using the three-dot one seemed more correct to me. To me it's very strange that the "range operator" approach hasn't been discussed at least as much as those other (IMO) much more exotic ones. Is this because it would be like admitting that there is something good in PERL too ? :-DDD Sure this would leave open a few problems, like how to specify the step (how about the BASIC "step" ? it shouldn't create any syntax ambiguity, I suppose) but those using increments different from +1 are already less "natural", and a more convolute syntax (range ?) or an explicit "while" could be acceptable anyway; looping using +1 and accessing by "[-i]" or "[i*3]" may be is more readable (and is used often in math). Ok... too much talking for a newbie, I'm back to reading :-) Andrea PS: Oh, by the way. Very funny the idea of allowing ++x with the meaning it has in Python :-) From cartermark46 at ukmail.com Sat Apr 10 08:42:13 2004 From: cartermark46 at ukmail.com (Mark Carter) Date: 10 Apr 2004 05:42:13 -0700 Subject: Is boa-constructor dead? Message-ID: I noticed that boa-constructor has been stuck at 0.2.3 for a long time now. Is it dead? From deetsNOSPAM at web.de Fri Apr 9 13:05:35 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Fri, 09 Apr 2004 19:05:35 +0200 Subject: regex help for a newbie References: Message-ID: > I need to do this by real parsing. In fact the solution from Diez isn't > enough. I will have to write a much more flexible parser, as I realized. Why not? If all you need is to extract that parenthesized structure, a self-written parser should be the easiest. Consider this: import re def parse(sg): res = [] for c in sg: if c == "%(": res.append(parse(sg)) elif c == ")": return res else: res.append(c) return res def sgen(s): rex = re.compile(r"(%\(|\))") for token in rex.split(s): yield token print parse(sgen("%(BBB%(CCC)BBB)")) > > Diez mentioned spark as a parser. I also found yappy, which is a parser > generator. I have not much experience with parsers. What is the > difference between these two? When should one use the one, when the > other? yappy is a lr(1) parser, and spark is a earley parser. Bont of them are suited for your problem. I personally found spark easy to use, as its very declarative - but I don't know yappy, maybe thats cool, to. -- Regards, Diez B. Roggisch From 7z6fp9202 at sneakemail.com Tue Apr 6 15:05:58 2004 From: 7z6fp9202 at sneakemail.com (John Houston) Date: 6 Apr 2004 12:05:58 -0700 Subject: "GLIBC_2.3" problem Message-ID: <103d4f03.0404061105.2100c38b@posting.google.com> I freezed a python script "hello.py" on a linux box with GLIBC_2.3. The frozen "hello" works good on the same linux PC. But when I tried to run it on another linux PC, it said: "ImportError: /lib/i686/libc.so.6: version `GLIBC_2.3' not found (required by ./struct.so)" I checked and found the GLIBC on the 2nd PC is version 2.2.5. I copied the /lib/i686/* from teh 1st PC to the 2nd, and it didn't work Is it possible to solve this problem? Or can I install a GLIB_2.3 on the personal folder of the 2nd PC (since I don't have the root access on the 2nd) Thanks From alan_salmoni at yahoo.com Thu Apr 8 07:56:09 2004 From: alan_salmoni at yahoo.com (Alan James Salmoni) Date: 8 Apr 2004 04:56:09 -0700 Subject: Compact Python library for math statistics References: Message-ID: Hi Gerrit, If you want an object-oriented version, try the SalStat stats module (salstat_stats.py). Features the descriptives you discussed plus a range of inferential tests (currently up to and including anova and nonparametric equivilents). Addy is http://salstat.sourceforge.net for the entire package. The CVS stats module is a little borked right now though as I've been making lots of changes, so get the stable downloadable one. Alan. Gerrit wrote in message news:... > wrote: > > I'm looking for a Python library for math statistics. This must be a cl > ear set of general statistics functions like 'average', 'variance', 'cova > riance' etc. > > The next version of Python will have a 'statistics' module. It is > probably usable in Python 2.3 as well. You can find it in CVS: > > http://cvs.sourceforge.net/viewcvs.py/*checkout*/python/python/nondist/sa > ndbox/statistics/statistics.py > > I'm not sure whether it's usable in current CVS, though. You may have to > tweak it a little. > > Gerrit. > > -- > Weather in Twenthe, Netherlands 02/04 11:55 UTC: > 16.0?C Broken clouds mostly cloudy wind 4.5 m/s ESE (57 m above NAP > ) From peter at engcorp.com Sun Apr 4 18:55:58 2004 From: peter at engcorp.com (Peter Hansen) Date: Sun, 04 Apr 2004 18:55:58 -0400 Subject: where download mcmillan installer In-Reply-To: References: Message-ID: Federico wrote: > Hi, Where can I download the mcmillan installer utility? > http://www.mcmillan-inc.com/ doesn't exist anymore? > Thanks I'm not sure of the best place, but a Google search led me to Mark Hammond's page on the starship: http://starship.python.net/crew/mhammond/spambayes/ Check down at the very end, where he indicates he has a modified installer which he's "working with Gordon on rolling these into the official Installer builds, but for now, you can download my older hacks here" and there's a link with a download of some kind. I hope it has what you need. -Peter From imbosol at aerojockey.invalid Sun Apr 4 20:14:58 2004 From: imbosol at aerojockey.invalid (Carl Banks) Date: Mon, 05 Apr 2004 00:14:58 GMT Subject: Python is faster than C References: <406F0907.96F37EA1@tunes.org> <5d83790c.0404032144.482787bd@posting.google.com> Message-ID: <6y1cc.1346$Qv6.482@fe2.columbus.rr.com> Raymond Hettinger wrote: > > > [Armin Rigo] >> >>> enumerate([6,7,8,9]) # uh ? >> > > This got me thinking about how much I would like to see the contents > of an iterator at the interactive prompt. > > I wonder if the read-eval-print loop could be trained to make a better > display: > > # rough pseudo-code sketch > while 1: > command = raw_input() > result = eval(command) > if result is None: > continue > if is_iterator(result): > result, copy = itertools.tee(result) > print "<%s object at 0x%8x:" % > (type(result).__name__, id(result)), > for elem in itertools.islice(copy, 3): > print repr(elem), > else: > print '...', > print '>' > else: > print repr(result) > _ = result > > > # intended result >>>> enumerate('abcdefgh') > >>>> list(_) > [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e'), (5, 'f'), (6, 'g'), > (7, 'h'), (8, 'i'), (9, 'j'), (10, 'k'), (11, 'l'), (12, 'm'), (13, > 'n')] I thought this myself, but what if the iterator is computationally intensive? -- CARL BANKS http://www.aerojockey.com/software "If you believe in yourself, drink your school, stay on drugs, and don't do milk, you can get work." -- Parody of Mr. T from a Robert Smigel Cartoon From aahz at pythoncraft.com Sat Apr 3 14:26:34 2004 From: aahz at pythoncraft.com (Aahz) Date: 3 Apr 2004 14:26:34 -0500 Subject: Prothon, metaclasses, Zope [Was: A 'Python like' language] References: <95aa1afa.0403272243.78d60724@posting.google.com> <95aa1afa.0404011933.5cc5e959@posting.google.com> <95aa1afa.0404022235.3962343@posting.google.com> Message-ID: In article <95aa1afa.0404022235.3962343 at posting.google.com>, Michele Simionato wrote: >aahz at pythoncraft.com (Aahz) wrote in message news:... >> In article <95aa1afa.0404011933.5cc5e959 at posting.google.com>, >> Michele Simionato wrote: >>> >>>My address michele.simionato at poste.it is mostly >>>a span recipient I don't check often. Rea addresses I check every day are >>>michelesimionato at libero.it and michele.simionato at partecs.com >> >> Then please make those addresses readily available by sticking them in >> your .sig or something. Having a non-replyable address is about as rude >> as top-posting. ;-) > >BTW, I tried to send you a message and got this: > >- These recipients of your message have been processed by the mail >server: >aahz at pythoncraft.com; Failed; 5.1.1 (bad destination mailbox address) > >Remote MTA iris2.directnic.com: SMTP diagnostic: 550 5.7.1 Mail from >smtp1.libero.it (193.70.192.51) refused (blackholed by >bl.spamcop.net); Blocked - see >http://www.spamcop.net/bl.shtml?193.70.192.51 > >So it looks like spam is taking control of our lifes and making both >of us to appear rude :-/ Ick. That's odd -- I thought my DNS provider didn't do that kind of thing, but I'm guessing they've been under such overload that they had to. Please forward that message with full headers to aahzpy at panix.com -- my local spam filters shouldn't trap it. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "usenet imitates usenet" --Darkhawk From tjreedy at udel.edu Sun Apr 4 15:57:00 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 4 Apr 2004 15:57:00 -0400 Subject: Working with a list in a more "pythonic" way References: <20040404124833458+0200@news.rhrz.uni-bonn.de> Message-ID: "Nickolay Kolev" wrote in message news:20040404124833458+0200 at news.rhrz.uni-bonn.de... > I would like to find a more pythonic way of solving the following: ... > I have come up with the following solution, but I hope some of you might > suggest a more _functional_ (reduce and map) way of diong it. For anti-reduce Pythoneers, those two desires are contradictory;-) My take: Pythonic is first correct, then about as clear as possible what is being done and why that gives the correct answer. Both your table lookup and Daniels dict lookup are immediately obvious and thus qualify to me. Both handle the switch between chars and pairs of chars about as smoothly as possible (except for your unnecessary try: except: as a substitute for subtracting 1 from the length). Rewritten, your code is score = 0 for i in range(len(phrase)-1): score += soundScoreMatrix[ord(x[i]) - 65][ord(x[i + 1]) - 65] Once written thusly, the reduce form is obvious (but obviously not tested): reduce(lambda score, i: score + soundScoreMatrix[ord(x[i]) - 65][ord(x[i + 1]) - 65], range(len(phrase)-1), 0) but aside from any didactic value this has, I prefer, in this case, the written-out loop. Terry J. Reedy From Mike at DeleteThis.Geary.com Wed Apr 28 15:52:42 2004 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Wed, 28 Apr 2004 12:52:42 -0700 Subject: Path ... where is my application's home dir? References: Message-ID: <10902sbs668i57@corp.supernews.com> Tim Golden wrote: > The usual way to [get the application data folder] on Windows > is to use the winshell functions from pywin32: > > > from win32com.shell import shell, shellcon > print shell.SHGetPathFromIDList ( > shell.SHGetSpecialFolderLocation (0, shellcon.CSIDL_APPDATA) > ) > > > which, on my machine, gives: > > C:\Documents and Settings\goldent\Application Data > > Conventionally, one creates a subdirectory of that > directory, named after your application, and puts > .ini files and so on in there. This seems to be the way > Microsoft has gone (thank goodness) and away from > the registry. Yes, that is the right place for a Windows application to store its data, with one caveat. On a system that uses a "roaming profile" as used in some corporate settings, the entire Application Data folder gets copied down from a server when the user logs in, and copied back up to the server when the user logs out. So, this folder is the right place for small things like settings files, but not for large amounts of data that should be kept on the local machine. There is another folder, the local application data folder, where large files should be kept. For example, Outlook and Outlook Express keep their databases in the local application data folder. You can get the path to this folder with the same code as above by changing CSIDL_APPDATA to CSIDL_LOCAL_APPDATA. However, Win98/Me/NT4 do not support CSIDL_LOCAL_APPDATA, so you'll need to check for an error return and fall back to CSIDL_APPDATA on those system. (I don't know how SHGetSpecialFolderLocation indicates an error--the docs don't say--maybe it raises an exception or returns an error value?) -Mike From booyah at ix.netcom.com Thu Apr 8 20:07:10 2004 From: booyah at ix.netcom.com (Boo Yah) Date: Thu, 8 Apr 2004 17:07:10 -0700 (GMT-07:00) Subject: How to define an Interface in Python 2.2.2? Message-ID: <27085941.1081469230393.JavaMail.root@statler.psp.pas.earthlink.net> Does Python 2.2.2 support Interface (as PHP 5 does) ? If so, how can i define it in Py 2.2.2? Regards, Booyah From joewong at mango.cc Wed Apr 14 23:22:05 2004 From: joewong at mango.cc (Joe Wong) Date: Thu, 15 Apr 2004 11:22:05 +0800 Subject: charset conversion routine? Message-ID: <0a9001c42298$d4445d40$7f00a8c0@scl01.siliconcreation.com> Hi, I am trying to use python to convert UTF8->BIG5 and GB->BIG5 charset. Is it possible and how to do it? From the manual I read something about unicode and locale, but I couldn't get a clear direction on how to make it work. Thanks in advance, -- Wong -------------- next part -------------- An HTML attachment was scrubbed... URL: From rick.ratzel at magma-da.com Tue Apr 13 17:01:21 2004 From: rick.ratzel at magma-da.com (Rick Ratzel) Date: Tue, 13 Apr 2004 16:01:21 -0500 Subject: Import / export values to/from C program In-Reply-To: References: Message-ID: <407c5522$0$46509$39cecf19@news.twtelecom.net> Steffen Jahn wrote: > Hi, > > I stumbled across Python when trying to invoke *scripts* from C programs. The > idea is to set up some variables in the C program, export them, run a Python > script, and, after completion, import some variables back into the C program. > This way, I can keep the C program very flexible for certain types of changes. > > Unfortunately, I can't see an API to export/import an PyObject directly. > I see currently only an indirect way: Implement import and export functions > in C which have to be called in the Python script (import function at > beginning and export function at end). Though I would prefer a *direct* access. > > At the moment, I start thinking whether direct access is really better since > the script needs anyways to *know* of the variables which are available (makes > not much difference whether variable or function...) > > Anyways, maybe somebody can tell me if such direct access is possible. A kick > in the right direction would be highly appreciated. > Not sure if this will help, but Elmer lets you run your Python code from C, where you can pass values back and forth between the languages without having to know the Python/C API. You do have to define an Elmer interface file for your Python module though, but its pretty easy. There are some examples on the website: http://elmer.sourceforge.net You did touch upon one of the main motivations for writing Elmer, and that is to keep the calling C/C++ program flexible for changes and prototyping new functionality...which is something Python is ideal for. Since Elmer generates an interface that looks "native" to C, you can easily replace the underlying Python code with C/C++ once you are through prototyping...if you think it's necessary. From Mike at DeleteThis.Geary.com Tue Apr 6 17:14:40 2004 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Tue, 6 Apr 2004 14:14:40 -0700 Subject: Missing Win32con References: Message-ID: <10767e2faahc3dd@corp.supernews.com> > I have installed Python and it appears to work. Trying it out on > some scripts gives me the error, "cannot find win32con" > > Can anyone suggest where I can get this file? I am running > Windows 2000. Install Mark Hammond's Windows extensions: http://starship.python.net/crew/mhammond/ -Mike From richie at entrian.com Sat Apr 3 04:50:39 2004 From: richie at entrian.com (Richie Hindle) Date: Sat, 03 Apr 2004 10:50:39 +0100 Subject: ANNOUNCE: 'goto' for Python In-Reply-To: References: Message-ID: [Roger] > http://www.fortran.com/come_from.html > http://c2.com/cgi/wiki?ComeFrom > http://aspn.activestate.com/ASPN/CodeDoc/Acme-ComeFrom/ComeFrom.html Thanks for the references! It's a bit of an embarrassment for the Python community that it's taken us so long to catch up. And it's a bit of an embarrassment for me that I didn't implement "goto " or "comefrom " - I'll implement those in the next release. (Computed and conditional comefroms are already on the list, as are computed labels, which I'm surprised to se missing from Clark's paper. His "assigned COME FROM" is almost the same thing, but I found it confusing - computed labels seem like a much clearer way of achieving the same thing.) -- Richie Hindle richie at entrian.com (I know it's two days since April 1st, but I can't help myself) From greg at cosc.canterbury.ac.nz Mon Apr 26 00:46:26 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Mon, 26 Apr 2004 16:46:26 +1200 Subject: Regexp optimization question In-Reply-To: References: Message-ID: Magnus Lie Hetland wrote: > One of the reasons I've avoided existing lexers is that I don't do > standard tokenization -- I don't partition all of the text into regexp > tokens. I allow the lexer to skip over text -- somewhat like how > whitespace is normally handled, except that this can be *any* text -- > and to return the next token that is of any use to the current parsing > rule. > > But who knows -- I may be able to use Plex anyway. You should be able to do this with Plex by defining a fall-back rule that matches any single character and ignores it. If you make it the last rule, and make sure it only matches one character, any other rule that also matches will take precedence over it. If you need to match different sets of tokens in different circumstances, you can do this with states, and have the parser switch states according to what it's currently doing. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From donn at drizzle.com Thu Apr 22 02:43:08 2004 From: donn at drizzle.com (Donn Cave) Date: Thu, 22 Apr 2004 06:43:08 -0000 Subject: How to get the ip addresses of a nic References: <2e262238.0404211825.2f6231b@posting.google.com> Message-ID: <1082616185.980821@yasure> Quoth Rob Nikander : | Justin Dubs wrote: | >>>>socket.gethostbyname(socket.gethostname()) |> |> '192.168.0.18' | | | That always gives me this: | | >>> import socket | >>> socket.gethostbyname(socket.gethostname()) | '127.0.0.1' That isn't your address? Try something like this - t = socket.socket(socket.AF_INET, socket.SOCK_STREAM) t.connect(('my.dns.server', 53)) print t.getsockname() Donn Cave, donn at drizzle.com From usenet at microtonal.co.uk Mon Apr 12 16:23:58 2004 From: usenet at microtonal.co.uk (Graham Breed) Date: Mon, 12 Apr 2004 21:23:58 +0100 Subject: String + number split In-Reply-To: References: <2SAec.70005$Id.6002@news-binary.blueyonder.co.uk> Message-ID: Stevie_mac wrote: > now thats what im talking about! > note to self, learn reg exp! > > Thing is, dont understand it one bit! any chance you comment it! (tell me where to go if you want!) I'd appreciate it > if you could - ta. Yes, certainly. Well, where to go would be the standard documentation, which you can now get from the command line: >>> import sre >>> help(sre) Help on module sre: ... but in this case, the expression is \d+$|_ \d matches a digit + means match more than 1 digit $ ensures the number is at the end of the string | means either \d+$ or _ can match _ is a literal underscore All I did then is substitute any matches with an empty string, which is the same as deleting all matches. Then (on the original string) return the last match, which will be the number at the end, and convert it to an integer. If the string isn't in the format you said it would be, you'll get either an IndexError or a ValueError. What your code was actually doing is subtly different -- assuming an uninterrupted string of letters exists at the front of the string, and anything that isn't alphabetic before the number starts. The other things people are suggesting are better tailored for this problem. The expression(s) you should use depend on the exact problem you're trying to solve. Graham From hjwidmaier at web.de Sat Apr 3 15:32:17 2004 From: hjwidmaier at web.de (Hans-Joachim Widmaier) Date: Sat, 03 Apr 2004 22:32:17 +0200 Subject: gettext and the interpreter Message-ID: Recently I wanted to do some debugging using one module of my first Python program using the gettext module. I just didn't find a way to disable the interpreter binding the last result to _, which ought to be (and stay) a function. Anybody got an idea how to do it? Hans-Joachim From simoninusa2001 at yahoo.co.uk Tue Apr 13 14:21:04 2004 From: simoninusa2001 at yahoo.co.uk (simo) Date: 13 Apr 2004 11:21:04 -0700 Subject: mcmillan installer References: Message-ID: <30260531.0404131021.7eb68543@posting.google.com> I've mirrored the last 3 versions I could find at home (5beta5 for Win/UNIX and 5b4 for Win) at http://www.the-jedi.co.uk/comps/downloads I'd really like to know what happened, I heard that Gordon had some problems with his hosts being taken over, but now his domain seems to have expired too. I hope he's OK. I don't know if he's thought of using Sourceforge.net or even BitTorrent, I think my bandwidth quota can cope for now. Personally I prefer Installer to py2exe, mainly because of --onefile and --upx and of course, it works with Linux too! From peter at engcorp.com Mon Apr 12 17:33:04 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 12 Apr 2004 17:33:04 -0400 Subject: I am puzled about numbers In-Reply-To: References: <107lvs6mree8pee@corp.supernews.com> Message-ID: <86Gdnd9CWrGNlubdRVn-gw@powergate.ca> Bengt Richter wrote: > On Mon, 12 Apr 2004 13:43:42 -0700, "A Evans" wrote: > >>Hello I came across an interesting loop in math today >>To me its interesting anyway I don't know if it will interest you [snip] >>I guess that just goes to show nine is a universal number >>or am I just completely insane and everyone knows this already > > 1: 7 % 777 => 7 > 2: 77 % 777 => 77 > 3: 777 % 777 => 0 > 4: 7777 % 777 => 7 > 5: 77777 % 777 => 77 > 6: 777777 % 777 => 0 > 7: 7777777 % 777 => 7 > 8: 77777777 % 777 => 77 > 9: 777777777 % 777 => 0 > > Careful not to jump to conclusions ;-) So what? Everyone knows that 7 is also a universal number! ;-) -Peter From plastic"no-spam-pls" at xsintrk.net Thu Apr 15 17:29:29 2004 From: plastic"no-spam-pls" at xsintrk.net (jeff) Date: Thu, 15 Apr 2004 21:29:29 GMT Subject: newbie question References: Message-ID: Krzysztof Stachlewski wrote in news:c5mtsl$dns$2 at absinth.dialog.net.pl: > jeff wrote: > >> ex: >> >> a = "text str" >> if a == "text str": print a >> >> why doesn't that work? i couldn't find much help about variable >> types in the manual, does it need a property like a.text? > > It works - at least on my computer. > That is: it prints "text str" to the console. > What did you expect it to do? > ok this is the bit i'm working with, i'm tinkering with sockets. when the recieved text == kill, i want the socket to close. actually, the example i posted worked for me too, but i don't understand why this doesn't. while 1: sdata = s.recv(1024) if not sdata: break if sdata == "kill": s.close() print "Recieved:", sdata From jepler at unpythonic.net Fri Apr 16 16:27:33 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Fri, 16 Apr 2004 15:27:33 -0500 Subject: a little math problem In-Reply-To: References: <20040416164439.GD26865@unpythonic.net> Message-ID: <20040416202733.GD3078@unpythonic.net> 25.2 isn't a multiple of .2. In fact, (126 * .2) appears not to be (126 * .2) % .2 != 0). Floating-point sucks. I'm really sorry about that. I'm also sorry about getting my answer wrong. I had it in my head that divmod() took integer arguments, not floating-point ones. Perhaps you should use the Decimal package (http://cvs.sourceforge.net/viewcvs.py/python/python/nondist/sandbox/decimal/), rational numbers, or scaled integers. The two problems with any such approach is that you can't use literal syntax for nonintegers anymore, and it's slower than floating-point. Jeff From martin at v.loewis.de Tue Apr 20 01:22:50 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 20 Apr 2004 07:22:50 +0200 Subject: Embedding Python in C In-Reply-To: <4039221c.0404191921.1384cb9c@posting.google.com> References: <4039221c.0404191921.1384cb9c@posting.google.com> Message-ID: youngdubliner at hotmail.com wrote: > I'm attempting to embedded Python23 in C. > However , I seem to be missing some header files from my PC. > Any idea where on the web I could locate the files below ? > > io.h > > sys/stat.h > > wchar.h They are provided with Visual C. Regards, Martin From roy at panix.com Tue Apr 27 20:35:51 2004 From: roy at panix.com (Roy Smith) Date: Tue, 27 Apr 2004 20:35:51 -0400 Subject: Is Perl *that* good? References: <108q51j4dscn7dc@corp.supernews.com> <87fzaqmm8t.fsf@strauser.com> <38ec68a6.0404262308.50029919@posting.google.com> Message-ID: In article , Carl Banks wrote: > It's worse because, unlike most objects, regexp objects are usually > global (at least they are when I use them). Moreover, the library > encourages us to make regexp objects global by exposing the regexp > compiler. So even if you personally use local regexps (and accept the > resulting performance hit), many will declare them global. I don't see why regexps are usually global. Nor do I see why exposing the compiler encourages them to be global, or why making them local should result in a performance hit. I do a lot of regex work. I just looked over a bunch of scripts I happen to have handy and only found one where I used global regexp objects. In that script, the regexps were only used in a single routine, so moving them down in scope to be local to that routine would have made more sense anyway. Looking back at the code, which I wrote several years ago, I have no idea why I decided to make them global. From andrew.henshaw at gtri.gatech.edu Fri Apr 9 07:29:33 2004 From: andrew.henshaw at gtri.gatech.edu (Andrew Henshaw) Date: Fri, 09 Apr 2004 07:29:33 -0400 Subject: Bug in struct.calcsize() ? References: <107d1efk77l1v3a@corp.supernews.com> Message-ID: <107d28uc3go6687@corp.supernews.com> Andrew Henshaw wrote: ...snip... I see you followed up to yourself with the solution! Now I just need to fix the bug in my newsreader (knode) that allows these followups to be scattered about the list, even though threading is turned on and sorting by subject is specified! -- Andy From fredrik at pythonware.com Fri Apr 16 07:10:16 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 16 Apr 2004 13:10:16 +0200 Subject: Documentation tool for python source code References: <930ba99a.0404120201.65203953@posting.google.com> Message-ID: "Sridhar R" wrote: > I am just wondering why epydoc isn't mentioned (or atleast in main > page) in the docsig section of www.python.org. the doc-sig page seems to list tools developed by doc-sig members. you can find a more comprehesive list of tools over at: http://www.python.org/cgi-bin/moinmoin/DocumentationTools (but that one's not complete either; http://effbot.org/zone/pythondoc.htm isn't included, for example... hrm.) From "Charles Krug" at cdksystems.com Fri Apr 16 09:19:27 2004 From: "Charles Krug" at cdksystems.com (U-CDK_CHARLES\Charles) Date: Fri, 16 Apr 2004 13:19:27 GMT Subject: Passing COM VB6 strings weirdness Message-ID: List: I've a Python COM server that keeps an event logs. I've been using it from VB6: logEvent "Message" The Python side of things looks like: def logEntry(self, caller = u'Unknown Caller', \ message = u'Unknown Message'): if self.fileOpen == True: return self.__Logger(str(caller), str(message)) else: return -1 The which refers back to the base logger class method: def __call__(self, caller = 'Unknown Caller', \ message = 'Unknown Message'): self.logFile.write(ctime(time()) + ', <' + caller \ + '>, -- ' + message + '\n') return 0 When I log certain events from VB, I also display a message box for the user or for me, depending on the specific message. If I call messageBox BEFORE I invoke logEntry, all is well. BUT if I invoke logEntry first, the passed string becomes a literal zero. Any thoughts on this? I'm not certain why I'm getting the returned value from this at all, let alone why it's being assigned to the argument string. Is my code telling Python to alter the value or is this a VB oddity? Thanks Charles From af at faino.org Mon Apr 12 17:09:38 2004 From: af at faino.org (Andrea Fino) Date: Mon, 12 Apr 2004 23:09:38 +0200 Subject: embedding python In-Reply-To: References: Message-ID: Brad Clements wrote: > I compiled Python 2.3.2(alpha2) on uClinux and linked it with libxml2 and > libxslt. This ran on a Arcturus 68K board with 2meg flash and 8meg ram. > Barely fit, was very slow. We abandoned the platform. I've been promised an > ARM board with 64 meg ram (uh, that was 6 months ago). Haven't seen it > arrive yet. > > Anyway, it works.. I just cross compiled as part of the uClinux dev chain. > You didn't mention which OS you want. > > Yeah, you right sorry about that. It's linux in 2.4 version with the normal glibc (i don't remenber which version). Thanks. -- Andrea Fino 8-) - "Sistemi su misura di qualita' industriale" "Handcrafted systems with industrial quality" [Phone: +39 071 2070104]+[Fax: +39 071 2077919]+[iaxtel:17002876594] [Web: http://www.faino.org]+[Email: af at faino.org] -----BEGIN GEEK CODE BLOCK----- Version: 3.1 GCS: d- s: a+ C+++ UL++++ P++ L++++ E--- W++ N++ o? K w--- O M V PS++ PE+ Y+ PGP t+ 5? X-- R* tv- b-- DI+++ D G++ e* h r y+ ------END GEEK CODE BLOCK------ From francis.moore at shaws.co.uk Thu Apr 1 05:17:51 2004 From: francis.moore at shaws.co.uk (Francis Moore) Date: 1 Apr 2004 02:17:51 -0800 Subject: Newbie TypeError problem Message-ID: Hi, Getting the following traceback from parsing an xml file: Traceback (most recent call last): File "D:\Python23\lib\site-packages\Pythonwin\pywin\framework\scriptutils.py", line 310, in RunScript exec codeObject in __main__.__dict__ File "D:\Development\OmniForm Converter\OFML to SHF\ListFile.py", line 74, in ? try: File "D:\Python23\lib\xml\sax\expatreader.py", line 107, in parse xmlreader.IncrementalParser.parse(self, source) File "D:\Python23\lib\xml\sax\xmlreader.py", line 119, in parse self.prepareParser(source) File "D:\Python23\lib\xml\sax\expatreader.py", line 111, in prepareParser self._parser.SetBase(source.getSystemId()) TypeError: SetBase() argument 1 must be string, not member_descriptor Seems to be failing on the line: parser.parse(file) But I can't see what the problem is. The program worked successfully and I don't remember changing anything major, so I can't understand what it's complaining about. Looking at expatreader.py hasn't really helped as my Python knowledge isn't that great yet. Any help much appreciated. Thanks, Francis. From ae Mon Apr 12 18:36:08 2004 From: ae (A Evans) Date: Mon, 12 Apr 2004 15:36:08 -0700 Subject: Random Numbers and a thought Message-ID: <107m6f0t4i0gnff@corp.supernews.com> I am looking at building a program in python that takes computer generated random sets of numbers and tries to solve the pattern I would like it to extend into complex math as many random numbers as possible I guess this is similiar to a key generator but thats not what I am going for I am not trying to hack software What complex functions and programming would I need to understand in python before building something like this Thank You From peter at engcorp.com Sun Apr 4 13:07:33 2004 From: peter at engcorp.com (Peter Hansen) Date: Sun, 04 Apr 2004 13:07:33 -0400 Subject: emergent/swarm/evolutionary systems etc In-Reply-To: References: <106um6hcr363u14@corp.supernews.com> Message-ID: Peter MacKenzie wrote: >>You might like "The Outsider's Guide to Artificial Intelligence" >>. > > Yes. It is interesting. I've been playing with the idea of graphical > representations for programming 'phrases' for a while, and the reference to > LISP brought it to mind. Although LISP doesn't look that much better than > Python code, are there any programs out there that let you program, um, > programs, using various shapes, colours etc? Just thinking about it brings > up all manner of difficulties that would be encountered if you tried to > create such a thing, but it would be nice if there was some immediately > obvious graphical connection between pieces of code [...] Using the "G" graphical language of LabVIEW, all code ends up _literally_ looking like spaghetti... would that help? ;-) -Peter From wilkSPAM at OUTflibuste.net Thu Apr 15 16:23:45 2004 From: wilkSPAM at OUTflibuste.net (Wilk) Date: Thu, 15 Apr 2004 22:23:45 +0200 Subject: CamelCase versus wide_names (Prothon) References: Message-ID: <87hdvl2dny.fsf@blakie.riol> "Mark Hahn" writes: > We have agreed in Prothon that unlike Python we are going to be 100% > consistant in our var and method naming. We will not have run-together > words like iteritems, we are going to always have seperated words like > has_key. > > Now we are in the midst of a discussion of camelCase versus wide_names. So > far our arguments are: > > 1) CamelCase is more elegant, modern, more readable, and more efficient in > character usage. > > 2) Wide_names is cleaner, more readable, compatible with C, which is the > standard module language for Python and Prothon. Wide_names is also the > Python standard. Before, i used CamelCase, but now i use only wide_name because i find that capitals letters are a pain for the finger and the wrist. For example when you whant to write Q (on querty or azerty keyboard), with one hand you must make a gymnastic, or you will need two hands. The best is to try the two very quickly... I've replaced thousand of lines after it ! But maybe it depends how we use the keyboard... > > Of course in the Python world you alread have wide_names as your standard, Not everytime and i regret... -- Wilk - http://flibuste.net From lbates at swamisoft.com Fri Apr 9 10:35:55 2004 From: lbates at swamisoft.com (Larry Bates) Date: Fri, 9 Apr 2004 09:35:55 -0500 Subject: maximum length of a list & tuple References: Message-ID: I've constructed lists with 100,000+ elements and they have worked flawlessly. FYI, Larry Bates Syscon, Inc. "Lupe" wrote in message news:c54lq3$2pe1sf$1 at ID-202776.news.uni-berlin.de... > hi, > > I'm finishing a small program which uses recursion for less than 100 levels. > > Each time the function is called, it compares an element of a list (which is > a list too) to other elements, which all amounts to millions of > comparisons. > > The program is working for short lists but not for longer ones. I think > there are two possible problems: either disk space is not enough to save > lists as the program is executed or there is a finite manageable list > lenght that is reached by the program. > > hence my question: > > is there a limit? which one? I'm using list.append() > what about for tuples? > > I'll rewrite that part of the code and will overcome the problem, since I > only need a few elements of the list generated, but I'm still curious about > the answers > > Thanks in advanve > > Lupe From tezt at email.si Mon Apr 12 16:27:03 2004 From: tezt at email.si (Mitja) Date: Mon, 12 Apr 2004 22:27:03 +0200 Subject: getting as global as __builtin__ Message-ID: How to make a variable visible from __main__ as well as all other imported modules? I.e., how to make it share the scope with __builtin__? Saying __builtin__.foo='bar' works, but seems messy - foo is far from a built-in thingy. Background: --------------------- I'm writing a web application with a central module and a few peripheral ones, which provide the content of the web page to the main module. The only script ever called is main.py, which then makes use of others via import. All of these modules have to have access to some variables (e.g. HTTP GET parameters), which are all gathered in a module common.py. Therefore, all modules "import common". Thing is, some of these variables are a result of database queries, so the can take some time to get. I would like to have them computed only once (at a specific function call) and then keep them somewhere where they are visible to all the modules throughout the execution of the program. This way, we come to the problem from the first paragraph ------------------- Are there better ways of doing it than __builtin__? Or is the entire approach wrong? Thanks for answers/suggestions, Mitja From gerrit at nl.linux.org Fri Apr 2 06:17:16 2004 From: gerrit at nl.linux.org (Gerrit) Date: Fri, 2 Apr 2004 13:17:16 +0200 Subject: Compact Python library for math statistics In-Reply-To: References: Message-ID: <20040402111716.GA12396@nl.linux.org> ??????? ??????? wrote: > I'm looking for a Python library for math statistics. This must be a clear set of general statistics functions like 'average', 'variance', 'covariance' etc. The next version of Python will have a 'statistics' module. It is probably usable in Python 2.3 as well. You can find it in CVS: http://cvs.sourceforge.net/viewcvs.py/*checkout*/python/python/nondist/sandbox/statistics/statistics.py I'm not sure whether it's usable in current CVS, though. You may have to tweak it a little. Gerrit. -- Weather in Twenthe, Netherlands 02/04 11:55 UTC: 16.0?C Broken clouds mostly cloudy wind 4.5 m/s ESE (57 m above NAP) -- Experiences with Asperger's Syndrome: http://topjaklont.student.utwente.nl/english/ From shagshag13 at yahoo.fr Thu Apr 1 06:46:15 2004 From: shagshag13 at yahoo.fr (Shagshag) Date: 1 Apr 2004 03:46:15 -0800 Subject: Handle multiple cookies with httplib Message-ID: <409a56e2.0404010346.6da1c2cf@posting.google.com> hello, how can i set multiple cookies like : Set-Cookie: cookiename1=value1; expires=Tue, 31-Mar-09 11:17:43 GMT; path=/; domain=www.domain.com Set-Cookie: cookiename2=value2; expires=Tue, 31-Mar-09 11:17:43 GMT; path=/; domain=www.domain.com to a httplib.HTTPConnection ? i used to do : connection = httplib.HTTPConnection(host) connection.putrequest('GET', pathn) connection.putheader('Cookie', cookie) also is there any way to view 'connection' in a readable format to understand how it is build after using many 'putheader' ? regards From rmunn at pobox.com Tue Apr 20 09:19:47 2004 From: rmunn at pobox.com (Robin Munn) Date: Tue, 20 Apr 2004 13:19:47 GMT Subject: Tutorial References: Message-ID: S?ren Kunst wrote: > hello, i need a good tutorial for Python, nothing for beginners Beginners at what? Beginners at Python? Beginners at programming? The official Python tutorial at http://docs.python.org/tut/tut.html is a good one to start with if you've programmed in other languages before and want a jump-start into Python. Other tutorials can be found at: http://www.python.org/topics/learn/ Note especially the division into tutorials for programmers: http://www.python.org/topics/learn/prog.html and tutorials for non-programmers: http://www.python.org/topics/learn/non-prog.html -- Robin Munn rmunn at pobox.com From max at alcyone.com Mon Apr 5 23:34:45 2004 From: max at alcyone.com (Erik Max Francis) Date: Mon, 05 Apr 2004 20:34:45 -0700 Subject: int('2.1') does not work while int(float('2.1')) does References: Message-ID: <40722555.66C70D40@alcyone.com> Vineet Jain wrote: > int('2.1') does not work while int(float('2.1')) does. If int can > covert a > float object then there is no reason why a float string should not be > converted too. > > When I do int('2.1') I get the following error: > > >>> a = int('2.0') > Traceback (most recent call last): > File "", line 1, in ? > ValueError: invalid literal for int(): 2.0 > > This does not seem very pythonic There's a fundamental difference between an int and a float. If the string you're trying to convert looks like a float, that means it doesn't look like an int. With your first example of '2.1', what should it mean? Should it truncate, round to negative infinity round to positive infinity, round to zero, what? Python can't guess for you, so it shouldn't try. Thus it's an error. -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis \__/ If I had another face, do you think I'd wear this one? -- Abraham Lincoln From tismer at stackless.com Mon Apr 5 17:54:50 2004 From: tismer at stackless.com (Christian Tismer) Date: Mon, 05 Apr 2004 23:54:50 +0200 Subject: Python is faster than C In-Reply-To: References: <406F0907.96F37EA1@tunes.org> Message-ID: <4071D5AA.4080200@stackless.com> Michel Claveau/Hamster wrote: > Hi ! > > Yes, but Psyco is writted in C & Python, and it use an C module. > Said "Psyco is faster than C", it's like said "Psyco is faster than Psyco". This is not so much of a contradiction. First of all, Psyco creates assembly code. Not the fastest, but it enters an area where Python has no entrance, yet. So what it does is to produce faster code, although not as fast as C could, but faster than the existing C implementation of Python. Seconde, depending on the algorithm you use, even Python can be faster than C. For example, a few years ago, I implemented a fast long integer multiplication in Python. At that time, CPython still had asymptotic behavior of O(n**2), while the Karatsuba algorithm I used hat something like O(2**1.53). The difference showed up with several thousands of digits, but it was remarkable. Later on, Karatsuba was built into the core, and it became clear to me that *I* caused this mess, because I had the chance to get that algorithm into the core, long time ago. I just missed it. What I'm trying to say: Finally it is always the algorithm. ciao - chris -- Christian Tismer :^) Mission Impossible 5oftware : Have a break! Take a ride on Python's Johannes-Niemeyer-Weg 9a : *Starship* http://starship.python.net/ 14109 Berlin : PGP key -> http://wwwkeys.pgp.net/ work +49 30 89 09 53 34 home +49 30 802 86 56 mobile +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 fredrik at pythonware.com Fri Apr 16 13:18:47 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 16 Apr 2004 19:18:47 +0200 Subject: Learning about dictionaries References: Message-ID: Thomas Philips wrote: > I'm teaching myself python and in the course of playing around with > dictionaries, I tried to create the following trivial dictionary > > {1:'one', 2:'two'} that's a dictionary, right. (to be precise, it's a "dictionary display" which is how you enter "dictionary values" in Python source code) > So I entered > >>> dict(1='one',2='two') that's not a dictionary, that's a function call. you're trying to call a function called "dict" with two keyword arguments, but your keywords doesn't match Python's identifier syntax. more here: http://docs.python.org/ref/calls.html http://docs.python.org/ref/dict.html From jack at performancedrivers.com Thu Apr 1 23:50:19 2004 From: jack at performancedrivers.com (Jack Diederich) Date: Thu, 1 Apr 2004 23:50:19 -0500 Subject: __nonzero__ of iterators In-Reply-To: References: Message-ID: <20040402045019.GF26450@performancedrivers.com> On Thu, Apr 01, 2004 at 10:30:10AM +0200, Christian Eder wrote: > Hi, > > I just discovered the following pitfall in Python 2.3. > Consider the following code : > > >>> a = {} > >>> bool (a.keys ()) > False > >>> bool (a.iterkeys ()) > True > >>> a = {} >>> a.keys() [] >>> a.iterkeys() >>> list(a.iterkeys()) [] a.iterkeys() is returning an iterator. list(a.iterkeys()) is returning all of the elements in the iterator (empty) If you want to test the boolean just use if (a): blah = 1 -jackdied From tim.one at comcast.net Wed Apr 21 12:54:14 2004 From: tim.one at comcast.net (Tim Peters) Date: Wed, 21 Apr 2004 12:54:14 -0400 Subject: python shutting down sloooooooowly/tuning dictionaries In-Reply-To: <20040421163801.GA13623%till@score.is.tsukuba.ac.jp> Message-ID: [Till] > Thanks for the suggestions but unfortunately I already tried disabling > gc. It did not have any noticable effect (not that I was patient > enough to time it) nor did using sys.exit(). sys.exit() doesn't skip cleanup. os._exit() does, but you use that at your own risk (it's probably fine, but you've been warned). > ... > To give an example of the actual time spans involved: 2-10 minutes for > running the program and > 30 minutes for shutdown. During that time > the amount of memory used by python does not seem to vary. This sounds like the platform C free() falling into quadratic-time behavior. You didn't say which version of Python you're using, or which OS + C runtime, and "stuff like that" varies according to both. This kind of behavior is generally much rarer under Python 2.3 than under earlier Pythons -- but if your platform C malloc/free suck, there's not much more Python can do about that than 2.3 already does. From rogerb at rogerbinns.com Sat Apr 3 01:54:55 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Fri, 2 Apr 2004 22:54:55 -0800 Subject: ANNOUNCE: 'goto' for Python References: Message-ID: Richie Hindle wrote: > [Bill] > > Can you explain to me why you need comefrom? Couldn't you replace > > "label.failed" with "goto cleanup"? Thanks. > > You don't strictly need comefrom, but then you don't strictly need goto > either. Use whatever control flow construct fits the problem you're > trying to solve. http://www.fortran.com/come_from.html http://c2.com/cgi/wiki?ComeFrom Needless to say, Perl has already been there :-) http://aspn.activestate.com/ASPN/CodeDoc/Acme-ComeFrom/ComeFrom.html Roger From mark at prothon.org Wed Apr 28 20:47:19 2004 From: mark at prothon.org (Mark Hahn) Date: Wed, 28 Apr 2004 17:47:19 -0700 Subject: Why we will use obj$func() often References: <84Uhc.22278$dZ1.5087@fed1read04> <8AWhc.23114$dZ1.11070@fed1read04> <40883BFE.B381518A@alcyone.com> <27_hc.23801$dZ1.2716@fed1read04> <40887145.789A2FE8@alcyone.com> <7cki80hj976bia36lhf9er97v073o1pqvm@4ax.com> <5vJjc.13116$Qy.1954@fed1read04> <52Ujc.16275$Qy.3111@fed1read04> Message-ID: Donn Cave wrote: > When I dream of a better language, it's not pasting new > gimmicks on Python, it's really a radically different direction. I've daydreamed the same thing and I've thought a classless language was radical. If it turns out to only be a gimmick in the end and not reap the payoffs I've been daydreaming about then I'll be quite dissapointed. If you focus on the closure &var then you are missing the exciting parts of the language picture. I don't need to ask questions about the exciting parts. Can you share some of your daydream ideas? From rawbobb at hotmail.com Mon Apr 12 09:26:28 2004 From: rawbobb at hotmail.com (bobb) Date: Mon, 12 Apr 2004 13:26:28 GMT Subject: connect with MySQL question References: Message-ID: <8Owec.16842$QQ6.8203@nwrdny02.gnilink.net> This was just recently asked, I believe. google for mysql client. wrote in message news:mailman.477.1081484212.20120.python-list at python.org... > > Hi! All > I download MySQL to Python interface software and get MySQLdb module etc installed. But when I start mysqld on XP from c:\mysql\bin (all in windows) and use following code to connect MySQL it fails > > # Database access > import MySQLdb > con=MySQLdb.connect(host="127.0.0.1",port=3306,user="root",passwd="mypasswd" ,db="smalldb") > Cursor=con.cursor() > sql_cmd="select * from customers" > Cursor.execute(sql_cmd) > results=Cursor.fetachall() > con.close() > > > It asked for client upgrade. What that mean? MySQL is 4.0 > Anyone can help? > Thanks in advance. > > Regards > Zhiyong > > ________________________________________________________________ > The best thing to hit the Internet in years - NetZero HiSpeed! > Surf the Web up to FIVE TIMES FASTER! > Only $14.95/ month -visit www.netzero.com to sign up today! > From pythongnome at hotmail.com Wed Apr 28 08:11:16 2004 From: pythongnome at hotmail.com (Lucas Raab) Date: Wed, 28 Apr 2004 12:11:16 GMT Subject: PY2EXE - Strange Things a-Happenin References: <7490e644.0404271717.28a4c7b4@posting.google.com> Message-ID: "Funduk" wrote in message news:7490e644.0404271717.28a4c7b4 at posting.google.com... > Hello, > > So I've been playing with Python and Pygame for a while and I decided > I wanted to make a real executable so I could send that stuff over to > my friends to show off my maad skillz. > > Everything was going great I went and got all the newest software > (including Distutils and PY2EXE) and read the docs on making a setup > py. > > Following is my setup.py: Sorry if It's a little long: > --------------------------------------------------------- > #make standalone, needs at least pygame-1.5.3 and py2exe-0.3.1 > > from distutils.core import setup > import sys, os, pygame, shutil > import py2exe > > #setup the project variables here. > #i can't claim these will cover all the cases > #you need, but they seem to work for all my > #projects, just change as neeeded. > > script = "cards.py" #name of starting .PY > icon_file = "" #ICO file for the .EXE (not working well) > optimize = 2 #0, 1, or 2; like -O and -OO > dos_console = 0 #set to 0 for no dos shell when run > extra_data = ['readme.txt'] #extra files/dirs copied to game > extra_modules = ['pygame.locals'] #extra python modules not auto > found > > #use the default pygame icon, if none given > if not icon_file: > path = os.path.split(pygame.__file__)[0] > icon_file = '"' + os.path.join(path, 'pygame.ico') + '"' > #unfortunately, this cool icon stuff doesn't work in current py2exe :( > #icon_file = '' > > > #create the proper commandline args > args = ['py2exe', '--force', '-O'+`optimize`] > args.append(dos_console and '--console' or '--windows') > if icon_file: > args.append('--icon') > args.append(icon_file) > args.append('--force-imports') > args.append(','.join(extra_modules)) > #args.append(','.join(pygame_modules + extra_modules)) > sys.argv[1:] = args + sys.argv[1:] > > project_name = os.path.splitext(os.path.split(script)[1])[0] > > > #this will create the executable and all dependencies > setup(name=project_name, scripts=[script]) > > #also need to hand copy the extra files here > def installfile(name): > dst = os.path.join('dist', project_name) > print 'copying', name, '->', dst > if os.path.isdir(name): > dst = os.path.join(dst, name) > if os.path.isdir(dst): > shutil.rmtree(dst) > shutil.copytree(name, dst) > elif os.path.isfile(name): > shutil.copy(name, dst) > else: > print 'Warning, %s not found' % name > > pygamedir = os.path.split(pygame.base.__file__)[0] > installfile(os.path.join(pygamedir, pygame.font.get_default_font())) > installfile(os.path.join(pygamedir, 'pygame_icon.bmp')) > for data in extra_data: > installfile(data) > --------------------------------------------------------- > > I got this from some 'here's how to make a setupfile site'. I started > using this one after the one I made caused me errors... Unfortunately > this one does the same. > > I'm using IDLE (but I did also try this in the cmd prompt) so I got > ahead and F5 this setup file and it goes ahead and haks away for a few > seconds (on my pos pII 450). Shortly I recieve this block of > statements and errors: > > Traceback (most recent call last): > File "C:\Documents and Settings\Administrator\My > Documents\Projects\Pygame Projects\Cards\pygame2exe.py", line 48, in > -toplevel- > setup(name=project_name, scripts=[script]) > File "C:\DOCUME~1\ADMINI~1\MYDOCU~1\Projects\Python\distutils\core.py", > line 101, in setup > _setup_distribution = dist = klass(attrs) > File "C:\DOCUME~1\ADMINI~1\MYDOCU~1\Projects\Python\Lib\site-packages\py2exe\__in it__.py", > line 75, in __init__ > distutils.dist.Distribution.__init__(self, attrs) > File "C:\DOCUME~1\ADMINI~1\MYDOCU~1\Projects\Python\distutils\dist.py", > line 130, in __init__ > setattr(self, method_name, getattr(self.metadata, method_name)) > AttributeError: DistributionMetadata instance has no attribute > 'get___doc__' > > > I looked up the last line in google and found a few posts noting the > same difficulties and I was led to believe that it was some kind of > 'mistake'... > > ... > > needless to say I was confused. I decided I could write a pretty good > cry for help (including lots of info etc) so I am now asking you for > help. > > All I want to do is make my stupid little program an executable! :) > HELP!!! > > Extra Info: > Python Version:2.3.3 > Pygame Version:1.6 > Distutils Version:1.0.2 > PY2EXE Version:0.5.0 > OS: Windows 2000 Pro > > Thanks in advance!!! You say you used the command prompt, but in what way?? Did you type in "python setup.py py2exe"?? Adding the "py2exe" is what tells python to use py2exe along with importing it into your setup script. You can't run your setup script using IDLE or the interactive interpreter. It has to be run from the command line. From michael at foord.net Fri Apr 9 04:25:45 2004 From: michael at foord.net (Fuzzyman) Date: 9 Apr 2004 01:25:45 -0700 Subject: Why Activestate Python ? Message-ID: <8089854e.0404090025.141f090c@posting.google.com> Again... a silly newbie question which might have an obvious answer.... but *why* is their an alternative distribution of python by activestate ? Apart fromt he fact that they bundle Mark Hammond's Windows Extensions with it (in the windows version) - what is to be gained from using their distributio instead of the 'normal' one ? Regards, Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html From mark at prothon.org Wed Apr 21 04:11:52 2004 From: mark at prothon.org (Mark Hahn) Date: Wed, 21 Apr 2004 01:11:52 -0700 Subject: Dollar sign ($) on foriegn keyboards? (prothon) References: Message-ID: "Mark Hahn" wrote ... > bm = obj..func # get func from obj and make bound method from obj and func > bm = obj$$func # get func from obj and make bound method from self and func Don't look to close at the details of the proposal. People over at the Prothon mailing list are shooting holes in it as I type. For example, the brain-melting double periods and double dollar-signs are already history. From stach at fr.USUN.pl Fri Apr 16 15:43:44 2004 From: stach at fr.USUN.pl (Krzysztof Stachlewski) Date: Fri, 16 Apr 2004 21:43:44 +0200 Subject: Error copying a file In-Reply-To: References: Message-ID: Stephen Boulet wrote: > I'm on win2000. The file is on a CD I burned, and I wanted to copy it to > a file name that doesn't have any quotation marks in it. The problem is > that I can't reference the file to begin with. The command: > > shutil.copy2(myfile,r'D:\foo.ogg') > > can't use the string held in myfile, although os.listdir('directory on > CD') contains it as the first entry. > > It would be nice if I could referene the file in a way that would not > cause the copy command to fail. Its not a problem with Python, but with the CD-burning software which allowed for the illegal char in the filename. Can you open the file using Explorer? Or move it to disk and rename? That's the best thing you can do about it. -- Stach Tlen: stachobywatelpl, GG: 1811474 Jabber: stach at jabber atman pl From tezt at email.si Fri Apr 2 08:19:42 2004 From: tezt at email.si (Mitja) Date: Fri, 2 Apr 2004 15:19:42 +0200 Subject: Travelling salesman variation in python References: Message-ID: "Diez B. Roggisch" wrote in message news:c4jk1t$2k9keu$1 at ID-111250.news.uni-berlin.de... > You could go for local search. First, create a randow tour. Then select a > neighborhood. Find the local minimum for that neighborhood. Do this as > often as you like. > > A typical neighborhood for tsps are four nodes where two of them are > adjacent in your tour. Then exchange the nodes so that they still form a > tours. If that has less costs, keep it that way. > > --n1--n2-- > --n3--n4-- > > becomes > > --n1\/n2-- > --n3/\n4-- > This is more or less just one of the things you'd do with simulated annealing. And with such a "randomized" problem, this is certainly the one and only way to go. If there are no rules defining the structure of the graph, you can't write an optimized code which takes these rules into account. Anyway, SA is what you want. Google for it, use it. Mitja From michele.simionato at poste.it Wed Apr 7 13:57:24 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 7 Apr 2004 10:57:24 -0700 Subject: OFF-TOPIC:: Why Lisp is not my favorite programming language References: <165b3efa.0403030443.4d591f04@posting.google.com> <40460dd5$0$5916$7a628cd7@news.club-internet.fr> <6in670lrldbjkuujle68a526293j57a7mn@4ax.com> <95aa1afa.0404070205.94b32e4@posting.google.com> Message-ID: <95aa1afa.0404070957.5c370a05@posting.google.com> Jacek Generowicz wrote in message news:...> > Eh, methinks you posted the wrong link. > > Did you mean to point to this thread containing this post: > > http://www.google.ch/groups?as_umsgid=ad2vzxoq.fsf%40ccs.neu.edu > > ? > > [Summary: Troll comes to c.l.l claiming that Lisp is slow. Challenges > Lispniks to try to beat C++ on speed on a program that was designed to > test speed of C++ compilers. Lispniks beat C++ for speed in both > Common Lisp and Scheme.] Ick! I had the wrong link in the clipboard! I am using a new machine at work and sometimes the clipboard surprises me. Anyway yes, I was referring to the thread you mention. Sorry about the mistake. Michele Simionato From RobMEmmons at cs.com Sat Apr 17 07:11:10 2004 From: RobMEmmons at cs.com (Robert M. Emmons) Date: Sat, 17 Apr 2004 06:11:10 -0500 Subject: Difficulty Finding Python Developers In-Reply-To: <4080AE97.C4CF0755@alcyone.com> References: <65cbc3dd.0404140641.3501fde8@posting.google.com> <407D6269.3090909@engcorp.com> <40808FF1.7060204@cs.com> <4080AE97.C4CF0755@alcyone.com> Message-ID: <408110CE.7030402@cs.com> > Note that doesn't mean it's a bad idea to hire a Python expert in order > to lead a team or make sure that everyone's learning Python properly. Being an expert is a good thing. No doubt about that. As in many things however, motivation is a good subsititute -- and possible with python itself. I think I would be more worried about the non-python language things -- they are harder to learn and take more time, and are where depth is important. Python itself is easy to learn. Learning to write CGI scripts, using Zope, doing database work, making a web site, using wxWindows, etc. These are more than just Python. Because of that -- the person that's going to do the job is going to need to be an expert in some of these areas...otherwise long learning curve. Rob From alexanro at stud.ntnu.no Wed Apr 14 10:14:04 2004 From: alexanro at stud.ntnu.no (Alexander Rødseth) Date: Wed, 14 Apr 2004 16:14:04 +0200 Subject: Pygame References: Message-ID: > What do you think should be the criteria for deciding whether > something "is part of Python" or isn't? I agree that my question was a bit vague, so here's a clarification: In that connection I meant "included in the standard installation procedure for the average inexperienced user". > Keep in mind that your guidelines should be applied somewhat > consistently to all packages that might be possibly be included. That's true, but still, there are several other modules, like email, sound, xml, databases, that could've been separate packages, but isn't. Why isn't fullscreen graphics considered that important? This is a riddle to me. > And keep in mind that no one wants Python to be a 150MB download... I totally agree with you on that one. :) - Alexander From jmdeschamps at cvm.qc.ca Wed Apr 21 09:36:24 2004 From: jmdeschamps at cvm.qc.ca (jmdeschamps) Date: 21 Apr 2004 06:36:24 -0700 Subject: Opening MS Word files via Python References: <7b454334.0404201628.371b9e8@posting.google.com> Message-ID: <3d06fae9.0404210536.3f277a37@posting.google.com> Rob Nikander wrote in message news:... > Fazer wrote: > > I am curious as to how I should approach this issue. I would just > > want to parse simple text and maybe perhaps tables in the future. > > Would I have to save the word file and open it in a text editor? That > > would kind of....suck... Has anyone else tackled this issue? > > The win32 extensions for python allow you to get at the COM objects for > applications like Word, and that would let you get the text and tables. > google: win32 python. > > word = win32com.client.Dispatch('Word.Application') > word.Documents.Open('C:\\myfile.doc') > > But I don't know the best way to find out the methods and properties of > the "word" object. > > Rob You can use VBA documentation for Word, and using dot notation and normal Pythonesque way of calling functions, play with its diverses objects, methods and attributes... Here's some pretty straightforward code along these lines: #************************ import win32com.client import tkFileDialog # Launch Word MSWord = win32com.client.Dispatch("Word.Application") MSWord.Visible = 0 # Open a specific file myWordDoc = tkFileDialog.askopenfilename() MSWord.Documents.Open(myWordDoc) #Get the textual content docText = MSWord.Documents[0].Content # Get a list of tables listTables= MSWord.Documents[0].Tables #************************ Happy parsing, Jean-Marc From apardon at forel.vub.ac.be Fri Apr 23 04:46:09 2004 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 23 Apr 2004 08:46:09 GMT Subject: CamelCase versus wide_names (Prothon) References: <6e0680ac.0404211252.7f7b4358@posting.google.com> <4086DFA7.9736E7D3@alcyone.com> Message-ID: Op 2004-04-22, Mark Hahn schreef : > "Roy Smith" wrote ... > > >> Well, we could always try something like... >> >> >> >> long >> variable >> name >> >> > > That's it! We'll do the whole Prothon language in XML! (The one idea that > hasn't been proposed over in Prothon lists yet :) How about this idea, which is about something different but may be related. Allow your argument list to be divided among the identifier. If you would define a component as something like an identifier but without an underscore and then define an identifier as a number of components attached to each other with underscores you then could allow a function to have part of its arguments between components. Something like: copy_to(a,b) could then also be written as: copy(a)to(b) -- Antoon Pardon From ashiyana at lycos.com Thu Apr 8 09:54:52 2004 From: ashiyana at lycos.com (anand k Rayudu) Date: Thu, 08 Apr 2004 09:54:52 -0400 Subject: Embedding python in ANSYS: Anyone tried it? Message-ID: Hi Berthold, You can embed python into any application very easily. Also you have to extend python to understand your applications APIs and objects. There are so many tools [Eg: SWIG, Boost ] to do this. Also python allows you to have 2 way communication between c/c++ & python, using that you can have call back mechanism, By embedding your application will have rich set of utilities. [ Remember python has very big list of modules ] To deploy your application you need not have to have python as pre installed at your customer location. You may supply python with your application. [ Some thing similar to JRE for JAVA] I hope this information helps you. Recently I embedded python into one FE application, if you want to know some specific details I can try to help you out. Please let me know. Best Wishes, Anand ____________________________________________________________ Find what you are looking for with the Lycos Yellow Pages http://r.lycos.com/r/yp_emailfooter/http://yellowpages.lycos.com/default.asp?SRC=lycos10 From http Tue Apr 20 21:49:05 2004 From: http (Paul Rubin) Date: 20 Apr 2004 18:49:05 -0700 Subject: PDF library? References: <7xad1631j8.fsf@ruckus.brouhaha.com> Message-ID: <7xzn96drse.fsf@ruckus.brouhaha.com> Simon Burton writes: > http://www.reportlab.org/ > > handles pdf files. Reportlab generates reports in pdf format, but I want to do the opposite, namely read in pdf files that have already been generated by a different program, and crunch on them. Any more ideas? Thanks. From johnbunderwood at yahoo.ca Tue Apr 6 15:24:26 2004 From: johnbunderwood at yahoo.ca (John Underwood) Date: Tue, 06 Apr 2004 15:24:26 -0400 Subject: Using python23 to develop an extension for an application that has python22 embedded References: <1073eeubflmchd5@corp.supernews.com> <1073vcag51uufe9@corp.supernews.com> <1075js9on4our07@corp.supernews.com> Message-ID: On Tue, 6 Apr 2004 08:40:57 -0700, "Michael Geary" wrote: >> Michael Geary wrote: >> > Anyway, I must be missing something here, because I would think >> > you could simply develop with your installed Python 2.2 and run >> > the code under your target application. You shouldn't have to be >> > worrying about any of the stuff you're dealing with. > >John Underwood wrote: >> May be it comes down to the approach taken to debug an extension. >> (I'm new to Python - as you've probably guessed - and debugging >> mixed language situations.) >> >> To use the dubugging features of Visual Studio to debug my extension >> code, I thought I needed to use python22_d.dll (the debug version fo >> python22.dll). Is this correct? If so, I have not been able to produce >> it with Visual Studio .NET because of the problems VS has with 2.2. >> >> On the other hand, would it be better to debug the extension without >> the Python interface (in other words, debug the internals of the >> extension that are not dependent on Python) before attempting to test >> the Python interface (which could be performed with python22.dll)? > >Oh! I think I just realized what I was missing. Is your Poser extension part >Python and part C/C++? I was assuming it was pure Python. There is a Python front-end (using tkinter). This is not implemented as an extension but is simply a script that runs in Poser. It imports the extension part (which is coded in C/C++). > >If it was pure Python, then of course it wouldn't matter if you had the >debug version of python22.dll. You'd use the debugging facilities that the >Python interpreter provides for Python code, which don't depend on having >the debug version of the interpreter. > >If you were debugging code in the Python interpreter itself, then you would >certainly need the debug version of python22.dll. > >But are you are developing both some Python code and an extension DLL >written in C/C++? In that case, it still wouldn't be necessary to have the >debug version of python22.dll, any more than you need a debug version of the >Windows DLLs such as kernel32.dll and user32.dll. You would just build a >debug version of *your* DLL. Set the Debugging options in your VS.NET >project properties to run Poser, and you'll be good to go. You can set >breakpoints in your DLL, trace through the code, etc. The only limitation >will be that you can't trace through the code inside python22.dll. Only if >you need to do that would you need a debug version of that DLL. > I tried a small extension DLL as a test using your suggestion. I could debug in VS.NET without the need of python22_d.dll which is all I need. Many thanks for the help. Regards, -John From dlissett0 at yahoo.com Sat Apr 24 21:59:56 2004 From: dlissett0 at yahoo.com (Duncan Lissett) Date: 24 Apr 2004 18:59:56 -0700 Subject: Richards bench benchmark References: <6748553f.0403291446.27fb7b93@posting.google.com> <6748553f.0403300836.744e3e22@posting.google.com> <6748553f.0403302317.4595844@posting.google.com> <6748553f.0404060802.6e0d708c@posting.google.com> <6748553f.0404211342.7591cd8e@posting.google.com> <40899240.7020508@engcorp.com> Message-ID: <6748553f.0404241759.1f98a441@posting.google.com> Peter Hansen wrote in message news:<40899240.7020508 at engcorp.com>... > Okay, first working version is available by going to > http://www.engcorp.com/main/projects/PyBench . > > That's about all the time I can spare on this for now. > Feel free to download, hack, improve, or ignore. Excellent! I've added the Python implementation timings: http://www.lissett.com/ben/bench1.htm I've no prior experience of Python to judge from, but for some reason I expected it to be faster than the interpreted implementation of Smalltalk designed for mobile devices. From tjreedy at udel.edu Thu Apr 8 20:50:05 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 8 Apr 2004 20:50:05 -0400 Subject: Pyrex list is down References: <74jek1-3qs.ln1@snout.lairds.org> <074gk1-8u1.ln1@snout.lairds.org> Message-ID: > Duncan Booth writes: > > >> I hate mailing lists anyway. I'd much rather use Usenet. Give your newsreader an account for news.gmane.org and subscribe to gmane.comp.python.pyrex. There are news-gated versions of about 50 python related mailing lists. TJR From peter at engcorp.com Thu Apr 1 21:28:39 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 01 Apr 2004 21:28:39 -0500 Subject: Richards bench benchmark In-Reply-To: <6748553f.0403302317.4595844@posting.google.com> References: <6748553f.0403291446.27fb7b93@posting.google.com> <6748553f.0403300836.744e3e22@posting.google.com> <6748553f.0403302317.4595844@posting.google.com> Message-ID: <406CCFD7.40108@engcorp.com> Duncan Lissett wrote: > Peter Hansen wrote: >>I'd implement it in Python for kicks, but I'm not sure how I'd know >>whether my version was doing the right thing. Are there any tests >>for it? Ways of ensuring the output is correct? > > Martin Richards original spec and debug/trace information is reposted > here: > http://www.lissett.com/ben/com/benchspec.htm Okay, as a starting point I've turned the "gold output" part of that spec into a first acceptance test, and have a shell bench.py which runs but fails ('pass' statements tend to do that a lot during TDD). The code should be available with svn co svn://fortress.engcorp.com/public/bench I don't really expect anyone to check it out at this stage, but if you happen to have a free moment, I wouldn't mind knowing if subversion is properly visible through my firewall. -Peter From peter at engcorp.com Fri Apr 2 17:34:52 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 02 Apr 2004 17:34:52 -0500 Subject: Making the Zen of Python more useful In-Reply-To: References: Message-ID: Aloysio Figueiredo wrote: >>>>import sys >>>>t,sys.stdout = sys.stdout, file('/dev/null', 'w') >>>>from this import s >>>>sys.stdout = t >>>>s.decode('rot-13') Aloysio, it's often helpful that sys.__stdout__ preserves a reference to the original sys.stdout (similarly with sys.__stdin__ and sys.__stderr__) so you don't have to preserve it manually like that. -Peter From ville at spammers.com Thu Apr 1 09:33:20 2004 From: ville at spammers.com (Ville Vainio) Date: 01 Apr 2004 17:33:20 +0300 Subject: Python as natural language (was Re: ANNOUNCE: 'goto' for Python References: Message-ID: >>>>> "Richie" == Richie Hindle writes: Richie> Entrian Solutions is pleased to announce version 1.0 of Richie> the 'goto' module. Richie> This adds the 'goto' and 'comefrom' keywords to Python Richie> 2.3, adding flexibility to Python's control flow Richie> mechanisms and allowing Python programmers to use many Richie> common control flow idioms that were previously denied to Richie> them. I like it! I especially like the way comefrom maps to how we speak. You know, "come here when you are done with the first file". Programming is hard for the beginners because there really is no direct mapping of many everyday speech idioms, and comefrom goes a long way to redeem this for Python. There is still a long way to go, though. I have some problems telling nouns apart from verbs. Python could innovate here by prefixing all the function names with !. This ought to make the parser faster also, considering that Python startup time has gone up in recent versions. Another gripe of mine is the if-statement. Often what is done is more important than the condition that determines what we are to do in the first place, esp. in situations where the condition is of the form "if the previous command succeeded". This could be easily redeemed by a postfix-if statement: err = foo() dostuff() domorestuff() :if not err This seems pretty elegant, considering that exceptions are a hackish and unnatural way to solve this problem. Python parser would cope with this just fine. -- Ville Vainio http://tinyurl.com/2prnb From tundra at tundraware.com Mon Apr 5 21:20:10 2004 From: tundra at tundraware.com (Tim Daneliuk) Date: 05 Apr 2004 21:20:10 EDT Subject: For Those Who Offered To Beta Test A New Python Configuration File Processor ... Message-ID: Please contact me privately - we are going to Beta pretty quickly and I managed to fatfinger the list of people who offered to help. If you are interested, you can get a look at what's going on here at: http://www.tundraware.com/Software/tconfpy/ TIA, -- ---------------------------------------------------------------------------- Tim Daneliuk tundra at tundraware.com PGP Key: http://www.tundraware.com/PGP/ From vincent_delft at yahoo.com Thu Apr 8 16:43:23 2004 From: vincent_delft at yahoo.com (vincent_delft at yahoo.com) Date: Thu, 08 Apr 2004 22:43:23 +0200 Subject: New PIL user : How to merge images Message-ID: <4075b940$0$1963$ba620e4c@news.skynet.be> Does any one can give me sample of PIL code that merge 2 pictures. To "normalize" pictures size, I would like to superpose pictures on a "fixed size" background. Thanks I've tried : import Image bg=Image.open('back.jpg') # size 800,600 img=Image.open('test.jpg') # size 400,400 But the both following command return an error img.paste(bg) bg.paste(img) From cmg at dok.org Thu Apr 15 11:18:01 2004 From: cmg at dok.org (Chris Green) Date: Thu, 15 Apr 2004 11:18:01 -0400 Subject: Difficulty Finding Python Developers References: <65cbc3dd.0404140641.3501fde8@posting.google.com> <30260531.0404141031.3415b975@posting.google.com> Message-ID: simoninusa2001 at yahoo.co.uk (simo) writes: > Yes, I'm beginning to think Python isn't as accepted as we think ;o) I've run into a few people that have used python in jobs but not very many. It seems to leave a bad taste for many people that don't have a text editor that does the right thing out of the box. It's amazing how much software development is done with people that don't place enough emphasis on making their tools make their job easy. I've seen a really good algorithms person run vmware on linux to get notepad.exe in win32... > I'm actually looking for a Python job now (in CA, not Atlanta) and > it seems that there's only a few out there, mostly at Google doing > SysAdmin stuff! Barely anyone actually lists Python as a main > requirement, more like a "nice to have" alongside Perl or C++. When I've gone into places, I've often sold them on having good luck teaching other people python and ending up with something more maintainable as everyone is forced to write about the same kind of python code as long as you don't get trigger happy with speciality methods. > > I've seen no web development positions or prototyping/testing at all, > which seems strange to me, as I mainly use Python for RAD, prototyping > C++/Qt apps etc. I've definately not seen webdev in python. Lots of asp, perl and php and lots of "where do we go from here". Often it takes doing something quickly in python and seeing some good results to get people to wake up to python. One example I was sharing at pycon was using the unittest framework to test other apps. Take an existing project that doens't have a test suite but does have a command line interface and generate test cases based off causing the prgram to perform actions. I first saw this in ghostscript and I wrote a preliminary one for an IDS. When searching for jobs I try to feel out how open the company is to new solutions and when a need that python fulfills comes up, use it. -- Chris Green Eschew obfuscation. From mark at prothon.org Thu Apr 15 14:05:29 2004 From: mark at prothon.org (Mark Hahn) Date: Thu, 15 Apr 2004 11:05:29 -0700 Subject: CamelCase versus wide_names (Prothon) References: <407ec022$0$54153$1b2cd167@news.wanadoo.nl> Message-ID: "Roy Smith" wrote... > It's entirely unclear how any of the above should influence your > decisions on language design :-) It may not technically be part of the language design, but aesthic issues like this need to be decided up front or they will be decided randomly. Users on the Prothon mailing list were asking me (I'm the BDFL there) to change from wide_names to camelCase and I wasn't letting them, because Python used wide_names and I have a rule about following Python unless there is a good reason to change. Then I came here and asked and to my surprise I'm finding out that 100% of python users want camelCase. This kind of blows away my argument against it. So camelCase it will be. Now I'll go through all the Python method and var names and convert them all to camelCase for Prothon. It shouldn't be a problem for users since the conversion is mechanical. From ndbecker2 at verizon.net Thu Apr 22 09:48:14 2004 From: ndbecker2 at verizon.net (Neal D. Becker) Date: Thu, 22 Apr 2004 09:48:14 -0400 Subject: Simple question about mutable container iterator Message-ID: x = [1,2,3] for i in x: i = 2 This doesn't change x. 2 questions: 1) Why not? Why doesn't assign to an iterator of a mutable type change the underlying object? 2) What is the preferred way to do this? From till at score.is.tsukuba.ac.jp Wed Apr 21 12:38:01 2004 From: till at score.is.tsukuba.ac.jp (Till Plewe) Date: Thu, 22 Apr 2004 01:38:01 +0900 Subject: python shutting down sloooooooowly/tuning dictionaries In-Reply-To: <40869D5F.9010408@sweetapp.com> References: <20040421153923.GA13234%till@score.is.tsukuba.ac.jp> <40869D5F.9010408@sweetapp.com> Message-ID: <20040421163801.GA13623%till@score.is.tsukuba.ac.jp> On Wed, Apr 21, 2004 at 06:12:15PM +0200, Brian Quinlan wrote: > >Since the entire database is too large I typically run the same > >program 10-100 times on smaller parts. The annoying bit is that the > >time for finishing one instance of a program before starting the next > >instance can take a lot of time. ... > > You might try disabling garbage collection using the gc module when you > your application is done. Explicitly closing any files bound to globals > might then be a good idea. > > Cheers, > Brian > Thanks for the suggestions but unfortunately I already tried disabling gc. It did not have any noticable effect (not that I was patient enough to time it) nor did using sys.exit(). Also, I am not using threads which excludes another possible explanation. To give an example of the actual time spans involved: 2-10 minutes for running the program and > 30 minutes for shutdown. During that time the amount of memory used by python does not seem to vary. A far as closing files is concerned, I am using cdb for writing read-only databases and I am using cdb.finish() (there is no explicit method for closing(); finish writes all key/value pairs to a temporary file and then moves that file to wherever you want it. But as far as I can see as soon as that file is written/has been moved no more I/O should take place. There is no data loss if I simply kill the python program. - Till From patrick at harsdorf.de Sun Apr 25 12:28:32 2004 From: patrick at harsdorf.de (Patrick von Harsdorf) Date: Sun, 25 Apr 2004 18:28:32 +0200 Subject: iterating over collection, deleting entries => PLEASE IGNORE References: Message-ID: Sorry, I missed that SnuSnu just posed a very similar question. Please ignore my post... From richie at entrian.com Fri Apr 2 15:40:34 2004 From: richie at entrian.com (Richie Hindle) Date: Fri, 02 Apr 2004 21:40:34 +0100 Subject: ANNOUNCE: 'goto' for Python In-Reply-To: References: Message-ID: [Bill] > Can you explain to me why you need comefrom? Couldn't you replace > "label.failed" with "goto cleanup"? Thanks. You don't strictly need comefrom, but then you don't strictly need goto either. Use whatever control flow construct fits the problem you're trying to solve. -- Richie Hindle richie at entrian.com From martin at v.loewis.de Fri Apr 30 18:48:46 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 01 May 2004 00:48:46 +0200 Subject: _socket module missing solaris 7 build python 2.3.3 In-Reply-To: <409275CC.1D6D080@csr.utexas.edu> References: <409275CC.1D6D080@csr.utexas.edu> Message-ID: <4092D7CE.1050605@v.loewis.de> Stephen Williams wrote: > anyone out there know of a way around this? compiler flags or > something? Around what? That sunfreeware does not ship the socket module? Contact Sun. If you want to work around contacting Sun, you have these alternatives: - build Python yourself. - just build the socket module. Regards, Martin From alford at wuphys.wustl.edu Mon Apr 12 18:17:27 2004 From: alford at wuphys.wustl.edu (Mark Alford) Date: Mon, 12 Apr 2004 17:17:27 -0500 (CDT) Subject: plot+interaction Message-ID: I have been using the gnuplot.py package for simple 2D plots. Works great. But I would like to have a tiny bit of interactivity: I would like the program to know where (in terms of the plot variables x and y) the user has mouse-clicked on the plot window. Is there any other plotting package that offers this functionality? Mark From usenet_spam at janc.invalid Thu Apr 29 23:49:34 2004 From: usenet_spam at janc.invalid (JanC) Date: Fri, 30 Apr 2004 03:49:34 GMT Subject: Path ... where is my application's home dir? References: Message-ID: Peter Hansen schreef: > Also works on WinXP. (And the last statistic I saw showed Win98 > users at something like 2% of the Windows-using population, > so perhaps we can almost forget about it... ?) I guess Win9x users are more like 15-30% of the Windows-using population... -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From mghsm at hotpop.com Sun Apr 18 09:15:08 2004 From: mghsm at hotpop.com (Richie Adler (ROT13)) Date: Sun, 18 Apr 2004 10:15:08 -0300 Subject: Any known bitmap/resource/image collection for a Spanish card deck? References: Message-ID: <928hgke7jazi.dlg@kilroysoft.com> On Thu, 18 Mar 2004 01:30:50 -0500, David M. Cooke wrote: > Have you checked pysol? (http://www.pysol.org/) It has a lot of card > decks (no Spanish ones at first glance, but lots of French, for instance). The poker deck is French in origin. All decks in pysol (including the optional additional ones) are variants of the same deck. -- o-=< Kilroy >=-o From mikalzetTogli at interfree.it Sat Apr 3 15:25:29 2004 From: mikalzetTogli at interfree.it (TaeKyon) Date: Sat, 03 Apr 2004 20:25:29 GMT Subject: recursive file editing Message-ID: I'm a python newbie; here are a few questions relative to a problem I'm trying to solve; I'm wandering if python is the best instrument or if awk or a mix of bash and sed would be better: 1) how would I get recursively descend through all files in all subdirectories of the one in which my script is called ? 2) each file examined should be edited; IF a string of this type is found foo.asp=dev?bar (where bar can be a digit or an empty space) it should always be substituted with this string foo-bar.html (if bar is an empty space the new string is foo-.html) 3) the names of files read may themselves be of the sort foo.asp=dev?bar; the edited output file should also be renamed according to the same rule as above ... or would this be better handled by a bash script ? Any hints appreciated -- Michele Alzetta From sross at connectmail.carleton.ca Mon Apr 26 08:43:47 2004 From: sross at connectmail.carleton.ca (Sean Ross) Date: Mon, 26 Apr 2004 08:43:47 -0400 Subject: Using descriptors to wrap methods References: <408cfa5a$0$28920$61fed72c@news.rcn.com> Message-ID: "Edward C. Jones" wrote in message news:408cfa5a$0$28920$61fed72c at news.rcn.com... > Here is a stripped-down version of a Python Cookbook recipe. Is there a > simpler, more Pythonical, natural way of doing this? > def wrap(f): def wrapped(*args, **kwds): print 'pre' result = f(*args, **kwds) print 'post' return result return wrapped From ville at spammers.com Sun Apr 4 04:18:16 2004 From: ville at spammers.com (Ville Vainio) Date: 04 Apr 2004 11:18:16 +0300 Subject: Python is faster than C References: <406F0907.96F37EA1@tunes.org> Message-ID: >>>>> "Armin" == Armin Rigo writes: Armin> Worse, and more importantly, the optimization starts to Armin> become visible to the programmer. Iterators, for example, Armin> are great in limited cases but I consider their Armin> introduction a significant complication in the language; Armin> before, you could expect that some function from which you Armin> would expect a sequence returned a list. Python was all Armin> lists and Iterators are an optimization? I always considered them just a more clean and elegant way to do the same thing :-). -- Ville Vainio http://tinyurl.com/2prnb From cm at leetspeak.org Fri Apr 30 08:28:03 2004 From: cm at leetspeak.org (Michael Walter) Date: Fri, 30 Apr 2004 14:28:03 +0200 Subject: static keyword In-Reply-To: References: Message-ID: Peter Hansen wrote: > Nick Jacobson wrote: > >> I believe the following "static" command would be useful in Python. > > [snip] > >> Just like in C, the variables i and firstcall are only assigned the >> first time foo() is called. To get this effect currently, one could >> use default arguments or wrapping the whole thing in a class. Both of >> these solutions seem like hacks, the above method IMO is more >> Pythonic. :) > > > I'm not sure how to interpret the smiley, but I'll take it > you weren't actually joking... > > Why do you call using OO ("wrapping it in a class", as you say) > a "hack"? Generally speaking, using objects to contain state > information such as this is exactly what most people would call > the cleanest, best approach. > [...] There's also a bunch of people who would consider this (modulo my obvious mistakes ;) the cleanest, best approach: (let ((first-call #t) (i '(10 11))) (define (foo) (when (first-call) (begin (display "first pass") (set! first-call #f)) (set! (array-ref i 0) (+ (array-ref i 0) 1)) (display (array-ref i 0)))) I.e. capture the state in a normal lexical variable. Cheers, Michael From michele.simionato at poste.it Wed Apr 28 10:19:56 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 28 Apr 2004 07:19:56 -0700 Subject: Generic constructors and duplication of internal Python logic References: <87ekqq41ya.fsf@pobox.com> <8dad5312.0404280217.21c2cfd1@posting.google.com> Message-ID: <95aa1afa.0404280619.778bd323@posting.google.com> sdementen at hotmail.com (Sebastien de Menten) wrote in message news:<8dad5312.0404280217.21c2cfd1 at posting.google.com>... > Here is a metaclass for uber-lazy user :-) > > Concretely, at the creation of the class it takes the source of the > __init__ function and add, at the first line of __init__, the line > that sets the attributes : > > self.foo, self.bar, self.baz, self.optional1, self.optional2 = > > foo, bar, baz, optional1, optional2 > Unfortunately this approach does not work if the source is not available (this happens when you are in the interpreter, or when you only have a .pyc file). I was playing this kind of tricks some time ago, then I decided that it was best to switch to Lisp/Scheme for this kind of stuff ;) Michele Simionato From wilkSPAM at OUTflibuste.net Fri Apr 16 07:00:29 2004 From: wilkSPAM at OUTflibuste.net (Wilk) Date: Fri, 16 Apr 2004 13:00:29 +0200 Subject: (For gurus) Embed functions in webpages like in PHP? References: <5eq4l1-9vm.ln1@pilz.hasos.com> Message-ID: <87llkwjigi.fsf@blakie.riol> Hi, Look at http://cheetahtemplate.org, you'll have the possibility to put python code into the template and have automatic and elegant cache... This page describe it and show very clear examples http://cheetahtemplate.org/docs/users_guide_html_multipage/output.caching.regions.html It's just an example, there are others possibility, with many web frameworks. http://www.python.org/cgi-bin/moinmoin/WebProgramming Robert Ferber writes: > Hi, > > I'm a PHP-programmer who evaluates Python for a new project. > I really like a lot of concepts of Python, especially the shell, but there > is one great feature of PHP which I don't know how to replace in Python: > > For database-intensive webpages, I like to cache the HTML-output on the fly > in the filesystem and put out the file later whenever the same URL is > requested again, for example: > > /cache/some_url: > > important database result that took 20 minutes to generate > > > and: > /www/master_script.php: > if (is_file("/cache/$URL")) include("/cache/$URL"); > else include("/scripts/soo_long_and_complicated.php"); > ?> > > So far so good, shouldn't be too much of problem to do something similar in > Python. > > However, it's sometimes necessary to still access the database, for example > to rotate banners, show user-specified style-sheets, change output > depending on the used browser, etc. > In PHP it's trivial to do this, instead of caching the output of a function, > I just cache "", so the example looks like this: > > > > important database result that took 20 minutes to generate > > > I've used this technique for about a year now and it works great for > semi-static pages (which are manually changed) or some not too fast > changing dynamic pages, in some cases I reduced the database-load to 20%. > The beauty of it is that I can use the same "random_banner_()" function for > the cache and on the fly. > > As far as I've seen, there is no way to embed Python-code in a webpage with > "" or anything equivalent and I don't see any other way to solve this > problem. > > But maybe somebody else does, I'd apreceate all ideas, > > Thanks a lot > > -- > "I don't suffer from insanity, I enjoy every minute of it" > - Calvin > -- Wilk - http://flibuste.net From balaji at email.arizona.edu Fri Apr 23 17:34:18 2004 From: balaji at email.arizona.edu (Balaji) Date: 23 Apr 2004 14:34:18 -0700 Subject: How to get the refernces Stored. Message-ID: <494182a9.0404231334.1f6b2dad@posting.google.com> import __main__ tempbuffer= None permbuffer={} class E: def __init__(self): # print id(self) self.hasVar = False def doOperation(self,op,rightOperand): e = E() if self.__class__ == E: e.hasVar = self.hasVar elif self.__class__ == V or rightOperand.__class__ == V or \ (rightOperand.__class__ == E and rightOperand.hasVar == True): e.hasVar = True e.operator = op e.left = self e.right = rightOperand global tempbuffer global permbuffer print "bll" f = copy.copy(e) print f r =findNonTempBufferRef(tempbuffer) print r if r != 'tempbuffer': print "hello" permbuffer[r] =tempbuffer tempbuffer = f return e def relationalOperators(self,op,rightOperand): print self,rightOperand e=E() e.operator =op e.left=self e.right=rightOperand return e def __neg__(self): return self def __radd__(self,e2): return self.doOperation('+',e2) def __add__(self,e2): return self.doOperation('+',e2) class V(E): """ This is a variable for MPY""" def __init__(self): print "V", E.__init__(self) self.hasVar = True self.val = None def __str__(self): if self.val: # print "self.val *****" return str(self.val) else: return findRefTo(self) or "MPY Error! Printing unnamed variable." def findRefTo(obj): import expression # Needed to get access to main. vnames = vars(__main__) for name in vnames.keys(): if vnames[name] == obj: return name return None def findNonTempBufferRef(obj): import expression # Needed to get access to main. vnames = vars(__main__) print vnames for name in vnames.keys(): if vnames[name] == obj: return name return None ************************************************** This my code... On interpretor if i create x=V() and y=V() creates two instances of class variable which inherits from expression class E. now if i say x+y and then c=x+y and ce=x+y i think i loose the original one... i want to store in a permbuffer all asignments made.. after assigning c and ce i want a copy of both in a permbuffer.. Iam at my witends .. Please help... Balaji From boblancaster at zxmail.com Tue Apr 27 10:20:13 2004 From: boblancaster at zxmail.com (Bob Lancaster) Date: 27 Apr 2004 07:20:13 -0700 Subject: creating an python function with DCoracle2 module References: <46a86393.0404270242.60fe9b35@posting.google.com> Message-ID: shmolduk at free.fr (pepericou) wrote in message news:<46a86393.0404270242.60fe9b35 at posting.google.com>... > I'm trying to developp an application which use Zope and DCOracle2 > module to access Oracle database. I've install the DCOracle2 product > on Windows XP, but when I create a python function to access my > database, I' have the following error when I test it : > import DCOracle2 is unauthorized > Can You help me ? > Thank you Sounds like the problem is on your machine, and not with DCOracle2. I've imported it quite nicely (on Windows 2000), and so have many others. I would check the permissions on your DCOracle files. Also, is that an English or French version of Windows XP? Many of our customers use non-English versions of XP, and those versions are often not as robust as the English version. Bob Lancaster rlancasterATbruker-axsDOTcom From simoninusa2001 at yahoo.co.uk Wed Apr 28 00:30:56 2004 From: simoninusa2001 at yahoo.co.uk (simo) Date: 27 Apr 2004 21:30:56 -0700 Subject: wxpython + py2exe + innosetup References: <408eca0c$1@newsflash.abo.fi> Message-ID: <30260531.0404272030.3fe52362@posting.google.com> "Simon Dahlbacka" wrote: > I'm "exefying" an application that uses wxpython, some com to control excel > and word and want to distribute this application. > > after creating the executable with py2exe, it still works fine (at least on > my development machine), however, if I create an installer package with > innosetup, install it and try to run it, I get a busy cursor for a split > second and then.. nothing. no errors no traceback no nothing.. viewing > dependencies does not reveal anything strange, and running the installed > program in a debugger just tells that the application has exited with code > 0. Does the program rely on any paths to files - i.e. does it open your Excel/Word file from the current directory? This is the only problem I've ever found with Inno - it's an FAQ too, there's an option to set the "Run From" property in the shortcuts. The sympton is that it won't work from the shortcut in Start/Desktop but will work from the program directory. What about permissions - if you installed it as non-Admin and it needs to write something Admin-only..... ISTool can make the InnoSetup options a bit easier to deal with - maybe you're accepting a default that needs to be changed? Some useful tips here: http://starship.python.net/crew/theller/moin.cgi/BetterCompression From joe at notcharles.ca Tue Apr 20 05:07:21 2004 From: joe at notcharles.ca (Joe Mason) Date: Tue, 20 Apr 2004 09:07:21 GMT Subject: Dollar sign ($) on foriegn keyboards? (prothon) References: Message-ID: In article , Peter Otten wrote: > Mark Hahn wrote: > >> We are considering switching to the dollar sign ($) for self, instead of >> the >> period ( . ) we are using now in Prothon. Ruby uses the at-sign (@) for > Apart from that obj$func() hurts my eye more than obj->func() and > obj!func(). As always, Python shines here with its obj.func() :-) I believe the suggestion is "$.func()" instead of "self.func()" (the Python way) or just ".func()" (the earlier Prothon way). Or possibly the suggestion is for "$func()", although I like $.func() much better. (I like this better than the ., though I still have no problem with writing self all the time, so I prefer sticking to the Python way. It solves my main problem with ., which is when you do have to pass self explicitly. "function_call(param1, ., parm2)" is much more confusing than "function_call(param1, $, param2)".) Joe From cpl.19.ghum at spamgourmet.com Sat Apr 10 04:23:53 2004 From: cpl.19.ghum at spamgourmet.com (Harald Massa) Date: Sat, 10 Apr 2004 10:23:53 +0200 Subject: wxListCtrl with CheckBox? References: <30260531.0404092256.6b58e3a1@posting.google.com> Message-ID: > I've got a report list and want to have a checkbox in the last column > of each row. Get the checkbos in the first column of each row and use a wx.checklistbox ??? Harald From grante at visi.com Wed Apr 28 14:52:06 2004 From: grante at visi.com (Grant Edwards) Date: 28 Apr 2004 18:52:06 GMT Subject: Problem with socket References: <408f7917$0$27016$626a14ce@news.free.fr> Message-ID: <408ffd56$0$17252$a1866201@newsreader.visi.com> On 2004-04-28, Thomas Herv? wrote: > Ok I hope it's clear. My problem is that "select" only tests > if there's data on the socket, and not the state of the > socket. That's not true. If the socket is closed, it will return from select as readable. > I want to be able to know if socket is "alive" or something > like that. But I don't want to make "send" in the client (stay > passive). Then, if I know that my socket is closed or my link > down, I can try to reconnect periodically. You'll know if the socket is closed because select will mark it as readable, and you'll get 0 bytes when you read it. If you want to know if the network or the other host has "gone away", set the SO_KEEPALIVE option on the socket. That will generate an error if the link is down. IIRC, it takes 75 minutes (or is it 150?) to time out after the other end goes away. -- Grant Edwards grante Yow! I wonder if there's at anything GOOD on tonight? visi.com From bkc at Murkworks.com Mon Apr 19 10:54:32 2004 From: bkc at Murkworks.com (Brad Clements) Date: Mon, 19 Apr 2004 10:54:32 -0400 Subject: Getting output from embedded python program References: <2aa196bb.0404190554.74631058@posting.google.com> Message-ID: _ "Kim" wrote in message news:2aa196bb.0404190554.74631058 at posting.google.com... > Hi everyone, > I'm writing a embeded python program, and I want to evaluate some > expression by calling function: > > PyRun_SimpleString("print 'hello'") > > I don't want to output it to stdout but putting it into string somehow > sothat I can process it. > > Do anybody know how I can do that? > Thanks very much > Kim Sure. You can create a StringIO object and assign it sys.stdout Or, you can create C "object" with a write method and assign an instance of that object to sys.stdout. -- Novell DeveloperNet Sysop #5 From drconrad at metaplay.com.au Wed Apr 21 04:33:27 2004 From: drconrad at metaplay.com.au (Simon Wittber) Date: Wed, 21 Apr 2004 16:33:27 +0800 Subject: No built-in swap function? In-Reply-To: Message-ID: <000a01c4277b$52563aa0$0000fea9@simonxp> >That's 6 LOAD_FAST, and 3 STORE_FAST operations, plus XOR'ing. NB. I do not fully understand how psyco works. The point I was trying to make, is that I expected a psyco optimised xor swap to optimise down to ~3 CPU instructions, much like my old C compiler once did. AFAIK, psyco generates machine code, not python byte code? Sw. From alanmk at hotmail.com Thu Apr 1 05:30:24 2004 From: alanmk at hotmail.com (Alan Kennedy) Date: Thu, 01 Apr 2004 11:30:24 +0100 Subject: From python-dev, space vs. tab controversy finally settled In-Reply-To: References: Message-ID: [Carl Banks] >> Here's a summary of the final decision Guido made concerning how >> Python will indent code in the future, from python-dev: >> >> [Nice April Fool spoof :-) elided] [Josiah Carlson] > Great april fools joke, but no such conversation has gone on in > Python-Dev in the last 3 months. > > Better luck next time. Spoil-sport! You could have at least given it a few *minutes* to get some traction! -- alan kennedy ------------------------------------------------------ check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/contact/alan From fpnews at fencepost.net Tue Apr 20 18:49:22 2004 From: fpnews at fencepost.net (Alan Miller) Date: Tue, 20 Apr 2004 22:49:22 GMT Subject: mcmillan installer (domain not expired) References: Message-ID: Steve Holden (python at holdenweb.com) wrote: >Unfortunately Gordon Macmillan seems to have disappeared without trace, >which is a great pity. The macmillan-inc domain registration appears to >have expired without renewal: Actually, you typo'd that - mcmillan-inc.com is registered until April of 2005. Still, I'm on the mailing list (which survived the apparent disappearance of mcmillan-inc.com) and haven't heard anything. There was one query a few weeks ago, but no responses. ajm From bignose-hates-spam at and-benfinney-does-too.id.au Wed Apr 14 18:59:43 2004 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 15 Apr 2004 08:49:43 +0950 Subject: Method for providing a trail period on a program References: <407CF4F0.4020604@yahoo.com.au> Message-ID: On Wed, 14 Apr 2004 15:40:25 -0500, Larry Bates wrote: > I find the idea that you can give the software away and charge for > support an interesting one. So interesting that many 21st-century companies are doing just that. > If you write REALLY good software with REALLY good documentation that > provides REALLY good tracing and debugging support (so users can track > down their own problems), what are you going to charge for? That is indeed your dilemma. What are you going to provide to the user that they will want to pay for? They will *not* want to pay for "usage license", despite the current copyright law. To expect that they will is to treat them as fools or slaves. When someone already has the software in their hands, what value are you going to add that they should pay for? Some existing suggestions: installation assistance, customisation, integration with other systems, printed documentation and so on. You can probably think of others. > The reason I wanted to put a trial period on > my software was that I may have the opportunity > to place it on the CDROM with a hardware device > that is being sold. You may want to treat the hardware as a value add for your software, and charge a royalty for each bundle sold. > I would like every end user to have the opportunity of trying out my > add-on package. I am however, not prepared to let them run it forever > for free. You wish, in short, to tell them what they can do with what they have legally purchased. Would you want others to do this to you? > If it provides value to them, I believe they should purchase a > license. If you legally mandate this, you will simply motivate them to find a replacement, or crack whatever protection you put in place, or not purchase in the first place, depending on their technical ability or respect for copyright law. Why not allow those who want to pay, do so, without demanding it? The principle here is: think of things users would *want* to pay for as a user of that software, and find a way to provide that. If they can see the value of paying for something, they'll be much more motivated to do so than being forced by some intentional flaw in the software. -- \ "I don't like country music, but I don't mean to denigrate | `\ those who do. And for the people who like country music, | _o__) denigrate means 'put down'." -- Bob Newhart | Ben Finney From eppstein at ics.uci.edu Sun Apr 11 20:50:24 2004 From: eppstein at ics.uci.edu (David Eppstein) Date: Sun, 11 Apr 2004 17:50:24 -0700 Subject: print u"\u0432": why is this so hard? UnciodeEncodeError References: Message-ID: In article , "Martin v. Lowis" wrote: > Michael Hudson wrote: > > The user can set it per-terminal, at runtime, with no notification to > > the running process that it has done so! > > I would find it acceptable to say "don't do that, then", here. However, > changing the encoding should be visible to new programs running in the > terminal. > > I wonder how much would break if Python would assume the terminal > encoding is UTF-8 on Darwin. Do people use different terminal > encodings? Now I'm curious -- how do you even find out it's a Terminal window you're looking at, rather than say an xterm? -- David Eppstein http://www.ics.uci.edu/~eppstein/ Univ. of California, Irvine, School of Information & Computer Science From hi at there.com Sat Apr 17 00:34:00 2004 From: hi at there.com (marvin) Date: Sat, 17 Apr 2004 04:34:00 GMT Subject: editing a wxGrid Message-ID: hi- i worked on a project in TCL/TK found at j_m_mc.tripod.com. I want to allow the user to edit the table using wxGrid and python. I'm just looking for some tips. For i.e. in sqlite and TCL most data is represented as a string. When do data types become an issue in this instance? If I allow the user to edit directly in a cell it seems it doesnt really matter because you can only enforce data validation if i use a form anyways as far as the data types go. I mean with sqlite the primary reason for using data types is in case i want to ever switch dbs. I cant remember off the top of my head but I think access or paradox would complain if you used a string for instance in a date field. So without some checking be in forced maybe it is not a good idea to directly allow editing in the table anyways. Is a better way stepping through or searching the array that populates the TkTable query result and tying it to a form that validates somehow? bottom line...i'm looking to extend my program a little and wondered if anything along these lines is feasible. thanks, marvin From hugh-m at moving-picture.com Fri Apr 16 04:22:58 2004 From: hugh-m at moving-picture.com (Hugh Macdonald) Date: Fri, 16 Apr 2004 09:22:58 +0100 Subject: CamelCase versus wide_names (Prothon) In-Reply-To: <87d6692ar8.fsf@blakie.riol> References: <87hdvl2dny.fsf@blakie.riol> <87d6692ar8.fsf@blakie.riol> Message-ID: <20040416092258.3d4f831a.hugh-m@moving-picture.com> On Thu, 15 Apr 2004 23:26:35 +0200 Wilk wrote: > On azerty keyboard _ is under 8 and does'nt need to press shift... I > did'nt remember that it's diffent on qwerty. On a qwerty keyboard, _ is SHIFT+- (to the right of 0) -- Hugh Macdonald The Moving Picture Company From fredrik at pythonware.com Fri Apr 23 05:01:56 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 23 Apr 2004 11:01:56 +0200 Subject: Regexp optimization question References: Message-ID: Magnus Lie Hetland wrote: > but now I have to find out which one of them matched at a > certain location. the techniques discussed in this article may be helpful: http://effbot.org/zone/xml-scanner.htm From bkelley at wi.mit.edu Wed Apr 14 13:09:20 2004 From: bkelley at wi.mit.edu (Brian Kelley) Date: Wed, 14 Apr 2004 13:09:20 -0400 Subject: [wxPython] MVC example? In-Reply-To: <407d7000$0$579$b45e6eb0@senator-bedfellow.mit.edu> References: <407d7000$0$579$b45e6eb0@senator-bedfellow.mit.edu> Message-ID: <407D7040.5000104@wi.mit.edu> Small typo... Brian Kelley wrote: > The cool thing is that anything modifying the model will notify the > model. In this case it is the controller modifying the model, but it > could be anything else, even another controller off in the distance > looking at something else. The cool thing is that anything modifying the model will notify the controller. From ville at spammers.com Tue Apr 27 02:46:45 2004 From: ville at spammers.com (Ville Vainio) Date: 27 Apr 2004 09:46:45 +0300 Subject: Is Perl *that* good? (was: How's ruby compare to it older brother python) References: <108q51j4dscn7dc@corp.supernews.com> Message-ID: >>>>> "Leif" == Leif B Kristensen writes: Leif> Here's a small sample: Leif> $str =~ s/HN/N/g; # John --> JON Leif> $str =~ s/TH/T/g; # Thor --> TOR Leif> $str =~ s/CHI/KJ/g; # Torchild --> TORKJL ... Isn't that trivial in all languages that support regexps? All too often Perl gets too much credit for doing things that are every bit as easy/easier in other languages. As a bonus, this python snippet returns the changes done for every individual regex pair: ------------- import re repls = [ ('NH','N'), ('TH','T'), ('CHI','KJ'), ('hel.*o','ll') # one regex just for show ] def subst_many(pairs, s): res = [] for pat,repl in pairs: s, n = re.subn(pat, repl, s) res.append(n) return s,res result, changes_done = subst_many(repls, my_text_file) -- Ville Vainio http://tinyurl.com/2prnb From claird at lairds.com Thu Apr 15 07:03:01 2004 From: claird at lairds.com (Cameron Laird) Date: Thu, 15 Apr 2004 11:03:01 -0000 Subject: Why Activestate Python ? References: <8089854e.0404090025.141f090c@posting.google.com> <1afv95dy6164y.1a9l3etptcw8w.dlg@40tude.net> Message-ID: <107sqv5o109su9f@corp.supernews.com> In article <1afv95dy6164y.1a9l3etptcw8w.dlg at 40tude.net>, Andrei wrote: >Fuzzyman wrote on 9 Apr 2004 01:25:45 -0700: > >> Again... a silly newbie question which might have an obvious >> answer.... but *why* is their an alternative distribution of python by >> activestate ? >> >> Apart fromt he fact that they bundle Mark Hammond's Windows Extensions >> with it (in the windows version) - what is to be gained from using >> their distributio instead of the 'normal' one ? > >You also get PythonWin and nice docs. Python might have good HTMLHelp >format docs by now as well, but last time I tried, there were many broken >things in it. At some point I was running an official Py2.3 >because ActiveState was a bit slow in releasing a 2.3 version, but I >continued to use the docs from ActiveState Py 2.2.X. Now I have their 2.3.2 >distribution installed. > >Apart from that, it's Python. Depending on what your usage pattern is, you >might not even notice what you have on your HD. . . . I'm not sure what kind of an answer the original questioner is after. It's a fact, though, that some organizations (still!) only understand "commercial" products. Developers and admini- strators in such organizations simply are allowed no access to standard Python; they're able to get on with their work only because of the availability of ActiveState Python. -- Cameron Laird Business: http://www.Phaseit.net From alloydflanagan at comcast.net Tue Apr 13 11:46:41 2004 From: alloydflanagan at comcast.net (A. Lloyd Flanagan) Date: 13 Apr 2004 08:46:41 -0700 Subject: FutureWarning question References: <16mnetilcmds6.1apnyu46tbjpw.dlg@40tude.net> Message-ID: Mike wrote in message news:<16mnetilcmds6.1apnyu46tbjpw.dlg at 40tude.net>... > I ran across the message below in 2.3.2 today. These are the lines of code: > > 402: if m1_hi >> 15 & 0x0001 == 1: > 403: m1_hi = m1_hi | 0xFFFF0000 > 404: if m1_lo >> 15 & 0x0001 == 1: > 405: m1_lo = m1_lo | 0xFFFF0000 > > This is the warning message: > > pwg.py:403: FutureWarning: hex/oct constants > sys.maxint will return > positive values in Python 2.4 and up > m1_hi = m1_hi | 0xFFFF0000 sys.maxint is the largest number that will fit into an int data type. Although your constant is 32 bits, the high bit is set, so it gets interpreted as a negative number. >>> x = 0xFFFF0000 >>> x -65536 In future versions of python, constants which are larger than sys.maxint will not be interpreted as negative, but will automatically be promoted to a long integer. The distinction between the two integer types will pretty much disappear. So, your constant will evaluate to a positive long integer (4294901760L). Since you're using it as a bit mask, and not a number, I don't think it will make a difference for your application. But the compiler can't tell for sure, so it warns you anyway. From mcfletch at rogers.com Wed Apr 21 15:11:43 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Wed, 21 Apr 2004 15:11:43 -0400 Subject: Time In-Reply-To: References: Message-ID: <4086C76F.5060505@rogers.com> That format is the ISO standard date-time format. The modern way to work with date-times in Python is to use the datetime module, so: >>> import datetime >>> d = datetime.datetime( 2004, 4, 21, 15, 05) >>> d.isoformat() '2004-04-21T15:05:00' You can use datetime.datetime( * mytuple ) to auto-unpack your tuple, btw. HTH, Mike Jonas Galvez wrote: >If I have a tuple like this: > > (year, month, day, hour, minute) > >Is there a way to automatically generate a string like this? > > "YYYY-MM-DDTHH:MM:00" > >I remember seeing something about it somewhere... wanted to be sure. > > ... _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From Mike at DeleteThis.Geary.com Sat Apr 24 12:46:54 2004 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Sat, 24 Apr 2004 09:46:54 -0700 Subject: Why we will use obj$func() often References: <8AWhc.23114$dZ1.11070@fed1read04> <40883BFE.B381518A@alcyone.com> <27_hc.23801$dZ1.2716@fed1read04> <40887145.789A2FE8@alcyone.com> <7cki80hj976bia36lhf9er97v073o1pqvm@4ax.com> <1082783076.585831@yasure> Message-ID: <108l6fvhl7fq29c@corp.supernews.com> David MacQuigg wrote: > How about instead of decorating variables with special > symbols or capitalization, we have a rule that says any > variables with unusual scope must be declared in a > statement at the top of the function where they are used. > So for example > > def func( x, y ): > global a, b, c ### module level > external d, e, f ### one level up > ... > > This would avoid the need for new and unique symbols, > would unclutter the code in the body of the function, would > provide a single place where you could see the scope of any > unusual variable, and would answer the question "What > external dependencies does this function have?" Does it > satisfy the need you are seeing for & variables? Hey, that is a great idea, David. I definitely like it better than the & notation. It would work in Python as well as Prothon, and give me clean and readable closures like I have in JavaScript. I would want it to mean: external d, e, f # # # search up the scope chain because I often want to use variables from scopes more than one level up. And maybe another word would be better than 'external' (although I don't have one in mind). But the idea is terrific. > Python added "read access" to external variables, so they > must have considered "write access" as well. I don't know > the history, but I would guess the reason they didn't allow > this is the same as the reason they don't allow GOTO. Yes > it is powerful, but it might encourage bad programming. We're both speculating, of course, but my guess is simply that automatic creation of variables by assignment conflicts with writing to variables from outer scopes. The global statement solves this for global variables, but no one thought it important enough to do something for nested scopes as well. Just my guess. > Can you imagine having to debug a large program where > none of the functions have any arguments, just &vars buried > in the bodies of the functions? That is the kind of code that > might be written by someone who does not want to think > ahead. You can write the call() first, then use & variables > whenever you need an argument. These are the kind of > things that must be considered when looking at a new > feature for a language. In JavaScript, I often use nested functions to factor out common operations within a function--things that are done repeatedly inside that function but aren't of interest outside the function. Lexical scoping lets me do that without the nuisance of passing in the same arguments to all these nested functions, or creating some little object for that purpose. I could post some sample code if anyone wants, but I fear I may have posted too much JavaScript code here already. :-) But the point is that I use this very thing to make my code simpler and more readable. -Mike From greg at cosc.canterbury.ac.nz Thu Apr 22 22:39:19 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Fri, 23 Apr 2004 14:39:19 +1200 Subject: Why we will use obj$func() often In-Reply-To: <8AWhc.23114$dZ1.11070@fed1read04> References: <84Uhc.22278$dZ1.5087@fed1read04> <8AWhc.23114$dZ1.11070@fed1read04> Message-ID: Mark Hahn wrote: > Mike C. Fletcher wrote: >> By the way, the modern Python idiom is: >> >> super( klass2, self ).func( ) > > You're kidding. That seems like a big leap backwards in friendliness. Don't worry, the traditional form of super call in Python isn't going away any time soon. It's not replaced by this; they do different things. The new form is occasionally needed, but not very often. I haven't found a use for it myself yet. (I *thought* I had found one the other day, but it turned out I hadn't.) -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From danb_83 at yahoo.com Fri Apr 16 01:26:08 2004 From: danb_83 at yahoo.com (Dan Bishop) Date: 15 Apr 2004 22:26:08 -0700 Subject: CamelCase versus wide_names (Prothon) References: <107tjp2qvgof4b0@corp.supernews.com> Message-ID: "Michael Geary" wrote in message news:<107tjp2qvgof4b0 at corp.supernews.com>... > Kevin Altis wrote: > > If you're using PEP 8 terminology then CamelCase is different > > than mixedCase. CamelCase is often used for class names and > > mixedCase for everything else. > > Just to add to the confusing terminology, in some circles mixed case with an > initial lowercase letter is called camelCase, while mixed case with initial > uppercase is called PascalCase. :-) Is there really a standard case convention for Pascal? What's the point of having one for a case-insensitive language? > The initial capital letter actually has significance in Prothon (I > think--unless that has changed). So the question is whether to use > NamesLikeThis and namesLikeThis, or Names_like_this and names_like_this. I prefer [Nn]amesLikeThis. Except for module_names. From paul at prescod.net Mon Apr 5 06:09:36 2004 From: paul at prescod.net (Paul Prescod) Date: Mon, 05 Apr 2004 03:09:36 -0700 Subject: Python is faster than C In-Reply-To: <36wn05qkeyk.fsf@hundertwasser.ti.uni-mannheim.de> References: <36wn05qkeyk.fsf@hundertwasser.ti.uni-mannheim.de> Message-ID: <40713060.7080305@prescod.net> Matthias wrote: >... > > Isn't the whole idea of very high level languages to shift complexity > from the user code to the language implementation? Shift code, yes. Shift complexity? Not necessarily. Ideally both the language implementation and the programs that use the implementation are both simple. Unoptimized code tends to be simpler than heavily optimized code. If you can get away without optimizing either then you win. > That's not a rhetorical question: Why is it that "simplicity of the > Python VM is an important goal"? > ... I would guess that overall it pays > to have a more complex language implementation and be rewarded by > simpler user code: For any decent language there's much more user code > out there than language implementation code. It pays whom? The relatively tiny team of volunteer maintaining the Python interpreter? The team at Nokia porting it to cell phones? Jim Hugunin porting it to the .NET platform? The Jython guys? "C is a programming language designed for writing Unix, and it was designed using the New Jersey approach. C is therefore a language for which it is easy to write a decent compiler, and it requires the programmer to write text that is easy for the compiler to interpret. Some have called C a fancy assembly language. Both early Unix and C compilers had simple structures, are easy to port, require few machine resources to run, and provide about 50%--80% of what you want from an operating system and programming language. Half the computers that exist at any point are worse than median (smaller or slower). Unix and C work fine on them. The worse-is-better philosophy means that implementation simplicity has highest priority, which means Unix and C are easy to port on such machines. Therefore, one expects that if the 50% functionality Unix and C support is satisfactory, they will start to appear everywhere. And they have, haven't they? Unix and C are the ultimate computer viruses." * http://www.jwz.org/doc/worse-is-better.html Python is the next viral tchnology. > One example where Python in the past made (in my opinion, for my > particular projects) the wrong choice is speed: People argued that > "simplicity of the Python VM" is more important than speed gains. The > result (for my code) was that after profiling, etc., I was coding > significant parts of my programs in C. No productivity gain > observed. With JIT compilation (psyco) this step might become > unnecessary: More complex VM, greatly simplified user code. That's why it is great that there are things like Pyrex and Pysco for you to use. The fact that you can benefit from them without making Guido's life harder (or that of Nokia or ...) is even better! Paul Prescod From thefirstofnovember at yahoo.com Mon Apr 19 09:54:12 2004 From: thefirstofnovember at yahoo.com (Kim) Date: 19 Apr 2004 06:54:12 -0700 Subject: Getting output from embedded python program Message-ID: <2aa196bb.0404190554.74631058@posting.google.com> Hi everyone, I'm writing a embeded python program, and I want to evaluate some expression by calling function: PyRun_SimpleString("print 'hello'") I don't want to output it to stdout but putting it into string somehow sothat I can process it. Do anybody know how I can do that? Thanks very much Kim From Mike at DeleteThis.Geary.com Tue Apr 13 12:53:29 2004 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Tue, 13 Apr 2004 09:53:29 -0700 Subject: Once-only evaluation of default parameter values function definitions References: <407B79D7.424F65A1@doe.carleton.ca> <107n2g6q9an672b@corp.supernews.com> <407BB8F5.E694AA49@doe.carleton.ca> Message-ID: <107o6ob2lhppnbd@corp.supernews.com> Fred Ma wrote: > Thanks, Mike. That's alot clearer. The default value looks like it's > a persistent object. It is similar to a static local variable in C++. > In Example#1, that object actually got changed. In contrast, in > Example#2, the code prevents L from remaining bound to None > beyond the first line, so the None object never gets changed. In > fact, my 2nd explanation was close: that there is an unnamed > persistent object that holds the default value to be bound to L for > invocations that don't explicity supply an argument for L. The > place I went wrong was to say that L never gets bound to None > again, after it has been bound to a caller supplied object on a > previous invocation of the function. That's just about right, Fred. More precisely, the default value is as persistent as the function definition itself (as opposed to a particular invocation of the function). Shalabh's message has some more details and tips. BTW, I'd say you're doing great for one day with the language! -Mike From joe at notcharles.ca Mon Apr 12 10:58:46 2004 From: joe at notcharles.ca (Joe Mason) Date: Mon, 12 Apr 2004 14:58:46 GMT Subject: How to get value of parent class References: Message-ID: In article , Jean-Pierre Bergamin wrote: > Hello > > I have the following class structure: > > > class MyServer: > > x= 0 > > class MyHandler(SocketServer.StreamRequestHandler): > def handle(self): > if x: # <---- How to get the X from the parent class? > # Or how to pass a value to this class anyway? > do_something() Just say "MyServer.x". Joe From hwlgw at hotmail.com Wed Apr 14 15:30:22 2004 From: hwlgw at hotmail.com (Will Stuyvesant) Date: 14 Apr 2004 12:30:22 -0700 Subject: Aspect Programming Module References: <84fc4588.0404140106.3fa0c55@posting.google.com> Message-ID: > [Alexandre Fayolle, being a good employee] > You may want to try the logilab.aspects package, available at > http://www.logilab.org/projects/aspects/ I am afraid you are serious. AOP is *not needed* for Python programmers. Plain and simple. Don't understand? Try this: "AOP is a contrived way to get around the limitations of a statically typed language." Put that on the logilab website. And hire somebody to repair the broken English over there, it looks really, um...oh well I am not a native English speaker myself either. -- "For the costs of subsidized agriculture in the EU, we can have all 56 million European cows fly around the world. First Class." -- J. Norberg From jjl at pobox.com Mon Apr 19 17:53:55 2004 From: jjl at pobox.com (John J. Lee) Date: 19 Apr 2004 22:53:55 +0100 Subject: Generic constructors and duplication of internal Python logic References: <87ekqq41ya.fsf@pobox.com> <95aa1afa.0404150033.79a53e1a@posting.google.com> Message-ID: <87k70bzlak.fsf@pobox.com> michele.simionato at poste.it (Michele Simionato) writes: > jjl at pobox.com (John J. Lee) wrote in message news:<87ekqq41ya.fsf at pobox.com>... > > I have to check things like: > > > > -are there too many positional arguments? > > -any unexpected keyword arguments? > > -multiple keyword arguments? > > -any duplication between positional and keyword arguments? > > > > etc. > > > > Surely there's some easy way of making use of Python's internal logic > > here? For some reason, I can't see how. Can anybody see a way? > > > > > > John > > Have you thought of performing the checks in the __call__ method > of a custom metaclass? No. How would that help? John From jeremy+plusnews at jeremysanders.net Sun Apr 18 08:39:41 2004 From: jeremy+plusnews at jeremysanders.net (Jeremy Sanders) Date: Sun, 18 Apr 2004 13:39:41 +0100 Subject: os.system help References: <78lgc.3445$AL1.7744@news1.mts.net> Message-ID: On Sat, 17 Apr 2004 23:32:01 -0500, Reid Nichol wrote: > Unfortunately PIL only writes .eps files. I was going to get the users > to install gs but of course it's install directory is variable. I've > tried using shortcuts but that didn't work. > > Since most of my intended users use windows only... I'm not familiar with GS on Windows, but it may be worth searching the registry to see whether the install path is written there. Jeremy From newsuser at itgoesclick.com Wed Apr 21 16:15:11 2004 From: newsuser at itgoesclick.com (Noah from IT Goes Click) Date: Wed, 21 Apr 2004 20:15:11 GMT Subject: Stupid Regex Question In-Reply-To: References: Message-ID: small loop problem? Jonas Galvez wrote: > I'm feeling dumb: > > str = "textmoretexttext" > > How can I get a list like ["textmoretext", > "text"] using regexes? I'm starting to believe it's not possible. > > Yeah, I know about the terror stories about using regexes to parse > HTML, but in this particular case, using a SAX parser would be an > horrendous overhead (I mean, it's a ridiculously simple string). > > > > =- > Jonas Galvez > jonasgalvez.com/blog > macromedia.com/go/team > > > > > From joe at notcharles.ca Wed Apr 14 19:09:07 2004 From: joe at notcharles.ca (Joe Mason) Date: Wed, 14 Apr 2004 23:09:07 GMT Subject: Aspect Programming Module References: <84fc4588.0404140106.3fa0c55@posting.google.com> Message-ID: In article , Will Stuyvesant wrote: >> [Alexandre Fayolle, being a good employee] >> You may want to try the logilab.aspects package, available at >> http://www.logilab.org/projects/aspects/ > > I am afraid you are serious. > > AOP is *not needed* for Python programmers. Plain and simple. > > Don't understand? Try this: > > "AOP is a contrived way to get around the limitations of a statically > typed language." Care to explain that? What I've seen of AOP seems like a very dynamic design philosophy. Joe From no.spam at no.spam.com Tue Apr 20 06:40:04 2004 From: no.spam at no.spam.com (Maciej Sobczak) Date: Tue, 20 Apr 2004 12:40:04 +0200 Subject: How to check if a path *could* be a legal path? Message-ID: Hi, I have a string. This string is to be used as a path for a new file. I would like to check if this string *could be* a valid file name, *before* I try to create the file itself. In other words, I would like to know whether some string violates the underlying OS's policies (or maybe some more restriced policies, but portable) considering file paths. Example: 1. s = 'C:\file.txt' the above is potentially a valid path on my system. 2. s = 'cc:/^- =#jk\kj+.+?! :-)' the above is rather invalid and I would like to check it somehow before I even try to create the file. Does the Python library contain a functionality that allows to achieve this goal? -- Maciej Sobczak : http://www.msobczak.com/ Programming : http://www.msobczak.com/prog/ From newsgroups at jhrothjr.com Wed Apr 21 06:31:09 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Wed, 21 Apr 2004 06:31:09 -0400 Subject: When is a __dict__ not a __dict__? References: <4085f2a4$0$16601$5a62ac22@freenews.iinet.net.au> Message-ID: <108cjb4qmlsk050@news.supernews.com> "Derek Fountain" wrote in message news:4085f2a4$0$16601$5a62ac22 at freenews.iinet.net.au... > Am I correct in thinking that a Python object which comes from a bit of C > code doesn't have a __dict__ attribute? I'm trying to poke around inside > the objects which control the expat XML parser, but they don't seem to have > __dict__s. It depends on the object. Some do, many don't. John Roth From nospam at kochandreas.com Sun Apr 25 14:03:25 2004 From: nospam at kochandreas.com (Andreas Koch) Date: Sun, 25 Apr 2004 20:03:25 +0200 Subject: Andreas' practical language comparison In-Reply-To: References: Message-ID: Peter Hansen wrote: > You might want to put a little more thought into the way you > present the information there. As it stands, it appears likely > to heavily influence people to produce the shortest possible > programs, rather than the most readable or even most typical for > a given language. A valid point. We currently have a discussion about this top on c.l.misc, where i made my first proposals for my site. Feel free to join in. > I sent bubble sort, based on the algorithm, but I'm not going > to bother with more if this is simply a fewest-lines competition, > since the first person to post some Perl will win (although K > appears to be ready to give tight competition in that area, > if the current list is any indication). It is on no way a fewest-lines competiton, especially considering that my favourite language (Delphi) had the most lines in nearly every test case :-) I removed the line counts from the overview matrix until we find a better solution. -- Andreas He screamed: THIS IS SIG! From sjf at autograf.pl Mon Apr 26 08:49:38 2004 From: sjf at autograf.pl (..:: sjf ::..) Date: Mon, 26 Apr 2004 14:49:38 +0200 Subject: Regular Expressions Message-ID: Hello, I would like to please to help me with build a regular expression. There are following piece of html code in my files: A - TYPE1: any_text
B - TYPE2: any_text_2
C - TYPE2: any_text_3
w - any_text_15
html code I need to have only following data: (B, any_text_2) (C, any_text_3) that is, these data TYPE2 in which. Thanks in advance -- .:: sjf ::.. "Linux is like Wigwam. No gates, no windows... Apache inside ;-)" From Kyler at news.Lairds.org Thu Apr 1 21:08:07 2004 From: Kyler at news.Lairds.org (Kyler Laird) Date: Fri, 02 Apr 2004 02:08:07 GMT Subject: Pyrex gets a perfect score. References: <905fcd91.0404011433.6681abd9@posting.google.com> Message-ID: rlratzel at siliconmetrics.com (Rick Ratzel) writes: >...just curious...did you look at Elmer >(http://elmer.sourceforge.net)? I hadn't. (I'm partial to Debian packages.) The description "Elmer is not a Python-to-C or Python-to-Tcl translator" makes me think that it's not appropriate for what I need right now - the ability to submit only C code. It does look like it would be useful for later work though. I think it's likely to provide cleaner interfaces than what I was able to generate using Pyrex. Thank you. --kyler From peter at engcorp.com Sat Apr 10 08:31:01 2004 From: peter at engcorp.com (Peter Hansen) Date: Sat, 10 Apr 2004 08:31:01 -0400 Subject: Python for MPG In-Reply-To: References: Message-ID: Will Stuyvesant wrote: > Is there Python software for dealing with MPG movies? I am not > interested in visual effects etc. but in cutting scenes from big MGP > files and creating new files with those scenes. Found via Google: http://www.mpgedit.org/mpgedit/ From root at mbtricot.it Sun Apr 25 10:41:43 2004 From: root at mbtricot.it (root at mbtricot.it) Date: Sun, 25 Apr 2004 16:41:43 +0200 Subject: Virus Alert Message-ID: <200404251441.i3PEfhV20325@linuxbox.mbtricot.it> The mail message (file: email-body) you sent to mbtfederico contains a virus. (InterScan on linuxbox.mbtricot.it) From fumanchu at amor.org Fri Apr 23 01:24:19 2004 From: fumanchu at amor.org (Robert Brewer) Date: Thu, 22 Apr 2004 22:24:19 -0700 Subject: Deleting objects - my earler post got garbled Message-ID: Asun Friere wrote: > "Martin v. L?wis" wrote in message > news:<40883067.4000702 at v.loewis.de>... > > > There is no way to explicitly delete an object in Python. > > So what does "del " actually do then? There is no "del ", only "del ". Therefore: "Deletion of a name removes the binding of that name from the local or global namespace, depending on whether the name occurs in a global statement in the same code block." as written at: http://docs.python.org/ref/del.html Robert Brewer MIS Amor Ministries fumanchu at amor.org From mcfletch at rogers.com Mon Apr 5 16:43:23 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Mon, 05 Apr 2004 16:43:23 -0400 Subject: slightly OT: BUT NEEDs to be said In-Reply-To: <8b42d1998c978c8c1cddf15c52a1c57b@dizum.com> References: <8b42d1998c978c8c1cddf15c52a1c57b@dizum.com> Message-ID: <4071C4EB.9070404@rogers.com> Oh, I *so* have more important things to do :) , but okay, I'll play along for a few seconds... Nomen Nescio wrote: >In article , Peter Hansen >wrote: > > ... >Cuddly cartoon characters like the Snake, or various BSD creatures = highly >acceptable and good. > > In terms of "acceptable and good" I think you'll find that Snakes and Devils/Daemons aren't really high on many people's lists, but then you know that and are just yanking the chain ;) . >MPFC = too aristically/politically/socially 'loaded' to be acceptable. > > Here's the thing, you object to the use of MPFC because you see the particular show as a *silly* waste of money. It's *not taking yourself so seriously that you lose your sense of humour* that makes MPFC a fine choice. The commercial-tower Oak runs around telling the world that it's the second coming of computer science, the caffeinated solution to all your problems if you'll just sit down and drink the acorn tea. It knows that if it can just scream loud enough then people will overlook it's poor character and weird obsessions and maybe pronounce it king. Python hasn't developed that level of insecurity, it's perfectly willing to admit its failings, it's happy to poke fun at itself and admit that it needs C to be successful; sure, it's better and more privileged than all of the other programming languages; sure, it's had the best education and derived huge benefit from it; sure, it's received patronage from the programming elite; sure, it has metaclasses, list comprehensions and descriptors like any decent ivory-tower language; but in the end, all that means nothing if it can't find the humanity in the situation of explaining things to computers, if you can't make programming just a little easier for the regular folks. And if you are taking all *that* seriously, then really, go do a funny walk somewhere and relax about it. We all pay taxes, and sometimes it funds things we don't like, it's part of modern life. Sometimes other people like TV shows we think are insipid or offensive, this too is part of life, and if you realise and accept that (within reason) you'll be happier and more content. Oh, and I like the snake more than the TV show too ;) . Good luck with coming to terms with all this, Mike _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From dwelch91 at comcast.net Sun Apr 4 18:15:49 2004 From: dwelch91 at comcast.net (djw) Date: Sun, 04 Apr 2004 22:15:49 GMT Subject: splitting a long token across lines In-Reply-To: References: Message-ID: Nakamura wrote: > Hi all, > > Say, I have a very long integer constant , how can > I split across lines ? > I tried something like > MODULUS = 7567567567567567567567567567567\ > 7567507546546986094860986094860\ > 2345646986598695869548498698989\ > ... > but it doesn't compile. > Is there another way to write a long numeric constant besides writing > it as a string and then converting to long? I also wouldn't like to put > it all on one very long line. > > Thanks! Well, I _suppose_ you could do this: MODULUS = "7567567567567567567567567567567"\ 7567507546546986094860986094860"\ 2345646986598695869548498698989"\ ... MODULUS = int(MODULUS) I'm sure I'm going to have to take some flak for this, though. I wouldn't do it. What's wrong with really long lines? Anything you do that I can see is going to obscure your code. -D From nmkolev at uni-bonn.de Sun Apr 4 10:25:44 2004 From: nmkolev at uni-bonn.de (Nickolay Kolev) Date: 4 Apr 2004 14:25:44 GMT Subject: =?utf-8?q?Re=3A_Working_with_a_list_in_a_more_=C2=84pythonic?= =?utf-8?b?wpMgd2F5?= References: <20040404124833458+0200@news.rhrz.uni-bonn.de> Message-ID: <20040404162551445+0200@news.rhrz.uni-bonn.de> > def get_val(x): > # gets the value from SSMatrix, now dumb > return ord(x) The point is to sum the transitions *between* the characters and the matrix only contains those scores. So "getting the value from SSMatrix" for a single character makes no sense (and is impossible). Nicky From bwglitch at hotpop.com Tue Apr 13 09:47:17 2004 From: bwglitch at hotpop.com (BW Glitch) Date: Tue, 13 Apr 2004 08:47:17 -0500 Subject: Logging Stacktrace To File In-Reply-To: <407bdce5$1_1@newspeer2.tds.net> References: <407bcbca$1_2@newspeer2.tds.net> <407bdce5$1_1@newspeer2.tds.net> Message-ID: Olaf Meding wrote: >>... have to catch the exception and then log it to the file. > > > Right. I do also know how to open a file and write to it. > > But how do I get at the stack trace? I would like to have it look the same > in the file as what gets printed to the screen. The traceback module provides you with that hook. The function is traceback.print_exc and you can pass a file-like object in the second parameter. -- Glitch http://andres980.tripod.com/tf.html "... You WIN, you depraved wad a' stinkin' slag." "Cultivated as always, even in defeat." -- Rattrap and Megatron, "Fallen Comrades" From no.email at please.com Mon Apr 12 05:54:53 2004 From: no.email at please.com (Stevie_Mac) Date: Mon, 12 Apr 2004 10:54:53 +0100 Subject: pythonwin crash (used to work) - please help quick. References: <5Reec.62668$Id.61067@news-binary.blueyonder.co.uk> Message-ID: I think seen somthing like this on net somewhere when i was searching. So if I understand this, a python GUI can't debug a script that uses code from any other GUI implementation (like wx for example)? If so, dang! Whats my options - different IDE - or - no debug! wait, im sure when I tried to run the script direct (through python and pythonw) it still bombed - but in pyShell it didn't - hows that? Stevie_Mac :confused: "Paul Prescod" wrote in message news:mailman.537.1081743469.20120.python-list at python.org... > Stevie_mac wrote: > > > OS=XP, Python 2.3, wx2.5.1.5u > > Not sure what's to blame here - or to be more precise, how to fix it!... > > > > If I do this in PythonWin... > > import wx > > d = wx.Dialog(None, -1, 'title') > > BANG - IDE crashes > > It typically doesn't work to have two GUIs in one process. PythonWin > uses MFC. Wx is a totally different GUI. > > Paul Prescod > > > From ae Mon Apr 12 18:05:16 2004 From: ae (A Evans) Date: Mon, 12 Apr 2004 15:05:16 -0700 Subject: I am puzled about numbers References: <107lvs6mree8pee@corp.supernews.com> <107m446tlvs9u01@corp.supernews.com> <4NqdnV5ZNrU-jObdRVn-hA@powergate.ca> Message-ID: <107m4l5bl2kq759@corp.supernews.com> Hey Sorry about that I will remember to search google next time before asking questions on the forum Thanks for the link Cheers From beliavsky at aol.com Thu Apr 29 10:06:59 2004 From: beliavsky at aol.com (beliavsky at aol.com) Date: 29 Apr 2004 07:06:59 -0700 Subject: debugging code References: <3064b51d.0404271139.6ec7057@posting.google.com> <408ee541$0$46510$39cecf19@news.twtelecom.net> <3064b51d.0404280658.ccf1894@posting.google.com> <408fe602$0$3708$39cecf19@news.twtelecom.net> Message-ID: <3064b51d.0404290606.1fe669aa@posting.google.com> Rick Ratzel wrote in message news:<408fe602$0$3708$39cecf19 at news.twtelecom.net>... > beliavsky at aol.com wrote: > > > > > > > > Thanks -- I will take your suggestion. Where are the Python command > > line options like -O and -OO documented? Typing 'python -h' just gives > > me > > > > -O : optimize generated bytecode (a tad; also PYTHONOPTIMIZE=x) > > -OO : remove doc-strings in addition to the -O optimizations > > Thats strange. Here they are for Python 2.3.3 as built on my system > (should be the same for you): I get the same output from 'python -h'. What I meant to say is that I am looking for more detailed documentation of the Python interpreter options. I looked briefly on python.org and did not find it. From mark at prothon.org Fri Apr 23 17:00:03 2004 From: mark at prothon.org (Mark Hahn) Date: Fri, 23 Apr 2004 14:00:03 -0700 Subject: Why we will use obj$func() often References: <84Uhc.22278$dZ1.5087@fed1read04> <8AWhc.23114$dZ1.11070@fed1read04> <+PXiAls/Kj/Q089yn@the-wire.com> Message-ID: "Mel Wilson" wrote ... > connection = serial.Serial ( ... ) > # connection is a file-like object, > # having the usual `write` method > > engine = MyFiniteStateMachine () > # engine happens to have a `writer` method that > # funnels out the machines products > # The default is effectively `def writer (self, s): print s` > > engine.writer = connection.write > # we channel engine's output through the serial connection > > Plugged together, it just works, as Mike says. No > trouble when engine's internal calls to `self.writer` end up > accessing a completely different object's method. It's only > lately that I've stopped to gawp at it, and wonder. That is a powerful testimonial to the "walks like a duck" principal which has nothing to do with classes or prototypes. Thankfully that works in a simple classless language like the current Prothon. From greg at cosc.canterbury.ac.nz Mon Apr 26 20:47:56 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Tue, 27 Apr 2004 12:47:56 +1200 Subject: Why we will use obj$func() often In-Reply-To: References: <84Uhc.22278$dZ1.5087@fed1read04> <8AWhc.23114$dZ1.11070@fed1read04> <40883BFE.B381518A@alcyone.com> <27_hc.23801$dZ1.2716@fed1read04> <40887145.789A2FE8@alcyone.com> <7cki80hj976bia36lhf9er97v073o1pqvm@4ax.com> <1082783076.585831@yasure> Message-ID: Mark Hahn wrote: > You cannot. Yes it literally means the immediately surrounding function. > In your example, I can't think of any scheme we've discussed that accesses x > in function f. Python surely cannot. Python can't write to it, but at least it can read it. Prothon apparently can't even read it. > As always, I'm open to suggestions... I can't think of any way to fix this that preserves the single-pass requirement, short of introducing some kind of declaration in the scope where the variable is defined. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From simoninusa2001 at yahoo.co.uk Sat Apr 10 02:56:42 2004 From: simoninusa2001 at yahoo.co.uk (simo) Date: 9 Apr 2004 23:56:42 -0700 Subject: wxListCtrl with CheckBox? Message-ID: <30260531.0404092256.6b58e3a1@posting.google.com> I've got a report list and want to have a checkbox in the last column of each row. I can't use SetItem to put the control there, not even a ToggleBox, and I haven't been able to superimpose the checkbox on top of the ListCtrl either (that was a desperate attempt, which would have involved lots of nasty looping to get the position for each row!) The only way to do it I've seen is to have an image that switches when you click: http://wiki.wxwindows.org/wiki.pl?WxListCtrl But then I don't think you will get the right event (you only get the row click event, not neccesarily the image click) and I already have a row click event, plus I'm pretty sure images are only for the first column. Is there a better way? I was hoping wxWidgets 2.5 was going to have this widget, or better still, the ability to put any [reasonable] control into a list cell.... On a side note, I've just installed wxPython and Python 2.3 onto a friend's LindowsOS box using a single apt-get command, it was a much nicer experience than compiling everything in RedHat9 and then rebuilding an RPM to upgrade to 2.5.1.5 From NAIGIMSESRIMAIL at gims.com Thu Apr 1 05:53:55 2004 From: NAIGIMSESRIMAIL at gims.com (GroupShield for Exchange (ESRIMAIL)) Date: Thu, 1 Apr 2004 12:53:55 +0200 Subject: ALERT - GroupShield ticket number OB70_1080816829_ESRIMAIL_3 was generated Message-ID: Action Taken: The message was blocked because of its subject. To: python-list at python.org From: Peter Otten <__peter__ at web.de> Sent: -1653591296,29628375 Subject: Re: test for nan Attachment Details:- Attachment Name: N/A File: Infected.msg Infected? No Repaired? No Blocked? Yes Deleted? No Virus Name: -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/ms-tnef Size: 1809 bytes Desc: not available URL: From dmq at gain.com Fri Apr 9 18:09:32 2004 From: dmq at gain.com (David MacQuigg) Date: Fri, 09 Apr 2004 15:09:32 -0700 Subject: A 'Python like' language References: <40645d8f$0$10775$afc38c87@news.easynet.co.uk> <1f9c60dtvj2alu8lk522l29nerqrv0trv3@4ax.com> Message-ID: On Mon, 29 Mar 2004 16:19:09 +0100, Stephen Horne wrote: >On 28 Mar 2004 21:49:07 -0500, aahz at pythoncraft.com (Aahz) wrote: > >>In article <1f9c60dtvj2alu8lk522l29nerqrv0trv3 at 4ax.com>, >>Stephen Horne wrote: >>> >>>I missed that. There's good precedent - it's the Pascal 'with' block, >>>but better (the leading dot tells you that you're dealing with a >>>'with' item rather than normal scoping rules). But - well - just >>>recently, people keep telling me that indented blocks are purely about >>>control flow. I keep disagreeing, but no-one has bothered agreeing >>>with me so I was feeling rather lonely and miserable in this crusade >>>:-( >> >>Huh? Where were they telling you that? (I don't read all of c.l.py by >>a long shot, 'specially when I've just gotten back from PyCon.) From my >>POV, indented blocks are about program structure and namespaces. Saying >>that ``class`` refers purely to control flow definitely misses the point. > >My replies were... > >Message-ID: > >Message-ID: > >I'm sure google can give you the full threads. I guess I'm the culprit here. I made the erroneous statement in a post a while back. Stephen corrected it. I failed to acknowledge. Got too busy with the Prothon mailing list, I guess. Anyway, I'm back. -- Dave From peter at engcorp.com Thu Apr 8 09:43:12 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 08 Apr 2004 09:43:12 -0400 Subject: OT: Esperanto again (was Re: why is python better than eg. smalltalk?? ) In-Reply-To: <407524df$0$5066$4d4ebb8e@news.nl.uu.net> References: <20031028061245.12451.00000133@mb-m01.aol.com> <4074f954$0$5802$79c14f64@nan-newsreader-02.noos.net> <407524df$0$5066$4d4ebb8e@news.nl.uu.net> Message-ID: <2dydnWcBufhsy-jdRVn-hA@powergate.ca> aku wrote: > On 2004-04-08, francois lepoutre wrote: > >> http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&oe=UTF-8&selm=3A2DD2CA.14A5D7E2%40engcorp.com&prev=/groups%3Fq%3Dpython%2520%2522van%2520rossum%2522%2520esperanto%26hl%3Den%26lr%3D%26ie%3DUTF-8%26oe%3DUTF-8%26sa%3DN%26tab%3Dwg > > The article talks about Esperanto and says: > "Still widely spoken in that country" > > This is humor people. there's as many people speaking Esperanto > here as that are walking on the moon right now. As the author of that, I have to object slightly. Yes, it was humor, but there are most definitely more people in the Netherlands who speak Esperanto than there are people walking on the moon, unless my lack of television has led to me missing a few key events in the world of space exploration in the last few years... (Neither, however, is it really fair to say it's "widely spoken", in the Netherlands, if one equates that to a large number of speakers instead of merely to diversity of geographic location...) -Peter From __peter__ at web.de Mon Apr 5 13:15:01 2004 From: __peter__ at web.de (Peter Otten) Date: Mon, 05 Apr 2004 19:15:01 +0200 Subject: recursive file editing References: Message-ID: TaeKyon wrote: > Il Sat, 03 Apr 2004 17:22:04 -0800, Josiah Carlson ha scritto: > >> for thing in os.walk('mydir'): >> filehandle = file(thing, 'r+') > > I'm such a newbe I can't get it to work. Here is an example: > > in empty directory foo I touch a b c d; > suppose I want to write "This works !" in each of these files. > > I run python >>>> import os >>>> for thing in os.walk('foo'): > ... thingopen = file(thing,'r+') > ... thingopen.write("This works !") > ... thingopen.close() > ... > Traceback (most recent call last): > File "", line 2, in ? > TypeError: coercing to Unicode: need string or buffer, tuple found > > And in fact: > >>>> for thing in os.walk('foo'): > ... print thing > ... > ('foo', [], ['a', 'b', 'c', 'd']) > > which is a tuple, I suppose. > > Selecting thing[2] doesn't help, because it now complains of it being a > list. > > In the end I get this to work: > > for filetuple in os.walk('foo'): > ... for filename in filetuple[2]: > ... fileopen = file(filename, 'r+') > fileopen.write("This works !") > fileopen.close() > > which seems a bit of a clumsy way to do it. > And besides it only works if I run python from directory foo, > otherwise it tells me "no such file or directory". A minimal working example is: import os for path, folders, files in os.walk("/path/to/folder"): for name in files: filepath = os.path.join(path, name) fileopen = file(filepath, 'r+') fileopen.write("This works !") fileopen.close() You need to compose the filepath, and, yes, it's a bit clumsy. I've written a little generator function to hide some of the clumsiness: def files(folder): for path, folders, files in os.walk(folder): for name in files: yield os.path.join(path, name) With that the code is simplified to: for filepath in files("/path/to/folder"): fileopen = file(filepath, 'r+') fileopen.write("This works !") fileopen.close() HTH, Peter From loic at fejoz.net Fri Apr 9 04:05:48 2004 From: loic at fejoz.net (Yermat) Date: Fri, 09 Apr 2004 10:05:48 +0200 Subject: Function args In-Reply-To: References: Message-ID: Jean-Michel Caricand wrote: > Bonjour Michel et mer?i pour la r?ponse tr?s rapide. Je tiens ? pr?ciser que > nous d?veloppons en interne > en langage Perl. Ma question peut donc sembler b?te pour des programmeurs > Python. > > Apr?s maintes recherches, je n'ai pas trouv? d'exemples me permettant de > comprendre le m?canisme employ? > par Python pour passer un simple nombre ? une fonction et le modifier > r?ellement. > > Imaginons que je veuille ?crire une fonction qui permute deux variables, > j'?cris : > > def permuter(a,b): > c = b > b = a > a = c > > Si tout est objet, donc pass? par r?f?rence a et b devraient ?tre r?ellement > modifier ? Pourtant ce n'est pas le cas. > > [...] En plus "permuter" est un mauvais exemple psuique l'on peut faire : >>> a = 1 >>> b = 2 >>> print a, b 1 2 >>> (a, b) = (b, a) >>> print a, b 2 1 En gros, tous les types primitifs de python sont "expans?s", autrement dit quand on les affecte ? une autre variable, c'est une copie. Tous les types complexes sont des r?f?rences. Yermat From mwh at python.net Mon Apr 5 09:11:33 2004 From: mwh at python.net (Michael Hudson) Date: Mon, 5 Apr 2004 13:11:33 GMT Subject: Python is faster than C References: <36wn05qkeyk.fsf@hundertwasser.ti.uni-mannheim.de> Message-ID: Matthias writes: > aahz at pythoncraft.com (Aahz) writes: > > While I'm generally in favor of what you're talking about, it seems to a > > certain extent that you're simply shifting complexity. Maintaining the > > simplicity of the Python VM is an important goal, I think, and some of > > your suggestions run counter to that goal. > > Isn't the whole idea of very high level languages to shift complexity > from the user code to the language implementation? > > That's not a rhetorical question: Why is it that "simplicity of the > Python VM is an important goal"? Well, possibly because it's easier to predict what a simple implementation is up to. Cheers, mwh -- You sound surprised. We're talking about a government department here - they have procedures, not intelligence. -- Ben Hutchings, cam.misc From mark at prothon.org Fri Apr 30 01:53:43 2004 From: mark at prothon.org (Mark Hahn) Date: Thu, 29 Apr 2004 22:53:43 -0700 Subject: What is good about Prothon? References: <69cbbef2.0404271534.6a7c90e6@posting.google.com> <69cbbef2.0404280722.704c7c97@posting.google.com> Message-ID: has wrote: > Eh, I'll see what I can do. Here's a short example to get you started: This is plenty. I'm getting a good idea of what is going on here. > In AS, every compiled script is itself a script object. Scripts can be > loaded into other scripts using the 'load script' command; this > provides the foundation for library-based design. I see no difference from a Prothon module so far (which is good). > Script objects can > also be declared within other script objects and handlers (aka > procedures) using the 'script [identifier]...end script' block. This, > along with their support for delegation via the 'parent' property, > allows you to do prototype-based OOP. Oh, so the script is also the function. That is a bit limiting, not having functions within a script. > Incidentally, because script > objects have first-class syntactic support, they also support modular > design within a single file, sectioning off parts as separate > namespaces without having to move code off into separate files as > you'd do in Python; This I REALLY like. I'll put this on the list of ideas to "steal" for Prothon. > Thus a single, very generic type (script) can perform all the roles > that it takes Python several specialised and largely > non-interchangeable types (classobj, instance, module) to do. Prothon is the same. Using a module as a prototype is a trick that recently paid off. We have no structure or rules making one object unable to play the role of another. As we slowly unwind our brains from class-thinking (not an easy task) I expect the benefits to pour forth. > Other nice stuff: while AS allows only a single delegate per object, > the ability to compose object behaviour at runtime makes it much more > powerful than class-based single inheritance, and less of a PITA to > use than MI. Just create and delegate-chain together the objects you > want as and when you need them. You don't have to convince me that dynamic delegation is good. > [* Python shouldn't feel too smug, however, seeing as I had no better > luck trying to dynamically attach property objects to class instances, > and had to resort to sticking nodes into a private dict accessed via > __getattr__ and __setattr__.] We'll make sure Prothon can feel smug in this regard. > Good programmers know how to add features; > great ones know how NOT to. I will be sure to remember that after Prothon is designed. Right now we are not adding features to Prothon, we are designing version 0.1. You have to add features when you start with zero features. Even you must admit a language with zero features is unintresting :) From martin at v.loewis.de Sun Apr 18 13:56:56 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 18 Apr 2004 19:56:56 +0200 Subject: using a USB HID device In-Reply-To: <40827ce3.1151345337@news.xs4all.nl> References: <40827ce3.1151345337@news.xs4all.nl> Message-ID: Wouter van Ooijen (www.voti.nl) wrote: > I want to use Python to interface with an USB HID device (not a > keyboard or mouse, just something that uses the HID driver to avoid > the need for a specific driver). Is this possible in pure Python on > Windows, or even better, in a portable way? What is the Win32 API for such devices? If it is plain CreateFile/ReadFile/WriteFile/DeviceIoControl, you should be able to do it in pure Python, using the PythonWin extensions. Likewise, on Unix, you can use device nodes, and the fcntl module. I don't think there is a platform-independent Python module for such devices, yet, but you could write your own abstraction layer using those building blocks. HTH, Martin From peter at engcorp.com Fri Apr 16 12:44:24 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 16 Apr 2004 12:44:24 -0400 Subject: AOP use cases In-Reply-To: <0pydnSB4WYuieuLdRVn-hQ@powergate.ca> References: <84fc4588.0404140106.3fa0c55@posting.google.com> <0pydnSB4WYuieuLdRVn-hQ@powergate.ca> Message-ID: <35qdnT4kNsX1kB3dRVn-gg@powergate.ca> Peter Hansen wrote: > I would be very interested to hear some real-world and real useful > use cases for AOP as well. So far, the logging example seems to > be put forth so often that I'm starting to suspect that's the > *only* "useful" thing people are doing with it. :-) > > From direct personal experience, could some AOP folks please > point out some compelling use cases so that the doubting > Thomases (and Wills, and Peters) can better understand and > accept the idea of AOP as being more than just a few fringe > cases? Thanks for the replies so far, but what concerns me is that almost no one seems to have actually used AOP in their code. Okay, I realize this is not the best forum to find a bunch of AOPers, probably, so I'd like to expand the request to include pointers to clear descriptions of *others'* compelling uses of AOP. Not just cool or theoretical ideas, but actual cases of AOP having been used for things where non-AOP would have been much more awkward or involved or something. The logging example is okay, yes, but another problem I have with it is that it's very development-oriented. It doesn't do anything directly for the user in terms of helping implement user functionality. Same goes for the contract aspect, which while probably very helpful for doing dBc in some cases, appears just to make a particular development style go easier. I'm not sure I'm asking this in the right way, but does AOP provide one with the ability to do anything useful in terms of actual end-user functionality, and if so please point me to a description of a real-world case where it did so. I'm not actually anti-AOP, just completely on the fence about the possible benefits. I like the Fourier Transform way of viewing it, but it's possible to relate FTs back to the real world in a pretty direct manner as they just allow an easy way to work in the frequency domain. What, in the AOP world, is the equivalent to "frequency"? -Peter From fredrik at pythonware.com Fri Apr 16 07:05:38 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 16 Apr 2004 13:05:38 +0200 Subject: Tkinter Button image option References: <8d3ec.74988$Ig.46341@pd7tw2no> Message-ID: Elaine Jackson wrote: > When I try to put an image onto a Tkinter button, I get a message that says the > image in question "doesn't exist" (it does, though). One of the references I > looked at said that Tkinter has to be "configured for" the Python Imaging > Library in order for the 'image' option to work. I've got the PIL, but as for > "configuration", I don't know. Maybe I need to reinstall Tcl/Tk? If anyone can > point me to the appropriate resource, I'd be very much obliged. did you get an error similar to this: TclError: image "pyimage1" doesn't exist a common reason for this is that you have multiple Tk instances in your application. if you create a PhotoImage under one Tk instance, you cannot access it from other instances. to fix this, make sure you only use one Tk instance (use Toplevel to create new toplevel windows), or make sure that you create the image under the same instance as the widget you're going to use it in. the easiest way to do this is to pass in a master keyword argument to the PhotoImage constructor: photo = PhotoImage(..., master=myroot) button = Button(myroot, ...) button.photo = photo # keep a reference (if the file you're trying to load doesn't exist, From moosebumps at moosebumps.com Sat Apr 24 03:13:06 2004 From: moosebumps at moosebumps.com (Moosebumps) Date: Sat, 24 Apr 2004 07:13:06 GMT Subject: python for console game development, memory tracking Message-ID: <6soic.40551$c77.17448@newssvr29.news.prodigy.com> When I have time, I am planning to evaluate Python for console game development (on Playstation 2, GameCube, and Xbox). Does anyone have any experience with this? Pretty much the only resource I have found, and the only thing that makes me think it might be possible is this: http://asbahr.com/python.html I would be interested to hear anybody's experience with Python on consoles. Before I even begin investigating though, there is a major question I have: How can you track the memory usage of Python? I would like to be able to track allocations by function / class, etc. I have googled and seen a bunch of threads with 1 guy asking the same exact question that I am, and no responses, which leads me to believe it's very easy or not possible. This would be dealbreaker unfortunately. But I am optimistic that Python is well designed so there must be some solution. thanks, MB From tzot at sil-tec.gr Wed Apr 7 05:20:38 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Wed, 07 Apr 2004 12:20:38 +0300 Subject: An attempt at guessing the encoding of a (non-unicode) string References: <6pa270h031thgleo4a31itktb95n9e4rvm@4ax.com> Message-ID: <3rh770p37kuop578tsj8kkcnubbg9ed47h@4ax.com> On Mon, 05 Apr 2004 13:37:34 -0700, rumours say that David Eppstein might have written: >BTW, if you're going to implement the single-char version, at least for >encodings that translate one byte -> one unicode position (e.g., not >utf8), and your texts are large enough, it will be faster to precompute >a table of byte frequencies in the text and then compute the score by >summing the frequencies of alphabetic bytes. Thanks for the pointer, David. However, as it often happens, I came second (or, probably, n-th :). Seo Sanghyeon sent a URL that includes a two-char proposal, and it provides an algorithm in section 4.7.1 that I find appropriate for this matter: http://www.mozilla.org/projects/intl/UniversalCharsetDetection.html -- TZOTZIOY, I speak England very best, Ils sont fous ces Redmontains! --Harddix From bart_nessux at hotmail.com Thu Apr 29 11:13:09 2004 From: bart_nessux at hotmail.com (bart_nessux) Date: Thu, 29 Apr 2004 11:13:09 -0400 Subject: reading and removing first x bytes of a file In-Reply-To: References: Message-ID: <40911B85.5080107@hotmail.com> Peter Hansen wrote: > bart_nessux wrote: > >> I have some Macbinary files on a PC. I want to recursively read these >> files and remove the first 128 bytes of the files if they contain the >> macbinary header info. I know how to read directories recursively, but >> how would I read the first 128 bytes of each file in the path? > > > os.listdir() can return a list of the names in the path. You > can use os.path.isfile() to check that a given name doesn't > refer to a subdirectory. > > Once you've opened one of the files for reading, just use .read(128) > to get a string containing the first 128 bytes from the file. > > -Peter Thanks Peter, the below code recursively read the first 128B... am I right in saying that? If so, now that I can read these bytes from all .bin files in a directory, what would be the safest and fastest way of removing them? Bart import os def pc_macbinary_fix(path): for root, dirs, files in os.walk(path): for fname in files: bin = os.path.splitext(fname) if bin[1] == '.bin': macbinary = file(os.path.join(root,fname), 'rb').read(128) print "The file named:", fname, "contains: ", macbinary, "\n." path = raw_input("Absolute path to the directory that contains the bin files: ") pc_macbinary_fix(path) From OlafMeding at noSpam.compuserve.com Tue Apr 13 07:15:35 2004 From: OlafMeding at noSpam.compuserve.com (Olaf Meding) Date: Tue, 13 Apr 2004 06:15:35 -0500 Subject: Logging Stacktrace To File Message-ID: <407bcbca$1_2@newspeer2.tds.net> In case of an exception, how could I log an exception to a file on disk? Much appreciate your help, thank you. Olaf From reverse.ku.oc.issolok at nothypgnal.delrest.co.uk Tue Apr 27 06:25:17 2004 From: reverse.ku.oc.issolok at nothypgnal.delrest.co.uk (Paul Sweeney) Date: Tue, 27 Apr 2004 10:25:17 +0000 (UTC) Subject: Default Argument Inconsistency? References: Message-ID: Ah, yes, got it :-) I'm new to Python (4 months) and thought I'd figured the whole immutable/mutable thang, and this was bothering me. Many thanks Paul "Diez B. Roggisch" wrote ... > > No, its not. As [] is logically false, the > > if not L: L = [] > > rebinds L with a fresh list. So the append is made to that list, not to the > one L is bound to as default argument. > > > -- From dmq at gain.com Fri Apr 30 11:25:19 2004 From: dmq at gain.com (David MacQuigg) Date: Fri, 30 Apr 2004 08:25:19 -0700 Subject: Explanation of Instance Variables in Python References: Message-ID: <2tr4901hjbus6kvml7d0qd9t0k64gtld9u@4ax.com> On 29 Apr 2004 01:30:55 GMT, bokr at oz.net (Bengt Richter) wrote: >On 29 Apr 2004 01:10:21 GMT, bokr at oz.net (Bengt Richter) wrote: >>I find well-annotated examples best for understanding something new. >>It also gives me working code to play with, to explore variations. >>How things break is often as instructive as how they work. >> >>I would suggest you encourage your students to experiment interactively. >>E.g., ask who can explain the following, and see what you get, and then >>collaborate with them to write sufficient comments to where they feel >>they "get it." >> >Actually, looking at my previous example, maybe this would give more hints, >in case they don't discover for themselves (strongly urge teaching how to >fish, not serving fish, though ;-): > > >>> class C(object): pass > ... > >>> def f(*args): print 'f was called with', args > ... > >>> f > > >>> C > > >>> f('hello') > f was called with ('hello',) > >>> c=C() > >>> c > <__main__.C object at 0x00901370> > >>> c.f('hello') > Traceback (most recent call last): > File "", line 1, in ? > AttributeError: 'C' object has no attribute 'f' > >>> c.f = f > >>> c.f > > >>> c.f('hello') > f was called with ('hello',) > >>> C.f = f > >>> c.f > > >>> c.f('hello') > f was called with ('hello',) > >>> del c.f > >>> c.f > > > >>> c.f('hello') > f was called with (<__main__.C object at 0x00901370>, 'hello') I like this example. It shows clearly how the first argument is inserted in the calling sequence for a normal method call. I remember that seemed very strange when I was learning Python. -- Dave From rogerb at rogerbinns.com Tue Apr 6 03:56:26 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Tue, 6 Apr 2004 00:56:26 -0700 Subject: A beginner's question on thread References: Message-ID: > Now my question is, how do I terminate the server thread if user wants > to exit the application? The easiest way is to setDaemon(True) on the thread. See the doc for exactly what it does. If you want to do it in a more "proper" fashion, then you have to make the thread do a polling loop, such as by putting a short timeout on the sockets, and then check a variable which indicates if you should continue, looping back if not. It would be really nice if Python supported interrupting a thread like Java does. Roger From me at privacy.net Sun Apr 18 09:08:37 2004 From: me at privacy.net (Heather Coppersmith) Date: 18 Apr 2004 09:08:37 -0400 Subject: module not callable - why not? References: <107dras2heahcb6@news.supernews.com> <8ef9bea6.0404122025.36efc84e@posting.google.com> <7xsmf1fxd9.fsf@ruckus.brouhaha.com> Message-ID: On 18 Apr 2004 02:28:50 -0700, Paul Rubin wrote: > Josiah Carlson writes: >> I think of modules as a namespace. Why? Because that is what >> they are. They contain a space of names, some of which may be >> useful to you, otherwise you wouldn't have imported the module. > Is a class instance not also a namespace? After all, it > contains a space of names, some of which you must have wanted or > else you wouldn't have instantiated it. > And yet, you can call a class instance if it has a __call__ > operation defined. I don't see why modules shouldn't be the > same. In that light, IMO, __call__ methods are the kluge. This argument seems to go back to (1) the old programs vs. data debate, and (2) the meaning of "functions are first class objects." Note that modules are neither functions nor objects. If I really want to call (the top-level code in) a module, I can always reload it: Regards, Heather -- Heather Coppersmith That's not right; that's not even wrong. -- Wolfgang Pauli From mongiaamit at yahoo.com Fri Apr 23 07:19:12 2004 From: mongiaamit at yahoo.com (Amit Mongia) Date: 23 Apr 2004 04:19:12 -0700 Subject: utf in Reportlab Message-ID: Hi, I have some text that contains url links as well as unicode characters. I am encoding the whole text into utf-8 and trying to render it using Reportlab. For that i am trying to use some True type fonts that support rendering utf8. For example Times New Roman on windows is able to render some german text that i have. The default Paragraph implementation with Platypus does not support url links at the moment while the experimental Paragraph implementation in para.py does. So i used the one in para.py. Now the implementation in para.py is not supporting the ttf fonts that i register with pdfmetrics. It still tries to render that text using some other font. Any suggestions on how to get around this problem. Anyone knows if a better version of para.py is available anytime soon. Regards, Amit Mongia From stauffer at swarthmore.edu Tue Apr 13 08:04:05 2004 From: stauffer at swarthmore.edu (Glenn Stauffer) Date: Tue, 13 Apr 2004 08:04:05 -0400 Subject: Escaping characters in MySQLdb query In-Reply-To: References: Message-ID: <407BD735.704@swarthmore.edu> There is a function in the MySQLdb module, string_literal(), that returns a properly escaped string. I do something like this when processing html form data that is being inserted in mysql: def dbescape(val): if val: return MySQLdb.string_literal(val) else: return "NULL" cursor.execute(insertsql % dbescape(formdict['address'].value) Until I figured this out, I was using the replace(...) method that you've been using. --Glenn Sean Berry wrote: >I was doing something like this: > >for item in values: > item = item.replace("'", "//'") > >But I am looking for something a lot nicer. > >Sorry about my first post date... 12 hours off. > > >"Sean Berry" wrote in message >news:AkEec.271$U83.155 at fed1read03... > > >>I wrote a little script that is inserting thousands of records into a >> >> >mysql > > >>database. >> >>How do I escape characters like ' in my insert statements? >> >>I have something like the following (much shorter) example: >> >>c.execute("INSERT INTO records (var1, var2) values ('%s', '%s')" >> >> >%(value1, > > >>value2)) >> >>My problem is when value1 is something like "Tom's auto supply". The ' in >>Tom's needs to be escaped. How can I do this? >> >>Thanks. >> >> >> >> > > > > From tzot at sil-tec.gr Sat Apr 10 12:27:37 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Sat, 10 Apr 2004 19:27:37 +0300 Subject: Python for MPG References: Message-ID: On Sat, 10 Apr 2004 08:31:01 -0400, rumours say that Peter Hansen might have written: >Will Stuyvesant wrote: > >> Is there Python software for dealing with MPG movies? I am not >> interested in visual effects etc. but in cutting scenes from big MGP >> files and creating new files with those scenes. > >Found via Google: http://www.mpgedit.org/mpgedit/ MPGEdit is for audio files only (MPEG 1 Layer I, II, III, MPEG 2, MPEG 2.5). Unfortunately I have no knowledge of a library for MPEG video editing with Python bindings, but TMPGEnc is a free tool that might help, providing cutting and merging tools. -- TZOTZIOY, I speak England very best, Ils sont fous ces Redmontains! --Harddix From tjreedy at udel.edu Mon Apr 12 16:39:04 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 12 Apr 2004 16:39:04 -0400 Subject: Is there a boolean(somestring) equivalent of int(somestring). References: Message-ID: > In article , > "Vineet Jain" wrote: > >Thanks for the code suggestion. > > > >>From what I've read, most people (including me) are attracted to Python > >because of how natural it is. Give that is a high priority for the language > >designers: > > > >How can anyone argue that > > > >bool('false') = True > > > >is more natural (and what you would expect) than > > > >bool('false') = False I would not argue about what *you* would or should expect, since I know nothing of your background and thought processes, but as for myself: 1. I am aware that the Boolean values, in themselves, are abstractions. In applications, they can represent the two possible answers to *any* forced dichotomy: nothing/something, 0/1, open/closed, up/down, inside/outside, dead/alive, passive/active, off/on, default/marked, wrong/right, isolated/connected, and so on, and, oh yes, when interpreted for logic, false/true. 2. I know Python to be a global algorithm language, and not just for English speakers, even though the keywords and builtin names are English or English-based. So I would not expect operators to be English-biased in their operations on values (as opposed to names). 3. I know that the dichotomy chosen for bool(sequence/collection) is empty/something, and that strings are a sequence of bytes. Terry J. Reedy From joe at notcharles.ca Thu Apr 15 15:41:13 2004 From: joe at notcharles.ca (Joe Mason) Date: Thu, 15 Apr 2004 19:41:13 GMT Subject: Aspect Programming Module References: <84fc4588.0404140106.3fa0c55@posting.google.com> Message-ID: In article , Will Stuyvesant wrote: >> [Joe Mason] >> > "AOP is a contrived way to get around the limitations of a statically >> > typed language." >> >> Care to explain that? What I've seen of AOP seems like a very dynamic >> design philosophy. > > Dynamic indeed. And that is a problem for statically types > programming languages like Java. > > To add logging capabilities to an instance object of a Python class > you simply add a function/method that does the job. Add it as an > attribute to the object itself, or to the object's __class__, or to > anything else you can get at via the object and its attributes. But that doesn't address the calling of the new function. You still have to either manually insert calls everywhere, or set up a system which notices when new functions are added and inserts calls to them as needed. Once you've done that - poof! Aspect Oriented Programing! Joe From dmq at gain.com Fri Apr 23 17:38:20 2004 From: dmq at gain.com (David MacQuigg) Date: Fri, 23 Apr 2004 14:38:20 -0700 Subject: Why we will use obj$func() often References: <84Uhc.22278$dZ1.5087@fed1read04> <8AWhc.23114$dZ1.11070@fed1read04> <40883BFE.B381518A@alcyone.com> <27_hc.23801$dZ1.2716@fed1read04> <40887145.789A2FE8@alcyone.com> <7cki80hj976bia36lhf9er97v073o1pqvm@4ax.com> Message-ID: <1q0j809vuirbsddmje23jt5d29jjvveosn@4ax.com> On Fri, 23 Apr 2004 13:40:55 -0700, "Mark Hahn" wrote: >"David MacQuigg" wrote ... >> >def getFunc(): >> > counter = 0 >> > def count(): >> > &counter += 1 >> > print &counter >> > return count > >> Here is how I would do it in Python: >> >> class Accumulator: >> def __init__(self): >> self.count = 0 >> def bump(self): >> self.count += 1 >> print self.count > >> It took me a few minutes to understand what the "closure" was doing. >> The Python code is more clear ( at least for anyone who will have to >> be working with classes anyway). There is nothing new to learn. >> >> Functionality = same >> Size of Source Code = same >> Transparency = Python wins > >Yes, it's a tie in this example. There are many cases however where you are >already in a situation where you have a function and the closure is >beneficial and creating a "class" would be unneeded overhead. I don't >really have the time to create something large enough here to demonstrate >it. You'll just have to take my word for it (or not). > >It's a tool for your toolchest and it's the kind of thing that if your not >familiar with it you'll never miss it, but once you learn it and use it a >few times you'll wonder how you ever lived without it. Also I can drag out >the old tired argument that if the closure bothers you "you don't have to >use it". I appreciate that I may be missing something important because it can only be seen in a larger example. For many years I scoffed at C++ thinking I could do anything I needed without OOP. Still, the question of whether we should include special syntax for closures is an important question that deserves some time on a use-case before even putting it into Prothon, let alone expecting Python users to learn it. I'm not seeing the "overhead" of classes that you refer to. To me, a class is very lightweight thing. I use nested classes, for example to store hierarchies of variables, like window1.plot2.xaxis.label.font.size = 12 It is quite alright to show a small example and expect us to extrapolate to something 100 times larger. Even if we extrapolate the example above, however, Python still wins. I don't like the "toolchest -- don't have to use it" argument, because that could be used to justify *any* added syntax, and I really like the compactness of Python. The more overlapping features we have, the more confusion there will be in reading someone else's programs, for example. I don't like the "once I learn it argument" either. An equally valid argument is that people who have developed a *habit* in other languages of using closures, are now unnecessarily dependent on them, and will have to learn simpler techiques to get by in Python. By the way, if we work on the example a little, Python wins on transparency *and* codesize. class A: count = 0 def bump(self): A.count += 1 print A.count c = A().bump c(); c(); c() -- Dave From andrew.henshaw at gtri.gatech.edu Fri Apr 2 08:01:07 2004 From: andrew.henshaw at gtri.gatech.edu (Andrew Henshaw) Date: Fri, 02 Apr 2004 08:01:07 -0500 Subject: Making the Zen of Python more useful Message-ID: <106qp0uivlefo40@corp.supernews.com> Yesterday, I was writing some test code for a module and I wanted some line-oriented text to use as a data source. I thought about using a docstring from one of the standard modules; but, it occurred to me that the Zen of Python text from the 'this' module would be *much* better, as it is more readable and would be a nice thing for our students to see. Unfortunately, the actual text is difficult to use: o the text is ROT-13 encoded and the module's translation routine is inline o the text is printed to stdout on import. I understand why Tim did this, but it did interfere with my purpose. So, in order to use the module for my test code, I had to implement a short ROT-13 translator, import the sys module, redirect stdout to a simple object that provided a null write method, import this, restore stdout, and then rot13(this.s). I suggest that the 'this' module could be used to provide a standard, line-oriented, test text. I would like to see the unencoded text made available directly, e.g. this.zen(). Unfortunately, my suggestion has a snag. I can't think of a convenient way to provide the 'import this' functionality for which the module was oringinally created, without forcing the test programmer to go through the gyrations of redirecting stdout. We could do an indirect import from another module that provides the desired behavior; but, this seems like overkill. Any thoughts? -- Andy From mwilson at the-wire.com Mon Apr 5 12:05:54 2004 From: mwilson at the-wire.com (Mel Wilson) Date: Mon, 05 Apr 2004 12:05:54 -0400 Subject: slightly OT: BUT NEEDs to be said References: <4078daf265c69e9353e8af72542da703@dizum.com> Message-ID: In article <4078daf265c69e9353e8af72542da703 at dizum.com>, Nomen Nescio wrote: > >Hi I downloaded this document about Python recently: > >http://datamining.anu.edu.au/~ole/publications/python.pdf > >I loved the cute little Snake graphic. > >I think it would be great for Python.org/people behind Python to adopt this >as an official mascot and DROP the god awful references to Monty Pythons's >Flying Circus. [ ... ] The link with Monty Python's Flying Circus is the only thing that lets us logically use the cute little snake as our mascot. Ask yourself, "Could a language named after a snake have a pet comedy troupe?" Regards. Mel. From tjreedy at udel.edu Wed Apr 21 13:33:43 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 21 Apr 2004 13:33:43 -0400 Subject: Py_ParseTuple Problem References: <4039221c.0404202256.3f21d817@posting.google.com> Message-ID: wrote in message news:4039221c.0404202256.3f21d817 at posting.google.com... > Hi All , > > Bit of a problem with Py_Parse or Py_ParseTuple ? > > I have a python script that reads a sector of flash in an embedded device. > it returns the value of each byte within the sector as a tuple. > > i.e. [255,255,255,255,255,255,255, .......etc etc for the whole sector ! As written, above is a list instead of a tuple. > We are using this script to read whats currently in any sector. > No problems there. > > Now I need to call our script from C. > > I want to copy each of the bytes within the sector into an C unsigned char *array Without knowing the C API, I would try to generate byte string from within Python. Three possibilities: 1. turn list into string - secstring = ''.join(map(chr, seclist)). Then use C API to get the cstring from string object. 2. turn list/tuple into array (of unsigned chars) or built that directly instead of list or tuple. See array module. I presume you can get at the buffer itself from C API. 3. look into ctypes module. > Is there any way to do this using Py_ParseTuple or Py_Parse ??? If you mean PyArg.... stuff, I believe these are meant for parsing argu;ments passed as heterogeneous Python tuple, which is quite different from what you want to do. Terry J. Reedy From edwin at localhost.localdomain Sat Apr 3 20:43:03 2004 From: edwin at localhost.localdomain (Edwin Young) Date: 03 Apr 2004 17:43:03 -0800 Subject: minor bug in cmath.asin? References: <406F3EDA.970F953A@alcyone.com> Message-ID: Erik Max Francis writes: > Edwin Young wrote: > > > I think it should be 0+0j (+0 for both parts). The official formula is > > at > > > > http://functions.wolfram.com/ElementaryFunctions/ArcSin/02/ > > Well this is Mathematica's official formula ... :-). Mathworld doesn't document how Mathematica works, it's a repository of generic mathetical info. "Official" is the wrong word, but I don't have a more authoritative reference to hand. > > > and is asin(z) = -i * log(i*z + sqrt(1 - z*z)) > > > > Which is slightly ambiguous. I read it as: > > > > (+0 - 1i) * log(i*z + sqrt(1 - z*z)) > > How is the original equation amiguous? It's not clear if the leading - sign affects the entire expression or indicates that i is negative. Python's implementation uses the former - I argue that the latter is more correct. The difference in result is just whether you get +0 or -0. I've also noticed that cmath.acos has the same issue, and that the formula used for cmath.asinh is not quite accurate around 0 : cmath.asinh(0) gives 4.44089e-16+0j, rather than 0 as expected. Does anyone know the history of the cmath implementation? There are some interesting formulas used for some of the trig functions and I'm curious to know where they came from. -- Edwin From peter.maas at mplusr.de Wed Apr 7 06:45:28 2004 From: peter.maas at mplusr.de (Peter Maas) Date: Wed, 07 Apr 2004 12:45:28 +0200 Subject: Conflux In-Reply-To: References: Message-ID: Manpreet wrote: > Mod_python error: "PythonHandler _Publisher" > > Traceback (most recent call last): > > File "/usr/lib/python2.3/site-packages/mod_python/apache.py", line > 338, in HandlerDispatch > result = object(req) > > File "/var/www/html/conflux/lib/_Publisher.py", line 217, in handler > module = apache.import_module(module_name, req.get_config(), > [path]) > > File "/usr/lib/python2.3/site-packages/mod_python/apache.py", line > 493, in import_module > f, p, d = imp.find_module(parts[i], path) > > ImportError: No module named index Just guessing, but I think, a file named index.py is missing or in the wrong place. What about contacting Conflux about this issue? Mit freundlichen Gruessen, Peter Maas -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Hubert-Wienen-Str. 24 Tel +49-241-93878-0 Fax +49-241-93878-20 eMail peter.maas at mplusr.de ------------------------------------------------------------------- From soeren_kunst at hotmail.NOSPAM.com Tue Apr 20 09:32:56 2004 From: soeren_kunst at hotmail.NOSPAM.com (Sören Kunst) Date: Tue, 20 Apr 2004 15:32:56 +0200 Subject: Re Message-ID: for Python Beginners, thx for the links From peter at engcorp.com Thu Apr 1 09:25:53 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 01 Apr 2004 09:25:53 -0500 Subject: OT (was Re: But it still doesn't explain the joke) In-Reply-To: <106o7vn56fgmt85@corp.supernews.com> References: <106o7vn56fgmt85@corp.supernews.com> Message-ID: Cameron Laird wrote: > In the litigious US, court cases for everything are unceasing. What > I suspect you have in mind is a Supreme Court hearing for a father > who, if I understand correctly, claims his religious freedom as an > atheist unconstitutionally impaired because of a requirement imposed > by the public school his daughter attends that she recite The Pledge > . > > More background appears at . Without following the links to verify, I'll just note (since I was reading this on the subway while heading for the PyCon venue) that the recitation is apparently not even mandatory (for the girl) but the father was objecting that she would even have to stand there and listen to it. (I don't know what the "rules" say, but the school representative said the girl didn't even have to say the pledge.) -Peter From jcarlson at uci.edu Sat Apr 3 02:46:26 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Fri, 02 Apr 2004 23:46:26 -0800 Subject: Translate escaped characters in a string In-Reply-To: References: Message-ID: > I have an application that reads the arguments sent to the script. If > an user enters a text like "Line 1\nLine2" (\n is slash+n, and not > LF), I would like to use \n and other supported escape sequences when > I write the text to a file. > > Is there a way to do this, other than writing my own parser? I know there's an easier way to do it, but the below works... >>> import encodings >>> print encodings.codecs.escape_decode('hello\\nworld')[0] hello world >>> If the stings are escaped normally, the above will produce what you want. - Josiah From ngeti at optonline.net Tue Apr 6 16:47:52 2004 From: ngeti at optonline.net (NGETI) Date: Tue, 06 Apr 2004 20:47:52 -0000 Subject: Missing Win32con Message-ID: I have installed Python and it appears to work. Trying it out on some scripts gives me the error, "cannot find win32con" Can anyone suggest where I can get this file? I am running Windows 2000. From bignose-hates-spam at and-benfinney-does-too.id.au Thu Apr 15 22:56:30 2004 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 16 Apr 2004 12:46:30 +0950 Subject: CamelCase versus wide_names (Prothon) References: Message-ID: On Thu, 15 Apr 2004 22:54:03 -0400, Fran?ois Pinard wrote: > [Mark Hahn] >> P.S. Has anyone noticed that I have finally taught myself how to not >> top-post? > > Even more, to quote parsimoniously. Congratulations! :-) Seconded. Thanks, Mark! It's not often I get to reduce my kill file because the person's posting style improved. Note that this will only encourage us to continue educating others :-) -- \ "I may disagree with what you say, but I will defend to the | `\ death your right to mis-attribute this quote to Voltaire." -- | _o__) Avram Grumer, rec.arts.sf.written, May 2000 | Ben Finney From skchim0 at engr.uky.edu Thu Apr 8 15:03:15 2004 From: skchim0 at engr.uky.edu (Satish Chimakurthi) Date: Thu, 8 Apr 2004 15:03:15 -0400 Subject: Embedding python in ANSYS: Anyone tried it? References: Message-ID: <017901c41d9c$25eb5560$559ea380@D4XN6B41> Hello Mr.Bernard, > I now started wrapping ANSYS UPF routines using >f2py and am already able to call some basic python examples from >ANSYS. I mainly asked because wrapping a sufficiant amout of the ANSYS >interface routines is a lot of stupid typing work, and if sombody else >did it before, it would be nice to share the work :-) If you have a ready example about how exactly F2PY was used with a particular UPF routine like "dspget" say, would you mind to send that to me. I would like to see how it works from Python. So, with your interface, you are able to invoke Python scripts from ANSYS or is it the other way round ? Would you please let me know in more detail ? Best Regards, Satish From robin at reportlab.com Thu Apr 29 12:20:13 2004 From: robin at reportlab.com (Robin Becker) Date: Thu, 29 Apr 2004 17:20:13 +0100 Subject: sys.modules strangeness In-Reply-To: References: <408FF0B1.5090505@chamonix.reportlab.co.uk> Message-ID: <40912B3D.60708@chamonix.reportlab.co.uk> A. Lloyd Flanagan wrote: > Robin Becker wrote in message news:<408FF0B1.5090505 at chamonix.reportlab.co.uk>... > >>We had some legacy applications that used import to get parts of documents in. >>When run separately these worked fine, but failed when run as a single process >>because they both imported ch1 (after jumping to their home dirs and placing >>these on the path). Clearly the first to run used up ch1. > > > Have you tried reload(ch1)? (see section 2.1, "Built-in Functions", > in the Python Library Reference. I know that reload works. I was trying to restore the modules state to a specific point as in general I didn't know where or which modules the apps could import. The original problem has gone away as I decided to exec the code files in a specific namespace rather than import them. I am still curious why replacing the current version of sys.modules with an earlier copy doesn't reset the modules list. -- Robin Becker From daniel.dittmar at sap.com Thu Apr 8 09:31:02 2004 From: daniel.dittmar at sap.com (Daniel Dittmar) Date: Thu, 8 Apr 2004 15:31:02 +0200 Subject: A second __builtins__- or globals()-like namespace. References: Message-ID: Jacek Generowicz wrote: > Python looks up names firstly in the nested function namespaces, then > the global namespace, and finally in builtins, raising NameError if it > fails to find a binding in any of those. > > Would it be possible (without hacking the interpreter) to add in > another namespace somewhere into this search hierarchy? You could try to replace the __builtins__ module with an object of your own liking. class IntermediateScope: def __init__ (self, outerscope, **kwargs): for name, value in kwargs.items (): setattr (self, name, value) self.outerscope = outerscope def __getattr__ (self, name): return getattr (self.outerscope, name) sys.modules ['__builtins__'] = IntermediateScope (__builtins__, myvar = myvalue) I haven't tested whether this works at all and what the effect on error messages could be. Daniel From SeeBelow at SeeBelow.Nut Fri Apr 23 21:52:30 2004 From: SeeBelow at SeeBelow.Nut (SeeBelow at SeeBelow.Nut) Date: Sat, 24 Apr 2004 01:52:30 GMT Subject: Difficulty Finding Python Developers (me too!) References: <65cbc3dd.0404140641.3501fde8@posting.google.com> <4084AB85.15E9BAE2@shaw.ca> <84fc4588.0404220406.3ec8b50f@posting.google.com> Message-ID: <4089C85C.2C40FC4D@shaw.ca> Anand Pillai wrote: > > Me! Me! > > Outsource it to India and I can help to do it for you :-) > > -Anand I have no preferences concerning the geographical location of the programmer. Did you read my original post? The job is for someone who does it for the fun and satisfaction and to participate in the progress of computer science. (i.e., there is no money involved.) Mitchell Timin -- "Many are stubborn in pursuit of the path they have chosen, few in pursuit of the goal." - Friedrich Nietzsche http://annevolve.sourceforge.net is what I'm into nowadays. Humans may write to me at this address: zenguy at shaw dot ca From ekoome at yahoo.com Thu Apr 22 11:06:26 2004 From: ekoome at yahoo.com (Eric) Date: 22 Apr 2004 08:06:26 -0700 Subject: Convert hexadecimal string to binary Message-ID: Guys, I have the following hexadecimal string - '\xff\xff\xff' which i need to convert to binary. How would i go about doing this? Eric From Stanislav.Paska at kios.sk Tue Apr 13 04:48:00 2004 From: Stanislav.Paska at kios.sk (Stano Paska) Date: Tue, 13 Apr 2004 10:48:00 +0200 Subject: how to break tuple to separate variables Message-ID: <407BA940.8000405@kios.sk> Hi. I need pass variables to function like tuple, but function accepts separate variables. Is there some elegant solution? My example: # ------------------------------- import datetime def date2tuple(aaa): try: y = int(aaa[:4]) m = int(aaa[5:7]) d = int(aaa[8:10]) except: y = m = d = 0 return (y, m, d) # i need some like this bbb = datetime.date(date2tuple('2004-11-03')) # but date requires bbb = datetime.date(2004, 11, 03) # ------------------------------- Thanks. Stano Paska From __peter__ at web.de Mon Apr 5 03:22:52 2004 From: __peter__ at web.de (Peter Otten) Date: Mon, 05 Apr 2004 09:22:52 +0200 Subject: write data file References: <337e6cd5.0404042146.6e39153c@posting.google.com> Message-ID: SunX wrote: > Question from a newbie. How do you write out a data file of floating > point numbers? file.write only takes strings. > Many thanks. The easiest way is to write them in a text file, one float per line. You can use repr() or str() to convert them to a string: >>> somefloats = [1.2, 3.4, 5.7] >>> f = file("tmp.txt", "w") >>> for n in somefloats: ... f.write(repr(n)) ... f.write("\n") ... Here's how to read them back into Python: >>> f = file("tmp.txt") >>> readfloats = [] >>> for line in f: ... readfloats.append(float(line)) ... >>> readfloats [1.2, 3.3999999999999999, 5.7000000000000002] The trailing digits are nothing to worry about (see the Python FAQ), for a nicer appearance do >>> str(readfloats[1]) '3.4' >>> print readfloats[1] # uses str() for string conversion 3.4 When you are not interested in a human-readable file and have more complex data to store, have a look at the pickle module. Peter From jepler at unpythonic.net Thu Apr 22 10:11:41 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Thu, 22 Apr 2004 09:11:41 -0500 Subject: Tkinter: how to fill values in OptionMenu dynamically In-Reply-To: References: Message-ID: <20040422141131.GA17776@unpythonic.net> You can't do it using OptionMenu, but you can use a Menubutton plus a menu with a postcommand. import Tkinter import time def create_menu(): menu.delete(0, Tkinter.END) menu.add_command(label=time.asctime()) menu.add_command(label="Does anybody even care?") but = Tkinter.Menubutton(text="Does anyobdy really know what time it is?") menu = Tkinter.Menu(but, postcommand=create_menu, tearoff=0) but.configure(menu=menu) but.pack() but.mainloop() Jeff From nicolas.lehuen at thecrmcompany.com Wed Apr 21 06:01:21 2004 From: nicolas.lehuen at thecrmcompany.com (Nicolas Lehuen) Date: Wed, 21 Apr 2004 12:01:21 +0200 Subject: Python 2.3.3 super() behaviour References: <40863bd7$0$25528$afc38c87@news.easynet.fr> Message-ID: <40864674$0$24834$afc38c87@news.easynet.fr> OK, I get it now, thanks. super() method calls should only be used for method involved in diamond-shaped inheritance. This is logical since in this case the base classe (from which the diamond-shaped inheritance starts) defines the interface of the method. This solves another question I was asking myself about super() : "how can it work when the method signature differ between B and C ?". Answer : the method signature should not change because polymorphic calls would be greatly endangered. The base class defines the signature of the method which must be followed by all its children, this way super() can work properly. The base method signature is not enforced by Python, of course, but you'd better respect it unless you get weird result in polymorphic calls. Regards, Nicolas "Peter Otten" <__peter__ at web.de> a ?crit dans le message de news:c65fbo$1q4$05$1 at news.t-online.com... > Nicolas Lehuen wrote: > > > Hi, > > > > I hope this is not a FAQ, but I have trouble understanding the behaviour > > of the super() built-in function. I've read the excellent book 'Python in > > a Nutshell' which explains this built-in function on pages 89-90. Based on > > the example on page 90, I wrote this test code : > > > > class A(object): > > def test(self): > > print 'A' > > > > class B(object): > > def test(self): > > print 'B' > > > > class C(A,B): > > def test(self): > > super(C,self).test() > > print 'C' > > > > print C.__mro__ > > c=C() > > c.test() > > > > The output is : > > (, , , > 'object'>) > > A > > C > > > > Whereas I was expecting : > > (, , , > 'object'>) > > A > > B > > C > > > > Was I wrong to expect this (based on what I've read ?) > > As soon as a test() method without the super(...).test() is reached, no > further test methods will be invoked. Only the first in the list of base > classes will be invoked. If I'm getting it right you have to do something > like: > > class Base(object): > def test(self): > print "base" > > class D1(Base): > def test(self): > super(D1, self).test() > print "derived 1" > > class D2(Base): > def test(self): > super(D2, self).test() > print "derived 2" > > class All(D1, D2): > pass > > All().test() > > Here all cooperating methods have a super() call, and the base class acts as > a showstopper to prevent that Python tries to invoke the non-existent > object.test(). > > Peter > > > From rob at nospam.net Sat Apr 17 06:37:11 2004 From: rob at nospam.net (Robert Ferber) Date: Sat, 17 Apr 2004 12:37:11 +0200 Subject: (For gurus) Embed functions in webpages like in PHP? References: <5eq4l1-9vm.ln1@pilz.hasos.com> Message-ID: Ville Vainio wrote: >>>>>> "rob" == Robert Ferber writes: > > rob> Hi, I'm a PHP-programmer who evaluates Python for a new > rob> project. I really like a lot of concepts of Python, > rob> especially the shell, but there is one great feature of PHP > rob> which I don't know how to replace in Python: > > rob> > rob> > rob> important database result that took 20 minutes to generate > rob> > > Check out the new mod_python, it offers exactly the functionality you > need. Some discussion is here: > > http://www.onlamp.com/pub/a/python/2004/02/26/python_server_pages.html This looks very promising, thanks a lot. -- "Statistics are like bikinis. What they reveal is suggestive, but what they conceal is vital" - Aaron Levenstein From aahz at pythoncraft.com Tue Apr 27 15:19:33 2004 From: aahz at pythoncraft.com (Aahz) Date: 27 Apr 2004 15:19:33 -0400 Subject: Is Perl *that* good? (was: How's ruby compare to it older bro References: <108qcobc4m8g972@corp.supernews.com> Message-ID: In article , Greg Ewing wrote: > >I suspect that, 20 years from now, there will still be a language >called Python, and it will still be quietly and unobtrusively kicking >all its competitors' backsides. > >Whether it will bear any resemblance to the Python of today is another >matter... Heh. Something like twenty years ago, a family friend pontificated that in the year 2000, there would be a computer language. He didn't know what it would look like, but he did know that it would be called FORTRAN. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I used to have a .sig but I found it impossible to please everyone..." --SFJ From usenet_spam at janc.invalid Thu Apr 1 22:29:52 2004 From: usenet_spam at janc.invalid (JanC) Date: Fri, 02 Apr 2004 03:29:52 GMT Subject: Prothon, metaclasses, Zope [Was: A 'Python like' language] References: <95aa1afa.0403272243.78d60724@posting.google.com> <95aa1afa.0404010017.2f1683b8@posting.google.com> Message-ID: "Mark Hahn" schreef: > As far as top-posting, I am trying to improve, it's just hard to > change my reply style after using it for 30 years without getting any > complaints before. I feel like I'm in a twilight-zone episode. You're still not using OE-QuoteFix... ;-) -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From fumanchu at amor.org Thu Apr 22 12:24:45 2004 From: fumanchu at amor.org (Robert Brewer) Date: Thu, 22 Apr 2004 09:24:45 -0700 Subject: Deleting objects Message-ID: Thomas Philips wrote: > I'm teaching myself OOP using Michael Dawson's "Python Programming For > The Absolute Beginner" and have a question about deleting objects. My > game has two classes: Player and Alien, essentially identical, > instances of which can shoot at each other. Player is described below > > class Player(object): > #Class attributes for class Player > n=0 #n is the number of players > > #Private methods for class Player > def __init__(self,name): > self.name = name > self.strength = 100 > Player.n +=1 > > def __del__(self): > Player.n -=1 > print "I guess I lost this battle" > > #Public methods for class Player > def blast(self,enemy,energy): > enemy.hit(energy) > > def hit(self,energy): > self.strength -= energy > if(self.strength <= 50): > self.__del__() > > I instantiate one instance of each class: > Hero = Player("Me") > Villain = Alien("Not Me") > > If Hero hits Villain with > Hero.blast(Villain, 100) > > Villain dies and executes its destructor (__del__). The game then > ends. However, when I execute the program in IDLE, IT FINISHES BY > EXECUTING THE DESTRUCTOR FOR BOTH HERO AND VILLAIN. > > How can this be? As one of the two objects was destroyed prior to the > end of the game, how can it be re-destroyed when the program ends? A couple points: 1. Forget what you know about 'private' and 'public' members. For now, create every attribute and method as if it were public. You can add back in concepts of 'private' members in a couple weeks, if you still feel you need them. 2. __del__ is not a destructor; that is, when you call: if(self.strength <= 50): self.__del__() self is not destroyed. Read http://docs.python.org/ref/customization.html for the spec on __del__. Instead, you might try a container (like a list) which holds Player instances: players = [] class Player(object): def __init__(self,name): self.name = name self.strength = 100 def blast(self,enemy,energy): enemy.hit(energy) def hit(self,energy): self.strength -= energy if(self.strength <= 50): print "I guess I lost this battle" players.remove(self) Hero = Player("Me") players.append(Hero) Villain = Player("Not Me") players.append(Villain) Hero.blast(Villain, 100) print players Robert Brewer MIS Amor Ministries fumanchu at amor.org From peter at engcorp.com Thu Apr 29 10:50:51 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 29 Apr 2004 10:50:51 -0400 Subject: String formatting (%) In-Reply-To: References: <0fc7c423f6c71f60bc863e72b0765f6c@news.teranews.com> Message-ID: Peter Hansen wrote: > >>> import re > >>> s = '21421906.12' > >>> > >>> re.sub(r'(?<=\d)(?=(\d\d\d)+\.)', ',', s) > '21,421,906.12' > >> Of course, the OP would substitute spaces for the commas. > > >>> _.replace(',', ' ') > '21 421 906.12' And in case the OP is entirely unfamiliar with regular expressions, you wouldn't actually do a separate "replace" operation like the above, so re.sub(r'(?<=\d)(?=(\d\d\d)+\.)', ' ', s) should work nicely, at least with any floating that *always* has a decimal point present. If the numbers might sometimes not have a decimal point, I think this will do the job, so it's a more general solution: re.sub(r'(?<=\d)(?=(\d\d\d)+(\.|$))', ' ', s) Note that addition of an alternate for \. at the end of the pattern. -Peter From a at a.invalid Tue Apr 20 12:24:35 2004 From: a at a.invalid (Timo Virkkala) Date: Tue, 20 Apr 2004 16:24:35 GMT Subject: Threats to the: Daily Python URL! In-Reply-To: References: <2ae25c6b.0404182250.4c5bc870@posting.google.com> Message-ID: <79chc.279$uz.274@read3.inet.fi> Nobody wrote: >>Please don't stop the excellent work that you do. >>I don't know what threats and insults you suffered but I would like to >>ensure you that I for one read the column and value it. > > The people who would do that (threats and insults) should have their jobs > offshored. ...preferably to the middle of the Pacific Ocean, with the employee with the job. =) -- Timo Virkkala From jcarlson at uci.edu Sun Apr 11 14:11:03 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Sun, 11 Apr 2004 11:11:03 -0700 Subject: Newbie Q: Extra spaces after conversion from utf-8 to utf-16-le ? In-Reply-To: <915dc3ae.0404102233.4248dc9a@posting.google.com> References: <915dc3ae.0404102233.4248dc9a@posting.google.com> Message-ID: > I am an absolute Newbie who has done a good amount of googling with > the keywords utf-8, utf-16, python, convert and has reasoned that the > following code could be used to convert a utf-8 text file to a > utf-16-le (I believe this is what Windows uses for Unicode): > > s1 = open("utf8_file_generated_with_perl.txt", "r").read() > s2 = unicode(s1, "utf-8") > s3 = s2.encode("utf-16-le") > open ("new_file_supposedly_in_utf16le", "w").write(s3) > > Well, this code kind of works (meaning I do not get any errors), but > the produced file contains an extra space after every character (l i k > e t h i s) and Windows believes this is an ANSI (i.e. non-unicode > file). Clearly, what I think is working is actually not. For standard /ASCII/ characters, when encoded with utf-16-le, there exists a 'null' character trailing every input character that exists in standard ASCII... >>> s = unicode("hello", "ascii") >>> s u'hello' >>> s2 = s.encode("utf-16-le") >>> s2 'h\x00e\x00l\x00l\x00o\x00' Generally, "Windows" makes no assumption about encoding and always assumes ASCII. What many (not all) systems do to tell the app what encoding is being used, is place what is known as a 'BOM' at the beginning of the file. Check unicode.org for more information. You will also likely find opening files as 'binary' in Windows, when working with unicode, goes a long ways towards making correct output. - Josiah From irmen at -nospam-remove-this-xs4all.nl Thu Apr 15 14:54:06 2004 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Thu, 15 Apr 2004 20:54:06 +0200 Subject: Socket error: 10053 software caused connection abort In-Reply-To: References: Message-ID: <407eda4e$0$576$e4fe514c@news.xs4all.nl> Jean-Pierre Bergamin wrote: > Hello there > > I'm getting an error on Windows XP when I send big data chunks over a socket > connection. The exception I get is: "socket.error: (10053, 'Software caused > connection abort')" > This happens in the socket.recv function. I have the same error here, and it is NOT because of a bug in Windows' TCP stack. (even though the problem does not occur on Linux). The problem is in your code. You are receiving chunks of data like this: > # Get data as long as there's something on the line > data = '' > block_size = 1024 > while(1): > chunk = self.connection.recv(block_size) > if not chunk: > break > > data += chunk > > if (len(chunk) < block_size): > # We got all the data > break > > return data But this code is flawed: recv() CAN return less than block_size, *even* if there is more data to be read on the socket. So, you should not check if the length of the received chunk is less than the length argument passed to recv(). Instead, you should count the total number of bytes you received and check that with the expected total amount. Also, string appending is slow. Better append to a list and when the loop is complete, return ''.join(alist). I fixed your client and server receive loops in the mentioned way, and they work fine even on windows :-) However there is one more thing, when your block_size (the argument to recv) is "too large" there are certain OSes that show problems (VMS, Windows XP). MemoryErrors and such. I have been using: chunk=sock.recv(min(60000,block_size)) quite successfully. --Irmen de Jong From jzgoda at gazeta.usun.pl Thu Apr 15 15:29:14 2004 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Thu, 15 Apr 2004 19:29:14 +0000 (UTC) Subject: CamelCase versus wide_names (Prothon) References: Message-ID: Mark Hahn pisze: > 1) CamelCase is more elegant, modern, more readable, and more efficient in > character usage. I use CamelCase in my ObjectPascal (Delphi, FP) code. Looks really good, but it's Pascal. > 2) Wide_names is cleaner, more readable, compatible with C, which is the > standard module language for Python and Prothon. Wide_names is also the > Python standard. I don't like underscores. I know, it's my problem. ;) > Of course in the Python world you alread have wide_names as your standard, > but could you for the moment pretend you were picking your standard from > scratch (as we are doing in the Prothon world) and give your vote for which > you'd prefer? mixedCase, like in Java (sorry). This convention makes clean distinction between objects and classes. I like it. Am I crazy? Yes, I am. ;) -- Jarek Zgoda http://jpa.berlios.de/ From tungwaiyip at yahoo.com Tue Apr 6 13:50:14 2004 From: tungwaiyip at yahoo.com (Tung Wai Yip) Date: Tue, 06 Apr 2004 10:50:14 -0700 Subject: unpack tuple of wrong size Message-ID: I want to do t = (1,2) a,b = t # get a=1 and b=2 However when t = (1,) a,b=t I got a "ValueError: unpack tuple of wrong size" What I want is for a=1 and b=None. Is there a good way to do this? Wai Yip Tung From greg at cosc.canterbury.ac.nz Wed Apr 7 20:52:47 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Thu, 08 Apr 2004 12:52:47 +1200 Subject: [OT] The Cracker's Guide To Python In-Reply-To: <04g770lqpbhdgr3n3b9mnu9o8f08fdkgk0@4ax.com> References: <04g770lqpbhdgr3n3b9mnu9o8f08fdkgk0@4ax.com> Message-ID: Christos TZOTZIOY Georgiou wrote: > The only problem would be that if the crack is written in > Python, it won't be able to open the dll as read-write... That's no problem -- use py2exe to wrap it up with its own private version of the interpreter. For bonus points, compile it with Pyrex, so the kiddies can have fun reverse engineering it to find out how it works. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From meyer at acm.org Wed Apr 7 18:56:07 2004 From: meyer at acm.org (Andre Meyer) Date: Wed, 7 Apr 2004 22:56:07 +0000 (UTC) Subject: Dynamic creation of an object instance of a class by name References: <10f99b0f.0404070656.5960e2c8@posting.google.com> Message-ID: Right, ok, well, I do not assume to know what classes can be instantiated, thus anything like accessing globals() is not likely to help, sorry. The eval() version works pretty ok so far. I am develpoing a module of which other people can make use of by developing their own subclasses, but they need to be instantiated by my code. Eval() does the trick for me or is there a better way, assuming you do not need to know which class it might be beforehand? btw I LOVE dynamicity... ;-) kind regards Andre From rajarshi at presidency.com Wed Apr 7 12:10:04 2004 From: rajarshi at presidency.com (Rajarshi Guha) Date: Wed, 07 Apr 2004 12:10:04 -0400 Subject: how to read data from a socket given a file descriptor Message-ID: Hi, I'm writing some code using PyGTK2 that uses inpu_add_full() to watch a socket. I've included the code below. I have two questions: 1) What does a condition == 16 mean? It does match any of the gtk.gdk.INPUT_* values. What is the use of the condition variable in the callback? 2) The source variable in the call back is an fd. I have some trivial code that is able to read from a socket: while 1: sock.listen(1) conn = sock.accept()[0] got = conn.recv(20) if (got == 'close'): break conn.send('hello there %d' % (c)) c += 1 But how can I make this work when I get an fd? Thanks, --%<------------------------------------------------------- def process_socket_message(source, condition): if condition == gtk.gdk.INPUT_READ: print 'something to read' elif condition == gtk.gdk.INPUT_WRITE: print 'ok to write' elif condition == gtk.gdk.INPUT_EXCEPTION: print 'an exception occured on the socket' else: print 'I dont know what the condition means' conn = sock.accept()[0] got = conn.recv(20) print got return gtk.TRUE if __name__ == '__main__': gnome.init('xxx','xxx') widgets = WidgetsWrapper('gui.glade','toplevel', TopLevelHandlers) # set up the socket to get messages from a client sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) sock.bind('/tmp/mysocket') # setup and input_add socket_handler_id = gtk.input_add_full(sock, gtk.gdk.INPUT_READ, process_socket_message) gtk.mainloop () From alf at calvin.fayauffre.org Thu Apr 15 04:25:27 2004 From: alf at calvin.fayauffre.org (Alexandre Fayolle) Date: Thu, 15 Apr 2004 08:25:27 +0000 (UTC) Subject: Aspect Programming Module References: <84fc4588.0404140106.3fa0c55@posting.google.com> <8ef9bea6.0404142155.90b41ef@posting.google.com> <407E394B.2050709@mxm.dk> Message-ID: Le 15-04-2004, Max M a ?crit?: > Hung Jung Lu wrote: > >> Python does not even have codeblocks. So how can you say AOP is not >> needed for Python programmers? > > I am probably rather dense, but I have not seen aspect oriented examples > that could not have been done with simple mixins. Hi Max, I'm probably rather dense too :-) How do you implement the logging aspect with a simple mixin? (the logging aspect prints a statement before and after each method call of a class instance) -- Alexandre Fayolle LOGILAB, Paris (France) http://www.logilab.com http://www.logilab.fr http://www.logilab.org From manian at dishnetdsl.net Tue Apr 13 02:19:45 2004 From: manian at dishnetdsl.net (Shiva Kumar) Date: Tue, 13 Apr 2004 11:49:45 +0530 Subject: [Csv]PEP 305 Message-ID: <002b01c4211f$51f4ff90$0701a8c0@advaita> hi, following code will be giving namespace error,plz find out what is the wrong in this & plz send meback to correct code. import System.Xml; importMicrosoft.Xml; public class Test { public static void Main(){ XmlDocument doc = new XmlDocument(); XmlCsvReader reader = new XmlCsvReader("c:\customers.csv"), doc.NameTable); reader.FirstRowHasColumnNames = true; reader.RootName = "customers"; reader.RowName = "customer"; doc.Load(reader); Console.WriteLine(doc.OuterXml); doc.Save("output.xml"); } thanks regards shivakumar -------------- next part -------------- An HTML attachment was scrubbed... URL: From jcarlson at uci.edu Sat Apr 3 17:09:50 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Sat, 03 Apr 2004 14:09:50 -0800 Subject: Python is faster than C In-Reply-To: References: <406F0907.96F37EA1@tunes.org> Message-ID: > For the 1st April, it's finish. That wasn't a joke, psyco does in fact work /really/ well for some things. - Josiah From jepler at unpythonic.net Thu Apr 22 07:23:15 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Thu, 22 Apr 2004 06:23:15 -0500 Subject: Cell objects and their values In-Reply-To: References: Message-ID: <20040422112314.GA19189@unpythonic.net> On Thu, Apr 22, 2004 at 10:34:13AM +0000, Michael Hudson wrote: > That wouldn't work in Python 2.2, I don't know what Jeff is using > these days... 2.4 CVS .. what, doesn't everybody? Jeff From peter at engcorp.com Fri Apr 2 17:40:31 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 02 Apr 2004 17:40:31 -0500 Subject: GUI Frameworks in Python? In-Reply-To: References: Message-ID: Peter Hansen wrote: > Hugh Macdonald wrote: > >> I just wrote the following simple script: >> >> ------------------------------------------------- >> #!/software/python/python2.2.2/linux/bin/python >> import time >> startTime = time.time() >> from wxPython.wx import * >> print "Time:",time.time()-startTime >> ------------------------------------------------- >> >> On running multiple times, I get the following outputs: >> >> Time: 4.60863804817 >> Time: 3.26165890694 >> Time: 3.24744296074 >> Time: 3.26767706871 >> Time: 3.25304102898 > > Running that repeatedly (sorry, can't reboot conveniently > right now, so can't get the first time) it takes 0.125 s > on my machine. Just upgraded to the newly released (thank you so very much for all your work Robin Dunn... now get back to that book! ;-) 2.5.1.5 to compare, sort of, with Chris Perkins' results. Now it consistently takes 0.20 seconds to run the above on my machine... how very odd. -Peter From michael at foord.net Wed Apr 14 03:23:09 2004 From: michael at foord.net (Fuzzyman) Date: 14 Apr 2004 00:23:09 -0700 Subject: Wrapper round x86 Assembler References: <8089854e.0404082353.7bf163a2@posting.google.com> <4dKdnQlIXMIXIevdRVn-gg@powergate.ca> <8089854e.0404100204.504186a0@posting.google.com> <8089854e.0404122329.5dfe5ce1@posting.google.com> Message-ID: <8089854e.0404132323.3283390@posting.google.com> Peter Hansen wrote in message news:... > Fuzzyman wrote: > > > Right ? I got confused by the mention that they could handle inline > > assembler.... so many of the compilers include an assembler as well... > > purely for 'inline assembly'.... ?? > > That's correct. Of course, many also do the CC+AS thing, but > I think that's no longer the most common approach. > > > My past experience of assembly was using an operating system that > > handled multitasking 'behind the scenes' (pre-emptive multitasking) - > > so there was no performance hit on the rest of your system from > > writing crappy assembly - and the internal architecture of the > > processor was useful enough to make coding fun..... > > The 68K was certainly assembly-friendly, compared to anything > yet produced by Intel. :-) > > > It does occur to me that for a certain subset of a 'pseudo assembly > > language' a 'cross-platform assembler' could work > > I really think that in most ways that matter (not quite all, but most) > this is exactly what C was designed to be and is. It is only a very > thin layer on top of assembly, really. You can think of it is a > pseudo-high-level language designed to allow assembly programmers to > write code roughly the way they would if they were not just hacking. > The Amiga's huge variety of STRUCT macros, for example, are > practically field-for-field identical to how C structs work, mostly > just providing an efficient method for specifying the offsets of > each field. Pointers are nothing more than a more concise way of > expressing the "indirect" addressing mode. Heck, C even has (or had) > the "goto" statement and labels! And the for loop syntax is basically > just how assembly loops are done, but again in a more concise and > readable fashion. > > I think anyone who attempted to do a "cross-platform assembler" > would quickly find themselves heading in the direction of something > like C. (I know such things have actually been attempted, and even > exist, by the way. They just aren't mainstream and clearly C has > greater success.) Any attempt to stay at the level of hardware > registers would immediately prevent the term "cross-platform" from > applying. > > -Peter In summary - I'm better off learning C and how to write Python extensions !! It's just a very 'undynamic solution'. Ho hum.... I've been trying to avoid delving into the arcane makefile/linker/compiler chain mysteries... probably be more useful anyway. I will be using MinGw and gcc I think.... great fun - any suggestions of good resources to start learning : a) The mechanics and plumbing of using MinGw to compile for the win32 platform (building makefiles, system configuration etc) b) learning C I'm 'aware' of the concepts of memory allocation, garbage collection etc - but I'm sure there's plenty more to learn.......... Regards, Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html From rjt-usenet at thegrindstone.me.uk Wed Apr 21 08:22:41 2004 From: rjt-usenet at thegrindstone.me.uk (Richard Taylor) Date: Wed, 21 Apr 2004 12:22:41 +0000 Subject: Passing argument to setsockopt(socket.SOL_SOCKET, IN.SO_BINDTODEVICE, intr) References: <408640b7$0$31671$fa0fcedb@lovejoy.zen.co.uk> Message-ID: <40866792$0$31708$fa0fcedb@lovejoy.zen.co.uk> Richard Taylor wrote: > > Hi > > Does anyone know the correct way to pass the 'device' argument to > setsockopt with the SO_BINDTODEVICE flag? > > I have tried various methods: > > setsockopt(socket.SOL_SOCKET,IN.SO_BINDTODEVICE,"eth0") > setsockopt(socket.SOL_SOCKET,IN.SO_BINDTODEVICE,inet_aton("eth0")) > setsockopt(socket.SOL_SOCKET,IN.SO_BINDTODEVICE,struct.pack("s","eth0")) > setsockopt(socket.SOL_SOCKET,IN.SO_BINDTODEVICE,struct.pack("p","eth0")) > > None of these work. I just get a "socket.error: (19, 'No such device')". > > I do have an "eth0" device :-) > > Many thanks > > Richard Solved it! So for others that find this in the news archive... The answer is: s.setsockopt(socket.SOL_SOCKET,IN.SO_BINDTODEVICE,struct.pack("%ds" % (len("eth0")+1,), "eth0")) Richard From aahz at pythoncraft.com Fri Apr 2 01:12:39 2004 From: aahz at pythoncraft.com (Aahz) Date: 2 Apr 2004 01:12:39 -0500 Subject: Prothon, metaclasses, Zope [Was: A 'Python like' language] References: <95aa1afa.0403272243.78d60724@posting.google.com> <95aa1afa.0404010017.2f1683b8@posting.google.com> <95aa1afa.0404011933.5cc5e959@posting.google.com> Message-ID: In article <95aa1afa.0404011933.5cc5e959 at posting.google.com>, Michele Simionato wrote: >aahz at pythoncraft.com (Aahz) wrote in message news:... >> >> Michele, I just got a mailbox full error when I tried sending you >> e-mail. Please fix. > >It should work now. My address michele.simionato at poste.it is mostly >a span recipient I don't check often. Rea addresses I check every day are >michelesimionato at libero.it and michele.simionato at partecs.com Then please make those addresses readily available by sticking them in your .sig or something. Having a non-replyable address is about as rude as top-posting. ;-) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "usenet imitates usenet" --Darkhawk From peter.maas at mplusr.de Thu Apr 22 05:25:42 2004 From: peter.maas at mplusr.de (Peter Maas) Date: Thu, 22 Apr 2004 11:25:42 +0200 Subject: Problem with xml.dom parser and xmlns attribute Message-ID: Hi, I have a problem parsing html text with xmldom. The following code runs well: -------------------------------------------- from xml.dom.ext.reader import HtmlLib from xml.dom.ext import PrettyPrint r = HtmlLib.Reader() doc = r.fromString( '''

hallo welt ''') PrettyPrint(doc) -------------------------------------------- but if I replace by I get the error Traceback (most recent call last): File "xhtml.py", line 5, in ? doc = r.fromString( File "C:\PROGRA~1\Python23\lib\site-packages\_xmlplus\dom\ext\reader\HtmlLib.py", line 69, in fromString return self.fromStream(stream, ownerDoc, charset) File "C:\PROGRA~1\Python23\lib\site-packages\_xmlplus\dom\ext\reader\HtmlLib.py", line 27, in fromStream self.parser.parse(stream) File "C:\PROGRA~1\Python23\lib\site-packages\_xmlplus\dom\ext\reader\Sgmlop.py", line 57, in parse self._parser.parse(stream.read()) File "C:\PROGRA~1\Python23\lib\site-packages\_xmlplus\dom\ext\reader\Sgmlop.py", line 160, in finish_starttag unicode(value, self._charset)) File "C:\PROGRA~1\Python23\lib\site-packages\_xmlplus\dom\Element.py", line 177, in setAttributeNS attr = self.ownerDocument.createAttributeNS(namespaceURI, qualifiedName) File "C:\PROGRA~1\Python23\lib\site-packages\_xmlplus\dom\Document.py", line 139, in createAttributeNS raise NamespaceErr() xml.dom.NamespaceErr: Invalid or illegal namespace operation >Exit code: 1 A lot of HTML documents on Internet have this xmlns=.... Are they wrong or is this a PyXML bug? Mit freundlichen Gruessen, Peter Maas -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Hubert-Wienen-Str. 24 Tel +49-241-93878-0 Fax +49-241-93878-20 eMail peter.maas at mplusr.de ------------------------------------------------------------------- From OlafMeding at compuserve.com Tue Apr 27 14:39:32 2004 From: OlafMeding at compuserve.com (Olaf Meding) Date: 27 Apr 2004 11:39:32 -0700 Subject: MS COM early and late binding Message-ID: <9e5ea2c4.0404271039.2da829b5@posting.google.com> Is there a way to find out if I am using early or late binding given the reference ("excel" in the example below) returned by Dispatch()? >>> import win32com.client >>> excel = win32com.client.Dispatch('Excel.Application') Thanks much for your help. Olaf From agriff at tin.it Mon Apr 26 02:30:10 2004 From: agriff at tin.it (Andrea Griffini) Date: Mon, 26 Apr 2004 06:30:10 GMT Subject: About generators Message-ID: I'm new to python and I really like what I've seen so far with just one exception; the absence of a nice syntax for ranges of integers. I've read PEPs about allowing for i in 10: print i and I must say I don't like it very much, but I didn't find a discussion about what looks more natural for i in 0...9: print i or squares = [x*x for x in 1...100] that is having "expr1 ... expr2" returning an iterator from expr1 to expr2 (second limit included). Has this been considered ? If yes (as I suppose) where can I find and explanation about it ? So far python seems very logical, and an explanation of this seemingly illogical absence would help me (I hope) in better understanding this language. TIA Andrea From akgul at infovillage.net Thu Apr 22 21:24:34 2004 From: akgul at infovillage.net (akgul at infovillage.net) Date: Fri, 23 Apr 2004 01:24:34 +0000 Subject: Python-list, Exotic sex is urgently necessary for you! In-Reply-To: References: Message-ID: An HTML attachment was scrubbed... URL: From irmen at -nospam-remove-this-xs4all.nl Wed Apr 14 03:01:01 2004 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Wed, 14 Apr 2004 09:01:01 +0200 Subject: ANN: Snakelets 1.24 (simple-to-use web app server with dynamic pages) In-Reply-To: <9396ba6f.0404131915.7cef8607@posting.google.com> References: <407c6d15$0$562$e4fe514c@news.xs4all.nl> <9396ba6f.0404131915.7cef8607@posting.google.com> Message-ID: <407ce1ab$0$566$e4fe514c@news.xs4all.nl> Stewart Midwinter wrote: > Interesting! There is definitely a niche for an app server that is > simpler to use than Zope. Could this be used for a simple CMS, i.e. > simpler than Plone? If so, are you aware of any examples of such a > use? Snakelets is a bare bone web app server (modeled after Java's JSP/Servlets). It provides the necessary foundation to build a dynamic web site/application, but not much more. A CMS is a (possibly quite complex) piece of software that must be built on top of it. What did you have in mind? Bye --Irmen de Jong. From fumanchu at amor.org Fri Apr 30 14:02:38 2004 From: fumanchu at amor.org (Robert Brewer) Date: Fri, 30 Apr 2004 11:02:38 -0700 Subject: Dictionnary vs Class for configuration Message-ID: Famille Delorme wrote: > I wrote a program in Python for a school project and I am in trouble. > I have make a Python script called conf.py. This file > contains dictionnarys > for configuration like this: > config_sql = { > "DATABASE" : "nanana", > "USERDB" : "bob", > "PASSWORD" : "********" > } > config_script = { > "TIMETOSLEEP" : 100 > "PATH" : "/home/script" > } > The config_section variable is included in each modules > (script python) used > in my program > (with from config.py import config_section) > And the use is like this > from conf.py import config_sql > print config["DATABASE"] > > But my master say it's better to do a class like this > class config : > def __init__(self, part=="") : > if (part=="SQL") : > self.database="nanana" > self.userdb="bob" > self.password="*******" > elif (part=="SCRIPT") : > self.timetosleep=10 > self.path="/home/script" > .... > > and the use like this > from conf.py import config > cfg=config("SQL") > print cfg.database > > We have do only a file for configuration because the > administrator is no > searching for configuration. > I want know : > - what is more faster, dictionnary method or class method? > - what use more ram memory ? > - if you are administrator, what method you like for > configure program ? > > Note: > * the class will not have methods, it is not necessary. > * the program is composed of several modules which import > config_section. People who install your code are 'deployers' of that code. When you use 'import' to load configuration data from a Python module, you force your deployers to learn Python. This is a bad choice, in my opinion. Therefore, both methods are insufficient. Look at the ConfigParser module for a better way to maintain data which is provided by your deployers. Robert Brewer MIS Amor Ministries fumanchu at amor.org From jjl at pobox.com Sat Apr 17 17:45:47 2004 From: jjl at pobox.com (John J. Lee) Date: 17 Apr 2004 22:45:47 +0100 Subject: AOP use cases References: <84fc4588.0404140106.3fa0c55@posting.google.com> <0pydnSB4WYuieuLdRVn-hQ@powergate.ca> <1082n594lndh27f@news.supernews.com> Message-ID: <87pta6qnw4.fsf@pobox.com> "John Roth" writes: [...] > When you're supporting a monolithic proprietary application, > sometimes you have to do what you have to do, but today > the entire idea simply smells of a high-tech way to do > ad-hoc patching where a really well designed application > would not need it (and I don't really care if the design is > up front or emergent.) That's unfair. Regardless of your view of its importance, AOP is clearly sufficiently well-motivated purely in terms of separation of concerns. That it's also useful as a hack to patch badly-designed software written in inflexible languages doesn't change that in the least. John From mcfletch at rogers.com Thu Apr 8 13:35:52 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Thu, 08 Apr 2004 13:35:52 -0400 Subject: Tcl/Tk extension access from python under windows In-Reply-To: References: Message-ID: <40758D78.8060103@rogers.com> The default search path for tcl packages from the Python Tcl/Tk is Python23\tcl\* so create a directory there with the name of the package, and put a pkgInfo.tcl and your dll into the directory. pkgInfo.tcl should look something like: if {![package vsatisfies [package provide Tcl] 8]} {return} package ifneeded Togl 1.6.0 \ [list load [file join $dir Togl.dll] Togl] You can use the tcl dde1.2 package you'll find there as a template. HTH, Mike Marcel Achim wrote: >Hi, > >I found a tcl extension that does exactly what I need to access a DLL >and it would require a large amount of SWIG glue to generate an >equivalent python extension. I want to access it via >root.tk.call("eval", "package require extension"). > ... _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From jack at performancedrivers.com Mon Apr 19 10:15:28 2004 From: jack at performancedrivers.com (Jack Diederich) Date: Mon, 19 Apr 2004 10:15:28 -0400 Subject: [Python-Dev] PEP 329: Treating Builtins as Constants in the Standard Library In-Reply-To: <00cb01c4260d$80b9b120$e841fea9@oemcomputer> References: <00cb01c4260d$80b9b120$e841fea9@oemcomputer> Message-ID: <20040419141528.GA23507@performancedrivers.com> On Mon, Apr 19, 2004 at 08:54:41AM -0400, Raymond Hettinger wrote: > Comments are invited on a new pep: > > http://www.python.org/peps/pep-0329.html > > Based on feedback received so far, there were several changes to the > original draft: > > * The module is public > > * The module name reflects its nature as a bytecode hack > I dread saying it, but is 'pragma.py' a better name than 'codetweaks.py'? They both rhyme with magic but pragma is more familiar (I think?). -jackdied From youngdubliner at hotmail.com Wed Apr 21 02:56:15 2004 From: youngdubliner at hotmail.com (youngdubliner at hotmail.com) Date: 20 Apr 2004 23:56:15 -0700 Subject: Py_ParseTuple Problem Message-ID: <4039221c.0404202256.3f21d817@posting.google.com> Hi All , Bit of a problem with Py_Parse or Py_ParseTuple ? I have a python script that reads a sector of flash in an embedded device. it returns the value of each byte within the sector as a tuple. i.e. [255,255,255,255,255,255,255, .......etc etc for the whole sector ! We are using this script to read whats currently in any sector. No problems there. Now I need to call our script from C. I want to copy each of the bytes within the sector into an C unsigned char *array Is there any way to do this using Py_ParseTuple or Py_Parse ??? something like this for instance ??? ...... Py_ParseTuple[pres,"??",&my_c_array] so now my_c_array[0] = 255 ,my_c_array[1] = 255 ,my_c_array[2] = 255 , etc etc Thanks for the help ! From Joseph.V.Laughlin at boeing.com Wed Apr 28 14:39:53 2004 From: Joseph.V.Laughlin at boeing.com (Laughlin, Joseph V) Date: Wed, 28 Apr 2004 11:39:53 -0700 Subject: Using C libraries Message-ID: <67B3A7DA6591BE439001F2736233351202876CE0@xch-nw-28.nw.nos.boeing.com> Has anyone had any difficulties using C libraries / data structures with python? Are there any things I need to be aware of? Joe Laughlin Phantom Works - Integrated Technology Development Labs The Boeing Company From dippyd at yahoo.com.au Wed Apr 14 03:38:23 2004 From: dippyd at yahoo.com.au (Steve) Date: Wed, 14 Apr 2004 17:38:23 +1000 Subject: maximum length of a list & tuple References: Message-ID: <407CEA6F.6000601@yahoo.com.au> Lupe wrote: > I just would like to know if there is any limit to a list or tuple. Yes. Since the universe only contains something like 10**85 particles of matter, the upper limit to a list is roughly 2**(10**85) bits. Sorry, I couldn't resist :-D You can store as many things in a list as you have memory for. I suppose there is probably some fundamental limit due to 32 bit addressing issues, but are you sure you are really storing so many items you are hitting that limit? I'd guess you aren't. For example, the other day I was playing around with Python, and just for a lark I created a list with 300,000,000 instances of None. It took about five minutes, but it worked :-) Going back to your original problem: > Each time the function is called, it compares an > element of a list (which is a list too) to other > elements, which all amounts to millions of > comparisons. Are you sure there isn't a more efficient algorithm for what you are trying to do? > The program is working for short lists but not for > longer ones. What do you mean it is working? It doesn't finish? It is too slow? Or it gives the wrong answer? If it is giving a wrong answer, there is a bug in your code. If it is running too slowly, chances are there is a better algorithm that will fix it. -- Steven D'Aprano From skip at pobox.com Mon Apr 12 22:46:23 2004 From: skip at pobox.com (Skip Montanaro) Date: Mon, 12 Apr 2004 21:46:23 -0500 Subject: print u"\u0432": why is this so hard? UnciodeEncodeError In-Reply-To: References: Message-ID: <16507.21631.794319.612353@montanaro.dyndns.org> David> Now I'm curious -- how do you even find out it's a Terminal David> window you're looking at, rather than say an xterm? I just compared the output of "env" in both xterm and Terminal windows and came up with these clues: * TERM in an xterm is "xterm". In Terminal it's "vt100". * In Terminal a TERM_PROGRAM environment variable is defined with a value of "Apple_Terminal". * The xterm also defines DISPLAY for obvious reasons. Skip From jbperez808 at wahoo.com Sat Apr 10 23:01:56 2004 From: jbperez808 at wahoo.com (Jon Perez) Date: 11 Apr 2004 03:01:56 GMT Subject: why is python better than eg. smalltalk?? no one has any solid arguments! you should all go to church with all that religious talk! References: Message-ID: Aahz wrote: > I found my editor fifteen years ago. Guess which it is. (The point > being that there are only two editors still in regular use that were > available fifteen years ago -- and those two editors are still ubiquitous > now. Doesn't matter much which you pick, they'll still be available > fifteen years in the future.) YEAAARRGGGHHH!!! An Emacs user... stay away from me, you satanist!!!! ;-) hehe j/k... From alban at magproductions.nl Wed Apr 28 06:26:07 2004 From: alban at magproductions.nl (Alban Hertroys) Date: Wed, 28 Apr 2004 12:26:07 +0200 Subject: Problem importing packages Message-ID: I'm trying to create a package containing a number of classes I made, but I can't get it to work... My package is structured like this: X/ __init__.py A.py B.py When I try: >>> import X.A python says: Traceback (most recent call last): File "", line 1, in ? ImportError: No module named X.A As far as I can see, I do it exactly like the 'documentation' says, but it obviously doesn't work this way. What am I missing? (clear documentation, obviously...) For the record, I believe my paths are right. If I do the following, I can at least import class A: >>> import sys >>> sys.path.append('X') >>> import A Python version is 2.3.3 on Debian Linux. From martin at tv-animation.com Wed Apr 14 04:22:04 2004 From: martin at tv-animation.com (Martin) Date: 14 Apr 2004 01:22:04 -0700 Subject: Deleting objects with method reference Message-ID: I can't delete this object after I call the Set() function. Why is this so special, and are there any way around it besides removing the ref ? class B: def __del__(self): print "del" def F(self): print "f" def Set(self): self.v = self.F o1 = B() o1.Set() del o1 o2 = B() o2.Set() o2.v = None del o2 >>> "del" -Martin From sympa at ens.fr Tue Apr 20 16:17:49 2004 From: sympa at ens.fr (SYMPA) Date: Tue, 20 Apr 2004 22:17:49 +0200 (CEST) Subject: Results of your commands Message-ID: <200404202017.i3KKHn3G060827@nef.ens.fr> > Command not understood: ignoring end of message. No command found in message From NAIGIMSESRIMAIL at gims.com Thu Apr 1 09:44:55 2004 From: NAIGIMSESRIMAIL at gims.com (GroupShield for Exchange (ESRIMAIL)) Date: Thu, 1 Apr 2004 16:44:55 +0200 Subject: ALERT - GroupShield ticket number OB76_1080830688_ESRIMAIL_3 was generated Message-ID: Action Taken: The message was blocked because of its subject. To: python-list at python.org From: Roel Schroeven Sent: -492544768,29628407 Subject: Re: test for nan Attachment Details:- Attachment Name: N/A File: Infected.msg Infected? No Repaired? No Blocked? Yes Deleted? No Virus Name: -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/ms-tnef Size: 1817 bytes Desc: not available URL: From oliver.schoenborn at utoronto.ca Wed Apr 14 21:01:39 2004 From: oliver.schoenborn at utoronto.ca (Humpty Dumpty) Date: Wed, 14 Apr 2004 21:01:39 -0400 Subject: audio input? References: <3fa378e7.0404141117.5e9f0428@posting.google.com> Message-ID: Have you checked out http://www.fmod.org/? It's a C library and there is a Python extension that uses it. However, I haven't tried it yet, I'm hoping to use it to read audio from mic and show the music notes that are played. Oliver "Tally" wrote in message > > anyone know of a clean, simple audio library or wrapper for Python > that is friendly to capturing low-latency audio to memory? It would be > nice if it had functions like RMS power and that kind of thing but I > can always write that myself in C... From trevp_spam at trevp.net Mon Apr 19 21:09:23 2004 From: trevp_spam at trevp.net (Trevor Perrin) Date: Tue, 20 Apr 2004 01:09:23 GMT Subject: block ciphers Message-ID: <7L_gc.53134$Gn6.49963@newssvr25.news.prodigy.com> (I know this has come up before, but the previous discussions I could find seemed inconclusive, so I hope people don't mind...) Q: How about adding block ciphers to Python 2.4? PEP 272 defines an API, and there's an excellent library that implements it [1]. It would be very little work to copy the AES and DES3 modules into stdlib (perhaps in a 'ciphers' package). As far as legal issues, US Export is no problem - you just email in a notice [2]. A few countries have import issues, though I believe they're widely disregarded (the windows installer comes with SSL; has anyone complained?). Furthermore, it would be easy to provide a no-crypto distribution. It's hard to distribute pure-python crypto software without this. You have to include or reference 3rd-party extension modules, which some users won't want to install, some will have trouble installing (like Windows users without a compiler), and some won't be able to install (Jython or IronPython users, for example). So is this totally out of the question? Or would it be worth pursuing, through a PEP, or patch, or discussion on python-dev? Trevor [1] http://www.amk.ca/python/code/crypto.html [2] http://www.bxa.doc.gov/Encryption/PubAvailEncSourceCodeNofify.html From herrn at gmx.net Mon Apr 5 08:47:34 2004 From: herrn at gmx.net (Marco Herrn) Date: 5 Apr 2004 12:47:34 GMT Subject: regex help for a newbie Message-ID: Hi, I am not very familiar with regular expressions. So I hope someone can help me to achieve what I want. I have the following string in my program: string= "aaa%(BBB%(CCC)BBB)aaa%(DDD)aaa" Now I need to extract the parts that are enclosed in %(). There are 3 levels of nesting. The first level is named 'aaa', the second 'BBB' and 'DDD' and the third 'CCC'. I do not need to extract the third level at this moment, since I extract the parts in a recursive function. So the thing I want to achieve here is to extract %(BBB%(CCC)BBB) and %(DDD). I tried it with the following: re.search("%\(.*\)", string).group() But that returns: %(BBB%(CCC)BBB)aaa%(DDD)' which is, of course, not what I want. So how must the regex look like that I get the two strings I need? Marco -- Marco Herrn herrn at gmx.net (GnuPG/PGP-signed and crypted mail preferred) Key ID: 0x94620736 From fredrik at pythonware.com Fri Apr 16 13:26:45 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 16 Apr 2004 19:26:45 +0200 Subject: Passing a parameter to filter References: Message-ID: Thomas Philips wrote: > Now, I try to filter a range using > >>> filter(f(k=3),range(20)) f(k=3) calls the function, so you're passing the return value to filter, not the function itself. that's obviously not what you want. some alternatives: filter(lambda x: f(x, 3), range(20)) [x for x in range(20) if f(x, 3)] the lambda form creates an "anonymous function" that takes one argument, and calls your f() function with the right arguments. the second form is a "list comprehesion", which is a compact way to write for-in loops. (this reply will be followed by 20 replies pointing you to 150-line scripts that lets you do what you want by a combination of metaclasses, byte- code rewriting, and iterators...) From martin at v.loewis.de Fri Apr 23 02:02:08 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 23 Apr 2004 08:02:08 +0200 Subject: Deleting objects - my earler post got garbled In-Reply-To: <38ec68a6.0404222110.43416e1d@posting.google.com> References: <40883067.4000702@v.loewis.de> <38ec68a6.0404222110.43416e1d@posting.google.com> Message-ID: Asun Friere wrote: >>There is no way to explicitly delete an object in Python. > > > So what does "del " actually do then? The syntax is not "del ", but "del ". It unbinds so that does no longer refer to the object it used to refer to, very similar to saying = None Whether that causes deletion of the object depends on whether there are other reference to the same object, in different variables. Regards, Martin From tor.iver.wilhelmsen at broadpark.no Wed Apr 28 15:48:18 2004 From: tor.iver.wilhelmsen at broadpark.no (Tor Iver Wilhelmsen) Date: 28 Apr 2004 21:48:18 +0200 Subject: Could someone explain this to a newbie References: Message-ID: Heiko Wundram writes: > in the string are contained in the chars array which you pass in (namely > "ne"), and thus they are also stripped from the string. Maybe the docs ought to state that the method stops once it hits a char not in the *set* the passed string represents. From Mike at DeleteThis.Geary.com Wed Apr 7 11:35:13 2004 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Wed, 7 Apr 2004 08:35:13 -0700 Subject: Using python23 to develop an extension for an application that has python22 embedded References: <1073eeubflmchd5@corp.supernews.com> Message-ID: <10787tl9fmth0cd@corp.supernews.com> Andrew MacIntyre wrote: > You can then use another compiler supported by the > Distutils (MS CL non-optimising compiler, MinGW, > Borland etc) to build the distributable extension in > either a Python 2.2 or 2.3 installation, without risking > mixing C runtime library mismatches (VS.NET uses a > different CRT than VS6 I understand). If using a 2.3 > installation, you'll need to substitute a 2.2 import > library when building the final distributable version. Do I understand you correctly? It sounds like you are saying there is a problem using a DLL built with VC6 and another DLL built with VS.NET in the same application, but if you were to use a Borland or other compiler, then you would avoid this problem. That's not right at all. It's commonplace to have multiple DLLs loaded into a Windows application, all built with different compilers and all using different C runtimes. You can have one built with VC6, another with VS.NET, and another with Borland or any other compiler. You certainly don't need to build a DLL with Borland instead of VS.NET to avoid conflicts with another DLL that was built with VC6. If python22.dll has some incompatibility with other DLLs that are built with VS.NET, then there is something seriously wrong with python22.dll. If I misunderstood you, let me know what it was that you were getting at here. BTW, if you're distributing a DLL or application built with VS.NET, you do need to make sure that the appropriate C runtime is available on the target system. In many cases, the best way to do this is to compile and link with the static C runtime instead of the DLL C runtime. If you use the DLL version of the C runtime, you need to distribute it with your app or DLL. To be sure of what other DLLs (C runtimes or whatever) your DLL or app depends on, the best tool is Dependency Walker: www.dependencywalker.com -Mike From mark at prothon.org Tue Apr 27 12:12:11 2004 From: mark at prothon.org (Mark Hahn) Date: Tue, 27 Apr 2004 09:12:11 -0700 Subject: What is good about Prothon? References: Message-ID: "David MacQuigg" wrote ... > Mammal.talk() # Call an unbound function. <== <== !!! This works great in Python, but in Prothon there is no such thing as a class to tell the difference in the binding. The concept of a prototype is in the programmer's mind, not the interpreter's, since every object can be a prototype. Feel free to make this an argument for Python 3, but quit comparing your proposal to Prothon since it is not Prothon compatible. You have argued this in the Prothon mailing lists for almost a month with Greg and me. Please don't just start it up again here (about Prothon I mean). From michael at foord.net Wed Apr 14 03:10:47 2004 From: michael at foord.net (Fuzzyman) Date: 14 Apr 2004 00:10:47 -0700 Subject: 3D Graphics Engine References: <8089854e.0404130639.3eb0db62@posting.google.com> Message-ID: <8089854e.0404132310.17cd290a@posting.google.com> [snip..] > > If you find more/better options, please update this wiki page: > http://www.py3d.org/py3d_zwiki/Python3dLinks > > Have fun, > Mike > > _______________________________________ > Mike C. Fletcher > Designer, VR Plumber, Coder > http://members.rogers.com/mcfletch/ Hmmm... There's lots of interesting things to explore here... too many in fact ;-) Rats... have to do some 'research'. Regards, Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html From andymac at bullseye.apana.org.au Tue Apr 6 07:32:36 2004 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Tue, 6 Apr 2004 21:32:36 +1000 (EST) Subject: Intermittant slow startup In-Reply-To: <9badaf0.0404051445.5b26b945@posting.google.com> References: <9badaf0.0404051033.9fec2db@posting.google.com> <4071A86D.97CA6CAE@alcyone.com> <9badaf0.0404051445.5b26b945@posting.google.com> Message-ID: <20040406213052.Y97937@bullseye.apana.org.au> On Tue, 5 Apr 2004, Michael Mossey wrote: > Erik Max Francis wrote in message news:<4071A86D.97CA6CAE at alcyone.com>... > > Michael Mossey wrote: > > > > > Runnng python 2.2 on HP-UX, I get intermittant slow startup. > > > Sometimes python starts up in a small fraction of a second, and > > > sometimes takes 3-5 seconds. This applies to any script I run, or > > > just typing 'python' at the prompt. > > > > > > I also observed something similar on Linux. > > > > > > Any ideas what would cause *intermittant* slow startup? > > > > Caching? Is it a long time between invocations that it takes a long > > time to start up? > > It is quite intermittant without much of a pattern I can see. One > thing that is definitely true is that if I start up python several > times in a row one right after the other, some can be slow and some > fast. I just observed it start fast twice, then start slow. I don't > remember if it ever does the other way around but I think it does. is any resource coming from an NFS mount? or other network source? -- 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 sdahlbac at abo.fi Wed Apr 14 02:09:03 2004 From: sdahlbac at abo.fi (Simon Dahlbacka) Date: 13 Apr 2004 23:09:03 -0700 Subject: refcounting References: <407c25ca$1@newsflash.abo.fi> Message-ID: "Martin v. L?wis" wrote in message news:... > Simon Dahlbacka wrote: > > > I'm a little confused about the reference counting.. > > > > static PyObject* MyFunction(PyObject * /*self*/, PyObject *args) { > > > > PyObject *list; > > PyArg_ParseTuple(args, &PyList_Type, &list); > > > > //do stuff with list elements > > > > // XXX do I need Py_INCREF(list); here ??? > > return list; > > Yes. PyArg_ParseTuple returns a borrowed reference to the list; the > reference is originally help by the argument tuple (which is immutable, > so the reference is guaranteed to stay while you hold on to the argument > tuple, which is only decrefed in the caller of MyFunction). > > The result must be a new reference, so you must incref. > > > PS. are there any documentation explaining the reference counting issues in > > more detail than the docs @ python.org ? > > No. For the specific issue, the documentation says it all: > > http://docs.python.org/api/arg-parsing.html > > says > > "O" (object) [PyObject *] ... The object's reference count is not increased. > > http://docs.python.org/api/common-structs.html#l2h-821 > > says > > PyCFunction ... The function must return a new reference. thanks for clarifying. Now I think that I understand (a bit more at least) Somehow I had managed to miss the common structs page (and especially the part about "the function must return a new reference") /Simon From pinard at iro.umontreal.ca Fri Apr 23 11:50:26 2004 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Fri, 23 Apr 2004 11:50:26 -0400 Subject: if (__name__ == '__main__'): main(sys.argv[1:]) In-Reply-To: References: <01c601c4271b$7f7300a0$b401010a@sparta> <4085A445.1050303@heneryd.com> Message-ID: <20040423155026.GB5587@alcyon.progiciels-bpi.ca> [Michael Hudson] > Fran?ois Pinard writes: > > A word about the `__metaclass__' line. My intent is to forget all about > > classic classes and go with the new type system as quickly as possible. > > I do not want to derive each and every of my classes from `object', > > and later edit all those `(object)' out when the classic classes will > > effectively get deprecated. > Why would you do that? Your question is surprising, after you just quoted the answer. I guess I miss the real meaning of your question. > I don't like using a __metaclass__ global because it's a non-local > effect. That's exactly why it is useful. You don't like it to be useful? :-) -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From __peter__ at web.de Wed Apr 21 14:54:49 2004 From: __peter__ at web.de (Peter Otten) Date: Wed, 21 Apr 2004 20:54:49 +0200 Subject: Python 2.3.3 super() behaviour References: <40863bd7$0$25528$afc38c87@news.easynet.fr> <4086bdfc$1@pfaff2.ethz.ch> Message-ID: Josef Meile wrote: > Peter Otten wrote: > > As soon as a test() method without the super(...).test() is reached, no > > further test methods will be invoked. Only the first in the list of > > base classes will be invoked. If I'm getting it right you have to do > > something like: > > > > class Base(object): > > def test(self): > > print "base" > > > > class D1(Base): > > def test(self): > > super(D1, self).test() > > print "derived 1" > > > > class D2(Base): > > def test(self): > > super(D2, self).test() > > print "derived 2" > > > > class All(D1, D2): > > pass > > > > All().test() > Ok, this produces almost what the original poster wanted. You > just have to invert the order of the base classes in All: > > >>>class All(D2, D1): > ... pass > ... > > then you will get: > >>> All().test() > base > derived 1 > derived 2 > > However, I don't understand jet why this doesn't print: > > base > derived 1 > base > derived 2 > > The method test of Base is called just once? Why? > I taught it was something like: > > All.test() -> D1.test() + D2.test() > > which is the same as: > > (Base.test() + print "derived 1") + (Base.test() + print derived 2") > > Thanks in advanced, > Josef Every instance has just one __dict__, so calling the same Base method twice would at best be redundant. The Python designers are a bit smarter than that and implemented "cooperative" methods for newstyle classes. See http://www.python.org/2.2/descrintro.html#cooperation for the details. Peter From ramen at lackingtalent.com Sat Apr 10 12:31:58 2004 From: ramen at lackingtalent.com (Dave Benjamin) Date: Sat, 10 Apr 2004 16:31:58 -0000 Subject: Code blocks and top posting References: <8ef9bea6.0404100720.65ffd2c9@posting.google.com> Message-ID: In article <8ef9bea6.0404100720.65ffd2c9 at posting.google.com>, Hung Jung Lu wrote: > Dave Benjamin wrote in message news:... >> def answer(question): >> return 'For pretty much the same reason top posting is.' >> >> if __name__ == '__main__': >> question = 'Why is Python not having code blocks annoying?' >> print answer(question) >> >> # HaHaOnlySerious > > def f(x): > print x > > if __name__ == '__main__': > f('Functions are annoying, by the same token?') for a_better_example in illustration_of_my_point: def you_now_see_why_they_are_there(): print 'At this point, you lack sufficient context to' print 'understand why this function is necessary.' after(you_read_the_above_lines, you_now_see_why_they_are_there) # ie. by requiring the programmer to declare a named function before # passing a closure containing statements, you force the order of # declaration to be the reverse of the order of operation. after(supporting_codeblocks, [ you | you.dont_have_to_read_things_backwards_anymore() ]) # Also, consider an asynchronous chain of events: def async_chain(): def do_step_3(): print 'Step 3.' def do_step_2(): print 'Step 2'. after_idle(do_step_3) def do_step_1(): print 'Step 1'. after_idle(do_step_2) # Do everything I said, but in the opposite order: after_idle(do_step_1) if only(we_could_find_a_nice_syntax_for_codeblocks): print 'We could again forward talking start.' # all in good fun, ramen() -- .:[ dave benjamin: ramen/[sp00] -:- spoomusic.com -:- ramenfest.com ]:. : please talk to your son or daughter about parametric polymorphism. : From martin at tv-animation.com Thu Apr 15 05:59:27 2004 From: martin at tv-animation.com (Martin) Date: 15 Apr 2004 02:59:27 -0700 Subject: Deleting objects with method reference References: Message-ID: Peter Otten <__peter__ at web.de> wrote in message news:... > ... > You can verify this with a weakref.ref object with an appropriate callback: > > import weakref > def ondel(o): > print "del" > > class B: > def F(self): > print "f" > def Set(self): > self.v = self.F > > > o1 = B() > o1.Set() > w = weakref.ref(o1, ondel) > del o1 > > Peter Hi Peter and thanks for your reply! However your example doesn't seem to work. import weakref import gc def ondel(o): print "del" class B: def F(self): print "f" def Set(self): self.v = self.F o1 = B() w1 = weakref.ref(o1, ondel) del o1 >>> del o2 = B() o2.Set() w2 = weakref.ref(o2, ondel) del o2 When I delete o2 I get no output. And gc.garbage is still empty! gc.garbage >>> [] I have tried it in both python 2.1 and 2.3.3. Why doesn't it work? -Martin From griffph at aol.com Mon Apr 19 11:31:20 2004 From: griffph at aol.com (Griff) Date: 19 Apr 2004 08:31:20 -0700 Subject: Problems using modulo Message-ID: Test program: =============================================================== t = 5.8 interval = 2.0 while t < 6.1: print "%s mod %s = %s " % (t, interval, t % interval ) t += 0.1 ================================================================ Results: 5.8 mod 2.0 = 1.8 5.9 mod 2.0 = 1.9 6.0 mod 2.0 = 2.0 !!!!!! 6.1 mod 2.0 = 0.1 ================================================================= if we change t to initialise at 5.9 and run the program again, ================================================================= t = 5.9 interval = 2.0 while t < 6.1: print "%s mod %s = %s " % (t, interval, t % interval ) t += 0.1 ================================================================= Results: C:\Python22>python modprob.py 5.9 mod 2.0 = 1.9 6.0 mod 2.0 = 0.0 # that's better ==================================================== I have tried this on Windows and Unix for Python versions between 1.52 and 2.3. I don't know much about how Python does its floating point, but it seems like a bug to me ? What is the best workaround so that I can get my code working as desired ? (ie I just want to tell whether my time "t" is an exact multiple of the time interval, 2.0 seconds in this case). Would be grateful for any suggestions cheers - Griff From aahz at pythoncraft.com Mon Apr 5 00:36:38 2004 From: aahz at pythoncraft.com (Aahz) Date: 5 Apr 2004 00:36:38 -0400 Subject: Python is faster than C References: Message-ID: In article , Armin Rigo wrote: > >You missed my point indeed. There are two levels here: one is the >language specification (the programmer's experience), and one is the >CPython implementation. My point is that with some more cleverness in >the implementation, iterators would be much less needed at the language >specification level (I'm not saying never, I think generators are >great, for example). Yes, exactly. Without generators, I'm not sure iterators would have taken off to the extent they have. >Yes, and I'm ranting against the idea that the programmer should be >bothered about it, when it could be as efficient automatically. From >the programmer's perspective, iterators are mostly like a sequence that >you can only access once and in order. A better implementation can >figure out for itself when you are only accessing this sequence once >and in order. I mean, it is just like range(1000000) which is a list >all right, but there is just no reason why this list should consume >4MB of CPython's memory when the same information can be encoded in >a couple of ints as long as you don't change the list. The language >doesn't need xrange() -- it is an implementation issue that shows up in >the Python language. While I'm generally in favor of what you're talking about, it seems to a certain extent that you're simply shifting complexity. Maintaining the simplicity of the Python VM is an important goal, I think, and some of your suggestions run counter to that goal. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "usenet imitates usenet" --Darkhawk From tim.golden at viacom-outdoor.co.uk Wed Apr 14 12:24:57 2004 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Wed, 14 Apr 2004 17:24:57 +0100 Subject: [Win32] HEEEEEEELLLLPPPP! I need to determine the cluster siz e on WinXP/NT/2k Message-ID: >Hi! > >I need Your help. I implement a Python NT service and I need to >determine (on WinXP/2k/XP) a cluster size of the particular partition >(to find out how much space a file will occupy on that partition). To make the obvious point, this is really a Win32 question rather than (or at least as well as) a Python one. So, if you haven't already, post to some suitable MS programming groups. Having said that, I've done pretty much the same research as you seem to have done and have reached the (frankly surprising) conclusion that there's no reliable way to do this in software, even using WMI (which is often a handy standby for these sorts of things). The only article I can find that comes close to helping, suggests parsing the output of chkdsk! (Well, it seems to work, but on my Win2k machine you have to wait a while for it to get there). Can you not determine the overall size of the disk, use GetFreeDiskSpace if it's less than 2Gb and then use some more desperate technique if it's over? Good luck, and sorry I can't be any more use. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star Internet. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From No.Spam.mc at No.Spam.mclaveau.No.Spam.com Fri Apr 9 04:30:51 2004 From: No.Spam.mc at No.Spam.mclaveau.No.Spam.com (Michel Claveau/Hamster) Date: Fri, 9 Apr 2004 10:30:51 +0200 Subject: Function args References: Message-ID: Bonjour ! >>> En gros, tous les types primitifs de python sont "expans?s", autrement dit quand on les affecte ? une autre variable, c'est une copie. Tous les types complexes sont des r?f?rences. Je comprend, mais, dans mon esprit, je pr?f?re me dire qu'il y a copie de ce qui est point?. Pour une variable simple (e.g. a=2) c'est l'objet '2' qui est point?, et donc, copi?. Dans le cas d'une liste, la liste pointe sur un ensemble de pointeurs vers diff?rents objets, et donc, on copie ces pointeurs (qui sont point?s). Malheureusement, mon point de vue accroche sur les tuples (non modifiables). Je me dis alors que les tuples sont non modifiables par exception... Cela revient un peu au m?me que ce que tu as exprim?, avec une image mentale un peu diff?rente. @-salutations -- Michel Claveau From pje at telecommunity.com Wed Apr 21 18:51:15 2004 From: pje at telecommunity.com (Phillip J. Eby) Date: Wed, 21 Apr 2004 18:51:15 -0400 Subject: PEP 329 and bytecode hacking In-Reply-To: Message-ID: <5.1.1.6.0.20040421183807.020405e0@telecommunity.com> At 03:07 PM 4/21/04 -0700, Robert Brewer wrote: >Phillip J. Eby wrote (on python-dev): > > ...builtins can potentially be optimized away > > altogether (e.g. 'while True:') or converted to fast > > LOAD_CONST, or perhaps even a new CALL_BUILTIN opcode... > >Raymond's cookbook recipe inspired me to write a generic Visitor for >inspecting and rewriting bytecode. Maybe it'll help someone out there >with prototyping bytecode hacks. For more sophisticated bytecode modifications, you'll want to keep track of things like source line number, the nth instruction and its operand if any (so you can scan *backwards*), the list of locations of a given opcode, etc. This Pyrex module: http://cvs.eby-sarna.com/PEAK/src/peak/util/_Code.pyx?rev=1.2&content-type=text/vnd.viewcvs-markup provides high-speed dynamic access to bytecode metadata, and is suitable for use in runtime bytecode hacks, since it does not require Python function call overhead for each instruction. E.g. instead of defing a 'visit_OPNAME' method that then gets called numerous times, you simply do something like: from peak.util._Code import codeIndex idx = codeIndex(someCodeObject) for op in (DELETE_NAME, DELETE_GLOBAL): for i in idx.opcodeLocations(op): warn_explicit( "Deletion of global during initialization", ModuleInheritanceWarning, someCodeObject.co_filename, idx.byteLine(idx.offset(i)), ) which demos the use of the byteLine (line number for a given offset in the code) and offset (offset of the nth instruction) methods. From biner.sebastien at ouranos.ca Wed Apr 14 14:27:18 2004 From: biner.sebastien at ouranos.ca (biner) Date: 14 Apr 2004 11:27:18 -0700 Subject: saving a tkinter canvas to gif Message-ID: Hello, Is there any way to save a canvas created with tkinter to a gif (or any other graphic) without using PIL (I cannot build it on our unix machine)? For example with this simple code : >>> from Tkinter import * root=Tk() base=Canvas(root,width=50,height=50) base.create_rectangle(0,0,50,25,fill='red') base.create_rectangle(0,25,50,50,fill='blue') base.pack() root.mainloop() <<< How can I save the image with the two colored rectangle onto a graphic file? I looked on google and in the documentation but I didn't find how to do it. Thanks for any help. Sebastien. biner.sebastien at ouranos.ca From edcogburn at hotpop.com Thu Apr 1 07:32:53 2004 From: edcogburn at hotpop.com (Ed Cogburn) Date: Thu, 01 Apr 2004 07:32:53 -0500 Subject: Python compiler -> py to C, py to ELF In-Reply-To: References: Message-ID: Peter Maas wrote: > Yermat wrote: > >> If you just want an exe file, also see py2exe >> (http://starship.python.net/crew/theller/py2exe/) >> >> If what you want is something faster than python but not an ELF file >> then also look at pyrex. > > > If the goal is fast code dont' forget psyco. It is an extremely > simple to use JIT compiler and can speed up Python scripts > dramatically It would be nice if Psycho were ported to the Mac as well so that all of the major platforms that have Python could use Psycho too. Then we could make Psycho a standard part of Python with it automatically used by default, just like the JIT compiler in Java. I figure at least half of these threads we constantly see about speeding up Python code would go away with a used-by-default JIT compiler. Its a nice dream anyway. :) From a-steinhoff at web.de Thu Apr 1 15:38:43 2004 From: a-steinhoff at web.de (Armin Steinhoff) Date: 1 Apr 2004 12:38:43 -0800 Subject: Just magic ... Message-ID: Hi all, I'm just porting a piece of python code for using a different database. When I run the original version .. the type of 'set' is a tuple ... and is magically in the new version a 'class instance'. The code is the same in both versions: ins_list = [(0,1,2,3),] self.IMpos =0 for set in ins_list: setdata = (self.IMpos,) + set[1:] Any ideas why set is treated as a 'tuple' and in the other case as a 'class instance' ?? (Python 2.3.3 ) Regards Armin From tinuviel at sparcs.kaist.ac.kr Thu Apr 29 01:12:13 2004 From: tinuviel at sparcs.kaist.ac.kr (Seo Sanghyeon) Date: 29 Apr 2004 05:12:13 GMT Subject: How to add an attachment with smtplib module References: Message-ID: <40908ead$0$97288$7a214f24@news.kaist.ac.kr> Sean Berry wrote: > I have the sample script that uses the smtplib module > that is available at python.org. > > How can I use this to send an attachment? You don't. smtplib is a transport for an already formatted email message. You create a message with email package, like this: from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIMEText from email.MIMEImage import MIMEImage msg = MIMEMultipart() msg.attach(MIMEText(file("text.txt").read()) msg.attach(MIMEImage(file("image.png").read()) And then send it: import smtplib mailer = smtplib.SMTP() mailer.connect() mailer.sendmail(from_, to, msg.as_string()) mailer.close() Read email package documentation for more details. From patrick at fraley.de Mon Apr 5 08:22:00 2004 From: patrick at fraley.de (Patrick W. Fraley) Date: Mon, 05 Apr 2004 14:22:00 +0200 Subject: Python NPTL Sockets Message-ID: Hi all, I had a problem not to long ago when I switched from RedHat 9 to Fedora Core 1. The problem seemed to have to do with the new nptl and the usage of the python socket module. It seemed that socket communication got interrupted and not all data was transfered, this seemed to especially hold true the larger the amount of data became. has anybody else experienced this? How about the new Version of Fedora using Kernel 2.6, can I expect the same problem there? Thanx in advance patrick w. fraley From max at alcyone.com Mon Apr 12 02:23:36 2004 From: max at alcyone.com (Erik Max Francis) Date: Sun, 11 Apr 2004 23:23:36 -0700 Subject: Easy question on error catching References: Message-ID: <407A35E8.C669206D@alcyone.com> Sean Berry wrote: > So, how do I catch this error so that I can do something else with it? > > Is it as simple as > try: > x = int(t) > except: > something else > > or do I need to catch a ValueError specifically? What you wrote will work, but catching a ValueError (except ValueError: ...) is a better solution. Especially in dynamically typed languages like Python, it's a good idea to catch the most restrictive error you think you need, and then expand the net if it's required. This way only what needs to get caught gets caught, and the rest gets passed up the appropriate caller if necessary. Granted, this is a special case since what you're trying to do is so simple, but it's a good practice to follow in the future. -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis \__/ Don't overestimate the decency of the human race. -- H.L. Mencken From __peter__ at web.de Thu Apr 1 02:38:20 2004 From: __peter__ at web.de (Peter Otten) Date: Thu, 01 Apr 2004 09:38:20 +0200 Subject: ESR's fortune.pl redone in python - request for critique References: Message-ID: Adelein and Jeremy wrote: > (PO)> The operating system and Python may both perform some caching > as > (PO)> they see fit, but conceptually (and practically at least for > (PO)> large files - they can still be larger than your RAM after all) > (PO)> they are *not* read into memory. > > So ``creating a file object'' is not the best terminology (? - > because creating other objects puts all of their attributes in a > defined memory space) - instead, I am creating an object with access > to a specific file (and of course, with methods to work on that > file)? There are other examples for objects not loading their entire data into memory - e. g. PIL images which you can safely ask for their size without having to fear that they load each and every pixel, or database tables. The __getattr__() method and properties further blur the difference between static data and lazily loaded or calculated data. In short - I think the term object is appropriate for all of these; the internal representation is an implementation detail. Peter From me at privacy.net Wed Apr 7 19:03:16 2004 From: me at privacy.net (Heather Coppersmith) Date: 07 Apr 2004 19:03:16 -0400 Subject: Are line continuations needed? References: <407409ef.82801353@news.eircom.net> Message-ID: On Wed, 07 Apr 2004 14:05:29 GMT, wallacethinmintr at eircom.net (Russell Wallace) wrote: > Python lets you continue a single logical line across more than > one physical line, either by putting a \ at the end or letting > it happen automatically with an incomplete infix operator. > I'm wondering how often is this feature needed? Would there be > any problems if it weren't part of the language? Completely contrived: if a == b or b == c or c == d or d == e or e == f or f == g .... No, I can't imagine this sort of thing actually coming up, and yes, it's "fixable" with some extra parenthesese: if (a == b or b == c or c == d) or (d == e or e == f or f == g .... Regards, Heather -- Heather Coppersmith That's not right; that's not even wrong. -- Wolfgang Pauli From donn at u.washington.edu Thu Apr 8 20:11:41 2004 From: donn at u.washington.edu (Donn Cave) Date: Thu, 08 Apr 2004 17:11:41 -0700 Subject: List vs tuples References: <107bf8q8fhsmg5e@news.supernews.com> Message-ID: In article , Roy Smith wrote: > "John Roth" wrote: >> A list is a data structure that is intended to be used with >> homogenous members; that is, with members of the same type. > > There's really nothing about a list which makes it more suitable for > homogeneous elements than a tuple. It's true that people do tend to > think tuple when they want a mixed collection of objects, but there's > nothing in the language semantics which makes that so. > > I've written lots of code which parses data files. If you've got a > sequence of arbitrary type objects, the easiest way to process them is > often to read them sequentially and append them to a list. I don't see > anything wrong with that. For example, I once had to write some code > which parsed SQL statements that looked something like: > > insert into foo values (1, 2, 'foo', 3.14, 'bar', 4, 5, 'baz', ...); > > There were a total of about 30 items of mixed type (strings, integers, > and floats) in the ()'s. > > One of the really nice things about Python (vs. C++ or Java) is that > you're not bound by the tyranny of static typing. This is a perfect > example of how this makes life so simple. Oh no, here we go again. In the hope that we can all get along, here's how both of these arguments can be true. And I'm sure Guido would agree if he were reading this, unless he was in an unusually obtuse frame of mind. Lists are indeed homogeneous by nature, but that doesn't mean that each element has the same type as the next. It means that any slice of the list has the same "type" as any other slice. When we are dealing with a record type, an ordered collection of items where an item's meaning is determined by its position, this obviously should be a tuple. For example, the tm struct returned from time.localtime(): each member is an integer, but it's not homogeneous in the list sense - the only valid slice of a tm value is [:], any other slice is not a tm value, its type is different even if it is still a tuple. When we are dealing with a regular list, its type is the same before and after you append() a new element. That doesn't mean that the new element is the same type as its predecessor, it just means that the list isn't itself a new type now that it has that last element. Donn Cave, donn at u.washington.edu From erik at heneryd.com Tue Apr 20 18:29:25 2004 From: erik at heneryd.com (Erik Heneryd) Date: Wed, 21 Apr 2004 00:29:25 +0200 Subject: if (__name__ == '__main__'): main(sys.argv[1:]) In-Reply-To: <01c601c4271b$7f7300a0$b401010a@sparta> References: <01c601c4271b$7f7300a0$b401010a@sparta> Message-ID: <4085A445.1050303@heneryd.com> Eli Stevens (WG.c) wrote: > I have a question about proper Python style when it comes to having a main > function in a module. I'm fairly new to Python - a few months of > very-part-time tinkering (lots'o'Java at work, shrug); my apologies if this > has been hashed out before. Random Googling didn't enlighten me, so instead > I'll ask here. :) > Guido wrote an article on the subject: http://www.artima.com/weblogs/viewpost.jsp?thread=4829 Erik Heneryd From rstephens at vectron.com Sun Apr 11 10:43:06 2004 From: rstephens at vectron.com (Ron Stephens) Date: 11 Apr 2004 07:43:06 -0700 Subject: Python is the best and most popular general purpose scripting language; the universal scripting language References: Message-ID: Ok, "scripting language" is perhaps an extremely imprecise term. But, some folks will still use it in describing Python; and I'm not sure that is a bad thing. I still think that Python can be meaningfully described as being the best general purpose scripting language, sort of the Swiss Army Knife of programming languages. No matter how many programming languages you might already know, Python will give you a wide range of advantages in an awful lot of problem domains. On the other hand, if you are a business analyst or program manager and you are only going to learn one language, Python would be the best choice for you also. Ron Stephens Python Learning Foundation From rnichol_rrc at yahoo.com Sat Apr 17 21:49:01 2004 From: rnichol_rrc at yahoo.com (Reid Nichol) Date: Sat, 17 Apr 2004 20:49:01 -0500 Subject: os.system help Message-ID: <78lgc.3445$AL1.7744@news1.mts.net> Hello, I have made a program that works wonderfully on OpenBSD but it uses os.system to get ghostscript to convert ps to jpeg. But, I wish this program to run on Windows as well. Is there any way I can snag where the gs executable is on Windows? What it is named? And so forth. From gustabares at verizon.net Fri Apr 9 12:27:07 2004 From: gustabares at verizon.net (Gus Tabares) Date: 9 Apr 2004 09:27:07 -0700 Subject: Debugging extensions under VS .NET 2003 Message-ID: This purpose of this post is to give a mini how-to on debugging Python extensions written in C under Visual Studio .NET 2003. Please feel free to correct any mistakes I may have made. Please realize that this is not a comprehensive guide to debugging Python extensions; this is only knowledge from what I have experienced. I hope that these instructions will be handy to anyone who is having trouble debugging Python extensions in a .NET 2003 environment. If you want to be able to debug your extensions, you will to build a debug version of the Python interpreter. The Python sources are freely available on python.org. You shouldn't need to build the entire Python environment, which includes downloading openssl (and other) sources. Your main concern is with the python project file. After you compile the python project file, you should have the following sets of files: python_d.exe (the debug interpreter), python23_d.dll, python23_d.lib. You will need the .lib to link against your debug extension. Compile and link a debug version of your extension, making sure to link against python23_d.lib. Also make sure that your extension is named in the following format: pydname_d.pyd. The _d is necessary when importing from the debug interpreter. Set your breakpoints in your extension code from within .NET. Make sure the debug command is the full path to debug version of the Python interpreter. It should bring up the debug interpreter when you start debugging. >From there you should be able to import your debug extension and step-through your code from within .NET. For more information and some examples, check out the readme file located in the PC\example_nt directory of the Python sources. Note that those instructions were written for Visual Studio 6 and not specifically for .NET 2003. Good luck, Gus Tabares From haim at babysnakes.org Tue Apr 13 12:33:47 2004 From: haim at babysnakes.org (Haim Ashkenazi) Date: Tue, 13 Apr 2004 19:33:47 +0300 Subject: mcmillan installer References: Message-ID: Gianluca Trombetta wrote: > thank you Larry, > > but I need to compile for linux platform and py2exe only work on windows > :-( you can use freeze. search for freeze.py in your python installation. Bye -- Haim From vincent at visualtrans.de Fri Apr 16 05:09:02 2004 From: vincent at visualtrans.de (vincent wehren) Date: Fri, 16 Apr 2004 11:09:02 +0200 Subject: Breakpoint in IDLE's debugger In-Reply-To: References: Message-ID: Batista, Facundo wrote: > I want to start my program under the IDLE's debugger, click "Go", and let > the program run. > > But also want that if the program goes through a specific line of code, to > stop and let me advance with "Step" or "Over" buttons. IDLE lets you set/clear breakpoints via the right-mouse-button context menu when you're in the source file. If you press "GO" the debugger will execute the code until a breakpoint is reached. HTH, Vincent Wehren From mcfletch at rogers.com Fri Apr 23 04:57:53 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Fri, 23 Apr 2004 04:57:53 -0400 Subject: Why we will use obj$func() often In-Reply-To: References: <84Uhc.22278$dZ1.5087@fed1read04> <8AWhc.23114$dZ1.11070@fed1read04> Message-ID: <4088DA91.5010402@rogers.com> Mark Hahn wrote: >Mike C. Fletcher wrote: > > ... >Internally in the interpreter I have the full Python super function almost >exactly. It's no coincidence. You need that to make inheritance work. I >can bring it out for the Prothon user, but I originally designed prothon >with keywords and symbols, not functions, something I'm taking a lot of heat >for now. > > Heat is a good way to bake ideas and remove impurities. >You've stretched my "one more thing to pitch" statement to the extreme >statement of "switch to this because of this one thing". Of course one >isn't going to care about one thing. > > Well, as I said, if you're going to have fun trolling I get to have fun trolling back ;) . Basically, I'm saying this particular detail is not an argument worth making on its own. The argument is going to be "it's a clean, simple, balanced and elegant syntax" and this level of detail is just part of that picture. Artwork is judged as a whole, and one might critique a particular facet if it's horrible, but perfection is assumed otherwise. >You may very well be right. > Never happened before, why assume it'd start now :) . >My biggest problem right now is stupid aesthetics. I have to decide where >to place Prothon on the continuum between lisp and perl. > *poke* surely you see the humour that a Python user will derive from that statement :) ;) . >When I crossed the >line and added $ for self people screamed bloody murder that it looked like >Perl. Before when I had a period for self they thought it looked great. I >can't believe how much they care about something so silly. > > Comparatively, instance-attribute access is used three or four times a minute when coding, while super is used once or twice a month for non-framework-programmers, so yes, I can see someone screaming bloody murder if they suddenly are looking at a screen full of $This and $that variables. $ is basically a character as far as glyphs go, it's a full-height glyph with ascenders and descenders, is very similar to a capital S, and generally makes reading code much harder as it obscures word-shape; .this or even self.this is much easier to read because you can pick out the words using your learned vocabulary of word-shapes. Readability counts BTW, I'm a professional designer, so "stupid aesthetics" are what I care about whenever I get a chance ;) . >Anyway, thanks very much for your input. I'm sorry if you wore out your >keyboard. Luckily the prices have really come down :) > > Unfortunately, MS doesn't make the classic Natural Keyboard any more (they just make that darned Natural Elite and the egads-it's-covered-in-pointless-extra-buttons USB Natural), so I have to savour every keystroke ;) . That's why I never post to newsgroups, Mike _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From pedro_rodriguez at club-internet.fr Fri Apr 23 05:54:24 2004 From: pedro_rodriguez at club-internet.fr (Pedro Rodriguez) Date: Fri, 23 Apr 2004 11:54:24 +0200 Subject: python extension, -pthreads and speed References: <4fd1aa5e.0404222336.2a1347a8@posting.google.com> Message-ID: On Fri, 23 Apr 2004 09:36:08 +0200, Joseph Heled wrote: > Hi, > > My python module is built using the recommended distutils.core, which > uses the -pthread flag. To my amazement this slows down the (-O3) code > by a factor of two (!2) > > My gcc documentation says pthread is a PowerPC flag, but I guess this is > wrong. > > Would my code fail if I drop this flag (Assuming I don't use threads at > all)? > > Why would there be such a speed penalty? > > Anyone can shed some light on that? > > Thanks, Joseph > >>python -V > Python 2.3 > >>gcc -v > Reading specs from /usr/local/lib/gcc-lib/i686-pc-linux-gnu/3.3/specs > Configured with: ../gcc-3.3/configure : (reconfigured) > ../gcc-3.3/configure --enable-languages=c,c++ Thread model: posix gcc > version 3.3 My understanding of your question is : my C extension module works slower when used through Python. If my guess is right, this isa possible hint on the subject. If your extension use IOs (fgets, sprintf...) or others standard library calls, they may be affected by the fact that Python is build with multithreading enabled, on so all those API start using mutexes to be thread safe, thus the extract cost. This simple C example exhibit the problem : #include int main(int argc, char *argv[]) { int i; FILE *in; in = fopen("/dev/null", "r"); for (i=0; i< 10000000; i++) { fgetc(in); } close(in); } $ gcc z.c -O3 -o z $ time ./z real 0m12.355s user 0m5.810s sys 0m6.550s $ gcc z.c -O3 -o z -pthread $ time ./z real 0m16.055s user 0m10.610s sys 0m5.440s Cheers, Pedro From No.Spam.mc at No.Spam.mclaveau.No.Spam.com Mon Apr 26 15:27:40 2004 From: No.Spam.mc at No.Spam.mclaveau.No.Spam.com (Michel Claveau/Hamster) Date: Mon, 26 Apr 2004 21:27:40 +0200 Subject: interfacing to a remote excel app References: <20040426150428.69010a3c@pistache.sara.nl> Message-ID: Bonjour ! Pour un probl?me similaire, j'ai fais : - sur la machine Windows/Excel : un script Python, petit serveur TCP, qui pilote Excel par COM - sur la machine distante un autre script Python envoie ses instructions "Excel", via TCP, et re?oit la r?ponse en retour. R?sultat : ?a marche bien, m?me ? travers Internet. In english (try) : Hi ! For a similar problem, I have make: - on the Windows/Excel machine: a script Python, little server TCP, which controls Excel by COM - on the distant machine another Python script sends its instructions "Excel", via TCP, and receive the response in return. Result: it goes well, even through Internet. @-salutations -- Michel Claveau m?l : http://cerbermail.com/?6J1TthIa8B site : http://mclaveau.com From nmkolev at uni-bonn.de Thu Apr 22 01:20:42 2004 From: nmkolev at uni-bonn.de (Nickolay Kolev) Date: Thu, 22 Apr 2004 07:20:42 +0200 Subject: Optimizing a text statistics function In-Reply-To: <4086efbc$1@nntp0.pdx.net> References: <4086efbc$1@nntp0.pdx.net> Message-ID: Scott David Daniels wrote: > Better not to do several huge string allocs above (I suspect). > This method lets you to work on files too large to read into memory: ... code ... Now this is something I was thinking about when I started considering options for this task. From my understanding, for line in file('...'): is only useful if I want to make checks on the lines and then do something with them: for line in file('...'): if line.startswith('XXX'): myDesiredLines.append(line) This avoids creating a huge list of all lines and then filtering it to another list with only the desired ones. In my case I want to get all the lines regardless of any condition. I also do not even need them as a list of lines, a single huge string is completely sufficient. It will be split on whitespace later anyway. Both methods should produce the same amount of memory usage as all words are stored in a list. Reading a file line by line should be slower, as Python would have to check where the newline characters are. Please comment and correct, I am making assumptions here. Clarification from someone who know how these things are internally implemented would be nice. Nicky From mcfletch at rogers.com Sat Apr 24 19:24:27 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Sat, 24 Apr 2004 19:24:27 -0400 Subject: Why we will use obj$func() often In-Reply-To: <408AECC7.7020601@prescod.net> References: <84Uhc.22278$dZ1.5087@fed1read04> <8AWhc.23114$dZ1.11070@fed1read04> <408AECC7.7020601@prescod.net> Message-ID: <408AF72B.5090404@rogers.com> Paul Prescod wrote: ... > Yes, people are irrational. But if you care about language popularity > you have to take that into account. Else you end up with a language > that never goes mainstream like Lisp. Oooh, lovely double entendre there... ;) You get a smiley for that one :) . Mike _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From noemail at noemail4u.com Thu Apr 15 08:00:19 2004 From: noemail at noemail4u.com (Dang Griffith) Date: Thu, 15 Apr 2004 12:00:19 GMT Subject: Getters and setters in python, common practise References: <407e402c$1@newsflash.abo.fi> <407e6cf9@newsflash.abo.fi> Message-ID: <08acb243aa2046aa5ba35b21e1d71fc6@news.teranews.com> On Thu, 15 Apr 2004 14:07:25 +0300, Petter Holmstr?m wrote: >Peter Hansen wrote: >>> Having a Delphi/Object Pascal-background, I'm very used to using >>> getters and setters when designing my classes. What is the common >>> practise in the Python world? Should one use them or not? >> >> Max described the common practice (don't use them until you actually >> need them) but forgot to mention that in recent versions of Python >> you can use "properties", in pretty much the same manner as Delphi >> uses them. > >I have not found any documentation on this topic. Could you please point >me to some? Food for a day: http://www.python.org/2.2/descrintro.html#property Teach you to fish: http://www.python.org/search/ --dang From mark at prothon.org Wed Apr 21 04:08:47 2004 From: mark at prothon.org (Mark Hahn) Date: Wed, 21 Apr 2004 01:08:47 -0700 Subject: Dollar sign ($) on foriegn keyboards? (prothon) References: <408629CF.30004@cosc.canterbury.ac.nz> Message-ID: "greg" wrote ... > Indeed. It sounds more like an alien race that's > escaped from an upcoming StarCraft expansion pack... Yes, but a very advanced alien race :) From spam at fisher.forestry.uga.edu Mon Apr 5 22:41:52 2004 From: spam at fisher.forestry.uga.edu (Chris Fonnesbeck) Date: 5 Apr 2004 19:41:52 -0700 Subject: Compact Python library for math statistics References: Message-ID: Gerrit wrote in message news:... > wrote: > > I'm looking for a Python library for math statistics. This must be a cl > ear set of general statistics functions like 'average', 'variance', 'cova > riance' etc. > > The next version of Python will have a 'statistics' module. It is > probably usable in Python 2.3 as well. You can find it in CVS: > > http://cvs.sourceforge.net/viewcvs.py/*checkout*/python/python/nondist/sa > ndbox/statistics/statistics.py > > I'm not sure whether it's usable in current CVS, though. You may have to > tweak it a little. > > Gerrit. I'm hoping there will be more functions added to this module (e.g. median, quantiles, skewness, kurtosis). It wouldnt take much to include at least the basic summary stats. I would be more than happy to contribute. cjf From garryknight at gmx.net Wed Apr 14 16:31:19 2004 From: garryknight at gmx.net (Garry Knight) Date: Wed, 14 Apr 2004 21:31:19 +0100 Subject: Looking for Python Definition References: Message-ID: <1081974678.10988.1@ersa.uk.clara.net> In message , Dave wrote: > Python22 is installed on my WINXP Home PC. > I have no idea what is does, or why it is installed. You posted this to comp.lang.python. The 'comp.lang' bit stands for 'computer language'. -- Garry Knight garryknight at gmx.net ICQ 126351135 Linux registered user 182025 From kaz30 at adelphia.net Thu Apr 29 18:28:51 2004 From: kaz30 at adelphia.net (ron) Date: Thu, 29 Apr 2004 18:28:51 -0400 Subject: WARNING! Virus or unsafe content was found in message from Message-ID: <000001c42e3b$fb31a760$6402a8c0@compaq7598> How do I remove details.scr from my computer ? -------------- next part -------------- An HTML attachment was scrubbed... URL: From semarketing-request at go.listdeliver.com Sun Apr 18 16:56:09 2004 From: semarketing-request at go.listdeliver.com (semarketing-request at go.listdeliver.com) Date: Sun, 18 Apr 2004 16:56:09 -0400 Subject: List Manager response Message-ID: <20040418205609408.AAA228@go.listdeliver.com> >>>> This is a multi-part message in MIME format. **** Command 'this' not recognized. **** No valid commands found. **** Commands must be in message BODY, not in HEADER. **** Help for semarketing-request at go.listdeliver.com: Introduction to the List Manager -------------------------------- This is the Mailing List Manager for Post.Office version v3.5.3. The interface is similar to Brent Chapman's "Majordomo". How to Access the List Manager ------------------------------ You can interact with the List Manager by sending commands in the body of an E-mail message addressed to "semarketing-request at go.listdeliver.com". (Important Note: Commands in the "Subject:" line are NOT processed.) Available List Manager Commands ------------------------------- The Post.Office Mailing List Manager understands the following commands: (Note: In the descriptions below items contained in []'s are optional. When providing the item, do not include the []'s around it.) subscribe [
] Subscribe yourself (or
if specified) to the named . unsubscribe [
] Unsubscribe yourself (or
if specified) from the named . which Find out which lists you are on. who Find out who is on the named . info Retrieve the general introductory information for the named . lists Show the lists served by this List Manager server. help Retrieve this message. end Stop processing commands (useful if your mailer adds a signature). From plastic"no-spam-pls" at xsintrk.net Fri Apr 16 17:06:12 2004 From: plastic"no-spam-pls" at xsintrk.net (jeff) Date: Fri, 16 Apr 2004 21:06:12 GMT Subject: newbie question References: Message-ID: "Richard Brodie" wrote in news:c5occn$ijq at newton.cc.rl.ac.uk: > You are missing Krzysztof's point. Even if the string 'kill' is sent, > TCP does not guarantee that is what you will receive. It is a pure > stream system and has no concept of records or lines; that isn't likely > the problem here but sooner or later, you *will* get burnt if you start > thinking that if 4 characters are sent, then 4 will be received. how can i be sure i have received the entire string? From jamesl at appliedminds.com Thu Apr 8 20:02:23 2004 From: jamesl at appliedminds.com (James Lamanna) Date: Thu, 08 Apr 2004 17:02:23 -0700 Subject: Bug in struct.calcsize() Message-ID: <4075E80F.5010602@appliedminds.com> Nevermind. I see that I need to make sure I turn alignment off . -- James Lamanna From try_vanevery_at_mycompanyname at yahoo.com Mon Apr 26 11:53:59 2004 From: try_vanevery_at_mycompanyname at yahoo.com (Brandon J. Van Every) Date: Mon, 26 Apr 2004 08:53:59 -0700 Subject: Maya API with Python? References: Message-ID: Harald Massa wrote: >> Anybody tried that? Progress or horror stories to tell? > > "Industrial Light & Magic Runs on Python" > http://www.pythonology.com/success&story=ilm > > > I am sure, they also use maya. Hmm yes but that doesn't provide specific useful information. Also, just because they use Python for process control of rendering farms doesn't mean they use it for everything they do. Now, if only ILM had a public forum, or if some group had enough ILM people in it.... -- Cheers, www.indiegamedesign.com Brandon Van Every Seattle, WA 20% of the world is real. 80% is gobbledygook we make up inside our own heads. From max at alcyone.com Tue Apr 6 00:14:16 2004 From: max at alcyone.com (Erik Max Francis) Date: Mon, 05 Apr 2004 21:14:16 -0700 Subject: int('2.1') does not work while int(float('2.1')) does References: <40722555.66C70D40@alcyone.com> Message-ID: <40722E98.253B5FF2@alcyone.com> Joe Mason wrote: > Why can it make this guess for "int(2.1)", then? It's got a rule for > converting floats to ints - why not use it here? Because int(aFloat) means round toward zero. int(aString) means make an int out of this string. -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis \__/ Convictions are more dangerous enemies of truth than lies. -- Friedrich Nietzsche From hungjunglu at yahoo.com Tue Apr 13 00:25:47 2004 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 12 Apr 2004 21:25:47 -0700 Subject: module not callable - why not? References: <107dras2heahcb6@news.supernews.com> Message-ID: <8ef9bea6.0404122025.36efc84e@posting.google.com> Jack Diederich wrote in message news:... > > - Don't name the module and a class in it the same thing > import Queue # Queue is a module > from Queue import Queue # Queue is a class > ... To be frank, this problem is just one of the symptoms of a sickened programming language. Python runs into this problem (like SimpleXMLRPCServer.SimpleXMLRPCServer) because: (a) By historical accident, Python modules differ significantly from regular classes. (Modules are like singleton without constructor for multiple instantiation, and without property getters/setters.) (b) Python uses class-based OOP, instead of prototype-based OOP. Class-based OOP is a historical mistake. If time could be turned back, I think people would rather start with prototype-based OOP, instead. Because of this mistake of using class-based OOP, you have incomplete objects like modules and classes: you usually can't use them directly, at least not as comfortably/powerfully. Therefore, you find yourself dealing with names like SimpleXMLPRCServer.SimpleXMLRPCServer, without being able to collapse instance/class/module into one single object and one single name. regards, Hung Jung From skip at pobox.com Sun Apr 18 10:20:16 2004 From: skip at pobox.com (Skip Montanaro) Date: Sun, 18 Apr 2004 09:20:16 -0500 Subject: Proposed PEP: Treating Builtins as Constants in the Standard Library In-Reply-To: <5d83790c.0404171557.3db69f48@posting.google.com> References: <5d83790c.0404171557.3db69f48@posting.google.com> Message-ID: <16514.36512.538734.642971@montanaro.dyndns.org> rh> Q. Why not make this a public module so that users can optimize rh> builtins or builtins and globals in their own code? rh> A. The ASPN recipe [2]_ is provided for this purpose. It takes a rh> modicum of skill to use correctly and not inadvertently tranform rh> a non-constant. I thought one of the basic tenets of Python was "we're all adults here". Programmers have unfettered access to the new module with which they can wreak havoc. I don't see this proposal as somehow any more dangerous. Skip From kkennedy65 at yahoo.com Mon Apr 19 12:31:28 2004 From: kkennedy65 at yahoo.com (kk) Date: 19 Apr 2004 09:31:28 -0700 Subject: Does Python compete with Java? References: <8b336527.0404051337.51bb4a1b@posting.google.com> <407deb56$1@news.unimelb.edu.au> <8b336527.0404151019.14b93502@posting.google.com> <5KydnYqkwP1ES-PdRVn-vA@powergate.ca> Message-ID: <8b336527.0404190831.65f7f7e2@posting.google.com> I was responding to your point made earlier. I was the one that started the thread, look again. Peter Hansen wrote in message news:<5KydnYqkwP1ES-PdRVn-vA at powergate.ca>... > kk wrote: > > > That is exactly my point! > > Uh, sorry, but what point? The email address and initials you > are using here (kkennedy65 at yahoo.com and kk) have not posted > before in this thread, as far as I can see. So who are you? :-) > > -Peter From http Fri Apr 16 16:10:21 2004 From: http (Paul Rubin) Date: 16 Apr 2004 13:10:21 -0700 Subject: Difficulty Finding Python Developers References: <65cbc3dd.0404140641.3501fde8@posting.google.com> <5d83790c.0404150701.605782a7@posting.google.com> <7xpta8hqe7.fsf@ruckus.brouhaha.com> <7xsmf4kbac.fsf@ruckus.brouhaha.com> <7x7jwg7ipn.fsf@ruckus.brouhaha.com> <7xwu4gzff2.fsf@ruckus.brouhaha.com> Message-ID: <7xwu4fu1jm.fsf@ruckus.brouhaha.com> Peter Hansen writes: > We've worked hard to convince our company to migrate our core > applications to Python, and now we're looking for a Python developer > in Atlanta to handle a short-term (approx. 3 month) project. > > That's not a good way to describe either of your scenarios, > I believe. I think it's more of an initial foray without the > company's future on the line type of thing... That sounds like a sales presentation where the 3-month project is the demo, and normally in those situations, it's important that the demo not hit any snags. So all the same issues apply. The way I had read it, though, management had already been persuaded to commit to Python, and now they had some project that they had to get finished. From peter at engcorp.com Fri Apr 2 09:30:31 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 02 Apr 2004 09:30:31 -0500 Subject: Making the Zen of Python more useful In-Reply-To: <106qp0uivlefo40@corp.supernews.com> References: <106qp0uivlefo40@corp.supernews.com> Message-ID: Andrew Henshaw wrote: > Yesterday, I was writing some test code for a module and I wanted some > line-oriented text to use as a data source. I thought about using a > docstring from one of the standard modules; but, it occurred to me that the > Zen of Python text from the 'this' module would be *much* better, as it is > more readable and would be a nice thing for our students to see. > > Unfortunately, the actual text is difficult to use: > o the text is ROT-13 encoded and the module's translation routine is > inline > o the text is printed to stdout on import. I understand why Tim did this, > but it did interfere with my purpose. > > So, in order to use the module for my test code, I had to implement a short > ROT-13 translator, import the sys module, redirect stdout to a simple > object that provided a null write method, import this, restore stdout, and > then rot13(this.s). I'm not sure why you had to do quite all that. The following is sufficient, and you don't need a custom ROT-13 thingie: >>> import StringIO, sys >>> s = StringIO.StringIO() >>> sys.stdout = s >>> import this >>> sys.stdout = sys.__stdout__ >>> s.getvalue() "The Zen of Python, by Tim Peters\n\nBeautiful is ... -Peter From jjl at pobox.com Sat Apr 24 15:28:16 2004 From: jjl at pobox.com (John J. Lee) Date: 24 Apr 2004 20:28:16 +0100 Subject: Generic constructors and duplication of internal Python logic References: <87ekqq41ya.fsf@pobox.com> <87oepnzlbp.fsf@pobox.com> <87k707elth.fsf@pobox.com> Message-ID: <87smetxjjj.fsf@pobox.com> Peter Otten <__peter__ at web.de> writes: > Peter Otten wrote: > > > But will I stop trying to come up with something better? no way. Here's my > > next try, and I'm likely to present something completely different again > > if you don't like it - not sure if that's a promise or a threat :-) > > A threat. > > def setLocals(d, selfName="self"): > self = d.pop(selfName) > for n, v in d.iteritems(): > setattr(self, n, v) > > class Demo(object): > def __init__(self, foo, bar, baz=2, bang=3): > setLocals(locals()) Perfect! About a hundred times better than my solution. Maybe this should be a Python Cookbook entry? John From __peter__ at web.de Tue Apr 20 04:26:40 2004 From: __peter__ at web.de (Peter Otten) Date: Tue, 20 Apr 2004 10:26:40 +0200 Subject: outline-style sorting algorithm References: <71650A6F73F1D411BE8000805F65E3CB3B3A4D@SRV-03> <1088ehljpqq4195@corp.supernews.com> Message-ID: Michael Geary wrote: > Interestingly enough, in Windows XP, Windows Explorer lists these files in > numerical order: > > file1 > file2 > ... > file9 > file10 > file11 Seems they special-cased this. Can they deal with fi1le fi2le fi10le and 1file 2file 10file too? > It would be nice if more OS shells sorted filenames like this. D'accord. Peter From simonb at NOTTHISBIT.webone.com.au Wed Apr 14 02:49:16 2004 From: simonb at NOTTHISBIT.webone.com.au (Simon Burton) Date: Wed, 14 Apr 2004 07:49:16 +0100 Subject: Import / export values to/from C program References: Message-ID: On Tue, 13 Apr 2004 13:47:51 -0700, Steffen Jahn wrote: > Hi, > > I stumbled across Python when trying to invoke *scripts* from C programs. > The idea is to set up some variables in the C program, export them, run a > Python script, and, after completion, import some variables back into the > C program. This way, I can keep the C program very flexible for certain > types of changes. Check out Pyrex. It can probably do what you want (whatever that is - i'm not quite sure.) Simon. From arker at newton.astro.ca Wed Apr 28 14:16:16 2004 From: arker at newton.astro.ca (Dennis Craven) Date: Wed, 28 Apr 2004 18:16:16 GMT Subject: Polling eth0? Message-ID: <3cdce0bb529198fa30efae192faeea7a@news.teranews.com> Hello, I intend on writing a small application that monitors incoming/outgoing traffic on eth0, and recording the bandwidth usage with monthly totals etc.. Where would be a good place to start in regards to connecting to eth0 and reading such data? I am somewhat familiar with Python, and its simple constructs, but I'm not so familiar with this network aspect. Any particular modules/examples/documentation/tutorials that I should start out reading? Thanks, ~djc From newsuser at itgoesclick.com Wed Apr 21 16:14:12 2004 From: newsuser at itgoesclick.com (Noah from IT Goes Click) Date: Wed, 21 Apr 2004 20:14:12 GMT Subject: Active State Komodo might do it Message-ID: I haven't actually checked if it does it for PHP but it says it has autocomplete, weather it explores your classes or not I don't know. http://www.activestate.com/Products/Komodo/index.plex From mark at prothon.org Tue Apr 27 03:17:53 2004 From: mark at prothon.org (Mark Hahn) Date: Tue, 27 Apr 2004 00:17:53 -0700 Subject: What is good about Prothon? References: Message-ID: "Mike C. Fletcher" wrote ... > Maybe I should add designing languages to my list of projects starved > for time :) . We'd love to have you... From kylotan at hotmail.com Mon Apr 12 21:27:58 2004 From: kylotan at hotmail.com (Kylotan) Date: 12 Apr 2004 18:27:58 -0700 Subject: Simple discussion of python cgi approaches? Message-ID: <153fa67.0404121727.45b23c30@posting.google.com> [Apologies if anyone sees this twice - at first I attempted to post it via my ISP's news server, but my ISP is notorious for poor news handling and I don't see it on Google Groups as having got through yet.] I've been writing a CGI app with Python 2.3 and Apache. It's ok, but a bit slow, and I assume a significant part of this is the process start-up time, among other things. So I'm interested in alternatives or optimisations. The problem is, there doesn't seem to be the kind of information out there that I want. There seem to be plenty of places that throw a list of URLs at you (eg. http://www.python.org/cgi-bin/moinmoin/WebProgramming, http://phaseit.net/claird/comp.lang.python/web_python.html), and a few sites that will give the absolute basics of CGI programming itself (which I don't need). I'm particularly confused by a few people advocating things like Xitami + LRWP for being very simple, yet it can't possibly be simpler than just dropping a cgi script into a directory, as I do with Apache, and the docs on LRWP (http://www.imatix.com/html/xitami/index12.htm#TOC114) make it look like I'd have to do significant rewriting of the scripts. It describes itself as being like FastCGI which, if true, doesn't exactly endear FastCGI to me either. All I want is a short description on the technologies that very closely resemble standard CGI, what they have to offer me, and what sort of alterations I would have to make to my installation or code in order to use these. Does such a comparison exist already? If not, is anybody able to comment on their own experiences with Python CGI apps? -- Ben Sizer From jcarlson at uci.edu Mon Apr 12 00:50:57 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Sun, 11 Apr 2004 21:50:57 -0700 Subject: maximum length of a list & tuple In-Reply-To: References: Message-ID: > Actually, unless I'm mistaken that stores only one integer, and a whole > lot of references to it... which are just pointers (4 bytes each). > > The technique is probably flawed in other ways, however, as it > is likely subject to memory fragmentation and other problems. You can't just store the integer. How would you differentiate between an integer in a list and a pointer? Answer: you must use PyIntObjects. Use the source. According to intobject.c, intobject.h and object.h, the structure of every intobject (after the macros have been expanded) is as follows: typedef struct { int ob_refcnt; _typeobject *ob_type; long ob_ival; } PyIntObject; The size of each of those on a 32 bit machine is 4 bytes, plus the pointer from the list (another 4 bytes), which leaves us with a total of 16 bytes per integer object in the list. Checking the memory usage of Python before and after the creation of 1 million integer list, I get a /very/ consistant ~16 bytes per. That would be 12 bytes for the object, and 4 bytes for each pointer in the list. There is some additional overhead that you'd notice in intobject.c and/or intobject.h, but yeah. Generally 16 bytes per integer. As for memory fragmentation, considering how memory paging and segmentation works, that's all underlying stuff that the OS deals with. I could go on as to why it doesn't matter in this case (considering the large mallocs necessary for the creation of large lists), but I'll leave that as an exercise to the reader. Again, from the source, 12 bytes for the object, 4 bytes for the pointer in the list, total of 16 bytes per intobject in a list. - Josiah From anton at vredegoor.doge.nl Thu Apr 8 14:29:26 2004 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Thu, 08 Apr 2004 20:29:26 +0200 Subject: Working with bytes. References: <406EE606.4000604@yahoo.com> <406f33b6$0$30963$3a628fcd@reader1.nntp.hccnet.nl> <4071273d$0$132$3a628fcd@reader1.nntp.hccnet.nl> <4071539F.718DBD1A@pobox.com> Message-ID: <40759a1c$0$140$3a628fcd@reader1.nntp.hccnet.nl> Jason Harper wrote: >Anton Vredegoor wrote: >> I wonder whether it would be possible to use more than six bits per >> byte but less than seven? There seem to be some character codes left >> and these could be used too? > >Look up Base85 coding (a standard part of PostScript) for an example of >how this can be done - 4 bytes encoded per 5 characters of printable ASCII. Thanks to you and Piet for mentioning this. I found some other interesting application of Base85 encoding. It's used for a scheme to encode ipv6 addresses (which use 128 bits). Since a md5 digest is 16 bytes (== 128 bits) there's a possibility to use this scheme. See http://www.faqs.org/rfcs/rfc1924.html for the details. Anton from string import digits, ascii_letters _rfc1924_chars = digits+ascii_letters+'!#$%&()*+-;<=>?@^_`{|}~' _rfc1924_table = dict([(c,i) for i,c in enumerate(_rfc1924_chars)]) _rfc1924_bases = [85L**i for i in range(20)] def bytes_to_rfc1924(sixteen): res = [] i = 0L for byte in sixteen: i <<= 8 i |= ord(byte) for j in range(20): i,k = divmod(i,85) res.append(_rfc1924_chars[k]) return "".join(res) def rfc1924_to_bytes(twenty): res = [] i = 0L for b,byte in zip(_rfc1924_bases,twenty): i += b*_rfc1924_table[byte] for j in range(16): k = i & 255 res.append(chr(k)) i >>= 8 res.reverse() return "".join(res) def test(): import md5 #md5.digest returns 16 bytes == 128 bits, an ipv6 address #also uses 128 bits (I don't know which format so I'm using md5 #as a dummy placeholder to get 16 bytes of 'random' data) bytes = md5.new('9034572345asdf').digest() r = bytes_to_rfc1924(bytes) print r check = rfc1924_to_bytes(r) assert bytes == check if __name__=='__main__': test() output: k#llNFNo4sYFxKn*J References: <698f09f8.0404240819.1d3c6001@posting.google.com> Message-ID: Jeremy Fincher wrote: > It's important to note that many of these features turn the > expressions that represent their use into decidedly non-regular > expressions, regardless of what Pythoneers and Perlers call them :) Indeed, which is one reason Plex doesn't do them. Plex converts all the REs into a big DFA, which means that Plex REs must truly be regular. This is the price you pay for scanning time independent of the complexity of the REs. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From jepler at unpythonic.net Fri Apr 23 07:37:19 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Fri, 23 Apr 2004 06:37:19 -0500 Subject: Help: Fatal Python error: deletion of interned string failed In-Reply-To: References: Message-ID: <20040423113719.GB2150@unpythonic.net> This indicates some kind of refcounting problem with interned strings. (string_dealloc was called for a mortal interned string, but removal of that string from the dict of interned strings failed for some reason) If you can find a case where this happens without using third-party modules like db2, you should file it as a bug on http://sourceforge.net/projects/python I have never heard of this error before, so it must be uncommon/hard to trigger or due to a module that few in the community use. Interned strings were made mortal in Python 2.3, so this could be a 2.2 vs 2.3 incompatibility in some third-party module. Jeff From claird at lairds.com Sat Apr 3 10:16:49 2004 From: claird at lairds.com (Cameron Laird) Date: Sat, 03 Apr 2004 15:16:49 -0000 Subject: Principles of documentation (was: Python Documentation Blows!) References: <40699A31.8000708@yahoo.com> <406A5892.7030809@mlug.missouri.edu> Message-ID: <106tlb1co98gb0d@corp.supernews.com> In article , Josiah Carlson wrote: . . . >better. Maybe it was that year of only really knowing C and C++ that >makes the difference, but I've never had issue with the wxWidgets >documentation. > >While I prefer Python's name with description later, having the type of >input and output from the function call given in the function definition >is convenient. Programming with a language that is static typed may be >a pain in the ass, but it is damn convenient when you are looking at >documentation. Even though wxWidgets class definitions can have huge >initialization argument lists, generally you can be sure of what you are >supposed to pass into something, and what you can expect in return. > > > - Josiah We're different--always interesting. As a heavy consumer and producer of documentation, "having the type .. in the function definition is convenient" intrigues me. Clouding my thoughts a bit is C's wimpy type system ('love the language, 'recognize its limits). Your proposition sounds to me much like what we used to believe about compile-time syntax checking, versus more robust and application-specific unit tests. My preliminary reaction, therefore: yes, indeed, type declar- ations are important, Python documenters should be particularly careful always to specify them explicitly, and, if anything, Python has the chance to improve on the standards C and C++ set, as its typing is stronger. -- Cameron Laird Business: http://www.Phaseit.net From flupke at nonexistingdomain.com Fri Apr 23 22:42:10 2004 From: flupke at nonexistingdomain.com (flupke) Date: Sat, 24 Apr 2004 02:42:10 GMT Subject: [OT] Plone Message-ID: <6ukic.84257$cd.5573763@phobos.telenet-ops.be> Hi, i've read some user comments on Zope. As was to be expected some say it's cool, others says it's difficult and not easy to debug. I would use Plone as CMS for our intranet which will also be a platform for our tools. Does plone make it even more difficult to get going or does it hide some of the difficulties of Zope? I'm kind of in a dillema here, the more i read about Python, the more i like it. As it seems mod_python/FCGI is a good combo to bring Python power to the web but since they want a CMS and i don't have time to write one from the ground up, i'm thinking of using Plone. I have my doubts about Zope especially from the viewpoint of administration. I will have to maitain the systems where it runs on also. Any comments? flupke From newsgroups at jhrothjr.com Wed Apr 7 18:25:03 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Wed, 7 Apr 2004 18:25:03 -0400 Subject: Are line continuations needed? References: <1078dq6i93pc12d@news.supernews.com> <1078skqn9hgdd19@corp.supernews.com> Message-ID: <1079015hfg56i28@news.supernews.com> "Michael Geary" wrote in message news:1078skqn9hgdd19 at corp.supernews.com... > John Roth wrote: > > [Backslash line continuations are], I believe, planned for > > removal in 3.0. Remember that 3.0 will break everything > > anyway: it's the release for incompatible changes. > > If this is true, it will put Python at a disadvantage compared to Perl with > regard to multiline strings. I thought David Bolen's example was pretty > compelling. > > Without the backslash continuation, you're forced to write multiline strings > with the first line indented differently from the rest of the lines: > > mystring = """first line > second line > third line""" > > Yuck. > > Backslash continuation fixes this, as David showed: > > mystring = """\ > first line > second line > third line""" > > Maybe there will be some other way to do clean multiline strings in Python > 3.0? Since you aparently used tab indentation, your examples came through with no indentation, so I can't tell what you're talking about. I've seen a number of ways of handling pretty-printing multi line strings while still making them come out the way you want. For example, as someone else mentioned, you could do this: mystring = ("first line" "second line" "Third line") The parenthesis handle the continuations, and automatic concatination of adjacent strings take care of the rest. Or if you want to use a multi-line string, then you could split it on whitespace and then join it again with a single space separator. There are a number of other things you can do, and some of them would be rather difficult to support syntactical. John Roth > > -Mike > > From benn at cenix-bioscience.com Wed Apr 21 12:18:09 2004 From: benn at cenix-bioscience.com (Neil Benn) Date: Wed, 21 Apr 2004 18:18:09 +0200 Subject: Optimizing a text statistics function In-Reply-To: References: Message-ID: <40869EC1.8030504@cenix-bioscience.com> Hello, I don't know python as well as most people on this list so this is a leading question. In other languages I've used (mainly java although some C, C# VB ), the way I woud look at speeding this up is to avoid loading all the words into memory in one go and then working upon them. I'd create one stream which reads through the file, then passes onto a listener each word it finds from the lexing (making the input into tokens) and then another stream listening to this which will then sort out the detail from these tokens (parsing), finally an output stream which put this data wherever it needs to be (DB, screen, file, etc). This means that the program would scale better (if you pass the European voting register through your system it would take exponentially much longer as you must scan the information twice). However as more experienced python programmers have not suggested this is this because there is : a. Something I'm not getting about python text handling b. Not easy/possible in python I ask this because I've been looking at (C)StringIO and it is OK for this kind of behaviour using strings (reading from a serial port and passing onto middleware) but it doesn't seem to have the ability to remove characters from the buffer once they have been read, therefore the buffer will grow and grow as the process runs. For now I'm having to use strings which is less than ideal because they are immutable (I was think of writing my own StringBuffer class will will discard characters once they have been read from the StringBuffer) and therefore my program scales badly. However I do agree with the earlier poster - don't optimise for speed unless you need to (I'm assuming this is an academic exercise and I'm waiting to go to the pub)!!! Simplicity of design is usually a better win. Cheers, Neil Dennis Lee Bieber wrote: >On Wed, 21 Apr 2004 16:51:56 +0200, Nickolay Kolev >declaimed the following in comp.lang.python: > > > >>It is really simple - it reads the file in memory, splits it on >>whitespace, strips punctuation characters and transforms all remaining >>elements to lowercase. It then looks through what has been left and >>creates a list of tuples (count, word) which contain each unique word >>and the number of time it appears in the text. >> >> >> > Without looking at the code, I'd probably drop the use of the >tuples for a dictionary keyed by the word, with the data being the >count. Granted, the output would not be easily sorted... > > Okay, you do have a dictionary... > > I suggest dropping the initialization pass -- for common words >it's going to be redundant... Dictionaries have a method for supplying a >default value if a key doesn't exist. See the following: > > >## for x in strippedWords: >## unique[x] = 0 >## >## for x in strippedWords: >## unique[x] += 1 > > for x in strippedWords: > unique[x] = unique.get(x, 0) + 1 > > >-- > > ============================================================== < > > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > > wulfraed at dm.net | Bestiaria Support Staff < > > ============================================================== < > > Home Page: < > > Overflow Page: < > > -- Neil Benn Senior Automation Engineer Cenix BioScience PfotenhauerStrasse 108 D-01307 Dresden Germany Tel : +49 (351) 210 1300 e-mail : benn at cenix-bioscience.com Cenix Website : http://www.cenix-bioscience.com From mab at iee Mon Apr 5 10:06:34 2004 From: mab at iee (Marco Bartel) Date: Mon, 05 Apr 2004 16:06:34 +0200 Subject: How to assign a default constant value in a function declaration In-Reply-To: References: Message-ID: <40716899$1@news.vo.lu> rzed wrote: > "Vineet Jain" wrote in > news:mailman.341.1081121191.20120.python-list at python.org: > > >>The following does not work although it seems like something you >>should be able to do. >> >>def someFunction(option=Constants.DEFAULT_VALUE): >> > > Do you mean in a context like this? > > >>>>class Const: > > ... someVal=255 > ... otherVal=0 > ... > >>>>Const.someVal > > 255 > >>>>someVal=255 >>>>someVal > > 255 > >>>>def blip(Const.someVal): > > File "", line 1 > def blip(Const.someVal): > ^ > SyntaxError: invalid syntax > >>>>def blip(someVal): > > ... (no syntax error) > > > I've wondered about that, too. > > i checked this out, and i think its the name you were using: Const i tried this, and it works fine >class mconst: > testval = 255 >def testme(test = mconst.testval) > print test >print testme() 255 if this is what you wanted dont use the word const for the class CU Marco From claird at lairds.com Fri Apr 30 22:43:32 2004 From: claird at lairds.com (Cameron Laird) Date: Sat, 01 May 2004 02:43:32 -0000 Subject: calling functions at the same time References: <1095ijdb5jotvf1@corp.supernews.com> Message-ID: <10963mkpkdpn3fa@corp.supernews.com> In article , Bart Nessux wrote: . . . >I need to ping 4 hosts at exactly the same time from the same machine (I >plan to timestamp the pings) to test and measure network conditions over >different routes to different hosts. Putting all the ping hosts in a list >and looping through it is not a fair or balanced way to do this because of >the time differences. > > > >> It turns >> out "simultaneously" has a plethora of meanings, and you're the >> only one in a position to get others to understand which you >> have in mind. > >I mean it to mean: at the *exact* same time... concurrently. Like runners >starting a race together. > >> >> It'll also help to know whether you mean "function" as specific >> to the Python language, or more abstractly, as a unit of useful >> accomplishment. > >Specific to Python. Good description! We're definitely getting somewhere. How serious are you about this?? More specifically, do you have in mind a conventional desktop host, or are you investing in specialized hardware and firmware? On a conventional rig, your network traffic will be sequenced; a single networking interface, say, can't emit four signals simultaneously, but *must* do first one packet, then the next, then ... Are you OK with that? What does "ping" mean to you? Do you have in mind the command-line executable, or are you planning to shape your own ICMP traffic? -- Cameron Laird Business: http://www.Phaseit.net From hungjunglu at yahoo.com Sun Apr 4 11:51:20 2004 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 4 Apr 2004 08:51:20 -0700 Subject: Working with a list in a more ?pythonic? way References: <20040404124833458+0200@news.rhrz.uni-bonn.de> Message-ID: <8ef9bea6.0404040751.192a9c64@posting.google.com> Nickolay Kolev wrote in message news:<20040404124833458+0200 at news.rhrz.uni-bonn.de>... > > Having a string consisting of letters only, find out the total sound > score of the string. The sound score is calculated as the sum of the > transition scores between the characters in that string. The transition > scores are stored in a 26 x 26 matrix. I.e. the transition A -> F would > have the score soundScoreMatrix[0][5]. My attempt here: import operator soundScoreMatrix = [[.1,]*26]*26 # sample score matrix phrase = 'abracadabra' cap_phrase = phrase.upper() indices = [ord(c)-65 for c in cap_phrase] scores = [soundScoreMatrix[indices[i-1]][indices[i]] for i in range(1, len(indices))] sum = reduce(operator.add, scores) print sum regards, Hung Jung From ajsiegel at optonline.com Tue Apr 6 12:04:44 2004 From: ajsiegel at optonline.com (Arthur) Date: 6 Apr 2004 09:04:44 -0700 Subject: slightly OT: BUT NEEDs to be said References: <8b42d1998c978c8c1cddf15c52a1c57b@dizum.com> Message-ID: <213df9a1.0404060804.33d68297@posting.google.com> "Mike C. Fletcher" wrote in message news:... > Sometimes other > people like TV shows we think are insipid or offensive, this too is part > of life, and if you realise and accept that (within reason) you'll be > happier and more content. Despite having loud issues about community conformity and peer pressures (isolated issues, but loud ones) I must say that the fact that the Holy Grail movie was one of only 3 I ever walked out on, hasn't seemed to brand me. I was feeling particularly fragile, I remember, and looking for comic relief. The dismembering stuff - as a comic notion - didn't work for me, at the moment. Wuss. For those on the edge of their seats: 2. Problem Child: "If he pees in the lemonade" , I told my son, "we're out of here". He pees in the lemonade. 3. Priscilla Queen of the Desert: There were options, it seemed to me. Take off the dress in the Outback, being one. There has to be a way to promote a message of tolerance, it seems to me, without making putzes out of guys living on their brawn and wits in the Outback. Art From cybermanxu at hotmail.com Wed Apr 21 22:14:48 2004 From: cybermanxu at hotmail.com (Jinming Xu) Date: Wed, 21 Apr 2004 21:14:48 -0500 Subject: A python telnet entry level question Message-ID: Hello Everyone, I am trying to write a python script to telnet to a server and then do something there. As the first step, I practiced the python example in Lib Reference 11.13.2. But I am finding the script stops after I supplied the password. Does anyone know why? Thanks in advance! Jinming Xu PS: Here is the script: import getpass import sys import telnetlib HOST = "localhost" user = raw_input("Enter your remote account: ") password = getpass.getpass() tn = telnetlib.Telnet(HOST) tn.read_until("login: ") tn.write(user + "\n") if password: tn.read_until("Password: ") tn.write(password + "\n") tn.write("ls\n") tn.write("exit\n") print tn.read_all() _________________________________________________________________ MSN Toolbar provides one-click access to Hotmail from any Web page ? FREE download! http://toolbar.msn.com/go/onm00200413ave/direct/01/ From jcarlson at uci.edu Sun Apr 4 14:18:16 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Sun, 04 Apr 2004 11:18:16 -0700 Subject: Python is faster than C In-Reply-To: References: <406F0907.96F37EA1@tunes.org> Message-ID: > Yes, but Psyco is writted in C & Python, and it use an C module. > Said "Psyco is faster than C", it's like said "Psyco is faster than Psyco". You probably meant "C is faster than C". That is a reasonable statement, but users of Psyco don't need to write anything special beyond a handful of extra statements in Python. To the user, Psyco is a module that makes things fast. They wrote everything in Python, so to them, "Python with Psyco is faster than C" is far more accurate. - Josiah From __peter__ at web.de Sun Apr 25 13:54:16 2004 From: __peter__ at web.de (Peter Otten) Date: Sun, 25 Apr 2004 19:54:16 +0200 Subject: List operator overloading snag References: <8TCdnQn1OKieaRbdRWPC-w@speakeasy.net> Message-ID: Steven Brent wrote: >>>> print S1 or S2 > Set: ['s', 'p', 'a', 'm'] # custom __repr__ used but still default > # __or__ behavior, returns first true operand > >>>> print S1.__or__(S2) > using Set.__or__ > Set: ['s', 'p', 'a', 'm', 'c', 't'] # now all the custom behaviors Try S1 | S2 instead, __or__() somewhat misleadingly implements the | aka "bitwise or" operator. Peter From loic at yermat.net1.nerim.net Sat Apr 3 13:04:40 2004 From: loic at yermat.net1.nerim.net (Yermat) Date: Sat, 03 Apr 2004 20:04:40 +0200 Subject: Verifying temporal properties. Need problems. In-Reply-To: References: <68771ca.0404010839.39b0c24f@posting.google.com> Message-ID: Bjorn Heimir Bjornsson a ?crit : > Hello Loic > I'm working with control flow only, generating pushdown systems from the > AST that are then checked with the model checker Moped (using LTL > properties). > A similar approach was taken for JavaCard > (http://www.sics.se/fdt/vericode/jcave.html). > I chose Python for fun, but at the moment support just a limited subset. > I'm unsure how far I will/can go. E.g. some dynamic stuff can't be analysed > statically. I also just ignore all data flow, which simplifies everything but > means I will not recognise all control flow correctly. > I checked some small non-python-specific problems, but experience of others > suggest that the aproach scales quite well. > This is an MSc thesis, I haven't published anything else. > Bjorn Hi, Ok I see. Instead of searching the workflow yourself you might look at PyPY. There is a class (see translator.py) that construct such a flow. I have also construct a simple data flow to check if a variable used was previously defined. On monday, I will show you a kind of workflow I'm creating in case mine is more complete than yours... Anyway, you're right that with dinamic stuff, analysis is difficult. But with research like StarKiller (Type Inference) it should become more and more easier... I will wait for your publication ;-) Lo?c From usenet_spam at janc.invalid Fri Apr 30 23:02:24 2004 From: usenet_spam at janc.invalid (JanC) Date: Sat, 01 May 2004 03:02:24 GMT Subject: Modules to create XML for OpenOffice References: Message-ID: "Ellinghaus, Lance" schreef: > Has anyone created a set of modules to facilitate creation of XM Document > files for OpenOffice? There is some stuff in the docutils "sandbox": And on systems that have OOo 1.1.0 or higher installed, you can use the Python-UNO bridge: -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From merv at spidernet.com.cy Mon Apr 12 16:50:15 2004 From: merv at spidernet.com.cy (merv hammer) Date: Mon, 12 Apr 2004 23:50:15 +0300 Subject: A new OS In-Reply-To: References: <107k441hitt2ld9@corp.supernews.com> Message-ID: <20040412205015.GA4746@spidernet.com.cy> On Mon, Apr 12, 2004 at 10:55:55AM -0700, Corey Coughlin wrote: > I think it sounds like a great idea. I'd ultimately like to go a > direction like that at some point. One of the biggest problems with > existing operating systems (like Windows or Linux) is that they are > for the most part built on C, which then dictates what the low level > calls look like, the memory architecture, and so on. Writing an OS in > Python could give you a new perspective on mapping a high level > architecture onto a machine. Imagine, for instance, an OS > architecture with a genuine object hierarchy, where low level details > get abstracted into a machine level that can be swapped out to conform > to different processor architectures, where garbage collection is an > OS service, and maybe the filesystem is actually an object persistance > system, so every file is actually an object with type instead of a bag > of bytes, and then imagine how easy it would be to add advanced > indexing a la Chandler to it. Could we then distribute programs as > only python bytecode, getting platform independence? Would it be > easier adding security using higher levels of abstraction? How about > creating a complete network OS? Would that be easier in python? In > general, as you abstract complex os services into simpler python code, > would it be easier to expand the capabilities of your os? I can't > imagine that it would be harder. It could be quite an interesting > project, if conducted with the aim of not just making yet another > generic operating system, but with the aim of creating a truly > pythonic OS. That would be great. > > > > > "A Evans" wrote in message news:<107k441hitt2ld9 at corp.supernews.com>... > > Hello Everyone I am working towards starting a project developing a new > > Operating System using the Python language (or a derivative thereof). As > > recommended on this forum I am asking if people are interested in something > > like this and ask who would be willing to support a project this large. > > > > Any and all ideas are welcome this message is just to see what kind of > > support this project would recieve > > > > Cheers > > > > Andrew > -- > http://mail.python.org/mailman/listinfo/python-list Hi there, just to let you know, perhaps as encouragement, that I am working on the foundations of an extensible shell (not surprisingly referred to as an xshell) which is really a BASH shell with all its functionality intact but which could be used interactively (at the command line) and via scripts using Python. This idea was born in discussions on a Gentoo list while contemplating the pros and cons of the Gentoo Portage Tree being written in Python. I know the idea is notreally new, but it has intrigued me ever since,to the point where I succumbed and decided to start thrashing out how it might be done. I just want to stress that xshell, as it is now, is not a Python shell per se, so to speak, but an e(x)tensible BASH shell in which Python language support can be compiled-in at compile/install time, after which one may be able to switch interactively between the sh dialect and Python at the command line and in BASH scripts. I am barely at Base One with the whole thing yet, with work and a motley crew of four young babies, I get only a few hours a night at it at best. I am at the stage of sketching a Python syntax for the prompt that will enable piping, backgrounding etc etc interatively. This little pet project of mine has generated quite some debate, among colleagues at work and developers and users on lists. The debate ranges from anunderstandable incredulity such as the "Why bother - learn sh!" to concerns over performance, file handling dynamics, and the thin-end-of-the-wedge syndrome ("if you build-in support for Python language syntax at the BASH shell environment, next people will be scripting the BASH shell in Ruby, or even Javascript!", by which no offense is meant to Ruby or JS coders, but rather that the BASH environment will become fragmented and less usable [consider, how would someone who has learned sh but does not know Python edit a BASH script written in Python? clearly a valid issue]). I am fully aware, as a developer and sometime-sysadmin that the power of BASH/SH is not just in its builtins but alsoin the fact that wherever one goes, its the same, give or take a bug fix across releases or a syntactical nuance across platforms. And this is before we even come to the issue of having a Python interpreter or some slimline version of onerunning in such as way as to catch instances of "live" interactive Python code from the commandline without having to fire up the whole Python engine everytime a single command is issued at the prompt. Anyway, without dismissing these and the whole stack of other issues related to it, here's my position: as an experienced C coder, I'm not looking to supplant the C-code base of *nix environments with Python because I don't like C. However, I do believe that there may be something to be said for the "tool-for-the-job" concept and there certainly are everyday tasks, sh routines and BASH scripts out there that might be well-served by a Python make-over. I believe there is much to be said for the conceptually clean development that can (in the best of worlds) emerge from the kind of programming involved in the use of syntactically clean high-levellers such as Python. I "hack" C-code for aliving and it seems to me that the very structure of C itself lends itself to be "hacked" (in the *nix sense) since the code can easily and quickly become obtuse, highly stylised (in an review-inefficient way, according to the nuances and stylistic habits of each C coder) and does not lend itself well to a living and changing development process, however modular and OO the C code may itself be. However, with such a clean, well-designed and expansive language as Python, one almost naturally (this is my feeling at least) begins to think in terms of extensibility and the future. For this reason, I am working on the hunch (I may well be very very wrong, of course) that Python may well turn out to be a useful and versatile BASH environment language. Using standard Python functionality, one may be able to extend dramatically the range of builtins available in the BASH shell by simply coding them and importing them as modules,for example. Thirdly, I believe that Linux, the free Unix flavours and the Open Source/Free Software world is about choice. Is there a way to build on the tools that are at our fingertips to offer more choice and possibilities to the user without at the same time running the risk of fragmenting existing and effective user practices? OK. that's enough from me. A python OS would be a very interesting project and perhaps an important experiment in finding new ways to look at and interpret what we do as developers and users. Lastly, I for one would be very enthused at the idea of being able to offer my meagre skills and experience to assist in such a project. kind regards m -- Merv Hammer ------------------------------------------------------------- mail:merv at spidernet.com.cy GPG PK: 7BC2A589 From michael at foord.net Wed Apr 14 04:01:04 2004 From: michael at foord.net (Fuzzyman) Date: 14 Apr 2004 01:01:04 -0700 Subject: CGI Problems With Xitami References: <8089854e.0404072356.7f33f440@posting.google.com> <8089854e.0404090633.7c8541ea@posting.google.com> <8089854e.0404130413.6dae0102@posting.google.com> Message-ID: <8089854e.0404132304.33c68820@posting.google.com> If in doubt.... reinstall.... Simply uninstalling and re-installing Xitami solved the problem. As far as *I* can see the settings the same as they were - but now it works.... Odd but good... :-) Regards, Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html From fredrik at pythonware.com Tue Apr 20 02:28:54 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 20 Apr 2004 08:28:54 +0200 Subject: module not callable - why not? References: <7xsmf1fxd9.fsf@ruckus.brouhaha.com><8ef9bea6.0404180956.cd1a152@posting.google.com> <8ef9bea6.0404190908.4b130d57@posting.google.com> <8ef9bea6.0404191535.cd7f9e6@posting.google.com> Message-ID: Hung Jung Lu wrote: > > inside the module, it's spelled > > > > name > > > > > > Can't believe I have to reply to all these silly bursts. :) > > This is a frequently asked question, Fredrik. I don't make it up. Now, > think again why newbies and oldies alike at times need to access > variables by name strings. Next time, digest first before you post. it's a common question from people who know certain other scripting languages but not Python, and don't know how to use dictionaries and other data structures to get the result they're after. globals() is hardly ever the right answer. frankly, are you sure *you* know Python well enough to write *Python* pro- grams in Python? given the things you complain about, I'm not so sure. From andymac at bullseye.apana.org.au Thu Apr 1 18:10:36 2004 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Fri, 2 Apr 2004 09:10:36 +1000 (EST) Subject: Reliability of venster+ctypes on win32 In-Reply-To: <01df01c417f2$27883960$6600a8c0@YODA> References: <8f198e47.0404010335.6045400e@posting.google.com> <01df01c417f2$27883960$6600a8c0@YODA> Message-ID: <20040402090904.P50485@bullseye.apana.org.au> On Thu, 1 Apr 2004, Dave Brueck wrote: > Somesh wrote: > > I downloaded and tried a small dialog-dll's application with > > venster+ctypes+python 2.3 > > its working very well, but is it reliable to use in big projects ? or > > part of big projects ? > > You'll have to make that determination yourself, but IMO they are both very > stable. We started using them both in production applications sooner than the > authors probably would have advised, but didn't encounter problems (we've > certainly never had any crashes due to either library, for example). Amen. -- 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 michael at foord.net Tue Apr 13 08:13:28 2004 From: michael at foord.net (Fuzzyman) Date: 13 Apr 2004 05:13:28 -0700 Subject: CGI Problems With Xitami References: <8089854e.0404072356.7f33f440@posting.google.com> <8089854e.0404090633.7c8541ea@posting.google.com> Message-ID: <8089854e.0404130413.6dae0102@posting.google.com> Andrew MacIntyre wrote in message news:... > On Sat, 9 Apr 2004, Fuzzyman wrote: > > > Andrew MacIntyre wrote in message news:... > > > > Are you using "python -u" when invoking your CGI script? Unbuffered I/O > > > saves lots of headaches with CGI, especially on Windows. > > > > Hmmm... I'm not, I'll try it. > > I might have fun working out how with Xitami.... and then with > > whatever server we have at work :-) > > I vaguely recall that Xitami might honour the "#!" convention, so try > heading your scripts with > > #!python -u Hmm.. tried that. It doesn't trip Xitami up - so I'm assuming it works :-) On the other hand it doesn't help. Weird - the same setup works at work... but not at home.... At work POST behaves fine, whilst at home I have to switch it to using GET.. most frustrating. Obviously *something* is causing this - but I can't track it down. Regards, Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html From premshree_python at yahoo.co.in Wed Apr 14 05:22:35 2004 From: premshree_python at yahoo.co.in (=?iso-8859-1?q?Premshree=20Pillai?=) Date: Wed, 14 Apr 2004 10:22:35 +0100 (BST) Subject: pyAlbum.py is now PyAC Message-ID: <20040414092235.39139.qmail@web8312.mail.in.yahoo.com> Hello, pyAlbum.py is now called PyAC - Python Album Creator. The project has been moved to SourceForge. It's at http://pyac.sourceforge.net If you have created an album using pyAlbum.py (NOT pyAlbum) or PyAC, and are interested in having your album's link placed at the development website, drop a line to pyalbum[AT]rediffmail[DOT]com -Premshree Pillai ===== -Premshree [http://www.qiksearch.com/] ________________________________________________________________________ Yahoo! India Matrimony: Find your partner online. http://yahoo.shaadi.com/india-matrimony/ From lubowiecka at go2.pl Mon Apr 5 07:08:35 2004 From: lubowiecka at go2.pl (Sylwia) Date: 5 Apr 2004 04:08:35 -0700 Subject: python processes names Message-ID: Hi! How to make python programs show up by name is ps (e.g ps -e). By default if we have many different python processes running simultaneously, then we can only see python python python for three different python processes. I would much rather see first_python_program_name.py, second_python_program_name.py and third_python_program_name.py listed by ps. Is that possible without downloading and installing any non-standard modules? Thank you in advance, Best wishes, Sylwia From huggiepython at graffiti.idv.tw Tue Apr 6 02:15:06 2004 From: huggiepython at graffiti.idv.tw (Timothy Wu) Date: Tue, 06 Apr 2004 14:15:06 +0800 Subject: A beginner's question on thread Message-ID: <40724AEA.8060709@graffiti.idv.tw> I'm writing a small utility that listens for socket connections, and also repond to user inputs via a text menu selection. In order to respond to both the user and the incoming connections I figure I need to use thread. I think I would use the main thread to handle the menu and spawn a thread which listens on a socket. Now my question is, how do I terminate the server thread if user wants to exit the application? If the server just sit there and listen the thread would never terminate by itself. What kind of inter-thread communications are available and where would I find info/tutorial on that? Timothy From shalabh at cafepy.com Fri Apr 23 04:23:51 2004 From: shalabh at cafepy.com (Shalabh Chaturvedi) Date: Fri, 23 Apr 2004 01:23:51 -0700 Subject: Subclasses in Python References: Message-ID: Thomas Philips wrote: > I'm teaching myself programming using Python, and have a question > about subclasses. My game has two classes, Player and Alien, with > identical functions, and I want to make Player a base class and Alien > a derived class. The two classes are described below > The two classes are almost identical, except that: > 1. When a new player is instantiated or destroyed, Player.n is > incremented/decremented, while when a new alien is instantiated, > Alien.n is incremented/decremented. > 2. When hit by an energy blast, the player and the alien have > different thresholds below which they die. > > How can I base the Alien's __init__(), __del__() and hit() methods on > the Player's methods, while ensuring that the appropriate class > variables are incremented/decremented when a new object is > instantiated and that the appropriate threshold is used when the > player/alien is hit by an energy bolt? > > Thomas Philips One easy solution is to use self.__class__.n and self.__class__.threshold instead of explicit Player.n and Player.threshold. Then derive Alien from Player and only keep the two class attributes in it. Get rid of all methods in Alien. If you haven't already guessed how this works: when you call any method on an Alient object, self.__class__ will be Alien, and if you call a method on a Player object, self.__class__ will be Player. -- Shalabh From jacek.generowicz at cern.ch Fri Apr 2 06:53:59 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 02 Apr 2004 13:53:59 +0200 Subject: Simple text markup (-> HTML) References: <406D3EAA.16466030@alcyone.com> Message-ID: Erik Max Francis writes: > Jacek Generowicz wrote: > > > I'm looking for something to help developers wirte documentation for > > bits of software they are writing. > > reStructredText. Bigtime. Way cool ! I am rather shocked that this (or its ancestors) has not registered on my radar before now. Thanks ! From newsgroups at jhrothjr.com Sun Apr 11 15:51:03 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Sun, 11 Apr 2004 15:51:03 -0400 Subject: Python OS References: <107j4eu6ffn2c68@corp.supernews.com> Message-ID: <107j8elr1m3tc65@news.supernews.com> "A Evans" wrote in message news:107j4eu6ffn2c68 at corp.supernews.com... > I have a question concerning the development of Python Based Operating > System. You see I have had sort of a dream to develop an Open Source > Operating System that would revolutionize the OS market and Since I started > using Python I have fallen in love with the language. Reading articles here > and there I have read that Python is a more secure language than C. I also > read another article (I can't remember which) saying Python would not be > able to develop an OS. I don't believe its true however. I am by no means a > programmer at this stage. But as I learn more and more I see Python as the > Holy Grail of programming languages > > My questions would then be, is Python capable of creating an OS from scratch > and if so would it be plausible if possible It depends on what you call "Python." The current Python implementations (CPython, Jython and the so far incomplete IronPython, PyPy and the unnamed version on Parrot) all depend on an operating system and interpreter that provides lots of services. (That's not quite true of PyPy, which is well worth looking at.) The central core of an operating system has to get down and dirty with the hardware. Modern operating systems are written in a very feature impoverished version of C with occasional excursions into Assembler either for performance or to get access to hardware that applications are prevented from accessing. You could undoubtedly create a language that would compile efficiently and would still have many (if not all) of the conveniences that Python provides, but it would be a different language. John Roth > > Cheers > > A python NewBie - Man I hate that term does anyone else Likewise. I prefer novice. I consider Newbie to be patronizing. JR. > > See Ya > > From hungjunglu at yahoo.com Mon Apr 19 19:35:39 2004 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 19 Apr 2004 16:35:39 -0700 Subject: module not callable - why not? References: <7xsmf1fxd9.fsf@ruckus.brouhaha.com><8ef9bea6.0404180956.cd1a152@posting.google.com> <8ef9bea6.0404190908.4b130d57@posting.google.com> Message-ID: <8ef9bea6.0404191535.cd7f9e6@posting.google.com> "Fredrik Lundh" wrote in message news:... > Hung Jung Lu wrote: > > > > That's not the only answer, and it's not the one I use: > > > > > > import foo > > > getattr(foo, 'name') > > > > You can't do this when you are inside the module itself. > > inside the module, it's spelled > > name > > Can't believe I have to reply to all these silly bursts. :) This is a frequently asked question, Fredrik. I don't make it up. Now, think again why newbies and oldies alike at times need to access variables by name strings. Next time, digest first before you post. Don't disappoint me. :) regards, Hung Jung From maxm at mxm.dk Tue Apr 20 08:11:14 2004 From: maxm at mxm.dk (Max M) Date: Tue, 20 Apr 2004 14:11:14 +0200 Subject: CamelCase versus wide_names (Prothon) In-Reply-To: <40851128.8000400@mxm.dk> References: <6ee58e07.0404192141.2229efd6@posting.google.com> <40851128.8000400@mxm.dk> Message-ID: <40851379$0$290$edfadb0f@dread12.news.tele.dk> Max M wrote: > Make . a normal letter. > > And make _ have the function that . has in Python, so that _ and . sort > of switches meaning. > > Anybody in hteir right mind can see that, that is a good idea: Oh I forgot to include a good example: def install.sub.skin(self, out, skin.folder): """Install a subskin""" skins.tool = get.tool.by.name(self, 'portal.skins') for skin in skins.tool_get.skin.selections(): path = skins.tool_get.skin.path(skin) path = map(string_strip, string_split(path,',')) if not skin.folder in path: try: path_insert(path_index('custom')+1, skin.folder) except value.error: path_append(skin.folder) path = string_join(path, ', ') skins.tool_add.skin.selection(skin, path) out_write('Subskin successfully installed into %s\n' % skin) else: out_write('*** Subskin was already installed into %s\n' % skin) It is allmost freakish how hard that is to read. On a more serious not though, what about a special notation for variables: _this is a variable_ = 'Some string' `Or this is a variable` = 'Some other string' Is that to hard to read? I guess that the backtick is. It is certainly easier to type on my Danish keyboard. regards Max M From stevenbee at removethis.att.net Sun Apr 25 13:23:13 2004 From: stevenbee at removethis.att.net (Steven Brent) Date: Sun, 25 Apr 2004 13:23:13 -0400 Subject: List operator overloading snag Message-ID: <8TCdnQn1OKieaRbdRWPC-w@speakeasy.net> Dear Group: I am a little perplexed by a basic example from the O'Reilly book, 2nd ed., which demonstrates overloading some builtin list operators by embedding lists in a wrapper class. Below is a snippet which shows the wrapper class and the overloaded operator definition within (in this case, '__or__') ## BEGIN SNIPPET (from setwrapper.py) class Set: def __init__(self, value = []): self.data = [] self.concat(value) def union(self, other): res = self.data[:] for x in other: if not x in res: res.append(x) print 'using Set.__or__' #for debugging return Set(res) def __repr__(self): return 'Set: ' + `self.data` #for debugging def __or__(self, other): return self.union(other) ## END SNIPPET The problem is that I can't seem to get my wrapped lists to use the overloaded versions of the operators without calling the customize instance method directly, as shown below: >>> import setwrapper; from setwrapper import * >>> S1 = Set(['s','p','a','m']) >>> S2 = Set(['s','c','a','t']) >>> print S1 or S2 Set: ['s', 'p', 'a', 'm'] # custom __repr__ used but still default # __or__ behavior, returns first true operand >>> print S1.__or__(S2) using Set.__or__ Set: ['s', 'p', 'a', 'm', 'c', 't'] # now all the custom behaviors This happens regardless of whether the module is imported into IDLE, or run standalone. Obviously I'm missing something very basic namespace issue, and I don't want to gloss over any bumps in my learning curve. Many thanks. -- ********************** www.emptydrum.com ...like a think tank without the thinking or the tank ********************** From tundra at tundraware.com Mon Apr 12 13:10:07 2004 From: tundra at tundraware.com (Tim Daneliuk) Date: 12 Apr 2004 13:10:07 EDT Subject: Parsing string array for differences In-Reply-To: <7598e160.0404120856.217bc8d5@posting.google.com> References: <7598e160.0404120856.217bc8d5@posting.google.com> Message-ID: <10vqk1-lcb1.ln1@eskimo.tundraware.com> Ray Slakinski wrote: > My below code doesn't do what I need it to do. What I want is to > capture the differences between two arrays of data into a new list. > So if list A has {Fred, Bob, Jim} and List B has {Jim, George, Fred} I > want to capture in list C just {Fred, Jim} > > y = 0 > z = 0 > data = {} > for element in listB: > x = 0 > for element in listA: > if listA[x] != listB[y]: > listC[z] = listB[y] > z = z + 1 > x = x +1 > y = y + 1 > > Any and all help would be /greatly/ appreciated! > > Ray http://pydoc.org/2.3/sets.html -- ---------------------------------------------------------------------------- Tim Daneliuk tundra at tundraware.com PGP Key: http://www.tundraware.com/PGP/ From python at rcn.com Mon Apr 5 02:49:56 2004 From: python at rcn.com (Raymond Hettinger) Date: 4 Apr 2004 23:49:56 -0700 Subject: Python is faster than C References: <406F0907.96F37EA1@tunes.org> <5d83790c.0404032144.482787bd@posting.google.com> Message-ID: <5d83790c.0404042249.5ff4e354@posting.google.com> [Jeff Epler] > from pprint import * > def install_hook(): > def displayhook(v): > import __main__ > if v is not None: > if isiterator(v): > print "<%s object at 0x%8x:" % ( > type(v).__name__, id(v)), > v, copy = itertools.tee(v) > for elem in itertools.islice(copy, 3): > print saferepr(elem), > try: > copy.next() > except StopIteration: > pass > else: > print '...', > sys.stdout.softspace=0 > print ">" > else: > pprint(v) > __main__._ = v > > sys.displayhook = displayhook This is very nice. In my sketch, I used Py2.4's itertools.tee() to handle non-restartable iterators. For Py2.3, a good alternative is: copy = list(itertools.islice(v, 3)) v = itertools.chain(copy, v) Now, copy can be used in the display and "v" produces the same values as the original iterator. Cheers, Raymond Hettinger P.S. If some experimentation shows your code to be useful at the interactive prompt, please submit a patch on SF so it won't be lost. From claird at lairds.com Thu Apr 1 00:03:15 2004 From: claird at lairds.com (Cameron Laird) Date: Thu, 01 Apr 2004 05:03:15 -0000 Subject: Python from the command line (was: Choosing Perl/Python for my particular niche) References: <40652B0D.7C313F77@doe.carleton.ca> <406532F7.D56DC671@doe.carleton.ca> <406934a9$0$7564$afc38c87@news.easynet.co.uk> <4069F1FD.601C9079@doe.carleton.ca> Message-ID: <106n8kj2t5n7m11@corp.supernews.com> In article <4069F1FD.601C9079 at doe.carleton.ca>, Fred Ma wrote: . . . >Perl/sed. About invoking Perl as part of a simple command in a >pipeline, I mean that one doesn't even have to write a script for it, >similar to sed > > Command1 | sed -e Expression1 -e Expression2 ... | Command_N > >This might also be possible in Python, in which case so much the better. >I'll find out (or someone might answer in a follow-up post). Thanks . . . # python -c "print 3 + 5" 8 -- Cameron Laird Business: http://www.Phaseit.net From vincent at visualtrans.de Mon Apr 5 02:16:24 2004 From: vincent at visualtrans.de (vincent wehren) Date: Mon, 05 Apr 2004 08:16:24 +0200 Subject: Why is there no PyInt_AsInt() ? In-Reply-To: References: Message-ID: Jon Perez wrote: > ...and instead down-cast the result of PyInt_AsLong() when > the PyObject was an integer in the first place?? Yes, but a Python integer is "not the same" as a C integer. Python integers are implemented using a C long. Vincent Wehren From alloydflanagan at comcast.net Wed Apr 7 18:09:45 2004 From: alloydflanagan at comcast.net (A. Lloyd Flanagan) Date: 7 Apr 2004 15:09:45 -0700 Subject: slightly OT: BUT NEEDs to be said References: <4078daf265c69e9353e8af72542da703@dizum.com> Message-ID: "Dave Brueck" wrote in message news:... > I remember that one time the user filters were suspected by some outsiders, and > Guido privately threatened to introduce mandatory curly braces around code > blocks if we as a group didn't convince people "on the outside" that the > filters didn't exist - hence the big conditional operator debate of '03. We > actually got assigned sides in that debate - didn't even get to pick them > ourselves. > OK, Dave, which side am I supposed to take on this one? I seem to have missed the memo... From jcarlson at uci.edu Sat Apr 10 16:19:53 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Sat, 10 Apr 2004 13:19:53 -0700 Subject: Code blocks and top posting In-Reply-To: References: <8ef9bea6.0404100720.65ffd2c9@posting.google.com> Message-ID: Clarification of my post necessary. > I understand your point, however... > > >>> def async_chain(): > ... def do_step_1(): > ... print 'Step 1.' > ... after_idle(do_step_2) > ... def do_step_2(): > ... print 'Step 2.' > ... after_idle(do_step_3) > ... def do_step_3(): > ... print 'Step 3.' > ... after_idle(do_step_1) > ... > >>> def after_idle(funct): > ... funct() > ... > >>> async_chain() > Step 1. > Step 2. > Step 3. I should clarify. The above works, but the below... > And what you seem to want... > > if condition: > funct() > > def funct(): > #body > > .... is not available in any modern programming language. It is also > not possible to handle syntactically in the Python interactive shell. Is not available. - Josiah From goodger at python.org Thu Apr 15 08:42:42 2004 From: goodger at python.org (David Goodger) Date: Thu, 15 Apr 2004 08:42:42 -0400 Subject: Is this an OK design? In-Reply-To: References: Message-ID: <407E8342.3000900@python.org> urnerk at qwest.net wrote: > ---- pv1.py ---- > > class P(object): > def __init__(self, amap) > self.amap = amap > self.P = self.__class__ # <-- store type of instance > > --- pv2.py --- > > import pv1 > class P(pv1.P): > > def __invert__(self): > # newmap = inverted self.amap > return self.P(newmap) # <--- class is now object attribute ... > What I'd like to know is: is my solution perverse or Pythonic? > Is there a better way? Whenever I've had to do the same thing, I'd just say: return self.__class__(newmap) Or make a specialized method, like: def new(self, *args): return self.__class__(*args) In other words, say it directly without the indirection of a class attribute. Unless, of course, you want to modify the attribute for some reason. Even then, I'd change the name to be more self-documenting. -- David Goodger From python at holdenweb.com Wed Apr 14 22:16:45 2004 From: python at holdenweb.com (Steve Holden) Date: Wed, 14 Apr 2004 22:16:45 -0400 Subject: Does Python compete with Java? In-Reply-To: References: Message-ID: <407DF08D.90407@holdenweb.com> Jakub Fast wrote: > > Thanks for a quick reply! > >> "LISP is over there ==>" >> >> Saying, in effect, that it isn't Pythonic. > > > Ok, maybe i'm asking for it :), but -- why? > > [i am willing to cease-and-desist asking any further if this is not a > welcome topic (like: we've discussed it fifty times by now, get a grip)] > Well, we are deep into the philosophical meaning of "pythonicity" here. If you haven't yet typed "import this" into an interactive interpreter session you should do so, but pythonicity is a little like the pattern gang's "quality without a name". It has been discussed, so a determined enough Googling will get you the details. I will confine myself to adding only that a) Python is intended to be easy to learn, and b) Any language construct that requires the lexical analyzer to be dynamically modified certainly will prove confusing to newcomers. The spirit of your contribution is entirely Pythonic, it's just that "practicality beats purity", and your ideas are a little impractical for a dynamic language like Python (remember, there's little distinction between "compile time" and "run time"). Try to treat these limitations as small challenges ;-) regards Steve From claird at lairds.com Sat Apr 3 19:37:37 2004 From: claird at lairds.com (Cameron Laird) Date: Sun, 04 Apr 2004 00:37:37 -0000 Subject: emergent/swarm/evolutionary systems etc References: Message-ID: <106um6hcr363u14@corp.supernews.com> In article , Peter MacKenzie wrote: >(Hmm, this might appear as a double posting, but I don't think my last one >made it through.) > >Thanks, but. > >("One approach to discussing and comparing AI >problem solving strategies is to categorize them using the >terms ''strong'' and ''weak'' methods. Generally, a weak . [much more] . . You might like "The Outsider's Guide to Artificial Intelligence" . -- Cameron Laird Business: http://www.Phaseit.net From me at privacy.net Wed Apr 21 04:31:40 2004 From: me at privacy.net (Duncan Booth) Date: 21 Apr 2004 08:31:40 GMT Subject: Generator inside a class prevent __del__ ?? References: <4085BA96.651D2E4A@free.fr> <200420041800310664%mday@apple.com> Message-ID: Rob Nikander wrote in news:kNKdnYsIEuHbdRjdRVn-uA at adelphia.com: > I checked out the documentation for that gc.garbage list and it says > that the collector can't free objects in cycles if the cyles have > objects that have __del__ methods. So it puts them in this list. > > I wonder what other garbage collectors do in this situation? Anyone > know? Java? > Most garbage collectors will do peculiar things if you have destructors or finalizers in the objects. The problem is that if two objects with finalizers reference each other there is no correct order to release the objects that will guarantee that the other object still exists, so the system either has to choose an arbitrary order, or refuse to call the finalizers. The .Net garbage collector is typical. Objects may have finalizers, and these finalizers are called as part of the garbage collection. The system guarantees that any finalizer is called exactly 0 or more times --- usually it is called once when the object is garbage collected, but if the object is never collected it may not be called at all, and if the object resurrects itself (e.g. during the finalizer it assigns itself to a global variable) the finalizer could be called more than once. A separate thread pool is used for finalizers, so your finalizer could be called while a user thread is executing a method on the object, and two objects which refer to each other could have their finalizers called in any order, or even simultaneously on separate threads. Effectively, this makes finalizers useless in all but the most obscure situations. When resources need to be released you should try to do it explicitly. In .Net this is handled by the Dispose() method, and the finalizer can then either try calling Dispose() if it has not yet been called, or could try logging an error although even that may be problematic from a finalizer. From peter9547 at btinternet.com Fri Apr 2 11:58:32 2004 From: peter9547 at btinternet.com (Peter MacKenzie) Date: Fri, 2 Apr 2004 16:58:32 +0000 (UTC) Subject: emergent/swarm/evolutionary systems etc References: Message-ID: Spreadsheets do seem to be an attractive option, but the benefits are not without their detractors: +Easy to work with +Require no/limited skill acquisition +Flexible -Cells can only hold single items of data (which can be worked around by using arrays of cells to hold multiple attributes for each location) -Require no/limited skill acquisition (being familiar and honest with my own psychological composition, I know that the only way I'm likely to develop a fair degree of programming competence is if there's a driving pressure to do so. It's something I'd like to learn, and this gives me the excuse/leverage to do so.) Unknowns: Time series graphical output would be necessary, even if it's very primitive. Do you know if the spreadsheet could be set up in such a way that cells would change colour depending on their values, or if the graph making facilities would be able to create reasonable representations of said values so that a series of graphs would be capable of showing up phenomena with fluidic (wavelike, turbulent, etc) characteristics? I'm afraid the temptation to take the hard route my prove too great (psychological paradoxes: I always feel good about feeling so terrible about these things after I've passed the point of no return in the undertaking, and the enormity of the task at hand sinks in - it's a whole adrenalin thing), but I'd still like to make a comprehensive assessment of my options before I commit to anything. From rawbobb at hotmail.com Mon Apr 12 11:13:07 2004 From: rawbobb at hotmail.com (bobb) Date: Mon, 12 Apr 2004 15:13:07 GMT Subject: connect with MySQL question References: <8Owec.16842$QQ6.8203@nwrdny02.gnilink.net> Message-ID: <7myec.41100$1y1.9195@nwrdny03.gnilink.net> perhaps it was on the mailing.database.mysql group, though :) "bobb" wrote in message news:8Owec.16842$QQ6.8203 at nwrdny02.gnilink.net... > This was just recently asked, I believe. > google for mysql client. > > wrote in message > news:mailman.477.1081484212.20120.python-list at python.org... > > > > Hi! All > > I download MySQL to Python interface software and get MySQLdb module etc > installed. But when I start mysqld on XP from c:\mysql\bin (all in windows) > and use following code to connect MySQL it fails > > > > # Database access > > import MySQLdb > > > con=MySQLdb.connect(host="127.0.0.1",port=3306,user="root",passwd="mypasswd" > ,db="smalldb") > > Cursor=con.cursor() > > sql_cmd="select * from customers" > > Cursor.execute(sql_cmd) > > results=Cursor.fetachall() > > con.close() > > > > > > It asked for client upgrade. What that mean? MySQL is 4.0 > > Anyone can help? > > Thanks in advance. > > > > Regards > > Zhiyong > > > > ________________________________________________________________ > > The best thing to hit the Internet in years - NetZero HiSpeed! > > Surf the Web up to FIVE TIMES FASTER! > > Only $14.95/ month -visit www.netzero.com to sign up today! > > > > From mcfletch at rogers.com Thu Apr 15 21:12:34 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Thu, 15 Apr 2004 21:12:34 -0400 Subject: Simple pyhon-based CMS In-Reply-To: References: <9396ba6f.0404131817.1219c695@posting.google.com> Message-ID: <407F3302.5080604@rogers.com> I use CoreBlog (http://coreblog.org/) for my blog (http://zope.vex.net/~mcfletch/plumbing/), it's very easy to use. Just a product sitting in Zope, no CMS facilities (i.e. no workflow mechanisms) that I've seen, but then you probably wouldn't want that for something simple and blog-like. Have fun, Mike >"Stewart Midwinter" wrote in message >news:9396ba6f.0404131817.1219c695 at posting.google.com... > > >>I'm looking for a simple python-based CMS (content management system), >>maybe with some blog-like features, ability to add articles - nothing >>too fancy. Do you have any suggestions? >> >>I've looked at Zope / Plone: very easy to install using the rpm I >>found. But it's obviously quite complex and powerful, which is no >>doubt of benefit on a site that has many users. But I'm just one >>person. All I want is a pythonic replacement for my current tool, >>postNuke. >> >> ... _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From tor.iver.wilhelmsen at broadpark.no Sat Apr 24 16:18:27 2004 From: tor.iver.wilhelmsen at broadpark.no (Tor Iver Wilhelmsen) Date: 24 Apr 2004 22:18:27 +0200 Subject: AOP use cases References: <84fc4588.0404140106.3fa0c55@posting.google.com> <0pydnSB4WYuieuLdRVn-hQ@powergate.ca> Message-ID: Tor Iver Wilhelmsen writes: > - Implementing Singleton as an aspect which states that calling Argh, I meant Immutable, og course. From heikki_salo at nobulkmailplease.sci.fi Mon Apr 26 16:03:11 2004 From: heikki_salo at nobulkmailplease.sci.fi (Heikki Salo) Date: Mon, 26 Apr 2004 23:03:11 +0300 Subject: C api: how to create objects? Message-ID: I bumbed into a seemingly trivial problem: in my C extension I want to create some very basic Python objects (no methods or attributes) and then add all the needed attributes according to given information. How can I do this!? I have tried to make new instances from PyObject with PyObject_New() and with some other functions as well, but the only result is that the application comes crashing down. I guess that I am doing something very wrong. This Python-code explains what I am trying to do: class Generic: pass data = getData() new_generic = Generic() if "color" in data: new_generic.color_value = data["color"] elif "position" in data: ... From jcarlson at uci.edu Sat Apr 10 15:35:43 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Sat, 10 Apr 2004 12:35:43 -0700 Subject: maximum length of a list & tuple In-Reply-To: References: Message-ID: > I just would like to know if there is any limit to a list or tuple. It depends on how much memory you have. Run the following and the last thing it prints out is your limit... c = 1 while c < 2**32: try: d = [1]*c print c c *= 2 except: break - Josiah From robin at alldunn.NOSPAM.com Thu Apr 1 17:46:33 2004 From: robin at alldunn.NOSPAM.com (Robin Dunn) Date: Thu, 01 Apr 2004 14:46:33 -0800 Subject: Don't understand wxPython event handling In-Reply-To: References: Message-ID: Robert wrote: > I also have anouther question: > > which is the better way to register to events: > eventManager.Register(self.OnPageDone,EVT_PAGE_DONE,self.pageContainer) > > or > > EVT_PAGE_DONE(self, self.OnPageDone) > > Short answer: It depends. Long answer: The eventManager sits on top of a Publish/Subscribe framework (Observer design pattern) so it is useful if you want to have lots of handlers for a specific event and/or if you want your handlers to be loosly coupled with the windows where the event was generated. If you put your handlers in the same class as the window that generated the event (or a parent window) then using the simpler form is just fine. -- Robin Dunn Software Craftsman http://wxPython.org Java give you jitters? Relax with wxPython! From sridharinfinity at yahoo.com Tue Apr 6 05:04:19 2004 From: sridharinfinity at yahoo.com (Sridhar R) Date: 6 Apr 2004 02:04:19 -0700 Subject: GUI Frameworks in Python? References: <930ba99a.0404030246.786455f5@posting.google.com> <8ef9bea6.0404041009.26ae2683@posting.google.com> Message-ID: <930ba99a.0404060104.fdf2605@posting.google.com> hungjunglu at yahoo.com (Hung Jung Lu) wrote in message news:<8ef9bea6.0404041009.26ae2683 at posting.google.com>... > sridharinfinity at yahoo.com (Sridhar R) wrote in message news:<930ba99a.0404030246.786455f5 at posting.google.com>... > > > > Man, you better use PyGTK (http://pygtk.org). It's portable (See pygtk > > faq for windows port). It's neet (API). > > Try also `glade`, `libglade`. > > http://glade.gnome.org , I think? > > Can someone outline some differences/advantages of PyGTK vs. wxPython? Sure. > > A first look at PyGTK shows me a more Unix-like look-and-feel. On the > other hand, wxPython on Windows does look very much like any other > Windows applications. Wrong. GTK apps do look with native look and feel. For Windows, look at the screenshots from the wimp project http://gtk-wimp.sourceforge.net I am sure about Mac too, as I have seen screenshots before (probably linked from GTK homepage) [You may better download download pygtk from windows from the link given the pygtk faq page] > > Is the event handling in PyGTK cleaner/better than wxPython? Does Of course. Have looked at libglade ( is availble as glade module in pygtk). You can even write a small function to autoconnect functions to events. Say you can write function in a format like def on_button1__clicked(self,button): "This function is called when button1 emits 'clicked' signal" ... stilll many more functions like this ... and you can even write your own function that autoconnects functions with their object/events. Instrospection in Event Handling! > PyGTK have more widgets? Sure. Also have a look at the GtkExtra (also pygtkextra) project. Writing new widgets is also pretty neat in PyGTK. > e FAQ of PyGTK does not have a comparison > section regarding other GUI toolkits, I think it would be useful if If not, you can try them yourself > one were included. (If you go to wxPython's mainpage, you read "Why > the hell hasn't wxPython become the standard GUI for Python yet?", and > also "BTW, great work! I've definitively switched from Tk. I work on > Win32, anybody who works on Win32 should switch!". Comments like that. > Readers can immediately know the relationship to Tk, and wxPython's > platform friendliness for Win32.) But, those people wouldn't have used PyGTK (or GTK) before. Don't get a mind-shift just bcoz of some famous personality has said it. Usually I will try out the possiblities and then choose from the domain. > Given the lack of comparison, I > would guess that GTK is unix-friendly, since Unix people usually would > mention little or nothing about Windows. :) As I said before, look at the screenshots. Or see this, http://gtk-wimp.sourceforge.net/screenshots/ Gimp in WinXP http://gtk-wimp.sourceforge.net/screenshots/gfx/gimp-winxp.png > Continuing with my guess: > are there any caveats for using PyGTK for Windows programmers? PyGTK apps were little slow in Windows. But since the Wimp theme (http://gtk-wimp.sourceforge.net) uses native win32 api calls to draw widgets it should be pretty fair when compared to normal win32 apps. Also try the tutorial at pygtk site Also see http://developer.gnome.org And very important try Glade, the GUI builder which generates XML files which can be given to the `glade` module of pygtk to build GUI dynamically. > > --------------------------- > > Given my observations, is it fair to say: > > (a) wxPython is widely used for Windows Python programmers, and May be. But you can't say that as the best, without looking at other toolkits. I found PyGTK great. > (b) PyGTK is widely used for Unix Python programmers? GTK is widely used in the UNIX world! That's true. > regards, > > Hung Jung Happy programming. From lbates at swamisoft.com Thu Apr 1 18:46:12 2004 From: lbates at swamisoft.com (Larry Bates) Date: Thu, 1 Apr 2004 17:46:12 -0600 Subject: Method for providing a trail period on a program Message-ID: I'm searching for a good way to provide a "trail period" (something like 90 days) for a commercial application that I'm writing. I'd like something that can easily stop working 90 days after installation. Can anyone point me to something that exists already? Thanks in advance, Larry Bates Syscon, Inc. From fredrik at pythonware.com Tue Apr 20 11:41:04 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 20 Apr 2004 17:41:04 +0200 Subject: Pygame book References: Message-ID: Lucas Raab wrote: > I was at the bookstore the other day and I noticed a book that dealt with > making games with Pygame. As I recall the book title was "Game Programming > with Python." I have an interest in making games, so I was wondering if any > of you have this book and if you do, could you please give me a nice > overview and whether I should buy the book or not. here's a very brief review (or rather, a "first impressions"): http://dev.r.tucows.com/blog/_archives/2004/4/19/36769.html From franck.lepoutre at caramail.com Thu Apr 8 03:17:02 2004 From: franck.lepoutre at caramail.com (francois lepoutre) Date: Thu, 8 Apr 2004 09:17:02 +0200 Subject: why is python better than eg. smalltalk?? no one has any solid arguments! you should all go to church with all that religious talk! References: <20031028061245.12451.00000133@mb-m01.aol.com> Message-ID: <4074f954$0$5802$79c14f64@nan-newsreader-02.noos.net> > Maybe what people like is all the extra software which has > been and is being written for python, which you do not have in smalltalk? > or what is it? Pleasantly surprised to find a smalltalk user here. Smart people:) My .0002 cents on python success: 1989 - I spent a couple of intellectually rewarding weeks (holiday ones ...) with the great Park's books and a version of smalltalk:) Was no computer science by education, just basically a professional and a geek looking for a practical tool to solve problems. Tried to develop something useful. Was unable to do so. The MVC model broke my brain. But I discovered object orientation. It was a great, unique and tasty experience. 2001 - my IIS module (an ISAPI-based servlet) sometimes breaks. Will never know why... Needed something a stable and simple way out of this nightmare. Enters python, no training, no book, just a couple of hours reading online and off we go. I spat out the code code for this reasonably complex app in a couple of days, forgetting i was coding an alien syntax. But was it alien? Apache got in the way, sql engines as well, html and javascript syntax too. Python never did. Last time it happened was with visicalc back in the beginning of the eighties... My inner feeling is that python is the Esperanto, not the Latin, of computer languages. Cleaner, leaner, simpler. If you can talk a few computer languages, you're fluent in python as well. Ain't no religious matter here. Just a compelling and enduring advantage. By the way: http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&oe=UTF-8&selm=3A2DD2CA.14A5D7E2%40engcorp.com&prev=/groups%3Fq%3Dpython%2520%2522van%2520rossum%2522%2520esperanto%26hl%3Den%26lr%3D%26ie%3DUTF-8%26oe%3DUTF-8%26sa%3DN%26tab%3Dwg From colin.blackburn at durham.ac.uk Wed Apr 7 04:34:49 2004 From: colin.blackburn at durham.ac.uk (Colin Blackburn) Date: Wed, 07 Apr 2004 09:34:49 +0100 Subject: design by contract versus doctest References: <407174ea$0$5066$4d4ebb8e@news.nl.uu.net> <4072977b$0$1699$afc38c87@news.easynet.co.uk> <4072a7d3$0$23314$afc38c87@news.easynet.co.uk> <4072c7f0$0$23294$afc38c87@news.easynet.co.uk> Message-ID: On Tue, 06 Apr 2004 16:08:30 +0100, Peter Hickman wrote: > Colin Blackburn wrote: >> Aku is correct, no checks are (necessarily) made by the function in >> installed code. It is the caller's responsibility to satisfy the >> pre-conditions. > > True but the caller does not check the pre-conditions, that is done in > the called. The called does not trust the caller to get things right, > hence the contract. You have DbC completely wrong. The contract is there to be trusted. As far as I can tell you are seeing what looks like a parameter check at the start of a method and assuming that that is a defensive check against the caller providing incorrect parameters. That is not what the preconditions are. The preconditions (and other constraints) were developed early in the design process. In fact, they guided the design process. The preconditions are ultimately coded (in Eiffel) but they are not part of the implementation of the method. They are not there to check for errors in production code. They are there to specify the contract, to specify what the caller must provide for the outcome to be guaranteed. They form part of the documentation whereas the implementation code (following do in Eiffel) does not. Writers of calling code can examine the pre and post-condition to know what they must do and what they can expect if the do things right. In fact some pre-conditions cannot be expressed computationally, there are put in as comments, and so cannot be checked by the called method. It is entirely the responsibility of the caller to check that the preconditions are satisfied, by providing correct parameters, say. It might do this explicitely, or implicitely but it is the caller that must satisfy those conditions. The called routine has no responsibility to check the preconditions, in fact it has every reason to expect those preconditions to be satisfied by the caller because that *is* the contract. Colin -- From jbperez808 at wahoo.com Sun Apr 11 19:59:34 2004 From: jbperez808 at wahoo.com (Jon Perez) Date: 11 Apr 2004 23:59:34 GMT Subject: why is python better than eg. smalltalk?? no one has any solid arguments! you should all go to church with all that religious talk! References: Message-ID: Aahz wrote: > Funny that two people made the same guess, when y'all could have gotten > the correct answer by going to my personal web page. ;-) > > http://rule6.info/ Whew...! Hail and well met, friend. :-D From has.temp2 at virgin.net Wed Apr 28 14:50:52 2004 From: has.temp2 at virgin.net (has) Date: 28 Apr 2004 11:50:52 -0700 Subject: prototypes in Python [was: what is good in Prothon] References: <95aa1afa.0404280120.30176ca9@posting.google.com> Message-ID: <69cbbef2.0404281050.4dc3380e@posting.google.com> michele.simionato at poste.it (Michele Simionato) wrote in message news:<95aa1afa.0404280120.30176ca9 at posting.google.com>... > So far, I have not installed Prothon, nor I have experience with Io, Self > or other prototype-based languages. Still, from the discussion on the > mailing list, I have got the strong impression that you do not actually > need to fork Python in order to implement prototypes. It seems to me > that Python metaclasses + descriptors are more than powerful enough to > implementing prototypes in pure Python. "Metaclasses" and "prototypes"... Now there's two words that should NEVER appear in the same sentence (or even on the same planet, for that matter). Metaclasses may be Manna for complexity junkies, but they're nothing but a viciously bad joke imposed by those who ought to have known better and perpetuated by those who never will. One of the great advantages of proto-OO is it shows up metaclasses for the ludicrous code masturbation they are. As to why they're still here, lingering like the stench of long-dead rat from under the floor when they should've been shitcanned years ago... well, draw your own conclusions. (Two words of my own: "politics" and "religion".) [BTW, this is a totally generic rant; please don't think it was meant personally! It's just that, well... if there's two words guaranteed to push ALL my wrong buttons, those two are it. Anyway, - and let's get back to our scheduled program...] -- As far as doing proto-OOP in Python is concerned, you can, but it'd be a bit like doing OOP [of any flavour] in C. i.e. Not much fun. You basically have to roll your own structures and runtime support, and provide syntactic sugar via some kind of pre-processor or compiler extension if you want it to be halfway decent for users to code in. Here's a very simple, incomplete and very naive example to give you an idea of how you might start attacking it: ############################# class _DelegateStub: """Terminates the delegate chain.""" delegate = None copy = staticmethod(lambda:_DelegateStub) class Object: """This class defines the generic proto-OO object 'type' used to create all objects.""" delegate = None # kludge _dict = None # kludge def __init__(self): self.delegate = _DelegateStub self._dict = {} def __getattr__(self, name): if self._dict.has_key(name): return self._dict[name] else: return getattr(self.delegate, name) def __setattr__(self, name, value): if name in ['delegate', '_dict']: self.__dict__[name] = value else: self._dict[name] = value def copy(self): """Clone this object.""" new = Object() new.delegate = self.delegate.copy() new._dict = self._dict.copy() return new # Creating a new object from scratch: # Define object 'foo' foo = Object() foo.a = 3 foo.b = 3 foo.multiply = lambda target:target.a*target.b # Do stuff with object (note: due to lack of runtime magic, user # must pass the target object to an object's 'method' themselves): print foo.a, foo.b # --> 3 3 print foo.multiply(foo) # --> 9 # Creating a new object by cloning an existing one: # Create object 'bar' by duplicating object 'foo' bar = foo.copy() print bar.multiply(bar) # --> 9 # Object 'bar' can be modified at will: bar.a = -5 bar.c = 'hello world' print bar.c # --> 'hello world' print foo.multiply(foo) # --> 9 print bar.multiply(bar) # --> -15 # Behavioural composition through delegation: # Create object 'zib' containing method 'power' with 'bar' as its delegate zib = Object() zib.power = lambda target:target.a**target.b zib.delegate = bar print zib.c # --> 'hello world' print zib.power(zib) # --> -125 ############################# Obviously, implementing a complete proto-OO system in and atop Python's native class-OO system is going to be both tedious to use (due to lack of syntactic sugar) and slow to execute (as it's all interpreted Python code). Which is why it makes sense to start from scratch as Mark is doing, or at least fork an existing language and seriously strip down and rebuild it (which is a thought that's previously crossed my own mind, though I lack the time, patience and C skills to tacke such a project myself). From kylotan at hotmail.com Tue Apr 13 22:57:55 2004 From: kylotan at hotmail.com (Kylotan) Date: 13 Apr 2004 19:57:55 -0700 Subject: Simple discussion of python cgi approaches? References: <153fa67.0404121727.45b23c30@posting.google.com> Message-ID: <153fa67.0404131857.7956595e@posting.google.com> Steve Holden wrote in message news:... > Kylotan wrote: > > > I'm particularly confused by a few people advocating things like > > Xitami + LRWP for being very simple, yet it can't possibly be simpler > > than just dropping a cgi script into a directory, as I do with Apache, > > and the docs on LRWP > > (http://www.imatix.com/html/xitami/index12.htm#TOC114) make it look > > like I'd have to do significant rewriting of the scripts. It describes > > itself as being like FastCGI which, if true, doesn't exactly endear > > FastCGI to me either. > > > Well, you said you are looking for "alternatives or optimaizations", so > it would appear that you feel you are approaching the limits of your > simple approach. It's a very unsual solution that will be simpler, > faster and cheaper than the "obvious" one, though such solutions aren't > unheard of, even in the web world. I know. I guess I am just spoiled by the simplicity of using things like Psyco that I sometimes forget that not everything comes for free! > mod_python [...] > > The intergration is very tight, and you can write Apache handlers of all > kinds in Python. I have experimented myself with writing request > handlers, with results briefly reported at PyCON this year. It's a good > general-purpose approach for uni-processor solutions. Yet I'm guessing it requires a significant amount of special-case code to use its own API? Looking at the manual it seems non-trivial to get it to work with scripts that were originally written to consume stdin and emit to stdout. > Clearly anything that has performance benefits over CGI is likely to be > a little more difficult to get running but believe me, the extra effort > isn't that great when you consider the rewards. The main problem I face is that I don't know what platform my scripts will eventually run on. I may not have the ability to install extra software so I need to keep my scripts close to the CGI standard. That is, one file per script, using the cgi module for form processing and print for output. I don't mind having to redirect stdout or call these scripts indirectly instead of via their __main__ functions, but writing to specific APIs (beyond a small wrapper layer, of course) is not an option at the moment. So I'm hoping for simple solutions that will involve no more than a few changes to each script, whereas most of the solutions that seem to be available require me to use their own request objects, or to treat pages as callable functions within an overall page as mod_python seems to require. -- Ben Sizer From peter at engcorp.com Mon Apr 5 22:01:31 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 05 Apr 2004 22:01:31 -0400 Subject: Does Python compete with Java? In-Reply-To: References: <8b336527.0404051337.51bb4a1b@posting.google.com> <1073su4etm95p35@news.supernews.com> Message-ID: Peter Hansen wrote: > Roy Smith wrote: > >> They don't have one for Python, but I expect it would be something >> like this: >> >> You create a Foot object and call its shoot() method. The bullet >> makes a hole in your foot, but by that time you've gotten dragged into >> a huge flamewar about the relative merits of spaces vs. tabs for >> indentation and barely notice the pain. > > > See Laura's excellent > > http://groups.google.com/groups?selm=slrna0f23p.511.QnickQm%40h00104b6bfa23.ne.mediaone.net Oops! My apologies to Nick Mathewson, who actually wrote that. I have a distinct, and clearly wrong, memory of it having been authored by Laura Creighton. :-( > and also a whole thread from late 2001 > > http://groups.google.ca/groups?threadm=fPBN7.961%24zX1.1625310%40typhoon.ne.mediaone.net > > -Peter From imbosol at aerojockey.invalid Sat Apr 17 22:01:57 2004 From: imbosol at aerojockey.invalid (Carl Banks) Date: Sun, 18 Apr 2004 02:01:57 GMT Subject: Proposed PEP: Treating Builtins as Constants in the Standard Library References: <5d83790c.0404171557.3db69f48@posting.google.com> Message-ID: Raymond Hettinger wrote: > PEP: 329 > Title: Treating Builtins as Constants in the Standard Library > Author: Raymond Hettinger > Status: Pre-PEP > > > Abstract > ======== > > This proposal is to add a private function for treating builtin > references as constants and to apply that function throughout > the standard library. Two things: 1. The new _bind module needs to have a more specific (and appropriate) name than _bind. The function in the module could still be named bind, but the module itself should be named something like _optimize_globals_as_consts_very_unsafe (Ok, but you get the idea.) 2. The module being optimized should have a special attribute, say __variable__, that identifies any globals that should not be optimized in this way: __variable__ = ['global_that_might_change'] Other than that, +1. I'm definitely in favor of optimization hacks whenever it doesn't intrude too much on the code. It would be nice if it were safer. -- CARL BANKS http://www.aerojockey.com/software "If you believe in yourself, drink your school, stay on drugs, and don't do milk, you can get work." -- Parody of Mr. T from a Robert Smigel Cartoon From daniel at dittmar.net Thu Apr 22 15:17:37 2004 From: daniel at dittmar.net (Daniel Dittmar) Date: Thu, 22 Apr 2004 21:17:37 +0200 Subject: AOP use cases In-Reply-To: References: <84fc4588.0404140106.3fa0c55@posting.google.com> <0pydnSB4WYuieuLdRVn-hQ@powergate.ca> Message-ID: Jacek Generowicz wrote: > Not really. By separation of concerns I mean: I know you meant 'separation of concers as defined by AOP'. But saying 'AOP allows separation of concerns as defined by AOP' is somewhat circular. > Stupid example: Why not use an intelligent example instead? LISP had before and after methods for ages, so there should be plenty of examples. Daniel From peter at engcorp.com Thu Apr 22 11:37:35 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 22 Apr 2004 11:37:35 -0400 Subject: Python use large scale projects In-Reply-To: References: <47fc6058.0404212327.24163290@posting.google.com> Message-ID: Larry Bates wrote: > I should point out that I have 30+ years of experience > and have learned many languages over the years, so I'm > not a language bigot. I just want something that makes > me productive and that produces reliable programs that > are HIGHLY maintainable. Maintenance becomes 80% of the > problem after an application is developed. Python fits > that bill for me. Beautiful post, Larry. You're speaking for many of us... From alloydflanagan at comcast.net Thu Apr 29 10:01:30 2004 From: alloydflanagan at comcast.net (A. Lloyd Flanagan) Date: 29 Apr 2004 07:01:30 -0700 Subject: Is classless worth consideration References: <69cbbef2.0404290259.fd8d71c@posting.google.com> Message-ID: has.temp2 at virgin.net (has) wrote in message news:<69cbbef2.0404290259.fd8d71c at posting.google.com>... > > Well, as far as Python itself is concerned, it'd go a long way in > eliminating the hideously baroque and increasingly brittle OO model it > currently has. But that's by-the-by; the real problem isn't with > Python itself but in the "we Python programmers". > I wouldn't call it "hideously baroque", myself. Yes, there are some details that need to be cleaned up (and when do we get a target date for Python 3?). On the other hand, for most programming most of the time, it's pretty straightforward. Of course, I'm a C++ expert, so my standard of what qualifies as "baroque" is probably pretty high. :) None of which means I don't think your approach isn't interesting and worth pursuing. I look forward to seeing how it goes. From noemail at noemail4u.com Wed Apr 21 07:31:15 2004 From: noemail at noemail4u.com (Daniel 'Dang' Griffith) Date: Wed, 21 Apr 2004 11:31:15 GMT Subject: AOP use case? (was Re: Proposed PEP: Treating Builtins as Constants in the Standard) References: <5d83790c.0404171557.3db69f48@posting.google.com> <097808fe24c7cc9771e446d5bddfe91d@news.teranews.com> Message-ID: On Tue, 20 Apr 2004 10:33:36 -0400, Peter Hansen wrote: >Daniel 'Dang' Griffith wrote: > >> On Mon, 19 Apr 2004 08:09:56 -0400, Peter Hansen >> wrote: >> ... >>>automated testing. The most easily demonstrated one is where >>>the builtin open/file calls are replaced with a simulated ("mock") >>>file system which applies to *all* modules, not just a single >>>module under test. This functionality is critical to some people >>>using Python with the Test-Driven Development approach to software. >> >> Isn't this the use case for AOP you were looking for? >> --dang > >As you might imagine from my previous postings, I have no idea. >I don't understand well enough what AOP really is to say, >obviously (given my requests for compelling use cases so I can >understand why I would even want to investigate it). > >Can you describe how AOP would solve this problem? As I >understand it so far, it has nothing to do with mock objects... Probably not. I'm not an "AOP person", but from what I understand, you could use an AOP-enabled language to replace the real file system (or whatever) objects with the mock objects. This is roughly analagous to the standard logging or auditing examples, wherein a program is doing what it needs to do, meanwhile a cross-cutting aspect intercepts certain operations and performing additional, or different, operations. --dang From hwlgw at hotmail.com Thu Apr 15 05:10:37 2004 From: hwlgw at hotmail.com (Will Stuyvesant) Date: 15 Apr 2004 02:10:37 -0700 Subject: Aspect Programming Module References: <84fc4588.0404140106.3fa0c55@posting.google.com> Message-ID: > [Joe Mason] > > "AOP is a contrived way to get around the limitations of a statically > > typed language." > > Care to explain that? What I've seen of AOP seems like a very dynamic > design philosophy. Dynamic indeed. And that is a problem for statically types programming languages like Java. To add logging capabilities to an instance object of a Python class you simply add a function/method that does the job. Add it as an attribute to the object itself, or to the object's __class__, or to anything else you can get at via the object and its attributes. You can not do that in Java because the Java class definition is "fixed", you can't change it. But they still want to do it, so they use a complex AOP framework to do it in. From peter9547 at btinternet.com Sat Apr 3 13:19:05 2004 From: peter9547 at btinternet.com (Peter MacKenzie) Date: Sat, 3 Apr 2004 18:19:05 +0000 (UTC) Subject: emergent/swarm/evolutionary systems etc References: <2de080a12a9c6c488149f4b031bb46be@news.teranews.com> Message-ID: I think then that I might stick with spreadsheets as far a possible. Do you know of any simulation programs that might be more suited? Also, how would you extract data from a spreadsheet for use in another program? I'm not familiar with means of linking spreadsheets to external applications, though I don't doubt that it can be done. From andymac at bullseye.apana.org.au Sat Apr 10 20:27:18 2004 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Sun, 11 Apr 2004 10:27:18 +1000 (EST) Subject: Wrapper round x86 Assembler In-Reply-To: <8089854e.0404100204.504186a0@posting.google.com> References: <8089854e.0404082353.7bf163a2@posting.google.com> <4dKdnQlIXMIXIevdRVn-gg@powergate.ca> <8089854e.0404100204.504186a0@posting.google.com> Message-ID: <20040411100719.D28686@bullseye.apana.org.au> On Sat, 10 Apr 2004, Fuzzyman wrote: > *However* it's not quite what I had in mind. What I'd like to be able > to do is to access machine code subroutines from within normal python. > > Not that exploring pyrex is a bad idea - I probably should. > I don't think my 'idea' would be hard to achieve, since effectively > all that would be needed is a wrapper to an existing freeware > assembler *and* an interface to the assembled 'objects'. Ho hum - a > bit beyond me at the moment and until I have a real burning need for > it will have to remain an idea...... At the moment you have several alternatives available that I can see: - build your assembly routines into a DLL/.so and use Thomas Heller's excellent ctypes module. - build your assembly routines into a library or DLL/.so and use Pyrex to call them. - find a C compiler that understands how to build asm files to objects, then tweak the Distutils support to call the compiler when it an assembly source file is included in a Distutils'ified package. On Windows MinGW should get the job done; gcc can do so for posix platforms. - do it the old fashioned way: create a makefile that builds the components and links to the Python core. If you want to avoid dealing with the necessary Python C API boilerplate required to allow Python to call your routine, you'll find the ctypes solution by far the easiest as your code only has to have a calling interface compatible with a C compiler. The Pyrex solution could work as well, but introduces an extra language layer into the situation. The other 2 approaches require that your code deals with the Python C API, and you would have to create the necessary include files to replicate "Python.h" appropriately. The only downside to the ctypes approach may be performance, as each call may have a high overhead cost compared to the other approaches. -- 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 herrn at gmx.net Mon Apr 5 16:43:26 2004 From: herrn at gmx.net (Marco Herrn) Date: 5 Apr 2004 20:43:26 GMT Subject: regex help for a newbie References: Message-ID: On 2004-04-05, Diez B. Roggisch wrote: > def parse(input): > res = "" > level = 0 > for c in input: > if c == "(": > level += 1 > elif c == ")": > level -= 1 > if level > 0 and c != "(": > res += c > return res Thanks, that helped a lot. I had to rewrite it a bit, but now it works. Many Thanks. Marco -- Marco Herrn herrn at gmx.net (GnuPG/PGP-signed and crypted mail preferred) Key ID: 0x94620736 From michael at foord.net Fri Apr 16 09:30:25 2004 From: michael at foord.net (Fuzzyman) Date: 16 Apr 2004 06:30:25 -0700 Subject: Wrapper round x86 Assembler References: <8089854e.0404082353.7bf163a2@posting.google.com> <4dKdnQlIXMIXIevdRVn-gg@powergate.ca> <8089854e.0404100204.504186a0@posting.google.com> <8089854e.0404122329.5dfe5ce1@posting.google.com> <8089854e.0404132323.3283390@posting.google.com> <8089854e.0404141105.37d09320@posting.google.com> Message-ID: <8089854e.0404160530.5b7c23aa@posting.google.com> Greg Ewing wrote in message news:... > Fuzzyman wrote: > > The only compielr I have is gcc under mingw - and I'm not at all sure > > it's set up right. Does pyrex still need a C-compiler or *is* pyrex a > > compiler ? > > It needs a C compiler. MinGW should be fine > (once you get it set up properly, anyway:-). Yeah - I'm having great fun getting it set up. MinGW seems easy enough to install - I've even compiled example C programs with gcc - but getting disutils to use it is another matter... Regards, Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html From arigo at tunes.org Sat Apr 3 19:53:05 2004 From: arigo at tunes.org (Armin Rigo) Date: Sun, 4 Apr 2004 00:53:05 +0000 (UTC) Subject: Python is faster than C References: <406F0907.96F37EA1@tunes.org> <7xy8pcogaa.fsf@ruckus.brouhaha.com> <406F454B.C4CC8063@tunes.org> <7xekr4vdek.fsf@ruckus.brouhaha.com> Message-ID: <406F5E95.EBE6D3E8@tunes.org> Paul Rubin wrote: > I think you're saying that instead of having xrange return a special > object, range should return that special object instead. I'm not too > clear on the distinction. No, range should return an object that is a list, as far as you can tell from Python, but which is represented more efficiently than an array of objects internally. The distinction is between the language level (it would be a list, with all operations, etc.) and the implementation (there is no reason why all lists should be arrays of PyObjects internally). Another example would be 'a'*999999999: the result is a string, but there is no reason that it takes 100MB of memory. Instead, store it into a C structure that contains a pointer to the original string object 'a' and the repetition counter, but still give this C structure the Python type str, so that the difference doesn't show up and the Python language remains simple. (This is a bit difficult to implement currently in CPython, but not impossible.) > Also, how can the compiler or interpreter > know whether the program will only access the object sequentially? > It has to predict the behavior of the program, instead of being told > explicitly. Ideally: If you do x=range(100); x[50]='hi' then the interpreter first builds this optimized range representation and assigns it to x; and when in the next statement you modify this list x it says 'oops! i cannot do that with this representation', so it reverts to an array-like representation (i.e. it creates all 100 elements) and then changes the 50th. No gain here. If on the other hand you only ever do 'easy' things with your list, like iterate over it or read elements, then it can all be done with the range representation, without falling back to the array representation. Again I'm not saying it is trivial to implement it, but that not having to expose for optimization purposes 'xrange' and the whole 'iterator' part of the language would be worth it, in my opinion. Armin From grante at visi.com Thu Apr 29 13:07:27 2004 From: grante at visi.com (Grant Edwards) Date: 29 Apr 2004 17:07:27 GMT Subject: Don't understand wxPython ids References: <408ed938$0$17263$a1866201@newsreader.visi.com> <408f3061$0$17258$a1866201@newsreader.visi.com> <408fb665$0$17264$a1866201@newsreader.visi.com> <40913150$0$17257$a1866201@newsreader.visi.com> Message-ID: <4091364f$0$30295$a1866201@newsreader.visi.com> On 2004-04-29, Grant Edwards wrote: >> #yourmodule.py >> import wx >> from event_kwargs import * > > Hmm. I guess it's time to upgrade to 2.5. I guess not. It appears it would require upgrading so many other things it would probably take at least a week or two. :( -- Grant Edwards grante Yow! I just heard the at SEVENTIES were over!! And visi.com I was just getting in touch with my LEISURE SUIT!! From elainejackson7355 at home.com Mon Apr 26 00:05:25 2004 From: elainejackson7355 at home.com (Elaine Jackson) Date: Mon, 26 Apr 2004 04:05:25 GMT Subject: Trouble Understanding O'Reilly Example References: <108p21f7asq1cc8@corp.supernews.com> Message-ID: <9U%ic.260962$Ig.239971@pd7tw2no> This is one of those "V8 bugs" that make you smack your forehead: line 4 of the function definition should read " if arg < res: ". Fix that, and everything works as expected. "slyraymond" wrote in message news:108p21f7asq1cc8 at corp.supernews.com... | On page 214 of _Learning Python_, the following function is described as one | that will return the smallest item in a group of arguments: | | def min1(*args): | res = args[0] | for arg in args[1:]: | if arg < args: | res = arg | return res | | However, when the function called with... | | print min1(3,4,1,2) | | ...it returns: | | 2 | | Why? From lac at strakt.com Tue Apr 13 02:20:07 2004 From: lac at strakt.com (Laura Creighton) Date: Tue, 13 Apr 2004 08:20:07 +0200 Subject: Estimating the Airspeed Velocity of an Unladen Swallow Message-ID: <200404130620.i3D6K7Ze009713@ratthing-b246.strakt.com> Somebody has done it. http://www.style.org/unladenswallow Laura From JasonHarper at pobox.com Mon Apr 5 08:43:16 2004 From: JasonHarper at pobox.com (Jason Harper) Date: Mon, 05 Apr 2004 05:43:16 -0700 Subject: Working with bytes. References: <406EE606.4000604@yahoo.com> <406f33b6$0$30963$3a628fcd@reader1.nntp.hccnet.nl> <4071273d$0$132$3a628fcd@reader1.nntp.hccnet.nl> Message-ID: <4071539F.718DBD1A@pobox.com> Anton Vredegoor wrote: > I wonder whether it would be possible to use more than six bits per > byte but less than seven? There seem to be some character codes left > and these could be used too? Look up Base85 coding (a standard part of PostScript) for an example of how this can be done - 4 bytes encoded per 5 characters of printable ASCII. Jason Harper From fidtz at clara#spam#.co.uk Thu Apr 8 07:11:02 2004 From: fidtz at clara#spam#.co.uk (DomF) Date: Thu, 8 Apr 2004 12:11:02 +0100 Subject: what is happening here? References: Message-ID: <1081422537.1714.0@ersa.uk.clara.net> "dan miller (moderator, s.p.d)" wrote in message news:c4vaum$q39$1 at nntp.ece.cmu.edu... > trying to figure out scoping of 'globals' in modules. So I have test.py: > > glob = 1 > > def setglob(v): > global glob > glob = v > > def getglob(): > return glob > > > and I do this: > > >>> from test import * > >>> glob > 1 > >>> getglob() > 1 > >>> glob=2 > >>> glob > 2 > >>> getglob() > 1 > >>> setglob(3) > >>> getglob() > 3 > >>> glob > 2 > > > Seems to me like the first time I invoke glob, it creates a new global > in my namespace, and initializes it to the value of the glob in test.py. > Seems counterintuitive! This is an instance of "from x import *" being harmful. Try this with just "import test" in the shell and it doesn't look confusing at all: >>> import test >>> glob Traceback (most recent call last): File "", line 1, in ? NameError: name 'glob' is not defined >>> test.glob 1 >>> test.getglob() 1 >>> glob=2 >>> glob 2 >>> test.getglob() 1 >>> test.setglob(3) >>> test.getglob() 3 >>> glob 2 Dom From nicolas.lehuen at thecrmcompany.com Thu Apr 22 10:53:55 2004 From: nicolas.lehuen at thecrmcompany.com (Nicolas Lehuen) Date: Thu, 22 Apr 2004 16:53:55 +0200 Subject: This is very simple question References: <108dbd1aftmkc48@corp.supernews.com> <4087a0f6$0$25552$afc38c87@news.easynet.fr> <108fl7h8oocmm5c@corp.supernews.com> Message-ID: <4087dc83$0$24703$afc38c87@news.easynet.fr> > > return result.reverse() # if you really want it reversed > > I agree that divmod() improves the algorithm, and thank > you for pointing that out. > > I'm reasonably certain that the return value of reverse() > is not what you believe it to be. > -- > > Cameron Laird > Business: http://www.Phaseit.net Ooops indeed, reverse() always returns None, because the reverse is made in place. I did test the program without the reverse, so I missed this mistake. Thanks ! BTW, I've been bitten by this behaviour a lot since I've switched to Python a year ago (coming from C++ and Java)... I would feel much better if reverse(), sort() and so on returned the list itself ; but then maybe other people would think the reversing/sorting etc. would not be done in place... Regards, Nicolas From has.temp2 at virgin.net Thu Apr 29 16:54:58 2004 From: has.temp2 at virgin.net (has) Date: 29 Apr 2004 13:54:58 -0700 Subject: Is classless worth consideration References: <69cbbef2.0404290259.fd8d71c@posting.google.com> Message-ID: <69cbbef2.0404291254.166f5da@posting.google.com> alloydflanagan at comcast.net (A. Lloyd Flanagan) wrote in message news:... > > Well, as far as Python itself is concerned, it'd go a long way in > > eliminating the hideously baroque and increasingly brittle OO model it > > currently has. > > I wouldn't call it "hideously baroque", myself. Yes, there are some > details that need to be cleaned up (and when do we get a target date > for Python 3?). On the other hand, for most programming most of the > time, it's pretty straightforward. > > Of course, I'm a C++ expert, so my standard of what qualifies as > "baroque" is probably pretty high. :) :) > None of which means I don't think your approach isn't interesting and > worth pursuing. I look forward to seeing how it goes. Prothon isn't my baby but Mark Hahn's - see . (FWIW, I also consider Prothon's OO programming model unnecessarily complex in its current state, but it's still early days so who knows.) As for seeing any language projects of my own, well I do have an idea of two I'm just getting started on. But I'd not hold my breath if I were you, as I'm a rather slow worker. :) From pje at telecommunity.com Wed Apr 21 19:08:50 2004 From: pje at telecommunity.com (Phillip J. Eby) Date: Wed, 21 Apr 2004 19:08:50 -0400 Subject: PEP 329 and bytecode hacking In-Reply-To: Message-ID: <5.1.1.6.0.20040421190433.01fe20c0@telecommunity.com> At 03:58 PM 4/21/04 -0700, Robert Brewer wrote: >Phillip J. Eby wrote: > > At 03:07 PM 4/21/04 -0700, Robert Brewer wrote: > > >Raymond's cookbook recipe inspired me to write a generic Visitor for > > >inspecting and rewriting bytecode. Maybe it'll help someone out there > > >with prototyping bytecode hacks. > > > > For more sophisticated bytecode modifications, you'll want to > > keep track of > > things like source line number, the nth instruction and its > > operand if any > > (so you can scan *backwards*), the list of locations of a > > given opcode, > > etc. This Pyrex module: > > > > >http://cvs.eby-sarna.com/PEAK/src/peak/util/_Code.pyx?rev=1.2&content-ty >pe=text/vnd.viewcvs-markup > > provides high-speed dynamic access to bytecode metadata, and is >suitable > > for use in runtime bytecode hacks, since it does not require Python > > function call overhead for each instruction. > >Good idea! I'll work on including that. It's not as context-sensitive as >visiting each opcode in turn, but sometimes no context is good context. You can visit items in turn using something like: i = 0 while True: opcode,operand = idx.opcode(i), idx.operand(i) i+=1 Or, if you have a more recent version of Pyrex than the above code was built for, you can make the 'length' attribute public (i.e. 'cdef public length') and use: for i in range(idx.length): opcode,operand = idx.opcode(i), idx.operand(i) From jepler at unpythonic.net Wed Apr 21 08:22:59 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 21 Apr 2004 07:22:59 -0500 Subject: Python GUI wrapper for a long operation In-Reply-To: <108cnp89aedqp82@corp.supernews.com> References: <9396ba6f.0404160520.364699c4@posting.google.com> <108cnp89aedqp82@corp.supernews.com> Message-ID: <20040421122259.GA9864@unpythonic.net> To interleave calculation and GUI activity in the same thread, simply call the "update_idletasks" or "update" method on any Tk widget at intervals. update_idletasks() will do things like repaint windows that have been uncovered or resized, or when the information displayed on a widget has changed. update() will handle all events, just like mainloop(), but returns as soon as there's no longer an event to handle. Jeff from Tkinter import * import time class StupidProgress(Label): def __init__(self, master): Label.__init__(self, master, text="0%") def progress(self, percent): self.configure(text="%s%%" % percent) self.update() abort = 0 def calculation(): b.configure(state=DISABLED) c.configure(state=NORMAL) for i in range(100): print "calculation" time.sleep(.1) # represents doing .1 second of calculation if check_abort(): b.configure(state=NORMAL) c.configure(state=DISABLED) l.progress(0) return l.progress(i) l.progress(100) c.configure(state=DISABLED) m.configure(text="Result: 42") def check_abort(): global abort if not abort: return 0 abort = 0 return 1 def do_abort(): global abort abort = 1 app = Tk() l = StupidProgress(app) m = Label(app, text="(No result)") b = Button(app, command=calculation, text="Find answer") c = Button(app, command=do_abort, text="Never mind", state=DISABLED) l.pack() m.pack() b.pack() c.pack() app.mainloop(); From Bill.Scherer at VerizonWireless.com Fri Apr 16 07:08:55 2004 From: Bill.Scherer at VerizonWireless.com (Bill Scherer) Date: Fri, 16 Apr 2004 07:08:55 -0400 Subject: Python 2.3 on RedHat 9 In-Reply-To: References: Message-ID: <407FBEC7.6040103@VerizonWireless.com> simo wrote: >Bill Scherer wrote: > > > >>>Did you install on top of Python 2.2 or did you install in a separate >>>directory (eg the default)? >>> >>> > > > >>2.3 prefix is /usr/local, RedHat's installed python prefix is /usr >> >> > >Yes, and that seems to be the root of all evil for me - everything I >install wants to go into the /usr//python2.2 directories >instead of /usr/local//python2.3! > >Forget the RPMs, > Many RPM's are relocatable; from the rpm man page: --prefix NEWPATH For relocateable binary packages, translate all file paths that start with the installation prefix in the package relocation hint(s) to NEWPATH. --relocate OLDPATH=NEWPATH For relocatable binary packages, translate all file paths that start with OLDPATH in the package relocation hint(s) to NEWPATH. This option can be used repeatedly if several OLDPATH?s in the package are to be relocated. >compile everything from source is my advice (I >installed 2.3.3, VPython, Installer, wxPython, PyQt, SIPs, >wxGlade....) > >What annoyed me was when I was evaluating LindowsOS and "apt-get >install libwxgtk24" installed everything for me (including Python >2.3.3!) in about 3 minutes as apposed to about 8 hours of compilation >time and hunting around for source tarballs! It was even easier that >Windows I think! > I too compille most of the Python add-ons I use. It's never taken 8 hours....it must be the 3Ghz cpu...;-) From daniel at syrinx.net Sat Apr 10 23:08:25 2004 From: daniel at syrinx.net (Daniel Ellison) Date: Sat, 10 Apr 2004 23:08:25 -0400 Subject: why is python better than eg. smalltalk?? no one has any solid arguments! you should all go to church with all that religious talk! References: Message-ID: "Jon Perez" wrote in message news:c5acf1$2nlp5a$1 at ID-180326.news.uni-berlin.de... > Aahz wrote: > > > I found my editor fifteen years ago. Guess which it is. (The point > > being that there are only two editors still in regular use that were > > available fifteen years ago -- and those two editors are still ubiquitous > > now. Doesn't matter much which you pick, they'll still be available > > fifteen years in the future.) > > YEAAARRGGGHHH!!! An Emacs user... stay away from me, you satanist!!!! > > ;-) hehe j/k... Yes, who in their right mind would use emacs when there's a perfectly good alternative in vi? From surrender_it at remove.yahoo.it Tue Apr 27 02:34:55 2004 From: surrender_it at remove.yahoo.it (gabriele renzi) Date: Tue, 27 Apr 2004 06:34:55 GMT Subject: Is Perl *that* good? References: <108q51j4dscn7dc@corp.supernews.com> Message-ID: il Mon, 26 Apr 2004 19:52:28 -0700, Michael ha scritto:: >I've wondered if there is really a reason why a single language >processor couldn't be made that Perl, Python, PHP, etc could all be >compiled into. that is the parrot, the perl6 VM I believe :) From jepler at unpythonic.net Wed Apr 21 08:44:16 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 21 Apr 2004 07:44:16 -0500 Subject: from newbie: how specify # of times to invoke a regex; conv tuple to string In-Reply-To: <40866ae1$1@news.bezeqint.net> References: <40866ae1$1@news.bezeqint.net> Message-ID: <20040421124415.GC9864@unpythonic.net> Instead of .findall(), you could use .finditer() and only consume a few results. Otherwise, you can write your own code to use the 2-arg version of .search() to start at the first position after the end of the previous match. If you want to take the tuple t = ('e', '', '8', '.') and get the string s = 'e8.' you want s = ''.join(t) Jeff From rob at nospam.net Sat Apr 17 06:42:49 2004 From: rob at nospam.net (Robert Ferber) Date: Sat, 17 Apr 2004 12:42:49 +0200 Subject: (For gurus) Embed functions in webpages like in PHP? References: <5eq4l1-9vm.ln1@pilz.hasos.com> Message-ID: <93f7l1-hns.ln1@pilz.hasos.com> Thomas Guettler wrote: > Am Fri, 16 Apr 2004 12:38:16 +0200 schrieb Robert Ferber: > >> Hi, >> >> I'm a PHP-programmer who evaluates Python for a new project. >> I really like a lot of concepts of Python, especially the shell, but >> there is one great feature of PHP which I don't know how to replace in >> Python: >> >> For database-intensive webpages, I like to cache the HTML-output on the >> fly in the filesystem and put out the file later whenever the same URL is >> requested again, for example: > > The problem with caching: When is > the data outdate? Currently I just use the file creation date. I set it for example 2 weeks into the future and whenever the creation date is in the past it is assumend out of date. > You could use this approach: > Run a cron-job every hour which does the complicated > query which needs long to compute. Dump > the result into a file (Look for "pickle" > in the module index of the docs). That wouldn't work, in fact it would make matters worse. First of all, I couldn't have different times for caches to get out of date, then, more importantly, I'd have to run it for every possible combination at once, for example for script.php?a=1&b=2&c=3, I'd have to do all combinations for a, b and c which could lead to thousands, sometimes millions of combinations. Also, there is no way to know which values of a, b and c are even possible, so I wouldn't even know what to generate. -- Harte Arbeit zahlt sich sp?ter mal aus. Faulheit sofort! From bo at systemhouse.dk Tue Apr 20 16:22:51 2004 From: bo at systemhouse.dk (Bo Jacobsen) Date: Tue, 20 Apr 2004 22:22:51 +0200 Subject: How to get the ip addresses of a nic Message-ID: Is there a simple way to get all the ip addresses of a nic, beyound parsing /etc/sysconfig/..... ------------------------------------------------- Bo Jacobsen From franck.lepoutre at caramail.com Wed Apr 21 05:56:01 2004 From: franck.lepoutre at caramail.com (francois lepoutre) Date: Wed, 21 Apr 2004 11:56:01 +0200 Subject: Paris python user group? Message-ID: <408795ee$0$25893$79c14f64@nan-newsreader-02.noos.net> Hi all french speaking, Paris-based python users, Bonjour ? tous les utilisateurs parisiens de python, How many are we to use python in the *Paris* Area? Enough to build some community life? Combien sommes nous ? utiliser python sur Paris? Assez pour monter une assoc? Two years ago i discovered perl and, by the way, their cheerfull and welcoming Paris user community http://paris.mongueurs.net/ Il y a deux ans, j'ai d?couvert perl et, par la m?me occasion, la chaleureuse ambiance des perl mongueurs de Paris Informal meeting at "La Taverne R?publique" 5, place de la R?publique every month. Socialising, a few drinks, some food (pizzas available for die-hard... but most would stick to moules-frites:) Une r?union informelle ? la "Taverne R?publique" 5, place de la R?publique chaque mois. Une ambiance decomplex?e, quelques boissons et des moules-frites (pizzas pour les accros). Great hours re-shaping IT late from 8pm into the night... but I have since switched to python. Des heures agr?ables ? refaire notre industrie ? partir de 8 heures du soir ... Mais depuis je suis pass? ? python. Anyone to join for a "Paris python user group"? Des volontaires pour un groupe parisien ? Same place, same programme, but there's room for negociation, both for the drink and the food :) Nous proposons le m?me lieu et la m?me formule mais nous sommes pr?ts ? discuter :) Fran?ois et Jean From mark at prothon.org Fri Apr 23 16:50:24 2004 From: mark at prothon.org (Mark Hahn) Date: Fri, 23 Apr 2004 13:50:24 -0700 Subject: Why we will use obj$func() often References: <84Uhc.22278$dZ1.5087@fed1read04> <8AWhc.23114$dZ1.11070@fed1read04> <40883BFE.B381518A@alcyone.com> <27_hc.23801$dZ1.2716@fed1read04> <40887145.789A2FE8@alcyone.com> <7cki80hj976bia36lhf9er97v073o1pqvm@4ax.com> Message-ID: "Mel Wilson" wrote in message news:ulXiAls/KH1K089yn at the-wire.com... > It can, if you spell '&' differently: > > def getfunc(): > def count (n=[0]): > n[0] += 1 > print n[0] > return count > > c = getfunc() > c() > c() > c() True. A bit inelegant, but then so is &. Would you trade the "mutable integer" and "count(n=[0])" kludges for a solution like &count ? Does anyone agree with me that a "closure variable prefix" is more explicit and readable? Let's seperate the aesthetic issues of using "Perl-like" symbols from the "closure variable prefix" functionality for a moment. I'd like feedback on both issues, but try to keep them seperate. From db3l at fitlinxx.com Wed Apr 7 13:04:25 2004 From: db3l at fitlinxx.com (David Bolen) Date: 07 Apr 2004 13:04:25 -0400 Subject: Are line continuations needed? References: <407409ef.82801353@news.eircom.net> Message-ID: Peter Maas writes: > Just had this example: > > d = { 'key1' : 'A very very long string of several hundred '\ > 'characters. I could use a multi-line string but '\ > 'then either left white space would be part of the '\ > 'string or I would have to align it at column 0 '\ > '(ugly). I could embed it into a pair of brackets '\ > 'but I see no advantage over \\. Finally I could '\ > 'put this string on a single line (also ugly and hard '\ > 'to read).' > ... > } Actually that's unnecessary since you are already in a braced expression from the dictionary constructor. So the lines are implicitly continuation lines until you close the dictionary, and the compilers combination of adjacent string constants still works. You can drop the continuation characters and it'll give the same dictionary. I tend to construct parenthetical expressions if I can to avoid the explicit line continuation character - mostly since I think it looks nicer, but there are some cases where I prefer the contination. There's normally an alternative to the continuation, but one that I don't consider as readable. For example, one place where I've used line continuations was in explicit from imports, such as: from some.package.exceptions import ExceptionName, OtherName, \ AnotherName, AndAnotherName where I find this more readable than repeating the "from import" portion of the line multiple times. I also use it to suppress leading newlines in triple quoted strings, while permitting me to write the entire string at the same indent level, e.g.: MSG = """\ blah blah blah and some more blah blah blah """ I'll also use it sometimes for string formatting operations (either standalone or as part of print) where sometimes I think it looks nicer than putting the entire expression in parenthesis), e.g.: some_variable = 'This is a formatting string args %s %s %s' % \ (argument1, argument2, argument3) -- David From jeffbarish at starband.net Tue Apr 6 12:02:34 2004 From: jeffbarish at starband.net (Jeffrey Barish) Date: Tue, 06 Apr 2004 10:02:34 -0600 Subject: CSV ignores lineterminator References: <16497.47126.723619.586429@montanaro.dyndns.org> <16497.52305.246261.519498@montanaro.dyndns.org> Message-ID: Skip Montanaro wrote: > > Jeffrey> Yes, I expect your example to work because each entry in > the Jeffrey> list defines a "line" regardless of csv: > ... > Jeffrey> In my example, the first "line" of the list is > Jeffrey> 'word1\tword2;word3\tword4'. What I expect to happen is > that Jeffrey> the list passes the entire line to csv.reader(), > which then Jeffrey> splits off 'word1\tword2' as the first line by > virtue of the Jeffrey> presence of the lineterminator ';' and then > continues to scan Jeffrey> what remains. > > I haven't the time to think deep thoughts about this problem at the > moment. You might want to post to the csv mailing list > (csv at mail.mojam.com) and see if one of the other csv folks can provide > a more coherent/accurate answer. > > Skip > For the record, the answer that I got back from one of the developers is that lineterminator is used only for output. -- Jeffrey Barish From bignose-hates-spam at and-benfinney-does-too.id.au Thu Apr 22 23:57:13 2004 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 23 Apr 2004 13:47:13 +0950 Subject: Why we will use obj$func() often References: <84Uhc.22278$dZ1.5087@fed1read04> <8AWhc.23114$dZ1.11070@fed1read04> <40883BFE.B381518A@alcyone.com> <27_hc.23801$dZ1.2716@fed1read04> <40887145.789A2FE8@alcyone.com> Message-ID: On Thu, 22 Apr 2004 20:31:41 -0700, Mark Hahn wrote: > "Erik Max Francis" wrote: >> Seriously considering every single possible proposal is not >> constructive. >> [...] >> Without a strong sense of what the language should look >> like, Prothon is going to continue to look more and more like Perl. >> It's already most of the way there. > > Please hold off your ad hominem attacks until the product is designed, > thank you very much. Please understand what an ad hominem attack is before accusing others of using it, thank you very much: Erik's assertions were relating to the topic, not to your person or circumstances. They were not argumentum ad hominem. -- \ "If you go to a costume party at your boss's house, wouldn't | `\ you think a good costume would be to dress up like the boss's | _o__) wife? Trust me, it's not." -- Jack Handey | Ben Finney From Mike at DeleteThis.Geary.com Wed Apr 7 17:28:57 2004 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Wed, 7 Apr 2004 14:28:57 -0700 Subject: Are line continuations needed? References: <1078dq6i93pc12d@news.supernews.com> Message-ID: <1078skqn9hgdd19@corp.supernews.com> John Roth wrote: > [Backslash line continuations are], I believe, planned for > removal in 3.0. Remember that 3.0 will break everything > anyway: it's the release for incompatible changes. If this is true, it will put Python at a disadvantage compared to Perl with regard to multiline strings. I thought David Bolen's example was pretty compelling. Without the backslash continuation, you're forced to write multiline strings with the first line indented differently from the rest of the lines: mystring = """first line second line third line""" Yuck. Backslash continuation fixes this, as David showed: mystring = """\ first line second line third line""" Maybe there will be some other way to do clean multiline strings in Python 3.0? -Mike From fd1 at gmx.org Fri Apr 9 17:55:43 2004 From: fd1 at gmx.org (Frank Dieckmann) Date: Fri, 09 Apr 2004 23:55:43 +0200 Subject: Python-2.3.3 install -> no "make" References: <2278156.F9pO2Pa3OA@Lumina-verte.org> <3kEdc.3041$VE5.900@lakeread01> Message-ID: <1619307.OB8hk4TKzy@Lumina-verte.org> Steve Holden wrote: > Frank Dieckmann wrote: >> Unpacking was fine, >> ./configure seems to be too, > > If you don't have "make" then you need to install some development > packages. "make" is the utility that uses the Makefile to build the > software. > > Steve Thank you, Steve and Jeff Epler! I have shown that I am a newbe with Linux... Your hint was right! I installed 'make' and than insalled Python successfully. Juchee, like we say in German (something like 'Yippee') Frank From peter at luciak.org Sat Apr 24 14:54:03 2004 From: peter at luciak.org (Peter Luciak) Date: Sat, 24 Apr 2004 20:54:03 +0200 Subject: ioctl(2) ? Message-ID: <20040424185403.GA1383@avalon> Hi, is there any way to do a ioctl in python? I didn't find it in the os module... Thanks, P. -- Peter `cuco' Luciak jabber://cuc0 at jabber.sk peter at luciak.org http://www.luciak.org/ Canadian: An unarmed American with health care. From tkpmep at hotmail.com Fri Apr 16 12:50:00 2004 From: tkpmep at hotmail.com (Thomas Philips) Date: 16 Apr 2004 09:50:00 -0700 Subject: Learning about dictionaries Message-ID: I'm teaching myself python and in the course of playing around with dictionaries, I tried to create the following trivial dictionary {1:'one', 2:'two'} So I entered >>> dict(1='one',2='two') SyntaxError: keyword can't be an expression As this did not work, I tried >>> dict(1=one,2=two) SyntaxError: keyword can't be an expression and >>> dict('1'='one','2'='two') SyntaxError: keyword can't be an expression as well as >>> dict('1'=one,'2'=two) SyntaxError: keyword can't be an expression Out of curiosity, I tried >>> dict(one=1,two=2) {'two': 2, 'one': 1} Why does this last attempt work, and more importantly, why did my four earlier attempts fail? I might add that I have no trouble getting what I want with >>> dict(zip((1,2),('one','two'))) {1: 'one', 2: 'two'} or >>> dict(((1,'one'),(2,'two'))) {1: 'one', 2: 'two'} Sincerely Thomas Philips From jcarlson at uci.edu Mon Apr 5 19:26:56 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Mon, 05 Apr 2004 16:26:56 -0700 Subject: Difference between default arguments and keyword arguments In-Reply-To: References: <406FFEAF.3080400@netscape.net> Message-ID: >>Functions implemented in C do not always have the property that every >>argument is a keyword argument. Functions implemented in Python do have >>that property. It's an implementation quirk. > > Really? > > def foo(*args): > pass > > foo(x=1) > > Traceback (most recent call last): > File "x.py", line 4, in ? > foo(x=1) > TypeError: foo() got an unexpected keyword argument 'x' Really. It just so happens that foo doesn't take any keyword arguments, nor does it have an argument named 'x'. - Josiah From roy at panix.com Fri Apr 16 11:32:38 2004 From: roy at panix.com (Roy Smith) Date: Fri, 16 Apr 2004 11:32:38 -0400 Subject: Goodbye TCL References: <0LudnSads6NmpuPdRVn-vw@centurytel.net> <107u6ef5a2ise19@news.supernews.com> Message-ID: In article , blacksqr at usa.net (Stephen Huntley) wrote: > I would be curious to know what is the biggest-capacity Python network > application in use? How does it scale in comparison with AOLServer? > Any ideas? How about the one you're using to post your articles -- Google. From dmq at gain.com Fri Apr 30 19:58:21 2004 From: dmq at gain.com (David MacQuigg) Date: Fri, 30 Apr 2004 16:58:21 -0700 Subject: Python 4 - Was: Ideas for Python 3 References: Message-ID: I'm starting a new sub-thread. Warning: Don't venture into this one if you can't stretch your imagination a little. What I'm looking for here is ideas for the ideal Python-like language that will make less-experienced users happy. To me, that means making Python simpler, not necessarily more powerful. I've got some ideas for how to handle the classes vs classless thing. See the "Python4" document at http://ece.arizona.edu/~edatools/Python Mainly, I want to keep classes, because I see them as very useful in most programs, where a "two-tier" organization is helpful. But I also think I understand the needs of those who don't want a two-tier organization. Seems like the answer is to make classes optional. Comments are welcome. Suggestions are even better. -- Dave ************************************************************* * * David MacQuigg, PhD * email: dmq at gain.com * * * IC Design Engineer * phone: USA 520-721-4583 * * * * Analog Design Methodologies * * * * * 9320 East Mikelyn Lane * * * * VRS Consulting, P.C. * Tucson, Arizona 85710 * ************************************************************* * From ajsiegel at optonline.com Thu Apr 1 10:30:35 2004 From: ajsiegel at optonline.com (Arthur) Date: Thu, 01 Apr 2004 15:30:35 GMT Subject: Followup: big projects, games, reload References: Message-ID: <8cco60967b3k1osmhq2642mdbr8ngaf2cj@4ax.com> On Wed, 31 Mar 2004 14:32:47 -0500, "Terry Reedy" wrote: >People fairly frequently ask about Python being used in big projects, >commercial projects, commercial games, etc. There was also a recent thread >on the limitations of 'reload' and what one might do to get the reload >behavior one wants... > >One of the PyCon talks that most surprised *me* is this: >http://www.python.org/pycon/dc2004/papers/29/Panda3D.htm It surprised me as well. But for different reasons. The Entertainment Technology Center at CMU seemed to have been (is?) ground zero for Alice. And Disney, is well, Disney. And the Alan Kay, Disney connection - as to *educational* technology, disturbed me - to put it mildly. I could say much on this. So it was great to see that collaboration of Disney and CMU produce something so clearly defined and powerful and - well - wholesome. It was refreshing that: Panda3d - as opposed to, Alice -is and has been opened source and crossplatform. It is and understands itself to be *entertainment* technology. No ambiguity, and not depending on who the audience happens to be. The students at CMU in the Building Virtual World class were given the choice of Alice and Panda3d and 100% chose to work with Panda3d. The class project usingt Panda3d presented seemed to me, at least, to be a clear swipe at the insipidness of Alice. The Python community should feel good about Disney's choice of Python as the scripting tools for Panda3d. And CMU support for the project going forward. Buy the community should intorspect a bit, IMO, about how so many bright people seemed to have become enamored of Alice, simultaneously. I will probably never get over the fact that a (let's say) overly generous view of Alice seemed to be almost of price of admission for community acceptance for those of us interested in Python and education. Art > >It seems that Disney's rather successful ToonTown Online ( >http://toontown.com ) >is scripted in Python on top of their now open sourced Panda3D (C++) >engine. >( http://www.etc.cmu.edu/panda3d ) >This answers the first set of questions in the affirmative. > >One of their reasons for using Python is to be able to do the following: > >"Redefining methods: > >One of the truly powerful features of Panda3D is that you can stop a >simulation, redefine a method, and start from that point again. This is >done using Python features. Panda3D recursively digs through namespaces to >find the definition of the class or methods and then swaps them for the >new, thus rebinding the new version. There is also special code written to >dig out all the stored function pointers, such as events and tasks, and >replace those as well." > >I think this nicely illustrates what I saw as the conclusion of the reload >thread: if one wants a reload function that does exactly what one wants in >a particular application, one should write it oneself, and with effect, one >can do so. > >Terry J. Reedy > > > From tundra at tundraware.com Thu Apr 8 11:10:06 2004 From: tundra at tundraware.com (Tim Daneliuk) Date: 08 Apr 2004 11:10:06 EDT Subject: why is python better than eg. smalltalk?? no one has any solid arguments! you should all go to church with all that religious talk! In-Reply-To: References: <20031028061245.12451.00000133@mb-m01.aol.com> Message-ID: Carlo v. Dango wrote: > On Thu, 30 Oct 2003 13:08:02 +0100, Andy Jewell > wrote: > > OK, I'm on the python wagon as well, but I do not really se much > improvement over JAVA... especially when it comes to maintaining and My view on Python's real virtue from several years ago: http://www.tundraware.com/Technology/Python-Is-Middleware/ -- ---------------------------------------------------------------------------- Tim Daneliuk tundra at tundraware.com PGP Key: http://www.tundraware.com/PGP/ From lubowiecka at go2.pl Wed Apr 14 11:37:41 2004 From: lubowiecka at go2.pl (Sylwia) Date: 14 Apr 2004 08:37:41 -0700 Subject: [Win32] HEEEEEEELLLLPPPP! I need to determine the cluster size on WinXP/NT/2k Message-ID: Hi! I need Your help. I implement a Python NT service and I need to determine (on WinXP/2k/XP) a cluster size of the particular partition (to find out how much space a file will occupy on that partition). Till now I faced the following problems: - The GetDiskFreeSpace() function is reliable in deriving cluster size if it is a FAT16 drive. If it is a FAT32 drive, the Win32 GetDiskFreeSpace call is lying about cluster size. -The newer GetDiskFreeSpaceEx call returns total and free space on the drive, but does not provide a cluster size parameter at all!!! -There's a small table that summarizes the default cluster size for every range of FAT32 volume sizes, but there's no guarantee that the user accepted the default when creating the partition :(((( - There is a DOS function, Int 21h Function 7303h Get_ExtFreeSpace (FAT32), but it exists only in Windows 95 SR 2 and later. This can be called through VWIN32.VXD using DeviceIoControl (unfortunately VWIN32 is Win9x/Me specific driver and it's not available on Win2K/XP). So is there any API that gets the FAT32 cluster size correctly in WinNT/2k/XP? Does anyone know of an API function that can tell me how much space a file will occupy on the disk? It'll need to work with FAT, FAT32, and NTFS. Thank You in advance! Farraige From jzgoda at gazeta.usun.pl Thu Apr 15 16:26:58 2004 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Thu, 15 Apr 2004 20:26:58 +0000 (UTC) Subject: CamelCase versus wide_names (Prothon) References: <87hdvl2dny.fsf@blakie.riol> Message-ID: Wilk pisze: >> 2) Wide_names is cleaner, more readable, compatible with C, which is the >> standard module language for Python and Prothon. Wide_names is also the >> Python standard. > > Before, i used CamelCase, but now i use only wide_name because i find > that capitals letters are a pain for the finger and the wrist. For > example when you whant to write Q (on querty or azerty keyboard), with > one hand you must make a gymnastic, or you will need two hands. Underscore is such same pain. I cann't see any advantage. -- Jarek Zgoda http://jpa.berlios.de/ From heiko at hhenkelmann.de Tue Apr 27 15:37:34 2004 From: heiko at hhenkelmann.de (Heiko Henkelmann) Date: Tue, 27 Apr 2004 21:37:34 +0200 Subject: How to access outer class attribute from nested class In-Reply-To: References: Message-ID: Sorry for not mentioning this in the first place. I don't want to instantiate the class. I much rather would to use it like: SomeClass.SomeNestedClass.SomeNestedClassMethod() Thanx Larry Bates wrote: > I use something like: > > class SomeClass: > SomeAttribute = 1 > > class SomeNestedClass: > SomeOtherAttribute = 2 > def __init__(self, parent): > self.parent=parent > return > > def SomeNestedClassMethod(self): > print "%s-%s" % ( > self.parent.SomeAttribute, > self.SomeOtherAttribute) > > def __init__(self): > self.SNC=self.SomeNestedClass(self) > return > > if __name__=="__main__": > a=SomeClass() > a.SNC.SomeNestedClassMethod() > > > I pretty much stole this idea from wxWindows. > > Larry Bates > Syscon, Inc. > > > >>Please see the following example. Is there any other way to access >>SomeAttribute from the nested class, without having to use the actual >>name of the outer class? >> >> >>class SomeClass: >> SomeAttribute = 1 >> >> class SomeNestedClass: >> SomeOtherAttribute = 2 >> >> def SomeNestedClassMethod(cls): >> print "%s%s" % ( >> SomeClass.SomeAttribute >> cls.SomeOtherAttribute, >> ) >> SomeNestedClassMethod = classmethod(SomeNestedClassMethod) >> >>Thanx > > > From NAIGIMSESRIMAIL at gims.com Thu Apr 1 05:11:05 2004 From: NAIGIMSESRIMAIL at gims.com (GroupShield for Exchange (ESRIMAIL)) Date: Thu, 1 Apr 2004 12:11:05 +0200 Subject: ALERT - GroupShield ticket number OB69_1080814264_ESRIMAIL_3 was generated Message-ID: Action Taken: The message was blocked because of its subject. To: python-list at python.org From: Peter Maas Sent: -1543787520,29628369 Subject: Re: test for nan Attachment Details:- Attachment Name: N/A File: Infected.msg Infected? No Repaired? No Blocked? Yes Deleted? No Virus Name: -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/ms-tnef Size: 1813 bytes Desc: not available URL: From Mike at DeleteThis.Geary.com Mon Apr 5 15:56:14 2004 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Mon, 5 Apr 2004 12:56:14 -0700 Subject: Using python23 to develop an extension for an application that has python22 embedded References: Message-ID: <1073eeubflmchd5@corp.supernews.com> John Underwood wrote: > Can I use python23_d and python23 to develop an extension for a > commercial application uses python22.dll? (Providing that I do not use > any new features found only in 2.3.) > > I would bulld version 2.2 but I am having trouble doing this with > Visual Studio .NET Standard. (There is a well documented problem with > version 2.2 (involving largeint.h) and VS.NET but none of the > solutions that I found have worked.) > > On the other hand, I have successfully built release and debug > versions of pythoncore with VS.NET. Why don't you just install the binary version of 2.2? That would be easier. You can have 2.2 and 2.3 installed on the same machine with no problem. http://www.python.org/2.2.3/ If 2.3 is the version you use most often, you may want to reinstall it after installing 2.2, so that your Windows file associations point to it. You can just reinstall 2.3 on top of your previous 2.3 installation. (Or maybe there's an easier way to do this.) -Mike From eriko at droakekwoakers.nl Tue Apr 6 04:11:09 2004 From: eriko at droakekwoakers.nl (Erik Oomen) Date: Tue, 06 Apr 2004 10:11:09 +0200 Subject: Does Python compete with Java? References: <8b336527.0404051337.51bb4a1b@posting.google.com> <1073su4etm95p35@news.supernews.com> Message-ID: Roy Smith wrote: > They don't have one for Python, but I expect it would be something like > this: > > You create a Foot object and call its shoot() method. The bullet makes > a hole in your foot, but by that time you've gotten dragged into a huge > flamewar about the relative merits of spaces vs. tabs for indentation > and barely notice the pain. Found this one at news.admin.net-abuse.email Python You shoot yourself in the foot and everything goes so smoothly that you go ahead to to shoot yourself in the other foot then your legs, then your torso and then your head. Problem solved. From newsgroups at jhrothjr.com Wed Apr 7 19:57:26 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Wed, 7 Apr 2004 19:57:26 -0400 Subject: Dynamic creation of an object instance of a class by name References: <10f99b0f.0404070656.5960e2c8@posting.google.com> Message-ID: <10795f3hoj37292@news.supernews.com> "Andre Meyer" wrote in message news:mailman.435.1081378579.20120.python-list at python.org... > Right, ok, well, I do not assume to know what classes can be instantiated, thus > anything like accessing globals() is not likely to help, sorry. The eval() > version works pretty ok so far. I am develpoing a module of which other people > can make use of by developing their own subclasses, but they need to be > instantiated by my code. Eval() does the trick for me or is there a better way, > assuming you do not need to know which class it might be beforehand? > btw I LOVE dynamicity... ;-) > > kind regards > Andre As long as you know where the class is (and I presume you do, since eval() is working), you can use getattr() to find the class, and then instantiate it the usual way. It's a good deal faster. The thing to remember is that eval() is not magic: it still needs to find the class you're referencing by the usual lookup path. For example, if you know it's in the current module, you could say: obj = getattr(globals(), "theClass")() If it's in another module, then the incantation becomes: obj = getattr(module, "theClass")() The moral of the story is that you do have to know where the class object resides. John Roth > > From hungjunglu at yahoo.com Fri Apr 30 14:17:59 2004 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 30 Apr 2004 11:17:59 -0700 Subject: Is classless worth consideration References: <69cbbef2.0404290259.fd8d71c@posting.google.com> <69cbbef2.0404291209.7a98a799@posting.google.com> <8ef9bea6.0404292307.66b78b83@posting.google.com> <84Kdnfu3OoN4oA_dRVn-vg@powergate.ca> Message-ID: <8ef9bea6.0404301017.575c91d7@posting.google.com> Peter Hansen wrote in message news:<84Kdnfu3OoN4oA_dRVn-vg at powergate.ca>... > Hung Jung Lu wrote: > > I have also pointed out previously that > > Python uses 5 devices where prototype-based needs only one: (a) class, > > (b) instance, (c) module, (d) metaclass, (e) scope. If this is not > > hideously baroque, then, Houston, we've got a problem. If you can > > really think outside the box, you'd pitch in also: (f) aspect. > > Well, (c) module is merely a packaging technique, not anything > to do specifically with OOP, so it shouldn't appear in a list > of "what do you think makes Python's OO model hideously baroque". Are you sure about that? Have you seen how people put an class instance in sys.modules so they could use it as a module (an old trick by now)? Have you seen people asking __call__() to make modules callable, and/or property getters/setters for modules? "Merely a packaging technique"? Have you seen people using modules as singletons? Do you realize that "from ... import ..." is nothing but a form of module inheritance? Think again. Let me say it again: think outside the box. It's hard to do when you are inside the box. But try. Try hard. > Scope doesn't quite seem to fit in this either, but not > being a theoretician I'll just leave the discussion at > this point I am sorry, there is no theory to do here. Check out the Io language. Code factorization is carried out not when two pieces of code are identical, but when they are analogous enough. By tearing things apart and claiming that they are different and should not be unified, it only goes to show you are still inside a box. All the 6 devices I have pointed out can be reduced to one single device: object. Matter of fact, many of them are already unified in a prototype-based language like Io, no theory there. Why have 6 devices and all kinds of redundancies/inconsistencies/hacks, when you can do it all with just one? As the other poster said: "hideously baroque" it is. regards, Hung Jung From peter at engcorp.com Mon Apr 5 13:21:34 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 05 Apr 2004 13:21:34 -0400 Subject: design by contract versus doctest In-Reply-To: <40718ddb$0$5071$4d4ebb8e@news.nl.uu.net> References: <407174ea$0$5066$4d4ebb8e@news.nl.uu.net> <40718ddb$0$5071$4d4ebb8e@news.nl.uu.net> Message-ID: aku wrote: > On 2004-04-05, Peter Hansen wrote: > >> aku wrote: >> >> >>>Isn't it so, that by applying DBC, a lot of unittests can be >>>made redundant? >> >> How would you propose verifying that your code will work if you >> don't run tests before you ship? > > > in debugging mode you obviously have to ensure that the caller > makes sure that all preconditions are met...then - by contract - > the postconditions are met on returning from the function. What is "debugging mode"? You aren't actually talking about _manual_ testing of some kind, are you? If not, I don't understand how you can be talking about automated testing, yet claiming that unit tests are redundant. Or are you simply saying that proper use of DBC can somewhat _reduce_ the number of unit tests you have to write? (In which case I ask how do you propose to verify that your precondition contracts are written properly?) -Peter From Chuck at spears.com Fri Apr 16 13:37:32 2004 From: Chuck at spears.com (Chuck Spears) Date: Fri, 16 Apr 2004 13:37:32 -0400 Subject: Best IDE? References: <4ace7f9f.0404111147.3120288a@posting.google.com> Message-ID: >CodeWright, now available from Borland. AFAIK, it's feature >compatible with Visual SlickEdit, though I think it's available >only on multiple Windows platforms. ;-) > --dang Borland is killing off this project. From peter9547 at btinternet.com Thu Apr 1 12:33:24 2004 From: peter9547 at btinternet.com (Peter MacKenzie) Date: Thu, 1 Apr 2004 17:33:24 +0000 (UTC) Subject: emergent/swarm/evolutionary systems etc References: Message-ID: Sorry for the long response time. I've been busy, and my brain has been clogged up with a cold and hayfever. Although I'm sure your instructions on creating files etc are perfectly valid, I lack the basic grammatical knowledge to make use of them (I really am very new to programing). I'll have to wait for my skills to catch up with my ideas before I can move on, but that must wait until July, as I have impending exams that demand much of my focus. In addition to exams, I also must start a dissertation in July for my geography hon B.Sc. Although I should ideally have found a subject two months ago, I've so far lacked any truly appealing project ideas (much to the consternation of my advisor). Since reading 'Emergence', by Steven Johnson, and conducting prelimenary research on the matter, I've settled on the dissertation title: "Emergence theory as an approach to city design". To this goal, I'd like to use computer modeling to simulate ways in which the spatial distribution of indicator phenomena in cities (land price/use, crime, demographic composition etc) is affected by bottom-up, local area rules. Given that I have only a basic foothold on the language, does anybody foresee difficulties for me learning enough to impliment simple and experimentally flexible sim-city style simulations (minus fancy graphics and llamas) in no more than 2 months (to allow for time to conduct actual experiments + field observations etc)? I would be able to engender aid from various staff, and the university library should carry titles on the subject. Failing that, I could do it the old fashioned way and buy a how-to book, but I'd like some opinions on the difficulty of the goal from people who've already trancended the non-programmer/programmer barrier. From doug at doug-.com Thu Apr 8 22:38:11 2004 From: doug at doug-.com (Doug) Date: Thu, 08 Apr 2004 21:38:11 -0500 Subject: How to define an Interface in Python 2.2.2? In-Reply-To: References: Message-ID: Boo Yah wrote: > Does Python 2.2.2 support Interface (as PHP 5 does) ? > > If so, how can i define it in Py 2.2.2? Python doesn't directly support interfaces. What most people for an interface is to create a class where the methods raise a NotImplementedError. For example: class MyInterface: def method1(): raise NotImplementedError def method2(): raise NotImplementedError class MyClass (MyInterface): "implements MyInterface" def method1(): some code here... def method2(): some code here... But see this page for some attempts at creating interfaces for Python: http://www.python.org/cgi-bin/moinmoin/MetaClasses From aahz at pythoncraft.com Sun Apr 11 23:29:55 2004 From: aahz at pythoncraft.com (Aahz) Date: 11 Apr 2004 23:29:55 -0400 Subject: Python OS References: <107j4eu6ffn2c68@corp.supernews.com> <107j8elr1m3tc65@news.supernews.com> Message-ID: In article <107j8elr1m3tc65 at news.supernews.com>, John Roth wrote: >"A Evans" wrote in message news:107j4eu6ffn2c68 at corp.supernews.com... >> >> A python NewBie - Man I hate that term does anyone else > >Likewise. I prefer novice. I consider Newbie to be patronizing. We could call them penitents. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Why is this newsgroup different from all other newsgroups? From herrn at gmx.net Tue Apr 6 16:23:16 2004 From: herrn at gmx.net (Marco Herrn) Date: 6 Apr 2004 20:23:16 GMT Subject: regex help for a newbie References: Message-ID: On 2004-04-06, marco wrote: > Marco Herrn writes: >> the parts in a recursive function. So the thing I want to achieve here >> is to extract %(BBB%(CCC)BBB) and %(DDD). > > p1, p2 = "aaa%(BBB%(CCC)BBB)aaa%(DDD)aaa".split("aaa")[1:-1] Doesn't help, since I do not know that there is the string "aaa". It was just an example. I do not know any of the strings/characters. The only thing I know is that a percent sign indicates that the content inside the following parentheses is an expression that has to be evaluated. I need to do this by real parsing. In fact the solution from Diez isn't enough. I will have to write a much more flexible parser, as I realized. Diez mentioned spark as a parser. I also found yappy, which is a parser generator. I have not much experience with parsers. What is the difference between these two? When should one use the one, when the other? Marco -- Marco Herrn herrn at gmx.net (GnuPG/PGP-signed and crypted mail preferred) Key ID: 0x94620736 From imbosol at aerojockey.invalid Wed Apr 28 02:18:41 2004 From: imbosol at aerojockey.invalid (Carl Banks) Date: Wed, 28 Apr 2004 06:18:41 GMT Subject: Is Perl *that* good? References: <108q51j4dscn7dc@corp.supernews.com> <87fzaqmm8t.fsf@strauser.com> <38ec68a6.0404262308.50029919@posting.google.com> Message-ID: <51Ijc.2549$ZD3.1367@fe1.columbus.rr.com> Wallclimber wrote: > > >> Asun> Probably the only time I would reach for Perl rather than for >> Asun> python is when I knew a task involved a lot of regex (and no >> Asun> object orientation). >> >> Why? I write non-object-oriented Python code all the time. To make the >> Python/Perl switch you'd still have to shift your mental gears to deal with >> a different syntax, different way of getting at and using functionality that >> isn't builtin, etc. Even with lots of regex fiddling to do, I think the >> extra overhead of using regexes in Python would be swamped by the other >> differences. In addition, as Jamie Zawinski suggests, regular expressions >> are not always the best choice. > > I have to agree with the original poster. My *only* complaint about > Python are not regex search, but regex search and replace operations. > Perl : s =~ s/(\w+)\s*=\s*(\d+)/$2 <= $1/g; > Python : regex.sub(s, "(\w+)\s*=\s*)\d+)", (lambda m: m.group(2)+" <= > "+m.group(1))) > > I didn't try this out so there might be some syntax problems in there, > but you get the idea. Is there a 'nicer' way to do this in python? > Using 'group' and lambda functions is really quite messy. (An, > obviously, in real life usage, the replacemant function can be much > bigger...) > > I'd be most grateful if somebody could show me a cleaner way to do > this. Define the following helper function (mrd stands for match replace dict, I wanted something small, call it what you want): def mrd(m): d = {} for i,g in enumerate(m.groups()): d[str(i+1)] = g return d Then your regex becomes: regex.sub(s, "(\w+)\s*=\s*)\d+)", "%(2)s <= %(1)s" % mrd(m)) Were you aware that, when a dict appears on the right side of string interpolation operator %, you can reference values in the dict by name? That's what the above trick does. Not quite down to Perl minimalism, but clean. -- CARL BANKS http://www.aerojockey.com/software "If you believe in yourself, drink your school, stay on drugs, and don't do milk, you can get work." -- Parody of Mr. T from a Robert Smigel Cartoon From arifi at tnn.net Tue Apr 13 04:43:28 2004 From: arifi at tnn.net (Arifi Koseoglu) Date: Tue, 13 Apr 2004 11:43:28 +0300 Subject: Newbie Q: Extra spaces after conversion from utf-8 to utf-16-le ? References: <915dc3ae.0404102233.4248dc9a@posting.google.com> Message-ID: Many thanks Josiah, Reading and writing in binary form did the trick. Very much appreciated. Cheers -arifi "Josiah Carlson" wrote in message news:c5c1u5$j09$1 at news.service.uci.edu... > > I am an absolute Newbie who has done a good amount of googling with > > the keywords utf-8, utf-16, python, convert and has reasoned that the > > following code could be used to convert a utf-8 text file to a > > utf-16-le (I believe this is what Windows uses for Unicode): > > > > s1 = open("utf8_file_generated_with_perl.txt", "r").read() > > s2 = unicode(s1, "utf-8") > > s3 = s2.encode("utf-16-le") > > open ("new_file_supposedly_in_utf16le", "w").write(s3) > > > > Well, this code kind of works (meaning I do not get any errors), but > > the produced file contains an extra space after every character (l i k > > e t h i s) and Windows believes this is an ANSI (i.e. non-unicode > > file). Clearly, what I think is working is actually not. > > For standard /ASCII/ characters, when encoded with utf-16-le, there > exists a 'null' character trailing every input character that exists in > standard ASCII... > >>> s = unicode("hello", "ascii") > >>> s > u'hello' > >>> s2 = s.encode("utf-16-le") > >>> s2 > 'h\x00e\x00l\x00l\x00o\x00' > > Generally, "Windows" makes no assumption about encoding and always > assumes ASCII. What many (not all) systems do to tell the app what > encoding is being used, is place what is known as a 'BOM' at the > beginning of the file. Check unicode.org for more information. > > You will also likely find opening files as 'binary' in Windows, when > working with unicode, goes a long ways towards making correct output. > > - Josiah From mark at prothon.org Tue Apr 27 00:01:17 2004 From: mark at prothon.org (Mark Hahn) Date: Mon, 26 Apr 2004 21:01:17 -0700 Subject: What is good about Prothon? References: Message-ID: "Mike C. Fletcher" wrote... > I'd want clarification of how to store a reference to > another object's (bound) method (which is *extremely* common > in Python code for storing, e.g. callbacks) > * I really dislike the :( ): function definition notation, > "Readability Counts". Why clutter the proposal with that? > * I'm neutral on the with: stuff, I'd much prefer a real block > mechanism similar to Ruby with (if we're using implicit targets), > the ability to specify the .x target for the block For what it's worth, you are basicly in agreement with the current proposals for Prothon. From mark at deverter.net Thu Apr 8 15:11:01 2004 From: mark at deverter.net (Mark d.) Date: Thu, 08 Apr 2004 19:11:01 GMT Subject: killing process Message-ID: <9thdc.4400$jR6.3088@fe2.texas.rr.com> I have been trying to make this function run that is triggered from a button on a Python rendered webpage. Clicking the button gets a processID, sends a kill command for the process and then generates a simple web page that displays the processID but the 'kill' command is not carried out. def restart(): pid = os.popen('pidof myProcess').read().strip() os.popen('kill -9 %s' %pid, 'w').close() print CGI() print HTML( HEAD('restart', None), BODY(None, 'process id:', pid )) return 1 This works just fine in the interpreter. Anyone have any ideas what I am overlooking? Cheers, Mark d. From junkmail at solumslekt.org Mon Apr 26 04:28:46 2004 From: junkmail at solumslekt.org (Leif B. Kristensen) Date: Mon, 26 Apr 2004 10:28:46 +0200 Subject: How's ruby compare to it older brother python References: Message-ID: Hunn E. Balsiche wrote: > in term of its OO features, syntax consistencies, ease of use, and > their development progress. I have not use python but heard about it > quite often; and ruby, is it mature enough to be use for developing > serious application, e.g web application as it has not many features > in it yet. > > I've given up on Perl for its ugly syntax and it is not the easiest > language to learn. How about PHP? It really depends on what you'll want to do. PHP is a great language for getting dynamic HTML pages up and running quickly. Perl is great for its string-handling abilities. (On my Web pages, I actually call a Perl script from PHP precisely for this reason.) However, both PHP and Perl can be very unwieldy for large projects. I'm a newcomer to Python, but it seems to scale much better than the other P-languages. For a first tour of Python, I'll suggest that you read the excellent tutorial by the language's author, Guido van Rossum: http://www.python.org/doc/current/tut/ regards, -- Leif Biberg Kristensen http://solumslekt.org/ Validare necesse est From ivan at yahoo.com Fri Apr 23 14:24:08 2004 From: ivan at yahoo.com (Ivan Lima) Date: Fri, 23 Apr 2004 18:24:08 +0000 (UTC) Subject: NumPy argsort question Message-ID: Hello, I have two 2-dimensional arrays A and B. I want to sort A along its columns (axis=1) and then sort B along its columns in the same order that A was sorted. I tried: sorted_A = sort(A,1) sorted_B = take(B, argsort(A,1), 1) but my last statement returns an array with an extra dimension. If A is a 2x3 matrix I get a 2x2x3 matrix. What am I missing? Thanks a lot, -- Ivan Lima - idl764 at yahoo dot com From jcarlson at uci.edu Sat Apr 10 16:13:25 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Sat, 10 Apr 2004 13:13:25 -0700 Subject: Wrapper round x86 Assembler In-Reply-To: <107g87b2k9cuoa7@corp.supernews.com> References: <8089854e.0404082353.7bf163a2@posting.google.com> <4dKdnQlIXMIXIevdRVn-gg@powergate.ca> <8089854e.0404100204.504186a0@posting.google.com> <107g87b2k9cuoa7@corp.supernews.com> Message-ID: > On modern CPUs, unless you really know what you're doing, hand-written > assembly code is likely to be slower than code generated by a good > optimizing C/C++ compiler. If your assembly code is at all straightforward, > it will definitely be slower than compiled code, because you'll be stalling > the CPU all over the place when one instruction waits for the results of a > previous one. Yes and no. With the existance of the Tomasulo algorithm for register renaming and out-of-order execution, you can pick up quite a bit of the ILP without even programming it that way. Of course, there is only so much the Tomasulo algorithm can do for crappy assembly. - Josiah From Mike at DeleteThis.Geary.com Mon Apr 19 11:50:08 2004 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Mon, 19 Apr 2004 08:50:08 -0700 Subject: equivalent to Java's toString()? References: Message-ID: <1087t9hc5vl833b@corp.supernews.com> Gabriel Cooper wrote: > What is the python equivalent to java's toString()? > > When debugging I want to be able to basically be able to do this: > > print MyObjectInstance > > or > print str(MyObjectInstance) > > and have it print out formatted output along the lines of: > > Object properties: Red=0 Yellow=0 Blue=255 Define a __str__ method in your class. It works just like toString() in Java and JavaScript: >>> class MyTest( object ): ... def __str__( self ): ... return 'My Test!' ... >>> test = MyTest() >>> print test My Test! >>> Also see __repr__ for a related method. -Mike From peter.schwalm at epost.de Wed Apr 7 21:34:07 2004 From: peter.schwalm at epost.de (Peter Schwalm) Date: 7 Apr 2004 18:34:07 -0700 Subject: Customizing the python search path depending on source directory References: <5cf809e9.0404061853.41cd3c85@posting.google.com> <5cf809e9.0404070452.643b7053@posting.google.com> Message-ID: <5cf809e9.0404071734.26f1078a@posting.google.com> Peter Hansen wrote in message news:... > Peter Schwalm wrote: > > > Peter Hansen wrote in message news:> > > > Thank you for your answer. But I'm afraid it's not the source > > directory but the current working directory. You can see the > > difference if you copy the passage > > > > "for ix1, p1 in enumerate(sys.path): print "%02.02d: %s" % (ix1, > > p1)" > > > > to a "normal script". If you start that "normal script" from a > > directory other than the source directory, you can see that both > > directories are included in sys.path. If you run this code inside > > sitecustomize.py this is not the case. > > On the contrary. When I start that from another directory which > is *not* in the path, I do not see that directory in the sys.path > at all, but merely the directory in which the script itself is > stored. This is the defined behaviour of the Python sys.path > stuff and you must be misinterpreting something. > > The current directory is *not* added to sys.path, unless it > just happens that the main script is in the current directory. > Again, thank you for your answer. This answer lets me suspect that you have a different version of python installed. Mine is 2.3.2 for win32 (activepython). To show you what I observe I have modified my "sitecustomize.py" slightly and have copied the unmodified text do script "test1.py" The source for both looks as follows: #------------------------------------------------------------------------- import sys import os print "--->", __file__, "..." print 64 * "-" print "python-version=", sys.version try: print "argv=", sys.argv except AttributeError: print "" print "sys.argv does still not exist!" try: print "sys.modules[\"__main__\"]=", sys.modules["__main__"].__file__ except AttributeError: print "" print "sys.modules[\"__main__\"].__file__ does still not exist" # ... shows that source directory is still not in sys.path print "sys.path=" for ix1, p1 in enumerate(sys.path): print "%02.02d: %s" % (ix1, p1) print 64 * "-" print "<---", __file__, "..." #------------------------------------------------------------------------- Here is the output from test1.py when run it's own source directory: E:\temp>test1.py ---> C:\Python23\lib\sitecustomize.pyc ... ---------------------------------------------------------------- python-version= 2.3.2 (#49, Oct 24 2003, 13:37:57) [MSC v.1200 32 bit (Intel)] argv= sys.argv does still not exist! sys.modules["__main__"]= sys.modules["__main__"].__file__ does still not exist sys.path= 00: E:\temp 01: d:\d\d8\AFP\r01\python 02: C:\WINNT\System32\python23.zip 03: C:\Python23\Lib\site-packages\Pythonwin 04: C:\Python23\Lib\site-packages\win32 05: C:\Python23\Lib\site-packages\win32\lib 06: C:\Python23\Lib\site-packages 07: C:\Python23\DLLs 08: C:\Python23\lib 09: C:\Python23\lib\plat-win 10: C:\Python23\lib\lib-tk 11: C:\Python23 12: C:\Python23\lib\site-packages\PIL ---------------------------------------------------------------- <--- C:\Python23\lib\sitecustomize.pyc ... ---> E:\temp\test1.py ... ---------------------------------------------------------------- python-version= 2.3.2 (#49, Oct 24 2003, 13:37:57) [MSC v.1200 32 bit (Intel)] argv= ['E:\\temp\\test1.py'] sys.modules["__main__"]= E:\temp\test1.py sys.path= 00: E:\temp 01: E:\temp 02: d:\d\d8\AFP\r01\python 03: C:\WINNT\System32\python23.zip 04: C:\Python23\Lib\site-packages\Pythonwin 05: C:\Python23\Lib\site-packages\win32 06: C:\Python23\Lib\site-packages\win32\lib 07: C:\Python23\Lib\site-packages 08: C:\Python23\DLLs 09: C:\Python23\lib 10: C:\Python23\lib\plat-win 11: C:\Python23\lib\lib-tk 12: C:\Python23 13: C:\Python23\lib\site-packages\PIL ---------------------------------------------------------------- <--- E:\temp\test1.py ... E:\temp> And here is the output from test1.py when run from a different directory (from subdirectory sub1): E:\temp\sub1>..\test1.py ---> C:\Python23\lib\sitecustomize.pyc ... ---------------------------------------------------------------- python-version= 2.3.2 (#49, Oct 24 2003, 13:37:57) [MSC v.1200 32 bit (Intel)] argv= sys.argv does still not exist! sys.modules["__main__"]= sys.modules["__main__"].__file__ does still not exist sys.path= 00: E:\temp\sub1 01: d:\d\d8\AFP\r01\python 02: C:\WINNT\System32\python23.zip 03: C:\Python23\Lib\site-packages\Pythonwin 04: C:\Python23\Lib\site-packages\win32 05: C:\Python23\Lib\site-packages\win32\lib 06: C:\Python23\Lib\site-packages 07: C:\Python23\DLLs 08: C:\Python23\lib 09: C:\Python23\lib\plat-win 10: C:\Python23\lib\lib-tk 11: C:\Python23 12: C:\Python23\lib\site-packages\PIL ---------------------------------------------------------------- <--- C:\Python23\lib\sitecustomize.pyc ... ---> E:\temp\test1.py ... ---------------------------------------------------------------- python-version= 2.3.2 (#49, Oct 24 2003, 13:37:57) [MSC v.1200 32 bit (Intel)] argv= ['E:\\temp\\test1.py'] sys.modules["__main__"]= E:\temp\test1.py sys.path= 00: E:\temp 01: E:\temp\sub1 02: d:\d\d8\AFP\r01\python 03: C:\WINNT\System32\python23.zip 04: C:\Python23\Lib\site-packages\Pythonwin 05: C:\Python23\Lib\site-packages\win32 06: C:\Python23\Lib\site-packages\win32\lib 07: C:\Python23\Lib\site-packages 08: C:\Python23\DLLs 09: C:\Python23\lib 10: C:\Python23\lib\plat-win 11: C:\Python23\lib\lib-tk 12: C:\Python23 13: C:\Python23\lib\site-packages\PIL ---------------------------------------------------------------- <--- E:\temp\test1.py ... E:\temp\sub1> As you can see in the second output, the source directory is *not* included in sys.path during the processing of sitecustomize.py, but only during the processing of the "normal script" test1.py. Does the output look different if you run these programs in your environment? Thank you Peter From anton at vredegoor.doge.nl Thu Apr 15 09:42:30 2004 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Thu, 15 Apr 2004 15:42:30 +0200 Subject: Difficulty finding Python employer Message-ID: <407e9164$0$122$3a628fcd@reader3.nntp.hccnet.nl> Will send no resume. Can't stand hype. Must telecommute. Anton From nicolas.lehuen at thecrmcompany.com Wed Apr 21 05:16:07 2004 From: nicolas.lehuen at thecrmcompany.com (Nicolas Lehuen) Date: Wed, 21 Apr 2004 11:16:07 +0200 Subject: Python 2.3.3 super() behaviour Message-ID: <40863bd7$0$25528$afc38c87@news.easynet.fr> Hi, I hope this is not a FAQ, but I have trouble understanding the behaviour of the super() built-in function. I've read the excellent book 'Python in a Nutshell' which explains this built-in function on pages 89-90. Based on the example on page 90, I wrote this test code : class A(object): def test(self): print 'A' class B(object): def test(self): print 'B' class C(A,B): def test(self): super(C,self).test() print 'C' print C.__mro__ c=C() c.test() The output is : (, , , ) A C Whereas I was expecting : (, , , ) A B C Was I wrong to expect this (based on what I've read ?) Regards, Nicolas From arigo at tunes.org Sat Apr 3 13:48:04 2004 From: arigo at tunes.org (Armin Rigo) Date: Sat, 3 Apr 2004 18:48:04 +0000 (UTC) Subject: Python is faster than C Message-ID: <406F0907.96F37EA1@tunes.org> Hi! This is a rant against the optimization trend of the Python interpreter. Sorting a list of 100000 integers in random order takes: * 0.75 seconds in Python 2.1 * 0.51 seconds in Python 2.2 * 0.46 seconds in Python 2.3 Tim Peters did a great job optimizing list.sort(). If I try with a simple, non-stable pure Python quicksort implementation, in Python 2.3: * 4.83 seconds * 0.21 seconds with Psyco First step towards world domination of high-level languages :-) The reason that Psyco manages to outperform the C implementation is not that gcc is a bad compiler (it is about 10 times better than Psyco's). The reason is that the C implementation must use a generic '<' operator to compare elements, while the Psyco version quickly figures out that it can expect to find ints in the list; it still has to check this assumption, but this is cheap and then the comparison is done with a single machine instruction. Similarily, here are some results about the heapq module, which is rewritten in C in the CVS tree for Python 2.4: l = [random.random() for x in range(200000)] heapq.heapify(l) This code executes on my laptop in: * 1.96 seconds on Python 2.3 (pure Python) * 0.18 seconds on Python 2.4cvs (rewritten in C) * 0.16 seconds on Python 2.3 with Psyco So this is not so much a plug for Psyco as a rant against the current trend of rewriting standard modules in C. Premature optimization and all that. Worse, and more importantly, the optimization starts to become visible to the programmer. Iterators, for example, are great in limited cases but I consider their introduction a significant complication in the language; before, you could expect that some function from which you would expect a sequence returned a list. Python was all lists and dicts, with dicts used as namespaces here and there. Nowadays you have to be careful. Moreover, it is harder to explain: >>> zip([1,2,3], [4,5,6]) # easy to understand and explain [(1, 4), (2, 5), (3, 6)] >>> enumerate([6,7,8,9]) # uh ? I know you can always do list(_). My point is that this is a user-visible optimization. enumerate() should return a normal list, and it should be someone else's job to ensure that it is correctly optimized away if possible (and I'm not even talking about Psyco, it could be done in the current Python implementation with a reasonable amount of effort). Protesting-ly yours, Armin From nmkolev at uni-bonn.de Sun Apr 4 06:48:28 2004 From: nmkolev at uni-bonn.de (Nickolay Kolev) Date: 4 Apr 2004 10:48:28 GMT Subject: =?utf-8?q?Working_with_a_list_in_a_more_=E2=80=9Epythonic?= =?utf-8?b?4oCcIHdheQ==?= Message-ID: <20040404124833458+0200@news.rhrz.uni-bonn.de> Hi all, I would like to find a more pythonic way of solving the following: Having a string consisting of letters only, find out the total sound score of the string. The sound score is calculated as the sum of the transition scores between the characters in that string. The transition scores are stored in a 26 x 26 matrix. I.e. the transition A -> F would have the score soundScoreMatrix[0][5]. I have come up with the following solution, but I hope some of you might suggest a more _functional_ (reduce and map) way of diong it. n = 0 # the final score of the string for i in range(len(phrase)): try: n += soundScoreMatrix[ord(x[i]) - 65][ord(x[i + 1]) - 65] except IndexError: pass I was thinking about using "reduce", but that would not work as the input and output of the function I would use are different (string input, integer output). Many thanks in advance, Nicky From nospam at kochandreas.com Sun Apr 25 11:35:39 2004 From: nospam at kochandreas.com (Andreas Koch) Date: Sun, 25 Apr 2004 17:35:39 +0200 Subject: Andreas' practical language comparison Message-ID: Hi all, i started a little "practical language comparison" - practical in the sense that i compare how actual distributions and versions and their libraries (not abstract language specifications) solve small test cases like the 8 queens problem. Currently there are contributions for 17 different languages, and none for Phyton (and Lisp. And Forth. And many others ). If someone is interested in contributing a few implementations, please have a look at: http://www.kochandreas.com/home/language/lang.htm and mail me your code snippets (or critics) or post them here. thanks a lot, -- Andreas He screamed: THIS IS SIG! From kramakrishnan at novell.com Thu Apr 8 12:07:13 2004 From: kramakrishnan at novell.com (Ramki) Date: 8 Apr 2004 09:07:13 -0700 Subject: Distributing a Python based application on Linux Message-ID: <98013c51.0404080807.6f08f1a3@posting.google.com> Hi !! I have written an install script to deploy some of my product rpms. The install script does OS Version Check, OS Memory check, logging the status of install into a log file amongst other things. Now the size of my product rpms is around 3 MB. If I am to distribute Python along with the install, it is taking around 12 MB totally (the python gz tar is around 9 MB), which is not ideal. Is there way I can avoid this by distributing only the bare minimum Python related binary along with my rpms ? Any help would be appreciated. thanks, Ram. From Scott.Daniels at Acm.Org Wed Apr 21 17:38:08 2004 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 21 Apr 2004 14:38:08 -0700 Subject: Optimizing a text statistics function In-Reply-To: References: Message-ID: <4086efbc$1@nntp0.pdx.net> Peter Otten wrote: > Nickolay Kolev wrote: Playing along, simply because it's fun. > def main(filename): > ... #> words = file(filename).read().translate(tr).split() #> histogram = {} #> wordCount = len(words) #> for word in words: #> histogram[word] = histogram.get(word, 0) + 1 Better not to do several huge string allocs above (I suspect). This method lets you to work on files too large to read into memory: wordCount = 0 histogram = {} for line in file(filename): words = line.translate(tr).split() wordCount += len(words) for word in words: histogram[word] = histogram.get(word, 0) + 1 > ... - Scott David Daniels Scott.Daniels at Acm.Org From peter at engcorp.com Thu Apr 29 09:08:25 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 29 Apr 2004 09:08:25 -0400 Subject: suggestions for using tuples instead of list (or vice versa) In-Reply-To: References: Message-ID: Thorsten Kampe wrote: > I found out that I am rarely using tuples and almost always lists > because of the more flexible usability of lists (methods, etc.) > > To my knowledge, the only fundamental difference between tuples and > lists is that tuples are immutable, so if this is correct, than list > are a superset of tuples, meaning lists can do everything tuples can > do and more. Only tuples can be used as dictionary keys. > Is there any advantage for using tuples? Are they "faster"? Consume > less memory? Not appreciably so in most cases. Certainly not enough to be a factor in choosing which to use except perhaps in very rare edge cases. > When is it better to use tuples instead of lists and when > better to use lists instead of tuples? The canonical answer (which some disagree with) is that you should use tuples when you have a collection of different types of items, such as a 'struct' in C would have. Use lists any other time you want a simple sequential collection of items. Use a list for effectively everything else, unless you need an immutable (tuple) for a dictionary key. One description of how to look at this that I've found helpful is something along the lines of "if you can take a slice of the data and consider it in the same way as the original, then you should use a list". For example, if you have a set of fifteen objects over which you plan to iterate, you can just as well iterate over the first five. If, however, you have a tuple of (year, month, day, hour, minute, second), taking the first four items is quite a different thing than taking all six of them. -Peter From johnbunderwood at yahoo.ca Mon Apr 5 15:04:32 2004 From: johnbunderwood at yahoo.ca (John Underwood) Date: Mon, 05 Apr 2004 15:04:32 -0400 Subject: Using python23 to develop an extension for an application that has python22 embedded Message-ID: Can I use python23_d and python23 to develop an extension for a commercial application uses python22.dll? (Providing that I do not use any new features found only in 2.3.) I would bulld version 2.2 but I am having trouble doing this with Visual Studio .NET Standard. (There is a well documented problem with version 2.2 (involving largeint.h) and VS.NET but none of the solutions that I found have worked.) On the other hand, I have successfully built release and debug versions of pythoncore with VS.NET. Thanks From cjw at sympatico.ca Sun Apr 11 22:44:45 2004 From: cjw at sympatico.ca (Colin J. Williams) Date: Sun, 11 Apr 2004 22:44:45 -0400 Subject: Is boa-constructor dead? In-Reply-To: References: <4077fa35$0$93590$cd19a363@news.wanadoo.nl> Message-ID: <2onec.1722$2Z6.166963@news20.bellglobal.com> Version 0.2.8 works well. It is not completely bug free, but it is a powerful tool. Colin W. Uwe Grauer wrote: > Andrei wrote: > >> Mark Carter wrote on Saturday 10 April 2004 14:42: >> >> >>> I noticed that boa-constructor has been stuck at 0.2.3 for a long time >>> now. Is it dead? >> >> >> >> Nope, it just doesn't release very often on the front page, where one >> would >> normally expect releases to appear :). There is activity on CVS. There is >> also a - not very well publicized - 0.2.8 zip/tarball somewhere in the >> forums if I'm not mistaken. I just can't find it right now. >> > > Here is a Message from Rijan from 15.12.03: > Riaan Booysen wrote: > > > Hi everyone, > > > > 0.2.8 is available from CVS. > > > > Changes: > > * Improved EOL handling > > * Converting (Edit->Convert...) > > * Mode switching (Edit->STC settings...) > > * Warning when mixed EOLs are detected > > * Added application todo view > > * On app module, Views->Application todos > > * Gives navigatible app wide todo list > > * Much improved support for maskededit family of controls > > * Added page about Sizers to the application help > > * It's not linked to yet, but can be opened in a browser, > > at Docs/boa/apphelp/Sizers.html > > * Many bug fixes > > * Fixed process freezing if printing > 4k text > > * Sizer, Designer and Editor bugs > > * BicycleRepairMan plug-in bugs > > > > Updated versions of the maskededit controls needed by Boa can be > > found here: > > http://boa-constructor.sourceforge.net/files/maskededitctrls-0.2.8.zip > > Replace the ones in wxPython/lib/* > > > > A checkout of the 0.2.8 tree can be found here: > > > http://boa-constructor.sourceforge.net/files/boa-constructor-0.2.8-snapshot.tgz > > > > > Enjoy, > > Riaan. > > > > Hope this helps, > Uwe > From deetsNOSPAM at web.de Fri Apr 16 10:19:22 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Fri, 16 Apr 2004 16:19:22 +0200 Subject: AOP use cases References: <84fc4588.0404140106.3fa0c55@posting.google.com> <0pydnSB4WYuieuLdRVn-hQ@powergate.ca> Message-ID: Peter Hansen wrote: > >> What are good usage examples? > The other one that springs to my mind is the role rights/permissions example. -- Regards, Diez B. Roggisch From mark at prothon.org Thu Apr 15 19:27:07 2004 From: mark at prothon.org (Mark Hahn) Date: Thu, 15 Apr 2004 16:27:07 -0700 Subject: CamelCase versus wide_names (Prothon) References: <407ec022$0$54153$1b2cd167@news.wanadoo.nl> Message-ID: "Jan Dries" wrote ... > In all fairness, you are finding out that 6 of the 8 first people to > respond to your post prefer CamelCase. The other two didn't voice a > clear opinion in either direction. While I'm sure that might be > indicative of some trend, it certainly does not mean 100% of Python > users want camelCase. Yes, I was definitely guilty of over-generalization. I was just so surprised that 100% of the first 6 who gave an opinion picked camelCase that I got carried away. Small sample sets like the first six can be deceptive, but the odds of wide_names winning after this early response are near zero. (Unless there is some correlation with camelCase-loving and quick-responding :) From jcarlson at uci.edu Wed Apr 7 00:48:01 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Tue, 06 Apr 2004 21:48:01 -0700 Subject: shutil.move, permission denied, why ? In-Reply-To: References: Message-ID: > def makeTree(self): > print 'HERE WE ARE' > f = file(self.__filename,'r') > f.close() > from shutil import move > from os.path import join > bakname = self.__filename + '.bak' > print bakname > print f.closed > f.close() > print 'TEST',f.closed > move(self.__filename,bakname) Try... os.rename(self.__filename, bakname) - Josiah From dkuhlman at rexx.com Fri Apr 16 14:55:26 2004 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Fri, 16 Apr 2004 11:55:26 -0700 Subject: Kuhlman's tutorials pretty good References: <407E1E20.D0216E92@doe.carleton.ca> <200404150710.i3F7A0Hw010978@locutus.doe.carleton.ca> <407E40CC.C06FA9E3@doe.carleton.ca> Message-ID: gabor wrote: [snip] > > hmmm..could you also put on the web the latex sources? (or a > ps/pdf version?)... > > or if it is already there, i can't find it :( The TeX/LaTeX sources for these tutorials and postscript (.ps) and PDF files are in: http://www.rexx.com/~dkuhlman/python_x01_training.zip A few comments: I was able, just now, to generate ps and pdf files. Thanks for asking this question. You motivated me to try to generate them. I did not know that I could do that. The fonts in the ps files are not so good, and the fonts in the pdf files are terrible. Maybe they will appear better on your system. If you look at them, please let me know. In both the ps and pdf files, example source code files that are included into the LaTeX source do not show. Only the file name appears. I don't know whether this is normal, or if it indicates an error on my part. There are a number of .tex files (the sources), a Makefile, and a number of example files (which are sucked in when I build the HTML files). These sources are intended for use with the Python documentation system. You can find out about that at: http://docs.python.org/doc/doc.html I don't know whether you are familiar with the Python documentation system. If you decide to generate ps or pdf files yourself, you will need the Python source code distribution and other things besides. You will also need to modify my Makefile. The Python documentation system is great, by the way. If I can be of help with your use of these files, please let me know. Dave -- http://www.rexx.com/~dkuhlman dkuhlman at rexx.com From reverse.ku.oc.issolok at nothypgnal.delrest.co.uk Tue Apr 27 05:24:44 2004 From: reverse.ku.oc.issolok at nothypgnal.delrest.co.uk (Paul Sweeney) Date: Tue, 27 Apr 2004 09:24:44 +0000 (UTC) Subject: Default Argument Inconsistency? Message-ID: The python tutorial gives the following example to demonstrate the fact that default args are only evaluated once: def f(a,L=[]): L.append(a) return L print f(1),f(2),f(3) [1] [1,2] [1,2,3] now I'm confident I understand this, but I do not understand how changing to the following (whatever the merits of so doing, it was an accidental typo) results in the output displayed: def f(a,L=[]): if not L: L=[] L.append(a) return L >>> print f(1),f(2),f(3) [1] [2] [3] surely on second entry to f, L == [1], so the "if not L:" should not fire?! I'm running v2.3.3 and have tried this on RH9.0 and W2K (just in case...) any enlightenment gratefully recieved THX From wweston at att.net Thu Apr 15 10:44:36 2004 From: wweston at att.net (wes weston) Date: Thu, 15 Apr 2004 14:44:36 GMT Subject: [Newbie Q on String & List Manipulation] In-Reply-To: <567a7c35.0404150247.7809bef5@posting.google.com> References: <567a7c35.0404150247.7809bef5@posting.google.com> Message-ID: Matthew wrote: > Hello All, > > today is the first day i try to programming in Python, > my assignment is, write a silly script that probably > will run a few times a day to check if the Gmail services > is ready or not. ;) > > however, i encountered some problem when playing with the > list and string. > > i'm using Python 2.2.2 on Redhat. if i write something like: > > a = "one" > b = "two" > a += b > print a > > i will get: > > onetwo > > ok, seems quite ok, however, not sure why it doesn't work on > my silly Gmail script (pls refer to my script belows): > > for item in thecookies: > mycookies += item > > print mycookies > > i have exactly 4 items in the "thecookies" list, however, when > printing out "mycookies", it just show the last item (in fact, > seems the 4 items have been overlapped each others). > > could somebody pls kindly take a look at my silly script and > gimme some advise? > > thanks very much in advance! :) > > --- > matthew > > > > > import re > import string > import sys > import urllib > > user = "da at email.address" > pswd = "dapassword" > > schm = "https://" > host = "www.google.com" > path = "/accounts/ServiceLoginBoxAuth" > qstr = {"service" : "mail", \ > "continue" : "http://gmail.google.com/", \ > "Email" : user, \ > "Passwd" : pswd} > > qstr = urllib.urlencode(qstr) > > url = schm + host + path + "?" + qstr > > conn = urllib.urlopen(url) > > headers = conn.info().headers > response = conn.read() > > thecookies = [] > > # > # extract all the Set-Cookie from the HTTP response header and put it in thecookies > # > > for header in headers: > matches = re.compile("^Set-Cookie: (.*)$").search(header) > if matches: > thecookies.append(matches.group(1)) > > # > # make sure we've grep the SID or die > # > > foundsessionid = 0 > > for item in thecookies: > if re.compile("^SID").search(item): > foundsessionid = 1 > break > > if not foundsessionid: > print "> Failded to retrieve the \"SID\" cookie" > sys.exit() > > # > # grep the GV cookie from the HTTP response or die > # > > matches = re.compile("^\s*var cookieVal= \"(.*)\";.*", re.M).search(response) > > if matches: > thecookies.append("GV=" + matches.group(1)) > else: > print "> Failed to retrieve the \"GV\" cookie" > sys.exit() > > print thecookies > > mycookies = "" > > for item in thecookies: > mycookies += item > > print mycookies > > # > # still got many things to do right here... > # > > sys.exit() >>> sum="" >>> list=["a","b","c","d"] >>> for x in list: ... sum+=x ... >>> sum 'abcd' From adamc at linuxmail.org Thu Apr 15 17:40:12 2004 From: adamc at linuxmail.org (Adam) Date: Thu, 15 Apr 2004 22:40:12 +0100 Subject: newbie question References: Message-ID: <20040415224012.45c22a15@debian> On Thu, 15 Apr 2004 20:55:11 GMT jeff wrote: > ex: > > a = "text str" > if a == "text str": print a > > why doesn't that work? i couldn't find much help about > variable types in the manual, does it need a property like > a.text? What error are you getting? adam From rogerb at rogerbinns.com Wed Apr 14 19:07:47 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Wed, 14 Apr 2004 16:07:47 -0700 Subject: Method for providing a trail period on a program References: <407CF4F0.4020604@yahoo.com.au> Message-ID: > I am however, not prepared to > let them run it forever for free. If it provides > value to them, I believe they should purchase a > license. This may put me in the minority on > a Python site, but that's the way I feel. Keep a counter of how many times the program has been run, and how long a time period it has been used for. Start whining once they get past a reasonable trial period. I would store the counters in the registry or somewhere similar. The user could go in and edit them back down to zero, but at that point they are trying to immorally alter the software function to get around the period. There is no real point trying to deal with people who are absolutely determined to steal. They will always succeed. People who have to make minor changes to circumvent stuff know they are doing wrong. You can also add in a weekly check for updates (with the users permission). That will remind people that they get to pay for the software's continued improvement (unless 1.0 happens to be perfect and user requirements never change :-) Roger From Michael.DeLaMaza at PETERSON.af.mil Mon Apr 26 15:01:46 2004 From: Michael.DeLaMaza at PETERSON.af.mil (De La Maza Michael A GS-11 AFSPC/XPYS) Date: Mon, 26 Apr 2004 19:01:46 -0000 Subject: Newbie question: Where is python23_bcpp.lib? Message-ID: <200404261901.i3QJ1rcD007078@theseus.peterson.af.mil> Under Windows, I'm trying to make a program (Gambit Python APIs) using Borland (i.e., "make -f borland"). The Borland make file, shown below, wants python23_bcpp.lib in $(PYTHONDIR)\libs\. Unfortunately, there is no such file (error shown below). There is a python23.lib file but simply substituting python23_bcpp.lib with python23.lib does not work. Can anyone help? Is this a problem with the borland.mak file or is it a problem with my install of Python? (I can run a "Hello World" program in Python so Python is not completely broken). Thanks, Michael de la Maza ===Make file=== # # $Source: /cvsroot/gambit/gambit/sources/python/borland.mak,v $ # $Date: 2004/04/09 18:25:47 $ # $Revision: 1.2 $ # # DESCRIPTION: # Makefile for Borland C++ 5.5 for Python interface # .AUTODEPEND !include ..\makedef.bcc PYTHONDIR = c:\python23 EXTRACPPFLAGS = -v -I$(PYTHONDIR)\include -I$(BCCDIR)\include -I.. -D__BCC55__ EXTRALINKFLAGS = CFG = ..\gambit32.cfg OPT = -Od .cxx.obj: bcc32 $(CPPFLAGS) -P -c {$< } LIBS=gambit $(PYTHONDIR)\libs\python23_bcpp.lib import32 cw32mt LINKFLAGS= /Tpd /Gn /q /x /L$(BCCDIR)\lib;.. $(EXTRALINKFLAGS) OPT = -Od DEBUG_FLAGS= CPPFLAGS= $(WXINC) $(EXTRACPPFLAGS) $(OPT) @$(CFG) all: gbt gbt: gbt_wrap.obj ilink32 $(LINKFLAGS) @&&! c0d32.obj gbt_wrap.obj _gbt.pyd nul $(LIBS) gbt.def ! SWIGFILES = \ behav.i \ game.i \ gbt.i \ infoset.i \ mixed.i \ nash.i \ node.i \ outcome.i \ player.i \ rational.i gbt_wrap.cxx: $(SWIGFILES) swig -c++ -python gbt.i clean: -erase *.obj -erase *.exe -erase *.res -erase *.map -erase *.rws ==Error===== C:\Temp\Gambit 09712\gambit-0.97.1.2\sources\python>make -f borland MAKE Version 5.2 Copyright (c) 1987, 2000 Borland ilink32 /Tpd /Gn /q /x /LC:\BORLAND\BCC55\lib;.. @MAKE0000.@@@ Fatal: Unable to open file 'PYTHON23_BCPP.LIB' -------------- next part -------------- An HTML attachment was scrubbed... URL: From ark at acm.org Fri Apr 30 13:52:44 2004 From: ark at acm.org (Andrew Koenig) Date: Fri, 30 Apr 2004 17:52:44 GMT Subject: Feedback on Sets, and Partitions References: Message-ID: > I could live with only immutable sets, but it is nice > being able to use: > myset.add(x) > > instead of: > newmyset = myset | Set([x]) What about myset |= Set([x]) Presumably that would work analogously to += for strings. > Another unintutive feature is that there can be multiple sets with the > same members. I.e., you can have sets A and B such that "A == B" is true > and "A is B" is false. Why is that any more unintuitive than the fact that there can be multiple integers with the same value? For example: x = 12345 y = 12344+1 After these two statements, most Python implementations will evaluat "x is y" as false, but of course 1==y is true. From spam1 at omegis.com Sun Apr 11 09:47:33 2004 From: spam1 at omegis.com (Omegis) Date: Sun, 11 Apr 2004 15:47:33 +0200 Subject: string help .. Message-ID: Hello, I'm a sustem admin on a linux box, long time ago we got a new system panel to manage the apache configuration files, from a nice guy that biuld it for us, as time go by the "nice" guy gone and i need to update something very small in the script ... today i have a check for php_value string in the httpd.conf file with this line: self.phpvalues = self.phpvalues = re.compile("^\s*php_value\s+(.*)$", re.M).findall(string) i need line to check also for "php_admin_value" i really dont know a lot in python so its a problem for me to do this alone ... thanks Alot for you help. Rotem From ae Sun Apr 11 23:43:54 2004 From: ae (A Evans) Date: Sun, 11 Apr 2004 20:43:54 -0700 Subject: A new OS Message-ID: <107k441hitt2ld9@corp.supernews.com> Hello Everyone I am working towards starting a project developing a new Operating System using the Python language (or a derivative thereof). As recommended on this forum I am asking if people are interested in something like this and ask who would be willing to support a project this large. Any and all ideas are welcome this message is just to see what kind of support this project would recieve Cheers Andrew From tjreedy at udel.edu Thu Apr 29 13:27:00 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 29 Apr 2004 13:27:00 -0400 Subject: static keyword References: <40912de6$0$46516$39cecf19@news.twtelecom.net> Message-ID: "Rick Ratzel" wrote in message news:40912de6$0$46516$39cecf19 at news.twtelecom.net... > Robert beat me to it...I was going to reply with a generator > example! Indeed...Nick *clearly* wants a generator. By far the most > elegant IMO. > Robert Brewer wrote: > > Nick Jacobson wrote: > > Bah. All these old fogies with their default arg hacks, when Nick > > *clearly* wants a generator: > >>>>def foo(): > > ... i = 10 > > ... print "First pass" > > ... while True: > > ... i += 1 > > ... yield i > > > >>>>g = foo() > >>>>g.next() > > > > First pass > > 11 Unless, of course, Nick's foo is a simplified illustrative example and he wants 'static' effect in functions with parameters. TJR From rogerb at rogerbinns.com Wed Apr 28 14:50:41 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Wed, 28 Apr 2004 11:50:41 -0700 Subject: Don't understand wxPython ids References: <408ed938$0$17263$a1866201@newsreader.visi.com> <1a34m1-fml.ln1@home.rogerbinns.com> <408fb5fc$0$17264$a1866201@newsreader.visi.com> Message-ID: Grant Edwards wrote: > I understand, but compare the above code with this: > > > menu.Append("&Delete", "Delete the file", action=self.OnFileDelete) > > .... > > toolbar.AddLabelTool("Delete", action=self.OnFileDelete) > > Which is easier to understand at a glance? If it is all in one place in one function then it is no big deal. In reality if you have editable toolbars, menus loaded from definitions elsewhere and stuff scattered across several modules then using ids makes that easier. Roger From peholmst at abo.fi Tue Apr 20 01:23:48 2004 From: peholmst at abo.fi (=?ISO-8859-1?Q?Petter_Holmstr=F6m?=) Date: Tue, 20 Apr 2004 08:23:48 +0300 Subject: File access and threads Message-ID: <4084b3eb@newsflash.abo.fi> Hello, I have a problem with file access which I believe is caused by a thread-problem. I first noticed it while trying to get PSP/Mod_Python to work in the shape of an exception claiming that there are no usable temporary directories. The second time I noticed it was when I was trying to dump an object to a file using pickle, and I got the "Bad file descriptor" error all the time, even though the file was created in the file system. I googled around and found out that there have been similar problems before, and that these are due to threading, but I didn't manage to find a solution (except to recompile Python without threads, which in my case is not an option as I'm running Zope on the server). Are there any tips you could give me? I'm running Python 2.3.3 (from the Ports collection) on FreeBSD 5.2.1. Thanks in advance, -Petter- From rick.ratzel at magma-da.com Tue Apr 27 18:57:04 2004 From: rick.ratzel at magma-da.com (Rick Ratzel) Date: Tue, 27 Apr 2004 17:57:04 -0500 Subject: debugging code In-Reply-To: <3064b51d.0404271139.6ec7057@posting.google.com> References: <3064b51d.0404271139.6ec7057@posting.google.com> Message-ID: <408ee541$0$46510$39cecf19@news.twtelecom.net> Python defines __debug__ to True by default, and False when optimizations are enabled...meaning you can enable/disable code without having to define/undefine vars ahead of time and without having to change it prior to deployment. This is how the "assert" statement works. You can only set __debug__ through the use of -O or -OO. For example, you can define a func like this: def printDebugStmt( stmt ) : if __debug__ : print stmt ...and use it like this: $ python >>> i=3 >>> printDebugStmt( "Hello World...i = %s" % i ) Hello World...i = 3 >>> $ python -O >>> i=3 >>> printDebugStmt( "Hello World...i = %s" % i ) >>> ...just remember to "ship" your app so it runs Python with -O or -OO. BTW: you can use freeze.py with -O or -OO to get the same result for a "frozen" app. -Rick beliavsky at aol.com wrote: > If I have some debugging code in a Python program (mostly print > statements) and I want to turn it "off", two obvious methods are to > (1) comment out the code > (2) set a logical 'debug' variable at the beginning and use it to > conditionally run the debugging code. > > Is there a better way? Some other languages have conditional > compilation. (I don't know if that is better or worse). What is the > "best" way to maintain "production" and "debugging" versions of a > Python program at the same time, preferably in the same file? From joe at notcharles.ca Thu Apr 22 13:17:18 2004 From: joe at notcharles.ca (Joe Mason) Date: Thu, 22 Apr 2004 17:17:18 GMT Subject: CamelCase versus wide_names (Prothon) References: <6ee58e07.0404192141.2229efd6@posting.google.com> <1082549174.163233@ns.topconrd.ru> <1082632248.524260@ns.topconrd.ru> Message-ID: In article <1082632248.524260 at ns.topconrd.ru>, Sergei Organov wrote: > Dave Benjamin writes: >> In article <1082549174.163233 at ns.topconrd.ru>, Sergei Organov wrote: > [...] >> > Yet nobody mentioned that we don't have lower-case digits ;) >> > >> > usb201_driver <-> usb201Driver <-> usb2??Driver >> >> Hey, as long as Perl is adding French quotes to the language, why don't we >> dig around in Unicode for some lower case numerals? I bet you could find >> some if you looked hard enough, in between the Klingon alphabet and >> Dingbats 47 perhaps... =) > > Or we can use underscore in this case: 'usb201_Driver', where underscore > means "camelize previous number" :) Careful what you suggest - Perl 6 might add that as an operator! Joe From bart_nessux at hotmail.com Fri Apr 30 19:43:37 2004 From: bart_nessux at hotmail.com (Bart Nessux) Date: Fri, 30 Apr 2004 19:43:37 -0400 Subject: calling functions at the same time References: <1095ijdb5jotvf1@corp.supernews.com> Message-ID: Cameron Laird wrote: > In article , > bart_nessux wrote: >>I need a script to call several functions at the same time. How does one >>call more than one function simultaneously? >> >> >> > > This has several smart-alecky answers, including "you don't", > and "with co-routines". The best way you can help yourself is > to describe a concrete situation where your (Python?) script > has a need to call even two functions simultaneously. I need to ping 4 hosts at exactly the same time from the same machine (I plan to timestamp the pings) to test and measure network conditions over different routes to different hosts. Putting all the ping hosts in a list and looping through it is not a fair or balanced way to do this because of the time differences. > It turns > out "simultaneously" has a plethora of meanings, and you're the > only one in a position to get others to understand which you > have in mind. I mean it to mean: at the *exact* same time... concurrently. Like runners starting a race together. > > It'll also help to know whether you mean "function" as specific > to the Python language, or more abstractly, as a unit of useful > accomplishment. Specific to Python. From deetsNOSPAM at web.de Wed Apr 21 05:17:20 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Wed, 21 Apr 2004 11:17:20 +0200 Subject: Can't spawn, or popen from daemon References: <1082481539.1395.21.camel@localhost> Message-ID: Not sure why its not working for you, but I have a similar situation where I use daemonize and I can spawn using popen2.popen3: out, inn, err = popen2.popen3(_.crm_executable % (path, program)) -- Regards, Diez B. Roggisch From gerrit at nl.linux.org Fri Apr 9 07:46:51 2004 From: gerrit at nl.linux.org (Gerrit) Date: Fri, 9 Apr 2004 13:46:51 +0200 Subject: List vs tuples In-Reply-To: <107bn9jtoafb921@news.supernews.com> References: <107bf8q8fhsmg5e@news.supernews.com> <107bn9jtoafb921@news.supernews.com> Message-ID: <20040409114651.GA6923@nl.linux.org> John Roth wrote: > This is perfectly true, but that's the intention. Guido says > so himself. Lots of people either don't believe him, or > don't understand him. I belong to the second group. I do understand the argument that for some kind of data, a subslice doesn't make sense. But then I think, why is it a sequence at all? It's easy to type 'return a,b,c'. But if the calling function only needs c, it does not enhance readablilty if it does foo()[2]. So personally I much prefer a function which then returns a dictionairy where the keys are strings and the values a, b and c, so that the code is more readable. Maybe it would be even better to have simple syntax for constructing an object with attributes a, b an c. For example timetuple. Why is timetuple a sequence at all? Until some Python version, the weekday would me timetuple[i], which is not friendly to the eye. Now you can fetch it through an attribute, which is much better, but I still think the order of the "elements" of a time don't make sense. Who thinks of time, coordinates, a database record or similar as a sequence? Does a high-level, object-oriented language need tuples at all? yours, Gerrit (who very rarely uses tuples). -- Weather in Amsterdam Airport Schiphol, Netherlands 09/04 12:25: 8.0?C Scattered clouds mostly cloudy wind 4.0 m/s N (-2 m above NAP) -- Experiences with Asperger's Syndrome: EN http://topjaklont.student.utwente.nl/english/ NL http://topjaklont.student.utwente.nl/ From hungjunglu at yahoo.com Mon Apr 5 00:04:36 2004 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 4 Apr 2004 21:04:36 -0700 Subject: Working with a list in a more ?pythonic? way References: <20040404124833458+0200@news.rhrz.uni-bonn.de> Message-ID: <8ef9bea6.0404042004.213adfb1@posting.google.com> Peter Otten <__peter__ at web.de> wrote in message news:... > > def calcScore(phrase): > return reduce( > lambda (sigma, last), i: (sigma + soundScoreMatrix[last][i], i), > map(lambda c: ord(c)-65, phrase[1:]), (0, ord(phrase[0])-65))[0] That's it! Great! "Tail call" in functional programming for emulating loop variables in imperative programming (the "last" variable in this case.) However, whenever functional languages get to the point of using tail calls, I think they get into a sad state of affair. It's basically using functional language to do imperative programming. In imperative languages you would have a sequence of lines for the assignments, and in functional language you pile them up as arguments to the left in the tail call, effectively emulating states. It's like writing a program horizontally. :) Hung Jung From jgrahn-nntq at algonet.se Sat Apr 24 08:39:35 2004 From: jgrahn-nntq at algonet.se (Jorgen Grahn) Date: Sat, 24 Apr 2004 12:39:35 +0000 (UTC) Subject: How to check if a path *could* be a legal path? References: Message-ID: [top-posting fixed] On Tue, 20 Apr 2004 09:07:51 -0500, Larry Bates wrote: > "Maciej Sobczak" wrote in message > news:c62ums$b3b$1 at atlantis.news.tpi.pl... >> Hi, >> >> I have a string. >> This string is to be used as a path for a new file. >> I would like to check if this string *could be* a valid file name, >> *before* I try to create the file itself. >> In other words, I would like to know whether some string violates the >> underlying OS's policies (or maybe some more restriced policies, but >> portable) considering file paths. > It is much easier to put your code that would create the > path inside a try block and just have an exception that > handles the failure. If most of the time the path is > legal, it is faster also. That strategy would fail in lots of situations where the path is actually well-formed, i.e. permission flags, non-existing directories, files where directories are expected ... But I agree that it generally seems better to detect failures here. And I think it's generally better to fail /hard/ here and let the user fix it, than try to fix the situation yourself - doing that would be awfully tricky in the general case. By the way, for Unix the test is pretty easy. It's more or less def isValid(path): return path and not '\0' in path /Jorgen -- // Jorgen Grahn Would You Let One Marry Your Sister?'' From mgibson at tripwire.com Tue Apr 20 19:16:33 2004 From: mgibson at tripwire.com (uebertester) Date: 20 Apr 2004 16:16:33 -0700 Subject: md5.hexdigest() converting unicode string to ascii References: <77b925de.0404151450.5c1f720a@posting.google.com> <77b925de.0404161337.3917ef56@posting.google.com> Message-ID: <77b925de.0404201516.7941cd83@posting.google.com> "Fredrik Lundh" wrote in message news:... > "uebertester" wrote: > > > None of the suggestions seem to address the issue. sValue = > > _winreg.QueryValueEx(y,"") returns a tuple containing the following > > (u'http://', 1). The string u'http://' is added to the md5 object via > > the update() and then hashed via hexdigest(). How do I keep the > > unicode string from being converted to ascii with the md5 functions? > > krzysztof already explained this: > > - MD5 is calculated on bytes, not characters. > - Unicode strings contain characters, not bytes. > - if you pass in a Unicode string where Python expects a byte string, > Python converts the Unicode string to an 8-bit string using the default > rules (which simply creates 8-bit bytes with the same values as the > corresponding Unicode characters, as long as the Unicode string only > contains characters for which ord(ch) < 128). > - if you're not happy with that rule, you have to convert the Unicode > string to a byte string yourself, using the "encode" method. > > m.update(u.encode(encoding)) > > - if you don't know what encoding you're supposed to use, you have > to guess. if it doesn't matter, as long as you remember what you used, > I'd suggest "utf-8" or perhaps "utf-16-le". > > > Or can I? > > given how things work, the "how do I keep the string from being > converted" doesn't really make sense. > > Thanks for the clarification. My confusion stemed from the Python Library Reference which states, "Its use is quite straightforward: use new() to create an md5 object. You can now feed this object with arbitrary strings using the update() method, and at any point you can ask it for the digest...". I've attempted the suggested solution specifying different encodings, however, the hash value that is returned does not match what I expect based upon another utility I'm checking against. Hash value returned by python specifying utf16 encoding: 731f46dd88cb3a67a4ee1392aa84c6f4 . Hash value returned by other utility: 0b0ebc769e2b89cf61a10a72d5a11dda . Note: I've tried other encoding also. As the utility I'm verifying against is extensively used, I'm assuming it is returning the correct value. I appreciate any help in resolving this as I'm trying to enhance an automated test suite written in python. Thanks From project5 at redrival.net Thu Apr 8 16:59:08 2004 From: project5 at redrival.net (Andrei) Date: Thu, 8 Apr 2004 22:59:08 +0200 Subject: List vs tuples References: Message-ID: <2cwtb2209b5b$.1tat8f32c6zi2.dlg@40tude.net> Mitja wrote on Thu, 8 Apr 2004 18:47:07 +0200: > A neewbie's question here, probably discussed before: > what's the purpose of having both lists AND tuples? > At the first (and second and third, to be honest) glance lists are just > tuples with extended functionality, so why have tuples around? You can use tuples as keys in a dictionary, but you can't use lists for that purpose (because they're mutable). > I've been working with Python for a few months now but haven't yet come > across a problem that would really require tuples. That's possible. Lists offer many more facilities than tuples (mainly due to them being mutable), so it's easier to just use a list (even if a tuple could do the job). -- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5 at jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From stach at fr.USUN.pl Fri Apr 16 17:06:12 2004 From: stach at fr.USUN.pl (Krzysztof Stachlewski) Date: Fri, 16 Apr 2004 23:06:12 +0200 Subject: Error copying a file In-Reply-To: References: Message-ID: Peter Hansen wrote: > Okay, any reason not to call this a bug in the Windows version of > Python, when os.path.isfile can handle the name but Python can't > open or copy the file? Hmmm... isfile() apparently uses some OS functions that don't check for valid characters in filenames. If it is a bug then it is a bug within Windows. But from the Windows point of view, a " in filename is simply some piece of corrupted data so it can do anything with it. It's good it doesn't display BSOD. ;-) -- Stach Tlen: stachobywatelpl, GG: 1811474 Jabber: stach at jabber atman pl From steveb428pleaseremovethis at hotmail.com Sat Apr 3 17:06:47 2004 From: steveb428pleaseremovethis at hotmail.com (DilbertFan) Date: Sat, 03 Apr 2004 22:06:47 GMT Subject: beginner import confusion References: <406f2fe7$1@nntp0.pdx.net> Message-ID: packages, okay... , yes, thank you.. got it, back to one of my O'Reilly books "Scott David Daniels" wrote in message news:406f2fe7$1 at nntp0.pdx.net... > DilbertFan wrote: > > > Hi, > > I really thought that I had this importing business down. > > I recently downloaded and installed mx module for the DateTime class. > > > > In IDLE, I go: > > import mx > > mx.DateTime.DateTime(2004) > > I get AttributeError: 'module' object has no attribute 'DateTime' > > mx is a package, mx.DateTime is a module; you need to import a module > to get to its contents. > > > but if you type: > > import mx.DateTime > > mx.DateTime.DateTime(2004) > > > > If you "import mx", ... doesn't that get everything? > If mx were a module, you would be right. However, it is a "package," > a collection of modules and packages. Packages are a way of keeping > the names one provider of many python modules from conflicting with > the module names of both you and python itself. > > > If you know, from the docs, that it contains a DateTime class > > and then a DateTime object, > mx.DateTime.DateTime is a class, not an object. > You could do: > from mx.DateTime import DateTime > to simply get the DateTime class and then use DateTime(2004). > > -- > -Scott David Daniels > Scott.Daniels at Acm.Org From newsgroups at jhrothjr.com Mon Apr 26 14:03:00 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 26 Apr 2004 14:03:00 -0400 Subject: how to add new print %b format to python? References: Message-ID: <108qjne9jqtit4c@news.supernews.com> "Rusty Shackleford" wrote in message news:slrnc8q9qp.htc.rs at frank.overlook.homelinux.net... > I have a Summer in front of me without any school, and I'd like to add a > new format for python print strings that will show any number in a > binary representation. For example: > > >>> '%b' % 3 > 11 > >>> '%b' % 5 > 101 > > You get the idea. I've written functions that return strings, so that > part is done, but where do I go to tinker with the python interpreter to > add this new format? > > Please don't argue with me about whether this is an advisable goal in > itself -- I'm using it as a method to learn about the internals of the > python language. Well, if I was familiar with the internals, I'd start with the code that implements the string object, since it's simply an overload of the '%' operator. Sorry I can't help you with a module name, though. To actually get it added to the core, you need to write a PEP and champion it through the process. Writing a reference implementation and the documentation is also a necessity. There's a PEP that explains the documentation standards for Python C language code; if your patch follows that you've improved your chances by some significant amount. John Roth From peter at engcorp.com Thu Apr 1 09:38:45 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 01 Apr 2004 09:38:45 -0500 Subject: GUI Frameworks in Python? In-Reply-To: <6ee58e07.0403311125.52f0acf0@posting.google.com> References: <6ee58e07.0403311125.52f0acf0@posting.google.com> Message-ID: Lothar Scholz wrote: > Peter Hansen wrote in message news:... > > >>Go figure. (And as I said this is an AMD 2200 with 512MB RAM, XP Pro.) > > > You and all others miss one important number: What a harddisk are you > using ? > A notebook with a 4200rpm has a much lower startup time then a > 7200rpm. It is as strange as a 10 against 2 seconds for the same > program on WinXP when compiled with Borland instead MS Visual C. An excellent question... My hard disk is a "lightning fast" Seagate 120GB 7200 RPM Serial-ATA drive with liquid bearings and an 8MB cache... Clearly it's those liquid bearings that make it so fast. ;-) -Peter From huzhenghui37 at tom.com Tue Apr 6 11:40:47 2004 From: huzhenghui37 at tom.com (huzhenghui37) Date: Tue, 06 Apr 2004 23:40:47 +0800 Subject: about the path of extensive modules Message-ID: <4072CF7F.5080603@tom.com> with my experience when i install the wxPython the installer put all things in the python\Lib\site-packages\ and from the source code "import wxpthon.wx" i know how import the modules when i install the py2exe the installer also put all things in the python\Lib\site-packages\ so i wonder the information about the method of modules path management in python. and if i write my own package of modules how to use (say, install) in python thanks From andrew-pythonlist at puzzling.org Thu Apr 1 06:52:37 2004 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Thu, 1 Apr 2004 21:52:37 +1000 Subject: How to connect multiple class instances to 1 Twisted factory? In-Reply-To: References: Message-ID: <20040401115237.GB14703@frobozz> On Wed, Mar 31, 2004 at 08:07:00PM -0500, Qp wrote: > Is this even possible? I'm designing a simple chat and game client/server > as an intro to Python, and it would be nice to represent the different > interfaces (public chat room, private chat rooms, game instances) as totally > seperate classes and show them in totally seperate windows. > > Given my basic understanding of Twisted, I see no way of doing this, and my > whole GUI is contained in one class. The project is doable this way, it > would just be much better with multiple class and multiple window > seperation. > > If anyone can give me any direction, I would appreciate it very much. This sounds feasible to me, although I'm no Tk expert. Try asking on the Twisted mailing list (twisted-python at twistedmatrix.com). -Andrew. From ville at spammers.com Wed Apr 28 09:33:46 2004 From: ville at spammers.com (Ville Vainio) Date: 28 Apr 2004 16:33:46 +0300 Subject: Is Perl *that* good? References: <108v74768o9sb9f@corp.supernews.com> Message-ID: >>>>> "Cameron" == Cameron Laird writes: Cameron> my provisional conclusion: my past attempts to track Cameron> down claims of the "Perl is tops for string-handling" Cameron> sort generally reinforced the proposition that the Cameron> speaker simply meant, "Perl privileges REs" (and that Cameron> the speaker had no familiarity with Python, let alone Cameron> Icon or Prolog). Now I see there's a likelihood of I tend to see praises of perl string handling as an indication of just not knowing Python. Somehow people acquire weird proconceptions (tcl is best for quick uis, perl for string handling, ...) and refuse to reconsider them even if the realities that originally created the preconceptions have changed, rendering the original claim categorically false. BTW, nobody seems to miss Perl libs and CPAN anymore. A few years ago most of the complaints regarding python were that perl has more libraries. This is a good sign :-). -- Ville Vainio http://tinyurl.com/2prnb From mcfletch at rogers.com Tue Apr 27 01:21:08 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Tue, 27 Apr 2004 01:21:08 -0400 Subject: What is good about Prothon? In-Reply-To: References: Message-ID: <408DEDC4.8030504@rogers.com> Mark Hahn wrote: ... >For what it's worth, you are basicly in agreement with the current proposals >for Prothon. > > Maybe I should add designing languages to my list of projects starved for time :) . Have fun, Mike _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From simoninusa2001 at yahoo.co.uk Mon Apr 5 17:35:21 2004 From: simoninusa2001 at yahoo.co.uk (simo) Date: 5 Apr 2004 14:35:21 -0700 Subject: Module import problems References: <30260531.0404041725.746befa0@posting.google.com> Message-ID: <30260531.0404051335.27cabd5d@posting.google.com> Yay, I've done it! I had to resort to "from login import *" in main.py and then "import wx" (and other modules like urllib/webbrowser etc) in login.py and it all seems to work. I didn't occur to me that I'd have to import the modules used in each module file, I thought it would work just from the parent (main.py) file. I've also stopped myself from calling classes instead of defs (I had the whole class in the __init__ def previously) and removed most of my global variables. Now I have twelve 1-6Kb files like login.py, plus an 18Kb main.py, instead of one 38Kb main.py to grep through! So it was worth the struggle to clean up a bit.... From claird at lairds.com Sun Apr 4 13:20:37 2004 From: claird at lairds.com (Cameron Laird) Date: Sun, 04 Apr 2004 17:20:37 -0000 Subject: emergent/swarm/evolutionary systems etc References: <106um6hcr363u14@corp.supernews.com> Message-ID: <1070gv5586u8mc2@corp.supernews.com> In article , Peter Hansen wrote: . . . >> LISP brought it to mind. Although LISP doesn't look that much better than >> Python code, are there any programs out there that let you program, um, >> programs, using various shapes, colours etc? Just thinking about it brings >> up all manner of difficulties that would be encountered if you tried to >> create such a thing, but it would be nice if there was some immediately >> obvious graphical connection between pieces of code [...] > >Using the "G" graphical language of LabVIEW, all code ends up >_literally_ looking like spaghetti... would that help? ;-) > >-Peter LabVIEW's the first example that came to my mind, although perhaps Prograph or JavaBeans (!) could be argued as more commercially successful. I've worked on VPLs a couple of cycles in my career already, in process-control contexts. My enthusiasm is tepid--but then I've exceedingly text-oriented. -- Cameron Laird Business: http://www.Phaseit.net From rogerb at rogerbinns.com Tue Apr 27 17:30:56 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Tue, 27 Apr 2004 14:30:56 -0700 Subject: Tkinter vs. wxPython? References: <408E9DCA.EC753FE6@shaw.ca> Message-ID: <9103m1-v2i.ln1@home.rogerbinns.com> SeeBelow at SeeBelow.Nut wrote: > Do many people think that wxPython should replace Tkinter? Is this > likely to happen? > > I ask because I have just started learning Tkinter, and I wonder if I > should abandon it in favor of wxPython. wxPython comes with a demo which includes sample code for almost all the different controls. I would recommend looking at the demo (and sample code) to see the scope of wxPython. The sample code will give you an idea of how readable the code is. In the end I used wxPython because I wanted things like printer support. Roger From peter at engcorp.com Fri Apr 9 11:01:45 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 09 Apr 2004 11:01:45 -0400 Subject: program distribution In-Reply-To: <4075f5bb_1@news.iprimus.com.au> References: <4075f5bb_1@news.iprimus.com.au> Message-ID: <4dKdnQ5IXMJEJ-vdRVn-gg@powergate.ca> mr_vocab wrote: > Hi im new to python but have made a few applications how can i save them > and get the to run sort of like an application What operating system are you using? Py2exe is the usual solution for Windows machines. Google can tell you more. -Peter From areafiftytwo at wanadoo.fr Thu Apr 15 20:32:19 2004 From: areafiftytwo at wanadoo.fr (Derek) Date: Fri, 16 Apr 2004 02:32:19 +0200 Subject: Simple pyhon-based CMS References: <9396ba6f.0404131817.1219c695@posting.google.com> Message-ID: what about squishdot? I believe that sits under plone. "Stewart Midwinter" wrote in message news:9396ba6f.0404131817.1219c695 at posting.google.com... > I'm looking for a simple python-based CMS (content management system), > maybe with some blog-like features, ability to add articles - nothing > too fancy. Do you have any suggestions? > > I've looked at Zope / Plone: very easy to install using the rpm I > found. But it's obviously quite complex and powerful, which is no > doubt of benefit on a site that has many users. But I'm just one > person. All I want is a pythonic replacement for my current tool, > postNuke. > > I looked at NewzBruiser: this would probably be simple enough, maybe > even too simple, but it requires that I enable SSI support on Apache, > something I seem to be unable to accomplish (I run SME server from > contribs.org and it uses a byzantine templating system for its > configuring, which leaves me in the dark on how to modify httpd.conf > there). > > Any other ideas? > > thanks > Stewart in Calgary From sridharinfinity at yahoo.com Sat Apr 3 05:51:48 2004 From: sridharinfinity at yahoo.com (Sridhar R) Date: 3 Apr 2004 02:51:48 -0800 Subject: Parrot for Python Message-ID: <930ba99a.0404030251.c2d2107@posting.google.com> Hi, I come across the Parrot project. Seems like it is a better compromising alternative for .NET and Java. That is, we can develop applications in Python (for productivity) and still can interact with components written in other languages, as they were compiled to the parrot byte code. But my concern is, how will Python interoperate with Parrot. Since, Python has strong interospection, won't it be difficult to generate parrot code from python source file. For doing a simple attribute reference, a.b = 10 the parrot code will be bigger (dict find, get, assign ...) Another question. Why is Java so popular than Python. Are the technologies for Java available for Python (no ... no jython)? We can implement them in python if we want. But the difference is speed. From adonisv at REMTHISearthlink.net Mon Apr 26 20:55:43 2004 From: adonisv at REMTHISearthlink.net (Adonis) Date: Tue, 27 Apr 2004 00:55:43 GMT Subject: Question on creating Tkinter Widgets Message-ID: I am creating some widgets by inheriting from Tkinter.Frame and populating the frame with whatever the widget will be then creating certain attributes/methods to be accessed later. My question is, is this a poper way to create widgets or should I take a different approach? Any help is greatly appreciated. Adonis From peter at engcorp.com Fri Apr 2 08:00:50 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 02 Apr 2004 08:00:50 -0500 Subject: Simple text markup (-> HTML) In-Reply-To: References: <406D3EAA.16466030@alcyone.com> Message-ID: Jacek Generowicz wrote: > Erik Max Francis writes: >>reStructredText. Bigtime. > > Way cool ! > > I am rather shocked that this (or its ancestors) has not registered on > my radar before now. It's ancestors, at least in the "Structured Text" world, weren't up to the task. But they didn't have David Goodger behind them... -Peter From michael at foord.net Thu Apr 1 02:18:32 2004 From: michael at foord.net (Fuzzyman) Date: 31 Mar 2004 23:18:32 -0800 Subject: Why '==' ?? References: <8089854e.0403302319.1ab56af0@posting.google.com> Message-ID: <8089854e.0403312318.77d465f@posting.google.com> Josiah Carlson wrote in message news:... > > if a = 3 > > print 'Yeah baby' > > > > are still *unambiguous*.... yet the interpreter refuses to understand > > you...... > > Oh, the CPython interpreter understands you, it just doesn't like what > you say. I (and I'm sure the majority of other Python users) agree with > the interpreter, your modified syntax leaves something to be desired. > > You syntax also /makes ambiguous/ the following currently valid Python > syntax... > > if a == 3: \ > print "hello" > > If we converted that to /your/ syntax, it would read... > Not at all...but there you go... you need to reread what I said :-) > if a = 3 \ > print "hello" > > Which would get internally translated to... > > if a = 3 print "hello" > > I don't think it makes sense, and I wouldn't expect an interpreter to > think it makes sense of it either. > > > > Theres no reason why a single '=' shouldn't be understood in a > > conditional.... > > Except that it would be a 'special case' when two different syntactical > symbols mean the same thing. > "Special cases aren't special enough to break the rules." > - The Zen of Python, by Tim Peters > Not at all. No need for a special case. Leave '==' with the same meaning as it currently has... but give '=' a dual meaning (as it has in reality) with the meaning obvious from context. In 'multi statements' (or whatever the correct phrase is to pre-empt any more otiose comments) require '==' so the syntax is clear. Ie. If the meaning is obvious.... '=' can replace '=='... if it's not.. it can't... > > As for needing a ':' to allow statements after a 'def' or a > > conditional.... python already has the ';' for that... why insist on a > > ':' > > Do you even read the docs? Sorry.. didn't realise memorising the entire python documentation was a requirement before posting :p > Python does not have ';' to allow statements Actually - *you've* completely misread the sense of what I've written ;-) > after a def, Python has ';' because it allows you to place more than one > statement on a single line. Yup. > That is, it allows... > a = 1;b = 2;c = 3; > > /not/ because it allows the absolutely ugly: > def fun(a,b): print a,; print b; > > You should note that ':' is placed in syntactically different locations > than ';', because they have syntactically different meanings. ':' means > "there is some scope that is being enclosed", Which is unnecessary *as far as I can see* - because it's always obvious that some scope is being enclosed......... You've failed to show any case where that's not true. (Although I wouldn't be surprised if it was..). The reason some people stated it was necessary was to allow another statement on the same line... which is what I said ';' was for. Sorry if you enjoy flaming newbies....... but in this case you'r a bit off beam Josian old bean............. Regards, Fuzzy (Recent python convert) http://www.voidspace.org.uk/atlantibots/pythonutils.html > while ';' means "that is > the end of the previous statement". > > > - Josiah From skip at pobox.com Mon Apr 26 11:48:33 2004 From: skip at pobox.com (Skip Montanaro) Date: Mon, 26 Apr 2004 10:48:33 -0500 Subject: Best way to add attributes to shelved objects? In-Reply-To: <20040426150535.GA63648@dogma.freebsd-uk.eu.org> References: <20040423193951.GC27351@dogma.freebsd-uk.eu.org> <16521.29527.356495.151656@montanaro.dyndns.org> <20040426150535.GA63648@dogma.freebsd-uk.eu.org> Message-ID: <16525.12113.839367.623697@montanaro.dyndns.org> skip> Why not check for those attributes in your __getstate__ method and skip> add default (or computed) values for any missing attributes? jm> I tried experimenting with these, and could not get them to work. ... jm> Are there any examples on how to do this? How about: class Foo: def __init__(self): self.a = 1 def __setstate__(self, d): if 'b' not in d: d['b'] = 2 self.__dict__ = d f = Foo() print hasattr(f, "a"), hasattr(f, "b") import pickle pfile = file("test.pck", "wb") pickle.dump(f, pfile) pfile.close() f = pickle.load(file("test.pck", "rb")) print hasattr(f, "a"), hasattr(f, "b") Skip From mark at prothon.org Sun Apr 25 23:58:42 2004 From: mark at prothon.org (Mark Hahn) Date: Sun, 25 Apr 2004 20:58:42 -0700 Subject: Why we will use obj$func() often References: <84Uhc.22278$dZ1.5087@fed1read04> <8AWhc.23114$dZ1.11070@fed1read04> <40883BFE.B381518A@alcyone.com> <27_hc.23801$dZ1.2716@fed1read04> <40887145.789A2FE8@alcyone.com> <7cki80hj976bia36lhf9er97v073o1pqvm@4ax.com> <1082783076.585831@yasure> Message-ID: "Greg Ewing" wrote in message news:c6hvdk$bs63j$1 at ID-169208.news.uni-berlin.de... > Mark Hahn wrote: > > The advantage of prefix symbols that Ruby and Prothon use right now is that > > the compiler and the program reader don't have to scan the code at all to > > see what scope the var belongs to. When you see the & you know it's in the > > surrounding function, > > Hang on a minute. Do you literally mean the immediately > surrounding function, and not one further out? In > > def f(): > def g(): > def h(): > &x = 42 > h() > g() > print x > > does the &x in h refer to the x in f? If it does, then I > don't see how you can deduce that in a single pass. If it > doesn't, then how do you refer to the x in f from h? You cannot. Yes it literally means the immediately surrounding function. In your example, I can't think of any scheme we've discussed that accesses x in function f. Python surely cannot. I understand this is quite limiting, but it's simple. As always, I'm open to suggestions... From andreas.lobinger at netsurf.de Wed Apr 21 04:28:51 2004 From: andreas.lobinger at netsurf.de (Andreas Lobinger) Date: Wed, 21 Apr 2004 10:28:51 +0200 Subject: PDF library? References: <7xad1631j8.fsf@ruckus.brouhaha.com> <7xzn96drse.fsf@ruckus.brouhaha.com> Message-ID: <408630C3.2BD8F7CE@netsurf.de> Aloha, Paul Rubin schrieb: > Simon Burton writes: > > http://www.reportlab.org/ > > handles pdf files. > Reportlab generates reports in pdf format, but I want to do the > opposite, namely read in pdf files that have already been generated by > a different program, and crunch on them. Any more ideas? Thanks. The commercial version (reportlab.com) mentions a tool named PageCatcher, that seems to be able to extract pages and page descriptions out of .pdf documents. There is not that many information on the web-page. If you read comp.text.tex you will find various solutions for composing and a few for extracting data/content from .pdf documents. Afaik there is at the moment (read as: i'm working on it) no free-self-contained- python solution. But as python is very interface-friendly you can use general tools like gs easily. For your problem i would suggest to use gs als a .pdf to .ps filter in the first place, work on the .ps and distill back with gs. Wishing a happy day LOBI From joe at notcharles.ca Sun Apr 4 00:22:14 2004 From: joe at notcharles.ca (Joe Mason) Date: Sun, 04 Apr 2004 05:22:14 GMT Subject: Python is faster than C References: <406F0907.96F37EA1@tunes.org> <7xy8pcogaa.fsf@ruckus.brouhaha.com> <406F454B.C4CC8063@tunes.org> <7xekr4vdek.fsf@ruckus.brouhaha.com> <406F5E95.EBE6D3E8@tunes.org> Message-ID: In article <406F5E95.EBE6D3E8 at tunes.org>, Armin Rigo wrote: > Another example would be 'a'*999999999: the result is a string, but > there is no reason that it takes 100MB of memory. Instead, store it > into a C structure that contains a pointer to the original string object > 'a' and the repetition counter, but still give this C structure the > Python type str, so that the difference doesn't show up and the Python > language remains simple. (This is a bit difficult to implement > currently in CPython, but not impossible.) What this does is makes the interpreter more complicated for features that not all programs will use. Only a very few programs will have long strings of repeated characters, and it's reasonable to ask them to implement their own stringlike class if they really want it. If this is built into the interpreter, then either it's an optional feature, in which case all those programs that rely on it to be remotely memory-efficient aren't portable, or it requires every single implementation to include it, including the PalmOS port and the one that's supposed to run on cell phones. Joe From stach at fr.pl Fri Apr 16 09:13:48 2004 From: stach at fr.pl (Krzysztof Stachlewski) Date: Fri, 16 Apr 2004 15:13:48 +0200 Subject: md5.hexdigest() converting unicode string to ascii References: <77b925de.0404151450.5c1f720a@posting.google.com> Message-ID: "Fredrik Lundh" wrote in message news:mailman.687.1082117438.20120.python-list at python.org... > (unicode characters are characters too, you know...) You're right. :-) Stach From osv at javad.ru Thu Apr 22 07:10:48 2004 From: osv at javad.ru (Sergei Organov) Date: 22 Apr 2004 15:10:48 +0400 Subject: CamelCase versus wide_names (Prothon) References: <6ee58e07.0404192141.2229efd6@posting.google.com> <1082549174.163233@ns.topconrd.ru> Message-ID: <1082632248.524260@ns.topconrd.ru> Dave Benjamin writes: > In article <1082549174.163233 at ns.topconrd.ru>, Sergei Organov wrote: [...] > > Yet nobody mentioned that we don't have lower-case digits ;) > > > > usb201_driver <-> usb201Driver <-> usb2??Driver > > Hey, as long as Perl is adding French quotes to the language, why don't we > dig around in Unicode for some lower case numerals? I bet you could find > some if you looked hard enough, in between the Klingon alphabet and > Dingbats 47 perhaps... =) Or we can use underscore in this case: 'usb201_Driver', where underscore means "camelize previous number" :) From peter.maas at mplusr.de Fri Apr 2 11:08:51 2004 From: peter.maas at mplusr.de (Peter Maas) Date: Fri, 02 Apr 2004 18:08:51 +0200 Subject: Python conference slogan In-Reply-To: References: <30260531.0404010833.1b834032@posting.google.com> <406C4DDF.5000907@zope.com> Message-ID: Jacek Generowicz wrote: > Peter Maas writes: > > >>These slogans are meaningless to (Monty) Python outsiders. [..] > A previous slogan was: > > Python: Programming the way Guido indented it. > > Pretty meaningless to Python outsiders, I'd say. No. Because an outsider will read 'intended it', at least I did. And that's not wrong, either :) The first poster (at least in my news reader) didn't tell anything about the purpose. For me a slogan's purpose is advertising and it's useless to advertise Python to people who like it already. Mit freundlichen Gruessen, Peter Maas -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Hubert-Wienen-Str. 24 Tel +49-241-93878-0 Fax +49-241-93878-20 eMail peter.maas at mplusr.de ------------------------------------------------------------------- From loic at yermat.net1.nerim.net Wed Apr 28 15:38:57 2004 From: loic at yermat.net1.nerim.net (Yermat) Date: Wed, 28 Apr 2004 21:38:57 +0200 Subject: Path ... where is my application's home dir? In-Reply-To: References: Message-ID: Peter Hansen a ?crit : > Yermat wrote: > >> Duncan Booth a ?crit : >> And for the user dir, you can do (at least on Win2000, not try >> elsewhere) : >> os.getenv('HOMEDRIVE') + os.getenv('HOMEPATH') > > > Also works on WinXP. (And the last statistic I saw showed Win98 > users at something like 2% of the Windows-using population, > so perhaps we can almost forget about it... ?) > > -Peter Good point ! Browsing old messages from clp in google. It seems the only way to do this on win98 is to read it in the registry... -- Yermat From Scott.Daniels at Acm.Org Sun Apr 4 17:32:12 2004 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sun, 04 Apr 2004 14:32:12 -0700 Subject: Difference between default arguments and keyword arguments In-Reply-To: <7vUbc.11592$yN6.3751@newsread2.news.atl.earthlink.net> References: <406FFEAF.3080400@netscape.net> <7vUbc.11592$yN6.3751@newsread2.news.atl.earthlink.net> Message-ID: <40707EDC.8090004@Acm.Org> Edward Diener wrote: > ... Makes sense. Thanks ! The tutorial should explain it more clearly. Right now you know what is confusing about the tutorial. _Please_ take the time to propose a fix to the tutorial -- you have an "impertise" (as opposed to "expertise") that tells you confusing interpretations of the text of the tutorial. Once you just know" this stuff, you won't be able to know what is confusing. So the time you spend, _right_now_ is the most valuable contribution you can make to Python for a while. Help us improve our documents. -- -Scott David Daniels Scott.Daniels at Acm.Org From devnull at example.com Mon Apr 26 23:00:57 2004 From: devnull at example.com (Derek Fountain) Date: Tue, 27 Apr 2004 11:00:57 +0800 Subject: 404 errors Message-ID: <408dcc25$0$16577$5a62ac22@freenews.iinet.net.au> I'm probably a bit off topic with this, but I'm not sure where else to ask. Hopefully someone here will know the answer. I'm writing a script (in Python) which reads a webpage from a user supplied URL using urllib.urlopen. I want to detect an error from the server. If the server doesn't exist, that's easy - catch the IOError. However, if the server exists, but the path in the URL is wrong, how do I detect the error? Some servers respond with a nicely formatted bit of HTML explaining the problem, which is fine for a human, but not for a script. Is there some flag or something definitive on the response which says "this is a 404 error"? From mark at prothon.org Wed Apr 21 14:25:48 2004 From: mark at prothon.org (Mark Hahn) Date: Wed, 21 Apr 2004 11:25:48 -0700 Subject: CamelCase versus wide_names (Prothon) References: <407ec022$0$54153$1b2cd167@news.wanadoo.nl> Message-ID: "Christos TZOTZIOY Georgiou" wrote ... > you'll have to be more firm and decisive, I hope you know that... You've chosen an interesting time to make that comment. Before Prothon I've had zero experience moderating anything, much less the barrage of opinions that come into the language design process. When I first started I thought everyone's opnion mattered and that I had the job of merging eveyone's ideas into a grand scheme that made everyone happy . Now I am discovering that everyone has there own agenda and that to a certain degree the more we discuss, the more people polarize around their own agenda instead of converging on a shared solution. We have idea's that range from pure Self, to pure Python, to pure Lisp, to pure original Prothon. I think I have recently found a smattering of people who really do go with the flow and we are starting to make some real progress (knock on wood). The good news is that ultimately I have the BDFL powers and can use them when needed. Just having the power is what is important. It is not the using of them that is important. From herrn at gmx.net Tue Apr 6 16:52:54 2004 From: herrn at gmx.net (Marco Herrn) Date: 6 Apr 2004 20:52:54 GMT Subject: user authentication via /etc/passwd|/etc/shadow References: Message-ID: On 2004-04-04, Martin v. L?wis wrote: > You need a combination of the pwd and crypt modules. Lookup the name > of the user using the pwd module, and fetch the encrypted password. > Then use crypt.crypt for encryption; use the first two letters of > the encrypted password as the salt. > > Be aware that some installations use MD5 passwords, which can be > recognized by starting with $1$ (or some such). A question to this md5 and sha1 hashed passwords. The python modules for these are different to the crypt module. Especially there is no salt. So how would I compare a given password to a given hash? Just rehash the password? Would the hash always be the same? I thought the salt was there to improve security. And how can I distinguish a these hash methods? For example I have a hash. How do I find out which hash method was used for this? As I have seen md5 hashs are always 128 bit long. When I have such a hash in hex form, can I say if that hash string has a length of 32 it is definitely a md5 hash, a length of 40 indicating a sha hash and a length of 13 indicating a crypt() hash? And what about the prefix $1$ for md5? When this is available just cut it off the hash? Are there any other forms of such prefixes? Sorry for this lot of questions. ;-) Marco -- Marco Herrn herrn at gmx.net (GnuPG/PGP-signed and crypted mail preferred) Key ID: 0x94620736 From michele.simionato at poste.it Sun Apr 4 09:48:30 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 4 Apr 2004 06:48:30 -0700 Subject: emergent/swarm/evolutionary systems etc References: Message-ID: <95aa1afa.0404040548.47e7967f@posting.google.com> "Peter MacKenzie" wrote in message news:... > In addition to exams, I also must start a dissertation in July for my > geography hon B.Sc. Although I should ideally have found a subject two > months ago, I've so far lacked any truly appealing project ideas (much to > the consternation of my advisor). Since reading 'Emergence', by Steven > Johnson, and conducting prelimenary research on the matter, I've settled on > the dissertation title: "Emergence theory as an approach to city design". > > To this goal, I'd like to use computer modeling to simulate ways in which > the spatial distribution of indicator phenomena in cities (land price/use, > crime, demographic composition etc) is affected by bottom-up, local area > rules. Given that I have only a basic foothold on the language, does > anybody foresee difficulties for me learning enough to impliment simple and > experimentally flexible sim-city style simulations (minus fancy graphics and > llamas) in no more than 2 months (to allow for time to conduct actual > experiments + field observations etc)? I would be able to engender aid from > various staff, and the university library should carry titles on the > subject. Failing that, I could do it the old fashioned way and buy a how-to > book, but I'd like some opinions on the difficulty of the goal from people > who've already trancended the non-programmer/programmer barrier. I would suggest you to forget about this project and to spend those two months in learning the basis of Python. IMO learning a programming language will do to your mind a far better good than learning a spreadsheet. Having said so, it is ok if you keep this project in the back of your mind while you learn programming, but do not expect you can finish it in a couple of months starting from scratch, without guidance and not working on it full time. OTOH, a couple of months is enough to get the basics of programming (which is not the same as becoming a programmer). I would estimate the time to get a minimal understanding of modern programming in one year. Still, notice that I estimate the time to write your first useful program in Python in five minutes, so you will get back something from your effort immediately. This is the nice thing about programming. The bad thing are bugs, that you will get well before the first five minutes ;) Michele Simionato From sholden at holdenweb.com Fri Apr 30 12:40:48 2004 From: sholden at holdenweb.com (Steve Holden) Date: Fri, 30 Apr 2004 12:40:48 -0400 Subject: Python Image Library (PIL) build error on Cygwin In-Reply-To: References: Message-ID: <40928190.5060004@holdenweb.com> Jason Tishler wrote: > Steve, > > On Thu, Apr 29, 2004 at 04:31:54PM -0400, Steve Holden wrote: > >>Does anyone know the workaround for this error, encountered when >>trying to build PIL 1.1.4 from source under cygwin (Python 2.3.3)? > > > Rebasing your system should fix the problem. See the following: > > http://www.tishler.net/jason/software/rebase/rebase-2.3.README > > Jason > Yup, now I can't find the Tk library, but the load errors are gone and the rest is fixable. This all seems very esoteric, I'm glad it's going away ... regards Steve From paddy3118 at netscape.net Thu Apr 15 23:29:29 2004 From: paddy3118 at netscape.net (Paddy McCarthy) Date: 15 Apr 2004 20:29:29 -0700 Subject: Simple db using list comprehensions References: <246a4e07.0404050626.153ff525@posting.google.com> Message-ID: <2ae25c6b.0404151929.409f9be5@posting.google.com> frank at chagford.com (Frank Millman) wrote in message news:<246a4e07.0404050626.153ff525 at posting.google.com>... > Hi all > > From time to time there is a request for a simple way of storing and > accessing data without using a full SQL database. > > I had this requirement recently, and I was pleasantly surprised by how > much I could achieve with a simple Python list and list > comprehensions. > > Assume the need to store data consisting of first name, surname and > phone number. To ensure uniqueness, I use an additional column to > store a unique id, which can just be a 'next number'. > > To create the table - > table = [] > > To initialise it with a couple of rows - > table.append([1,'Frank','Millman',12345]) > table.append([2,'John','Smith',54321]) I like the idea but think you should have a definition of something like - INDEX,FIRSTNAME,SURNAME,PHONE = range(4) You should use the names instead of all the 'magic' constants below when referring to fields in rows. Cheers, Paddy. > > To get the last id used - > last_id = max([row[0] for row in table]) > > Alternatively, if you know the rows are in id sequence - > last_id = table[-1][0] > > To add a new row - > firstname = 'Fred' > surname = 'Jones' > phone = 23456 > > First, ensure first name and surname are unique - > rows = [row for row in table if row[1] == firstname and row[2] == > surname] > if len(rows): > errmsg = 'Already exists' > > If ok, add the row - > last_id += 1 > table.append([last_id,firstname,surname,phone]) > > To select all rows according to some criteria (eg surnames starting > with 'M') - > rows = [row for row in table if row[2][0] == 'M'] > > If you need a copy of the rows - > rows = [row[:] for row in table if row[2][0] == 'M'] > > To sort the rows in surname sequence - > rows = [[row[2],row] for row in rows] # prepend surname to row for > sorting > rows.sort() > rows = [row[1] for row in rows] # remove prepended surname > > To select and sort at the same time - > rows = [[row[2],row] for row in table if row[2][0] == 'M'] > rows.sort() > rows = [row[1] for row in rows] > > To amend a phone number if you know the first name and surname - > rows = [row for row in table if row[1] == 'Fred' and row[2] == > 'Jones'] > if not rows: > errmsg = 'not found' > elif len(rows) > 1: > errmsg = 'more than one row found' > else: > rows[0][3] = phone > > To delete a row if you know the first name and surname - > rows = [row for row in table if row[1] == 'Fred' and row[2] == > 'Jones'] > if not rows: > errmsg = 'not found' > elif len(rows) > 1: > errmsg = 'more than one row found' > else: > pos = [row[0] for row in table].index(rows[0][0]) > del table[pos] > > To delete all rows with a phone number of 0 - > ids = [row[0] for row in table] > rows = [row[0] for row in table if row[3] == 0] > for row in rows: > pos = ids.index(row) > del table[pos] > del ids[pos] > > I have not tested all of these, but you get the idea. > > I did not have to save the data, but if you need to, I am sure you can > pickle it. > > Hope this is of interest. > > Frank Millman From walter at livinglogic.de Sat Apr 3 04:30:02 2004 From: walter at livinglogic.de (=?ISO-8859-1?Q?Walter_D=F6rwald?=) Date: Sat, 03 Apr 2004 11:30:02 +0200 Subject: HTML writer In-Reply-To: References: <406D3C97.7020006@livinglogic.de> Message-ID: <406E841A.2040700@livinglogic.de> Moosebumps wrote: > "Walter D?rwald" wrote in message > news:406D3C97.7020006 at livinglogic.de... > >> [...] >> >>There are several possible HTML generators for Python: >>HTMLgen http://starship.python.net/crew/friedrich/HTMLgen/html/main.html >>HyperText http://dustman.net/andy/python/HyperText/ >>XIST http://www.livinglogic.de/Python/xist/ > > > Thanks for those links, they look like what I'm looking for. Does anyone > have any comment on which one of these requires you to have the least amount > specific web programming knowledge? Each of them requires you to know what the HTML tags mean. > i.e. I know basic HTML, and I am an > experienced C programmer, but haven't really delved into the specifics of > it... never really wanted to clutter up my mind with the alphabet soup of > web programming : ). I was thinking that there was some Python library > that would wrap the functionality of these languages in some nice consistent > OO python interface. It looks like all of these are exactly that, from what > I gather, which is great. > > That is, I would not like any specific HTML tags anywhere in my own code, > and it seems like that is what they will allow me to do. But I would be > interested to hear opinions/experiences with these packages. As the author of XIST I'm naturally biased, but one advantange of XIST is that it's still actively maintained. HTMLgen and HyperText don't seem to be. To see an example take a look at http://www.livinglogic.de/viewcvs/index.cgi/LivingLogic/xist/HOWTO.xml. This XML file doesn't contain any HTML tags, but gets converted to HTML (see http://www.livinglogic.de/Python/xist/Howto.html), to XSL-FO (see http://www.livinglogic.de/Python/xist/Howto.fo) and PDF (see http://www.livinglogic.de/Python/xist/Howto.pdf) HTH, Walter D?rwald From scs2paw at leeds.ac.uk Mon Apr 19 09:27:37 2004 From: scs2paw at leeds.ac.uk (Paul A. Wilson) Date: 19 Apr 2004 06:27:37 -0700 Subject: Tkinter Button command query Message-ID: I'm new to Tkinter programming and am having trouble creating a reusable button bar... I want to be able to feed my class a dictionary of button names and function names, which the class will make. My button bar is implemented a Frame subclass, which takes the button dictionary as an argument and displays the buttons on the screen: class OptionsBar(Frame): def __init__(self, buttonDict, parent=None) Frame.__init__(self, parent) parent.someFunction() # This works fine for (name, command) in buttonDict.items(): Button(self, text=name, command=command).pack(side=TOP, fill=BOTH) and then another Frame subclass, e.g. MyWindow, uses the bar as follows: self.buttonDict = {'Button1':'someFunction', 'Button2':'otherFunction'} ... myBar = OptionsBar(parent=self, buttonDict=self.buttonDict) myBar.pack(side=RIGHT) ... def someFunction(): do button stuff My problem is that the Button instances aren't calling the correct functions when pressed. Is there anyway I get Button to call its parent frame's parent frame's functions? I've tried using self.buttonDict = {'Button1':'parent.someFunction', 'Button2':'parent.otherFunction'} but to no avail. Hope my explanations make sense. Any suggestions? Cheers PAW From sarge at arena.invalid Wed Apr 28 19:24:19 2004 From: sarge at arena.invalid (Sarge) Date: Wed, 28 Apr 2004 23:24:19 GMT Subject: MATLAB2Python Message-ID: Hi, everybody! I'm a moderately experienced programmer in Matlab, and looking for a free computational language (Matlab is *REALLY* expensive for an individual, like me). I came across Python (actually Scipy) and immediately felt comfortable with the interface and syntax. I'm still a newbe, so, before attempting a serious work on it, I'd like to hear any opinion about migration from Matlab to Python, and also a rough comparison between these two languages. Thanx in advance, and excuse me for my very bad English (I'm not a native English speaker), Sarge From mh at pixar.com Fri Apr 23 15:01:12 2004 From: mh at pixar.com (Mark Harrison) Date: Fri, 23 Apr 2004 19:01:12 GMT Subject: Goodbye TCL References: <0LudnSads6NmpuPdRVn-vw@centurytel.net> <21ccedf1.0404160639.14c2d852@posting.google.com> <1080ml0hdpp6tdf@corp.supernews.com> Message-ID: In comp.lang.tcl Donal K. Fellows wrote: > Cameron Laird wrote: > > 'Different way to say this: "database", in this sense, is a dirty > > subject, in that it's far more tied to grungy details of specific > > implementations than the masses generally realize, or than either > > Python or Tcl, both of which prize purity in their own ways, > > generally support. A general database abstraction is about as > > rarefied as a general GUI abstraction. > > I had a quick look into general DB APIs in the past, and the response I > got from the DB community at the time was "but this doesn't support this > *vital* feature only implemented in one DB that 0.01% of users really > need and therefore we could never ever use your proposal for a standard > API". It's kind of discouraging. > > FWIW, I think some mostly-common subset of functionality is possible (if > we assume SQL underneath; without that, you can't get anywhere) and it > would be enough to get most of the low-end and casual users total > satisfaction. And maybe this would encourage alteration in the high-end > interfaces to be more like each other too. > > Donal. > Python has a nice relational database API standard, which seems to be well implemented across several databases, although I've only used the postgresql one myself. http://www.python.org/peps/pep-0249.html Cheers, Mark -- Mark Harrison Pixar Animation Studios From no_replies at fake_email_address.invalid Thu Apr 1 13:32:12 2004 From: no_replies at fake_email_address.invalid (Robert Oschler) Date: Thu, 1 Apr 2004 13:32:12 -0500 Subject: [OT] WARNING! - Dangerous new e-mail virus! Message-ID: "A deadly new computer virus that is spreading rapidly by e-mail has already caused massive damage to thousands of unprotected computers worldwide. The virus is rumored to be the deadly brainchild of renegade microbiology scientists, who have figured out how to cross the barrier from the digital world to the analog, and create a real biological virus on the victim's computer. For an actual photo of a ravaged computer, and further details on this frightening new virus, visit http://www.robotsrule.com/ ". -- sec.alert. From skip at pobox.com Mon Apr 12 22:56:07 2004 From: skip at pobox.com (Skip Montanaro) Date: Mon, 12 Apr 2004 21:56:07 -0500 Subject: print u"\u0432": why is this so hard? UnciodeEncodeError In-Reply-To: References: <16505.58626.39783.581506@montanaro.dyndns.org> Message-ID: <16507.22215.60324.63839@montanaro.dyndns.org> Skip> I generally use xterm instead of Terminal.app. I think it's Skip> encoding is latin-1. Martin> Not on OS X. I run xterms under XDarwin. I don't think the default encoding is different than xterms in any other X environment. If I execute print u'\xed'.encode("latin-1") in an xterm I get an accented "i". If I execute print u'\xed'.encode("utf-8") in a Terminal window I also get an accented "i". Skip From matthew at coredumps.net Fri Apr 16 01:54:24 2004 From: matthew at coredumps.net (Matthew) Date: 15 Apr 2004 22:54:24 -0700 Subject: [Newbie Q on String & List Manipulation] References: <567a7c35.0404150247.7809bef5@posting.google.com> Message-ID: <567a7c35.0404152154.1645e79d@posting.google.com> Hello all, finally, i found a way to make to a+=b works, but, i don't understand why it works... ;( i changed the script from: for item in thecookies: mycookies += item to: for item in thecookies: mycookies += repr(item) and thing works fine. i've also check the "type" of both the "item" & "mycookies" and they both are "str". i don't understand why i need to use the repr to make it work... sigh... --- matthew From tjreedy at udel.edu Thu Apr 29 22:04:49 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 29 Apr 2004 22:04:49 -0400 Subject: Andreas' practical language comparison References: <408c23b8$0$41746$5fc3050@dreader2.news.tiscali.nl><5ago80thlgfrsrapol1lldi2cq0uulto4n@4ax.com> <873c6m5vrq.fsf@pobox.com> Message-ID: > I think there's an n-queens solution by Tim Peters somewhere, written > as an example of Python simple generators (which is mostly 'his' > language feature, IIRC). It is in Lib/test/test_generators.py. It also has other examples of fancy footwork with generators . Anyone interested in the topic should read it. Terry J. Reedy From lbates at swamisoft.com Fri Apr 30 19:09:43 2004 From: lbates at swamisoft.com (Larry Bates) Date: Fri, 30 Apr 2004 18:09:43 -0500 Subject: IDE for Python References: Message-ID: Take a look at www.activestate.com for their products. Some are free, some are charge items. Also take a look at: http://www-106.ibm.com/developerworks/linux/library/l-pide/ many products reviewed/listed here. Larry Bates Syscon, Inc. "dont bother" wrote in message news:mailman.164.1083359859.25742.python-list at python.org... > Hi Guys: > Is there any good IDE for Python. I checked on > www.python.org and found some. Installed bluefish but > to my surprise its just an editor. I guess it cannot > even compile my code in python or maybe I am wrong. > Any ideas/recommendations for a free IDE for Python > Thanks > Dont > > > > > __________________________________ > Do you Yahoo!? > Win a $20,000 Career Makeover at Yahoo! HotJobs > http://hotjobs.sweepstakes.yahoo.com/careermakeover > From usenet_spam at janc.invalid Tue Apr 13 21:43:36 2004 From: usenet_spam at janc.invalid (JanC) Date: Wed, 14 Apr 2004 01:43:36 GMT Subject: Making urllib2 work with proxy urls References: <84fc4588.0404130351.77a1faf0@posting.google.com> <30260531.0404131454.49adec6d@posting.google.com> Message-ID: simoninusa2001 at yahoo.co.uk (simo) schreef: > The pac file is usually just a script with the config data for > browsers, it will return something like "PROXY > http-proxy.mydomain.com:80" > > I very much doubt urllib2 can actually proces the .pac file. > > You should be able to open that file and figure out what you need to > set the proxy variable to in urllib2 (or your ENVironment). A PAC file is a script that defines a JavaScript function: function FindProxyForURL(url, host) { // based on url & host: // return "DIRECT" to use no proxy, or something like // return "PROXY proxy.example.com:8080" to use that proxy } This function can get quite complex, so to use it automaticly, you might need a JavaScript engine... -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From project2501 at project2501.cor Mon Apr 12 19:24:26 2004 From: project2501 at project2501.cor (Project2501) Date: Tue, 13 Apr 2004 00:24:26 +0100 Subject: unexpected performance from threads and network client benchmarking Message-ID: i'm a little puzzled by the received wisdom of python threads. the wisdom says that you will not see any performance increase from the use of threads on the client side trying to it a server (high request rate). this is explained in terms of the GIL.. but i do see a difference... on python 2.3 on freebsd4.9 and linux 2.6 here is the pseudocode: loop: create a thread which will query a server and wait for response sleep(for interval) that's it. the interval in the sleep does change in steps over time. the threads themselves are passes the current time.time() and they themslves take the difference between this time and the time.time at which the response was received. (with a timeout). threads are created up to a given maximum (finished threads decrement a global counter). ok - now the interesting bit. with a maximum of one client thread at a time, the graphs responce time against the time.time() (at thread creation) are largely flat but with random jumps... as more client threads are allowed, the graphs become smoother with generally higher peak responce times ... and show: * initial flat response time - good, server is able to cope nicely * increase (almost linear) as the rate increases - server is queueing requests? or is taking longer to schedule more requests. whatever. * again, a flat rate at high request rates. possible client limit. perhaps reaching time/scheduler resolution of the python runtime? there is higher responce time from the server as more client threads attack it - why? if they can only execute one at a time? isi t because the switching between them is quicker than the creation of a new attack thread when there a max of 1 (sequential client)? the target server is single threaded (radiator radius server, is well known as single threaded and sequential)- it handles requests sequentially! the client and server machines are also uni-processor. Does this mean that there is a benefit to python threads? i'm puzzled! why the benefit in responce times? From jjl at pobox.com Thu Apr 22 17:40:47 2004 From: jjl at pobox.com (John J. Lee) Date: 22 Apr 2004 22:40:47 +0100 Subject: Generic constructors and duplication of internal Python logic References: <87ekqq41ya.fsf@pobox.com> <95aa1afa.0404150033.79a53e1a@posting.google.com> <87k70bzlak.fsf@pobox.com> <95aa1afa.0404192008.3a9da567@posting.google.com> Message-ID: <87fzavelnk.fsf@pobox.com> michele.simionato at poste.it (Michele Simionato) writes: > jjl at pobox.com (John J. Lee) wrote in message news:<87k70bzlak.fsf at pobox.com>... > > michele.simionato at poste.it (Michele Simionato) writes: > > > Have you thought of performing the checks in the __call__ method > > > of a custom metaclass? > > > > No. How would that help? > > I had in mind something like that: > > class _WithConstructorChecked(type): # helper metaclass > def __call__(cls, *args, **kw): > assert len(args)<=2, "%s called with more than 2 args" % cls > assert kw.has_key("kw"), "%s needs a 'kw=' argument" % cls > return super(_WithConstructorChecked,cls).__call__(*args,**kw) > > class WithConstructorChecked(object): # mixin class > __metaclass__ = _WithConstructorChecked > > class C(WithConstructorChecked): > def __init__(self, *args, **kw): > pass > > c=C(1,2,kw=3) # ok; try different signatures to get assertion errors > > In this example the mixin class WithConstructorChecked ensures that C is > called with at least two positional arguments and a keyword argument named > 'kw'. The code of class C is not touched at all, you just add > WithConstructorChecked to the list of its bases. > > Is that what you are looking for? No. :-) See my replies to Peter: I'm trying to re-use Python's own knowledge of to get attributes assigned, without repetition (see my original post for the kind of repetition that motivated me), and without simply liberally assigning as attributes any old arguments that get passed in. Seems like it's not possible, though. I don't see how a metaclass helps here. John From markus_wankusGETRIDOFALLCAPS at hotmail.com Fri Apr 2 08:29:28 2004 From: markus_wankusGETRIDOFALLCAPS at hotmail.com (Markus Wankus) Date: Fri, 02 Apr 2004 08:29:28 -0500 Subject: [OT] Top posting is a PITA [was : Prothon Prototypes vs Python Classes] In-Reply-To: References: <569c605ld1cj8fc1emolk08ete0s1prls1@4ax.com> <106di86neu1qh4d@news.supernews.com> <4069a001$0$4237$afc38c87@news.easynet.co.uk> <4069e9d9$0$8915$636a15ce@news.free.fr> <406a98ee$0$290$edfadb0f@dread12.news.tele.dk> <_QUac.63300$1A6.1594640@news20.bellglobal.com> Message-ID: <1Vdbc.20271$j57.1135407@news20.bellglobal.com> Jacek Generowicz wrote: > Markus Wankus writes: > > >>Geez..you can't even joke about this apparently. OK. Whatever. I'm >>easy. I *did* get the point BTW... > > > Cool. Sorry ... I've been away for a few days ... and having to wade > through a lot of top-posted crap on my return has made my tolerance > of TPing come close to an all-time low ... which is accompanied by a > sense of humour failure. > > I'm off to sit in a sensory deprivation tank for a few hours. Well - I guess I was being a bit of a dolt too...sorry. ;o) Let's all sit in our sensory deprivation tanks! That sounds like fun! Who here can construct metaclasses in the dark, in their head? Markus. From jcarlson at uci.edu Wed Apr 7 01:11:58 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Tue, 06 Apr 2004 22:11:58 -0700 Subject: GUI Frameworks in Python? In-Reply-To: References: <930ba99a.0404030246.786455f5@posting.google.com> <8ef9bea6.0404041009.26ae2683@posting.google.com> Message-ID: >> The basic idea is fairly similar in both, but event handlers >> ("signal handlers" in Gtk terminology) seem more straightforward >> to set up in PyGtk. In wxPython, for example, you have to get the >> ID number of the widget and pass that to an event-binding function; >> in PyGtk, you just pass the widget itself. >> >> That's just one example of how the PyGtk API is simpler. It might >> not sound like much, but lots of little things like that add up >> to make me like PyGtk much better. > > > I know, I can't believe wxPython doesn't use a simpler API for things > like event binding rather than just sticking to the C++ api so closely. > That's why people are creating their own wrappers to wxPython now. It's > ridiculous. And yes, I know event binding was made slightly simpler for > 2.5. 2.5 also takes some steps backwards, in the name of being more > like the C++ api. Simpler? According to Greg, passing ids of the widget was a pain...well, in 2.5 you can pass the widget. Apparently that is significant enough to warrant Greg complaining about it, and Robin Dunn to fix it. What parts of the 2.4 to 2.5 conversion are steps backward? - Josiah From eastier at free.fr Wed Apr 21 09:11:36 2004 From: eastier at free.fr (Emmanuel) Date: Wed, 21 Apr 2004 15:11:36 +0200 Subject: Reload All Message-ID: <40867308.26DD15BD@free.fr> Hi, I use a 'reload all' feature in my app, that allow to reload every module. I first try this version : import sys def Reload(): for a in sys.modules.values(): if ( type(a) == type(sys) ): # I can't remember why if ( '__file__' in dir ( a ) ): # to avoid reload of extending C module try: ## print a.__name__ reload ( a ) except ImportError: Log ("Reload", "error importing module" + a.__name__) but there are some cases where the order of the reload is important. I came into this one : CODE : =============== Base.py ---------- class Base: def __init__(self): print "Base Init" Derived.py ------------ import Base class Derived( Base.Base): def __init__(self): Base.Base.__init__(self) print "Derived additional init" In order to reload all to work, Base _MUST_ be reloaded before Derived. So I continue with this code, modified from something I get on the forum : ---------------------------------------------------- import inspect def reload_from_root(root): if(not inspect.ismodule(root)): print 'root is not a module!! Failing.' print type(root) #Keeping lists of pairs where pairs are (parent, child) #to establish module relationships and prevent #circular reloads reload_me = [(None, root)] reloaded = [] while(len(reload_me) > 0): tmp = reload_me.pop() for x in inspect.getmembers(tmp[1]): if(inspect.ismodule(x[1])): if ( '__file__' in dir ( x[1] ) ): if((tmp[1], getattr(tmp[1], x[0])) not in reloaded): reload_me.append((tmp[1], getattr(tmp[1], x[0]))) ## reload(tmp[1]) # If I use reload here, the child is always reloaded before the parent reloaded.append((tmp[0], tmp[1])) reloaded.reverse() TheReloaded = [] for pair in reloaded: if (pair[1] not in TheReloaded ): # Don't reload twice the Base, else it can reload in this order : # Base - Derived1 - Base- Derived2 # and Derived1 init will fails reload (pair[1]) TheReloaded.append( pair[1]) ---------------------------------------------------- This code solves my current problems, but I can imagine some possible issue with two levels hierarchies. So is there a perfect solution ? Thanks by advance, Emmanuel From gruel at astro.ufl.edu Thu Apr 15 13:33:13 2004 From: gruel at astro.ufl.edu (Nicolas Gruel) Date: Thu, 15 Apr 2004 13:33:13 -0400 Subject: plot+interaction In-Reply-To: References: Message-ID: <407ec75a$0$488$636a15ce@news.free.fr> with ppgplot that must be possible to do this. http://efault.net/npat/hacks/ppgplot/ Nicolas Mark Alford wrote: > I have been using the gnuplot.py package for simple 2D plots. > Works great. But I would like to have a tiny bit of interactivity: > > I would like the program to know where (in terms of the > plot variables x and y) the user has mouse-clicked on the plot window. > > Is there any other plotting package that offers this functionality? > > Mark > From project5 at redrival.net Fri Apr 9 09:19:04 2004 From: project5 at redrival.net (Andrei) Date: Fri, 9 Apr 2004 15:19:04 +0200 Subject: Why Activestate Python ? References: <8089854e.0404090025.141f090c@posting.google.com> Message-ID: <1afv95dy6164y.1a9l3etptcw8w.dlg@40tude.net> Fuzzyman wrote on 9 Apr 2004 01:25:45 -0700: > Again... a silly newbie question which might have an obvious > answer.... but *why* is their an alternative distribution of python by > activestate ? > > Apart fromt he fact that they bundle Mark Hammond's Windows Extensions > with it (in the windows version) - what is to be gained from using > their distributio instead of the 'normal' one ? You also get PythonWin and nice docs. Python might have good HTMLHelp format docs by now as well, but last time I tried, there were many broken things in it. At some point I was running an official Py2.3 because ActiveState was a bit slow in releasing a 2.3 version, but I continued to use the docs from ActiveState Py 2.2.X. Now I have their 2.3.2 distribution installed. Apart from that, it's Python. Depending on what your usage pattern is, you might not even notice what you have on your HD. -- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5 at jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From joe at notcharles.ca Mon Apr 5 23:47:03 2004 From: joe at notcharles.ca (Joe Mason) Date: Tue, 06 Apr 2004 03:47:03 GMT Subject: int('2.1') does not work while int(float('2.1')) does References: <40722555.66C70D40@alcyone.com> Message-ID: In article <40722555.66C70D40 at alcyone.com>, Erik Max Francis wrote: > There's a fundamental difference between an int and a float. If the > string you're trying to convert looks like a float, that means it > doesn't look like an int. > > With your first example of '2.1', what should it mean? Should it > truncate, round to negative infinity round to positive infinity, round > to zero, what? Python can't guess for you, so it shouldn't try. Thus > it's an error. Why can it make this guess for "int(2.1)", then? It's got a rule for converting floats to ints - why not use it here? Joe From martin at v.loewis.de Thu Apr 29 22:30:34 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 30 Apr 2004 04:30:34 +0200 Subject: locale.CODESET / different in python shell and scripts In-Reply-To: References: <4091621F.5060307@v.loewis.de> Message-ID: <4091BA4A.4000608@v.loewis.de> Nuff Said wrote: > When I add the following line to the above script > > print u"sch?nes M?dchen".encode(encoding) > > the result is: > > sch?nes M?dchen (with my self-compiled Python 2.3) > sch??nes M??dchen (with Fedora's Python 2.2) > > I observed, that my Python gives me (the correct value) 15 for > len(u"sch?nes M?dchen") whereas Fedora's Python says 17 (one more > for each German umlaut, i.e. the len of the UTF-8 representation of > the string; observe, that the file uses the coding cookie for UTF-8). > Maybe Fedora's Python was compiled without Unicode support? Certainly not: It would not support u"" literals without Unicode. Please understand that you can use non-ASCII characters in source code unless you also use the facilities described in http://www.python.org/peps/pep-0263.html So instead of "?", you should write "\xf6". > Is there something I do utterly wrong here? Yes, you are. > Python can't be that complicated? Python is not. Encodings are. Regards, Martin From Mike at DeleteThis.Geary.com Tue Apr 6 16:13:33 2004 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Tue, 6 Apr 2004 13:13:33 -0700 Subject: Using python23 to develop an extension for an application that has python22 embedded References: <1073eeubflmchd5@corp.supernews.com> <1073vcag51uufe9@corp.supernews.com> <1075js9on4our07@corp.supernews.com> Message-ID: <10763relbrppace@corp.supernews.com> John Underwood wrote: > I tried a small extension DLL as a test using your suggestion. > I could debug in VS.NET without the need of python22_d.dll > which is all I need. > > Many thanks for the help. Great! Glad it worked out. Talk with you later, Mike From peter at engcorp.com Mon Apr 12 07:18:47 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 12 Apr 2004 07:18:47 -0400 Subject: maximum length of a list & tuple In-Reply-To: References: Message-ID: Josiah Carlson wrote: >> Actually, unless I'm mistaken that stores only one integer, and a whole >> lot of references to it... which are just pointers (4 bytes each). >> >> The technique is probably flawed in other ways, however, as it >> is likely subject to memory fragmentation and other problems. > > You can't just store the integer. How would you differentiate between > an integer in a list and a pointer? Answer: you must use PyIntObjects. > Use the source. Python does not recognize anything called "pointers" at the language level, only internally. What I was saying is that the only PyIntObject created was one with the ob_ival of 1. Then a list containing one pointer to it was created. Then it was replicated "c" times. Only one integer. Please refute that claim rather than just arguing a bunch of other points, none of which I dispute but all of which I claim are irrelevant to the question at hand. > Checking the memory usage of Python before and after the creation of 1 > million integer list, I get a /very/ consistant ~16 bytes per. That > would be 12 bytes for the object, and 4 bytes for each pointer in the > list. Please post the expression you are using, for comparison. > I could go on as to why it doesn't matter in this case (considering the > large mallocs necessary for the creation of large lists), but I'll leave > that as an exercise to the reader. Please go on about it. I'd like to see where you discuss what happens to the previously memory that was held in earlier lists, as it iterates through the loop creating exponentially larger lists. > Again, from the source, 12 bytes for the object, 4 bytes for the pointer > in the list, total of 16 bytes per intobject in a list. Nice. So each entry in the list is 4 bytes (as I indicated). And if they all point to a single instance of the integer 1, how many extra bytes do you think that allocates? -Peter From peter at engcorp.com Tue Apr 27 14:48:28 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 27 Apr 2004 14:48:28 -0400 Subject: Is Perl *that* good? In-Reply-To: References: <108q51j4dscn7dc@corp.supernews.com> <87fzaqmm8t.fsf@strauser.com> <38ec68a6.0404262308.50029919@posting.google.com> Message-ID: Paramjit Oberoi wrote: >> Asun> Regex is much more 'immediate' in Perl. >> >>Sure, it's syntactically bound into the language. There will always be an >>extra constant overhead to enable regular expressions in Python. That > > > If only compiled regular expression objects allowed easy access to the > last match object, python regxes would become significantly more > convenient. For example, today you have to write: > > m = myregex.match(line) > if (m): > xyz = m.group('xyz') > > It would be much easier to do: > > if myregex.match(line): > xyz = myregex.lastm.group('xyz') > > Having to introduce a new variable name for a match object just > muddles the code unnecessarily in common regex usage scenarios. Wouldn't that be a fairly trivial class to write, and use in your own code? This is the kind of thing people tend to whip up on the fly and add to their little bag of tools if they really like it. Something like (untested, not real code, just for the idea): class myregex(re): def match(self, data): self.lastm = self.pattern.match(data) return self.lastm -Peter From tjreedy at udel.edu Thu Apr 29 14:03:40 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 29 Apr 2004 14:03:40 -0400 Subject: outline-style sorting algorithm References: Message-ID: "Thorsten Kampe" wrote in message news:c2bdjg9l06p2.dlg at thorstenkampe.de... > If made some tests with lists of one million items: > > The first test was with a randomized sequence of numbers from 1 - > 1000000. Duplicate numbers were allowed. The comparing function was > the identity (lambda x: x). I do not understand what you did, and therefore cannot judge results. A compare function takes two args (the objects to be compared) and returns -1, 0, 1. (I believe 0, 1 for <= or >t may be sufficient currently). How did you use the one-param identity? Terry J. Reedy From peter at engcorp.com Thu Apr 15 06:12:59 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 15 Apr 2004 06:12:59 -0400 Subject: Threading question In-Reply-To: References: Message-ID: Torsten Marek wrote: > I have a simple question about threads in Python. I am starting a > number of threads in my program and I want print out the amount of time > needed after all threads stopped. Do I need to explictly join the > threads, set a condition or is it possible to somehow work with > try/finally like that: > > try: > for i in range(0, num_threads): > s = MyThread() > s.start() > finally: > print "all threads finished" The other threads are running in, well, other threads, so you won't see any effect on the above thread when they end. Therefore you can't get much mileage out of a finally clause. A .join() is definitely the way to go here. -Peter From jcarlson at uci.edu Sun Apr 4 15:40:27 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Sun, 04 Apr 2004 12:40:27 -0700 Subject: Siginificant figures calculating zprob In-Reply-To: <9405c70f.0404031852.155d17d5@posting.google.com> References: <9405c70f.0404031852.155d17d5@posting.google.com> Message-ID: > I want to calculate zprob(the area under the normal curve) > with python and I managed to find a function from the > internet. > > But the problem is that the function calculates the result > with only a few significant figures. If I want to get the > 20th number of the result(z-prob) what should I do? I want > to get the confidence level of "6sigma" and all I get at the > moment is "1". > > I remember that Python's long type has unlimited number of > significant figures as long as the memory allows. What about > floating point numbers? Python floats are normally IEEE 754 FP values, which generally have 53 bits of precision. It's been a while since I did this kind of stuff, but after doing a few tests, the summation using Simpson's rule for numerical integration converges fairly quickly for most znorm ranges. I use 4096 divisions beacuse it seems to be fast and accurate to at least 10 decimal places for the ranges I've tested. More divisions may or may not increase precision, but for most tasks, I would imagine the code given at the end would be sufficient. There are various float casts, and floating point constants given in the code. With the tests that I did, it seems that some are necessary for higher precision. Oh, I hope this is precise enough... >>> div = 1024 >>> while div < 16*1024: ... print div, repr(znorm_range(0, 1, div)) ... div *= 2 ... 1024 0.3413447460685452 2048 0.3413447460685422 4096 0.34134474606854304 8192 0.34134474606854265 >>> - Josiah from math import sqrt, e, pi def znorm_x(x,c=1.): return c/sqrt(2.*pi)*e**(-(x*x)/2.) def znorm_range(low, high, divisions=4096): #divisions needs to be even, we'll increment it if necessary divisions += divisions%2 #necessary if either low or high are integers low, high = float(low), float(high) inc = (high-low)/float(divisions) x = low+inc t = znorm_x(low) + znorm_x(high) c = 4. while x < high: t += znorm_x(x,c) x += inc c = 6.-c return (high-low)*t/3./divisions From jonas at jonasgalvez.com Wed Apr 21 14:43:49 2004 From: jonas at jonasgalvez.com (Jonas Galvez) Date: Wed, 21 Apr 2004 15:43:49 -0300 Subject: Time Message-ID: If I have a tuple like this: (year, month, day, hour, minute) Is there a way to automatically generate a string like this? "YYYY-MM-DDTHH:MM:00" I remember seeing something about it somewhere... wanted to be sure. Thanks in advance, =- Jonas Galvez jonasgalvez.com/blog macromedia.com/go/team From erlendga at tva.ifi.uio.no Thu Apr 1 13:53:09 2004 From: erlendga at tva.ifi.uio.no (Erlend Andreas Garberg) Date: Thu, 1 Apr 2004 18:53:09 +0000 (UTC) Subject: Travelling salesman variation in python References: Message-ID: In article , Josiah Carlson wrote: > Look at current TSP algorithms, and exchange their minimization rutines > for a maximization rutine. TSP is an NP-hard problem, which means that > there is no currently known algorithm for solving it in polynomial time. > You can approximate it or do a search on the solution space, but > solving it requires searching basically all of the solution space. > > - Josiah An approximate solution would be good enough, do you have any suggestions about how do do that? -- mvh Erlend Garberg erlendga at ifi.uio.no From lubowiecka at go2.pl Tue Apr 13 08:15:44 2004 From: lubowiecka at go2.pl (Sylwia) Date: 13 Apr 2004 05:15:44 -0700 Subject: how to calculate correctly the cluster size Message-ID: Hi! I need Your help... I am trying to find a way to calculate the cluster size for a drive. I looked at the GetDiskFreeSpaceEx function in Win32 and it turned out that it didn't provide the information I was looking for. Using the old GetDiskFreeSpace function I could just multiply the Bytes per Sector by the Sector per Cluster and get the cluster size. I heard that the old GetDiskFreeSpace function may report not proper values for volume sizes that are greater than 2 gigabytes. The new version of that function (GetDiskFreeSpaceEx) returns the final disk free size without the ability to calculate the cluster size - and the old version does not work correctly with FAT 32... what can I do? Is there another function I can use? Thank You in advance, Farraige From missive at frontiernet.net Thu Apr 15 11:04:19 2004 From: missive at frontiernet.net (Lee Harr) Date: Thu, 15 Apr 2004 15:04:19 GMT Subject: Pygame References: <107qkrbhnjpmh9b@news.supernews.com> <107rksn9nosm78a@news.supernews.com> <4de76ee2.0404150304.3048ee44@posting.google.com> Message-ID: > Personally, I'm not in favour of sweeping all the most popular third > party libraries into the standard library, although I can understand the > motivation of the original poster for wanting to include Pygame. > It might be interesting to see some kind of "stub" installer which was quite small, but you could check different pieces you wanted to use (Tkinter, Pygame, wxPython, etc) and have it download and install only what you really want. Implementation is left for someone who uses windows ;o) From shmolduk at free.fr Tue Apr 27 06:42:49 2004 From: shmolduk at free.fr (pepericou) Date: 27 Apr 2004 03:42:49 -0700 Subject: creating an python function with DCoracle2 module Message-ID: <46a86393.0404270242.60fe9b35@posting.google.com> I'm trying to developp an application which use Zope and DCOracle2 module to access Oracle database. I've install the DCOracle2 product on Windows XP, but when I create a python function to access my database, I' have the following error when I test it : import DCOracle2 is unauthorized Can You help me ? Thank you From paddy3118 at netscape.net Mon Apr 26 16:42:00 2004 From: paddy3118 at netscape.net (Paddy McCarthy) Date: 26 Apr 2004 13:42:00 -0700 Subject: On: 'The Python CSV Module and Legacy Data' Message-ID: <2ae25c6b.0404261242.c2a3358@posting.google.com> Hi, I read http://radio.weblogs.com/0124960/ which has a quoted number in a csv file being interpreted as a string. I checked it out with my csv2txt utility (http://www.paddyx.pwp.blueyonder.co.uk/) And that does seem to be the case. Should this action not be thought of as an error? If the csv module reads a quoted string shouldn't it present it internally as a string? Since the csv reader is intelligent, maybe the correct proceedure would be for it to: * If it only sniffs out numbers held in strings then change all strings containing valid numbers to numbers. * If it initially sniffs out unquoted numbers, or no numbers at all, or a mixture of quoted and unquoted numbers, then return un-quoted numbers as numbers and quoted numbers as strings. Or we could explicitely tell the CSV module what to do with quoted number strings! I haven't checked what the csv writer does with a string that could also represent a number. Will it quote that on output? hmmm... Cheers, Paddy. From cygnus at cprogrammer.org Thu Apr 15 09:23:24 2004 From: cygnus at cprogrammer.org (Jonathan Daugherty) Date: Thu, 15 Apr 2004 09:23:24 -0400 Subject: Difficulty Finding Python Developers In-Reply-To: References: <65cbc3dd.0404140641.3501fde8@posting.google.com> <65cbc3dd.0404141018.36d9d4ce@posting.google.com> Message-ID: <20040415132324.GA28100@vulcan.cprogrammer.org> # If I were his management, here I might say, "But I thought you # said Python was older than Java! If it's so good, why hasn't it # caught on more than Java?" or "How can it build on the strengths # of Java when it's older?" The supposition that something is inherently good or better does not imply that it will become popular. Managerial mandate and hype usually determine "popularity." :) # or worse? And wouldn't the best programmers be using the most # popular languages, because they would make more money that way?" Whether one is a good programmer and whether one is out to let one's salary determine one's skill set are two totally different qualities. People who use 'popular' languages are rarely the best programmers *because* they use popular languages; it's not that deterministic. -- _ ,^. _ ,'/ -' '- \`. / | \ / | \ Jonathan Daugherty | | | | | | | \_,' `._/ | http://www.cprogrammer.org | | \ / `. .' `--._.--' From fumanchu at amor.org Tue Apr 13 22:41:29 2004 From: fumanchu at amor.org (Robert Brewer) Date: Tue, 13 Apr 2004 19:41:29 -0700 Subject: Does Python compete with Java? Message-ID: Jakub Fast wrote: > ...isn't the zen of python more along the way of: > "the master hits the student repeatedly with a stick > and the student experiences enlightenment" rather > than "the master takes the toys away from the student". Neither is even remotely true in my experience with Python. Perl and Java (respectively) are over there ==> ;) If the master has to hit the student at all, he's chosen the wrong way to teach. If he has to do it repeatedly, he's a pretty poor judge of sticks and students. For the toy analogy, the master keeps the guns, tear gas, and nuclear bombs locked up, not the toys. FuManChu From noemail at noemail4u.com Thu Apr 29 07:59:45 2004 From: noemail at noemail4u.com (Daniel 'Dang' Griffith) Date: Thu, 29 Apr 2004 11:59:45 GMT Subject: String formatting (%) References: Message-ID: <0fc7c423f6c71f60bc863e72b0765f6c@news.teranews.com> On Wed, 28 Apr 2004 09:15:02 -0400, Peter Hansen wrote: >Pascal wrote: > >> Hello, >> I've a float number 123456789.01 and, I'de like to format it like this >> "123 456 789.01". >> Is this possible with % character? > >No, as shown by http://docs.python.org/lib/typesseq-strings.html >but you could probably use the 'locale' module instead. > >I suspect there's also a regular expression that could deal with >that, but I don't want to know what it is. ;-) > >-Peter Since you don't want to know what it is, I'll at least tell you where it is: In Mastering Regular Expressions by Jeffrey E. F. Friedl. I don't have it front of me, but it's the "commafying" example. A quick search of the author's site looks like it's on pgs 64-65. Of course, the OP would substitute spaces for the commas. --dang From NAIGIMSESRIMAIL at gims.com Thu Apr 1 03:54:37 2004 From: NAIGIMSESRIMAIL at gims.com (GroupShield for Exchange (ESRIMAIL)) Date: Thu, 1 Apr 2004 10:54:37 +0200 Subject: ALERT - GroupShield ticket number OB66_1080809672_ESRIMAIL_3 was generated Message-ID: Action Taken: The message was blocked because of its subject. To: python-list at python.org From: Peter Maas Sent: -219147264,29628358 Subject: Re: test for nan Attachment Details:- Attachment Name: N/A File: Infected.msg Infected? No Repaired? No Blocked? Yes Deleted? No Virus Name: -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/ms-tnef Size: 1813 bytes Desc: not available URL: From Scott.Daniels at Acm.Org Sat Apr 3 16:13:02 2004 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sat, 03 Apr 2004 13:13:02 -0800 Subject: beginner import confusion In-Reply-To: References: Message-ID: <406f2fe7$1@nntp0.pdx.net> DilbertFan wrote: > Hi, > I really thought that I had this importing business down. > I recently downloaded and installed mx module for the DateTime class. > > In IDLE, I go: > import mx > mx.DateTime.DateTime(2004) > I get AttributeError: 'module' object has no attribute 'DateTime' mx is a package, mx.DateTime is a module; you need to import a module to get to its contents. > but if you type: > import mx.DateTime > mx.DateTime.DateTime(2004) > > If you "import mx", ... doesn't that get everything? If mx were a module, you would be right. However, it is a "package," a collection of modules and packages. Packages are a way of keeping the names one provider of many python modules from conflicting with the module names of both you and python itself. > If you know, from the docs, that it contains a DateTime class > and then a DateTime object, mx.DateTime.DateTime is a class, not an object. You could do: from mx.DateTime import DateTime to simply get the DateTime class and then use DateTime(2004). -- -Scott David Daniels Scott.Daniels at Acm.Org From No.Spam.mc at No.Spam.mclaveau.No.Spam.com Sun Apr 4 08:33:40 2004 From: No.Spam.mc at No.Spam.mclaveau.No.Spam.com (Michel Claveau/Hamster) Date: Sun, 4 Apr 2004 14:33:40 +0200 Subject: Python is faster than C References: <406F0907.96F37EA1@tunes.org> <406F3A33.70FB70CC@tunes.org> Message-ID: Hi ! Sorry, but i had let down C language. I can't compare. See also my answer to Josiah Carlson. And Psyco is sufficiently good not to need ambiguous arguments. @-salutations -- Michel Claveau From davidf at sjsoft.com Thu Apr 22 01:42:28 2004 From: davidf at sjsoft.com (David Fraser) Date: Thu, 22 Apr 2004 07:42:28 +0200 Subject: Python 2.3.3 super() behaviour In-Reply-To: <4086539d$0$24773$afc38c87@news.easynet.fr> References: <40863bd7$0$25528$afc38c87@news.easynet.fr> <40864674$0$24834$afc38c87@news.easynet.fr> <40864ea6$0$25528$afc38c87@news.easynet.fr> <4086539d$0$24773$afc38c87@news.easynet.fr> Message-ID: Hi Nicolas Another related idea: Use template functions when you have enough control over the objects: def A(base=object): class A(base): def __init__(self): print "A" super(A, self).__init__() return A def B(base=object): class B(base): def __init__(self): print "B" super(B, self).__init__() return B class C(B(A())): def __init__(self): print "C" super(C, self).__init__() C() This is a bit different to multiple inheritance, but can have nice effects... David Nicolas Lehuen wrote: > Ah, so there *is* more than one way to do it, then ? ;) > > What the example shows is that super(...).__init__ does make one call to > each superclass' __init__, provided that those superclasses play nicely and > use super() themselves (as Peter wrote). If one of the superclasses does not > use super(), the 'magical' iteration over parent methods is interrupted, > hence the need to put those bad guys at the end of the superclasses list in > the class declaration. > > But you're right, David, the simplest way to get what I want is to > explicitely call the superclasses' __init__. However, this would mean that > super() is not as useful as it seems. I'd rather find a way to *always* use > super() than have special cases for certain inheritance trees. In other > words, I'd rather have only one way to do it :). > > Regards, > Nicolas > > "David Fraser" a ?crit dans le message de > news:c65j4o$3me$1 at ctb-nnrp2.saix.net... > >>super is not going to be helpful here, so why not call the X.__init__ >>functions explicitly? >>Since you *need* multiple __init__ calls from the multiply-inherited >>class, super isn't going to work... >> >>Nicolas Lehuen wrote: >> >>>The only problem I have is that I want to build a multiple inheritance >>>involving an object which does not cooperate, namely : >>> >>>class T(object): >>> def __init__(self): >>> super(T,self).__init__() >>> >>>class TL(list,object): >>> def __init__(self) >>> super(TL,self).__init__() >>> >>>In this case, T.__init__ is not called, because list.__init__ does not > > use > >>>super(). The only clean way to proceed is to change the inheritance > > order : > >>>TL(T,list). This way, both constructors are called. >>> >>>Here is another example which exhibits the behaviour : >>> >>>class A(object): >>> def __init__(self): >>> super(A,self).__init__() >>> print 'A' >>> >>>class B(object): >>> def __init__(self): >>> print 'B' >>> >>>class C(B,A): >>> def __init__(self): >>> super(C,self).__init__() >>> print 'C' >>> >>>class D(A,B): >>> def __init__(self): >>> super(D,self).__init__() >>> print 'D' >>> >>> >>> >>>>>>C() >>> >>>B >>>C >>><__main__.C object at 0x008F3D70> >>> >>>>>>D() >>> >>>B >>>A >>>D >>><__main__.D object at 0x008F39F0> >>> >>>The problem is that if you go further down the inheritance, the > > behaviour is > >>>even more complicated : >>> >>>class E(object): >>> def __init__(self): >>> super(E,self).__init__() >>> print 'E' >>> >>>class F(C,E): >>> def __init__(self): >>> super(F,self).__init__() >>> print 'F' >>> >>>class G(D,E): >>> def __init__(self): >>> super(G,self).__init__() >>> print 'G' >>> >>> >>> >>>>>>F() >>> >>>B >>>C >>>F >>><__main__.F object at 0x008F3D70> >>> >>>>>>G() >>> >>>B >>>A >>>D >>>G >>><__main__.G object at 0x008F3EF0> >>> >>>class H(E,C): >>> def __init__(self): >>> super(H,self).__init__() >>> print 'H' >>> >>>class I(E,D): >>> def __init__(self): >>> super(I,self).__init__() >>> print 'I' >>> >>> >>> >>>>>>H() >>> >>>B >>>C >>>E >>>H >>><__main__.H object at 0x008F3E30> >>> >>>>>>I() >>> >>>B >>>A >>>D >>>E >>>I >>><__main__.I object at 0x008F3FD0> >>> >>>So the conclusion is : never do that :). Another more constructive >>>conclusion would be : always put the most cooperative classes first in > > the > >>>inheritance declaration, provided that it doesn't interfere with your > > needs. > >>>A class which has an uncooperative ancestor is less cooperative than a > > class > >>>which has only cooperative ancestors. >>> >>>Regards, >>>Nicolas >>> >>>"Nicolas Lehuen" a ?crit dans le > > message > >>>de news:40864674$0$24834$afc38c87 at news.easynet.fr... >>> >>> >>>>OK, I get it now, thanks. >>>> >>>>super() method calls should only be used for method involved in >>>>diamond-shaped inheritance. This is logical since in this case the base >>>>classe (from which the diamond-shaped inheritance starts) defines the >>>>interface of the method. >>>> >>>>This solves another question I was asking myself about super() : "how > > can > >>>it >>> >>> >>>>work when the method signature differ between B and C ?". Answer : the >>>>method signature should not change because polymorphic calls would be >>>>greatly endangered. The base class defines the signature of the method >>> >>>which >>> >>> >>>>must be followed by all its children, this way super() can work > > properly. > >>>>The base method signature is not enforced by Python, of course, but > > you'd > >>>>better respect it unless you get weird result in polymorphic calls. >>>> >>>>Regards, >>>>Nicolas >>>> >>>>"Peter Otten" <__peter__ at web.de> a ?crit dans le message de >>>>news:c65fbo$1q4$05$1 at news.t-online.com... >>>> >>>> >>>>>Nicolas Lehuen wrote: >>>>> >>>>> >>>>> >>>>>>Hi, >>>>>> >>>>>>I hope this is not a FAQ, but I have trouble understanding the >>> >>>behaviour >>> >>> >>>>>>of the super() built-in function. I've read the excellent book 'Python >>>> >>>>in >>>> >>>> >>>>>>a Nutshell' which explains this built-in function on pages 89-90. >>> >>>Based >>> >>> >>>>on >>>> >>>> >>>>>>the example on page 90, I wrote this test code : >>>>>> >>>>>>class A(object): >>>>>> def test(self): >>>>>> print 'A' >>>>>> >>>>>>class B(object): >>>>>> def test(self): >>>>>> print 'B' >>>>>> >>>>>>class C(A,B): >>>>>> def test(self): >>>>>> super(C,self).test() >>>>>> print 'C' >>>>>> >>>>>>print C.__mro__ >>>>>>c=C() >>>>>>c.test() >>>>>> >>>>>>The output is : >>>>>>(, , , >>> >>>>> >>> >>>>>>'object'>) >>>>>>A >>>>>>C >>>>>> >>>>>>Whereas I was expecting : >>>>>>(, , , >>> >>>>> >>> >>>>>>'object'>) >>>>>>A >>>>>>B >>>>>>C >>>>>> >>>>>>Was I wrong to expect this (based on what I've read ?) >>>>> >>>>>As soon as a test() method without the super(...).test() is reached, no >>>>>further test methods will be invoked. Only the first in the list of > > base > >>>>>classes will be invoked. If I'm getting it right you have to do >>> >>>something >>> >>> >>>>>like: >>>>> >>>>>class Base(object): >>>>> def test(self): >>>>> print "base" >>>>> >>>>>class D1(Base): >>>>> def test(self): >>>>> super(D1, self).test() >>>>> print "derived 1" >>>>> >>>>>class D2(Base): >>>>> def test(self): >>>>> super(D2, self).test() >>>>> print "derived 2" >>>>> >>>>>class All(D1, D2): >>>>> pass >>>>> >>>>>All().test() >>>>> >>>>>Here all cooperating methods have a super() call, and the base class >>> >>>acts >>> >>> >>>>as >>>> >>>> >>>>>a showstopper to prevent that Python tries to invoke the non-existent >>>>>object.test(). >>>>> >>>>>Peter >>>>> >>>>> >>>>> >>>> >>>> >>> > > From tony at deletethis.thoward.plus.net Tue Apr 20 12:47:04 2004 From: tony at deletethis.thoward.plus.net (Tony of Judicious) Date: Tue, 20 Apr 2004 17:47:04 +0100 Subject: Rekall configure probs References: Message-ID: Diez B. Roggisch wrote: > Tony of Judicious wrote: > >> Not sure if this is right ng but i'm trying to install Rekall on Suse 9 >> prof >> >> During ./configure i get the msg: >> >> checking for X... configure: error: Can't find X includes. Please check >> your installation and add the correct paths! >> >> Any idea what it is looking for? > > the x window include files? Whatever it needs them for - nstall the X > devel packages. > Ta, that did it BUT has now come up with LOTS of other dependencies......... From peter at engcorp.com Mon Apr 26 11:54:47 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 26 Apr 2004 11:54:47 -0400 Subject: Is Perl *that* good? (was: How's ruby compare to it older bro In-Reply-To: References: Message-ID: jwsacksteder at ramprecision.com wrote: > I suspect the perl is the first place many people get exposed > to regexes and when they understand the utility of that, some > of the glow rubs off on perl. Someone actually said to me > once "I program in perl because I can't live without regex." > Now when someone says "perl text-processing", I hear "regex". > (If I was motivated, I would include the above substitution in > regex notation here...) > > The php/mysql crowd gives me this feeling as well, but that's > a discussion for another day and another list. I guess it would be interesting to pose the question back to them "If you could not use regexes in Perl, would you still like to program in it?" or "If you couldn't use mysql in PHP would you still use it?" What similar question, if any, would be a difficult one for us Python types? -Peter From greg at cosc.canterbury.ac.nz Thu Apr 29 22:52:55 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Fri, 30 Apr 2004 14:52:55 +1200 Subject: What is good about Prothon? In-Reply-To: <69cbbef2.0404291609.72d391db@posting.google.com> References: <108t2tlo06j8vb9@corp.supernews.com> <69cbbef2.0404281446.4e0ab52e@posting.google.com> <69cbbef2.0404291609.72d391db@posting.google.com> Message-ID: has wrote: > # Create object 'a' > a = Object() > a.x = 1 > > # Create objects 'b' and 'c' > b = a() > c = a() You've mistranslated your example. The Prothon equivalent would be more like b = a.copy() c = a.copy() and then you have three independent objects, just as you want. The exactly equivalent thing can also be done in Python, for what its' worth. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From llothar at web.de Thu Apr 22 12:03:34 2004 From: llothar at web.de (Lothar Scholz) Date: 22 Apr 2004 09:03:34 -0700 Subject: Python editors for Windows question References: Message-ID: <6ee58e07.0404220803.24aeefe1@posting.google.com> Marco Aschwanden wrote in message news:... > The best auto-completion you can get for Python is: WingIde > http://wingide.com/ > > Normally WingIDE is quite good at auto-completion but sometimes it needs > some help: > > if wingIde does not "recognize" a class you may add: > > assert isinstance(btnHello, wxButton) > > and after that point it will handle this for you too... But keep in mind that auto-completion is by concepts miles away from what you see in Java. The problem for us who try to implement this feature is always that most people don't understand why this is impossible in a dynamically typed language. From hungjunglu at yahoo.com Sun Apr 4 14:09:05 2004 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 4 Apr 2004 11:09:05 -0700 Subject: GUI Frameworks in Python? References: <930ba99a.0404030246.786455f5@posting.google.com> Message-ID: <8ef9bea6.0404041009.26ae2683@posting.google.com> sridharinfinity at yahoo.com (Sridhar R) wrote in message news:<930ba99a.0404030246.786455f5 at posting.google.com>... > > Man, you better use PyGTK (http://pygtk.org). It's portable (See pygtk > faq for windows port). It's neet (API). > Try also `glade`, `libglade`. > http://glade.gnome.org , I think? Can someone outline some differences/advantages of PyGTK vs. wxPython? A first look at PyGTK shows me a more Unix-like look-and-feel. On the other hand, wxPython on Windows does look very much like any other Windows applications. Is the event handling in PyGTK cleaner/better than wxPython? Does PyGTK have more widgets? The FAQ of PyGTK does not have a comparison section regarding other GUI toolkits, I think it would be useful if one were included. (If you go to wxPython's mainpage, you read "Why the hell hasn't wxPython become the standard GUI for Python yet?", and also "BTW, great work! I've definitively switched from Tk. I work on Win32, anybody who works on Win32 should switch!". Comments like that. Readers can immediately know the relationship to Tk, and wxPython's platform friendliness for Win32.) Given the lack of comparison, I would guess that GTK is unix-friendly, since Unix people usually would mention little or nothing about Windows. :) Continuing with my guess: are there any caveats for using PyGTK for Windows programmers? --------------------------- Given my observations, is it fair to say: (a) wxPython is widely used for Windows Python programmers, and (b) PyGTK is widely used for Unix Python programmers? regards, Hung Jung From python at holdenweb.com Fri Apr 9 17:08:07 2004 From: python at holdenweb.com (Steve Holden) Date: Fri, 09 Apr 2004 17:08:07 -0400 Subject: Python-2.3.3 install -> no "make" In-Reply-To: <2278156.F9pO2Pa3OA@Lumina-verte.org> References: <2278156.F9pO2Pa3OA@Lumina-verte.org> Message-ID: <3kEdc.3041$VE5.900@lakeread01> Frank Dieckmann wrote: > Hi! > > I 've tryed to install Python-2.3.3 under SuSE 8.0: > Unpacking was fine, > ../configure seems to be too, > but there was no make-file (only "Makefile" but that seems to be something > else). > What have I forgotten or which fault did I made? > How can I handle this problem, what do I have to do to install Python? > > Kind regards! > > Frank If you don't have "make" then you need to install some development packages. "make" is the utility that uses the Makefile to build the software. regards Steve From ramen at lackingtalent.com Mon Apr 5 22:01:20 2004 From: ramen at lackingtalent.com (Dave Benjamin) Date: Tue, 06 Apr 2004 02:01:20 -0000 Subject: Fake post alert(was: Stackless Website down, Project gone, I'm dead.) References: <20040402195104.186481807.eric@zomething.com> Message-ID: In article , Christian Tismer wrote: > Dave Benjamin wrote: >> >> Christian Tismer doesn't lock his workstation! I'm telling!! =) > > No, he didn't evict certain accounts, well, still not going > into details. If you ask me, it looks like you just did. But at least you lock your workstation; I'd hate to think you're one of those people that doesn't lock their workstation... > Btw, incidentially, the Stackless site really went down over > the weeken, and I'm more than happy to announce that it is > up and running, again, nothing lost at all. An odd coincidence. Well, I'm glad to hear the site's back up. Last year, I had a site get hacked and rooted, and I was up until 3am installing Apache, mod_python, and a large handful of Python libraries. It definitely enlightened me about the benefits of writing deployment scripts... (since I did not write any) Happy goto-ing, Dave -- .:[ dave benjamin: ramen/[sp00] -:- spoomusic.com -:- ramenfest.com ]:. : please talk to your son or daughter about parametric polymorphism. : From admin at na.org Wed Apr 28 03:20:17 2004 From: admin at na.org (admin at na.org) Date: Wed, 28 Apr 2004 00:20:17 -0700 Subject: Symantec Mail Security detected a virus based on a message you sent (SYM:10517043161659824748) Message-ID: <0aee01c42cf1$42048730$b0a8a8c0@na.org> Subject of the message: something for you Recipient of the message: Roberta Tolkan From alban at magproductions.nl Wed Apr 28 06:28:54 2004 From: alban at magproductions.nl (Alban Hertroys) Date: Wed, 28 Apr 2004 12:28:54 +0200 Subject: Problem importing packages In-Reply-To: References: Message-ID: Alban Hertroys wrote: > I'm trying to create a package containing a number of classes I made, > but I can't get it to work... > > My package is structured like this: > > X/ > __init__.py Doh! I named it __init.py__ instead... It DOES work using __init__.py. From peter at engcorp.com Thu Apr 29 22:14:50 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 29 Apr 2004 22:14:50 -0400 Subject: static keyword In-Reply-To: References: Message-ID: Nick Jacobson wrote: > Yes, that is excellent. Thank you very much. :) > > The good news: you can reset all your "static" data whenever you want, > by calling foo(). Can't do that in C. > > The bad news: I just hope I don't forget and call foo() instead of > g.next(). > I would rather the command foo() by default call the next iteration, > and, say, foo().reset() would recall the function from scratch. But > that's neither here nor there.. Do this then (and this is, if not a hack, at least unusual style): >>>def foo_reset(): # same as previous foo was, just renamed >>>foo = foo_reset().next >>>foo() First pass 11 >>>foo() 12 Happy now? ;-) -Peter From tzot at sil-tec.gr Mon Apr 5 05:55:25 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Mon, 05 Apr 2004 12:55:25 +0300 Subject: An attempt at guessing the encoding of a (non-unicode) string References: Message-ID: <6pa270h031thgleo4a31itktb95n9e4rvm@4ax.com> On Fri, 02 Apr 2004 14:49:07 -0800, rumours say that David Eppstein might have written: >I've been getting decent results by a much simpler approach: >count the number of characters for which the encoding produces a symbol >c for which c.isalpha() or c.isspace(), subtract a large penalty if >using the encoding leads to UnicodeDecodeError, and take the encoding >with the largest count. Somebody (by email only so far) has suggested that spambayes could be used to the task... perhaps they're right, however this is not as simple and independent a solution I would like to deliver. I would believe that your idea of a score is a good one; I feel that the key should be two-char combinations, but I'll have to compare the success rate of both one-char and two-char keys. I'll try to search for "representative" texts on the web for as many encodings as I can; any pointers, links from non-english speakers would be welcome in the thread. -- TZOTZIOY, I speak England very best, Ils sont fous ces Redmontains! --Harddix From llothar at web.de Tue Apr 20 17:55:18 2004 From: llothar at web.de (Lothar Scholz) Date: 20 Apr 2004 14:55:18 -0700 Subject: Difficulty Finding Python Developers References: <65cbc3dd.0404140641.3501fde8@posting.google.com> Message-ID: <6ee58e07.0404201355.7465406@posting.google.com> > *I* didn't realise that, I assumed $45,000/year to $55,000/year annual > rate, which would be a reasonable rate in Canada (in Canadian dollars > even) for a programmer with 1 or 2 years of experience. I'd forgotten > just how well Americans get paid for having fun... You mean the lucky persons working at Wal-Mart ? From paddy3118 at netscape.net Sat Apr 3 06:08:36 2004 From: paddy3118 at netscape.net (Paddy McCarthy) Date: 3 Apr 2004 03:08:36 -0800 Subject: [ANN] csv2txt.py csv file convertion script Message-ID: csv2text is a program I wrote to illustrate a point I made on comp.lang.python about not just creating great Python modules, or Python programs, but of doing both at the same time. This program makes the CSV module of Python more accessible by creating a program 'filter' that guesses and parses a csv file type on standard input and generates different formats on standard output. At the moment, output types are CSV, HTML (as an HTML table), and a text format that is written to be easily parsed by tools such as TCL or AWK that may not have such a powerful CSV reader module handy. The text format has conversions to allow AWK to handle CSV files with fields that contain embedded newlines (XL can generate that type of CSV file). Homepage: http://www.paddyx.pwp.blueyonder.co.uk/csv2txt/README.html Cheers, Paddy. From claird at lairds.com Mon Apr 26 12:04:27 2004 From: claird at lairds.com (Cameron Laird) Date: Mon, 26 Apr 2004 16:04:27 -0000 Subject: Is Perl *that* good? (was: How's ruby compare to it older bro References: Message-ID: <108qcobc4m8g972@corp.supernews.com> In article , Peter Hansen wrote: . . . >I guess it would be interesting to pose the question back to >them "If you could not use regexes in Perl, would you still >like to program in it?" or "If you couldn't use mysql in PHP >would you still use it?" > >What similar question, if any, would be a difficult one for >us Python types? > >-Peter Over in Perlmark, Randal "often" (his adverb) claims no one'd use Tcl now if Expect and Tk hadn't kept it alive. I don't get it, though. The questions just don't work for me; I don't find them as illuminating as more pre- cise and less inflammatory alternatives. Moreover, I'm sure I could find abundant Perlites who'd still use it without its built-in REs. If Python lacked the interactive shell ... well, someone would build it, immediately. -- Cameron Laird Business: http://www.Phaseit.net From ykingma at accessforall.nl Fri Apr 30 04:53:43 2004 From: ykingma at accessforall.nl (Ype Kingma) Date: Fri, 30 Apr 2004 10:53:43 +0200 Subject: Cross-Language Encryption: Python/Java References: <87y8oe4g9l.fsf@pobox.com> Message-ID: <40921418$0$61616$e4fe514c@news.xs4all.nl> John J. Lee wrote: > Daniel Orner writes: > >> I'm working on a project that consists of a Java application >> on the desktop, and a server with Python CGI code. I'm trying to find >> an encryption algorithm, which would let me send encrypted information >> to the server, to work identically in both Python and >> Java. (I.e. which would let me encrypt data in Java, send it to the >> Python server, and decrypt it there.) For various reasons, I don't >> want to use the built-in Java encryption suite. > [...] > > Use Jython. Whether it makes sense to put Jython on server or client > probably depends on details that only you know. Another option is a ssh tunnel from each client to your server. If this is feasible in your environment, it has the big advantage that your code won't even now that the communication is encrypted, only the client would have to connect to the tunnel. Perhaps someone else can comment on secure sockets. Java has them, and I'd expect your server to know how to deal with them, too. I'd also ask on a Zope list. Good luck, Ype From scott.b.drummonds.nospam at intel.com Wed Apr 14 17:01:44 2004 From: scott.b.drummonds.nospam at intel.com (Scott Brady Drummonds) Date: Wed, 14 Apr 2004 14:01:44 -0700 Subject: Fast Data Comparison (dict v. list. v string) Message-ID: Hi, everyone, I'm a relative novice at Python and am working on some optimizations in my first Python project. At its core, this tool I'm writing needs to perform many comparisons to fixed-size lists of fixed-length strings. Currently, my implementation uses dictionaries to store each string. I maintain a separate "key-mapping" dictionary that maps keys from one dictionary to the other. Then, all I have to do to compare the two dictionaries is as follows: for metaKey in keyMap.keys(): if dict1[metaKey] != dict2[keyMap[metaKey]]: # Do some processing Since the sizes of the dictionaries never change, I tried implementing this using lists. The solution looks something like this (and assumes that a pre-processing phase has sorted the contents of each list so their indexes are the same): for i in len(list1): if list1[i] != list2[i]: # Do some processing As it turns out, this implementation appears to be about 33% faster than the dictionary-based one. Now, assuming that the datum being stored at each index can fit into one character, I could do a string-based implementation like this: for i in len(string1): if string1[i] != string[i]: # Do some processing This last solution actually runs about the same as the dictionary, which takes 50% longer than the list implementation. Now, my questions are: 1) Does anyone have another suggestion as to how I can organize these data so that I can compare many elements many times? 2) Is there a string comparison operator that will return which indexes have different values? Maybe it would be faster than the iterative comparison approach for the third implementation. 3) Since my data are changing between the successive executions of the code snippets above, I need a way of having the other parts of the program update it. But, it appears that strings are constant as I can't assign individual characters with "string1[i] = '0'". Is there any way around this? Thanks! Scott -- Remove ".nospam" from the user ID in my e-mail to reply via e-mail. From huggiepython at graffiti.idv.tw Mon Apr 12 03:44:02 2004 From: huggiepython at graffiti.idv.tw (Timothy Wu) Date: Mon, 12 Apr 2004 15:44:02 +0800 Subject: Best IDE? In-Reply-To: <4ace7f9f.0404111147.3120288a@posting.google.com> References: <4ace7f9f.0404111147.3120288a@posting.google.com> Message-ID: <407A48C2.7090500@graffiti.idv.tw> rakanishu wrote: > I don't know if I'd call 'em IDEs but it's worth taking the time to > learn either emacs or vim. Both are very powerful editors that run on > multiple platforms. I tried emacs three times, but couldn't get into > it. I'm now getting hooked on vim. YMMV. I love Vim. I really do. And it works wonderfully on both Linux and Windows with Exuberant ctags (http://ctags.sourceforge.net/) on Python code. However the only thing that's bugging me is once I'm used to using Vi(that's practically the only editor I've ever use), I'm forever stuck with using Vi. I wish all other real IDEs comes with Vi mode, or I can somehow embed Vim in there (or someone else doing it for me as I'm not that technical). I would love to be using an IDE if it doesn't slow me down. Timothy From xpythonist at yahoo.com.br Fri Apr 2 16:35:51 2004 From: xpythonist at yahoo.com.br (=?iso-8859-1?q?Aloysio=20Figueiredo?=) Date: Fri, 2 Apr 2004 18:35:51 -0300 (ART) Subject: Making the Zen of Python more useful In-Reply-To: Message-ID: <20040402213551.14899.qmail@web61002.mail.yahoo.com> >>> import sys >>> t,sys.stdout = sys.stdout, file('/dev/null', 'w') >>> from this import s >>> sys.stdout = t >>> s.decode('rot-13') u"The Zen of Python..." >>> :) :) Aloysio --- Andrew Henshaw escreveu: > In article , > n3613 at klaff.org says... > > > > > >from this import s > >s.decode('rot13') > > > Thanks for the response. Unfortunately, this still has the > (generally > desired) behavior of the text being printed to stdout. For the less > general > case of using the text to feed some test code, I don't think that is > best. > Unfortunately, I can't think of a way to accomplish both by simply > modifying > the 'this' module (for future releases). Adding another module would > do it; > but, I was hoping someone could suggest a better way. > > -- > Andy > > -- > http://mail.python.org/mailman/listinfo/python-list ______________________________________________________________________ Yahoo! Mail - O melhor e-mail do Brasil! Abra sua conta agora: http://br.yahoo.com/info/mail.html From jacek.generowicz at cern.ch Thu Apr 8 04:41:45 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 08 Apr 2004 10:41:45 +0200 Subject: Dynamic creation of an object instance of a class by name References: <10f99b0f.0404070656.5960e2c8@posting.google.com> Message-ID: Andre Meyer writes: > Right, ok, well, I do not assume to know what classes can be > instantiated, But you are assuming that you have a string which knows, right ... > thus anything like accessing globals() is not likely to help, > sorry. The eval() version works pretty ok so far. ... thus I fail to see a fundamental difference between the eval and globals approaches, in both cases you need the name of the class. > I am develpoing a module of which other people can make use of by > developing their own subclasses, but they need to be instantiated by > my code. Eval() does the trick for me or is there a better way, > assuming you do not need to know which class it might be beforehand? Why don't you just get your users to pass whatever class object they want, to your code ... which can then instantiate the class. Something like: # Your code class your_base: foo = 1 def do_something_with_user_class_instance(user_class): uci = user_class() print uci print dir(uci) return uci # User code class user_derived(your_base): def __init__(self): self.bar = 2 do_something_with_user_class_instance(user_derived) From jjl at pobox.com Thu Apr 22 18:30:09 2004 From: jjl at pobox.com (John J. Lee) Date: 22 Apr 2004 23:30:09 +0100 Subject: Book "Programming on Win32" still useful? References: <39cbe663.0404192259.3e105972@posting.google.com> Message-ID: <877jw7ejda.fsf@pobox.com> "drs" writes: > "Piet" wrote in message > news:39cbe663.0404192259.3e105972 at posting.google.com... [...] > > still a good buy? I think it will surely be enough to get the basics, > > but what if I want more? > > It is still very useful. While Python has changed, the parts that are > covered in the book have not changed that much. Further, aside from .NET, > win32 is about the same -- particularly since you are using the version of > windows that was current when the book was published. New stuff not in the book: ctypes is very much worth looking at; IronPython and other .NET efforts are worth keeping an eye on, at least. John From newsgroups at jhrothjr.com Thu Apr 8 19:14:58 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Thu, 8 Apr 2004 19:14:58 -0400 Subject: List vs tuples References: <107bf8q8fhsmg5e@news.supernews.com> Message-ID: <107bn9jtoafb921@news.supernews.com> "Roy Smith" wrote in message news:roy-BDDD71.17205008042004 at reader1.panix.com... > "John Roth" wrote: > > A list is a data structure that is intended to be used with > > homogenous members; that is, with members of the same type. > > There's really nothing about a list which makes it more suitable for > homogeneous elements than a tuple. It's true that people do tend to > think tuple when they want a mixed collection of objects, but there's > nothing in the language semantics which makes that so. > > I've written lots of code which parses data files. If you've got a > sequence of arbitrary type objects, the easiest way to process them is > often to read them sequentially and append them to a list. I don't see > anything wrong with that. For example, I once had to write some code > which parsed SQL statements that looked something like: > > insert into foo values (1, 2, 'foo', 3.14, 'bar', 4, 5, 'baz', ...); > > There were a total of about 30 items of mixed type (strings, integers, > and floats) in the ()'s. > > One of the really nice things about Python (vs. C++ or Java) is that > you're not bound by the tyranny of static typing. This is a perfect > example of how this makes life so simple. This is perfectly true, but that's the intention. Guido says so himself. Lots of people either don't believe him, or don't understand him. If you think of it this way, the "quirks" become understandable: it makes no sense to append something to the end of a c type struct, for example. John Roth From ny_r_marquez at yahoo.com Fri Apr 23 16:37:26 2004 From: ny_r_marquez at yahoo.com (R.Marquez) Date: 23 Apr 2004 13:37:26 -0700 Subject: CAD graphics with Python: Which lib, pack, tool? References: Message-ID: <8a27e309.0404231237.6ce7c37f@posting.google.com> "F. GEIGER" wrote in message news:... > Hi all, > > I'm dev'ing a control app, that has as a part of it a window showing > CAD-drawings. > > So I'd like to display drawings coming from DXF files. In the first place > I'd start displaying rectangles and circles, i.e. simple shapes. > Nevertheless, the goal is to scan DXF files for the shapes to be displayed. > > PythonCAD comes to my mind. But, alas, yet I did not succeed in installing > it on my Win2k box - the underlying graphics toolkit is missing DLLs. > > But anyway, as I do not want to develop a full blown CAD program (I "simply" > want to display, zoom an rotate them), there's probably somthing simpler out > there for my purposes. > > My app uses Python 2.3.x and wxPython (2nd latest release, upgrade any time > soon). I dev it on Win2k which will be the first target platform. But I see > Linux as a target already on the horizon. > > So the lib should run on Win2k, but not prevent me from running on Linux. > The lib should integrate somehow with wxPython. > > OTH, there are graphic libs 'n' packs out there similar to wxPython (was it > FOX?). So, if there are many more pros than cons, I'd consider changing from > wxPython. > > Any hint is welcome. > > Best regards > Franz GEIGER I was going to suggest looking into embedding a drawing viewer such as Volo View as an ActiveX component, until I realized that you want a cross platform solution. You may want to look at QCad which is GPLed and cross platform (I think through GTK), but I have no idea what it would take to embed it into your app. I wonder if looking at the code and/or talking with the developer you could come up with a simple DXF reader. (Of course you could study the DXF format on your own as well, but I think that is what you are trying to avoid. :) -Ruben From jcarlson at uci.edu Sat Apr 10 15:18:00 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Sat, 10 Apr 2004 12:18:00 -0700 Subject: Code blocks and top posting In-Reply-To: References: <8ef9bea6.0404100720.65ffd2c9@posting.google.com> Message-ID: I understand your point, however... >>> def async_chain(): ... def do_step_1(): ... print 'Step 1.' ... after_idle(do_step_2) ... def do_step_2(): ... print 'Step 2.' ... after_idle(do_step_3) ... def do_step_3(): ... print 'Step 3.' ... after_idle(do_step_1) ... >>> def after_idle(funct): ... funct() ... >>> async_chain() Step 1. Step 2. Step 3. And what you seem to want... if condition: funct() def funct(): #body ... is not available in any modern programming language. It is also not possible to handle syntactically in the Python interactive shell. - Josiah From derek at hiredgoons.org Wed Apr 14 13:19:22 2004 From: derek at hiredgoons.org (Derek Thomson) Date: Thu, 15 Apr 2004 03:19:22 +1000 Subject: Difficulty Finding Python Developers In-Reply-To: <65cbc3dd.0404140641.3501fde8@posting.google.com> References: <65cbc3dd.0404140641.3501fde8@posting.google.com> Message-ID: <407d73b4@duster.adelaide.on.net> Hi Paul, Paul Morrow wrote: > We haven't actually > posted a job on Monster, but we have been talking with various > headhunters in our area and they don't have many resumes that show > Python experience. An so now, of course, mgt is wondering whether > selecting Python was a mistake. > Management are wondering whether some technology selection was a mistake because "headhunters" with not a single clue about anything technical whatsoever have trouble attracting people with those skills? These "recruitment" types are merely salespeople - if it isn't spoken about in glossy business magazines with lots of pictures and pie-charts then it doesn't exist as far as they are concerned. That is the space they operate in. Therefore they only *attract*, in the main, developers who fall into that area as well. Honestly, they probably do have more people than they think with Python skills in their set of clients (I don't know *any* professional developers who don't at least understand Python in a limited way), but it just doesn't register in either their consciousness or via their reporting tools. Secondly, if the terminology hasn't been explained to them very carefully via power-point slides they just don't want to know, or at least find it very difficult to cope in general. I've had a couple of calls from "headhunters" supposedly wanting Python developers. They try to work through the same scripts but substituting "Python" for "Java" all the while. It just doesn't work - and they are doing both employers and potential employees a disservice by attempting to do this. No doubt they report back that they couldn't find anyone suitable - because everyone they contacted responded by asking variations of, "Do you have any idea what the hell you are talking about?" So, I'd consider getting new management, fast! :) With that kind of logic, we would all be using COBOL to this day. Where would all the developers for anything else come from? How would all those poor "headhunters" find jobs for their clients who only know COBOL? That's what's in all the glossy magazines! My advice is to use internet forums where you can recruit directly - in cutting edge areas like Python "headhunters" are definitely *worse* than useless. It will be faster, cheaper, and you'll get better people. Regards, Derek. From tjreedy at udel.edu Fri Apr 2 11:56:06 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 2 Apr 2004 11:56:06 -0500 Subject: __nonzero__ of iterators References: Message-ID: "Christian Eder" wrote in message news:c4gjup$615$1 at ttt14.vie.at.tttech.ttt... > I just discovered the following pitfall in Python 2.3. It is only a pitfall for those who mistakenly think that iterator == (actual, in memory, Python) sequence. They are related but quite different in their Python meaning. A sequence (array, actually) allows random access. An iterator only allows forward scanning. A sequence, in general, is accessed by indexing or slicing. An iterator only returns values via a .next method. I don't know if the turorial emphasizes these differences enough or not. > Consider the following code : > > >>> a = {} > >>> bool (a.keys ()) > False > >>> bool (a.iterkeys ()) > True > > So, an "empty" iterator evaluates to True in boolean context. So what? Why would you take bool() of an object known to be non-null? > At a first glance, this is not what one would expect. Depends on whether one mistakenly thinks iterator == sequence. Consider: bool(0) == bool(0L) == bool(0.0) == False but bool('0') == True. A pitfall? Yes, for someone who thinks number representations can blindly replace numbers (as, I have the impression, is true for some other languages). No, for someone who understands the difference in Python > This causes > several problems, e.g. if you operate on something expected to be > sequence, and you guard your code with "if seq :" to avoid crashing into > an empty sequence, you still crash if you get an empty iterator, Passing an iterator to a sequence function is a bug that should cause a crash. So should passing a numberstring to a number function that does not check and convert if necessary. Consider: if num: return hi//num If num == '1', this will crash, as it should. So will '''print "This answer is " + numstring''' when numstring is an unconverted number. > even if > the rest of your code is able to deal with an iterator as well as with > any other sequence type. To repeat, an iterator is not a sequence type. Not is a sequence and iterator type. But both are iterable types. If 'the rest of your code' deals with the sequence *as a sequence*, by using sequence access methods, then it cannot deal with the iterator 'as well' unless you convert the iterator to a sequence with a sequence constructor, as in 'seq = list(it)'. (Yes, you may want to type-guard this). And you put that *before* your 'if seq:' guard. But the current idiom (see * note below) for new code is to only do this if you need random access (to sort, for instance). If you only need forward sequential access, the current idiom is to convert the sequence to an iterator with 'it = iter(seq)'. Or use a for loop which does this for you. Or call a function itself coded with an iter call or for loop. To avoid the need to test the type first, before the conversion, iterators were defined as returning themselves in response to iter() so that it = iter(it)' is innocuous in a way that mylist = list(mylist) may not be. For an explicit while loop (which is seldom needed), the idiom is it = iter(input) while 1: try: item = it.next except StopIteration: break For iterators, the item-requiring code is guarded by try: except StopIteration: instead of if seq:. * The reason to convert 'iterables' to iterator rather than list as the common type is that the former scales better as one expands to serially processing millions, billions, and even trillions of items. In addition, for statements convert to iterator anyway. (The current exception for old-iterator-protocol objects will, I am sure, disappear sometime in the future.) Also, in the (possibly mythical) future, Guido would like to change generic list-returning functions and methods to return iterators instead. ('Generic' means no specific reason to do otherwise, as there obviously is with tuple, list, list.sequence, list.sort, etc.) So, for instance, dict.iterkeys would be renamed dict.keys and the current dict.keys (which effectively equals list(dict.iterkeys()) anyway) would disappear -- and this post could no longer happen ;-) Terry J. Reedy From michele.simionato at poste.it Sun Apr 4 00:45:32 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 3 Apr 2004 21:45:32 -0800 Subject: emergent/swarm/evolutionary systems etc References: Message-ID: <95aa1afa.0404032145.7b3b9466@posting.google.com> Josiah Carlson wrote in message news:... > Want to run a file? (be careful though, executing the contents of a > file can be dangerous)... > fil = open('filename', 'rb') > contents = fil.read() > fil.close() > exec(contents) or just use execfile('filename') or even import filename. Michele Simionato From lance.ellinghaus at eds.com Thu Apr 29 13:07:05 2004 From: lance.ellinghaus at eds.com (Ellinghaus, Lance) Date: Thu, 29 Apr 2004 13:07:05 -0400 Subject: Modules to create XML for OpenOffice Message-ID: <79D80D394197764997DC956801CABCEEA9A5AE@ushem204.exse01.exch.eds.com> Has anyone created a set of modules to facilitate creation of XM Document files for OpenOffice? lance Lance Ellinghaus TWAI Operations Integration/Special Projects Work Phone: 214-922-6458 Work Cell: 972-877-0409 Nextel: 142*52*5511 Home Phone: 940-271-1274 Email: lance.ellinghaus at eds.com From shane at zope.com Thu Apr 1 12:14:07 2004 From: shane at zope.com (Shane Hathaway) Date: Thu, 01 Apr 2004 12:14:07 -0500 Subject: Python conference slogan In-Reply-To: <30260531.0404010833.1b834032@posting.google.com> References: <30260531.0404010833.1b834032@posting.google.com> Message-ID: <406C4DDF.5000907@zope.com> simo wrote: > Peter Maas wrote: > > >>I surrender immediately and have to admit that I don't get it (One >>Nation Under Under Python). Google was no help. I couldn't find the >>source, only echoes (seems to be a wide spread joke pattern in the >>US). Care to give us ignorants a hint? > > > Yeah, as an Englishman, I don't get it either (despite living in the US). Ok, it's definitely not good. It's a cross between the U.S. Pledge of Allegience and Python's use of double-underscores. It was *not* intended to suggest that Python replaces deity. ;-) Any creative suggestions? Shane From pm_mon at yahoo.com Tue Apr 20 10:21:46 2004 From: pm_mon at yahoo.com (Paul Morrow) Date: Tue, 20 Apr 2004 10:21:46 -0400 Subject: Difficulty Finding Python Developers In-Reply-To: References: <65cbc3dd.0404140641.3501fde8@posting.google.com> Message-ID: Yes, that's our ad. I guess hr wasn't as careful as they should've been when they authored it (there's also a mispelled word)... :-( You probably already realized this, but that should've been $45 to $55 per hour. Roy Smith wrote: > pm_mon at yahoo.com (Paul Morrow) wrote: > >>We've worked hard to convince our company to migrate our core >>applications to Python, and now we're looking for a Python developer >>in Atlanta to handle a short-term (approx. 3 month) project. But our >>initial searches have been fairly unsuccessful. We haven't actually >>posted a job on Monster, but we have been talking with various >>headhunters in our area and they don't have many resumes that show >>Python experience. An so now, of course, mgt is wondering whether >>selecting Python was a mistake. >> >>As anyone had a similar experience? Suggestions? > > > I'm guessing this is your ad: > > Company: Loyaltyworks, Inc. > Location: Atlanta, GA 30305 > Salary/Wage: 45.00 - 55.00 USD /year > Status: Per Diem, Temporary/Contract/Project > > I think you'd do better if you were willing to pay a bit more. Most > developers find it difficult to pay the rent on $55 a year. :-) From atheist at pandora.be Tue Apr 6 06:14:51 2004 From: atheist at pandora.be (Wouter Vanden Hove) Date: Tue, 06 Apr 2004 12:14:51 +0200 Subject: error installing packages Message-ID: I'm trying to install Numeric on a mandrake-9.1 box but I get following error: [root at localhost numarray-0.9]# python setup.py install 'import site' failed; use -v for traceback Using EXTRA_COMPILE_ARGS = [] Traceback (most recent call last): File "setup.py", line 153, in ? main() File "setup.py", line 144, in main setup(**p) File "/usr/lib/python2.3/distutils/core.py", line 135, in setup ok = dist.parse_command_line() File "/usr/lib/python2.3/distutils/dist.py", line 422, in parse_command_line args = self._parse_command_opts(parser, args) File "/usr/lib/python2.3/distutils/dist.py", line 469, in _parse_command_opts cmd_class = self.get_command_class(command) File "/usr/lib/python2.3/distutils/dist.py", line 770, in get_command_class __import__ (module_name) File "/usr/lib/python2.3/distutils/command/install.py", line 22, in ? libname = sys.lib AttributeError: 'module' object has no attribute 'lib' How is this to be solved? Wouter From peter at engcorp.com Thu Apr 15 09:13:26 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 15 Apr 2004 09:13:26 -0400 Subject: Difficulty Finding Python Developers In-Reply-To: References: <65cbc3dd.0404140641.3501fde8@posting.google.com> <65cbc3dd.0404141018.36d9d4ce@posting.google.com> Message-ID: A B Carter wrote: > 2 - Start setting expectations with management. For example, explain > that if there are not a lot of Python programmers it's because it's a > new language that > it builds on the strengths of langauges such as C++, Java and perl > while avoiding their weaknesses. If I were his management, here I might say, "But I thought you said Python was older than Java! If it's so good, why hasn't it caught on more than Java?" or "How can it build on the strengths of Java when it's older?" > Mention that when you do find a > Python programmer he'll probably be better than your average perl or > Java programmer. And here I would ask, "Why do you say that? If there are so few of them around, how could anyone know whether they're better or worse? And wouldn't the best programmers be using the most popular languages, because they would make more money that way?" > Make the argument that you get what you pay for, and > the extra expense of Python is worth it. "I thought you said Python was free... now you're telling me it's going to cost us more than the other languages because it's so hard to hire anyone who knows it?" > 3 - With 2 out of the way consider rethinking how this three month > project should be done. If Python talent is scarce then it might make > more sense to develop in-house talent. This may no longer be a three > month project but down the road your in a more solid position, which > ,if you think about it, is a basic part of what Python is all about. Good advice here, IMHO. :-) This is what we did when first considering Python, by the way, and I had a co-op student learn the langauge and develop a GPIB interface with a wrapper around a DLL using "calldll". It took him about a week to learn Python, about a week to get a basic calldll wrapper working, about a week to implement a simple RF test for one of the devices the company made (controlling two signal generators and a spectrum analyzer) and about a week to figure out how to slap a simple GUI on it using Tkinter. I wonder if this "three month project" has much more than that in it... -Peter From llothar at web.de Wed Apr 14 18:40:35 2004 From: llothar at web.de (Lothar Scholz) Date: 14 Apr 2004 15:40:35 -0700 Subject: Difficulty Finding Python Developers References: <65cbc3dd.0404140641.3501fde8@posting.google.com> <407D6269.3090909@engcorp.com> Message-ID: <6ee58e07.0404141440.4d8ab0f4@posting.google.com> Peter Hansen wrote in message news:<407D6269.3090909 at engcorp.com>... > Paul Morrow wrote: > Don't hire "Python programmers". I successfully staffed a team > with over twenty five developers over the last five years, without > once hiring anyone who was a "Python programmer". I did make an There is a difference between a long term development team and a three month milestone programm task. In the later case you must hire an experienced python programmer - if possible. From sean_berry at cox.net Fri Apr 23 01:42:44 2004 From: sean_berry at cox.net (Sean Berry) Date: Thu, 22 Apr 2004 22:42:44 -0700 Subject: Python CGI: how to retrieve variables passed by URL References: Message-ID: This may help, but not sure if there is a better, built in way. print os.environ["QUERY_STRING"].split("=")[1] prints value if I use localhost/cgi-bin/script-name.cgi?variable=value and this will work... but is there a better way? "Sean Berry" wrote in message news:hU1ic.86730$U83.37750 at fed1read03... > If I go to my cgi python script with > localhost/cgi-bin/script-name.cgi?variable=value > > How do I gather this value? > > Thanks in advance. > > From slurper1234 at hotmail.com Sun Apr 11 19:28:59 2004 From: slurper1234 at hotmail.com (slurper) Date: Mon, 12 Apr 2004 01:28:59 +0200 Subject: Python OS References: <107j4eu6ffn2c68@corp.supernews.com> Message-ID: <4079d494$0$1355$ba620e4c@news.skynet.be> "A Evans" wrote: > I have a question concerning the development of Python Based Operating > System. You see I have had sort of a dream to develop an Open Source > Operating System that would revolutionize the OS market and Since I > started using Python I have fallen in love with the language. Reading > articles here and there I have read that Python is a more secure language > than C. I also read another article (I can't remember which) saying Python > would not be able to develop an OS. I don't believe its true however. I am > by no means a programmer at this stage. But as I learn more and more I see > Python as the Holy Grail of programming languages entirely crazy for production os, spending lots of time as a hobby project but you're right about python... > > My questions would then be, is Python capable of creating an OS from > scratch and if so would it be plausible if possible > > Cheers > > A python NewBie - Man I hate that term does anyone else > > See Ya From alexanro at stud.ntnu.no Sun Apr 18 19:31:46 2004 From: alexanro at stud.ntnu.no (=?iso-8859-1?q?Alexander_R=F8dseth?=) Date: Mon, 19 Apr 2004 01:31:46 +0200 Subject: Pygame References: Message-ID: Thanks for the link and the thought. Enthought is probably an interesting project. However, I just want to know why fullscreen graphics is not included in Python by default. Besides, a huge amount of the power of Python-scripts comes from knowing what other people has installed already. - Alexander From rawbobb at hotmail.com Thu Apr 29 20:28:11 2004 From: rawbobb at hotmail.com (bobb) Date: Fri, 30 Apr 2004 00:28:11 GMT Subject: How to read a file from another server? Newbie References: <%Oejc.16$ph.9@fed1read07> <9ugjc.3709$g31.1370@newsread2.news.atl.earthlink.net> Message-ID: Sean, what kind of server are you trying to get at where the file exists? bobb "Sean Berry" wrote in message news:Yyjjc.2071$Jy3.1146 at fed1read03... > ssh I think. > > > "Ivan Voras" wrote in message > news:c6k9fh$3t9$1 at bagan.srce.hr... > > Edward Diener wrote: > > > > > Sean Berry wrote: > > > > > >>I am trying to read in a file from another server. > > >> > > >>If I try > > >>x = open("servername:/path/to/file", "r") > > > > > > > > > x = open("servername://path/to/file", "r") > > > > Um, what does this to? What protocol does it use? > > From tkpmep at hotmail.com Thu Apr 22 16:09:06 2004 From: tkpmep at hotmail.com (Thomas Philips) Date: 22 Apr 2004 13:09:06 -0700 Subject: Deleting objects - my earler post got garbled Message-ID: I have a question about deleting objects. My game has two classes, Player and Alien, essentially identical, instances of which can shoot at each other. Player is described below class Player(object): #Class attributes for class Player n=0 #n is the number of players #Private methods for class Player def __init__(self,name): self.name = name self.strength = 100 Player.n +=1 def __del__(self): Player.n -=1 print "I guess I lost this battle" #Public methods for class Player def blast(self,enemy,energy): enemy.hit(energy) def hit(self,energy): self.strength -= energy if(self.strength <= 50): self.__del__() I instantiate one instance of each class: Hero = Player("Me") Villain = Alien("Not Me") If Hero hits Villain with Hero.blast(Villain, 100), Villain dies and executes its destructor (__del__). The game then ends. However, 1. When I execute the program in IDLE, IT FINISHES BY EXECUTING THE DESTRUCTOR FOR BOTH HERO AND VILLAIN. How can this be? As one of the two objects was destroyed prior to the end of the game, how can it be re-destroyed when the program ends? 2. After Hero hits Villain with an energy of 100, Villain executes its destructor, but I find I can then type Villain.blast(Hero,100) and have the alien (whose demise had me gloating) blast me right back! Why is it that the blast() method works for an object whose destructor has been executed? Thomas Philips Post a follow-up to this message From cnoviello at hotmail.com Sun Apr 25 12:16:24 2004 From: cnoviello at hotmail.com (Carmine Noviello) Date: Sun, 25 Apr 2004 16:16:24 GMT Subject: [ANN]PyCrash-0.4pre2 released Message-ID: Hi, a new version of PyCrash is released with new features and improvement.You can download it at: http://sourceforge.net/project/showfiles.php?group_id=98026&package_id=111026&release_id=233776 What's new in this release: * Added a new method to PyCrash class, forceDump(), that forces the creation of the crash dump, if an exception is raised. forceDump() can be very useful when an exception hasn't reached the top-level, but the user wants the same to make a dump of the application context. * Starting from this release, by default, PyCrash doesn't start exception tracing automatically. User must invoke the enable() method to start tracing, and can use the disable() method to stop tracing in every moment. * Now the getEncryptedCrashDump() method of utils.Encrypt.EncryptedPyCrash class is deprecated, and it will be no longer supported starting from PyCrash-0.4 release. Use instead the getCrashDump() method. * Added a new class HTMLPyCrash, in the pycrash.util module, which converts the crash dump in HTML format rather than XML. The generated HTML dump is based on CSS, so the developer can define custom CSS to arrange the output. There is also a new script in the util subdir, named pucrash2html.py, which converts PyCrash file in HTML format. You can see an example of the output generated by the HTML dumper here: http://pycrash.sourceforge.net/test-pycrash.html Enjoy! _______________________________________________________________________ About PyCrash Project: PyCrash is a Run-Time Exception Dumper which handles uncaught exceptions during the execution of Python programs and collects information about the program context. PyCrash can be very useful in report bug information, because the programmer can easily analyse the program execution context of the crashed application. Major information collected by PyCrash in the crash dump is: - Information about operating system, Python and Python Standard Library version and general information about the program that is crashed (e.g., program name and version, time at witch program started and ended, and so on) - Information about the uncaught exceptions, like the exception type, the context (namely method name) in which the exception occurred and the exception value - General information about variables state - Information about the stack of each thread, like the list of stack frames, the variables value in each stack frame, and so on - General information about source code, like variable and function position in source file that can be useful for the programmer to find quickly bugs in source tree The format of the crash dump file generated by PyCrash is XML, so the programmer can easily read this file to understand why the program is crashed. Now, is also available a GUI browser, named PyCrash Viewer, which allows developers to analyze quickly and easily PyCrash crash dump files in a graphical manner. * Starting from next version, we'll try to document all the PyCrash API More information can be found at: http://www.pycrash.org Thanks!

PyCrash 0.4pre2 - a crash handler for Python written applications. (25-04-04)

From asdf at asdf.com Tue Apr 27 06:34:11 2004 From: asdf at asdf.com (asdf sdf) Date: Tue, 27 Apr 2004 10:34:11 GMT Subject: python for MVS legacy access? Message-ID: wondering what python resources might be available for python-based legacy system access, particularly to MVS, DB2 and Adabas. What additional pieces might be needed to implement this access? Python would be running on Unix and need to do Adabas and DB2 access. Screen-scraping is a common technique. Any screen scraping modules for python? I assume this would require an SNA gateway on the unix system to enable 3270 emulation? True? How about telnet for 3270? Plenty of python support for telnet. A hundred years ago, I used telnet for 3270 access over a dialup line. Is telnet access likely to be available on a contemporary system? Would it support some kind of database access? How about python database interfaces for DB2 and Adabas? I see the PyDB2 module mentioned at python.org. Any know have any experience with it? No mention of any Adabas support at python.org. I assume that the pyDB2 module would require installation of some underlying DB2 proprietary libraries for Unix. Similar to SQL*Net for Oracle. True? Does python to MVS access raise any special security issues? Does support for any of these ideas create any special hardship on the MVS sysadmin/DBA side? From titi2027 at netplus.ch Mon Apr 26 14:56:21 2004 From: titi2027 at netplus.ch (titouille) Date: 26 Apr 2004 11:56:21 -0700 Subject: How to pass the focus on python application Message-ID: Hi everybody ! first, sorry for my poor english, I'm french mothertongue ;) technologies : -------------- Python 2.3 Twisted Matrix 1.2.0 wxPython 2.5.1 platform : ---------- winXP I explain my problem : I try to build a multi-plateform python socket server to interact with flash animations. Animations send by xmlSocket xml string, server intercept string, parse it, execute method and return result as xml string to the FlashXmlSocket. at beginning, xml sended string contains DOM document who describe one or multiples operation(s) to execute. So final xml string (with return results) contains already one or multiple return execution statements When i use serveal methods like OpenFile or SaveFile, DialogBox appears on the screen. But it appear not on the top, because focus is on flash animation... So if flash animation is for exemple in full-screen, user don't see the opened dialog-box... How to, on each platform (win, linux, mac), add a method to set the focus on the server if it's required ?? for example, send xml contain method like this : 1. setFocusToServer () 3. setNewWorkingDirectory (path) 2. OpenDialog (message, defaultDirectory, defaultFile, wildcard) and add a -- setFocusToServer (self) if wx.Platform == '__WXMAC__': # code to focus server on mac when required elif wx.Platform == '__WXMSW__': # code to focus server on window when required elif wx.Platform == '__WXGTK__ || wx.Platform == '__WXMOTIF__ : # code to focus server on linux when required -- method to focus application on each platform many thanks in advance for your ideas, url and experience about this subject Thierry From roy at panix.com Tue Apr 27 22:37:08 2004 From: roy at panix.com (Roy Smith) Date: Tue, 27 Apr 2004 22:37:08 -0400 Subject: Is Perl *that* good? References: <87fzaqmm8t.fsf@strauser.com> <38ec68a6.0404262308.50029919@posting.google.com> Message-ID: Carl Banks wrote: > especially because regexps are > prone to being used in recursive functions and such Why are regexps prone to being used in recursive functions? From jgentil at sebistar.net Fri Apr 2 20:49:19 2004 From: jgentil at sebistar.net (Jon-Pierre Gentil) Date: Fri, 02 Apr 2004 19:49:19 -0600 Subject: Major memory leak during embedding Python in C++ In-Reply-To: References: Message-ID: <106s610hae92ldb@corp.supernews.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Ben Held wrote: > Having recently upgraded to Python 2.4, I am having a large memory > leak with the following code built with VC++ 6.0: Your first mistake is that Python 2.3.3 is the latest version. Wherever you got Python 2.4, I'd be scared. - -- :: Jon-Pierre Gentil :: PGP Key ID 0xA21BC30E :: Jabber: jgentil at jabber.org -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.4 (GNU/Linux) Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org iEYEARECAAYFAkBuGB8ACgkQOrVFmaIbww7pBgCeNSQFcfLnAHVzEzXyxOZqZJfV 6D0Aniso/bD/iGxMtyqRhpF/QUoWTsu7 =JNV2 -----END PGP SIGNATURE----- From simoninusa2001 at yahoo.co.uk Sat Apr 10 14:23:01 2004 From: simoninusa2001 at yahoo.co.uk (simo) Date: 10 Apr 2004 11:23:01 -0700 Subject: wxListCtrl with CheckBox? References: <30260531.0404092256.6b58e3a1@posting.google.com> Message-ID: <30260531.0404101023.68179d59@posting.google.com> Harald Massa wrote: > > I've got a report list and want to have a checkbox in the last column > > of each row. > Get the checkbos in the first column of each row and use a wx.checklistbox No that won't work as you can't put any widgets in the first column of a wxListCtrl, only a bitmap. And a wxCheckListBox is entirely different from a list *with* checkboxes - it's a list *of* checkboxes IYSWIM. Plus, it really has to be in the last column for my app :-( I fear I'm getting to the point I was when I gave up on PyQt - I've run out of widgets, and am going to have to start looking at making my own somehow..... From lbates at swamisoft.com Fri Apr 9 10:40:17 2004 From: lbates at swamisoft.com (Larry Bates) Date: Fri, 9 Apr 2004 09:40:17 -0500 Subject: how to force a python service to reconfigure itself after updating? References: Message-ID: You could move the reading of the configuration file inside the loop so it is read each time the service wakes up. Unless your configuration file is huge (10,000+ lines), the overhead is negligible. The other alternative is to put a socket server inside the service and have a small external program to send something to it when it needs to reread the config file. Regards, Larry Bates Syscon, Inc. "Farraige" wrote in message news:c548h3$8gh$1 at nemesis.news.tpi.pl... > Hi! > > I hope you will help me. I have the following problem.... > I have implemented a Windows NT service using win32serviceutil. The service > runs a 'working loop' in another thread and waits for the stop event to be > set. A working loop thread checks the space used by logfiles against the > given upper limit and deletes the files, if the upper limit is reached. > After each space analysis it sleeps for about 30 minutes. The service > handles start/stop/restart/.../update parameters from the command line. > Update command updates by default all the changes made in the service python > code without need to restart the service... What about the situation if my > service reads some configuration datas from its config file? If I change > some data in the configuration files, those changes "will not be seen" after > using update parameter due to none change was made in the service code. Do > you have an idea how to overload the standard behaviour of using update > command line parameter to force the service to reconfigure itself without > restarting? I don't now how to implement communication between the main > function that handles all command (thanks to > win32serviceutil.HandleCommandLine) line parameters and the working thread > that is started by the service in its SvcRun method? > > Thanks in advance for any hints! > > Best wishes, > > Niki > > From peter at semantico.com Wed Apr 7 10:20:28 2004 From: peter at semantico.com (Peter Hickman) Date: Wed, 07 Apr 2004 15:20:28 +0100 Subject: design by contract versus doctest In-Reply-To: <40740321$0$5063$4d4ebb8e@news.nl.uu.net> References: <407174ea$0$5066$4d4ebb8e@news.nl.uu.net> <4072977b$0$1699$afc38c87@news.easynet.co.uk> <4073c94a$0$5066$4d4ebb8e@news.nl.uu.net> <4073cf1b$0$18217$afc38c87@news.easynet.co.uk> <40740321$0$5063$4d4ebb8e@news.nl.uu.net> Message-ID: <40740e2e$0$27667$afc38c87@news.easynet.co.uk> aku wrote: > I recall correctly, the author himself mention's that DBC is squarely > based on dijkstra's earlier theoretical basis..... Oh god I'm going to have to read it all again! From peter at engcorp.com Tue Apr 13 21:31:46 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 13 Apr 2004 21:31:46 -0400 Subject: Looking for Python Definition In-Reply-To: References: Message-ID: <2Z-dnTP30LwfCeHd4p2dnA@powergate.ca> Dave wrote: > Greetings! > Python22 is installed on my WINXP Home PC. > I have no idea what is does, or why it is installed. > I am not a programmer and do not know what purpose this program provides to > me. > > Any and all information and suggestions are welcome. Read this: http://www.python.org/doc/faq/installed.html -Peter From peter at engcorp.com Fri Apr 30 07:56:07 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 30 Apr 2004 07:56:07 -0400 Subject: urllib2/cookies - surely there's a better way ? In-Reply-To: <282f826a.0404292248.7b71c7d6@posting.google.com> References: <282f826a.0404292248.7b71c7d6@posting.google.com> Message-ID: <84KdnfW3OoNKow_dRVn-vg@powergate.ca> Richard Shea wrote: (about urllib2 and cookies) Search for "ClientCookie"... From R.Brodie at rl.ac.uk Fri Apr 2 08:25:57 2004 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Fri, 2 Apr 2004 14:25:57 +0100 Subject: Travelling salesman variation in python References: Message-ID: "Duncan Smith" wrote in message news:c4jp26$jko$1 at newsg4.svr.pol.co.uk... > No, you're not. I think simulated annealing is a decent candidate for this > problem. The difficulty (in my experience) is in finding decent parameters > for the cooling schedule, so you can find good solutions in reasonable time. The book, "Numerical Recipes" contains a description of simulating annealing, giving the travelling salesman problem as an example. Extracts available online. From jcarlson at uci.edu Wed Apr 7 02:01:47 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Tue, 06 Apr 2004 23:01:47 -0700 Subject: slightly OT: BUT NEEDs to be said In-Reply-To: <213df9a1.0404060804.33d68297@posting.google.com> References: <8b42d1998c978c8c1cddf15c52a1c57b@dizum.com> <213df9a1.0404060804.33d68297@posting.google.com> Message-ID: Arthur wrote: > "Mike C. Fletcher" wrote in message news:... > > >>Sometimes other >>people like TV shows we think are insipid or offensive, this too is part >>of life, and if you realise and accept that (within reason) you'll be >>happier and more content. > > > Despite having loud issues about community conformity and peer > pressures (isolated issues, but loud ones) I must say that the fact > that the Holy Grail movie was one of only 3 I ever walked out on, > hasn't seemed to brand me. I was feeling particularly fragile, I > remember, and looking for comic relief. The dismembering stuff - as a > comic notion - didn't work for me, at the moment. Wuss. > > For those on the edge of their seats: > > 2. Problem Child: "If he pees in the lemonade" , I told my son, "we're > out of here". He pees in the lemonade. > > 3. Priscilla Queen of the Desert: There were options, it seemed to me. > Take off the dress in the Outback, being one. There has to be a way to > promote a message of tolerance, it seems to me, without making putzes > out of guys living on their brawn and wits in the Outback. > > Art You are lumping "Monty Python and the Holy Grail", "Problem Child" and "The Adventures of Priscilla, Queen of the Desert" together in one message saying, "they all suck" (to some degree or another). If at any point you thought "Problem Child" was going to be good to watch, either for you or your son, then you need a /serious/ parental wakeup call. Watching 30 seconds of trailer when I was 10, was enough to convince me that it was a worthless piece of crap, and I was part of the core demographic. As an aside, have you bothered to see "...Holy Grail" since you walked out of it, or have you damned it based on your impression of it while you were "feeling particularly fragile"? Just curious. As for you not enjoying "Priscilla...", well, that is unfortunate. However, the message was not that of tolerance, tolerance carries one unfortunate meaning - you tolerate the kid on the airplane kicking your seat. Perhaps you meant acceptance. And yes, there have been many movies about non-heterosexual lifestyles made, some better, some worse. The choices the writer/director made in regards to "Priscilla..." were his to make, and again, it is unfortunate that you didn't enjoy the movie. - Josiah From no.email at please.com Sat Apr 10 15:48:42 2004 From: no.email at please.com (Stevie_mac) Date: Sat, 10 Apr 2004 20:48:42 +0100 Subject: Simple Class Question - need clarity please References: <2tce701vv505395hcr6dqtvc8ot0fdmkrk@4ax.com> Message-ID: Yes, I've since found the to be the case (reload). I realised it didn't like some formatting & held onto the old (bad) code. I had corrected some indentation ( a tab character was used in 1 line were all others were spaces ). Once corrected, I reloaded & all was OK PS, using activepython (pythonwin) in windows "Alan Gauld" wrote in message news:urig70ppe9f6015e9vi73qht5esl2d4kiu at 4ax.com... > On Sat, 10 Apr 2004 11:33:37 +0100, "Stevie_mac" > wrote: > > > very odd. Works for my now too. Is there some sort of cache that > > holds onto old (bad) code? > > > > How were you running it? From an OS command prompt or from the > IDLE shell (or any other python) prompt? If the latter maybe you > needed to do a > > >>> (mywindow) > > But if from the OS prompt it should be fine. > > Alan g. > > Author of the Learn to Program website > http://www.freenetpages.co.uk/hp/alan.gauld From Holger.Joukl at LBBW.de Tue Apr 20 11:28:15 2004 From: Holger.Joukl at LBBW.de (Holger Joukl) Date: Tue, 20 Apr 2004 17:28:15 +0200 Subject: Tutorial Message-ID: >>hello, i need a good tutorial for Python, nothing for beginners >>wfw S?ren If you want to buy a book, consider David Beazley?s "Python: Essential Reference" (New Riders). One of the best programming language books I have ever seen, but you should have some programming experience. Otherwise you could stick to python?s own documentation - fine as well. G H. Der Inhalt dieser E-Mail ist vertraulich. Falls Sie nicht der angegebene Empf?nger sind oder falls diese E-Mail irrt?mlich an Sie adressiert wurde, verst?ndigen Sie bitte den Absender sofort und l?schen Sie die E-Mail sodann. Das unerlaubte Kopieren sowie die unbefugte ?bermittlung sind nicht gestattet. Die Sicherheit von ?bermittlungen per E-Mail kann nicht garantiert werden. Falls Sie eine Best?tigung w?nschen, fordern Sie bitte den Inhalt der E-Mail als Hardcopy an. The contents of this e-mail are confidential. If you are not the named addressee or if this transmission has been addressed to you in error, please notify the sender immediately and then delete this e-mail. Any unauthorized copying and transmission is forbidden. E-Mail transmission cannot be guaranteed to be secure. If verification is required, please request a hard copy version. From nuffsaid at phreaker.net Thu Apr 29 17:44:22 2004 From: nuffsaid at phreaker.net (Nuff Said) Date: Thu, 29 Apr 2004 23:44:22 +0200 Subject: locale.CODESET / different in python shell and scripts References: <4091621F.5060307@v.loewis.de> Message-ID: On Thu, 29 Apr 2004 22:14:23 +0200, Martin v. L?wis wrote: > PLEASE invoke > > locale.setlocale(locale.LC_ALL, "") > > before invoking nl_langinfo. Different C libraries behave differently > in their nl_langinfo responses if setlocale hasn't been called. Thanks a lot for your help! That solved (part of) the problem; now I get 'UTF-8' (which is correct) when running the following script (with either my self-compiled Python 2.3 or Fedora's Python 2.2): #!/usr/bin/env python # -*- coding: UTF-8 -*- import locale locale.setlocale(locale.LC_ALL, "") encoding = locale.nl_langinfo(locale.CODESET) print encoding Still, one problem remains: When I add the following line to the above script print u"sch?nes M?dchen".encode(encoding) the result is: sch?nes M?dchen (with my self-compiled Python 2.3) sch??nes M??dchen (with Fedora's Python 2.2) I observed, that my Python gives me (the correct value) 15 for len(u"sch?nes M?dchen") whereas Fedora's Python says 17 (one more for each German umlaut, i.e. the len of the UTF-8 representation of the string; observe, that the file uses the coding cookie for UTF-8). Maybe Fedora's Python was compiled without Unicode support? (Is that even possible? I recall something about a UCS2 resp. UCS4 switch when compiling Python; but without Unicode support? And if it would be possible, shouldn't a Python without Unicode support disallow strings of the form u"..." resp. show a warning???) This really drives me nuts because I thought the above approach should be the correct way to assure that Python scripts can print non-ASCII characters on any terminal (which is able to display those characters in some encoding as UTF-8, ISO-8859-x, ...). Is there something I do utterly wrong here? Python can't be that complicated? Nuff. From nuffsaid at phreaker.net Wed Apr 28 18:37:39 2004 From: nuffsaid at phreaker.net (Nuff Said) Date: Thu, 29 Apr 2004 00:37:39 +0200 Subject: locale.CODESET / different in python shell and scripts References: Message-ID: On Tue, 27 Apr 2004 22:29:59 +0200, Martin v. L?wis wrote: > Because, for some reason, locale.setlocale() is called in your > interactive startup, but not in the normal startup. > > It is uncertain why this happens - setlocale is not normally > called automatically; not even in interactive mode. Perhaps > you have created your own startup file? I use two Python versions on my Linux box (Fedora Core 1): the Python 2.2 which came with Fedora and a Python 2.3 which I compiled myself. (I didn't tinker with the last one; Fedora's Python is a (well known) mess.) Both Python versions give me 'ANSI_X3.4-1968' when I run a script with 'print locale.nl_langinfo(locale.CODESET)'. When I execute the same command in an interactive Python shell, I get the (correct) 'UTF-8'. (By 'correct', I mean that the bash command 'locale' gives me 'LANG=en_US.UTF-8, LC_CTYPE="en_US.UTF-8", ...'. This seems to be correct, because e.g. the 'less ...' command shows files which are UTF-8 encoded in the correct way; files which are e.g. 'ISO-8859-1' encoded are not shown in the correct way.) Things are getting even worse: I write a Python script which uses Unicode strings; now I want to 'print ...' one of those strings (containing non-ASCII characters; e.g. German umlauts). With Fedora's Python 2.2 I have to use 'print s.encode('ISO-8859-1') or something similar. With my self-compiled Python 2.3, I have to use (the expected) 'print s.encode('UTF-8')' (though it shows me 'ANSI_X3.4-1968' when using 'print locale.nl_langinfo(locale.CODESET)' in the same file). ??? Any ideas what's going wrong here? (I tried 'python -S ...'; doesn't make a difference.) From reverse.ku.oc.issolok at nothypgnal.delrest.co.uk Wed Apr 28 04:49:00 2004 From: reverse.ku.oc.issolok at nothypgnal.delrest.co.uk (Paul Sweeney) Date: Wed, 28 Apr 2004 08:49:00 +0000 (UTC) Subject: sending an object - twisted or what? References: Message-ID: "Lars Heuer" wrote in message news:mailman.45.1083079451.25742.python-list at python.org... > > I wish to send an object (only one class, but many objects) > > from python running on one computer to python on another. > > It will be over the internet, so needs to be 'secure'. > > > Is twisted the only way to go, or is there something > > simpler for my app? The code for twisted is fairly simple (I found > > I don't know if it's simpler, but there's PyRO: > http://pyro.sourceforge.net/ > I meant to say I had looked at that too, but I just want to operate a queue of objects sent between systems, so the whole name server/URI approach is quite a lot of unnecessary overhead. Thanks for the post though. :-) Paul From SeeBelow at SeeBelow.Nut Tue Apr 27 19:07:16 2004 From: SeeBelow at SeeBelow.Nut (SeeBelow at SeeBelow.Nut) Date: Tue, 27 Apr 2004 23:07:16 GMT Subject: Tkinter vs. wxPython? References: <408E9DCA.EC753FE6@shaw.ca> Message-ID: <408EE7A6.321ED53A@shaw.ca> Doug Holton wrote: > > SeeBelow at SeeBelow.Nut wrote: > > > Do many people think that wxPython should replace Tkinter? Is this > > likely to happen? > > > > I ask because I have just started learning Tkinter, and I wonder if I > > should abandon it in favor of wxPython. > > Could you share a little more info, like are you new to GUI programming, > what platform do you develop on (windows, mac, linux), and what features > do you need for your application. > > If you this is your first time using a GUI toolkit I'd recommend > sticking with Tkinter. It is simpler to use and there is much more and > better documentation since it has been a standard part of Python for a > long time. > > But myself I use wxPython because it has more features. I'm mostly a C programmer, with a little Python experience. I have only basic needs for GUI and graphics. The Tkinter set of widgets seems adequate for my needs, although one never knows for sure what ones needs might be. Portability is important. My audience is 50/50 linux and Windows people. I myself use Win 2000. Ease of learning is important to me. I have only a little experience with GUI and graphics programming. I keep using the phrase "GUI and graphics" because I need graphical output from my programs, not just a GUI to control them. Mitchell Timin -- "Many are stubborn in pursuit of the path they have chosen, few in pursuit of the goal." - Friedrich Nietzsche http://annevolve.sourceforge.net is what I'm into nowadays. Humans may write to me at this address: zenguy at shaw dot ca From gnupeaker at yahoo.com Fri Apr 30 20:38:12 2004 From: gnupeaker at yahoo.com (Eyal Lotem) Date: Fri, 30 Apr 2004 17:38:12 -0700 (PDT) Subject: Announcing PyInvoke Message-ID: <20040501003812.46413.qmail@web50701.mail.yahoo.com> I have not yet seen real transparent RPC for Python, so I decided to implement one: http://pybuild.sourceforge.net/pyinvoke.html I find it really cool, as setting it up is very easy, and using it requires writing little to none rpc-related code. This is not an invitation to "Transparent networking is just wrong" flames, because there are many cases where transparent networking is simply the quickest, simplest and best solution. Please try it out and give me some feedback! (If you send it to the list, please CC it to me) I would also appreciate ideas on easy ways to create authenticated SSL connections automatically between hosts in order to run PyInvoke on top of such a connection to enable security. Thanks! __________________________________ Do you Yahoo!? Win a $20,000 Career Makeover at Yahoo! HotJobs http://hotjobs.sweepstakes.yahoo.com/careermakeover From pythongnome at hotmail.com Tue Apr 20 08:20:43 2004 From: pythongnome at hotmail.com (Lucas Raab) Date: Tue, 20 Apr 2004 12:20:43 GMT Subject: Pygame book Message-ID: I was at the bookstore the other day and I noticed a book that dealt with making games with Pygame. As I recall the book title was "Game Programming with Python." I have an interest in making games, so I was wondering if any of you have this book and if you do, could you please give me a nice overview and whether I should buy the book or not. TIA Lucas From newsgroups at jhrothjr.com Thu Apr 15 19:20:01 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Thu, 15 Apr 2004 19:20:01 -0400 Subject: Goodbye TCL References: <0LudnSads6NmpuPdRVn-vw@centurytel.net> Message-ID: <107u6ef5a2ise19@news.supernews.com> "Stephen Huntley" wrote in message news:f82c8ae7.0404151057.67333d4e at posting.google.com... > Ed: > > I think your post is valuable. Instead of trying to invalidate your > arguments, I will outline my reasons why I stick to Tcl. Then we can > perhaps glimpse how strengths and weaknesses counterbalance. > > The main reasons I stick with Tcl are: What's amusing is that every one of your arguements in favor of TCL are also arguements in favor of Python. This is, after all, 2004, not 1994. Languages don't get widespread use today unless either 1) some mega-mastodon is pushing them, like Java or C#, or 2) they just work out of the box, and solve real problems for the people using them. John Roth > 1. Rock-solid stability. I'm too old to spare time wondering if > frequent crashes in my software are my fault or the underlying > technology's fault. Tcl largely removes this consideration from the > equation. America Online's web server is written in Tcl. It is > highly unlikely I will ever need to scale a product of mine to that > level, so there's a lot of headroom for me. > > I have occasionally looked into new technologies, like Python, PHP, > Ruby, etc; but I've noticed that if you look beyond the FAQ's deep > into the developer mailing lists, you'll generally find statements > like: 'development of the core is going really really well, and within > the next few releases we actually expect it to be stable!' Hold me. > > I frequently use Tcl to write wrappers for other products to catch and > compensate for their shortcomings. This would be pointless if it > weren't for the fact that Tcl is at least an order of magnitude more > stable and reliable than any other technology I've tried. > > 2. Freedom from bugs. For years after college I did almost no coding > because I was sick of the fact that I would have to rewrite literally > everything I wrote two or three times to find a syntactically correct > version that didn't hit a deadly bug. Imagine my surprise when my > first Tcl scripts Just Worked. And the docs were accurate and > complete too, so I didn't have to spend half my time > reverse-engineering (another new experience). For this reason alone > Tcl is almost single-handedly responsible for the fact that I am still > working in the computer world. > > In ten years of Tcl scripting, I think I've encountered three bugs in > the core. I found upon reporting that each one was already fixed in > the latest version. I just don't bother to upgrade my core very often > because of 1. and 2. > > 3. Platform agnosticism. Since Tcl was originally designed to be > embedded it play no favorites in terms of platform features. It's > available on a wide variety of platforms and I suspect will be there > on the platforms of the future in equally reliable forms. I started > with computers on Unix as a student, as a professional worked first > with Macintosh v 7, then on to Windows, and now a bit of everything > (five *nix versions, four Win*s and handheld devices). AS/400 was in > there somewhere. Tcl has been there every step of the way. I'm too > old to relearn my chops every time a new OS fad blows through, and I > don't want to have to predict winners and losers. I feel Tcl > minimizes the likelihood I will have to. > > Here at work I suggested we use a free Tcl installer program rather > than a for-pay Java one. Management chose the Java option. Why? > Because the Java company officially supported all the platforms we > needed to be on, and management felt they couldn't take the risk of > going without assurances. It's turned out that the installer has > required special handling or patches for every OS (and almost every OS > version) we've tried it on, resulting in numerous gotchas and > release-note warnings for our customers. And "official support" is a > bulletin board where their engineers' response is always "we're > working on it." Meanwhile my build and test scripts run merrily and > without alteration everywhere. > > Alternative technologies tend nakedly to favor *nix, and seem only to > offer a subset of function on other OS's grudgingly. Python and > similar technologies treat platform-specific issues like pathnames and > line terminators as special cases with their own commands or > compensating strategies to handle them. Tcl largely handles them > tranparently. It was years before I was even aware of some of these > issues because Tcl handled them so well. Python uses ASCII as a > default string encoding, but recently managed to bolt on a Unicode > library (same with PHP I think). I haven't looked into its Shift-JIS > suppport, which I need for work (and is included with Tcl). > > 4. Tk. Other technologies say 'We don't have a native GUI interface, > but there's a binding to the Tk library.' For all intents and > purposes, Tk is the only game in town for cross-platform GUI > scripting. When I'm using Tcl I know I have access to 100% of Tk's > features and the latest Tk version. Is that true with other > languages' bindings? I don't know, but if I had to bet money I'd say > no. > > Tk follow's Tcl's logic, and it's a lot easier to program Tk > interfaces when in the Tcl mindset then try to access Tk's features by > switching gears from another language's mindset. I don't do GUI > programming very often, but when I have to, it's nice to know that I > can do it as a trivial extension of my existing Tcl skills. > > Ed, your voice-recognition project looks very interesting, and I look > forward to using it when it's ready for prime time. I spend 90% of my > time in front of a Windows computer (my boss's choice, not mine): how > does it run on Windows? How stable is it? How does Twisted's event > architecture compare to Tcl's? > > > Steve Huntley From jepler at unpythonic.net Wed Apr 7 09:02:54 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 7 Apr 2004 08:02:54 -0500 Subject: String comparison problem In-Reply-To: References: Message-ID: <20040407130254.GD6139@unpythonic.net> You should use "repr" to see the exact byte sequence contained in the strings. If the strings really contain the same sequence of bytes, then they are equal. There must be some difference between them that is non-printable. >>> s1 = "01b7ebfc27437a90cc421c50df8f9ac5" >>> s2 = "01b7ebfc27437a90cc421c50df8f9ac5" >>> s1 == s2 1 But what you'll actually find is that this statement > print string.lower(md5sum(f_md5)) will print a different value the first and second times you execute it. Jeff From peter at engcorp.com Mon Apr 26 13:21:54 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 26 Apr 2004 13:21:54 -0400 Subject: Zip with sequences of diffrent length In-Reply-To: References: Message-ID: <3-qdnWq1k_2v2BDd4p2dnA@powergate.ca> Nickolay Kolev wrote: > I want to make tuples of the elements of a list like this. > > l = [1, 2, 3] > > Wanted tuples: > > (1, 2) > (2, 3) > (3, None) > > I can get the first two tuples using zip(l, l[1:]). How do I get the > last one? >>> l = [1, 2, 3] >>> zip(l, l[1:]+[None]) [(1, 2), (2, 3), (3, None)] From rogerb at rogerbinns.com Thu Apr 22 16:37:01 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Thu, 22 Apr 2004 13:37:01 -0700 Subject: Multi-threaded printing and UIErrors in Windows Message-ID: <10nll1-rt5.ln1@home.rogerbinns.com> My program has a random smattering of print statements scattered throughout that are mainly a debugging aid. They are typically things like this: print "entering key mode" The code is multithreaded, and the printing typically happens in both the main thread and a worker thread doing serial port IO. The problem I am experiencing when the program is packaged up with py2exe is that exceptions happen: IOError: [Errno 9] Bad file descriptor This can happen in either thread. Why is this happening? It doesn't happen on Linux or Mac, and hasn't happened when not using py2exe. Python 2.3, wxPython 2.4, py2exe 0.5 (and the previous version). Roger From mikalzetTogli at interfree.it Wed Apr 7 15:49:31 2004 From: mikalzetTogli at interfree.it (TaeKyon) Date: Wed, 07 Apr 2004 19:49:31 GMT Subject: recursive file editing References: Message-ID: Il Tue, 06 Apr 2004 15:08:37 +0200, Peter Otten ha scritto: > I suggest that you stick with with the simpler approach in my later post > until you have a firm grip of classes. For the task at hand the Path class > seems overkill, now I'm reconsidering it. Here is a variation on the theme I came up with this afternoon: #!/usr/bin/python import os, sys, re, fileinput try: target_folder = (sys.argv[1]) original_pattern = (sys.argv[2]) result_pattern = (sys.argv[3]) except: print "Substitutes a string with another in all files of a directory" print " Use: ./MyScript.py directory string other_string" sys.exit() for folders, folder, filelist in os.walk(target_folder): for filename in filelist: file = os.path.join(folders,filename) for line in fileinput.input(file,'inplace=1'): line = re.sub(original_pattern,result_pattern,line) print line # Commented out because apparently useless, from the documentation I # don't quite understand whether it ought to be here or not # fileinput.close() This works - almost. 1) It does substitute the pattern, however it seems to add a newline for each newline present in the original file every time it is run (so files get longer and longer), and I don't understand why. 2) The final fileinput.close() seems to be useless; the program works without, and bug 1) isn't affected. -- Michele Alzetta From eric_brunel at despammed.com Mon Apr 19 11:30:58 2004 From: eric_brunel at despammed.com (Eric Brunel) Date: Mon, 19 Apr 2004 17:30:58 +0200 Subject: outline-style sorting algorithm References: <4083E8E7.8060503@mxm.dk> Message-ID: Max M wrote: > jwsacksteder at ramprecision.com wrote: > > I have a need to sort a list of elements that represent sections of a > > document in dot-separated notation. The built in sort does the wrong > thing. > > Not really. You are giving it a list of strings, and it sort those > alphabetically. That seems like the right thing to me ;-) > > > This seems a rather complex problem and I was hoping someone smarter > than me > > had already worked out the best way to approach this. For example, > consider > > the following list- > > >>>>foo > > > > ['1.0', '1.0.1', '1.1.1', '1.2', '1.9', '1.10', '1.11', '1.20', > '1.20.1', > > '1.30'] > > You need to convert them to another datatype first. Your best bet here > would be a list or a tuple, as they can map directly to your data. > > '1.0.1'.split('.') == [1,0,1] [snip] Nope: '1.0.1.split('.') == ['1', '0', '1'] So the int's are still represented as strings and it does not solve the OP's problem: >>> foo = ['1.0', '1.0.1', '1.1.1', '1.2', '1.9', '1.10', '1.11', '1.20', '1.20.1', '1.30'] >>> bar = [x.split('.') for x in foo] >>> bar [['1', '0'], ['1', '0', '1'], ['1', '1', '1'], ['1', '2'], ['1', '9'], ['1', '10'], ['1', '11'], ['1', '20'], ['1', '20', '1'], ['1', '30']] >>> bar.sort() >>> bar [['1', '0'], ['1', '0', '1'], ['1', '1', '1'], ['1', '10'], ['1', '11'], ['1', '2'], ['1', '20'], ['1', '20', '1'], ['1', '30'], ['1', '9']] And the 1.20.something are still before 1.9 What you need to do is explicitely convert to integers the strings in the list resulting from the split. Here is the shortest way to do it >>> bar = [map(int, x.split('.')) for x in foo] >>> bar [[1, 0], [1, 0, 1], [1, 1, 1], [1, 2], [1, 9], [1, 10], [1, 11], [1, 20], [1, 20, 1], [1, 30]] Now you can sort: >>> bar.sort() >>> bar [[1, 0], [1, 0, 1], [1, 1, 1], [1, 2], [1, 9], [1, 10], [1, 11], [1, 20], [1, 20, 1], [1, 30]] Hooray! We've got the result we wanted. Now, convert integers back to string and re-join everything: >>> foo = ['.'.join(map(str, x)) for x in bar] >>> foo ['1.0', '1.0.1', '1.1.1', '1.2', '1.9', '1.10', '1.11', '1.20', '1.20.1', '1.30'] That's what we expected... HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From mark at prothon.org Sat Apr 3 16:11:03 2004 From: mark at prothon.org (Mark Hahn) Date: Sat, 3 Apr 2004 13:11:03 -0800 Subject: "correct" tab/space rule? (prothon) Message-ID: Ville Vainio came up an idea for one final tweak of the tab/space indent algorithm we are using in Prothon, and the final result surprised me, in that it directly addresses the problem of mixed tabs and spaces. We have been having flame wars about tabs vs. spaces and I was thinking this was an opinion kind of thing and it never occured to me to look at it as a simple bug that needed fixing. Give me a second of your time to pitch it that way. When you mix tabs and spaces in Python and you change the tab width in your editor, the indents don't visually line up any more, even thought it compiles fine. This is the bug/problem. If you just don't allow tabs and spaces to be mixed in any one block, where you define a block to be a group of matching indented lines, then this problem cannot occur and the bug cannot occur. Our new Prothon rules fix this problem while allowing maximum flexibilty to use both tabs and spaces, and we've thrown in a new easier continuation method just for good measure. Prothon indentation rules: 1) You must use only tabs or only spaces for indents in any one indentation block. You cannot mix tabs and spaces in a block. A block is defined as a group of consecutive indented lines. Non-indented lines seperate blocks. 2) Each indent level can have any number of characters more than the previous level, whether you are using tabs or spaces. If you drop back to the left to dedent, and your column position does not match any level above, you will get a lexer error. 3) If you increase the indentation level above the previous line by even one character, and that previous line does not end in a colon, then the new line will be considered a continuation of the previous line. 4) If a line contains an active (not quoted or commented) (, {, or [ without a matching end character, then the following line is always a continuation, no matter what that following line contains. 5) There is still support for using the trailing backslash ( \ ) to indicate that the next line is a continuation. This may be removed in the future if everyone agrees to do so. 6) A continuation line is effectively added to the end of the previous line so any line following a continuation line uses the last non-continuation line for the "previous line" in all the rules above. From blacksqr at usa.net Fri Apr 16 11:31:03 2004 From: blacksqr at usa.net (Stephen Huntley) Date: 16 Apr 2004 08:31:03 -0700 Subject: Goodbye TCL References: <0LudnSads6NmpuPdRVn-vw@centurytel.net> <107u6ef5a2ise19@news.supernews.com> Message-ID: "John Roth" wrote in message news:<107u6ef5a2ise19 at news.supernews.com>... > "Stephen Huntley" wrote in message > news:f82c8ae7.0404151057.67333d4e at posting.google.com... > > Ed: > > > > I think your post is valuable. Instead of trying to invalidate your > > arguments, I will outline my reasons why I stick to Tcl. Then we can > > perhaps glimpse how strengths and weaknesses counterbalance. > > > > The main reasons I stick with Tcl are: > > What's amusing is that every one of your arguements in favor > of TCL are also arguements in favor of Python. This is, after > all, 2004, not 1994. Languages don't get widespread use > today unless either 1) some mega-mastodon is pushing them, > like Java or C#, or 2) they just work out of the box, and > solve real problems for the people using them. > > John Roth I'm certain that Python is a lovely language with many uses. You're right saying that since 1994 many new technologies have just worked out of the box. The gotcha I have encountered is the problems you run into a year or so down the line, when you want to move to a new platform, or use an exotic character encoding, or scale up by an order of magnitude. This is where Tcl has shined for me. I would be curious to know what is the biggest-capacity Python network application in use? How does it scale in comparison with AOLServer? Any ideas? From rdsteph at earthlink.net Mon Apr 12 13:32:41 2004 From: rdsteph at earthlink.net (Ron Stephens) Date: 12 Apr 2004 10:32:41 -0700 Subject: Python is the best and most popular general purpose scripting language; the universal scripting language References: Message-ID: <8e6e8e5d.0404120932.1c10d305@posting.google.com> Kirk Job-Sluder wrote in message news:...> A nice Bourne one-liner that does useful work, but which I really don't > feel is worth doing in python. The two hours I spent learning awk has > paid off whenever I need to pretty-print a character-delimited file. Kirk Job-Sluder wrote in message news:...> A nice Bourne one-liner that does useful work, but which I really don't > feel is worth doing in python. The two hours I spent learning awk has > paid off whenever I need to pretty-print a character-delimited file. I agree, shell scripts are great. But my main point is not whether or not to classify Python as a scripting language, or how to define a scripting language, nor do I mean the "universal solvent" phrase to mean Python is the only tool for all (or even most ) jobs. Rather, I mean that Python is perhaps the best tool for writing actual code, beyond the simplest shell scripts (although Python can be good for that too) and short of Windows-only GUI forms-based Microsoft Office add-ins to Access databases (although Python can be used to do that too.) In other words, one of Python's greatest strength's is enabling the efficient writing of actual code that is easy to read and maintain and to interface effectively with a very wide range of tools and environments. Like it or not, but for the foreseeable future, most people and organizations that want to create and deploy GUI software exclusively for Windows desktops and using exclusively Windows applications are going to use Visual Studio .Net. In the same way, most people who want to create and deploy truly cross platform GUI software may find Java to be there main tool. Sure, Python can be used to write and deploy the same kind of programs on Windows or across all major platforms. But the real strength of Python even in these cases in the writing of the actual code; that's where Python's simplicity, power, ease, readability, maintainability and efficiency really shines. The creation of the GUI's and the actual deployment can be down the tools like wxPython, PyGtk, PyQt, and there associated IDE's and tools, and the deployment can be done with py2exe, McMillan's installer, etc etc, or, by using the platform specific tools form Microsoft, Apple, and for the various Unices. But, it would be hard, I think to argue that the use of Python makes the creation of GUI's and the actual deployment (cross platform or Windows only) easier and more efficient than the other (currently more popular) alternatives to Pythonic tools. After all, for cross platform deployment, it's hard to beat Java .jar files; and for creation and deployment of Windows-only GUI frontends, its hard to beat Visual Studio. But for the actual writing of the code, that's were it can be argued that Python brings added programmer productivity, efficiencies and other advantages. See my point? Or is it as clear as mud now ;-))) Ron Stephens www.awaretek.com/weblog.html From greg at cosc.canterbury.ac.nz Thu Apr 29 00:41:00 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Thu, 29 Apr 2004 16:41:00 +1200 Subject: Why we will use obj$func() often In-Reply-To: <52Ujc.16275$Qy.3111@fed1read04> References: <84Uhc.22278$dZ1.5087@fed1read04> <8AWhc.23114$dZ1.11070@fed1read04> <40883BFE.B381518A@alcyone.com> <27_hc.23801$dZ1.2716@fed1read04> <40887145.789A2FE8@alcyone.com> <7cki80hj976bia36lhf9er97v073o1pqvm@4ax.com> <5vJjc.13116$Qy.1954@fed1read04> <52Ujc.16275$Qy.3111@fed1read04> Message-ID: Mark Hahn wrote: > It turns out that Greg and I were mistaken. The &var syntax can easily > handle unlimited nested scopes and not even slow up my one-pass compiler. It does incur the expense of a run-time lookup for intermediate-scoped variables, however. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From paul at prescod.net Sun Apr 25 13:36:26 2004 From: paul at prescod.net (Paul Prescod) Date: Sun, 25 Apr 2004 10:36:26 -0700 Subject: List operator overloading snag In-Reply-To: <8TCdnQn1OKieaRbdRWPC-w@speakeasy.net> References: <8TCdnQn1OKieaRbdRWPC-w@speakeasy.net> Message-ID: <408BF71A.9070500@prescod.net> Steven Brent wrote: >... > The problem is that I can't seem to get my wrapped lists to use the > overloaded versions of the operators without calling the customize > instance method directly, as shown below: > >>>>import setwrapper; from setwrapper import * > > >>>>S1 = Set(['s','p','a','m']) >>>>S2 = Set(['s','c','a','t']) > > >>>>print S1 or S2 Try this: >>> print S1 | S2 Paul Prescod From mark at prothon.org Tue Apr 20 02:10:22 2004 From: mark at prothon.org (Mark Hahn) Date: Mon, 19 Apr 2004 23:10:22 -0700 Subject: CamelCase versus wide_names (Prothon) References: <6ee58e07.0404192141.2229efd6@posting.google.com> Message-ID: "William Park" wrote ... Someone else already mentioned this > > problem: > > > > smtp_message <-> SMTPMessage <-> SmtpMessage If you consider the capital letter as just a replacement for the underbar, then the answer is definitely smtpMessage. I don't see any problem. From alf at calvin.fayauffre.org Thu Apr 15 04:01:33 2004 From: alf at calvin.fayauffre.org (Alexandre Fayolle) Date: Thu, 15 Apr 2004 08:01:33 +0000 (UTC) Subject: Aspect Programming Module References: <84fc4588.0404140106.3fa0c55@posting.google.com> Message-ID: Will Stuyvesant feels like trolling: >> [Alexandre Fayolle, being a good employee] +1 point for ad hominem attack. >> You may want to try the logilab.aspects package, available at >> http://www.logilab.org/projects/aspects/ > > I am afraid you are serious. I am. Deadly serious. I even took part in the implementation of the module. And I'll tell you a secret. Even though logilab.aspect was more a proof of concept implementation, we actually use it, especially the logging and contract aspects, in production code. > AOP is *not needed* for Python programmers. Plain and simple. Oh. And we're all supposed to take your word for it then. Such useless comments are not needed by the Python community. Plain and simple. > Don't understand? Try this: +1 point for implying I'm an idiot. > "AOP is a contrived way to get around the limitations of a statically > typed language." Do you have anything to offer besides blunt dogmatic assertions? Could you please quote your sources, or provide some supportive arguments. The goal of AOP is "separating crosscutting concerns". This has nothing to do with static/dynamic typing. It is a design problem. I think you should read a bit on the topic before making a fool of yourself. Here are a few links, for your education: The original idea: http://www.parc.xerox.com/csl/groups/sda/publications/papers/Kiczales-ECOOP97/for-web.pdf Aspect home page: http://www.aosd.net aspects links: http://www.volantec.biz/aspect.htm AspectJ tutorial: http://www.eclipse.org/aspectj/ Crtitical analysis: http://citeseer.nj.nec.com/highley99aspect.html Other projects provide AOP facilities for Python: Pythius: http://pythius.sourceforge.net/ PEAK: http://peak.telecommunity.com/Articles/WhatisPEAK.html > Put that on the logilab website. And hire somebody to repair the > broken English over there, it looks really, um...oh well I am not a > native English speaker myself either. Thank you for this very constructive remark. I hate to admit it, but this is probably the most sensible thing you wrote in your post, though the Netiquette explicitely frowns on such remarks. -- Alexandre Fayolle LOGILAB, Paris (France) http://www.logilab.com http://www.logilab.fr http://www.logilab.org From shalabh at cafepy.com Thu Apr 15 20:25:00 2004 From: shalabh at cafepy.com (Shalabh Chaturvedi) Date: Thu, 15 Apr 2004 17:25:00 -0700 Subject: tutorials In-Reply-To: References: Message-ID: Deefex wrote: > hey what's up, i've been looking for online tutorials to learn python on > windows but i can't find anything. does anyone know a good site with > good beginner's python information? thank you very much. The Python site will tell you how to go about it: http://www.python.org/topics/learn/ > -- > Deefex -- Shalabh From jacek.generowicz at cern.ch Wed Apr 7 07:16:14 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 07 Apr 2004 13:16:14 +0200 Subject: OFF-TOPIC:: Why Lisp is not my favorite programming language References: <165b3efa.0403030443.4d591f04@posting.google.com> <40460dd5$0$5916$7a628cd7@news.club-internet.fr> Message-ID: nish20 at netzero.net (Mike Nishizawa) writes: > If it beats LISP at it's own game which is, list processing, > an especially good application for a LISt Processing language. [lots more uninformed garbage elided] Please get a clue about what Lisp is in the 21st century (hell, even what it was in the last 2 decades of the 20th century), before posting any more of your drivel. For example, you could look at http://franz.com/success/ for a little insight into what is being done (mereyly by processing lists and parsing files, according to your view of the world) in Lisp today. From eppstein at ics.uci.edu Thu Apr 8 03:20:20 2004 From: eppstein at ics.uci.edu (David Eppstein) Date: Thu, 08 Apr 2004 00:20:20 -0700 Subject: print u"\u0432": why is this so hard? UnciodeEncodeError References: Message-ID: In article , "Martin v. Lowis" wrote: > > That seems to work reasonably well in Python 2.3 (but not 2.2!). But > > then for some obscure reason if I redirect stdout in my shell it fails. > > $ LANG=en_US.UTF-8 python2.3 -c 'print u"\u0432"' > /dev/null > > > > Why is that? > > Python 2.3 discovers the encoding of your terminal, and will display > Unicode characters if the terminal supports them. Python 2.2 did not do > that, and the new feature is mainly useful in interactive mode. Py2.3 sure doesn't discover the encoding of my terminal automatically: hyperbolic ~: python Python 2.3 (#1, Sep 13 2003, 00:49:11) [GCC 3.3 20030304 (Apple Computer, Inc. build 1495)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> print u"\u0432".encode('utf8') 2 >>> print u"\u0432" Traceback (most recent call last): File "", line 1, in ? UnicodeEncodeError: 'ascii' codec can't encode character '\u432' in position 0: ordinal not in range(128) (that 2 was something else looking like an angular capital B before I copied and pasted it into my newsreader...and yes, utf8 is the correct encoding.) -- David Eppstein http://www.ics.uci.edu/~eppstein/ Univ. of California, Irvine, School of Information & Computer Science From daniel.dittmar at sap.com Fri Apr 16 11:22:08 2004 From: daniel.dittmar at sap.com (Daniel Dittmar) Date: Fri, 16 Apr 2004 17:22:08 +0200 Subject: AOP use cases References: <84fc4588.0404140106.3fa0c55@posting.google.com> <0pydnSB4WYuieuLdRVn-hQ@powergate.ca> Message-ID: Peter Hansen wrote: > From direct personal experience, could some AOP folks please > point out some compelling use cases so that the doubting > Thomases (and Wills, and Peters) can better understand and > accept the idea of AOP as being more than just a few fringe > cases? Not from personal experience, but these have been mentioned: - multithreading: create class A' like class A, but with specific methods synchronized - persistence - transactions: pass a transaction context through a call hierarchy spanning several objects and let the transaction fail if certain methods fail It may very well be that these can be implemented in current Python, but this only means that Python already has good support for AOP. Daniel From vald at dead.art.pl Wed Apr 21 14:56:25 2004 From: vald at dead.art.pl (KN) Date: Wed, 21 Apr 2004 20:56:25 +0200 Subject: inheritance and private attributes Message-ID: <20040421185625.GA26996@hell.art.pl> I've run into such problem: I have something like this: class A(object): def __init__(self): self.__value = None class B(A): def test(self): if self.__value: print "Ok." else: print "Empty." >>> b = B() >>> b.test() Traceback (most recent call last): File "", line 1, in ? File "", line 3, in test AttributeError: 'B' object has no attribute '_B__value' Why I have no access to private attribute from a class that inherits other class? I just want to have access to the same private variables but also to extend its functionality by adding a method that operates on those private attributes and I'm unable to do so. Is this normal behaviour? What should I do if I want to override method and use private attribute, or just add some other method which changes this attribute? /K From hemanth_sethuram at yahoo.com Fri Apr 16 04:49:43 2004 From: hemanth_sethuram at yahoo.com (Hemanth P.S.) Date: 16 Apr 2004 01:49:43 -0700 Subject: Best IDE? References: Message-ID: <9be5e130.0404160049.257ce8e1@posting.google.com> If you are looking for an IDE only for Python development, take a look at SPE.(http://spe.pycs.net). It looks quite cool with PyCrust integrated. Here is the blurb from the site: """ Spe is a python IDE with wxGlade GUI designer, auto-indentation, auto completion, call tips, syntax coloring, syntax highlighting, class explorer, source index, auto todo list, sticky notes, integrated pycrust shell, python file browser, recent file browser, drag&drop, context help, ... Special is its blender support with a blender 3d object browser and its ability to run interactively inside blender. Spe is extensible with boa. """ --Hemanth Josiah Carlson wrote in message news:... > > This has prolly been asked 100 times - so please refrain from flaming if you can... > > > > What's the best MSwindows editor for python? I'm currently using PythonWin (ActiveState) at the moment, its a bit > > buggy - but not too bad. I mean, its got autocomplete & tips & help & autoindentaion (not always good tho). > > > > Thing is, I'm sure there is something better. Is there? > > Many people stick with the standard Python-included Idle. > > Others use their favored *nix editor on Windows (usually Emacs or VI(M)) > > Some have found they love SciTE. > > If you could get Eric3 running on Windows, it'd probably be /very/ nice. > > The editor component of Boa Constructor is pretty good (haven't used it > in a while), but is a bit sluggish. > > SPE (Stani's Python Editor) is also pretty good, though can be slow at > times, and uses MDI, which people usually love or hate. > > I use PyPE, find it to be a satisfactory replacement for Idle, and is > quite fast. I wrote it, which is why I place it at the bottom. > > > There are many other general text editors with some sort of Python > support, but I don't use any of them, so I'll not talk about them. > > - Josiah From imbosol at aerojockey.com Thu Apr 8 15:10:35 2004 From: imbosol at aerojockey.com (Carl Banks) Date: 8 Apr 2004 12:10:35 -0700 Subject: getattr() in default namespace. References: Message-ID: <60dfb6f6.0404081110.5218466b@posting.google.com> python at simon.vc (SimonVC) wrote in message news:... > Hi group, long time reader first time poster (ive always wanted to say > that). > > How do you use getattr() to get a refernce to a function defined in > the default namespace.. It's not really possible to do this in general. I know of no way, for example, to access the current namespace with getattr inside a class definition. However, I'm assuming you're taking about a module's namespace (i.e., a so-called global namespace) and not a class or function namespace. You can do this very easily with "namespace = __import__(__name__)". It even works at top level. Python 2.3.2 (#2, Dec 17 2003, 13:21:01) [C] on hp-ux11 Type "help", "copyright", "credits" or "license" for more information. >>> a = 1 >>> namespace = __import__(__name__) >>> getattr(namespace,'a') 1 -- CARL BANKS From anand at easi.soft.net Thu Apr 22 04:56:48 2004 From: anand at easi.soft.net (Anand K Rayudu) Date: Thu, 22 Apr 2004 14:26:48 +0530 Subject: COM & Python References: Message-ID: <408788D0.3090002@easi.soft.net> Dear David, Thanks a lot for the link, Actually that is same from the book. I am trying to provide a "Rapid Application Development Environment" for the application I am developing through python. The reason I Want to stick on to pythonwin is , it comes as a default with python extension for windows. Also that my application is based on MFC, it looks like pythonwin is a natural fit for me. I can get same look & feel as the other dialog boxes. My developers have good experience on MFC. I will try out wxPython also & see. For me it looks like pythonwin is a preferred option. Thanks again, Anand David Fraser wrote: > What about > http://www.onlamp.com/pub/a/python/excerpts/chpt20/pythonwin.html > (from that book)? > Or have you tried wxPython (not COM but great)? > > David > > Anand K Rayudu wrote: > >> Hi Larry, >> >> Thanks for the suggestion, I have gone through the book, but >> unfortunately nothing much is discussed about this topic. >> Being new to MFC i am finding it difficult to get started. >> I want to just create a dialog box, with my own controls and get the >> python call backs for them. >> can some one please share some example source code or any experience >> regarding this. >> Any help will be a great start point for me. >> >> Regards, >> Anand >> >> >> Larry Bates wrote: >> >>> Get a copy of >>> Python Programming on Win32 By Mark Hammond, Andy Robinson >>> >>> This is the best starting point for you. >>> >>> Larry Bates >>> Syscon, Inc. >>> >>> "Anand K Rayudu" wrote in message >>> news:mailman.752.1082375155.20120.python-list at python.org... >>> >>> >>>> Hi all, >>>> >>>> I want to use python with COM extension. I am successful using >>>> python as >>>> client. >>>> I could interact to my application through COM interfaces from python. >>>> >>>> I also want to use the win32ui layer, which wrapped all MFC user >>>> interface functionality. >>>> I am just wondering if some on can guide me with some documentation on >>>> using them. >>>> I want to know how the call backs are handled in particular. >>>> Any sample code will be a great start for me. >>>> If this is possible I can create any dialog boxes with any controls >>>> from >>>> python itself!! :-) >>>> And take advantage of MFC's View , scroll view and so on. Just >>>> exciting!! >>>> >>>> Thanks in advance, >>>> Anand >>>> >>>> >>>> >>>> >>>> >>> >>> >>> >>> >>> >> From wilkSPAM at OUTflibuste.net Mon Apr 19 03:43:50 2004 From: wilkSPAM at OUTflibuste.net (Wilk) Date: Mon, 19 Apr 2004 09:43:50 +0200 Subject: Pygame References: Message-ID: <87wu4c76q1.fsf@blakie.riol> Alexander R?dseth writes: > Thanks for the link and the thought. > Enthought is probably an interesting project. > > However, I just want to know why fullscreen graphics > is not included in Python by default. For example if you whant python on a server you don't need any graphical tools. And so you don't whant a lot of dependency (libsdl...) Also when a module go in the core of python it will have to follow the release of python. And so will be freezed for long time. -- Wilk - http://flibuste.net From __peter__ at web.de Thu Apr 1 02:08:52 2004 From: __peter__ at web.de (Peter Otten) Date: Thu, 01 Apr 2004 09:08:52 +0200 Subject: Using bound variables in Tkinter events References: <4067a227$0$16577$5a62ac22@freenews.iinet.net.au> <406b7c51$0$16594$5a62ac22@freenews.iinet.net.au> Message-ID: Derek Fountain wrote: >> import Tkinter as tk >> root = tk.Tk() >> >> def check(action): >> print {"1":"inserting", "0": "deleting"}.get(action, "should never >> happen") >> return True >> checkId = root.register(check) >> >> entry = tk.Entry(root, validate="key", validatecommand=checkId + " %d") >> entry.pack() >> root.mainloop() >> >> The above was found by trial and error, so no warranties :-) > > Awesome, thank you. I don't understand what's going on though. Can you > explain a bit? I don't understand the mechanism which is expanding the %d. > Is there some magic in the tk.Entry constructor which does it, or is that > root.register() doing something clever? register() wraps a python function into a tcl function and returns the new tcl function's name (can they start with a number?). If you provide a string instead of a python function reference as a callback for (e. g.) validatecommand, it is passed unaltered to tcl. That's all there is to it - at least so my theory goes. Peter From oren-py-l at hishome.net Fri Apr 23 04:02:21 2004 From: oren-py-l at hishome.net (Oren Tirosh) Date: Fri, 23 Apr 2004 04:02:21 -0400 Subject: Proper Way of checking for a collections class In-Reply-To: References: Message-ID: <20040423080221.GA89638@hishome.net> On Thu, Apr 22, 2004 at 01:23:00PM -0400, Gary Coulbourne wrote: > Howdy, > > I've been trying to find a good idiom for testing if the input to a > function is one of the collections classes... the best I could do is this: > > if hasattr(thing_to_test, '__iter__'): > ... > > Is this right? Or, is there a better way besides a cascade of type() > tests? Search for "look before you leap" (LBYL) in this newsgroup and you will find lots of discussions about the issue. The recommended style is not to LBYL - just try to do whatever you want to do with an object and catch any resulting exceptions. Oren From aahz at pythoncraft.com Tue Apr 20 21:17:22 2004 From: aahz at pythoncraft.com (Aahz) Date: 20 Apr 2004 21:17:22 -0400 Subject: File access and threads References: <4084b3eb@newsflash.abo.fi> Message-ID: In article <4084b3eb at newsflash.abo.fi>, =?ISO-8859-1?Q?Petter_Holmstr=F6m?= wrote: > >I have a problem with file access which I believe is caused by a >thread-problem. I first noticed it while trying to get PSP/Mod_Python to >work in the shape of an exception claiming that there are no usable >temporary directories. > >The second time I noticed it was when I was trying to dump an object to >a file using pickle, and I got the "Bad file descriptor" error all the >time, even though the file was created in the file system. Could you at least post a full traceback? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I used to have a .sig but I found it impossible to please everyone..." --SFJ From daniel.dittmar at sap.com Mon Apr 19 11:21:13 2004 From: daniel.dittmar at sap.com (Daniel Dittmar) Date: Mon, 19 Apr 2004 17:21:13 +0200 Subject: AOP use cases References: <84fc4588.0404140106.3fa0c55@posting.google.com> <0pydnSB4WYuieuLdRVn-hQ@powergate.ca> <1082n594lndh27f@news.supernews.com> <87pta6qnw4.fsf@pobox.com> <1083nja30c9s2a4@news.supernews.com> <1087i9rgum1g2cb@news.supernews.com> Message-ID: John Roth wrote: > "Daniel Dittmar" wrote in message >> AOP grew out of the observation that an evergrowing percentage of the >> code of the average method is taken over by parts that are not >> related to the main purpose of the method, but by logging, >> sychronization, transaction handling and other stuff. > > Bad design is bad design. Having methods with more > than one responsibility is poor cohesion and high coupling. > Spending a bit of time thinking about how to encapsulate > this type of crud will pay big dividends. Unfortunately, it > won't get academic publication credits. So if you want a feature (= public method) that supports logging + synchronization + transaction handling + 'the main feature', you'll write four methods, each one doing it's own and then calling the next layer. This is certainly doable, but if you do this to several methods in several classes, you'll be probably asking yourself if there isn't a better way. AOP tries to be such a way. > Duplicated code is duplicated code, and should be ruthlessly > eliminated wherever found. It doesn't matter whether it's > generated by some tool or inserted by the developer. It depends on your programming language if every kind of duplication can be factored out. Assume that you want a variant of a class where several methods are synchronized. The code for the methods in the new class will always look like lock.acquire () call_original_method (args) lock.release () I do not see how the duplication in the structure can be factored out in languages like Java or C++. In Python, I could do the following class SynchronizedCall: def __init__ (self, lock, method): self.lock = lock self.method = method def __call__ (self, *args, **keywargs): self.lock.acquire () try: self.method (*args, *keywargs) finally: self.lock.release () obj.append = SynchronizedCall (obj.lock, obj.append) # the following calls to obj.append () will be synchronized >> And the 'we do this through refactoring' argument ends where you use >> external libraries unless you want to fork them. > > Now you're contradicting yourself. First you say that it's not > about patching to get around stupid libraries, now you say it > is about patching to get around stupid libraries. It's not *only* about patching existing libraries, it's a different way to structure the code. In addition, it has the potential advantage that you can adapt existing libraries without having to change them. Daniel From michalw at trylogia.pl Fri Apr 16 04:31:39 2004 From: michalw at trylogia.pl (Jacek Cz) Date: Fri, 16 Apr 2004 10:31:39 +0200 Subject: Embeded python without filesystem Message-ID: Do you have some tips about making Python small (minimal list of modules) and isolated from filesystem. I have an idea #define Py_WITHOUT_FILES This switch should disable some function/modules from modules sys, fileobject, but also import from file, path resolving etd. From pit.grinja at gmx.de Tue Apr 20 02:59:26 2004 From: pit.grinja at gmx.de (Piet) Date: 19 Apr 2004 23:59:26 -0700 Subject: Book "Programming on Win32" still useful? Message-ID: <39cbe663.0404192259.3e105972@posting.google.com> Hi all, I started programming (or hacking) python some time ago. Since python offers a lot of Win32 specific extensions and since my OS will probably stay Win2k for the next time, I would like to know the possibilities of Win32 programming with python a little better. In this context I stumbled over the book mentioned in the title, which really looks like what I?ve been looking for, but I am a little afraid because it was published 4 years ago and covers only python 1.52. Both Python and the Win32 interface have been continuously developped, and I don?t know whether the things I can learn from this book are still useful today. Can somebody give me some advice whether this book is still a good buy? I think it will surely be enough to get the basics, but what if I want more? Best regards Peter From wweston at att.net Wed Apr 7 11:42:30 2004 From: wweston at att.net (wes weston) Date: Wed, 07 Apr 2004 15:42:30 GMT Subject: String comparison problem In-Reply-To: References: Message-ID: Senthoorkumaran Punniamoorthy wrote: > I am printing these information. > > print string.lower(info_res[2]) > print string.lower(md5sum(f_md5)) > print len(string.lower(info_res[2])) > print len(string.lower(md5sum(f_md5))) > print str(string.lower(md5sum(f_md5)) == string.lower(info_res[2])) > > and the output are > > 01b7ebfc27437a90cc421c50df8f9ac5 > 01b7ebfc27437a90cc421c50df8f9ac5 > 32 > 32 > False > > I was wondering why the last print statement is returning false when two > strings are identical? > > Senthoor > > _________________________________________________________________ > Tired of spam? Get advanced junk mail protection with MSN 8. > http://join.msn.com/?page=features/junkmail > import urllib2 > import sre > import string > import sys > import md5 > import socket > import logging > import getopt > import os > from property import property > > md5_bufsize=8096 > bufsize=8096 > ''' > Change History > -------------- > 1.01g: > i. file close from file_writer() removed so that caller can close the file > ii. exception handling introduced for mail sending to handle missing > SMTP config > iii.file_Dled() method is replaced > iv. The program doesn't exit if it can't find the logfile anymore. It > just downloads again. > v. small bug fixes > vi. grab_info was made little less complicated by removing the > compilation of regex > > 1.01h: > i. If the MD5 check sum doesn't match, trying n number of times > ''' > version="1.01h" > > # MD5 checksum program taken from python_home/tools/scripts/md5sum.py > # That was a stand alone script with many options > # Just took the function which did the checksumming, and reduced it. > > def md5sum(fp): > m = md5.new() > try: > while 1: > data = fp.read(md5_bufsize) > if not data: > break > m.update(data) > except IOError, msg: > log.error('I/O error: '+ str(msg)) > log.error('System Abort') > sys.exit(1) > > return m.hexdigest() > > '''Reads the file from fp_in and writes it to fp_out. fp_in normally is > the file being > downloaded and fp_out is the file being written to the local disk''' > def file_writer(fp_in, fp_out): > try: > log.info('File Downloading in Progress.',) > while 1: > data = fp_in.read(bufsize) > if not data: > break > fp_out.write(data) > fp_out.flush() > #fp_out.write('senthoor') > #fp_out.flush() > except IOError, msg: > log.error('Error resolving address: '+ str(msg)) > log.error('System Abort') > sys.exit(1) > except socket.error, msg: > log.error('Soket error: '+ str(msg)) > log.error('System Abort') > sys.exit(1) > > def send_mail(mailserver,from_addr, to_addr, file_name): > msg = 'Greetings all, \n The lastest virus definition file' + > file_name + ' has been down loaded' > server = smtplib.SMTP(mailserver) > server.set_debuglevel(1) > server.sendmail(from_addr, to_addr, msg) > server.quit() > > '''Takes a list of regular expressions and a Source(String) and searchs > source for > match and returns a list with all the matches''' > def grab_info(listRegEx,source): > #this needs improvement. The compilation is unnecessary and will be > removed > return map(lambda x:x.group(1),map(lambda x: sre.search(x, > source),listRegEx)) > > def show_usage(): > print 'under construnction' > > '''Processes the command line argument''' > def process_args(a): > try: > args = getopt.getopt(a[1:],'dv') > for x in args[0]: > if x[0] == '-d': > log.setLevel(logging.DEBUG) > if x[0] == '-v': > print 'theRetriever '+ version +', MotleyPythons' > sys.exit(0) > except getopt.GetoptError,msg: > show_usage() > sys.exit(1) > > '''Checks the log file whether the file name exsits. If the file name > exsits then no need to download the file since its been already > downloaded''' > def file_Dled(file,fileName): > if os.path.exists(file): > return sre.search(fileName,open(file).read()) > > '''When the file is downloaded and written to the local disk the > log file updated with the file name''' > def file_DlOK(file,fileName): > exc = 0 > try: > fp = open(file,'a') > fp.write(fileName + '\n') > fp.close > except IOError,msg: > log.error('I/O error: '+ str(msg)) > log.error('System Abort') > sys.exit(1) > > #Logging Initialised > logging.basicConfig() > log = logging.getLogger('Retriever') > log.setLevel(logging.INFO) > process_args(sys.argv) > > > # Get information from config file > config = property('config.cfg') > log.debug('Config Loaded') > dllog=config.get_safe('LOCATION','')+'dledfile.lst' > no_of_trys = 0 > > #this is being introduced so that file be downloaded if the it was > #not download failed and we are going to have a time testing this:-) > md5_error=1 #at the begining no file so md5_error is true:-) > log.debug('Retries :' + str(config.get_safe('RETRIES',0))) > while md5_error and (no_of_trys<=int(config.get_safe('RETRIES',0))): > no_of_trys +=1 > > #until its proven md5 mismatch exit we assume it doesn't > #this helps us only to repeat downloaing in the case of mismatch > #and if the downloading stops for other reasons > md5_error = 0 > try: > f1 = urllib2.urlopen(config.get('URL')) > log.debug(config.get('URL') + 'has been read') > except urllib2.URLError, msg: > log.error('Error Reading ' + config.get('URL') + '\n' + str(msg)) > log.error('System Abort') > sys.exit(1) > htmlsource = f1.read() > f1.close() > > info_regex = > ['href="(.*2\d{7}-\d{3}-i32.exe)"','href=".*(2\d{7}-\d{3}-i32.exe)"','MD5:\s(.*)\s > info_res = grab_info(info_regex,htmlsource) > log.debug('retrieved info \n' + str(info_res)) > # Exit if file already loaded > if file_Dled(dllog,info_res[1]): > log.info('File already downloaded. Process Stopping',) > sys.exit(0) > > #reading and writing to a local file > virusdeflocal=open(config.get_safe('LOCATION','')+info_res[1],'wb') > authinfo = urllib2.Request(config.get('URL')) > virusdefserver = > urllib2.urlopen('http://'+authinfo.get_host()+info_res[0]) > file_writer(virusdefserver,virusdeflocal) > virusdeflocal.close() > virusdefserver.close() > > f_md5=open(config.get_safe('LOCATION','')+info_res[1],'rb') > if string.lower(md5sum(f_md5)) == string.lower(info_res[2]): > log.debug("Yipee !!!, it works!!") > # Have to copy the file to the common share > # Must have location in config file > > # Put entry in logfile > file_DlOK(dllog,info_res[1]) > try: > > send_mail(config.get('SMTP'),config.get('FROM_ADDR'),config.get('TO_ADDR'),filename) > > except KeyError, msg: > log.error('Mail not sent: ' + str(msg)) > > else: > log.debug("Bummer") > md5_error=1 Senthoorkumaran Punniamoorthy, >>> s1='01b7ebfc27437a90cc421c50df8f9ac5' >>> s2=s1 >>> import string >>> print str(string.lower(s1))==string.lower(s2) True ????????????????????????/ wes From user_77 at hotmail.com Mon Apr 19 12:05:47 2004 From: user_77 at hotmail.com (Nobody) Date: Mon, 19 Apr 2004 16:05:47 GMT Subject: Threats to the: Daily Python URL! References: <2ae25c6b.0404182250.4c5bc870@posting.google.com> Message-ID: "Paddy McCarthy" wrote in message news:2ae25c6b.0404182250.4c5bc870 at posting.google.com... > I sent the following this morning: > > > > -------- Original Message -------- > Subject: Threats to the: Daily Python URL! > Date: Mon, 19 Apr 2004 07:50:04 +0100 > From: Donald 'Paddy' McCarthy > To: daily at pythonware.com > > > Hi, > I read your 'Administrative note' at http://www.pythonware.com/daily/ today > > Please don't stop the excellent work that you do. > I don't know what threats and insults you suffered but I would like to > ensure you that I for one read the column and value it. > > Thanks, Paddy. > The people who would do that (threats and insults) should have their jobs offshored. From dkuhlman at rexx.com Fri Apr 23 12:13:00 2004 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Fri, 23 Apr 2004 09:13:00 -0700 Subject: Setting variable values from dictionary References: Message-ID: Sean Berry wrote: > If I have a dictionary like the following: > > {'category' : 2, 'shape', 4} > > How can I use this to make > category = 2 and > shape = 4. > > I want to be able to do this regardless of the dict values type. > So: > > {'cateogry' : 2, 'shape' : 'circle'} > > will work as well. locals().update(mydict) Oops. I just actually read the docs: locals( ) Update and return a dictionary representing the current local symbol table. *Warning*: The contents of this dictionary should not be modified; changes may not affect the values of local variables used by the interpreter. [Emphasis added.] So, perhaps, the following is to be preferred: for name, value in mydict.items(): exec('%s = %s' % (name, value)) But, what do you want to do about name clashes? Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From james at ractive.ch Wed Apr 14 17:56:54 2004 From: james at ractive.ch (Jean-Pierre Bergamin) Date: Wed, 14 Apr 2004 23:56:54 +0200 Subject: Socket error: 10053 software caused connection abort Message-ID: Hello there I'm getting an error on Windows XP when I send big data chunks over a socket connection. The exception I get is: "socket.error: (10053, 'Software caused connection abort')" This happens in the socket.recv function. What I found out is that such errors can occur if there's not enough buffer for receiving data in the underlying hardware. On Linux it works fine. I guess, that the socket-code on windows could be buggy and tries to read from a buffer whithout checking the length. The server.py script does not alway receive all the data that was sent by the client. I'd be glad if someone could test theses scripts to see if this error also occurs on other coputers and systems. Or is there anything wrong with the code? Regards James ====================================================== server.py ====================================================== import SocketServer class MyHandler(SocketServer.StreamRequestHandler): def get_all(self): # Get data as long as there's something on the line data = '' block_size = 1024 while(1): chunk = self.connection.recv(block_size) if not chunk: break data += chunk if (len(chunk) < block_size): # We got all the data break return data def handle(self): data = self.get_all() data_len = len(data) if (data_len == 0): return print "Received: %d" % data_len total_sent = 0 while(total_sent < data_len): sent = self.connection.send(data) if not sent: break data = data[sent:] total_sent += sent try: s = SocketServer.TCPServer(('', 12345), MyHandler) s.serve_forever() except Error, msg: print msg ====================================================== client.py ====================================================== import sys import socket from time import sleep port = 12345 host = 'localhost' loops = 100 data_len = 12000 send_data = 'x' * data_len to_send = len(send_data) for _ in range(loops): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(("localhost", port)) total_sent = 0 while(total_sent < to_send): sent = s.send(send_data) if not sent: break; print "Sent: %d" % sent total_sent += sent print "Total-sent: %d" % total_sent # Get data as long as there's something on the line data = '' block_size = 1024 while(1): got = s.recv(block_size) if not got: print "Connection broken" break data += got if (len(got) < block_size): # We got all the data break data_len = len(data) s.close() print 'Received bytes: %d' % len(data) From toby at rcsreg.com Thu Apr 15 19:47:41 2004 From: toby at rcsreg.com (Tobiah) Date: Thu, 15 Apr 2004 23:47:41 GMT Subject: Newbie question: matching In-Reply-To: References: Message-ID: This should really be done with the XML parsing libraries. I don't remember the libs now, but I watched a co-worker translate HTML into XML, and then use minidom, or sax or some other lib to parse the XML. It is very convenient once you see how to do it. You either trigger an event for each tag/text, or get handed an entire object tree representing your HTML, which you can traverse and examine at a much higher level than you can trying to match tags with regular expressions. Toby josh R wrote: > Hi all, > > I am trying to write some python to parse html code. I find it easier > to do in perl, but would like to learn some basic python. My code > looks like this: > > line = "eat at joe'sor elseyou'll starve" > so = re.compile("(\.*?\<\\tr\>)") > foo=so.match(line) > print foo.groups() > > I'd like to get an array of elements that looks like this: > > array(0)= eat at joe's > array(1)= or else > array(2)= you'll starve > > Could you please tell me the correct way to do the matching? > > also, is there something similiar to perl's s/foo/bar/g? > > Thanks!!! > Josh From ncw at axis.demon.co.uk Fri Apr 2 05:30:05 2004 From: ncw at axis.demon.co.uk (Nick Craig-Wood) Date: 02 Apr 2004 10:30:05 GMT Subject: Travelling salesman variation in python References: Message-ID: Erlend Andreas Garberg wrote: > My problem is that when the number of nodes is higher than 8, the > algorithm slows to a crawl (because of O(n!) complexity). I wonder if > there is some way I can optimize my algorithm to make it run faster? > Currently it takes 20 seconds to compute the best combination with 9 > nodes on my hardware. I had to solve exactly this problem when I was at University (many moons ago now ;-) I used Simulated Annealing - have a search for the term and you'll see plenty of references. Its good at finding a (local) minimum. Just be glad you don't have to write it in Fortran like I did! -- Nick Craig-Wood ncw at axis.demon.co.uk From chad at sabinasp.com Fri Apr 23 23:31:21 2004 From: chad at sabinasp.com (Chad Thompson) Date: Sat, 24 Apr 2004 03:31:21 GMT Subject: site.py Message-ID: I have a patch / feature enhancement for python that affects site.py. Is there a moderator for this file? >From what I have read, my code doesnt seem to fit into a PEP, its not a bug fix either. This is why I wanted to see if a moderator could answer some questions. Ideas? Thanks Chad From jbperez808 at yahoo.com Tue Apr 6 23:56:18 2004 From: jbperez808 at yahoo.com (Jon Perez) Date: Wed, 07 Apr 2004 11:56:18 +0800 Subject: Type checking inside a C extension... doesn't throw exception on failure In-Reply-To: References: <40712D9E.3050802@prescod.net> <407229F6.6080809@yahoo.com> Message-ID: Jon Perez wrote: > Andrew MacIntyre wrote: > >> First rule of using the Python C API: _always_ check the return value of >> API functions. > > This only applies to API functions which return PyObject*, right? ...because it is not hard to find instances in the source code for the modules that come with Python where, for example, PyTuple_SetItem()'s return value is not checked for. From seibold at bartsch.de Fri Apr 23 01:06:08 2004 From: seibold at bartsch.de (seibold at bartsch.de) Date: Fri, 23 Apr 2004 07:06:08 +0200 (CEST) Subject: Ich bin im Urlaub Message-ID: <20040423050608.C635517F4EE@mars.bartsch.de> Ich bin vom 16. April, 2004 (15 Uhr) bis zum 2. Mai, 2004 (23 Uhr) nicht da. Ihre E-Mail-Betreffs "Re: Re: Thanks!" werde ich beantworten, sobald ich wieder da bin. From paul at prescod.net Sat Apr 3 19:19:20 2004 From: paul at prescod.net (Paul Prescod) Date: Sat, 03 Apr 2004 16:19:20 -0800 Subject: Parrot for Python In-Reply-To: <106theugbjm8l30@news.supernews.com> References: <930ba99a.0404030251.c2d2107@posting.google.com> <106theugbjm8l30@news.supernews.com> Message-ID: <406F5488.5020801@prescod.net> John Roth wrote: >... > > I believe there were some people working on a Python > port to Parrot a while ago, but they lost interest when > the then current Parrot implementation was insufficient > to handle what they wanted to do. > > It's all a volunteer effort; it'll get done if enough > people want to get together to get it done. The developers of Parrot are implementing Python on Parrot themselves. http://www.hole.fi/jajvirta/weblog/20040108T2001.html As of a month ago: "Just in case anyone's keeping track, here are a few things that are working: ? Bytecode loading ? Objects ? Method calls ? Operator Overloading oh, yeah, and all that pesky math stuff, subroutines, and strings. They work too, though Unicode needs some help. And variables. We can do variables. Still need some work on nested namespaces, actual bytecode translation, and object performance, but..." From beliavsky at aol.com Wed Apr 28 11:28:48 2004 From: beliavsky at aol.com (beliavsky at aol.com) Date: 28 Apr 2004 08:28:48 -0700 Subject: PyChecker does STATIC analysis? Message-ID: <3064b51d.0404280728.5fb7539e@posting.google.com> If I run PyChecker on the following program, stored in xtry.py, m = 10000000 k = 0 for i in xrange(m): k = k + i print k x = range(3) print x[3] the output is 49999995000000 Warnings... xtry:1: NOT PROCESSED UNABLE TO IMPORT Processing xtry... Caught exception importing module xtry: File "H:\Energy\rao\python\Lib\site-packages\pychecker\checker.py", line 530, in setupMainCode() module = imp.load_module(self.moduleName, file, filename, smt) File "xtry.py", line 7 print x[3] IndexError: list index out of range I am surprised that PyChecker actually needs to execute the code block for i in xrange(m): k = k + i print k before finding the out-of-bounds error. I have seen PyChecker described as a "static analysis" tool, and it does find some problems that such a tool ought to. But it seems that for the simple program I have shown, it basically runs the program, and I could just run the Python program to find the same errors. An aspect of Python programming that sometimes frustrates me is that a program will run, perhaps for a few minutes, before stopping because of a misspelled variable or an out-of-bounds variable. It seems that currently, PyChecker will not solve this problem. I wish there were a tool that did (and would be willing to pay for it). The Lahey/Fujitsu Fortran 95 compiler is able to catch the out-of-bounds error at COMPILE time for an analogous Fortran program. From martin at v.loewis.de Fri Apr 16 15:52:16 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 16 Apr 2004 21:52:16 +0200 Subject: Embeded python without filesystem In-Reply-To: References: Message-ID: Jacek Cz wrote: > Do you have some tips about making Python small (minimal list of > modules) and isolated from filesystem. I have an idea > > #define Py_WITHOUT_FILES > This switch should disable some function/modules from modules sys, > fileobject, but also import from file, path resolving etd. It would be good if you could try to develop such a patch, and would volunteer to maintain it. If you do volunteer, there is a good chance that it gets included with Python. Regards, Martin From pyth78 at yahoo.com Fri Apr 16 06:56:13 2004 From: pyth78 at yahoo.com (Ian Adams) Date: Fri, 16 Apr 2004 03:56:13 -0700 (PDT) Subject: QueryInterface -- NewB Message-ID: <20040416105613.7569.qmail@web41409.mail.yahoo.com> How do I do this in Python? hres = pObj->QueryInterface(IID_MyIntf1, (void **) &piMyIntf1); piMyIntf1->QueryInterface(IID_MyIntf2, (void **) &piMyIntf2); piMyIntf2->SomeMthd(args); Also, how do I call/manage smart pointer interfaces? Thanks. --------------------------------- Do you Yahoo!? Yahoo! Tax Center - File online by April 15th -------------- next part -------------- An HTML attachment was scrubbed... URL: From no_spam at terastat.com Tue Apr 27 19:31:12 2004 From: no_spam at terastat.com (bap) Date: Tue, 27 Apr 2004 23:31:12 GMT Subject: Problem with PY2EXE and VPython References: Message-ID: <43Cjc.54834$aQ6.4096572@attbi_s51> Thomas Thanks -- removing the OPENGL dlls did the trick. Turns out they are included with Windows2k (and xp and Nt) -- which I once knew, but anyway having another copy apparently greatly confused Windows. Bruce "Thomas Heller" wrote in message news:mailman.55.1083090463.25742.python-list at python.org... > Bruce, I could not reply to the private mail you sent me (some permanent > error at the mail server), so here it goes: > > Bruce Peterson writes: > > > Thomas > > Thanks -- here are the files in the distribution directory created > > by PY2EXE for tower of Hanoi demo. > > cvisual.dll > > datetime.pyd > > DDRAW.dll > > dirlist.txt > > GLU32.dll > > hanoi.exe > > library.zip > > multiarray.pyd > > OPENGL32.dll > > python23.dll > > umath.pyd > > w9xpopen.exe > > _numpy.pyd > > _sre.pyd > > > > Bruce, you should at least remove these files from the dist dir, and > make sure in other ways that opengl and direct draw (is this directX, or > how it's called?) is installed on the target system: > > > DDRAW.dll > > GLU32.dll > > OPENGL32.dll > > I'm not sure where cvisual.dll comes from. (10 seconds later, after > googling around: ah, it's from VPython, so it must stay). > > The other files are Python extensions. > > Thomas > > From opengeometry at yahoo.ca Sat Apr 17 19:37:43 2004 From: opengeometry at yahoo.ca (William Park) Date: 17 Apr 2004 23:37:43 GMT Subject: Difficulty Finding Python Developers References: <65cbc3dd.0404140641.3501fde8@posting.google.com> <65cbc3dd.0404141018.36d9d4ce@posting.google.com> Message-ID: Paul Morrow wrote: > For those who've asked... > > This particular project is essentially a web-based registration > application. We'll probably want to use mod_python to serve the > pages, and Oracle for the database backend. It will have things like > a white-paper area that requires registration to access, an opt-in/out > email component, and the like. > > But we do want the developer to be physically here (in Atlanta). "3-month" usually means "Summer student", because it indicates that you want lots of staff turnover. So, university, college, or high school comes to mind. In fact, go to your local High School, hire couple of script kiddies, and teach them Python. You'll probably get more result out of them, and cheaper too. Also, if you post some kind of "open competition", say 1. $5000 for a script to get HTML form data, format them, and ... 2. $2000 for ... 3. $1000 for ... you might get more response. Here, you are concentrating on result, and not on tools. This is because your client pays you for getting the job done, and not for using Python. cc: OP -- William Park, Open Geometry Consulting, Linux solution/training/migration, Thin-client From roy at panix.com Thu Apr 15 09:07:17 2004 From: roy at panix.com (Roy Smith) Date: Thu, 15 Apr 2004 09:07:17 -0400 Subject: List vs tuples References: <107bf8q8fhsmg5e@news.supernews.com> <7in05lfpqt.fsf@enark.csis.hku.hk> Message-ID: "urnerk at qwest.net" wrote: > As for emulating C structs, I liked the suggestion of using a class with > only data attributes. That's a logical analogy, as in C++, it's the struct > that morphs into the basic class, with the addition of methods to data. > > However, if you really want to used a low level C struct, there's actually a > struct in the standard library implemented using a C struct. That depends on what you're trying to do. The struct module lets you get at (or generate) packed binary data. Unless you're dealing with binary files or network protocols, you'll probably never have a reason to use it. In C terms, the functionality the struct module implements is essentially a union of a struct and a char array. The degenerate class I had suggested makes a lot more sense for the more common case of just wanted to build an aggregate data item and be able to refer to the members by name. From pirx at python.net Sat Apr 3 20:59:16 2004 From: pirx at python.net (Christian Tismer) Date: Sun, 4 Apr 2004 01:59:16 +0000 (UTC) Subject: Python is faster than C References: <406F0907.96F37EA1@tunes.org> <7xy8pcogaa.fsf@ruckus.brouhaha.com> <406F454B.C4CC8063@tunes.org> <7xekr4vdek.fsf@ruckus.brouhaha.com> <406F5E95.EBE6D3E8@tunes.org> Message-ID: Armin Rigo tunes.org> writes: > Again I'm not saying it is trivial to implement it, but that not having > to expose for optimization purposes 'xrange' and the whole 'iterator' > part of the language would be worth it, in my opinion. First of all, I'm trying to see whether I can write through this interface. As you might have realized, sarcastically after they fooled me with that April joke, my site was really lost, andthis is a tad. Anyway, I'd like to add that Armin's idea can be extended (as he surely knows) to special casing seldom assignments to and algorithmically given array. That is, in the case of just a few assignments, a list could internally aufment the expression. If the number of elements grows, it could be turned into a preferred dictionary, after reaching some threshold. And after another threshold, it could be turned into something like a real list, or just a specialized, typed list, depending on the type. In general, I share Armin's impression, that iterators are nothing else but an explicit way to spell optimizations. While explicit is better than implicit, in the case of optimizations, I believe it is an over-specification, and almost completely in the false direction. We have to prove this in a known project, still. There is one thing where I think explicit iterator do make some sense, in a way the reader might not expect. Let me show: if you do something like for each in sequence: try: do_something_with(each) except SomeThingWrongWithThis: # handle exception somehow In terms of iterators, we implicitly create an interator here and consume it. The explicit notation of iterators gives us this advantage: instead you can do it this way: it = iter(sequence) can_continue = 1 while can_continue: try: for each in it: do_something_with(each) exceptSomeThingWrongWithThis can_continue = some_recovery(each) continue In words: By the help of iterators, it is possible to write exception handlers for special cases *outside* the loop, repair the error, and continue iterating in the loop. I have used this pattern a lot of times now, and I'm quite happy ith it. But I have to admit, that this is too a bad, explicit optimization, and a compiler could be smart enough to do this for me, automatically. cheers - chris From fumanchu at amor.org Wed Apr 14 17:22:50 2004 From: fumanchu at amor.org (Robert Brewer) Date: Wed, 14 Apr 2004 14:22:50 -0700 Subject: Fast Data Comparison (dict v. list. v string) Message-ID: Scott Brady Drummonds wrote: > I'm a relative novice at Python and am working on some > optimizations in my > first Python project. At its core, this tool I'm writing > needs to perform > many comparisons to fixed-size lists of fixed-length strings. > > Currently, my implementation uses dictionaries to store each > string. I > maintain a separate "key-mapping" dictionary that maps keys from one > dictionary to the other. Then, all I have to do to compare the two > dictionaries is as follows: > for metaKey in keyMap.keys(): > if dict1[metaKey] != dict2[keyMap[metaKey]]: > # Do some processing Try writing that as: for key, val in keyMap.itervalues(): if dict1[key] != dict2[val]: # Do some processing ...and see how much faster it is on your dataset. 33-50% faster would not be uncommon on a large set. FuManChu From marco at reimeika.ca Tue Apr 6 02:19:32 2004 From: marco at reimeika.ca (marco) Date: 06 Apr 2004 02:19:32 -0400 Subject: regex help for a newbie References: Message-ID: Marco Herrn writes: > I have the following string in my program: > > string= "aaa%(BBB%(CCC)BBB)aaa%(DDD)aaa" [snip] > the parts in a recursive function. So the thing I want to achieve here > is to extract %(BBB%(CCC)BBB) and %(DDD). p1, p2 = "aaa%(BBB%(CCC)BBB)aaa%(DDD)aaa".split("aaa")[1:-1] Cheers, -- marco at reimeika.ca Gunnm: Broken Angel http://amv.reimeika.ca http://reimeika.ca/ http://photo.reimeika.ca From vald at dead.art.pl Fri Apr 16 18:50:06 2004 From: vald at dead.art.pl (KN) Date: Sat, 17 Apr 2004 00:50:06 +0200 Subject: global variables extended to other objects/modules Message-ID: <20040416225006.GY22646@hell.art.pl> Hello, I'm new to this list, and I have an important question at the beginning. There is a matter that concerns me - it's the globales implementation. I've read nearly everything I found about this and about problems people were having with using it. And now I'd like to ask here, because it seems to be more than globales() matter, but an object-programming one. I don't know any patterns for solving such problems. Actually I'm working on an web application based on mod_python, but this is not very important here. I use MVC patterns for application flow, so I have one object that works as handler and controller, and this object creates Action-classes which run all necessary business logic by creating other objects that for example fetch information from database. You probably know what I need to do here - I need a link to the database that will be accessible from _every_ module and object that needs to use it. I wanted it to be started and closed by main module - controller.py. Main area where I will use it will be a bunch of small model-objects, like Person/Store etc. classess that fetch data from db, saves them, return them to Action object which passess them back to the controller etc. Now, when I cannot have a really global attributes that will be accessible even for objects imported from different modules, only way I see is to pass it in constructors, so: controller.py -> Action.__init__(dblink) then in Action I need to use Person and Job classess that both need db access: action.py -> Person.__init__(dblink), Job.__init__(dblink) and so on. Is this a common way of solving this problem? What I don't want for sure is multiple connections per request so I need a single object storing db_link. Is there any solution that will not force me to pass this reference to every object I create, when I need db access? I thought something about using globals() there and I found that I can use sys.modules for getting the main object (controller) from any other module. when I define in controller.py which is __main__ something like global db = DBlink() I can use in any module something like this, right? local_db_link = sys.modules['__main__'].db and I will get reference to this link created on the beginning of application? But this seems to be ugly and not very object-oriented? The problem wouldn't be so big if I hadn't so many attributes I need to pass to most of my objects, like request, session, configuration and other attribs that should be 'application-wide' It would be very bad to define in every object __init__ which will have so many arguments. Best regards, Kamil From teiffel at attglobal.net Tue Apr 20 10:40:43 2004 From: teiffel at attglobal.net (Marcello Pietrobon) Date: Tue, 20 Apr 2004 10:40:43 -0400 Subject: closing file Message-ID: <4085366B.2020407@attglobal.net> Hello, Once I open a file, for example as: class MyClass: def logFileOpen( self ): self.fdFilenameLog = file( self.filenameLog, 'a' ) return I cannot find in hte documentation how to make sure the file are closed. I guess that Python is closing all files at the end of the application or when an Exception is raised Is this true ? Is the file closed when the destructor is called ? ( Internally because I don't see a way to call a destructor in Python ). Thank you very much, Marcello From mark at prothon.org Wed Apr 21 16:02:35 2004 From: mark at prothon.org (Mark Hahn) Date: Wed, 21 Apr 2004 13:02:35 -0700 Subject: Dollar sign ($) on foriegn keyboards? (prothon) References: Message-ID: "Fredrik Lundh" wrote ... > when I posted my message, 25 of 48 messages visible in my newsreader > were Prothon-related. In my defense, who would have thought that asking if international keyboards had trouble typing a dollar sign would be a troll question? I would never had thought to make a web page questionaire for such an innocent sounding question. Do you think it's because I added "(prothon)" to the subject? I do that as a courtesy but maybe it causes trolling. From mwallis at swri.org Mon Apr 26 17:09:55 2004 From: mwallis at swri.org (Melissa Wallis) Date: Mon, 26 Apr 2004 16:09:55 -0500 Subject: omniorb, python and callbacks Message-ID: <108qul5he6cn1ba@corp.supernews.com> I have a class with 5 callbacks. Two of the callbacks work fine but the others don't. The main difference is that the callbacks that don't work are composed of a sequence of structs. I noticed a comment about this same problem on the web but no solution was noted. What makes the callbacks with the sequences so different? It seems that when one of the callbacks with a sequence is called it just hangs. I am talking to a TAO orb from omniORB. Thanks for any help Melissa From klappnase at web.de Tue Apr 27 05:50:57 2004 From: klappnase at web.de (klappnase) Date: 27 Apr 2004 02:50:57 -0700 Subject: askstring => grab failes References: Message-ID: wes weston wrote in message news:... > Guys/Gals, > Does anyone know why a call to tkSimpleDialog.askstring > would result in a grab fail error. The call is from a toplevel > window. The error happens about two thirds of the time! It > doesn't happen at all in other apps. Is it a build issue? > > Redhat 9.0 > Python 2.3.3 > > Thanks, > wes I had this same problem (Mandrake9.1, Python2.3.3/Tk8.4.5 as well as Python2.2.3/Tk8.3.3) that I got error mesages on askstring() dialogs: TclError: grab failed: window not viewable Because it happens with both python/Tk versions I don't think it's a build problem. Maybe it's a Tk-bug? It drove me nuts for a while until I wrote my own dialog widget. Any hints here would be very appreciated. Regards Michael From bdesth.quelquechose at free.quelquepart.fr Wed Apr 28 05:12:11 2004 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 28 Apr 2004 11:12:11 +0200 Subject: Embedding OCaml within Python In-Reply-To: <37aad18.0404280019.500e2841@posting.google.com> References: <37aad18.0404280019.500e2841@posting.google.com> Message-ID: <408f6ef2$0$17614$636a15ce@news.free.fr> Max Powers wrote: > I've spent an interesting day searching the web for help with calling > OCaml functions from a python program and have come to the newsgroup > for some advice (unfortunately I'm learning both languages at the same > time, so maybe I've missed something obvious!) > > The situation is this; I've got a large legacy program that is written > in ocaml, within which there's a parser. I'd like to be able to call > that parser from my python program (actually it's really a GUI using > wxPython), rather than reimplement it (and then have to maintain two > parsers into the future). I may say something stupid but... I suppose this OCaml program has a CLI ? If so, can't you just call the OCaml program from your wxPython GUI and get result back via a pipe ? > > I've come across Viper, which looks like a python compiler/interpreter > implemented in OCaml, so I imagine that I could get it to do some > magic tricks to call a ocaml library from python, but I think that's > doomed to failure because of the C extensions of wxPython. AFAIK, wxWidget is C++, not C... > I've stumbled across Pycaml, but don't quite understand how to use it > to call ocaml from python. Alternatively I think I can wrap the ocaml > library in a C wrapper and then call that from python. For what I saw (30' fast scan of the Pycaml page), it seems you would need to write OCaml wrappers for your legacy OCaml code. But I dont have any working experience in this kind of stuff, so I may have it all wrong. > Can anyone give advice/share experiences? Is combining OCaml with > python relatively straightforward with a bit more effort, or am I in > for a world of pain? I guess you could ask help from the OCaml community too... > Thanks, Err... Not sure I'm really helpful here :( Bruno From mark at prothon.org Thu Apr 22 23:19:10 2004 From: mark at prothon.org (Mark Hahn) Date: Thu, 22 Apr 2004 20:19:10 -0700 Subject: Why we will use obj$func() often References: <84Uhc.22278$dZ1.5087@fed1read04> <8AWhc.23114$dZ1.11070@fed1read04> <40883BFE.B381518A@alcyone.com> <27_hc.23801$dZ1.2716@fed1read04> Message-ID: "Peter Hansen" wrote ... > It will be interesting to see whether > Prothon manages to achieve similar success in either area. I apologize if I got competitive. As I have said many times, I don't expect Prothon to compete with Python. It's hard to bust your butt on something day in and out without getting carried away. From john at hazen.net Wed Apr 28 18:11:48 2004 From: john at hazen.net (John Hazen) Date: Wed, 28 Apr 2004 15:11:48 -0700 Subject: Path ... where is my application's home dir? In-Reply-To: References: Message-ID: <20040428221148.GB6584@gate2.hazen.net> [Marco Aschwanden] > >But I still wonder: Suppose sys.argv[0] wouldn't work. What > >would be the > >easiest way to find out where an application lies? > > > >Ideas: > >1. going through sys.path and checking whether the application > >file is in > >a dir > >2. or is there a module method, that tells you where it is stored? [Tim Golden] > As far as I know, it's effectively impossible: the "application" you're > running is the Python executable, so even if you were do some fancy > stuff with the win32 process/thread API and work out who you were > and where you were running, that'd probably give you: > c:/pythonxx/python.exe. After poking around in the interactive python, I found __file__. I wrote this test script, and created a dummy module "loc" in the same directory: --------- loc.py ---------- pass --------- end loc.py ---------- --------- test.py ---------- #!/usr/bin/python import loc,os print __file__ print loc.__file__ print os.path.dirname(loc.__file__) --------- end test.py ---------- Here's the output: (MacOS) lap:john$ ./test.py ./test.py /Users/john/loc.pyc /Users/john lap:john$ (output shows test.py path relative and loc path absolute invoked from different directories, and by invoking with "python test.py") Note that, for some reason, the file that was initially loaded by python uses a relative pathname, but any modules loaded by that module seem to use fully qualified path. I'd be interested if there's a reason for this, and if it works in windows as well. If it does, and you can package another file with your application (especially since you talked about having an "application directory"), then it could be a solution that works without invoking any os-specific commands. -John From jmdeschamps at cvm.qc.ca Mon Apr 19 11:59:16 2004 From: jmdeschamps at cvm.qc.ca (jmdeschamps) Date: 19 Apr 2004 08:59:16 -0700 Subject: Threats to the: Daily Python URL! References: <2ae25c6b.0404182250.4c5bc870@posting.google.com> Message-ID: <3d06fae9.0404190759.3096d492@posting.google.com> paddy3118 at netscape.net (Paddy McCarthy) wrote in message ... > I sent the following this morning: > ... > To: daily at pythonware.com > > > Hi, > I read your 'Administrative note' at http://www.pythonware.com/daily/ today > > Please don't stop the excellent work that you do. > I don't know what threats and insults you suffered but I would like to > ensure you that I for one read the column and value it. > > Thanks, Paddy. I second the comment "Please don't stop the excellent work that you do." My daily morning routine is such: 1- open e-mail 2- open Daily News (thanks again) 3- open comp.lang.python 4- open Dilbert... That and coffee and the day gets on a roll...! Jean-Marc From mwh at python.net Mon Apr 19 07:07:20 2004 From: mwh at python.net (Michael Hudson) Date: Mon, 19 Apr 2004 11:07:20 GMT Subject: AOP use cases References: <84fc4588.0404140106.3fa0c55@posting.google.com> <0pydnSB4WYuieuLdRVn-hQ@powergate.ca> <35qdnT4kNsX1kB3dRVn-gg@powergate.ca> Message-ID: Peter Hansen writes: > Peter Hansen wrote: > > I would be very interested to hear some real-world and real useful > > use cases for AOP as well. So far, the logging example seems to > > be put forth so often that I'm starting to suspect that's the > > *only* "useful" thing people are doing with it. :-) > > From direct personal experience, could some AOP folks please > > point out some compelling use cases so that the doubting > > Thomases (and Wills, and Peters) can better understand and > > accept the idea of AOP as being more than just a few fringe > > cases? > > Thanks for the replies so far, but what concerns me is that > almost no one seems to have actually used AOP in their code. What do you understand "AOP" to mean? One meaning of "AOP" seems to be a collection of techniques and tools to make programming in the Java environment a pleasanter experience. This meaning hardly applies to programming in Python... Cheers, mwh -- I think my standards have lowered enough that now I think ``good design'' is when the page doesn't irritate the living fuck out of me. -- http://www.jwz.org/gruntle/design.html From lesstif-admin at lesstif.org Sat Apr 3 02:21:28 2004 From: lesstif-admin at lesstif.org (lesstif-admin at lesstif.org) Date: Sat, 03 Apr 2004 02:21:28 -0500 Subject: Request to mailing list Lesstif rejected Message-ID: Your request to the Lesstif mailing list Posting of your message titled "Re: My details" has been rejected by the list moderator. The moderator gave the following reason for rejecting your request: "Non-members are not allowed to post messages to this list." Any questions or comments should be directed to the list administrator at: lesstif-admin at lesstif.org From moosebumps at moosebumps.com Thu Apr 22 03:16:51 2004 From: moosebumps at moosebumps.com (Moosebumps) Date: Thu, 22 Apr 2004 07:16:51 GMT Subject: String/source code analysis tools References: Message-ID: Man, I love Python! After writing this, with about 10 minutes of googling, I found the difflib, which can do diffs token by token. I can do what I want with about 10 lines of code probably. Wow. I think the diff is pretty much the best solution -- but if anyone has any other pointers I would appreciate it. I would have to diff all pairs of files and I can get a score of how similar they are to each other. So if I have 10 files I would have to run it 45 times to get all pairs of diffs. That should be OK since they are small files in general. MB "Moosebumps" wrote in message news:j0Khc.25133$Q%5.6444 at newssvr27.news.prodigy.com... > I have a whole bunch of script files in a custom scripting "language" that > were basically copied and pasted all over the place -- a huge mess, > basically. > > I want to clean this up using Python -- and I'm wondering if there is any > sort of algorithm for detecting copied and pasted code with slight > modifications. > > i.e. a simple example: > > If I have two pieces of code like this: > > func1( a, b, c, 13, d, e, f ) > func2( x, y, z, z ) > > and > > func1( a, b, c, 55, d, e, f ) > func2( x, y, z, x ) > > I would like to be able to detect the redundancies. This is obviously a > simple example, the real code is worlds messier -- say a 3 line script, each > line has 800 characters, copied 10 times over with slight modifications > among the 800 characters. I'm not exaggerating. So I'm wondering if there > is any code out there that will assist me in refactoring this code. > > My feeling that a general solution this is very intractable, but I thought > I'd ask. I'd probably have to roll my own based on the specifics of the > situation. > > It is actually sort of like a diff algorithm maybe, but it wouldn't go line > by line. How would I do a diff, token by token? I don't know anything > about what algorithms diffs use. > > thanks, > MB > > > From tim.one at comcast.net Wed Apr 21 14:50:25 2004 From: tim.one at comcast.net (Tim Peters) Date: Wed, 21 Apr 2004 14:50:25 -0400 Subject: Dollar sign ($) on foriegn keyboards? (prothon) In-Reply-To: Message-ID: [Tim] >> Prothon is trying some design decisions that are very hard to try in >> CPython now, and how they turn out is interesting to me. [/F] > design by self-selecting newsgroup subsets has been tried before, also > for CPython. it a great way to waste lots of time and get really > lousy results (or no results at all, in CPython's case). Have you followed these threads? Prothon has different designs for object layout, class semantics, threading, and garbage collection (among other subsystems), and c.l.py has played little (if any) role in what Mark wants to do about those. The consequences of those decisions ("how they turn out") should be of interest to everyone with at least a smidgen of knowledge about CPython's and/or Jython's implementations. Then again, you're just crabby today <0.7 wink>. From jepler at unpythonic.net Tue Apr 6 22:50:20 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Tue, 6 Apr 2004 21:50:20 -0500 Subject: Tkinter radiobutton border In-Reply-To: References: Message-ID: <20040407025020.GA30336@unpythonic.net> Peter Otten's advice is correct, if all you want to do is get rid of this 1-pixel area. However, you may want to use highlightbackground to set it to green, so that the visual cue for "this widget has keyboard focus" is retained. To explain a little more, every widget has a "highlight rectangle" around it, which has a thickness of highlightthickness and a color of either highlightcolor (if the widget or a child has focus), or highlightbackground (otherwise). A few widgets may actually behave differently (buttons on win32 display a dotted rectangle between the border and the contents, for instance). Widgets that don't normally take focus (such as frames and labels) have a 0 highlightthickness by default, but can be given a highlightthickness. Widgets that tend to take keyboard focus default to a highlight thickness of 1, with back for highlightcolor and the system background color for highlightbackground. This is why I suggest that you consider setting the highlightbackground to green. If you create a scrolled area, you may want to set the highlightthickness of the scrolled widget to 0, and that of the frame that encloses it and the scrollbars to 1. This will make the focus rectangle surround the scrolled widget and the scrollbars together. Jeff From peter9547 at btinternet.com Fri Apr 2 05:16:19 2004 From: peter9547 at btinternet.com (Peter MacKenzie) Date: Fri, 2 Apr 2004 10:16:19 +0000 (UTC) Subject: emergent/swarm/evolutionary systems etc References: Message-ID: I'll take that to mean that my chances are slim. Although this probability is mediated my lack of a social life, I've conceived of a contingency wherein a standard spreadsheet application could be used to facilitate at least some limited degree of modelling. Given your recommendation, I'll ensure the feasibility of this option before I commit to the primary methodology, thereby ensuring that a disappointing rate of progress doesn't prove fatal for my dissertation. Fortunately, I've found an online textbook at http://www.ibiblio.org/obp/thinkCSpy/index.htm, which appears better suited to my needs than the standard python documentation, and may alleviate some of the conceptual and syntactical difficulties I've been experiencing. I expect I may be back here for additional aid in the near-future. From rlratzel at siliconmetrics.com Thu Apr 1 17:33:37 2004 From: rlratzel at siliconmetrics.com (Rick Ratzel) Date: 1 Apr 2004 14:33:37 -0800 Subject: Pyrex gets a perfect score. References: Message-ID: <905fcd91.0404011433.6681abd9@posting.google.com> ...just curious...did you look at Elmer (http://elmer.sourceforge.net)? Elmer generates a C interface to a Python module. No knowledge of the Python/C API is necessary, and the resulting C interface resembles (as close as possible) the underlying Python interface. Take a look at: http://elmer.sourceforge.net/examples.html The Elmer examples in this presentation might be helpful too: http://elmer.sourceforge.net/PyCon04/elmer_pycon04.html ...as well as the source code for the examples: http://elmer.sourceforge.net/PyCon04/Elmer_PyCon04.tgz Like you mentioned, since the underlying code is Python, it will not be as fast as C. However, Elmer allows you to easily prototype new functionality in Python and later re-write it in C for speed, similar to what you said. The C interface looks "native", and the generated header file can even be re-used in most cases when/if you re-write in C. The presentation & example code has a C++ example, showing how Python classes and types can be used "seamlessly" in C++ too. Kyler Laird wrote in message news:... > I mentioned earlier that I started using Pyrex because I'm taking a > computer vision course that requires all assignments to be submitted > as C(++). While I could write C it would hurt me to do so and > certainly distract me from the computer vision aspects. I like > using Python these days and Pyrex looked like a good solution. > > (BTW, on the last assignment I saw several messages from someone > having difficulty with segfaults due to memory allocation problems. > Grrr... Time spent messing with pointers is not advancing one's > understanding of computer vision.) > > Here's one reaction I got on the subject: > > 1. How is your teacher going to react when you hand in obfuscated-ish > > C code that depends on the whole Python interpreter _and_ PIL? > > The bottom line is that I got a perfect score on all (seven) of my > homework assignments. At first, I spent way too much time on them - > figuring out how to use Pyrex and also just having fun exploring > possibilities that I wouldn't have considered if I'd used C. Later, > however, I found that I could start on the assignment the night > before it's due and complete it in time. In terms of time, it was > still a good investment over this short period. > > Most important, I had fun doing these assignments and I learned a > lot from them. I am confident that I would not have accomplished > as much with C (from scratch). > > Our project is going to require fast decoding of an image. My > homework solutions have been agonizingly slow. There's a lot of > room for optimizations and I'm looking forward to using Pyrex to > prototype in Python and then replace pieces with C as needed. > > I can certainly see how Pyrex could serve nicely beyond academic > settings. Is it a way to sneak Python into projects that are > "strictly C"? Sure, it can work. Can it free the developer to > quickly experiment with new concepts without spending excessive > effort on programming? Definitely. Is speed and ease of > development sometimes more important than execution speed. Yup. > Can Pyrex be used effectively as a path to a native C solution? > We'll see, but I'm confident that it can. > > Thank you, Pyrex! > > --kyler From nhv at cape.com Fri Apr 30 16:13:20 2004 From: nhv at cape.com (Norman Vine) Date: Fri, 30 Apr 2004 16:13:20 -0400 Subject: Python Image Library (PIL) build error on Cygwin References: <40928190.5060004@holdenweb.com><20040430193031.GA1728@tishler.net> <4092AB1C.8050101@holdenweb.com> Message-ID: "Steve Holden writes: > > sholden at DELLBOY ~/install/Imaging-1.1.4 > $ python setup.py build > running build > running build_py > running build_ext > building '_imagingtk' extension > gcc -shared -Wl,--enable-auto-image-base > build/temp.cygwin-1.5.9-i686-2.3/_imagingtk.o > build/temp.cygwin-1.5.9-i686-2.3/Tk/tkImaging.o -LlibImaging > -L/usr/lib/python2.3/config -lImaging -ltk8.4 -ltcl8.4 -lpython2.3 -o > build/lib.cygwin-1.5.9 > -i686-2.3/_imagingtk.dll > /usr/lib/gcc-lib/i686-pc-cygwin/3.3.1/../../../../i686-pc-cygwin/bin/ld: > cannot find -ltk8.4 > collect2: ld returned 1 exit status > error: command 'gcc' failed with exit status 1 > > I'm wondering if I might need to download extra libraries, but I can't > see anything appropriate. Try cd /usr/lib ln -s libtk84.a libtk8.4.a ln -s libtcl84.a libtcl8.4.aHTHNorman From peter at engcorp.com Thu Apr 29 15:49:48 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 29 Apr 2004 15:49:48 -0400 Subject: static keyword In-Reply-To: References: Message-ID: <-pydnU64kMXAwQzdRVn_iw@powergate.ca> Nick Jacobson wrote: > I don't know if "hack" is the right word. What I meant is it seems > like overkill to have to make (and name) a class, plus add a second > function, every time you want a function to have a static variable. I can't recall the last time I wanted a function to have a static variable. Years, it's been... (That probably just says something about our approach to design and coding. I'm not criticizing you, just explaining why what I showed seems natural and simple to mean, but not to you.) -Peter From edreamleo at charter.net Mon Apr 12 20:53:56 2004 From: edreamleo at charter.net (Edward K. Ream) Date: Mon, 12 Apr 2004 19:53:56 -0500 Subject: accept xml instead of plain Python text? References: <107jc0h6r5c3g3d@corp.supernews.com> Message-ID: <107meh6l6j85id9@corp.supernews.com> > 1. What advantage would you get? Lately there has been discussion in Leo's forums about various different ways of having Leo represent structure in source files. At present Leo uses so-called "sentinel" lines, comment lines of the form #@. An xml format would make embedding structure very easy. OTOH, xml is less readable than sentinels, and some of Leo's users (or their managers) dislike sentinels, so arguably xml is a step backwards. As an alternative, there have been some proposals to separate structure from content in two separate files. The idea is to script cvs so that the two files (the content and the structure) are always committed and updated in synch. All this is blue-sky musing at present. > 2. How exactly should the XML look like? A good question. One thing I didn't say in my original post was that I envision one would have all sorts of problems deciding on what pythonMl (or leoPyMl) would be. The situation is a similar to the discussions about document formats. I suppose one could propose an extensible format: the Python compiler would ignore the extensions... > The simplest approach I can think of is... This might sometimes be useful because one could add "annotation" attributes to the element. Like Hi, I really thought that I had this importing business down. I recently downloaded and installed mx module for the DateTime class. In IDLE, I go: import mx mx.DateTime.DateTime(2004) I get AttributeError: 'module' object has no attribute 'DateTime' but if you type: import mx.DateTime mx.DateTime.DateTime(2004) If you "import mx", like the first example, doesn't that get everything? If you know, from the docs, that it contains a DateTime class and then a DateTime object, and you specify the whole thing, why shouldn't that work? thanks for your patience Steve From daniel at dittmar.net Fri Apr 23 15:56:33 2004 From: daniel at dittmar.net (Daniel Dittmar) Date: Fri, 23 Apr 2004 21:56:33 +0200 Subject: AOP use cases In-Reply-To: References: <84fc4588.0404140106.3fa0c55@posting.google.com> <0pydnSB4WYuieuLdRVn-hQ@powergate.ca> <4087D662.6010209@yahoo.com> Message-ID: Dave Kuhlman wrote: > So, arbitrarily complex transformations on the source code with > the intent of hiding the intension of the source code are good, > right? What do you think a C compiler is doing? "But it's still my code, the compiler simply allows to run it on a another processor." AOP tries to provide transformations so that it is still your code, but that it can run in a multitude of contextes (example: single user, servlet engine, transaction monitor). There are other approaches like code generation. But chances are that that multiple code generators cannot be combined easily, as each precompiler will reject the syntax extensions of the others as syntax errors. Daniel From tjreedy at udel.edu Fri Apr 30 01:19:51 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 30 Apr 2004 01:19:51 -0400 Subject: Subclasses in Python References: Message-ID: "Greg Ewing" wrote in message news:c6sdiq$fk1bl$1 at ID-169208.news.uni-berlin.de... > Thomas Philips wrote: > > Perfect! But tell me, how did you know to use __name__? I typed > > dir(object) and dir(Player) in IDLE, and in neither case did __name__ > > show up. > > Probably it's an oversight on the part of whoever implemented > the dir() method for classes. I guess you just have to find > out things like that by hanging out in c.l.py.:-) And submit a bug report on sourceforge so some future person will find it with dir(). tjr From vincent at visualtrans.de Tue Apr 13 13:18:07 2004 From: vincent at visualtrans.de (vincent wehren) Date: Tue, 13 Apr 2004 19:18:07 +0200 Subject: Python crashes - cannot pin it down! In-Reply-To: References: Message-ID: Stevie_mac wrote: > Figure this! > > ### Shell1 ### > >>>>from wxPython.wx import * >>>>mb = wxMessageBox('hello') > > > ### testmb.py ### > from wxPython.wx import * > mb = wxMessageBox('hello') > Try changing that to: from wxPython.wx import * app = wxPySimpleApp() app.MainLoop() wxMessageBox("Hello") HTH, Vincent Wehren From i2Postal2 at postal.i2.com Fri Apr 16 13:32:53 2004 From: i2Postal2 at postal.i2.com (i2Postal2 at postal.i2.com) Date: Fri, 16 Apr 2004 12:32:53 -0500 Subject: Report to Sender Message-ID: Incident Information:- Database: c:/lotus/domino/data/mail3.box Originator: python-list at python.org Recipients: ang at i2.com Subject: Mail Delivery (failure ang at i2.com) Date/Time: 04/16/2004 12:32:42 PM Message sent to ang at i2.com was quarantined because it contained content that has the potential to put i2 at risk. Please feel free to contact the intended recipient for options. From fredrik at pythonware.com Mon Apr 19 10:59:32 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 19 Apr 2004 16:59:32 +0200 Subject: Tkinter Button command query References: Message-ID: Paul A. Wilson wrote: > I'm new to Tkinter programming and am having trouble creating a > reusable button bar... I want to be able to feed my class a dictionary > of button names and function names, which the class will make. > > My button bar is implemented a Frame subclass, which takes the button > dictionary as an argument and displays the buttons on the screen: > > class OptionsBar(Frame): > def __init__(self, buttonDict, parent=None) > Frame.__init__(self, parent) > parent.someFunction() # This works fine > for (name, command) in buttonDict.items(): > Button(self, text=name, command=command).pack(side=TOP, > fill=BOTH) Tkinter wants the functions, not the names of the functions. you can use getattr() to get around this: for (name, command) in buttonDict.items(): command = getattr(parent, command) Button(self, text=name, command=command)... (getattr(obj, "name") is the same as obj.name) From rogerb at rogerbinns.com Sun Apr 18 16:30:57 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Sun, 18 Apr 2004 13:30:57 -0700 Subject: using a USB HID device References: <40827ce3.1151345337@news.xs4all.nl> Message-ID: Samuel Schulenburg wrote: > wouter at voti.nl (Wouter van Ooijen (www.voti.nl)) wrote in message news:<40827ce3.1151345337 at news.xs4all.nl>... > > I want to use Python to interface with an USB HID device (not a > > I found that USB > devices do not use this layer, and as a result I am also investigating > using python to access USB devices. So far it looks like a seperate > driver along with a interfaceing DLL will needed. Here is one I made earlier: http://cvs.sf.net/viewcvs.py/bitpim/bitpim/native/usb/ It is a Python wrapper (using SWIG) around libusb (including libusb-win32). My BitPim project currently ships using it on Windows, Linux and Mac. Roger From jdhunter at ace.bsd.uchicago.edu Thu Apr 15 08:45:16 2004 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Thu, 15 Apr 2004 07:45:16 -0500 Subject: warnings Message-ID: In the following import warnings warnings.warn('change me') The warning is issued: hunter:~/python/test> python test.py test.py:3: UserWarning: change me warnings.warn('change me') I want to supress the line echo. Eg, I just want hunter:~/python/test> python test.py test.py:3: UserWarning: change me How do I configure warnings to do this? Thanks! John Hunter From crap1234 at hotmail.com Mon Apr 5 16:05:10 2004 From: crap1234 at hotmail.com (Stefan Axelsson) Date: Mon, 05 Apr 2004 22:05:10 +0200 Subject: slightly OT: BUT NEEDs to be said In-Reply-To: <8b42d1998c978c8c1cddf15c52a1c57b@dizum.com> References: <8b42d1998c978c8c1cddf15c52a1c57b@dizum.com> Message-ID: Nomen Nescio wrote: > Cuddly cartoon characters like the Snake, or various BSD creatures = highly > acceptable and good. Well, one shouldn't feed the trolls. (And kudos on a well done one at that.) BUT, on the subject of "highly acceptable and good" BSD creatures see: http://www.erenkrantz.com/Humor/BSDDaemon.shtml for an encounter with at least two people (and I use that term losely) who would beg to disagree. If you think "Oxford liberals" are scary... :-) Stefan, -- Stefan Axelsson (email at http://www.cs.chalmers.se/~sax) From sakesun at boonthavorn.com Fri Apr 9 06:08:13 2004 From: sakesun at boonthavorn.com (Sakesun Roykiattisak) Date: Fri, 09 Apr 2004 17:08:13 +0700 Subject: Why Activestate Python ? In-Reply-To: References: Message-ID: <4076760D.1090509@boonthavorn.com> >Apart fromt he fact that they bundle Mark Hammond's Windows Extensions >with it (in the windows version) - what is to be gained from using >their distributio instead of the 'normal' one ? For me, Mostly documents. Win-html-help, extra documents (PEPs, Dive Into Python, Python HOWTOs, Non-Programmers Tutorial) It's great start point for newbie like me. From rkern at ucsd.edu Thu Apr 29 19:21:37 2004 From: rkern at ucsd.edu (Robert Kern) Date: Thu, 29 Apr 2004 16:21:37 -0700 Subject: Closures In-Reply-To: References: Message-ID: Michael Sparks wrote: > On Thu, 29 Apr 2004, Gustavo Niemeyer wrote: > > >>class Closure: >> def __init__(self): >> self.__dict__ = sys._getframe().f_back.f_locals > > > Out of interest how portable is this? Strikes me as extremely useful > class to have lying around :) The only thing that makes me wonder is the > access to _getframe... Well, Guido considers "anything that uses sys._getframe() to be a danger to society unless proven innocent," but what does he know? ;-) http://article.gmane.org/gmane.comp.python.devel/58837 > Michael -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From mcfletch at rogers.com Mon Apr 26 18:44:51 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Mon, 26 Apr 2004 18:44:51 -0400 Subject: Is there a Python library that packs binary data into one file? In-Reply-To: <85b54e91.0404261301.69d5c1e9@posting.google.com> References: <85b54e91.0404261301.69d5c1e9@posting.google.com> Message-ID: <408D90E3.8040700@rogers.com> Jacob H wrote: >Hello all, > >Today I began writing a utility script that takes given binary files >and puts them all into one datafile. My idea is to be able to access >any binary data I want by indexing the datafile, e.g. >wanted_image_data = datafileobj[IMAGE_DATA]. The purpose is to hide >external image files from the user in a simple game I'm writing. > >Though I have a good idea of how to implement this, before I begin I >am curious to know if some Python master out there has already come >out with a library that does the same. Anyone? :) > > Not quite what you're asking for, but ResourcePackage embeds resources automatically in Python files. If you are py2exe'ing your projects the result is that the images are invisible (they are part of the Python bytecode files py2exe packs into the exe). The nice part is the automation; you just update the data-file (stored in a sub-package of your main game package) and the embedded version is automagically updated on next import of the resource package (run of the game). http://resourcepackage.sf.net/ Have fun, Mike _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From padhia at yahoo.com Thu Apr 29 17:01:18 2004 From: padhia at yahoo.com (P Adhia) Date: 29 Apr 2004 14:01:18 -0700 Subject: String formatting (%) References: Message-ID: <3281a460.0404291301.3c3c647d@posting.google.com> alloydflanagan at comcast.net (A. Lloyd Flanagan) wrote in message Another version of a more compact function would be, def commafy(s): return len(s) > 3 and "%s,%s" % (commafy(s[:-3]), s[-3:]) or s Note that this function accepts string representation of an integer (without checks of course). P Adhia From roy at panix.com Wed Apr 21 18:08:01 2004 From: roy at panix.com (Roy Smith) Date: Wed, 21 Apr 2004 18:08:01 -0400 Subject: CamelCase versus wide_names (Prothon) References: <6e0680ac.0404211252.7f7b4358@posting.google.com> <4086DFA7.9736E7D3@alcyone.com> Message-ID: In article <4086DFA7.9736E7D3 at alcyone.com>, Erik Max Francis wrote: > Mike wrote: > > > Since Python has removed the need for the ';' character, how about > > using that as a word separator? It's very easy to type, as it is right > > next to the 'L' key on a qwerty keyboard. > > > > Here;is;a;test;paragraph.;What;do;you;think?;Is;it;the;greatest;programming; > > language;invention;since;the > > ;curly;brace? > > This is a really stellar example of why designing a language by > committee doesn't work very well ... Well, we could always try something like... long variable name From rogerb at rogerbinns.com Sat Apr 3 18:25:35 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Sat, 3 Apr 2004 15:25:35 -0800 Subject: Another issue in xmlrpclib Message-ID: <6ot3k1-12e.ln1@home.rogerbinns.com> This was a fun problem to track down. The xmlrpclib._Method object should do something about __str__/__repr__. I have some code that prints out variables when an exception happens, and if anything references one of those _Method objects, then str/repr is called, which it tries to remote. The real problem arises when the original exception occurred doining some XML-RPC, so an exception is printed which when it hits the _Method object causes another XML-RPC connection to be made, which has an exception which when printed hits the _Method object causes another XML-RPC connection to be made, which has an exception which when printed ... (you get the idea :-) I don't know what the exact right solution for this is. Amongst the possible solutions: - Inherit from object, which causes many Python special methods (stuff begining with __) to be defined (I am using this as it is the easiest) - In getattr, refuse to work if the method name starts with one or two underlines - In ServerProxy.__request filter the methodname - Do nothing This issue could hit in other ways. For example, if someone makes a list of XML-RPC methods (via ServerProxy) and then sorts them, various __cmp__ like functions would be called and sent to the remote end. Roger From contact.see.sig at localhost.localdomain Fri Apr 16 07:17:48 2004 From: contact.see.sig at localhost.localdomain (Milan =?ISO-8859-15?Q?Holz=E4pfel?=) Date: Fri, 16 Apr 2004 13:17:48 +0200 Subject: (For gurus) Embed functions in webpages like in PHP? References: <5eq4l1-9vm.ln1@pilz.hasos.com> Message-ID: <20040416131748.1c8a6eff.contact.see.sig@localhost.localdomain> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On Fri, 16 Apr 2004 12:38:16 +0200 Robert Ferber wrote: [...] > As far as I've seen, there is no way to embed Python-code in a webpage > with"" or anything equivalent and I don't see any other way to > solve this problem. > > But maybe somebody else does, I'd apreceate all ideas, > > Thanks a lot I'm sure you'll find something on the sites wilk posted, but I just remembered that I recently read an article which is exactly this done in: (scroll down to "Technology demo: pytext" if you don't want to read the whole thing) I think one should be able to use the "pytext interpreter" as interpreter for a CGI script. (or use "#!/usr/bin/python /path/to/pytext" as first line of the CGI script... or do whatever, just in case one doesn't know :-) ) (If anyone wants all four parts of the article nicely linked on one page, here it is: ) But I think you could also use a script which reads the database result from a file and also does the banner rotation or whatever (so you don't have your result in the script which is called, but you read the result from a file nevertheless) Regards, Milan - -- Milan Holz?pfel alias jagdfalke alias jag ?ff. GnuPG-Schl?ssel / GnuPG Publiy Key GnuPG Fingerabdruck / GnuPG Fingerprint 4C8A 5FAF 5D32 6125 89D1 0CE5 DB0C AF4F 6583 7966 Hinweis: Die Domain jagdfalke.net geh?rt mir nicht mehr wirklich. Deshalb bitte keine jagdfalke.net-eMail-Adressen mehr benutzen. Neue Kontaktm?glichkeiten gibts auf , meine neue Domain ist mjh.name. NOTE: I don't really own the domain jagdfalke.net any logner. Therefore don't use any jagdfalke.net eMail-addresses any more. You can look at for new adresses, my new domain is mjh.name. Hinweis 2: Wenn sich hier nicht findet, was in der Absender-Zeile ver- sprochen wurde, dann schau mal ein paar Zeilen weiter oben ;-) Note 2: If you can't find what I've promised in the From-line, then then have a look at some of the lines above ;-) -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.4 (GNU/Linux) iD8DBQFAf8Dc2wyvT2WDeWYRAnL4AJ9ZwW2VVNDwmliE5y2mZjOh1nayUgCgtezc SaYvtxHSFSDSqb8H5goGpQM= =ZOzo -----END PGP SIGNATURE----- From bram at nospam.sara.nl Mon Apr 26 09:04:28 2004 From: bram at nospam.sara.nl (Bram Stolk) Date: Mon, 26 Apr 2004 15:04:28 +0200 Subject: interfacing to a remote excel app Message-ID: <20040426150428.69010a3c@pistache.sara.nl> pyHello, Google helped me find a nice package to interface python with MS Excel. "win32all", or sometimes called by the name "pywin32". http://starship.python.net/crew/mhammond/ However, this win32all extension seems to be specifically built for the windows platform only. What could I use if I want to interface to excel from a python interpreter running on a remote UNIX machine? The specific task I want to accomplish is as follows: I want python on UNIX to be able to make selections in excel (highlight rows). Also, I want to have changes in the selected (highlighted) items in excel to be communicated to the python running on UNIX. What would be the best way to do this? Thanks, Bram PS: A possible approach would be to run two interpreters, one on both platforms, and have the MS python talk to excel. However, I would like a solution with low-impact to the MS platform, and want to get away without having to install python and win32all on the MS machine. -- ------------------------------------------------------------------------------ Bram Stolk, VR Engineer. SARA Academic Computing Services Amsterdam, PO Box 94613, 1090 GP AMSTERDAM email: bram at nospam.sara.nl Phone +31-20-5923059 Fax +31-20-6683167 "For the costs of subsidized agriculture in the EU, we can have all 56 million European cows fly around the world. First Class." - J. Norberg ------------------------------------------------------------------------------ From edcogburn at hotpop.com Thu Apr 1 06:46:13 2004 From: edcogburn at hotpop.com (Ed Cogburn) Date: Thu, 01 Apr 2004 06:46:13 -0500 Subject: [OT] Top posting is a PITA [was : Prothon Prototypes vs Python Classes] In-Reply-To: <106lrnu8g89iq75@corp.supernews.com> References: <569c605ld1cj8fc1emolk08ete0s1prls1@4ax.com> <106di86neu1qh4d@news.supernews.com> <4069a001$0$4237$afc38c87@news.easynet.co.uk> <4069e9d9$0$8915$636a15ce@news.free.fr> <106lrnu8g89iq75@corp.supernews.com> Message-ID: R Baumann wrote: > one follows the "standard" of the newsgroup one is participating in. No such thing, since there is no way to enforce these "standards", and the bottom-posters will always bottom post, and the top-posters will always top post no matter where they are. > Complaining whether one top posts or bottom posts is just a waste of > time, and you, me, we, all know it. Not always, sure there are the smart asses who top-post just to annoy people, but a lot of top-posters do that because they are newbies and don't know that it annoys so many people. Often they just need to find out how to change their reader program's default, or simply discover that their reader does have such an option. > this is more irritating than whether one is "posting in the approved manner". No it isn't, as long as someone sticks "OT" in the subject line, I don't mind anyone talking about something else. If its identified as off topic, I can always skip it. Top-posting on the other hand, is annoying because its unnatural for most of us. Most of us may not say anything, and most of the time its not "serious", but IMO, top-posting is far more irritating then OT posts. > This thread was renamed to a different subject, but that was a > half-dozen rants later in the thread than it needed to be. Why complain about this when you're obviously still participating in this thread two *dozen* posts after "OT" was inserted? > Get my point? Naw, too much to expect. I've wasted both your time and my > time with my own rant against your rants. :-) Yep, everyone has their pet peeve, but isn't it kinda obvious by now that there are a *lot* more people peeved about top-posting than there are peeved at OT posts. :) > A lot of you guys seem far more interested in starting arguments and keeping > them running, than you are discussing the pros and cons of Python and > providing helpful answers. Rein in your egos, no one, and I include myself, > has anything helpful to contribute in this kind of "dust-up". I've seen this complaint a thousand times too, and it never makes a difference. You're basically asking people to stop being human, which is why we designated "OT" as a warning for others that the conversation has drifted far afield. However, we never did adopt "TP" so top-posters could warn others, mainly because top-posting is not seen as inevitable, irresistible human behavior, it is of course simply an example of laziness (or ignorance), nothing more. While laziness is inevitable in some humans, its still not accepted behavior. People arguing with one another is perfectly natural, and has been going on for millenia, but for most of the world, its written conversations are done top-to-bottom, not bottom-to-top. From harry.g.george at boeing.com Thu Apr 22 12:46:14 2004 From: harry.g.george at boeing.com (Harry George) Date: Thu, 22 Apr 2004 16:46:14 GMT Subject: Convert hexadecimal string to binary References: Message-ID: ekoome at yahoo.com (Eric) writes: > Guys, > I have the following hexadecimal string - '\xff\xff\xff' which i need > to convert to binary. > > How would i go about doing this? > > Eric Assuming you mean the result is a string of "1" and "0" chars, here is a mechanism. We use a lookup to avoid converting to and from internal numbers. #---x is the data--- x='\xff\xff\xff' #---notice it is actually a sequence of 8-bit bytes--- #---generate a dictionary of all 256 values and their binary codings--- bits={'\x00':'00000000', '\x01':'00000001', .......... '\xff':'11111111'} #---collect answer in buffer--- s=StringIO.StringIO() for byte in x: s.write(bits[byte]) #---report result--- print s.getvalue() -- harry.g.george at boeing.com 6-6M21 BCA CompArch Design Engineering Phone: (425) 342-0007 From henkjan at xs4all.nl Sat Apr 24 14:12:59 2004 From: henkjan at xs4all.nl (Henk-Jan de Jong) Date: Sat, 24 Apr 2004 20:12:59 +0200 Subject: deleting items within a for loop - mutable indices References: <4089cb21$1_2@mk-nntp-2.news.uk.tiscali.com> Message-ID: <408aae2a$0$557$e4fe514c@news.xs4all.nl> Hello, this should work: for i in deletion_list: x.remove(i) Matuka "SnuSnu" wrote in message news:4089cb21$1_2 at mk-nntp-2.news.uk.tiscali.com... > Okay - here's a (probably) really easy question: > > I can't do the following, so what's the best way to handle this > case of wanting to delete within a loop? > > x = [0,1,2,3,4,5,6,7,8] > deletion_list = [2,7,8] > > for i in deletion_list: > del x[i] > > This obviously doesn't work because the list keeps changing > each time I delete something, so the indices are no longer valid > after the first delete (so I get an IndexError on teh last delete). > > My hack is to do this first (which makes sure that the higher indices > are deleted first), but this is not very elegant or quick: > > deletion_list.sort() > deletion_list.reverse() > # BTW: It's a shame I can't do deletion_list.sort().reverse() > > Is there a simple solution? > > (It would be nice to do something like > del x[2,7,8] # or.. > del [*deletion_list] > ) > > Thanks. > From rogerb at rogerbinns.com Thu Apr 29 22:26:20 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Thu, 29 Apr 2004 19:26:20 -0700 Subject: Don't understand wxPython ids References: <408ed938$0$17263$a1866201@newsreader.visi.com> <1a34m1-fml.ln1@home.rogerbinns.com> Message-ID: Greg Ewing wrote: > Giving an identifier to a command so that it can be > invoked in multiple ways is a good idea, but it would > be much more Pythonic if a *name* could be used as the > identifier rather than a number. That is kinda what my code is doing :-) The name just happens to be a static class member mapped to an integer. > Use of a number here seems to be entirely the result > of blindly carrying over a feature of the C++-oriented > API into Python. There has been much debate about this on the wxPython lists. One school of thought is to make wxPython as "Pythonic" as possible, with its own set of documentation and own community. The fact that there is a C++ library underneath would be a minor implementation detail. A second school of thought (to which I belong) is that wxPython should stick to the C++ API closely unless changes significantly improve developer productivity. The means that wxPython remains a member of the wxWidgets community, the standard wxWidgets documentation remains the same and appropriate, and it is easy to translate C++/Perl/other language wxWidgets programs into wxPython and vice versa even for the people who do not know the languages. Of course there is no "right answer" as to what is best, and ultimately it is up to Robin and his good taste. At the moment wxPython is largely in the second camp, with some amount of the former present. Some people have implemented stuff in the former camp on top of wxPython (eg wax). People are of course welcome to criticise wxWidgets, but as someone who as actually done programs on multiple different platforms and GUI toolkits, I am very impressed. I'll listen to people who have actually written something that runs on several platforms and operating systems first. Roger From lbates at swamisoft.com Wed Apr 28 15:17:39 2004 From: lbates at swamisoft.com (Larry Bates) Date: Wed, 28 Apr 2004 14:17:39 -0500 Subject: Using C libraries References: Message-ID: Depends on what you mean by "difficulties". I've interfaced Python with lots of different .DLL libraries. The "tricky" part is getting enough information about the proper data structures for calling the external functions. Much study of struct module is normally required. And you need either my DLLInterface code: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146847 or you can use Thomas Heller's ctypes module: http://starship.python.net/crew/theller/ctypes/ Or you can roll your own... Larry Bates Syscon, Inc. "Laughlin, Joseph V" wrote in message news:mailman.92.1083177600.25742.python-list at python.org... Has anyone had any difficulties using C libraries / data structures with python? Are there any things I need to be aware of? Joe Laughlin Phantom Works - Integrated Technology Development Labs The Boeing Company From fredrik at pythonware.com Tue Apr 20 02:21:32 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 20 Apr 2004 08:21:32 +0200 Subject: Tkinter: Selecting one item in each of two listboxes References: Message-ID: Jeffrey Barish wrote: > I have an application that produces two listboxes. I would like to be > able to select one of the items in the first listbox and one of the > items in the second listbox. However, when I make my selection in the > second listbox, the selected item in the first listbox gets deselected. > Is there a way to do this? I tried setting selectmode to MULTIPLE, but > that option only allows me to select multiple items in one of the > listboxes (both of which get deselected when I make a selection in the > second listbox). see the discussion of "exportselection" on the listbox patterns page: http://www.pythonware.com/library/tkinter/introduction/listbox.htm => patterns From bug-gs at ghostscript.com Tue Apr 6 01:43:49 2004 From: bug-gs at ghostscript.com (bug-gs at ghostscript.com) Date: Tue, 6 Apr 2004 14:43:49 +0900 Subject: hi Message-ID: <200404060539.OAA25306@tcimdv001.tonami.mec.mei.co.jp> ------------------ Virus Warning Message (on mail1) Found virus WORM_LOVGATE.W in file body.scr The uncleanable file is deleted. --------------------------------------------------------- -------------- next part -------------- The message contains Unicode characters and has been sent as a binary attachment. -------------- next part -------------- ------------------ Virus Warning Message (on mail1) body.scr is removed from here because it contains a virus. --------------------------------------------------------- From gabriel.cooper at mediapulse.com Tue Apr 13 15:33:22 2004 From: gabriel.cooper at mediapulse.com (Gabriel Cooper) Date: Tue, 13 Apr 2004 15:33:22 -0400 Subject: Trouble installing Python on RedHat 9 Message-ID: <407C4082.6040503@mediapulse.com> I have this old PC I'm using as a development box to emulate my work environment, only I don't know much about the admin side of linux, so I'm having very newbie-type problems getting started. I have red hat 9 on an old PC and I'm trying to install an updated version of python. Currently I think it has python 2.2 but I wanted to update to 2.3 for the sake of knowing I could do it, so I downloaded the tarball, uncompressed it, then ran ``./configure --prefix=/usr`` to compile it such that it would overwrite the 2.2 install. Everything went OK with configure so I ran make, which died giving parse errors in some tk file. After some reading some I came across this: "If you're compiling from source on Red Hat 9, RH9 compiles Tcl/Tk as UCS-4, but Python still defaults to UCS-2. You can either use ./configure --enable-unicode=ucs4 with Python, or you can try Anthony Baxter's patched version of Tcl/Tk" So I tried that, along with my prefix= parameter but I still get the same error. I grabbed my red hat 9 disks and found an RPM labelled "tk-something" so I installed that and tried again, but got the same errors (or what appear to be the same errors). Anyway, here's a small snippet of what ``make`` throws at me: [...] gcc -pthread -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -fPIC -fno-strict-aliasing -DWITH_APPINIT=1 -I/usr/X11R6/include -I. -I/root/packages/Python-2.3.3/./Include -I/usr/local/include -I/root/packages/Python-2.3.3/Include -I/root/packages/Python-2.3.3 -c /root/packages/Python-2.3.3/Modules/_tkinter.c -o build/temp.linux-i686-2.3/_tkinter.o In file included from /root/packages/Python-2.3.3/Modules/_tkinter.c:71: /usr/include/tk.h:83:29: X11/Xlib.h: No such file or directory In file included from /root/packages/Python-2.3.3/Modules/_tkinter.c:71: /usr/include/tk.h:581: parse error before "Bool" /usr/include/tk.h:583: parse error before "event" /usr/include/tk.h:584: parse error before "root" /usr/include/tk.h:585: parse error before "subwindow" /usr/include/tk.h:586: parse error before "time" /usr/include/tk.h:586: `time' redeclared as different kind of symbol /usr/include/time.h:184: previous declaration of `time' /usr/include/tk.h:591: parse error before "same_screen" /usr/include/tk.h:597: parse error before "Bool" [...] Any ideas? If I just need to RTFM, let me know which "M"! ;) Thanks! From fredrik at pythonware.com Wed Apr 21 12:43:40 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 21 Apr 2004 18:43:40 +0200 Subject: Stupid Regex Question References: Message-ID: Jonas Galvez wrote: > I'm feeling dumb: > > str = "textmoretexttext" > > How can I get a list like ["textmoretext", > "text"] using regexes? I'm starting to believe it's not possible. print re.findall("(.*?)", str) From johnc_tan at hotmail.com Fri Apr 16 20:28:00 2004 From: johnc_tan at hotmail.com (John) Date: Fri, 16 Apr 2004 20:28:00 -0400 Subject: Initializing Python in Optimized mode from C++ References: <4080635b$0$46515$39cecf19@news.twtelecom.net> Message-ID: "Rick Ratzel" wrote in message news:4080635b$0$46515$39cecf19 at news.twtelecom.net... > set Py_OptimizeFlag to 1 for -O, and 2 for -OO. Do this prior to > calling Py_Initialize(); > > You can also improve your startup time by setting > Py_NoSiteFlag = 1...assuming you don't need to load site.py > > for example: > > extern int Py_OptimizeFlag; > extern int Py_NoSiteFlag; > ... > if( !Py_IsInitialized() ) { > Py_OptimizeFlag = 2; > Py_NoSiteFlag = 1; > Py_Initialize(); > } I was viewing this thread from Google groups and didn't see your response before I replied. This is exactly what I was looking for...thanks! Out of curiosity, what does the -OO flag do on top of the normal optimizations? From loic at yermat.net1.nerim.net Thu Apr 22 15:11:41 2004 From: loic at yermat.net1.nerim.net (Yermat) Date: Thu, 22 Apr 2004 21:11:41 +0200 Subject: Proper Way of checking for a collections class In-Reply-To: References: Message-ID: Robert Brewer a ?crit : > Gary Coulbourne wrote: > >>I've been trying to find a good idiom for testing if the input to a >>function is one of the collections classes... the best I >>could do is this: >> >>if hasattr(thing_to_test, '__iter__'): >> ... > > > The best way depends upon (and mirrors) exactly what you want to do with > those classes. If you're going to call iter(thing), then the above is > fine. If instead you want sequences, try operator.isSequenceType, > etcetera. > > > FuManChu > I don't think so ! For example, String has no __iter__ method but is iterable ! I would do : try: it = iter(thing_to_test) except TypeError: it = None if it: for var in it: do stuff... -- Yermat From matt.warren at zoom.co.uk Thu Apr 1 04:56:23 2004 From: matt.warren at zoom.co.uk (Matt Warren) Date: 1 Apr 2004 01:56:23 -0800 Subject: win32com support (follow up to previous thread) Message-ID: <500826d0.0404010156.737ab682@posting.google.com> Does this mean that there isn't a way to put a button into Visual Studio 6.0 and then have it execute python code all purely done in python. I.e could I write a python program that puts a button in the msdev toolbar like the outlook.py example and then when its pushed reformats the current document, using the Application.Document.SelectAll() com methods or something like that. Cheers Matt >> Generally, you can do a QueryInterface for the object. However, if >> the object does not support IDispatch, you will haver trouble - we >> don't support arbitrary interfaces when calling them, only >> implementing them. >> >> ob = ob._obj_.QueryInterface( >> > >I take it the chances of this working are slim to none ? > >> >> The GUID must be for a type library. If you run "makepy.py -i", then >> you will get a list of all valid typelibs you can use, and the params >> for it. >> > >Bum! > >Perhaps I should look at implementing the actual addin in C++ and then >embed python into it so that most the work can be done by that. > >Thanks for your help anyway > >Rich From maxm at mxm.dk Fri Apr 2 07:00:24 2004 From: maxm at mxm.dk (Max M) Date: Fri, 02 Apr 2004 14:00:24 +0200 Subject: Prothon, metaclasses, Zope [Was: A 'Python like' language] In-Reply-To: References: <95aa1afa.0403272243.78d60724@posting.google.com> <95aa1afa.0404010017.2f1683b8@posting.google.com> Message-ID: <406d55c6$0$206$edfadb0f@dread12.news.tele.dk> Mark Hahn wrote: >>it is difficult to give credit to people liking tabs and > > As far as top-posting, I am trying to improve, it's just hard to change my > reply style after using it for 30 years without getting any complaints > before. I feel like I'm in a twilight-zone episode. Actually I am too. There is some interresting dynamics going on here. Appart from that Brandon guy, I have never experienced such a reaction before in this group. I hope it is just a fluke. regards Max M From paul at prescod.net Sun Apr 4 14:14:40 2004 From: paul at prescod.net (Paul Prescod) Date: Sun, 04 Apr 2004 11:14:40 -0700 Subject: Newbie TypeError problem In-Reply-To: References: Message-ID: <40705090.7010100@prescod.net> Francis Moore wrote: > File "D:\Python23\lib\xml\sax\expatreader.py", line 111, in > prepareParser > self._parser.SetBase(source.getSystemId()) > TypeError: SetBase() argument 1 must be string, not member_descriptor > > Seems to be failing on the line: > > parser.parse(file) Please insert this line into your program: print type(file) Perhaps the type is something other than you expect? Paul Prescod From deetsNOSPAM at web.de Fri Apr 2 06:45:57 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Fri, 02 Apr 2004 13:45:57 +0200 Subject: Travelling salesman variation in python References: Message-ID: You could go for local search. First, create a randow tour. Then select a neighborhood. Find the local minimum for that neighborhood. Do this as often as you like. A typical neighborhood for tsps are four nodes where two of them are adjacent in your tour. Then exchange the nodes so that they still form a tours. If that has less costs, keep it that way. --n1--n2-- --n3--n4-- becomes --n1\/n2-- --n3/\n4-- -- Regards, Diez B. Roggisch From peter at engcorp.com Mon Apr 5 12:12:52 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 05 Apr 2004 12:12:52 -0400 Subject: design by contract versus doctest In-Reply-To: <407174ea$0$5066$4d4ebb8e@news.nl.uu.net> References: <407174ea$0$5066$4d4ebb8e@news.nl.uu.net> Message-ID: aku wrote: > Isn't it so, that by applying DBC, a lot of unittests can be > made redundant? How would you propose verifying that your code will work if you don't run tests before you ship? Don't say "manual testing"... -Peter From mlh at furu.idi.ntnu.no Sat Apr 24 11:15:45 2004 From: mlh at furu.idi.ntnu.no (Magnus Lie Hetland) Date: Sat, 24 Apr 2004 15:15:45 +0000 (UTC) Subject: Regexp optimization question References: Message-ID: In article , Paul McGuire wrote: [snip] > > pyparsing supports this kind of text skipping, using scanString() > instead of parseString(). I already have a working implementation in Python -- if this isn't more efficient (I'm just talking about the tokenization part) I don't think there would be much gain in switching. (IIRC, the pyparsing docs say that pyparsing is slow for complex grammars, at least.) BTW: I have not done some experiments with Plex with lots of regular expressiosn; simply compiling a pattern with 500 alternatives took forever, whereas re.compile was quite fast. So... If I can somehow be content with only getting one match per position, I guess re is the best solution. Or I could implement something in C (Pyrex)... (Or use something like pybison.) -- Magnus Lie Hetland "Wake up!" - Rage Against The Machine http://hetland.org "Shut up!" - Linkin Park From jepler at unpythonic.net Sun Apr 4 14:24:26 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Sun, 4 Apr 2004 13:24:26 -0500 Subject: Processes with strange behavoir In-Reply-To: References: Message-ID: <20040404182426.GE3455@unpythonic.net> "exit" -> doesn't do anything "exit()" -> does something Jeff From See_my at Signature.com.invalid Tue Apr 20 05:17:44 2004 From: See_my at Signature.com.invalid (Tuxtrax) Date: Tue, 20 Apr 2004 09:17:44 GMT Subject: emacs for OS X Message-ID: Hi all My editor of choice on linux for python, bar none, is xemacs. I love the python mode that detects a python file and handles indentation and coloration for me automagically. I have been using a powerbook for a while now, and I finally found emacs for aqua in OS X Jaguar (10.2.8). I downloaded it from porkrind.com. The version of emacs is 21.3 I believe. Anyway, not only does it *not* detect python files automatically, but it tries to use fundamental mode to handle them which is a pain in the ass. I want my coloring and indentation back, damn it all! I found python-mode.el in the python distribution folder, but not only do I have no clue as to what to do with it, I can't find an emacs folder or a .emac file. Just the emac program. Any help with this would be greatly appreciated. If you have overcome this yourself I especially want to hear from you. In other news..... I have a code question for you all. This one is a real trip. I am trying to use NNTPLIB to download just the message numbers and "from" fields for any specified number of messages I want, from 1 to 10,000. So far so good. But when I play by the rules, I get unpredictable results. If I ask for 20 from headers I get one. If I ask for 500, I get a couple. If I ask for 6000, one time I might get 500, the next time I might get 2,300. It is very frustrating. Here is the code soundbite: response, number_of_messages, first_available_message, last_available_message, groupname = n.group(newsgroup) ############### # Do we need to create run time files from server download? # This section takes care of it if it needs to be done. if dbuild_flag == 1 or fexist(database_shelve+".db") == 0: # Retrieve and print From: information # The NNTPlib xhdr routine returns a list of nested sublists. Each # sulist contains a pair - message number, requested header in string # form. message_request = getinput("\nHow many posts should I be interested in? [max 10,000]") if int(message_request) > int(number_of_messages): print "\nRequest exceeds current available message count. Adjusting to %s posts" % number_of_messages message_request = number_of_messages elif int(message_request) > 10000: print "\nRequest exceeds program capacity. Assuming max of 10,000 posts, and continuing ...." message_request = "10000" last_message = str(int(first_available_message) + int(message_request)) stringrequest = first_available_message+"-"+last_message print "\nRetrieving list of first %s newsgroup participants" % message_request print "\nI'm working ..............." # This is what should work reliably and is not: response, poster = n.xhdr("from", stringrequest) ################## Now when I make my xhdr request using the full range of messages as told to me by: response, number_of_messages, first_available_message, last_available_message, groupname = n.group(newsgroup) by changing: stringrequest = first_available_message+"-"+last_message to: stringrequest = first_available_message+"-"+last_available_message I get reliable results every time. Anyone care to help me on this one? It simply makes no sense that I should be able to get reliable results only when I ask for all 48,000 "from" message headers available from my newsgroup of choice. I have verified, by the way, that last_message is a properly formed string in the format needed by xhdr. thanks, and best regards, Mathew -- ROT 13 this address to mail me: bar jbeq abg guerr; uvtu qrfreg zna, gura nqq - ng lnubb qbg pbz. From bokr at oz.net Tue Apr 27 16:09:42 2004 From: bokr at oz.net (Bengt Richter) Date: 27 Apr 2004 20:09:42 GMT Subject: Regexp optimization question References: Message-ID: On Fri, 23 Apr 2004 22:56:38 +0000 (UTC), mlh at furu.idi.ntnu.no (Magnus Lie Hetland) wrote: >In article , William Park wrote: >[snip] >> >>Since you want both the matched strings and their locations in file, you >>pretty much have to this manually, one by one. > >Well -- that's more or less what I'm doing. (Or -- I can get the match >objects all at once, of course, using finditer.) > >I guess I'll have to look elsewhere for performance improvements. Hm. > Have you tried something like this? >>> s = 'asdad foobaz rhubarb pie' >>> import re >>> rxo = re.compile(r'(foo|bar|baz)') >>> rxo.split(s)[1::2] ['foo', 'baz', 'bar'] Regards, Bengt Richter From martin at v.loewis.de Sat Apr 10 04:28:37 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 10 Apr 2004 10:28:37 +0200 Subject: print u"\u0432": why is this so hard? UnciodeEncodeError In-Reply-To: References: Message-ID: David Eppstein wrote: > A system that requires me to manually set the LANG environment variable > is no better than a system that requires me to manually define an > encoding once in Python. Perhaps: depending on your criteria to judge "no better". It does demonstrate that Python can be made to determine the terminal's encoding, without changing any kind of Python or C source code. Regards, Martin From claird at lairds.com Sat Apr 3 18:02:26 2004 From: claird at lairds.com (Cameron Laird) Date: Sat, 03 Apr 2004 23:02:26 -0000 Subject: emergent/swarm/evolutionary systems etc References: Message-ID: <106ugk2brruis3a@corp.supernews.com> In article , Josiah Carlson wrote: >> rules. Given that I have only a basic foothold on the language, does >> anybody foresee difficulties for me learning enough to impliment simple and >> experimentally flexible sim-city style simulations (minus fancy graphics and >> llamas) in no more than 2 months (to allow for time to conduct actual >> experiments + field observations etc)? I would be able to engender aid from >> various staff, and the university library should carry titles on the >> subject. Failing that, I could do it the old fashioned way and buy a how-to >> book, but I'd like some opinions on the difficulty of the goal from people >> who've already trancended the non-programmer/programmer barrier. > > >Two months is a pretty tight schedule. If you're on your toes, I would >bet you could learn enough of the langauge to support your ideas in 2 >months. Actually programming the thing in 2 months; I wouldn't be able >to make that kind of judgement about your abilities. . . . Bluntly, I'd bet against it. There's a daunting amount of new material you'll need to learn. My advice: we can help you refine your project so that the computing part is less overwhelming. 'You read von Thunen, by the way? -- Cameron Laird Business: http://www.Phaseit.net From jcarlson at uci.edu Sat Apr 3 21:18:57 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Sat, 03 Apr 2004 18:18:57 -0800 Subject: OT (was Re: But it still doesn't explain the joke) In-Reply-To: <406F3C29.6030504@freedom.place> References: <106o7vn56fgmt85@corp.supernews.com> <406F3C29.6030504@freedom.place> Message-ID: > The father is put in an awkward position of having to explain how he is > not a traitor to his country of birth. Not necessarily, the whole "under god" clause, that has caused basically all of the legal issues in the last few decades, is the result of McCarthy-era foolishness. http://www.religioustolerance.org/nat_pled1.htm Really, he's standing up for his child's rights. Had that clause not been there, this lawsuit (and other similar ones) would not have even been brought to court. Bush invades Iraq (killing thousands of innocents), lies about his reasons for it, gets caught in his lie, and lies some more. Oh, and he's currently up for reelection. You tell me, who'se the traitor? - Josiah From ajw140NO at SPAMyork.ac.uk Thu Apr 29 13:01:22 2004 From: ajw140NO at SPAMyork.ac.uk (Andrew Wilkinson) Date: Thu, 29 Apr 2004 18:01:22 +0100 Subject: ANN: PyLinda 0.1 Message-ID: PyLinda 0.1 By Andrew Wilkinson Contents -------- 1. Introduction 2. Installation 3. Using Linda 4. Known Problems 5. Contact 6. License 1. Introduction --------------- Linda is an widely studied distributed computing environment, centered around the notion of a tuple space. A tuple space is a bag (also called a multi-set) of tuples. A tuple is an ordered, typed chunk of data. Tuple spaces exist independently of processes in the system, and the data placed into a tuple space also exist independently. See "Generative communication in Linda" (1985) and "Multiple tuple spaces in Linda" both by David Gelernter for more information on Linda. PyLinda is a simple implementation of a linda system, however it also includes several of the more recently proposed extensions to Linda in the form of multiple tuple spaces, garbage collection, sane non-blocking primitives and bulk tuple operations. 2. Installation --------------- To install simply unpack the tarball, and execute 'python setup.py install'. PyLinda requires a Python 2.3+ and has only been tested on Linux and Solaris, however it should be possible for it to other operating systems. It may be possible for the server and some client programs to run under Windows, however since it does not support 'fork' several of the included examples will not work. 3. Using Linda -------------- First a server must be started - 'linda_server.py'. Then a client program must be started, the simplest is just the python interactive interpreter. bash$ python >>> import linda >>> linda.connect() >>> linda.universe._out((1,2,3)) Now quit that interpreter, and start a new one... bash$ python >>> import linda >>> linda.connect() >>> linda.universe._in((int, int, int)) (1, 2, 3) If you want to add a new computer to the linda network simply run 'linda_server.p -c' where the computer you supply is already running a linda server. 4. Known Problems ----------------- * The actual implementation is quite slow. The process of storing tuples is slow and uses a large amount of memory, this could probably be fixed by rewriting that bit in C. * No support for the eval primitive. * Only built in types (and tuplespace references) can be included in tuples. This will change in the future, and is the subject of my PhD. * Documentation is very thin and could do with improving. People with some knowlege of Linda should not have a problem using PyLinda however. 5. Contact ---------- All the latest news and information about PyLinda can be found at http://www-users.cs.york.ac.uk/~aw/pylinda. Comments, suggestions and bug reports are all welcome at aw at cs dot york dot ac dot uk 6. License ---------- For full details of the license see the file LICENSE. Copyright 2004 Andrew Wilkinson . This file is part of PyLinda (http://www-users.cs.york.ac.uk/~aw/pylinda) PyLinda is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. PyLinda is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with PyLinda; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA From peter.maas at mplusr.de Fri Apr 2 07:09:35 2004 From: peter.maas at mplusr.de (Peter Maas) Date: Fri, 02 Apr 2004 14:09:35 +0200 Subject: Python conference slogan In-Reply-To: References: <30260531.0404010833.1b834032@posting.google.com> <406C4DDF.5000907@zope.com> Message-ID: <406D57FF.4040601@mplusr.de> Peter Maas wrote: > As Iunderstand this thread there is a need for a slogan that is short, > not too hard to understand and unforgettable (probably a definition > of the word slogan). Python insiders don't need a slogan at all. Something like - Python - there's no better way to code. [stolen from: Lufthansa - there's no better way to fly] - Your brain would choose Python. [stolen from: Your cat would by Whiskas :)] - Python fits your brain. - Unleash your brain with Python. - Python - the natural programming language Mit freundlichen Gruessen, Peter Maas -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Hubert-Wienen-Str. 24 Tel +49-241-93878-0 Fax +49-241-93878-20 eMail peter.maas at mplusr.de ------------------------------------------------------------------- From __peter__ at web.de Fri Apr 16 16:06:35 2004 From: __peter__ at web.de (Peter Otten) Date: Fri, 16 Apr 2004 22:06:35 +0200 Subject: empty window when using askopenfile References: Message-ID: Sorin Gherman wrote: > Is there any way to minimize/hide the annoying default, empty Tk > window that shows behind the native file opening dialog , when using > askopenfile, etc, in tkCommonDialog? import Tkinter, tkFileDialog root = Tkinter.Tk() root.withdraw() tkFileDialog.askopenfile() Peter From has.temp2 at virgin.net Sat Apr 3 18:05:31 2004 From: has.temp2 at virgin.net (has) Date: 3 Apr 2004 15:05:31 -0800 Subject: HTML writer References: Message-ID: <69cbbef2.0404031505.770b3716@posting.google.com> "Moosebumps" wrote in message news:... > Is there a standard solution for writing HTML web pages with Python? I > don't know that much about web programming, but basically I want to generate > some internal reports on a web page. First ask yourself if you need to generate pages dynamically, or is pre-rendering and serving them up statically fine? The latter is much, much simpler to code for. For what you describe this may be all you need. There's no shortage of frameworks for doing the former though (I believe Quixote is well regarded as a "programmer-friendly" solution, for example). For templating, as long as you're comfy with a modicum of OO programming then I'd recommend my HTMLTemplate module: . Compiles HTML templates to a simple Python object model than can be manipulated programmatically. Small and simple with no external dependencies, clean separation between code and markup, and a very clean, compact API; easily outstrips the old-school bloatware ASP/PSP-style systems with their horrible code-in-markup soup. On the offchance you need to do arbitary markup generation (for generating really irregular tables and stuff that can't easily be templated), there's always HTMLgen but it's pretty old and hoary now. Donovan Preston's Nevow.Stan module is much more modern; see for an introduction. > I know there newer things like CSS and XHTML -- are these more or less > effort to generate? i.e. are they more complicated, or do they have more > uniform syntax? What do they necessarily buy you? CSS (cascading style sheets) are for styling (and - if you're brave - page layout). Absolutely fine for styling text (waaay nicer than using tag crap). Many browsers still have problems with more complex presentational stuff, but it doesn't sound like you'll be needing that. Not something you should have to generate programmatically - whole point of CSS being you just write it once and apply it to your entire site. XHTML is just a tidied up version of the HTML standard; enforces a few things that were optional in HTML, e.g. correct closing of element tags, the main advantage of this being it can be parsed, manipulated, etc. as XML. > I am an experienced > programming, but I don't know that much about all the alphabet soup that is > web programming. Yeah, there's a lot o' crap to avoid out there. Still, a good start'd be finding yourself a nice modern introduction to writing HTML and CSS, and go from there. There's scads of stuff online for this - main problem's knowing the good from the bad. Reckon you some find some good links at (though you may have to sift through a bit of geeky buzzword evangelism waffle to get to it:). You won't need the advanced stuff and the basics are easy. (Honest. Hint: if a tutorial makes it sound complicated, find a better tutorial!) HTH From claird at lairds.com Mon Apr 19 09:32:02 2004 From: claird at lairds.com (Cameron Laird) Date: Mon, 19 Apr 2004 13:32:02 -0000 Subject: Goodbye TCL References: <0LudnSads6NmpuPdRVn-vw@centurytel.net> <21ccedf1.0404160639.14c2d852@posting.google.com> <1080ml0hdpp6tdf@corp.supernews.com> Message-ID: <1087l6i1a67ml31@corp.supernews.com> In article , Donal K. Fellows wrote: >Cameron Laird wrote: >> 'Different way to say this: "database", in this sense, is a dirty >> subject, in that it's far more tied to grungy details of specific >> implementations than the masses generally realize, or than either >> Python or Tcl, both of which prize purity in their own ways, >> generally support. A general database abstraction is about as >> rarefied as a general GUI abstraction. > >I had a quick look into general DB APIs in the past, and the response I >got from the DB community at the time was "but this doesn't support this >*vital* feature only implemented in one DB that 0.01% of users really >need and therefore we could never ever use your proposal for a standard >API". It's kind of discouraging. > >FWIW, I think some mostly-common subset of functionality is possible (if >we assume SQL underneath; without that, you can't get anywhere) and it >would be enough to get most of the low-end and casual users total >satisfaction. And maybe this would encourage alteration in the high-end >interfaces to be more like each other too. > >Donal. > Yeah; I've written database abstractions, going back to before there was a Tcl. *I* like them fine. To me, though, they don't feel like something that belongs in the core. -- Cameron Laird Business: http://www.Phaseit.net From hemanth_sethuram at yahoo.com Fri Apr 23 02:43:22 2004 From: hemanth_sethuram at yahoo.com (Hemanth P.S.) Date: 22 Apr 2004 23:43:22 -0700 Subject: Python use large scale projects References: <47fc6058.0404212327.24163290@posting.google.com> Message-ID: <9be5e130.0404222243.7cbf1be4@posting.google.com> And combine your use of Python with Leo (http://leo.sourceforge.net), another excellent application developed in Python, and it should make developing and maintaining a large scale project easier than other programming languages/tools. --Hemanth From jbenson at sextans.lowell.edu Tue Apr 13 15:56:38 2004 From: jbenson at sextans.lowell.edu (Jim Benson) Date: Tue, 13 Apr 2004 12:56:38 -0700 (MST) Subject: Trouble installing Python on RedHat 9 In-Reply-To: <407C4082.6040503@mediapulse.com> Message-ID: On Tue, 13 Apr 2004, Gabriel Cooper wrote: > Anyway, here's a small snippet of what ``make`` throws at me: > > In file included from /root/packages/Python-2.3.3/Modules/_tkinter.c:71: > /usr/include/tk.h:83:29: X11/Xlib.h: No such file or directory You need to install XFree86-devel-4.3.0-2 to get Xlib.h Hope that helps, Jim From scrutinizer at gmx.at Sun Apr 4 11:37:55 2004 From: scrutinizer at gmx.at (Francesco) Date: Sun, 04 Apr 2004 17:37:55 +0200 Subject: Python Filemanager and Shell Context Menu Message-ID: Hello Pythonnian's (sorry for crossposting) I have written on the base of Miro Rajic a (still) small filemanager in wxPython. Now I want to add (for Windows XP) a explorer shell context menu. I have no idea, how to accomplish this. For what I can imagine: Either use ctypes and the kernel or shell dll, or win32 extensions. Have someone done such a task before? Can someone help me? Who has interesest and want to join in my project "wxPyAtol"? particulary for the next time: - Testing - support for linux - maybe restructure the program. (it is not very pyhton like) - drag and drop support - leap to wxPython 2.5 latest sources: http://berg.heim.at/anden/421194/wxpyatol.zip SF Site: https://sourceforge.net/projects/wxpyatol/ My Homepage: http://my.heim.at/franciss/ Sorry for my english and thank you in advance. -- Francesco From jeffbarish at starband.net Wed Apr 21 23:49:00 2004 From: jeffbarish at starband.net (Jeffrey Barish) Date: Wed, 21 Apr 2004 21:49:00 -0600 Subject: Tkinter: how to fill values in OptionMenu dynamically Message-ID: Is there a way to fill the values in an OptionMenu dynamically? I need something like the add_command method from Menu. Is there a better way to implement a pull-down list? -- Jeffrey Barish From tjreedy at udel.edu Thu Apr 29 13:53:00 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 29 Apr 2004 13:53:00 -0400 Subject: python 2.3's lambda behaves old fashioned References: Message-ID: "Uwe Schmitt" wrote in message news:c6r3qo$1574k$1 at hades.rz.uni-saarland.de... > I just tried (Python 2.3) Which did not change anything in this regard... > li = [ lambda x: x*a for a in range(10) ] which, except for function __name__ and func_name attributes, translates (unabbreviates) to li = [] for a in range(10): def tem(x): return x*a li.append(tem) del tem which is equivalent to li = [] for a in range(10): def tem(x): return x*__multiplier li.append(tem) __multiplier = a del a, tem > which results in > > li[0](1) = 9 > ... > li[9](1) = 9 As one would expect from second translation above if not the first. Its funny how some people expect default parameter objects to be re-calculated on every call instead of just once, while others sometimes expect global vars to be evaluated just once instead of on every call ;-) The question of whether free vars within lambdas within list comps should get 'early binding' instead of the usual late binding was discussed on Py-Dev list last fall and some this winter. I believe Guido recently said no change. Terry J. Reedy From PPNTWIMBXFFC at spammotel.com Thu Apr 22 03:30:23 2004 From: PPNTWIMBXFFC at spammotel.com (Marco Aschwanden) Date: Thu, 22 Apr 2004 09:30:23 +0200 Subject: Python editors for Windows question References: Message-ID: The best auto-completion you can get for Python is: WingIde http://wingide.com/ Normally WingIDE is quite good at auto-completion but sometimes it needs some help: if wingIde does not "recognize" a class you may add: assert isinstance(btnHello, wxButton) and after that point it will handle this for you too... Good luck, Marco From jcarlson at uci.edu Thu Apr 1 13:44:01 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Thu, 01 Apr 2004 10:44:01 -0800 Subject: Travelling salesman variation in python In-Reply-To: References: Message-ID: > I would appreciate some comments on this :) Look at current TSP algorithms, and exchange their minimization rutines for a maximization rutine. TSP is an NP-hard problem, which means that there is no currently known algorithm for solving it in polynomial time. You can approximate it or do a search on the solution space, but solving it requires searching basically all of the solution space. - Josiah From donn at u.washington.edu Fri Apr 23 16:21:30 2004 From: donn at u.washington.edu (Donn Cave) Date: Fri, 23 Apr 2004 13:21:30 -0700 Subject: Why we will use obj$func() often References: Message-ID: In article , "Mike C. Fletcher" wrote: > Mark Hahn wrote: > >"Mike C. Fletcher" wrote ... > > > > > > > >>$ is basically a character as far as glyphs go, it's a > >>full-height glyph with ascenders and descenders, is very similar to a > >>capital S, and generally makes reading code much harder as it obscures > >>word-shape; .this or even self.this is much easier to read because you > >>can pick out the words using your learned vocabulary of word-shapes. > >> > >> > > > >Well I have a problem now. I gave people on my mailing list a choice > >between $var, `var, ~var, and ^var. The current tally is four votes for > >$var and none for any of the others. According to your criteria, $var is > >the worst and ~var should be the best. Am I correct? > > > Depends on the font ;) . Certainly $ is going to have the most > (negative) impact on readability, but the other three are all basically > lightweight enough that they don't read as characters (basically any > glyph that fills the same space as a lower-case o is going to markedly > change the shape of a word. ` is the least likely to be read as a > character, but is really hard to distinguish from ', so likely not a > great choice. ^ doesn't occupy the middle space, so doesn't get read as > a character either. ~ doesn't read as one either because it doesn't > touch the baseline. > > $, however, is going to be familiar to your PERL aficionados, and > familiarity counts a lot for those who are familiar with it, regardless > of whether it's technically easier to read. The other three are > basically just arbitrary punctuation, so people don't have any > associations built up with them (they don't look at them and > automatically think "attribute access"). The dot character does have > lots of attribute-access associations; hence a leading dot (which > doesn't read as a character) will tend to test favourably on both scales > (practical and familiar). Hm, I do have some associations with the other three, and also with $ in an infix position. Maybe I have more junk than usual in my mental closet, but we are supposed to venerate the aged so I will report without embarrassment that I remember VMS library functions like RMS$PARSE etc. This basically goes along with the argument above - it's a single identifier, $ is not punctuation. VMS is still around, too. The C use of ~ (bitwise negation operator) and ^ (bitwise xor) should be a problem, but otherwise I guess ~ seems like a character to me too. In an infix position. hi~ho vs. hi_ho, same look to me. They are also operators in the Plan 9 rc shell, incidentally - glob match and distributive concatenation, respectively. Any of the four would be an unhappy choice, in my view. Maybe there's some way to use : Donn Cave, donn at u.washington.edu From mday at apple.com Tue Apr 20 19:14:07 2004 From: mday at apple.com (Mark Day) Date: Tue, 20 Apr 2004 16:14:07 -0700 Subject: closing file References: Message-ID: <200420041614070129%mday@apple.com> In article , Marcello Pietrobon wrote: > Once I open a file, for example as: > class MyClass: > def logFileOpen( self ): > self.fdFilenameLog = file( self.filenameLog, 'a' ) > return > > I cannot find in hte documentation how to make sure the file are closed. File objects have a close() method that you can call. See -Mark From alloydflanagan at comcast.net Fri Apr 30 09:58:20 2004 From: alloydflanagan at comcast.net (A. Lloyd Flanagan) Date: 30 Apr 2004 06:58:20 -0700 Subject: Why we will use obj$func() often References: <40887145.789A2FE8@alcyone.com> <7cki80hj976bia36lhf9er97v073o1pqvm@4ax.com> <1082783076.585831@yasure> Message-ID: Greg Ewing wrote in message news:... > Mark Hahn wrote: > > You cannot. Yes it literally means the immediately surrounding function. > > In your example, I can't think of any scheme we've discussed that accesses x > > in function f. Python surely cannot. > > Python can't write to it, but at least it can read it. > Prothon apparently can't even read it. > Actually, when I tried the code I got a NameError. I don't see why I would want to access a variable defined in an inner scope from an outer scope; this seems like a great way to clutter up the namespace and confuse the issue of what the variable actually refers to. From bjornhb3 at yahoo.se Tue Apr 6 05:35:59 2004 From: bjornhb3 at yahoo.se (Bjorn Heimir Bjornsson) Date: Tue, 6 Apr 2004 09:35:59 +0000 (UTC) Subject: Verifying temporal properties. Need problems. References: <68771ca.0404010839.39b0c24f@posting.google.com> Message-ID: Yermat wrote in > Instead of searching the workflow yourself you might look at PyPY. > There is a class (see translator.py) that construct such a flow. Thanks Loic for pointing out pypy's controlflow. I will check if I can use it. I had searched for something like this for Python but never found anything. > On monday, I will show you a kind of workflow I'm creating in case > mine is more complete than yours... It would be really interesting to see what can be done with pypy's controlflow. Bjorn From No.Spam.mc at No.Spam.mclaveau.No.Spam.com Sat Apr 3 13:55:42 2004 From: No.Spam.mc at No.Spam.mclaveau.No.Spam.com (Michel Claveau/Hamster) Date: Sat, 3 Apr 2004 20:55:42 +0200 Subject: Python is faster than C References: <406F0907.96F37EA1@tunes.org> Message-ID: Hi ! For the 1st April, it's finish. From t at REMOVETHISbrowse.to Wed Apr 28 18:17:10 2004 From: t at REMOVETHISbrowse.to (Tom) Date: Wed, 28 Apr 2004 22:17:10 +0000 (UTC) Subject: asp script engine registrition In-Reply-To: References: Message-ID: jianchiwei wrote... > question: > I run > c:\python23\Lib\site-packages\win32comext\axscript\client\pyscript.py > and it told me > Registered: Python > Registration of Python ActiveX Scripting Engine complete. > > But, when I run a asp script > > <%@LANGUAGE=Python%> > <% @LANGUAGE="Python" %> ?? > I still get > HTTP/1.1 500 Server Error > caused by the first line of code "<%@LANGUAGE=Python%>". > It seems to me that python script engine is not correctly registered. > Could someone help me on this please? > Thanks > J.W. > > > > From fma at doe.carleton.ca Thu Apr 15 01:31:19 2004 From: fma at doe.carleton.ca (Fred Ma) Date: 15 Apr 2004 05:31:19 GMT Subject: Kuhlman's tutorials pretty good Message-ID: <407E1E20.D0216E92@doe.carleton.ca> I find Dave Kuhlman's tutorials very good, and very complementary to the stock tutorial that is part of the python download. Even when they cover the same thing, if it's not that clear in one tutorial, reading the other makes it quite clear. But one can swim around the Python website for ages before rummaging into Kulhman's tutorials (Python 101 and 201). I thought it was easy to run into a few days ago. Has the website changed? Aren't Kuhlman's tutorials good enough to sit shoulder-to-shoulder with the other links in "Python for Programmers"? I thought that's where it was before. Granted, it's got a few sections (like Using Regular Expressions and Match Objects, 2.3 & 2.4 of 201) that need editting, but invaluable nevertheless. From the point of view of someone still waiting for Learning Python to come. Fred -- Fred Ma Dept. of Electronics, Carleton University 1125 Colonel By Drive, Ottawa, Ontario Canada, K1S 5B6 From dparsons at cuivre.freenix.fr Tue Apr 27 03:15:59 2004 From: dparsons at cuivre.freenix.fr (dparsons at cuivre.freenix.fr) Date: Tue, 27 Apr 2004 07:15:59 +0000 Subject: Python-list, do you want be better lover? VxoRHRAxRA In-Reply-To: References: Message-ID: An HTML attachment was scrubbed... URL: From Mike at DeleteThis.Geary.com Tue Apr 20 12:20:48 2004 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Tue, 20 Apr 2004 09:20:48 -0700 Subject: CamelCase versus wide_names (Prothon) References: <6ee58e07.0404192141.2229efd6@posting.google.com> <40851128.8000400@mxm.dk> <40851379$0$290$edfadb0f@dread12.news.tele.dk> Message-ID: <108ajf1j55ul61@corp.supernews.com> > Max M wrote: > > Make . a normal letter. > > > > And make _ have the function that . has in Python, so that _ and . sort > > of switches meaning. > > def install.sub.skin(self, out, skin.folder): > """Install a subskin""" > > skins.tool = get.tool.by.name(self, 'portal.skins') > > for skin in skins.tool_get.skin.selections(): > path = skins.tool_get.skin.path(skin) > path = map(string_strip, string_split(path,',')) > if not skin.folder in path: > try: > path_insert(path_index('custom')+1, skin.folder) > except value.error: > path_append(skin.folder) > path = string_join(path, ', ') > skins.tool_add.skin.selection(skin, path) > out_write('Subskin successfully installed into %s\n' % > skin) > else: > out_write('*** Subskin was already installed into %s\n' % > skin) > > > It is allmost freakish how hard that is to read. Interesting... I think you're kidding around, but I actually like that notation quite a bit. The problem I have with names_with_underscores is that the underscore adds too much separation between the words, causing visual confusion over which word belongs to which name. This is especially true in a proportional font. Consider one of the function calls in your code, and for a moment forget your expectations from Python, C, and similar languages: skins.tool_get.skin.selections() If you view that in a proportional font, the visual grouping is vivid: skins.tool is one unit, and get.skin.selections is a separate unit. That big fat underscore is more than twice the width of the tiny little periods, so that's where the visual break occurs. Compare it with the traditional: skins_tool.get_skin_selections(): When I read that code in my mind (again viewing it in a proportional font), I have to make an effort to prevent myself from pronouncing it this way: "skins" (pause) "tool get" (pause) "skin" (pause) "selections". After all, the words "tool" and "get" have only that tiny period in between, while there is a much larger distance between the other words. (In the font I'm viewing this in, underscore is 2.2 times the width of period, and 2.75 times the width of an actual space character!) Of course, in a monospaced font, period, underscore, and space are all the same width, and so many languages use underscore as an "alphanumeric" character and period as a separator that it would probably be confusing to do otherwise. But it's interesting how a proportional font stands all of this on its head, with underscore being so much wider than the other punctuation marks. -Mike From andymac at bullseye.apana.org.au Thu Apr 8 06:30:01 2004 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Thu, 8 Apr 2004 20:30:01 +1000 (EST) Subject: CGI Problems With Xitami In-Reply-To: <8089854e.0404072356.7f33f440@posting.google.com> References: <8089854e.0404072356.7f33f440@posting.google.com> Message-ID: <20040408202708.Y9951@bullseye.apana.org.au> On Thu, 8 Apr 2004, Fuzzyman wrote: > All of a sudden the 'POST' method has stopped working - when I specify > 'POST' as the method in forms... the CGI gets no data... and I really > don't want to use 'GET' as it makes the password visible in the URL... Are you using "python -u" when invoking your CGI script? Unbuffered I/O saves lots of headaches with CGI, especially on Windows. -- 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 RHORDON at uvcs.uvic.ca Fri Apr 30 14:15:28 2004 From: RHORDON at uvcs.uvic.ca (Rhordon Wikkramatileke) Date: Fri, 30 Apr 2004 11:15:28 -0700 Subject: Out of Office AutoReply: Deliver Mail (rhordon@uvcs.uvic.ca) Message-ID: I will be away on business from April 22 to May 10, 2004. Messages will be returned on May 11. In the case of urgent matters, please contact Pat Webster at pwebster at uvcs.uvic.ca or (250) 721-6412 Regards. Dr. Rhordon Wikkramatileke From mauro.baraldi at bol.com.br Fri Apr 23 17:49:20 2004 From: mauro.baraldi at bol.com.br (Mauro Baraldi) Date: 23 Apr 2004 14:49:20 -0700 Subject: Change the color of partial text of a TextBox. Message-ID: Hello, Someone can post some example of how to change the color of text on the TextBox. I try to use the method bind to capture a event like key press, but I don' found a method to change the color of this letter pressed. It's something like Color Delegator of IDLE, but more simple... Thanks Mauro From me at privacy.net Wed Apr 7 04:39:35 2004 From: me at privacy.net (Duncan Booth) Date: 7 Apr 2004 08:39:35 GMT Subject: unpack tuple of wrong size References: Message-ID: Tung Wai Yip wrote in news:c7r57095assq7p777q2ugudnh72qud8kgb at 4ax.com: > However when > t = (1,) > a,b=t > > I got a "ValueError: unpack tuple of wrong size" > > What I want is for a=1 and b=None. Is there a good way to do this? Probably the simplest is: a, b = (t + (None, None))[:2] From jean-michel.caricand at laposte.net Fri Apr 9 02:33:47 2004 From: jean-michel.caricand at laposte.net (Jean-Michel Caricand) Date: Fri, 9 Apr 2004 08:33:47 +0200 Subject: Function args References: Message-ID: Bonjour Michel et mer?i pour la r?ponse tr?s rapide. Je tiens ? pr?ciser que nous d?veloppons en interne en langage Perl. Ma question peut donc sembler b?te pour des programmeurs Python. Apr?s maintes recherches, je n'ai pas trouv? d'exemples me permettant de comprendre le m?canisme employ? par Python pour passer un simple nombre ? une fonction et le modifier r?ellement. Imaginons que je veuille ?crire une fonction qui permute deux variables, j'?cris : def permuter(a,b): c = b b = a a = c Si tout est objet, donc pass? par r?f?rence a et b devraient ?tre r?ellement modifier ? Pourtant ce n'est pas le cas. Pourriez simplement me donner un exemple pour cette fonction. Encore mer?i "Michel Claveau/Hamster" a ?crit dans le message de news: c55f5r$f2l$1 at news-reader4.wanadoo.fr... > Bonjour ! > > En Python, les variables sont des sortes de pointeurs sur des objets. Tout > passage de variable comme param?tres se fait forc?ment par r?f?rence (en > fait, on passe la r?f?rence ? l'objet). > De plus l'affectation d'une variable cr?e un autre objet, car la plupart des > objets ne sont pas modifiables. > > Seuls le sont les listes et les dictionnaires sont modifiables. Une cha?ne > de caract?res n'est pas modifiable non plus. > > Cependant, il existe des modules contenant d'autres types ayant des > comportement diff?rents. Il est ?galement possible de d?finir ses propres > classes, dont on (re)-d?finira le comportement. > > > > PS : il existe aussi un newsgroup fr.comp.lang.python > > > > @-salutations > -- > Michel Claveau > m?l : http://cerbermail.com/?6J1TthIa8B > site : http://mclaveau.com > > From paul at shiningrose.co.uk Tue Apr 27 14:38:14 2004 From: paul at shiningrose.co.uk (p brian) Date: Tue, 27 Apr 2004 19:38:14 +0100 Subject: Trying to write comments after escaping newline Message-ID: Dear all, Weirdly enough i do not think I have come across this before. Perhaps I do not use enough comments.... mystring = "hello " + someVariable + \ "multiple lines 4 clarity" + \ someothervariable print mystring The above works , but if I add comments mystring = "hello " + someVariable + \ #comment "multiple lines 4 clarity" + \ #comment someothervariable #comment it stops working because instead of escaping a newline I am now just escaping a space or tab. Is there some clever thing i have missed? Thanks for any advice paul From bram at nospam.sara.nl Wed Apr 14 11:01:18 2004 From: bram at nospam.sara.nl (Bram Stolk) Date: Wed, 14 Apr 2004 17:01:18 +0200 Subject: spherical coordinates References: <20040414111334.34b5d225@pistache.sara.nl> <7x1xmqua94.fsf@ruckus.brouhaha.com> Message-ID: <20040414170118.0733e51f@pistache.sara.nl> Organization: SARA X-Newsreader: Sylpheed version 0.9.8claws (GTK+ 1.2.10; i686-pc-linux-gnu) Mime-Version: 1.0 Content-Type: text/plain; charset=US-ASCII Content-Transfer-Encoding: 7bit On Wed, 14 Apr 2004 11:06:49 GMT "Paul McGuire" wrote: > > I can imagine that all these conversions could be a performance killer if > done entirely in Python, and could stand to be done as a C extension. This > is probably why the OP was asking if such a package already exists. > Well, performance is not my first concern. I just want encapsulated classes for convenience, that handle all sorts of spherical coordinate specifics. For instance... interpolation between spherical coordinates. You can avoid going to/from cartesian if you properly handle the wrap-around at 180 and 360 degrees. Also, I want to be able to recursively subdivide the theta,phy space, and do stratification in theta,phy space, and al sorts of other operations, on the surface of a given sphere. An encapsulating class for these kind of coordinates would be a help, I thought. Bram -- ------------------------------------------------------------------------------ Bram Stolk, VR Engineer. SARA Academic Computing Services Amsterdam, PO Box 94613, 1090 GP AMSTERDAM email: bram at nospam.sara.nl Phone +31-20-5923059 Fax +31-20-6683167 "For the costs of subsidized agriculture in the EU, we can have all 56 million European cows fly around the world. First Class." - J. Norberg ------------------------------------------------------------------------------ From singleify_me_jjeesstteerr at mmccss.vvuuww.aacc.nnzz Sat Apr 10 02:08:48 2004 From: singleify_me_jjeesstteerr at mmccss.vvuuww.aacc.nnzz (Mike McGavin) Date: Sat, 10 Apr 2004 18:08:48 +1200 Subject: Changing the default string object used by the interpreter Message-ID: <1081577328.739901@bats.mcs.vuw.ac.nz> Hi everyone. I'm wondering if anyone can suggest a way, short of directly hacking the python interpreter, to change the default str class to a different one. ie. So that every time a str instance is created, it uses *my* class instead of the built-in python string. Is there anything hidden away that can be overloaded that might make this possible to do? For some context, I've been hacking away on an experimental pet project for a while. I have a class that I call zstr, which inherits the standard python str class, adding some state information. The idea is that strings can have several representations, such as different ways that they're currently escaped, even though all different representations are essentially the same string. If the string contains information about its current state, it might be possible to make defensive coding in things like web scripting a bit easier. eg. Any code that's unsure of the string's state can re-escape it to make sure, whilst the string instance itself can ensure that it doesn't accidentally get escaped several times in different parts of the code. My somewhat inefficient, buggy and badly documented prototype module is available at [ http://www.mcs.vuw.ac.nz/~jester/zstr/ ]. One problem I've discovered anecdotally, however, is that many of the strings I'd *like* to naturally treat as zstr objects are ones that are initially generated as ordinary strings from external code, such as the built-in libraries. Explicitly wrapping every single string that my code receives into a zstr constructor is both ugly and somewhat unreliable, since they're so common that I often forget. Therefore I'd like to experiment with ways to bypass this. What I'd like to try, as mentioned above, is to override Python's string creation code, so that it automatically uses a zstr class instead of the str class for every string created in the system. I guess the one exception would be where my zstr class inherits and (in some cases) uses the regular python str class internally, in which case the real str would need to be able to be referenced. If anyone can suggest a way to do it, I'd love to hear it. Thanks for any help. Mike. From williams at csr.utexas.edu Fri Apr 30 11:50:36 2004 From: williams at csr.utexas.edu (Stephen Williams) Date: Fri, 30 Apr 2004 10:50:36 -0500 Subject: _socket module missing solaris 7 build python 2.3.3 Message-ID: <409275CC.1D6D080@csr.utexas.edu> after compiling python 2.3.3 on a solaris 7 system, one of our users gets this error message now with a script he had previously written: % python >>> from ftplib import FTP Traceback (most recent call last): File "", line 1, in ? File "/usr/local/lib/python2.3/ftplib.py", line 45, in ? import socket File "/usr/local/lib/python2.3/socket.py", line 44, in ? import _socket ImportError: No module named _socket this behavior is also apparent if you simply download the python 2.3.3 distribution from sunfreeware.com, so it makes me think there is a bug somewhere in this distribution. whatever the reason, the module _socket just simply does not get made. and no, it is not in any of the normal paths that one would include for python libraries. anyone out there know of a way around this? compiler flags or something? -- ''' (O O) ,-------------- oOO-(_)-OOo -------------, | Stephen Williams | | Manager of Computer Services | | Center for Space Research | | University of Texas at Austin | | 3925 W. Braker Ln., Suite 200 | | Austin, TX 78759-5321 | | 512.471.7235 512.471.3570 (fax) | | williams at csr.utexas.edu | |____________________ Oooo ______________| oooO ( ) ( ) ) / \ ( (_/ \_) From ajsiegel at optonline.com Wed Apr 7 09:08:47 2004 From: ajsiegel at optonline.com (Arthur) Date: Wed, 07 Apr 2004 13:08:47 GMT Subject: slightly OT: BUT NEEDs to be said References: <8b42d1998c978c8c1cddf15c52a1c57b@dizum.com> <213df9a1.0404060804.33d68297@posting.google.com> Message-ID: <7nt7709s4emnjpov92tntdnb4sr1kcdar7@4ax.com> On Tue, 06 Apr 2004 23:01:47 -0700, Josiah Carlson wrote: > >You are lumping "Monty Python and the Holy Grail", "Problem Child" and >"The Adventures of Priscilla, Queen of the Desert" together in one >message saying, "they all suck" (to some degree or another). I lumped them together only saying I walked out on all three. An historical fact. > >If at any point you thought "Problem Child" was going to be good to >watch, either for you or your son, then you need a /serious/ parental >wakeup call. Watching 30 seconds of trailer when I was 10, was enough >to convince me that it was a worthless piece of crap, and I was part of >the core demographic. One thing you, or at least I, learn as a parent is not to be too quick to judge other people's parenting. My son was not as perceptive as you. It was not my style to impose my will, generally, on such matters. I did decide to make a stand on the spot, and let him know I was offended enough to drag him out of there. Good luck to you, as a parent. If its something you choose to undertake. > >As an aside, have you bothered to see "...Holy Grail" since you walked >out of it, or have you damned it based on your impression of it while >you were "feeling particularly fragile"? Just curious. No. But if it's any consolation, Faulty Towers is on my list of favorite TV shows. > >As for you not enjoying "Priscilla...", well, that is unfortunate. >However, the message was not that of tolerance, tolerance carries one >unfortunate meaning - you tolerate the kid on the airplane kicking your >seat. Perhaps you meant acceptance. And yes, there have been many >movies about non-heterosexual lifestyles made, some better, some worse. > The choices the writer/director made in regards to "Priscilla..." were >his to make, and again, it is unfortunate that you didn't enjoy the movie. My wife is a great fan of gay culture, if it is fair to say that such a thing exists. I was at Priscilla becasue she had already see it, and insisted I go with her to see it. I guess I was protesting being dragged there. It was not somehting I needed to see, was my assessment, or my statement to her. We survived the incident, you'll be happy to know. Art > > - Josiah From peter.maas at mplusr.de Mon Apr 26 04:14:21 2004 From: peter.maas at mplusr.de (Peter Maas) Date: Mon, 26 Apr 2004 10:14:21 +0200 Subject: How's ruby compare to it older brother python In-Reply-To: References: Message-ID: Hunn E. Balsiche wrote: > I've given up on Perl for its ugly syntax and it is not the easiest language > to learn. How about PHP? http://www.python.org/doc/Comparisons.html Mit freundlichen Gruessen, Peter Maas -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Hubert-Wienen-Str. 24 Tel +49-241-93878-0 Fax +49-241-93878-20 eMail peter.maas at mplusr.de ------------------------------------------------------------------- From mark at prothon.org Wed Apr 21 20:21:03 2004 From: mark at prothon.org (Mark Hahn) Date: Wed, 21 Apr 2004 17:21:03 -0700 Subject: CamelCase versus wide_names (Prothon) References: <6e0680ac.0404211252.7f7b4358@posting.google.com> <4086DFA7.9736E7D3@alcyone.com> Message-ID: "Roy Smith" wrote ... > Well, we could always try something like... > > > > long > variable > name > > That's it! We'll do the whole Prothon language in XML! (The one idea that hasn't been proposed over in Prothon lists yet :) From plastic"no-spam-pls" at xsintrk.net Fri Apr 16 03:34:41 2004 From: plastic"no-spam-pls" at xsintrk.net (jeff) Date: Fri, 16 Apr 2004 07:34:41 GMT Subject: newbie question References: Message-ID: "Krzysztof Stachlewski" wrote in news:c5nuno$1mj$1 at absinth.dialog.net.pl: > This is because you are trying to use a socket that is already closed. > You are calling s.close() but you are not break-ing out of the loop. > In the next iteration s.recv() is called, but s is closed > at that moment. Add a break after the call to s.close(). > Stach *smacks forehead* *hard* From jacek.generowicz at cern.ch Thu Apr 8 08:46:07 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 08 Apr 2004 14:46:07 +0200 Subject: A second __builtins__- or globals()-like namespace. Message-ID: Python looks up names firstly in the nested function namespaces, then the global namespace, and finally in builtins, raising NameError if it fails to find a binding in any of those. Would it be possible (without hacking the interpreter) to add in another namespace somewhere into this search hierarchy? ====================================================================== If you want more background ... I have an application which generates Python proxies for C++ objects, automatically. For example, given namespace foo { struct bar { void zot(); }; } the application automatically creates an object "foo" of type Namespace, contaiting an attribute "bar" of type "Cclass", contaiting an attribute "zot" of type "CMethod". IOW, it's as if someone had written class Namespace: pass class So far, I am storing the whole C++ scope tree (rooted at C++' global namespace) in a variable, say "g", which makes the user refer to the aforementioned "zot" as "g.foo.bar.zot". I would like to get rid of the leading "g." without polluting globals() or __builtins__ (and providing a means of explicit disambiguation of any name clashes). IOW, I would like an object (eg __cpp__), in which Python tries to find the binding of a name after looking in globals() but before looking in __builtins__ (or maybe after __builtins__, or even before globals()). From derek at hiredgoons.org Wed Apr 7 11:00:01 2004 From: derek at hiredgoons.org (Derek Thomson) Date: Thu, 08 Apr 2004 01:00:01 +1000 Subject: Are line continuations needed? In-Reply-To: <10784c8ps1vsu34@news.supernews.com> References: <407409ef.82801353@news.eircom.net> <40740f99@duster.adelaide.on.net> <10784c8ps1vsu34@news.supernews.com> Message-ID: <40741771.8040909@hiredgoons.org> John Roth wrote: >Derek Thomson wrote: >> >>class ParticleDistributionBehaviorServer \ >> (Microphysics__POA.ParticleDistributionBehavior): >> >> [snip] >> >>So the fact that you don't need it in the case of incomplete expressions >>eliminates *most* of the need for it, but there are still a few cases >>where it is required. > > > Technically, you could have split it at the period, but that > might be even worse in terms of readability. I didn't know that, but yes, it would be ugly. > > BTW - why did it have to fit in 80 columns? Because that's our coding standard. But it wouldn't matter if it was 120 columns, or in fact any number you specify - I can still construct an example that won't work. Regards, Derek. From jepler at unpythonic.net Sat Apr 3 22:13:37 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Sat, 3 Apr 2004 21:13:37 -0600 Subject: Typing \n in strings In-Reply-To: References: Message-ID: <20040404031336.GA3455@unpythonic.net> >>> a = "line1\nline2" >>> a # This prints repr(a) 'line1\nline2' >>> print a # This prints a line1 line2 When you enter an expression in the interactive interpreter, and its result is not None, Python shows you the repr() of the value. When you use 'print expression', you are shown the str() of the value. Skip ahead to 7.1, "Fancier Output Formatting", for some more details. Jeff From peter at engcorp.com Mon Apr 5 21:31:20 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 05 Apr 2004 21:31:20 -0400 Subject: slightly OT: BUT NEEDs to be said In-Reply-To: <8b42d1998c978c8c1cddf15c52a1c57b@dizum.com> References: <8b42d1998c978c8c1cddf15c52a1c57b@dizum.com> Message-ID: Nomen Nescio wrote: > In article , Peter Hansen > wrote: > >>Some people despise snakes, and are terrified of them. > > Everyone loves cute cuddly snakes and no one in their right mind is afraid > of them. They don't carry any political baggage or meaning. "Cuddly"? I'd hate to meet your girlfriend... and after reading the first lines of your response I can see clearly you are just trolling and don't really want a serious discussion. If that's not a true statement, at least back off this ludicrous claim and let's try to carry on a rationale discussion. Else: bye. -Peter From paul at prescod.net Mon Apr 5 04:22:57 2004 From: paul at prescod.net (Paul Prescod) Date: Mon, 05 Apr 2004 01:22:57 -0700 Subject: Python is faster than C In-Reply-To: <5d83790c.0404042249.5ff4e354@posting.google.com> References: <406F0907.96F37EA1@tunes.org> <5d83790c.0404032144.482787bd@posting.google.com> <5d83790c.0404042249.5ff4e354@posting.google.com> Message-ID: <40711761.5090702@prescod.net> Raymond Hettinger wrote: > ... > > P.S. If some experimentation shows your code to be useful at the > interactive prompt, please submit a patch on SF so it won't be lost. Why put this behaviour in the interactive prompt rather than in repr()? Paul Prescod From R.Brodie at rl.ac.uk Fri Apr 23 05:03:42 2004 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Fri, 23 Apr 2004 10:03:42 +0100 Subject: Problem with xml.dom parser and xmlns attribute References: Message-ID: "Peter Maas" wrote in message news:c68jai$g85$1 at swifty.westend.com... > Thanks, Richard. But in the Internet most of the time I don't know > what kind of document I'm dealing with when I start parsing. I guess > I should use HTMLParser (?). If you're dealing with a wide range of web pages, chances are they will have all manner of rubbish in them. I would probably feed the stuff through Tidy (or uTidyLib) first, to convert to cleanish XHTML, then use an XML parser. From john_bradbury at skipthistalk21.com Mon Apr 26 06:09:20 2004 From: john_bradbury at skipthistalk21.com (John Bradbury) Date: Mon, 26 Apr 2004 10:09:20 +0000 (UTC) Subject: Pytables Message-ID: Does anyone know how to get support for pytables. I have tried posting to the forum & emailing the author - to no avail. The question I have is, how do you update existing tables. I see insert and delete functions, but no obvious way to update. John Bradbury From mauriceling at acm.org Mon Apr 26 00:10:23 2004 From: mauriceling at acm.org (Maurice LING) Date: Mon, 26 Apr 2004 04:10:23 GMT Subject: A new OS In-Reply-To: <107k441hitt2ld9@corp.supernews.com> References: <107k441hitt2ld9@corp.supernews.com> Message-ID: <408c8baa$1@news.unimelb.edu.au> A Evans wrote: > Hello Everyone I am working towards starting a project developing a new > Operating System using the Python language (or a derivative thereof). As > recommended on this forum I am asking if people are interested in something > like this and ask who would be willing to support a project this large. > > Any and all ideas are welcome this message is just to see what kind of > support this project would recieve > > Cheers > > Andrew > > Is it possible to program a python virtual machine into an EEPROM (eletrically erasable programmable read-only memory) and then set the BIOS to access this VM as the bootloader? So in directly, we have a very low level python VM in the system when it boots up...... Maurice From benn at cenix-bioscience.com Tue Apr 27 09:38:28 2004 From: benn at cenix-bioscience.com (Neil Benn) Date: Tue, 27 Apr 2004 15:38:28 +0200 Subject: xml.parsers.expat vs. xml.sax In-Reply-To: References: Message-ID: <408E6254.2050901@cenix-bioscience.com> Hello, I'm fairly new to Python but I've had a fair bit of experience in SAX. Basically xml.sax.XMLReader is a simple implementation that doesn't do anything when you call parse, setFeature etc. Expat is an implementation of the XMLReader, therefore in actual fact you will never know that you are using Expat as an SAX XMLReader implmentation and you never should need to know - it is simply returned from make_parser The reason that SAX has this mechanism is that it easily allows you to switch implementations in and out. Take a look at the source code and it immediatly becaomes clear! This makes more sense in other languages which have formal interfaces but Python doesn't have such a thing (although you can acheive the same effect in other ways if you so desire). PS I'm new to Python so if that's wrong for the Python SAX implementation then please let me know! Cheers, Neil Thomas Guettler wrote: >Hi! > >What are the difference between xml.parsers.expat >and xml.sax? > >Up to now I used xml.sax.make_parser and subclass >from ContentHandler. > >I think xml.sax.make_parser uses expat as default. >Why should I want to use xml.parsers.expat? > > Regards, > Thomas > > > -- Neil Benn Senior Automation Engineer Cenix BioScience PfotenhauerStrasse 108 D-01307 Dresden Germany Tel : +49 (351) 210 1300 e-mail : benn at cenix-bioscience.com Cenix Website : http://www.cenix-bioscience.com From python at holdenweb.com Wed Apr 14 20:50:46 2004 From: python at holdenweb.com (Steve Holden) Date: Wed, 14 Apr 2004 20:50:46 -0400 Subject: Simple discussion of python cgi approaches? In-Reply-To: <153fa67.0404131857.7956595e@posting.google.com> References: <153fa67.0404121727.45b23c30@posting.google.com> <153fa67.0404131857.7956595e@posting.google.com> Message-ID: Kylotan wrote: [...] > > The main problem I face is that I don't know what platform my scripts > will > eventually run on. I may not have the ability to install extra > software so I > need to keep my scripts close to the CGI standard. That is, one file > per script, > using the cgi module for form processing and print for output. I don't > mind > having to redirect stdout or call these scripts indirectly instead of > via > their __main__ functions, but writing to specific APIs (beyond a small > wrapper > layer, of course) is not an option at the moment. > > So I'm hoping for simple solutions that will involve no more than a > few changes > to each script, whereas most of the solutions that seem to be > available require > me to use their own request objects, or to treat pages as callable > functions within an overall page as mod_python seems to require. > Well, what you've just said probably rules out both the approaches I chose to write about, but you've also defined your problem much more closely and so someone else migth be able to offer more helpful advice. regards Steve From hanzhupeng at kingsoft.net Fri Apr 2 01:13:31 2004 From: hanzhupeng at kingsoft.net (cn99) Date: Fri, 2 Apr 2004 14:13:31 +0800 Subject: newbie comes. Message-ID: Hi, all Highhands :) this is a title for professors in China From __peter__ at web.de Sun Apr 11 03:05:48 2004 From: __peter__ at web.de (Peter Otten) Date: Sun, 11 Apr 2004 09:05:48 +0200 Subject: about streamtoken References: Message-ID: Lin Armis wrote: > hi all: > In java,there is streamtoken method to deal with input string. > how does the python do this work? > Supposed that input "aa/dd/as/23/a22",I wanna the string "23" change to > int('23'),but how can I tell the diffrent between '23'and 'aa' in the all > strings?in java ,I can use streamtoken to recognize the number type and > string type from input,but i dont know how is in Python. Here is one simplistic way to do it: >>> s = "aa/dd/as/23/a22" >>> def convert(s, converters=[int, float]): ... for c in converters: ... try: ... return c(s) ... except ValueError: ... pass ... return s ... >>> a = [convert(t) for t in s.split("/")] >>> a ['aa', 'dd', 'as', 23, 'a22'] Use introspection to detect a token's type: >>> isinstance(a[0], int) False >>> isinstance(a[3], int) True For more complicated input you could use regular expressions. Peter From peter at engcorp.com Wed Apr 21 08:44:20 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 21 Apr 2004 08:44:20 -0400 Subject: CamelCase versus wide_names (Prothon) In-Reply-To: <1082549174.163233@ns.topconrd.ru> References: <6ee58e07.0404192141.2229efd6@posting.google.com> <1082549174.163233@ns.topconrd.ru> Message-ID: Sergei Organov wrote: > Gerrit writes: > > >>Mark Hahn wrote: >> >>>"William Park" wrote ... >>> >>>Someone else already mentioned this >>> >>>>>problem: >>>>> >>>>> smtp_message <-> SMTPMessage <-> SmtpMessage >>> >>>If you consider the capital letter as just a replacement for the underbar, >>>then the answer is definitely smtpMessage. I don't see any problem. >> >>SMTP is an acronym. Because it's an acronym, it's most often spelled in >>allcaps. > > > Yet nobody mentioned that we don't have lower-case digits ;) > > usb201_driver <-> usb201Driver <-> usb2??Driver usbTwoOhOneDriver ? ;-) From sly_raymond at charter.net Mon Apr 26 04:44:57 2004 From: sly_raymond at charter.net (slyraymond) Date: Mon, 26 Apr 2004 03:44:57 -0500 Subject: Trouble Understanding O'Reilly Example References: <108p21f7asq1cc8@corp.supernews.com> <108p2o7j6lqqmc5@corp.supernews.com> Message-ID: <108piuodmckpd71@corp.supernews.com> So the book contains a typo. Hmm. What's amusing about this particular typo is that on the very next page the authors give the result of the function call, and the erroneous result is consistent with the code: (from p. 215): "C:\Python22>python mins.py 2" ...a double typo! Chris wrote: > slyraymond wrote: > >> def min1(*args): >> res = args[0] >> for arg in args[1:]: >> if arg < args: >> res = arg >> return res > Apologizing for whatever damage knode did to the formatting, try: > > if arg < res: > > instead of > > if arg < args > > For debugging purposes, add the line > > print args > > just before the return statement to see exactly what is going on. > > Chris From ae Sun Apr 11 14:43:36 2004 From: ae (A Evans) Date: Sun, 11 Apr 2004 11:43:36 -0700 Subject: Python OS Message-ID: <107j4eu6ffn2c68@corp.supernews.com> I have a question concerning the development of Python Based Operating System. You see I have had sort of a dream to develop an Open Source Operating System that would revolutionize the OS market and Since I started using Python I have fallen in love with the language. Reading articles here and there I have read that Python is a more secure language than C. I also read another article (I can't remember which) saying Python would not be able to develop an OS. I don't believe its true however. I am by no means a programmer at this stage. But as I learn more and more I see Python as the Holy Grail of programming languages My questions would then be, is Python capable of creating an OS from scratch and if so would it be plausible if possible Cheers A python NewBie - Man I hate that term does anyone else See Ya From jepler at unpythonic.net Mon Apr 5 12:08:05 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 5 Apr 2004 11:08:05 -0500 Subject: Python and USB In-Reply-To: <407162b0$1@news.vo.lu> References: <407162b0$1@news.vo.lu> Message-ID: <20040405160805.GE11343@unpythonic.net> Marco, I have some custom USB hardware that I wanted to use from Python. I wrote a C library that called libusb routines, then wrapped my library with Pyrex. I am very pleased with the results! It even worked on Windows after a little work, using libusb-win32. Main page for this project: http://unpy.net/avr/usb/uavrp/ The Pyrex module: http://unpy.net/avr/usb/uavrp/uavrp-1.0/avr.pyx The C library: http://unpy.net/avr/usb/uavrp/uavrp-1.0/hostlib.c Jeff From python at rcn.com Mon Apr 5 02:16:24 2004 From: python at rcn.com (Raymond Hettinger) Date: 4 Apr 2004 23:16:24 -0700 Subject: __nonzero__ of iterators References: <106qopdnqbd0164@news.supernews.com> Message-ID: <5d83790c.0404042216.2478ecf8@posting.google.com> [Christian Eder] > > I just discovered the following pitfall in Python 2.3. > > Consider the following code : > > > > >>> a = {} > > >>> bool (a.keys ()) > False > > >>> bool (a.iterkeys ()) > > True > > > > So, an "empty" iterator evaluates to True in boolean context. > > At a first glance, this is not what one would expect. This causes > > several problems, e.g. if you operate on something expected to be > > sequence, and you guard your code with "if seq :" to avoid crashing into > > an empty sequence, you still crash if you get an empty iterator, even if > > the rest of your code is able to deal with an iterator as well as with > > any other sequence type. This was fixed in Py2.4: Python 2.4a0 (#46, Apr 4 2004, 05:21:08) [MSC v.1200 32 bit (Intel)] on win32 IDLE 1.1a0 >>> d = dict(a=1, b=2, c=3) >>> it = d.iterkeys() >>> bool(it) True >>> list(it) ['a', 'c', 'b'] >>> bool(it) False [John Roth] > One of the issues is that the iterator many not be able, even in > principle, be able to figure out whether there is, in fact, a next > element. Consider a pipe or an internet connection. > > However, you're talking about the special iterator that the > dictionary object returns. I'm not sure whether this behavior > is a bug or a feature. It would clearly be possible for that > iterator object to proxy the __nonzero__ call to the basic > dictionary object, and from what you show, it doesn't do so. > > I belive this is a quite different issue from a "has next" type > of function. Right. So, the only iterators that provide knowledge of their length are the ones like dictionaries that know what lies ahead. For the rest, the behavior is unchanged (i.e. they do not provide a __len__() method). Raymond Hettinger From loic at fejoz.net Fri Apr 16 05:38:42 2004 From: loic at fejoz.net (Yermat) Date: Fri, 16 Apr 2004 11:38:42 +0200 Subject: Aspect Programming Module In-Reply-To: References: <84fc4588.0404140106.3fa0c55@posting.google.com> <8ef9bea6.0404142155.90b41ef@posting.google.com> <407E394B.2050709@mxm.dk> Message-ID: Alexandre Fayolle wrote: > Le 16-04-2004, Yermat a ?crit : > > >>Does it help ? > > > Well, yes and no. I agree that this is how AOP can be made to work in > Python (aand your implementation is not conceptually very different from > logilab.aspect (except that the module has some entry points for > choosing which methods are tied to the aspect) > > However, I would not call this a "mixin" (which was the key word in my > question). My vision of a mixin implies (maybe wrongly) some > responsibilities to be added or customized through multiple inheritance > to a given class by a mixin class. This supposes that the originial > class was designed with the mixin in mind. > Oups sorry ! So maybe something like the following. In fact, I'm really wondering what is really AOP. It seems just like code factorization after all and use it only on some instance ! class LoggerAOP(object): def __init__(self, f, name): self.f = f self.name = name def __call__(self, *args, **keywords): if callable(self.f): print "calling %s" % self.name result = self.f(*args, **keywords) print "end of call %s" % self.name return result raise TypeError, "%s not callable" % self.name class FunctionLoggerClass(object): def __getattribute__(self, attrName): realAttr = object.__getattribute__(self, attrName) if callable(realAttr): return LoggerAOP(realAttr, attrName) return realAttr class MyClass(object): def __init__(self, name): self.name = name def foo(self, a): return "%s say hello to %s" % (self.name, a) class SpecMyClass(FunctionLoggerClass, MyClass): pass m = SpecMyClass("Yermat") print m.name print m.foo("world") -- Yermat From peter at engcorp.com Wed Apr 28 15:24:02 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 28 Apr 2004 15:24:02 -0400 Subject: Path ... where is my application's home dir? In-Reply-To: References: Message-ID: Yermat wrote: > Duncan Booth a ?crit : > And for the user dir, you can do (at least on Win2000, not try elsewhere) : > os.getenv('HOMEDRIVE') + os.getenv('HOMEPATH') Also works on WinXP. (And the last statistic I saw showed Win98 users at something like 2% of the Windows-using population, so perhaps we can almost forget about it... ?) -Peter From piro at officine.it Wed Apr 28 12:46:46 2004 From: piro at officine.it (Daniele Varrazzo) Date: Wed, 28 Apr 2004 18:46:46 +0200 Subject: Formatting Currency According to Locale Message-ID: Hi everybody Is there any way to make the most of locale.localeconv() in formatting currencies? I can use many tricks as >>> locale.setlocale(locale.LC_ALL, locale.getlocale()) >>> lc = locale.localeconv() >>> >>> cash = 1427.48 >>> print "%s%s" % ( lc['currency_symbol'], locale.format('%.*f', (lc['frac_digits'],cash), 1)) ?1.427,48 But that presumes many things, such as lc['mon_grouping'] == lc['grouping'] # format uses the latter value, doesn't he? lc['p_sign_posn'] == 3 # else i must change the format string, # maybe building a mapping to order the pieces, splitting + and - cases... I'm using... Python 2.3.2 (#49, Oct 24 2003, 13:37:57) [MSC v.1200 32 bit (Intel)] on win32 ... and watching localeconv(), i also see many other not much documented details: n_cs_precedes, n_sep_by_space... Is it up to me to write a function to keep all these details into account? Bye Daniele From jules at REMOVETHIS.op59.net Mon Apr 12 18:18:40 2004 From: jules at REMOVETHIS.op59.net (Julian Smith) Date: Mon, 12 Apr 2004 23:18:40 +0100 Subject: How to kill a SocketServer? References: <86GdndxCWrGil-bdRVn-gw@powergate.ca> Message-ID: <20040412231840.630157e5.jules@REMOVETHIS.op59.net> On Mon, 12 Apr 2004 17:29:35 -0400 Peter Hansen wrote: > Jean-Pierre Bergamin wrote: > > The accept() call still won't get interrupted. :-( > > > > Other ideas? > > You have three choices. > > 1. Run your server as a separate process, communicating with it > via some kind of RPC, and just kill it when desired. > > 2. Use non-blocking sockets. This is the standard and > simplest approach in many ways. > > 3. Arrange to have one thread open a socket connection to the > application, waking up your accept()ing thread. Then check > a flag which tells the server thread to exit. I have a class that can be constructed from a socket and looks like a file object, but whose blocking read() method can be interrupted by a different thread. The read() method uses poll() to block on both the real underlying file descriptor and an internal file descriptor created using os.pipe(). It works on OpenBSD and Cygwin, but I haven't tried it on anything else yet. I'm a relative newcomer to Python, so I'm sure there are some subleties that I've missed. See http://www.op59.net/cancelable.py if you're interested. > > By definition, blocking calls block, and you can't safely kill > a thread in Python so pick one from the above and run with it... > > -Peter - Julian -- http://www.op59.net From maxm at mxm.dk Mon Apr 19 10:57:43 2004 From: maxm at mxm.dk (Max M) Date: Mon, 19 Apr 2004 16:57:43 +0200 Subject: outline-style sorting algorithm In-Reply-To: References: Message-ID: <4083E8E7.8060503@mxm.dk> jwsacksteder at ramprecision.com wrote: > I have a need to sort a list of elements that represent sections of a > document in dot-separated notation. The built in sort does the wrong thing. Not really. You are giving it a list of strings, and it sort those alphabetically. That seems like the right thing to me ;-) > This seems a rather complex problem and I was hoping someone smarter than me > had already worked out the best way to approach this. For example, consider > the following list- >>>>foo > > ['1.0', '1.0.1', '1.1.1', '1.2', '1.9', '1.10', '1.11', '1.20', '1.20.1', > '1.30'] You need to convert them to another datatype first. Your best bet here would be a list or a tuple, as they can map directly to your data. '1.0.1'.split('.') == [1,0,1] But list are a bit easier here. foo_as_tuples = [f.split('.') for f in foo] foo_as_tuples.sort() Then you must convert it back to strings again. foo = ['.'.join(f) for f in foo_as_tuples] There is a standard way of sorting quickly in python, called decorate-sort-undecorate. It is allmost the same example as before: decorated = [(itm.split('.'),itm) for itm in foo] decorated.sort() foo = [d[-1] for d in decorated] regards Max M From usenet_spam at janc.invalid Mon Apr 19 17:09:17 2004 From: usenet_spam at janc.invalid (JanC) Date: Mon, 19 Apr 2004 21:09:17 GMT Subject: os.system help References: <78lgc.3445$AL1.7744@news1.mts.net> <5Lzgc.4355$AL1.9508@news1.mts.net> Message-ID: Reid Nichol schreef: > The registry contains certain data but not *exactly* the data I need. I > could construct from that but according to the docs it's quite new so > I'd rather not use it. I did this 2 years ago (using a NSIS 1.x install script to change a batch file) and it worked for everyone who tested & used it then (at least 10 people, maybe more). I think most of them had a 7.x GS version. (Maybe some 6.x versions too, but I don't remember exactly.) Two years isn't that "quite new" anymore... -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From peter at engcorp.com Mon Apr 26 19:55:06 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 26 Apr 2004 19:55:06 -0400 Subject: Compiler In-Reply-To: References: Message-ID: Steven wrote: > Just curious, is there a python compiler? > Or something that creates bytecode, like java? Yes. They are the same thing. Javac compiles Java source to Java bytecode. C compilers compile C source to machine-specific bytecode (called machine code). Python compiles Python source to Python bytecode. The main difference is that Python does this transparently behind your back whenever the source has change, while many other languages that do it require a separate manual step... -Peter From no.email at please.com Fri Apr 9 19:53:46 2004 From: no.email at please.com (Stevie_mac) Date: Sat, 10 Apr 2004 00:53:46 +0100 Subject: Simple Class Question - need clarity please References: <2tce701vv505395hcr6dqtvc8ot0fdmkrk@4ax.com> Message-ID: > Its a good idea to post the entire error traceback so we see the > actual line of code the error refers to. This error usually means > you accessed a name from a module without prefixing it with the > module name. But so far as I can see you haven't done that here. # mywindow.py # import win32con, win32ui from pywin.mfc import dialog #, window class Window: def MakeDlgTemplate(self): style = win32con.DS_MODALFRAME | win32con.WS_POPUP | win32con.WS_VISIBLE | win32con.WS_CAPTION | win32con.WS_SYSMENU | win32con.DS_SETFONT dlg = [ ["My Dialog", (0, 0, 100, 100), style, None, (8, "MS Sans Serif")], ] s = win32con.BS_PUSHBUTTON | win32con.WS_CHILD | win32con.WS_VISIBLE dlg.append([128, "Cancel", win32con.IDCANCEL, (55, 80, 40, 16), s]) return dlg def DoModal(self): mw = win32ui.CreateDialogIndirect( self.MakeDlgTemplate() ) mw.DoModal() import mywindow class MyClass(mywindow.Window): def Show(self): self.DoModal() t = MyClass() t.Show() #ERROR OUTPUT File "C:\My Python Stuff\window\test.py", line 7, in ? t.Show() File "C:\My Python Stuff\window\test.py", line 4, in Show self.DoModal() File "C:\My Python Stuff\window\mywindow.py", line 12, in DoModal mw = win32ui.CreateDialogIndirect( self.MakeDlgTemplate() ) NameError: global name 'MakeDlgTemplate' is not defined From peter at engcorp.com Sat Apr 24 15:39:23 2004 From: peter at engcorp.com (Peter Hansen) Date: Sat, 24 Apr 2004 15:39:23 -0400 Subject: ioctl(2) ? In-Reply-To: References: Message-ID: <4qqdnSHVRZnxXxfd4p2dnA@powergate.ca> Peter Luciak wrote: > is there any way to do a ioctl in python? I didn't find it in the os > module... http://docs.python.org/lib/module-fcntl.html From rick.ratzel at magma-da.com Fri Apr 16 18:51:07 2004 From: rick.ratzel at magma-da.com (Rick Ratzel) Date: Fri, 16 Apr 2004 17:51:07 -0500 Subject: Initializing Python in Optimized mode from C++ In-Reply-To: References: Message-ID: <4080635b$0$46515$39cecf19@news.twtelecom.net> JT wrote: > Hi, > > When embedding Python in C++, is there anyway to initialize the > interpreter so that it runs in optimized mode, equivalent to > specifying the -O flag when running the interpreter from the command > line? > > Thanks, > John set Py_OptimizeFlag to 1 for -O, and 2 for -OO. Do this prior to calling Py_Initialize(); You can also improve your startup time by setting Py_NoSiteFlag = 1...assuming you don't need to load site.py for example: extern int Py_OptimizeFlag; extern int Py_NoSiteFlag; ... if( !Py_IsInitialized() ) { Py_OptimizeFlag = 2; Py_NoSiteFlag = 1; Py_Initialize(); } From jdhunter at ace.bsd.uchicago.edu Thu Apr 29 17:42:11 2004 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Thu, 29 Apr 2004 16:42:11 -0500 Subject: MATLAB2Python In-Reply-To: (Robert Kern's message of "Thu, 29 Apr 2004 14:15:22 -0700") References: <1090ivtaa0b2e26@corp.supernews.com> <40904EDE.9060407@erols.com> <715kc.3$i6.251@psinet-eu-nl> Message-ID: >>>>> "Robert" == Robert Kern writes: Robert> Do you mind a hefty download? If not, then try Enthought's Robert> distribution of Python[1]. matplotlib seems to have an exe Robert> installer for Windows, so I assume it's straightforward. Robert> But, in short, that order is correct (the last three all Robert> depend on Numeric). Robert> [1] http://www.enthought.com/python/ Seconded - that is what I recommend on the matplotlib web site for windows users - enthought then matplotlib. See the windows section on http://matplotlib.sourceforge.net/installing.html. enthought will give you numeric and scipy (and VTK which is awesome for 3D) and almost all of matplotlib will work out of the box with enthought on windows. matplotlib supports different GUI environments. On windows tkagg or wxagg are the natural choices and they come with enthought. On a modern linux box, gtkagg is a natural choice, but may require you to upgrade your pygtk (grkagg also runs great on windows but require a couple of extra packages). Switching between backends on different platforms is mainly seamless - your matplotlib scripts are unchanged and the navigation controls are the same. The choice is made in a configuration file http://matplotlib.sourceforge.net/faq.html#MATPLOTLIBRC See http://matplotlib.sourceforge.net/backends.html and http://matplotlib.sourceforge.net/faq.html#WHICHBACKEND for details. As for install order on linux, something like python2.2 or later a python GUI (wxpython, tkinter, or pygtk) numeric or numarray scipy (optional) matplotlib # set the numerix var to reflect your numarray/numpy choice matplotlib provides a numeric/numarray compatibility interface (written by Todd Miller, one of lead numarray developers) so you can work with either numeric or numarray transparently. Be forewarned that scipy uses numeric so you may want to go with this if you plan on using scipy heavily. JDH From jacek.generowicz at cern.ch Tue Apr 6 10:12:54 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 06 Apr 2004 16:12:54 +0200 Subject: Does Python compete with Java? References: <8b336527.0404051337.51bb4a1b@posting.google.com> <1073su4etm95p35@news.supernews.com> Message-ID: Chris Herborth writes: > One of Python's most awesome features (IMHO at least) is that you can > fire up an interactive interpreter while you're writing your code, and > try things out as you go... using this technique, I've unit tested > methods and algorithms interactively and ended up with useful, > non-trivial applications that run and work properly the first time. > > > With compiled languages (Java, C#, C++), I find I'm writing a bit of ^^^^^^^^^^^^^^^^^^^^^^^ > code, taking a break to compile it, figuring out how to unit test the > method... Python saves me a huge amount of time in the prototype and > development cycles. Please note that this has nothing to do with compilation per-se. There are languages with to-native-binary compilers which give you all the instant turnaround flexibility that Python does. Indeed, there are even some development environments for the languages you mention which try to provide a similar experience. From armislin at hotmail.com Sat Apr 10 23:41:46 2004 From: armislin at hotmail.com (Lin Armis) Date: Sun, 11 Apr 2004 11:41:46 +0800 Subject: about streamtoken Message-ID: hi all: In java,there is streamtoken method to deal with input string. how does the python do this work? Supposed that input "aa/dd/as/23/a22",I wanna the string "23" change to int('23'),but how can I tell the diffrent between '23'and 'aa' in the all strings?in java ,I can use streamtoken to recognize the number type and string type from input,but i dont know how is in Python. cheers, Mian _________________________________________________________________ ???? MSN Explorer: http://explorer.msn.com/lccn/ From bjg at network-theory.co.uk Thu Apr 29 10:27:40 2004 From: bjg at network-theory.co.uk (Brian Gough) Date: 29 Apr 2004 15:27:40 +0100 Subject: reading and removing first x bytes of a file References: Message-ID: <87isfihnab.fsf@network-theory.co.uk> bart_nessux writes: > I have some Macbinary files on a PC. I want to recursively read these > files and remove the first 128 bytes of the files if they contain the > macbinary header info. I know how to read directories recursively, but > how would I read the first 128 bytes of each file in the path? You can use the file object .seek() and .read() methods to move around in the file and read parts of it. There is an example in the "Input and Output" chapter of the Python Tutorial. -- Brian Gough Network Theory Ltd, Publishing the Python Manuals --- http://www.network-theory.co.uk/ From nospam at here.com Sat Apr 10 13:44:24 2004 From: nospam at here.com (Richard Townsend) Date: Sat, 10 Apr 2004 18:44:24 +0100 Subject: New user - Now what ? References: Message-ID: <3rWdc.31611$Y%6.3949707@wards.force9.net> > Any tutorials I can use to utilise Python on my web-pages ? > http://www.python.org/ http://docs.python.org/tut/tut.html http://www.python.org/doc/Intros.html http://www.python.org/topics/web/ From adwser at hotmail.com Tue Apr 27 12:54:26 2004 From: adwser at hotmail.com (jtd) Date: 27 Apr 2004 09:54:26 -0700 Subject: Non-blocking connect BLOCKS Message-ID: Hi all, I'm using asyncore to download a large list of web pages, and I've noticed dispatcher.connect blocks for some hosts. I was under the impression that non-blocking sockets do not block on connects, in addition to reads and writes. My connect code is essentially the same as the asyncore example: http://docs.python.org/lib/asyncore-example.html It seems unlikely that I am the first to encounter this problem, can someone explain what's wrong and suggest a remedy? Rob From peter at engcorp.com Fri Apr 2 06:48:27 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 02 Apr 2004 06:48:27 -0500 Subject: Travelling salesman variation in python In-Reply-To: References: Message-ID: Erlend Andreas Garberg wrote: > In article , Josiah Carlson wrote: > >>Look at current TSP algorithms, and exchange their minimization rutines >>for a maximization rutine. TSP is an NP-hard problem, which means that >>there is no currently known algorithm for solving it in polynomial time. >> You can approximate it or do a search on the solution space, but >>solving it requires searching basically all of the solution space. > > An approximate solution would be good enough, do you have any > suggestions about how do do that? I haven't tried it for such a case, but have you considered a genetic algorithm approach? Since you say an approximate solution is good enough, I would think a GA could vastly shrink the search space that has to be covered to get "close", assuming that data is not such that hidden somewhere in it is a single link which has an associated number that is vastly higher than the others. (That would tend to make the GA search even worse than a brute force approach.) -Peter From anton at vredegoor.doge.nl Sat Apr 3 16:57:25 2004 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Sat, 03 Apr 2004 23:57:25 +0200 Subject: Working with bytes. References: <406EE606.4000604@yahoo.com> Message-ID: <406f33b6$0$30963$3a628fcd@reader1.nntp.hccnet.nl> "Adam T. Gautier" wrote: >I came up with a solution using the binascii module's hexlify method. That is the most obvious method, I think. However, the code below stores 7 bits per byte and still remains ascii-compliant (the binascii.hexlify method stores 4 bits per byte). Anton from itertools import islice def _bits(i): return [('01'[i>>j & 1]) for j in range(8)][::-1] _table = dict([(chr(i),_bits(i)) for i in range(256)]) def _bitstream(bytes): for byte in bytes: for bit in _table[byte]: yield bit def _dropfirst(gen): while 1: gen.next() for x in islice(gen,7): yield x def sevens(bytes): """ stream normal bytes to bytes where bit 8 is always 1""" gen = _bitstream(bytes) while 1: R = list(islice(gen,7)) if not R: break s = '1'+ "".join(R) + '0' * (7-len(R)) yield chr(int(s,2)) def eights(bytes,n): """ the reverse of the sevens function :-) """ gen = _bitstream(bytes) df = _dropfirst(gen) for i in xrange(n): s = ''.join(islice(df,8)) yield chr(int(s,2)) def test(): from random import randint size = 40 R = [chr(randint(0,255)) for i in xrange(size)] bytes = ''.join(R) sv = ''.join(sevens(bytes)) check = ''.join(eights(sv,size)) assert check == bytes print sv if __name__ == '__main__': test() sample output: ?????????????????????????????????????????????? From jepler at unpythonic.net Wed Apr 21 19:59:54 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 21 Apr 2004 18:59:54 -0500 Subject: Cell objects and their values In-Reply-To: References: Message-ID: <20040421235954.GB13610@unpythonic.net> This seems to work, but it's undocumented (specifically, func_closure as an argument to new.function is undocumented) and makes my tummy feel funny when I think about it. >>> import new >>> def cell_get(cell): ... def f(): return cell ... return new.function(f.func_code, {}, "f", (), (cell,))() ... cell_get's 'f' does LOAD_DEREF 0 / RETURN, new.function() chooses the created function's func_closure, which is the called right away. >>> def f(): ... x = 3 ... def g(): ... return x ... return g.func_closure[0] ... >>> c = f() >>> cell_get(c) 3 ... it works! Jeff From gioco at nekhem.com Mon Apr 19 09:24:18 2004 From: gioco at nekhem.com (Corrado Gioannini) Date: Mon, 19 Apr 2004 15:24:18 +0200 Subject: outline-style sorting algorithm In-Reply-To: <71650A6F73F1D411BE8000805F65E3CB3B3A4D@SRV-03> References: <71650A6F73F1D411BE8000805F65E3CB3B3A4D@SRV-03> Message-ID: <20040419132417.GA1476@zephyr> On Mon, Apr 19, 2004 at 09:08:59AM -0400, jwsacksteder at ramprecision.com wrote: > I have a need to sort a list of elements that represent sections of a > document in dot-separated notation. The built in sort does the wrong thing. > This seems a rather complex problem and I was hoping someone smarter than me > had already worked out the best way to approach this. For example, consider > the following list- I think you should use a sort function built for this special case. For example you can sort items comparing map(int, item.split('.')) >>> cmp(map(int, '1.20.1'.split('.')), map(int, '1.9'.split('.'))) 1 that is: >>> cmp([1,20,1],[1,9]) 1 hth, C. -- Thought is only a flash between two long nights, but this flash is everything. (H. Poincar?) From sean at sands.beach.net Fri Apr 23 11:11:34 2004 From: sean at sands.beach.net (Sean Berry) Date: Fri, 23 Apr 2004 15:11:34 GMT Subject: Setting variable values from dictionary Message-ID: If I have a dictionary like the following: {'category' : 2, 'shape', 4} How can I use this to make category = 2 and shape = 4. I want to be able to do this regardless of the dict values type. So: {'cateogry' : 2, 'shape' : 'circle'} will work as well. Thanks in advance for any help. You guys rock. -- From loic at fejoz.net Thu Apr 1 04:57:58 2004 From: loic at fejoz.net (Yermat) Date: Thu, 01 Apr 2004 11:57:58 +0200 Subject: ANNOUNCE: 'goto' for Python In-Reply-To: <406bd703$0$14074$626a14ce@news.free.fr> References: <406bd703$0$14074$626a14ce@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > Richie Hindle wrote: > >> Entrian Solutions is pleased to announce version 1.0 of the 'goto' >> module. >> >> This adds the 'goto' and 'comefrom' keywords to Python 2.3, adding >> flexibility to Python's control flow mechanisms and allowing Python >> programmers to use many common control flow idioms that were previously >> denied to them. >> > Trop gros, passera pas... !-) > What is the day today ? Oh yes the first of April ! From fgeiger at datec.at Sat Apr 24 03:20:42 2004 From: fgeiger at datec.at (F. GEIGER) Date: Sat, 24 Apr 2004 09:20:42 +0200 Subject: [OT] Plone References: <6ukic.84257$cd.5573763@phobos.telenet-ops.be> Message-ID: Plone is based on Zope, i.e. Plone := Zope + CMS-components. Installation is easy (can speak only for Win2k) and I suggest that you simply try it. I'm sure that after 2 or 3 hours you know whether or not Plone is yours. Cheers Franz "flupke" schrieb im Newsbeitrag news:6ukic.84257$cd.5573763 at phobos.telenet-ops.be... > Hi, > > i've read some user comments on Zope. As was to be expected some say > it's cool, others says it's difficult and not easy to debug. > I would use Plone as CMS for our intranet which will also be a platform > for our tools. Does plone make it even more difficult to get going or does > it > hide some of the difficulties of Zope? > I'm kind of in a dillema here, the more i read about Python, the more i like > it. As it seems mod_python/FCGI is a good combo to bring Python power > to the web but since they want a CMS and i don't have time to write one > from the ground up, i'm thinking of using Plone. > I have my doubts about Zope especially from the viewpoint > of administration. I will have to maitain the systems where it runs on also. > > Any comments? > flupke > > > From mail at markus-franz.de Thu Apr 22 13:25:29 2004 From: mail at markus-franz.de (Markus Franz) Date: Thu, 22 Apr 2004 19:25:29 +0200 Subject: Main-process doesn't wait for child-processes Message-ID: Hi. I created a little script: for currenturl in sys.argv[1:]: pid = os.fork() if pid == 0: signal.alarm(10) do_something() # placeholder for the download and print routine break This script is started by ./script.py http://www.website1.com http://www.website2.com As you see it creates child-processes for loading all websites specified on the command line. (So all websites are loaded in parallel.) Each child-process simply load a websites and print the contents to STDOUT (above replaced by do_something). (With signal.alarm(10) I make sure that each child-process will not run longer than 10 seconds.) But now I have a difficult problem: This script is executed by a comand-line-function (shell_exec) in PHP, the response of the Python-script is used inside the PHP application. In the python script the main process seem to stop immediately after starting the script, only the child-processes seem to run. Because of this my PHP application will not wait untill the child-processes have finised and so I can't use the contents of the websites. (I think the solution should be that the main-process waits untill the child-processes terminate.) Now my question is: How can I force the main-process to wait untill every child-process is finished? I tried: for currenturl in sys.argv[1:]: pid = os.fork() if pid == 0: signal.alarm(10) do_something() # placeholder for the download and print routine break else: os.wait() The version above behaves like a script that loads all given websites in sequence... I also tried: for currenturl in sys.argv[1:]: pid = os.fork() if pid == 0: signal.alarm(10) do_something() # placeholder for the download and print routine break time.sleep(4) That didn't help me, too. The following is a PHP application that may help you to understand the bad behavoir of my application (you will guess my problem if you execute both the PHP and the Python script): Thank you. Best regards Markus Franz From imbosol at aerojockey.invalid Thu Apr 1 23:48:06 2004 From: imbosol at aerojockey.invalid (Carl Banks) Date: Fri, 02 Apr 2004 04:48:06 GMT Subject: ftpmirror.py in reverse? References: Message-ID: Harry George wrote: > I maintain a website on a local machine, and want to maintain a clone > of it on a www-visible remote machine via ftp. I.e., local to remote. > > Going remote to local, ftpmirror.py would (I understand) do the job. > > Is there some tool available (or even a parameter for ftpmirror.py) > which can do local-->remote? I've written such a script. http://www.aerojockey.com/software/#ftpupsync It's public domain, use at your own risk, n' at. It probably doesn't work on Windows, but wouldn't be hard to modify it to. Sorry, no documentation. I really should document it, tie up loose ends and package it. Sorry about the tabs^H^H^H^H Unicode indent characters. -- CARL BANKS http://www.aerojockey.com/software "If you believe in yourself, drink your school, stay on drugs, and don't do milk, you can get work." -- Parody of Mr. T from a Robert Smigel Cartoon From daniel.dittmar at sap.com Mon Apr 5 05:52:54 2004 From: daniel.dittmar at sap.com (Daniel Dittmar) Date: Mon, 5 Apr 2004 11:52:54 +0200 Subject: Python is faster than C References: <36wn05qkeyk.fsf@hundertwasser.ti.uni-mannheim.de> Message-ID: Matthias wrote: > That's not a rhetorical question: Why is it that "simplicity of the > Python VM is an important goal"? Replace 'simplicity' with 'portability'. This is especially true for JIT compilers, which are not only complex, but are unportable by design. > I would guess that overall it pays > to have a more complex language implementation and be rewarded by > simpler user code: For any decent language there's much more user code > out there than language implementation code. The question is not 'does it pay?', the question is 'who pays?'. Daniel From aahz at pythoncraft.com Thu Apr 1 08:43:41 2004 From: aahz at pythoncraft.com (Aahz) Date: 1 Apr 2004 08:43:41 -0500 Subject: Python conference slogan References: Message-ID: In article , Peter Maas wrote: > >I surrender immediately and have to admit that I don't get it (One >Nation Under Under Python). Google was no help. I couldn't find the >source, only echoes (seems to be a wide spread joke pattern in the >US). Care to give us ignorants a hint? It's from the Pledge of Allegiance: I Pledge Allegiance to the flag of the United States of America and to the Republic for which it stands, one Nation under God, indivisible, with liberty and justice for all. The "under under" part of course refers to Python's special methods. See also http://history.vineyard.net/pledge.htm IIRC, there's currently a court case to remove the "under God" part. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "usenet imitates usenet" --Darkhawk From paul at prescod.net Fri Apr 9 20:03:28 2004 From: paul at prescod.net (Paul Prescod) Date: Fri, 09 Apr 2004 17:03:28 -0700 Subject: Compact Python library for math statistics In-Reply-To: <3064b51d.0404091308.472dfb78@posting.google.com> References: <3064b51d.0404061038.4d69fd89@posting.google.com> <5d83790c.0404090024.5cefb2ea@posting.google.com> <3064b51d.0404091308.472dfb78@posting.google.com> Message-ID: <407739D0.40907@prescod.net> beliavsky at aol.com wrote: >... > > Overall, the Python code below is about 100 times slower than the > Fortran equivalent. This is a typical ratio I have found for code > involving loops. > > from math import sqrt > n = 10000000 + 1 > sum_sqrt = 0.0 > for i in range(1,n): > sum_sqrt = sum_sqrt + (float(i))**0.5 > print sum_sqrt If you rewrite it as Pyrex: def func5(int n): cdef float sum_sqrt cdef long int i sum_sqrt = 0.0 for i from 0 <= i < n: sum_sqrt = sum_sqrt + i**0.5 return sum_sqrt This generates: for (i = 0; i < n; ++i) { sum_sqrt = (sum_sqrt + pow(i, 0.5)); __pyx_L2:; } Except for the useless label, this is idiomatic C code and I doubt that Fortran is going to be much of any faster given most compilers. Even so, on my computer, this code is nowhere near 100 times faster than the pure Python version. I think you are timing the allocation of a very large memory buffer with range(). Consider this alternative: def func1(n): sum_sqrt = 0.0 for i in xrange(1,n): sum_sqrt = sum_sqrt + sqrt(i) return sum_sqrt or def func2(n): return sum(itertools.imap(sqrt, xrange(1, n))) Paul Prescod From RobMEmmons at cs.com Mon Apr 12 20:34:26 2004 From: RobMEmmons at cs.com (Robert M. Emmons) Date: Mon, 12 Apr 2004 19:34:26 -0500 Subject: Starting a Python COM server from vb? In-Reply-To: References: Message-ID: <407B3592.7010508@cs.com> > Pretty much what it says. > > I've a number of Python services that I'd like to use from vb. The > hitch is ensuring the services are started before the VB program tries > to use them. > > Startup folder isn't a good solution, as folks sometimes putter with > their startup folder options. > > Is it as simple as exec()-ing the service script? That IS workable, > provided VB's exec() function plays nice and allows the service to run. Maybe I missunderstand -- but as far as I know there are NO reasons to RUN anything before you use it. Only thing you need to do is to register your Python COM servers. When you use them in VB, just instantiate them like any other COM object. Python is not special in any way. Rob From fredrik at pythonware.com Mon Apr 19 13:54:12 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 19 Apr 2004 19:54:12 +0200 Subject: module not callable - why not? References: <7xsmf1fxd9.fsf@ruckus.brouhaha.com><8ef9bea6.0404180956.cd1a152@posting.google.com> <8ef9bea6.0404190908.4b130d57@posting.google.com> Message-ID: Hung Jung Lu wrote: > > That's not the only answer, and it's not the one I use: > > > > import foo > > getattr(foo, 'name') > > You can't do this when you are inside the module itself. inside the module, it's spelled name From junkmail at solumslekt.org Sat Apr 3 15:35:30 2004 From: junkmail at solumslekt.org (Leif B. Kristensen) Date: Sat, 03 Apr 2004 22:35:30 +0200 Subject: recursive file editing References: Message-ID: This is a Perl one-liner: perl -p -i -e 's/foo/bar/gi' `find ./` regards, -- Leif Biberg Kristensen http://solumslekt.org/ Validare necesse est From no.email at please.com Sun Apr 11 09:09:46 2004 From: no.email at please.com (Stevie_mac) Date: Sun, 11 Apr 2004 14:09:46 +0100 Subject: Best IDE? Message-ID: This has prolly been asked 100 times - so please refrain from flaming if you can... What's the best MSwindows editor for python? I'm currently using PythonWin (ActiveState) at the moment, its a bit buggy - but not too bad. I mean, its got autocomplete & tips & help & autoindentaion (not always good tho). Thing is, I'm sure there is something better. Is there? (is there a VS.NET addin?) From wweston at att.net Fri Apr 2 10:31:17 2004 From: wweston at att.net (wes weston) Date: Fri, 02 Apr 2004 15:31:17 GMT Subject: splitting one dictionary into two In-Reply-To: <5d83790c.0404020042.41f4a576@posting.google.com> References: <5d83790c.0404020042.41f4a576@posting.google.com> Message-ID: <9Hfbc.21085$He5.413767@bgtnsc04-news.ops.worldnet.att.net> Raymond Hettinger wrote: > [jsaul] > >>I have to split a dict into two dicts. Depending on their values, >>the items shall remain in the original dict or be moved to another >>one and at the same time be removed from the original dict. >> >>OK, this is how I do it right now: >> >> dict1 = { "a":1, "b":3, "c":5, "d":4, "e":2 } >> dict2 = {} >> klist = [] >> >> for key in dict1: >> if dict1[key] > 3: # some criterion >> dict2[key] = dict1[key] >> klist.append(key) >> >> for key in klist: >> del dict1[key] >> >> print dict1 >> print dict2 >> >>That means that I store the keys of the items to be removed from >>the original dict in a list (klist) and subsequently remove the >>items using these keys. >> >>Is there an "even more pythonic" way? > > > Your way seems clean enough to me. > > One other approach is to use items() so you can modify dict1 as you go: > > for key, value in dict1.items(): > if value > 3: > dict2[key] = value > del dict1[key] > > > > Raymond Hettinger Raymond, I had the same approach seen above before the originator added the fact that the starting dictionaries would typically be "huge". Robert Brewer timed this method as 5 times slower than his method which showed me that my obsession with simplicity needs to be looked at. wes From lbates at swamisoft.com Tue Apr 20 10:07:51 2004 From: lbates at swamisoft.com (Larry Bates) Date: Tue, 20 Apr 2004 09:07:51 -0500 Subject: How to check if a path *could* be a legal path? References: Message-ID: It is much easier to put your code that would create the path inside a try block and just have an exception that handles the failure. If most of the time the path is legal, it is faster also. Regards, Larry Bates Syscon, Inc. "Maciej Sobczak" wrote in message news:c62ums$b3b$1 at atlantis.news.tpi.pl... > Hi, > > I have a string. > This string is to be used as a path for a new file. > I would like to check if this string *could be* a valid file name, > *before* I try to create the file itself. > In other words, I would like to know whether some string violates the > underlying OS's policies (or maybe some more restriced policies, but > portable) considering file paths. > > Example: > > 1. > s = 'C:\file.txt' > > the above is potentially a valid path on my system. > > 2. > s = 'cc:/^- =#jk\kj+.+?! :-)' > > the above is rather invalid and I would like to check it somehow before > I even try to create the file. > > Does the Python library contain a functionality that allows to achieve > this goal? > > -- > Maciej Sobczak : http://www.msobczak.com/ > Programming : http://www.msobczak.com/prog/ > From reverse.ku.oc.issolok at nothypgnal.delrest.co.uk Wed Apr 28 04:46:43 2004 From: reverse.ku.oc.issolok at nothypgnal.delrest.co.uk (Paul Sweeney) Date: Wed, 28 Apr 2004 08:46:43 +0000 (UTC) Subject: sending an object - twisted or what? References: <20040427152051.50234c65.mutah@NOSPAM-libertysurf.fr> Message-ID: "Mutah" wrote in message news:20040427152051.50234c65.mutah at NOSPAM-libertysurf.fr... > On Tue, 27 Apr 2004 13:00:17 +0000 (UTC) > Paul Sweeney wrote: > > > Is twisted the only way to go, or is there something > > simpler for my app? The code for twisted is fairly simple (I found > > http://twistedmatrix.com/documents/current/howto/pb-copyable) > > but the library is a bit heavy and I don't want to go through the > > hassle of dependencies/compiling etc if there's a simpler way. > > > > > Using only modules shipped with python, a simpler way (in term of > dependencies only) would be to pickle the objects and > then send the result throught a socket. > > On the other side, you may need to write more code to do that. > I was considering that but there is all the associated problems of knowing when a complete object has been received, guarding against spoof data being received from the internet etc. It is a case of balancing "reinventing the wheel" vs getting a pre-built wheel but with a huge road-train undesirably attached. Paul From peter at engcorp.com Fri Apr 2 11:45:20 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 02 Apr 2004 11:45:20 -0500 Subject: emergent/swarm/evolutionary systems etc In-Reply-To: References: Message-ID: Peter MacKenzie wrote: > Peter Hansen + Mickel Gr?nroos, (unsure of a more suitable intro protocol > for this environment + situation) > > Oh the joy! It makes life worth living when things click into place and > make sense. My style of learning seems ill suited to the material available > on the subject, so although I had indeed read all that I could find on > making files, it was presented in a manner that I couldn't quite comprehend. > To elaborate, I process linguistic information in a holistic, intuitive > manner; a quality that requires for me to develop a 'feel' for the language > in question, rather than a literal understanding of the rules. > > Because of this, I need full-yet-simple working examples to deconstruct and > process. Most of the examples I've come across have been fragmented and > incomplete, which leaves me grasping at loose ends and the countless > possibilities therein. It's as though somebody had handed me at birth a > dictionary and a set of grammatical rules, with the expectation that I would > be able to piece it all together and learn to communicate. Sounds like you should check out www.diveintopython.org, which as I recall has quite full examples. If you haven't read it already do so. The only other thing I can suggest is spend less time defending your way of learning things :-) and more time just *doing* it. Write code, and when it doesn't work at first, experiment. Python should be learned with the interactive interpreter prompt right in front of you, typing and watching and learning... Anyway, keep at it. Python is certainly one of the easiest if not the easiest modern language to learn (IMHO) so you should find yourself making relatively good progress, whatever your difficulties. -Peter From eppstein at ics.uci.edu Fri Apr 9 11:52:47 2004 From: eppstein at ics.uci.edu (David Eppstein) Date: Fri, 09 Apr 2004 08:52:47 -0700 Subject: print u"\u0432": why is this so hard? UnciodeEncodeError References: Message-ID: In article , "Martin v. Lowis" wrote: > David Eppstein wrote: > > Well, no. > > > > Python 2.3 (#1, Sep 13 2003, 00:49:11) > > [GCC 3.3 20030304 (Apple Computer, Inc. build 1495)] on darwin > > Type "help", "copyright", "credits" or "license" for more information. > > > >>>>import sys;sys.stdin.encoding > > > > 'US-ASCII' > > You did not follow Hye-Shik's instructions closely enough. You > failed to set the LANG environment variable before starting Python. A system that requires me to manually set the LANG environment variable is no better than a system that requires me to manually define an encoding once in Python. It doesn't seem to answer your question about automatic determination of the Terminal's encoding. -- David Eppstein http://www.ics.uci.edu/~eppstein/ Univ. of California, Irvine, School of Information & Computer Science From johnbunderwood at yahoo.ca Tue Apr 6 09:45:14 2004 From: johnbunderwood at yahoo.ca (John Underwood) Date: Tue, 06 Apr 2004 09:45:14 -0400 Subject: Using python23 to develop an extension for an application that has python22 embedded References: <1073eeubflmchd5@corp.supernews.com> <1073vcag51uufe9@corp.supernews.com> Message-ID: On Mon, 5 Apr 2004 17:44:55 -0700, "Michael Geary" wrote: >John Underwood wrote: >> I have both 2.2 and 2.3 installed on my computer. My problem has to do >> with Visual Studio .NET which will build 2.3 but will not build 2.2. >> (MS removed largeint.h which is required by pythoncore in 2.2 when >> they went from Visual C++ 6 to VS.NET. I tried supplying largeint.h to >> VS.NET but that did not work.) >> >> Since I cannot build 2.2, I do not have python22.dll or python22_d.dll >> (the debug version). (They are not shipped with python you have to >> produce them yourself.) > >The executable Python installer for Windows does install pythonXX.dll. You >should find python22.dll and python23.dll in your Windows system32 >directory. > >Do you need python22_d.dll at all? I would think you'd need it only if you >were actually debugging the Python interpreter itself. I've never needed a >debug version of the Python DLL to debug ordinary Python code. > >> The commercial application to which I need to add an extension has >> python22.dll in its runtime folder. I have no control over this >> application and have to use whichever version they have chosen. > >Paint Shop Pro? Curious Labs - Poser 5 > >> Since I do have python23.dll and python23_d.dll (from a successful >> build of 2.3), can I use these to develop an extension for the >> aforementioned commercial application if I stay away from any new >> features in 2.3 (but not in 2.2)? > >Are you talking about source code compatibility only? Sure, as long as you >use only language features available in both the old and new versions. You >can't use .pyc bytecode files from one version with a different version. > Yes, although I'll have to check into the .pyc bytecode issue - which I don't think is a problem. >Anyway, I must be missing something here, because I would think you could >simply develop with your installed Python 2.2 and run the code under your >target application. You shouldn't have to be worrying about any of the stuff >you're dealing with. > May be it comes down to the approach taken to debug an extension. (I'm new to Python - as you've probably guessed - and debugging mixed language situations.) To use the dubugging features of Visual Studio to debug my extension code, I thought I needed to use python22_d.dll (the debug version fo python22.dll). Is this correct? If so, I have not been able to produce it with Visual Studio .NET because of the problems VS has with 2.2. On the other hand, would it be better to debug the extension without the Python interface (in other words, debug the internals of the extension that are not dependent on Python) before attempting to test the Python interface (which could be performed with python22.dll)? -John From michele.simionato at poste.it Wed Apr 7 06:05:33 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 7 Apr 2004 03:05:33 -0700 Subject: OFF-TOPIC:: Why Lisp is not my favorite programming language References: <165b3efa.0403030443.4d591f04@posting.google.com> <40460dd5$0$5916$7a628cd7@news.club-internet.fr> <6in670lrldbjkuujle68a526293j57a7mn@4ax.com> Message-ID: <95aa1afa.0404070205.94b32e4@posting.google.com> Stephen Horne wrote in message news:<6in670lrldbjkuujle68a526293j57a7mn at 4ax.com>... > LISP is normally interpreted - maybe always, I think you will be crucified for that affirmation. Anyway, here is an interesting thread talking about Lisp optimizations: http://groups.google.it/groups?hl=it&lr=&ie=UTF-8&threadm=95aa1afa.0402262158.5b33de79%40posting.google.com&rnum=1&prev=/groups%3Fhl%3Dit%26lr%3D%26ie%3DISO-8859-1%26q%3Dsimionato%2Bfeature%2Brequest%26btnG%3DCerca%2Bcon%2BGoogle%26meta%3Dgroup%253Dcomp.lang.python.* The gist is "Lisp can be faster than C/C++". Michele Simionato From http Wed Apr 14 14:02:44 2004 From: http (Paul Rubin) Date: 14 Apr 2004 11:02:44 -0700 Subject: Difficulty Finding Python Developers References: <65cbc3dd.0404140641.3501fde8@posting.google.com> Message-ID: <7xd66aigjf.fsf@ruckus.brouhaha.com> pm_mon at yahoo.com (Paul Morrow) writes: > We've worked hard to convince our company to migrate our core > applications to Python, and now we're looking for a Python developer > in Atlanta to handle a short-term (approx. 3 month) project. But our > initial searches have been fairly unsuccessful. We haven't actually > posted a job on Monster, but we have been talking with various > headhunters in our area and they don't have many resumes that show > Python experience. An so now, of course, mgt is wondering whether > selecting Python was a mistake. > > As anyone had a similar experience? Suggestions? I think nobody minds when people post Python jobs to this newsgroup. In fact I bet you're getting queries already. What's the project? From alloydflanagan at comcast.net Wed Apr 21 14:03:43 2004 From: alloydflanagan at comcast.net (A. Lloyd Flanagan) Date: 21 Apr 2004 11:03:43 -0700 Subject: CamelCase versus wide_names (Prothon) References: <407F3F20.DB8FA765@alcyone.com> Message-ID: "Mark Hahn" wrote in message news:... > "Erik Max Francis" wrote ... > > > I'm surprised you're creating your own language and don't have enough > > internal stylistic sense to make this choice yourself. > FWIW, Mark, I'm with you on this one. Standardizing variable names isn't exactly what I'd call a "deep" design decision. What's wrong with asking experienced programmers what works best? Speaking of which -- camelCase, definitely. Unless you want to allow spaces in your variable names... :) From ptmcg at austin.rr._bogus_.com Wed Apr 14 07:19:08 2004 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Wed, 14 Apr 2004 11:19:08 GMT Subject: spherical coordinates References: <20040414111334.34b5d225@pistache.sara.nl> <7x1xmqua94.fsf@ruckus.brouhaha.com> Message-ID: "Paul McGuire" wrote in message news:dX8fc.587$lp3.280 at fe2.texas.rr.com... > "Paul Rubin" wrote in message > news:7x1xmqua94.fsf at ruckus.brouhaha.com... > > Peter Maas writes: > > > r = sqrt(x**2 + y**2) > > > phi = atan(y/x) > > > > Better use phi=atan2(y,x) in case x=0. Similarly for the other atan > calls. > > These are formulas for cylindrical coordinates. The OP was asking for > spherical coordinates rho, theta, and phi, where: > > rho = distance from origin (similar to r in cylindrical coords) > theta = angle from the positive x axis of the xyz vector projection onto the > x-y plane (just like theta in cylindrical coords) > phi = angle of the xyz vector from the x-y plane > > To convert from spherical to Cartesian: > > x = rho * sin(phi) * cos(theta) > y = rho * sin(phi) * sin(theta) > z = rho * cos(phi) > > From Cartesian to spherical: > > rho = sqrt(x**2 + y**2 + z**2) > theta = atan2(y, x) > if rho != 0.0: > phi = acos( z / rho ) > else: > phi = pi / 2 * sgn(z) > > I can imagine that all these conversions could be a performance killer if > done entirely in Python, and could stand to be done as a C extension. This > is probably why the OP was asking if such a package already exists. > > -- Paul > > (Hmm, the math module doesn't have a sgn() function. Is this difficult to > add?) > > D'oh - that's what I get for pulling formulas off the web and not reviewing the material!!! phi = angle of the xyz vector from the positive z-axis phi = acos( z / rho) Sorry! http://www.math.montana.edu/frankw/ccp/multiworld/multipleIVP/spherical/body.htm From daniel at syrinx.net Mon Apr 5 19:51:43 2004 From: daniel at syrinx.net (Daniel Ellison) Date: Mon, 5 Apr 2004 19:51:43 -0400 Subject: [maybe OT] Making posters References: <95aa1afa.0404030143.58c32975@posting.google.com> <95aa1afa.0404050650.2d39b1a5@posting.google.com> Message-ID: "Michele Simionato" wrote: > What I do not understand is if the "scale" operator automatically splits > the graph in many pages if it becomes too large. Probably not. As I said, it's been a few years, but I would suspect the "scale" operator simply scales the user coordinate system by the proportions given so that everything drawn after that command will be rendered accordingly. It's most likely the host application or utility that splits the image into multiple pages. Dan From rjt-usenet at thegrindstone.me.uk Wed Apr 21 09:35:58 2004 From: rjt-usenet at thegrindstone.me.uk (Richard Taylor) Date: Wed, 21 Apr 2004 13:35:58 +0000 Subject: Passing argument to setsockopt(socket.SOL_SOCKET, IN.SO_BINDTODEVICE, intr) References: <408640b7$0$31671$fa0fcedb@lovejoy.zen.co.uk> <40866792$0$31708$fa0fcedb@lovejoy.zen.co.uk> Message-ID: <408678be$0$31680$fa0fcedb@lovejoy.zen.co.uk> Jeff Epler wrote: > On Wed, Apr 21, 2004 at 12:22:41PM +0000, Richard Taylor wrote: >> The answer is: >> >> s.setsockopt(socket.SOL_SOCKET,IN.SO_BINDTODEVICE,struct.pack("%ds" % >> (len("eth0")+1,), "eth0")) >> Richard Taylor wrote: > > Maybe this is simpler: > #dev = "eth0" > s.setsockopt(..., dev + '\0') > I think it has the same effect as your code, but it is a little clearer > to me that the setsockopt call needs a zero-terminated C string as its > argument. > > Jeff You are right. I did not realise that you could append a null in that way. Thanks. Richard From hungjunglu at yahoo.com Thu Apr 8 18:50:12 2004 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 8 Apr 2004 15:50:12 -0700 Subject: Are line continuations needed? References: <1078dq6i93pc12d@news.supernews.com> <1078skqn9hgdd19@corp.supernews.com> <1079015hfg56i28@news.supernews.com> <4596f01b3d76279a6c75379203735ded@news.teranews.com> Message-ID: <8ef9bea6.0404081450.3b82e96f@posting.google.com> Dang Griffith wrote in message news:<4596f01b3d76279a6c75379203735ded at news.teranews.com>... > On 8 Apr 2004 08:32:02 GMT, Duncan Booth wrote: > > > >mystring = """\ > >+---------------+ > >| '" | > >+---------------+ > >""" > > > mystring = ( > """+---------------+\n""" > """| '" |\n""" > """+---------------+""" > ) mystring = """ +---------------+ | '" | +---------------+ """ [1:] Hung Jung From fumanchu at amor.org Thu Apr 29 18:59:52 2004 From: fumanchu at amor.org (Robert Brewer) Date: Thu, 29 Apr 2004 15:59:52 -0700 Subject: static keyword Message-ID: I wrote: > > >>> def foo(): > > ... i = 10 > > ... print "First pass" > > ... while True: > > ... i += 1 > > ... yield i > > ... > > >>> g = foo() > > >>> g.next() > > First pass > > 11 > > >>> g.next() > > 12 and Nick Jacobson replied: > Yes, that is excellent. Thank you very much. :) > > The good news: you can reset all your "static" data whenever you want, > by calling foo(). Can't do that in C. > > The bad news: I just hope I don't forget and call foo() instead of > g.next(). > I would rather the command foo() by default call the next iteration, > and, say, foo().reset() would recall the function from scratch. It all comes down to naming, for me. When you make a generator, name it as a generator, not as one of the produced items. That is, for the above, you would never name it next_item(), because that gives the wrong idea: >>> g = next_item() >>> next_item() ...as you can see, the last line throws you because you didn't get what you might expect from a functional perspective. However, if I name it count_from_eleven, which would then read as: >>> g = count_from_eleven() >>> count_from_eleven() ...that problem goes away, because the last call doesn't "read" right. You'd never write it, because the name signals to you that you're doing The Wrong Thing. Robert Brewer MIS Amor Ministries fumanchu at amor.org From FBatista at uniFON.com.ar Wed Apr 28 13:26:36 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Wed, 28 Apr 2004 14:26:36 -0300 Subject: Formatting Currency According to Locale Message-ID: [Daniele Varrazzo] #- Is it up to me to write a function to keep all these details #- into account? These issues will be handled inside the Money module. Hey! I first need to finish the Decimal module, ;) If you want to help, can start with PEP 327 for the Decimal module. I posted a pre-PEP for the Money module to the list, you can read those posts also (in both standard and developers list, you can search them in google). . Facundo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA La informaci?n contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener informaci?n confidencial o propietaria, cuya divulgaci?n es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no est? autorizado a divulgar, copiar, distribuir o retener informaci?n (o parte de ella) contenida en este mensaje. Por favor notif?quenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magn?tico) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telef?nica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electr?nicos pueden ser alterados, motivo por el cual Telef?nica Comunicaciones Personales S.A. no aceptar? ninguna obligaci?n cualquiera sea el resultante de este mensaje. Muchas Gracias. -------------- next part -------------- An HTML attachment was scrubbed... URL: From david at rebirthing.co.nz Thu Apr 15 05:27:44 2004 From: david at rebirthing.co.nz (David McNab) Date: Thu, 15 Apr 2004 21:27:44 +1200 Subject: ANN: YahooQuote module Message-ID: <407E5590.7060505@rebirthing.co.nz> Announcing YahooQuote, probably the easiest and most convenient API for downloading (and caching) stockmarket prices off the internet. http://www.freenet.org.nz/python/yahooquote I know it's not the first python module for pulling yahoo stockmarket quotes. It's not even original code - the fetching/caching/parsing engine is ripped verbatim (under the GPL) from Rimon Barr's 'pyq' utility. I've just wrapped it into some cushy high-level classes. But I do believe it's the most natural, pythonic and easily learned API for accessing ticker prices, accumulating an historical database, and using in other python programs (eg your favourite neural net algorithm-du-jour for technical analysis). Enjoy Cheers David From theller at python.net Tue Apr 27 02:48:38 2004 From: theller at python.net (Thomas Heller) Date: Tue, 27 Apr 2004 08:48:38 +0200 Subject: Problem with PY2EXE and VPython References: Message-ID: "bap" writes: > When I try to run a program on a clean machine using the VPython extensions > after compiling with PY2EXE I get the following error message: "The > procedure entry point IsWow64Process could not be located in the dynamic > link library KERNEL32.dll" . The compiled version runs fine on the original > machine (win NT OS) but gives this error message on a machine without > VPython installed (Win 2K OS). Is this anything that can be fixed with > appropriate parameters in PY2EXE or does it require that VPython be tweaked? This error looks like that py2exe is picking up some 'system dlls' into the dist directory, which are (sometimes) system specific. If you post the list of files that are in the dist directory, it might be possible to name them. Earlier versions of py2exe had a builtin list of dlls which should be ignored, this list will again be in the next version. Thomas From newsgroups at jhrothjr.com Sun Apr 4 21:44:01 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Sun, 4 Apr 2004 21:44:01 -0400 Subject: Advocacy opportunity References: <10719mdp83juif4@corp.supernews.com> Message-ID: <1071eiaddi7mo95@news.supernews.com> "Cameron Laird" wrote in message news:10719mdp83juif4 at corp.supernews.com... > I've been advised that > > is open to correction in its Python column. Who wants to tackle > this? Python certainly supports interaction, we have plenty to boast > about in regard to foreign functions, we offer GUIs in abundance, ... > > They seem rather liberal. If Python supports private methods and > variables (and JavaScript does native threads!?!) (but somebody seems > to have it in for C++), we might as well argue it gives root classes, > too. I wouldn't. To me, a root class is a common class that is **the** root of the object hierarchy, in some useful sense such as contributing numerous common methods. Granted, new style classes are rooted in object, but object doesn't seem to contribute much except for __getattribute__. > I think if I had friends who were salesmen, they'd advise me, "You > just mark, 'Yes', everywhere, and deal with it if someone argues." Jason Voegele's paper also needs some corrections. (Pixeldate's seems to go to a porn site.) I see your point: there are a huge number of question marks in the Python column. Some of them I don't know how to fill out, and a few of them I don't know what he's talking about, frankly. John Roth > -- > > Cameron Laird > Business: http://www.Phaseit.net From get at bent.com Thu Apr 8 05:14:32 2004 From: get at bent.com (nobody) Date: Thu, 8 Apr 2004 19:14:32 +1000 Subject: Non-math-geek needs help with CRCs (binascii.crc32) References: <4073c865$0$27642$61ce578d@news.syd.swiftdsl.com.au> Message-ID: <40751603$0$27643$61ce578d@news.syd.swiftdsl.com.au> > http://www.ross.net/crc/ That doesn't seem to mention anything about poly $EDB88320, which is the code I'm trying to a) be compatible with, b) define for future developers so they don't have to go through this whole mess. It appears whatever Python uses is compatible, but stating the poly by itself doesn't mean anything. Somehow, depending on how the numbers are massaged, the old code based on $EDB88320 is compatible with what the above site documents as $04C11DB7. This is all very confusing.. From elainejackson7355 at home.com Thu Apr 8 02:14:38 2004 From: elainejackson7355 at home.com (Elaine Jackson) Date: Thu, 08 Apr 2004 06:14:38 GMT Subject: list comprehensions References: Message-ID: OK, it's pretty embarassing that I gave up when it wasn't in the contents and never even thought of the index. And so far everybody's been too polite to point out that I left the base case out of my recursion. But I stand by my complaint about unintuitiveness, because I've discovered that you get an error from x = [(i,j) for i in range(7-j) for j in range(3)] while y = [[(i,j) for i in range(7-j)] for j in range(3)] works fine. In other words, my intuition was that x would be reduce(list.__add__,y). And in fact I'm still a little confused, because I would describe the syntax of y as going, as you say, from left to right (ie: a left-branching tree). I suppose I'm going from the inside out, and you're talking about going from the outside inward. Or something like that. Anyway, thanks for your help. Now that I know what to read, I'll read it. Peace "Terry Reedy" wrote in message news:mailman.434.1081374131.20120.python-list at python.org... | | "Elaine Jackson" wrote in message | news:yjZcc.42823$Pk3.9547 at pd7tw1no... | > | > List comprehensions don't work the way you intuitively expect them to | work. | | One of my pet posting peeves is when people ascribe their own | characteristics to others, as when they write 'you' when they really mean, | or should have meant, 'I'. But nevermind. | | > I realize many people have no intuitions about how list comprehensions | 'should' | > work, | | List comprehensions are sufficiently 'artificial' that I would advise | anyone to avoid the temptation to intuit how they work without consulting | the manual, tutorials, or other written explanations. | | The Python Reference Manual Index, section L, entry List..comprehensions | takes one to subsection 5.2.4 List displays. The last two sentences | therein read | | "When a list comprehension is supplied, it consists of a single expression | followed by at least one for clause and zero or more for or if clauses. In | this case, the elements of the new list are those that would be produced by | considering each of the for or if clauses a block, nesting from left to | right, and evaluating the expression to produce a list element each time | the innermost block is reached." | | OK, takes a couple of readings and maybe some working examples. | | > partitions = lambda n: [[n]]+[[k]+x for x in partitions(n-k) for k in | > range(1,n)] | > | > As defined above, the function raises an exception when you call it ('k' | > referenced before assignment). | | Of course, you have the two for clauses reversed, as the error message | might suggest to an experienced Pythoneer. As the manual specifies, for/if | clauses nest *left to right*. To match the double loop below, you want | instead | | [[k]+x for k in range(1,n) for x in partitions(n-k)] | | > def partitions(n): | > reVal=[[n]] | > for k in range(1,n): | > for x in partitions(n-k): | > reVal.append([k]+x) | > return reVal | | Terry J. Reedy | | | | From richardd at hmgcc.gov.uk Mon Apr 5 05:22:11 2004 From: richardd at hmgcc.gov.uk (richardd) Date: Mon, 5 Apr 2004 10:22:11 +0100 Subject: Reading binary using a struct - behavour not as expected? Message-ID: <40712544$1@mail.hmgcc.gov.uk> Hi, I am writing code to deal with PCAP files. I have a PCAP dump and I am looking at the timestamps in the PCAP packet headers to see if they are in the correct order in the file. To do this I have a class called PCAPPacketHdr as follows import struct class PCAPPacketHdr: FormatString = "LLLL" TSSec = None TSUSec = None InclLen = None OrigLen = None def Pack(self): return struct.pack( self.FormatString, self.TSSec, self.TSUSec, self.InclLen, self.OrigLen ) def Unpack(self, buffer): self.TSSec, self.TSUSec, self.InclLen, self.OrigLen = struct.unpack( self.FormatString, buffer ) def Size(self): return struct.calcsize (self.FormatString) I then have code which opens up the file (skipping the PCAP file magic number and PCAP file header), and reads in each packet header as follows: while not eof: #read in PCAPPacketHdr buf = curFile.read(packetHdr.Size()) if len(buf) == packetHdr.Size(): packetHdr.Unpack(buf) if lastPacketHdr != None: if lastPacketHdr.TSSec > packetHdr.TSSec: outputFile.write("ERROR: Packet TSSec earlier than last one: \n") outputFile.write(" Last Packet "+repr(lastPacketHdr.TSSec)+"."+repr(lastPacketHdr.TSUSec)+"\n") elif lastPacketHdr.TSSec == packetHdr.TSSec: if lastPacketHdr.TSUSec > packetHdr.TSUSec: outputFile.write("ERROR: Packet TSUSec earlier than last one\n") outputFile.write(" Last Packet "+repr(lastPacketHdr.TSSec)+"."+repr(lastPacketHdr.TSUSec)+"\n") outputFile.write(" Packet "+repr(packetHdr.TSSec)+"."+repr(packetHdr.TSUSec)+"\n") lastPacketHdr = copy.deepcopy(packetHdr) #skip packet payload packetPayload = curFile.read(packetHdr.InclLen) else: eof = True This code appears to work fine for extracting the timestamps from the file, the repr( ) calls on the timestamps allow me to write them to the output file correctly, it's just the comparison operators don't appear to be working as I would expect. It appears than when the TSUSec timestamp is the same as the previous one in the data I input, it reports "ERROR: Packet TSUSec earlier than last one". This makes me think that the comparison operators aren't acting on the data as longs as I expected. Can anyone shed some light on what I'm doing wrong, I'm still very new to Python. Thanks in advance, Rich From martin at v.loewis.de Mon Apr 12 14:27:45 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 12 Apr 2004 20:27:45 +0200 Subject: print u"\u0432": why is this so hard? UnciodeEncodeError In-Reply-To: <16505.58626.39783.581506@montanaro.dyndns.org> References: <16505.58626.39783.581506@montanaro.dyndns.org> Message-ID: Skip Montanaro wrote: > Martin> I wonder how much would break if Python would assume the > Martin> terminal encoding is UTF-8 on Darwin. Do people use different > Martin> terminal encodings? > > I generally use xterm instead of Terminal.app. I think it's encoding is > latin-1. Not on OS X. Terminal.App is a software package completely different from xterm. For one thing, xterm is for X11, whereas Terminal.App is for Window Server (or whatever the name of the Apple GUI is). It may be that Apple has changed the defaults at some time, but atleast on my installation, the default encoding of Terminal.App for all users is UTF-8. Regards, Martin From peter at engcorp.com Thu Apr 22 06:19:49 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 22 Apr 2004 06:19:49 -0400 Subject: AOP use cases In-Reply-To: References: <84fc4588.0404140106.3fa0c55@posting.google.com> <0pydnSB4WYuieuLdRVn-hQ@powergate.ca> Message-ID: Jacek Generowicz wrote: (a lengthy reply, and thank you for taking the time!) > Peter Hansen writes: >>I would be very interested to hear some real-world and real useful >>use cases for AOP as well. > > AOP is about separation of concerns. Let me repeat that: AOP is about > SEPARATION OF CONCERNS. [snip] > As for real world examples ... if you think of AOP as separation of > concerns which you want to be weaved together, then I am sure that you > will be able to come up with plenty of excellent real world examples > yourself. Unfortunately, that's just my point. So far I haven't been able to do that, it seems. The example posted previously with the "synchronization wrapper" approach is, however, quite understandable and comes from real-world experience that many of us share. Is that AOP? Is it not AOP? If it's an application of AOP principles, then is AOP anything other than a good practice which some of us have been doing for years, prettied up with a nice name. In other words, Just Another Pattern? Jacek, I appreciate the attempt to clarify, but so far it seems to me that *everyone* who talks about AOP just talks in abstract terms and isn't willing (or able?) to pin it down with *real* real-world examples, just "imagine this" or "wouldn't it be nice if". You seem to be someone who understands AOP well: do you use it? Could you please provide an example from your own uses which demonstrates the effectiveness of AOP versus "not AOP" in the same way that the synchronization example posted earlier is clearly better when done as a wrapper than with the code duplicated everywhere (i.e. with the "concerns" not separated)? -Peter From BrenBarn at aol.com Thu Apr 15 11:50:01 2004 From: BrenBarn at aol.com (OKB (not okblacke)) Date: 15 Apr 2004 15:50:01 GMT Subject: CamelCase versus wide_names (Prothon) References: Message-ID: Mark Hahn wrote: > Of course in the Python world you alread have wide_names as your > standard, but could you for the moment pretend you were picking > your standard from scratch (as we are doing in the Prothon world) > and give your vote for which you'd prefer? camelCase, hands down. Underscores are much too difficult to type, and in my opinion should be avoided except when you WANT a hard-to-type identifier (as with private variables, etc.). -- --OKB (not okblacke) Brendan Barnwell "Do not follow where the path may lead. Go, instead, where there is no path, and leave a trail." --author unknown From aahz at pythoncraft.com Fri Apr 2 15:13:50 2004 From: aahz at pythoncraft.com (Aahz) Date: 2 Apr 2004 15:13:50 -0500 Subject: Simple text markup (-> HTML) References: <406D3EAA.16466030@alcyone.com> Message-ID: In article , Jacek Generowicz wrote: >Erik Max Francis writes: >> Jacek Generowicz wrote: >>> >>> I'm looking for something to help developers wirte documentation for >>> bits of software they are writing. >> >> reStructredText. Bigtime. > >Way cool ! > >I am rather shocked that this (or its ancestors) has not registered on >my radar before now. You should be shocked. ;-) It's been discussed lots. The really neat thing about reST is that it scales upward fairly well -- I'm writing a book with it, and so is at least one other person. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "usenet imitates usenet" --Darkhawk From james at ractive.ch Mon Apr 12 09:46:42 2004 From: james at ractive.ch (Jean-Pierre Bergamin) Date: Mon, 12 Apr 2004 15:46:42 +0200 Subject: How to kill a SocketServer? Message-ID: Me again... :-) Is there any possibility to kill a SocketServer that was started like this: class ServerThread(threading.Thread): class MyHandler(SocketServer.StreamRequestHandler): def handle(self): line = self.rfile.readline() self.wfile.write(line.upper()) def run(self): s = SocketServer.TCPServer(('', 1234), self.MyHandler) s.server_forever() def stop_server() # Any chance to stop the server here??? what_to_do() # ???????? server_thread = ServerThread() server_thread.start() # do other things server_thread.stop_server() The problem is, that I found no way to interrupt the blocking call to self.rfile.readline(). Is there a way to do that? Using an asynchronous server is not an option. Thanks in advance James From jacek.generowicz at cern.ch Fri Apr 2 10:26:35 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 02 Apr 2004 17:26:35 +0200 Subject: Python conference slogan References: <30260531.0404010833.1b834032@posting.google.com> <406C4DDF.5000907@zope.com> Message-ID: Peter Maas writes: > These slogans are meaningless to (Monty) Python outsiders. As I > understand this thread there is a need for a slogan that is short, > not too hard to understand and unforgettable (probably a definition > of the word slogan). Python insiders don't need a slogan at all. A previous slogan was: Python: Programming the way Guido indented it. Pretty meaningless to Python outsiders, I'd say. From no_replies at fake_email_address.invalid Sun Apr 18 17:42:40 2004 From: no_replies at fake_email_address.invalid (Robert Oschler) Date: Sun, 18 Apr 2004 17:42:40 -0400 Subject: Python/Win based report generator for MySQL databases Message-ID: <%zCgc.59345$oj6.9111@bignews6.bellsouth.net> Has anybody seen a nice Python 2.2+ compatible based module/package, running on a Win2k box, that makes creating reports from a MySQL database easy? I am both a Python programmer and MySQL programmer so it doesn't have to be too simple, just useful. Thanks Robert From grace-request at plasma-gate.weizmann.ac.il Sun Apr 11 21:29:04 2004 From: grace-request at plasma-gate.weizmann.ac.il (grace-request at plasma-gate.weizmann.ac.il) Date: Mon, 12 Apr 2004 04:29:04 +0300 Subject: **SPAM-W** *Your information In-Reply-To: <200404120128.i3C1SwcZ011747@plasma-gate.weizmann.ac.il> References: <200404120128.i3C1SwcZ011747@plasma-gate.weizmann.ac.il> Message-ID: <200404120129.i3C1T4bs011776@plasma-gate.weizmann.ac.il> Sorry, but submissions to this list is restricted to its members. For bug reports and suggestions related to Grace please follow links found at http://plasma-gate.weizmann.ac.il/Grace/ You will also find there info on how to subscribe to the mailing list. This is a multi-part message in MIME format. ------=_NextPart_000_0016----=_NextPart_000_0016 Content-Type: text/plain; charset="Windows-1252" Content-Transfer-Encoding: 7bit *** eSafe-W detected hostile content in this email and removed it. *** \presentation_document4.pif Infected with Win32.Netsky.s (Non-Removable), Blocked The presentation document. Thank you +++ X-Attachment-Type: document +++ X-Attachment-Status: no virus found +++ Powered by the new Norton OnlineAntiVirus +++ Free trial: www.norton.com ------=_NextPart_000_0016----=_NextPart_000_0016-- From frank at chagford.com Mon Apr 5 10:26:23 2004 From: frank at chagford.com (Frank Millman) Date: 5 Apr 2004 07:26:23 -0700 Subject: Simple db using list comprehensions Message-ID: <246a4e07.0404050626.153ff525@posting.google.com> Hi all >From time to time there is a request for a simple way of storing and accessing data without using a full SQL database. I had this requirement recently, and I was pleasantly surprised by how much I could achieve with a simple Python list and list comprehensions. Assume the need to store data consisting of first name, surname and phone number. To ensure uniqueness, I use an additional column to store a unique id, which can just be a 'next number'. To create the table - table = [] To initialise it with a couple of rows - table.append([1,'Frank','Millman',12345]) table.append([2,'John','Smith',54321]) To get the last id used - last_id = max([row[0] for row in table]) Alternatively, if you know the rows are in id sequence - last_id = table[-1][0] To add a new row - firstname = 'Fred' surname = 'Jones' phone = 23456 First, ensure first name and surname are unique - rows = [row for row in table if row[1] == firstname and row[2] == surname] if len(rows): errmsg = 'Already exists' If ok, add the row - last_id += 1 table.append([last_id,firstname,surname,phone]) To select all rows according to some criteria (eg surnames starting with 'M') - rows = [row for row in table if row[2][0] == 'M'] If you need a copy of the rows - rows = [row[:] for row in table if row[2][0] == 'M'] To sort the rows in surname sequence - rows = [[row[2],row] for row in rows] # prepend surname to row for sorting rows.sort() rows = [row[1] for row in rows] # remove prepended surname To select and sort at the same time - rows = [[row[2],row] for row in table if row[2][0] == 'M'] rows.sort() rows = [row[1] for row in rows] To amend a phone number if you know the first name and surname - rows = [row for row in table if row[1] == 'Fred' and row[2] == 'Jones'] if not rows: errmsg = 'not found' elif len(rows) > 1: errmsg = 'more than one row found' else: rows[0][3] = phone To delete a row if you know the first name and surname - rows = [row for row in table if row[1] == 'Fred' and row[2] == 'Jones'] if not rows: errmsg = 'not found' elif len(rows) > 1: errmsg = 'more than one row found' else: pos = [row[0] for row in table].index(rows[0][0]) del table[pos] To delete all rows with a phone number of 0 - ids = [row[0] for row in table] rows = [row[0] for row in table if row[3] == 0] for row in rows: pos = ids.index(row) del table[pos] del ids[pos] I have not tested all of these, but you get the idea. I did not have to save the data, but if you need to, I am sure you can pickle it. Hope this is of interest. Frank Millman From sholden at holdenweb.com Wed Apr 21 19:58:10 2004 From: sholden at holdenweb.com (Steve Holden) Date: Wed, 21 Apr 2004 19:58:10 -0400 Subject: NVidia Gelato has Python binding References: Message-ID: "Terry Reedy" wrote in message news:mailman.881.1082583742.20120.python-list at python.org... > >From http://film.nvidia.com/page/gelato.html : > > Gelato is NVIDIA's new professional image rendering software, running on > top of its new Quadro FX graphics hardware. In addition to its C++ API, > > "A Python binding also ships with Gelato, allowing users to script input, > automatically generating geometries and shading instead of explicitly > specifying them in advance. " > > This is the only such binding mentioned. They apparently feel that Python > is well enough known that no explanatory phrase is needed. > It probably *is* well-known in the target market, since Industrial Light and Magic are a very well-known Python user. regards -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ From amk at amk.ca Thu Apr 15 14:49:41 2004 From: amk at amk.ca (A.M. Kuchling) Date: Thu, 15 Apr 2004 13:49:41 -0500 Subject: CamelCase versus wide_names (Prothon) References: Message-ID: On Thu, 15 Apr 2004 08:17:08 -0700, Mark Hahn wrote: > Of course in the Python world you alread have wide_names as your standard, > but could you for the moment pretend you were picking your standard from > scratch (as we are doing in the Prothon world) and give your vote for which > you'd prefer? Wide_names: for a while I wrote code using mixedCase, but subsequently switched back; the resulting method/function names are easier to read and to talk about. --amk From hungjunglu at yahoo.com Tue Apr 20 17:41:56 2004 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 20 Apr 2004 14:41:56 -0700 Subject: Editing/Writing Word-Files from Python References: Message-ID: <8ef9bea6.0404201341.405beb5@posting.google.com> Daniel Cloutier wrote in message news:... > > is it possible to edit or write Word-files out of a Python-Program? Yes. (a) You need the win32all modules from Mark Hammond. (b) To try out the object model of MS Word, press ALT+F11 to bring up the VBA environment, then F2 to view the object browser. It's a complicated subject. ------------------------------------------- import pythoncom from win32com.client import Dispatch app = Dispatch('Word.Application') app.Visible = 1 doc = app.Documents.Add() s = doc.Sentences(1) s.Text = 'This is a test.' doc.SaveAs('C:\\mydoc2.doc') app.Quit() app = None pythoncom.CoUninitialize() -------------------------------------------- You may want to add better exception handling, otherwise, you may often have danggling processes when exceptions happen. (You'll then have to manually kill them from the task manager.) regards, Hung Jung From dmq at gain.com Tue Apr 27 19:35:36 2004 From: dmq at gain.com (David MacQuigg) Date: Tue, 27 Apr 2004 16:35:36 -0700 Subject: Ideas for Python 3 Message-ID: I am starting a new thread so we can avoid some of the non-productive argument following my earlier post "What is good about Prothon". At Mr. Hahn's request, I will avoid using the name "Prothon" in the subject of any post to this newsgroup. Please ignore the old thread. I've also updated my webpage http://ece.arizona.edu/~edatools/Python Anyone with some good ideas for "Python 3" is welcome to contribute. I hope GvR won't sue me for calling it "Python 3" :>) Here is the original proposal: < snip criticism of Prothon syntax > ... There are a number of aspects to this simplification, but for me the unification of methods and functions is the biggest benefit. All methods look like functions (which students already understand). Prototypes (classes) look like modules. This will make teaching OOP much simpler, especially for the students and professional engineers (non-CIS) that I am most concerned about. I teach electronic design tools, not programming. Current plans are to include some basic Python, no OOP. If I could add OOP with another 4 hours, I would do it. I've written a proposal for a prototype syntax that I believe captures the essense of what is good in Prothon, while not departing too radically from Python. see PrototypeSyntax.htm at http://ece.arizona.edu/~edatools/Python/ I would like to get feedback from Python experts on the potential problems with this syntax. The major question is automatic translation of existing Python programs to the new syntax. I'm one of those users who would not give up the existing libraries in Python, no matter how good some alternative language may be. I would also like to get feedback from users on what they like or dislike about this proposal. I will summarize this feedback in the "Pros and Cons" section of the proposal. Below are some excerpts from the syntax proposal. Please see the link above for better formatting. -- Dave Proposed Prototype Syntax ========================= < snip > Example of Simplified Classes ( Prototypes ) ============================================ Animal --> Mammal --> Feline --> Cat ------- ------- ------- ------- numAnimals numMammals numFelines numCats home genus __init__() __init__() __init__() __init__() .sound .sound .name show() show() show() show() talk() talk() proto Animal(object): # Inherit from the primitive object. numAnimals = 0 home = "Earth" ... ... proto Cat(Feline): numCats = 0 __init__ :( n = "unknown", s = "Meow" ): Feline.__init__() Cat.numCats += 1 .name = n # Set instance variables. .sound = s show :(): # Define a "static method". Feline.show() print " Cats:", Cat.numCats talk :(): print "My name is ...", .name print "I am a %s from %s" % (.genus, .home) Mammal.talk() # Call an unbound function. print __self__ ### Diagnostic check. cat1 = Cat() # Create instance. with cat1: # Modify instance variables. home = "Tucson" genus = "feline" name = "Garfield" >>> cat1.talk() My name is ... Garfield I am a feline from Tucson Mammal sound: Meow <__main__.Cat object at 0x00A894B0> >>> Changes from Current Python =========================== -- Keyword class is changed to proto. -- All methods have the same form, identical to a simple function. -- Function header lines are re-arranged. def --> : Parentheses are optional. -- self is replaced with a leading dot, and eliminated from the arg list. -- Current instance is available if ever needed via __self__ -- Instances can have their attributes modified in a with block. Benefits of Proposed Syntax =========================== -- Unification of all function forms ( bound, unbound, static, class, lambda ). All will have the same form as a normal function definition. This will make it easier to teach OOP. Students will already understand functions and modules. OOP is a small step up. A prototype will look just like a module ( except for the instance variables ). See Parallels between Prototypes and Modules below. -- Using an explicit __self__ variable avoids the magic first argument, and makes it easier to explain instance variables. See the sections below comparing a brief explanation of instance variables in Python vs the simplified form. A full presentation of OOP, like pages 295-390 in Learning Python, 2nd ed. will likely be 1/2 the number of pages. Not only is the basic presentation simpler, but we can eliminate a lot of discussion of lambda functions, static methods, etc. -- All attributes of a prototype ( both data and functions ) will be in a neat column, making it easier to find a particular attribute when visually scanning a program. Understanding the structure of a program will be almost as quick as seeing a UML diagram. -- Lambda keyword will be gone. An anonymous function using normal function syntax can be extremely compact. ( :x,y:x+y ) -- Method definitions will be less cluttered and less typing with __self__ as a hidden variable. -- Changing numerous attributes of an instance will be more convenient. ( need use case ) -- Migration of Python programs to Python 3 will be automatic and reliable. ??? Pros and Cons of the Proposed Syntax ==================================== Classlessness Con: The proposed syntax is not purely classless. This is important because ... ??? Unification of Methods and Functions Pro1: Less to learn. Con1: Experts don't care. Beginners don't need advanced method syntax. Pro2: Replace lambdas with standard function syntax. Con2: ??? Explicit __self__ Pro1: Allows the unification of methods and functions. Con1: ??? Pro2: Explanation of instance variables is simpler. Con2: Using __self__ instead of a special first argument is less explicit. Pro3: Less typing and less clutter in method definitions. Con3: Can use "s" or "_" instead of "self" to minimize typing and clutter. "Assignment" Syntax for Function Definitions Pro1: See all the variables at a glance in one column. Con1: ??? Pro2: Emphasize the similarity between data and functions as attributes of an object. Con2: ??? Symbol instead of def Keyword Pro: Allows lambda functions to be included in the unification. Con: Symbols are never as clear as keywords. With Block Pro: Saves typing the object name on each line. Con: Making it too easy to modify prototypes after they have been created will lead to more undisciplined programming. Issues relevant to teaching OOP =============================== Parallels between Prototypes and Modules ---------------------------------------- Ninety percent of what students need to know about prototypes is already understood from their study of functions and modules. Even some tricky issues are best explained by comparing to a parallel situation with modules. < snip > Explanation of Instance Variables in Python ------------------------------------------- """ Some of the variables inside the functions in a class have a self. prefix. This is to distinguish local variables in the function from "instance variables". These instance variables will be found when the function is called, by searching the instance which called the function. The way this works is that calling the function from an instance causes that instance to be passed as the first argument to the function call. So if you call cat1.talk(), that is equivalent to Cat.talk(cat1) If you call cat1.set_vars( "Garfield", "Meow"), that is equivalent to Cat.set_vars(cat1, "Garfield", "Meow") The "current instance" argument is auto-magically inserted as the first argument, ahead of any other arguments that you may provide in calling a method that is "bound" to an instance. Note: The distinction between instances and classes is important here. If you call a function from a class, that function is not bound to any instance, and you have to supply the instance explicitly in the first argument ( Cat.talk(cat1) ) The variable name self is just a convention. As long as you put the same name in the first argument as in the body of the definition, it can be self or s or even _ The single underscore is handy if you want to maximally suppress clutter. """ Explanation of Simplified Instance Variables -------------------------------------------- """ Some of the variables inside the functions in a prototype have a leading dot. This is to distinguish local variables in the function from "instance variables". When a function is called from an instance ( cat1.talk() ) a special global variable __self__ is automatically assigned to that instance ( __self__ = cat1 ) Then when the function needs an instance variable ( .sound ) it uses __self__ just as if you had typed it in front of the dot ( __self__.sound ) The leading dot is just an abbreviation to avoid typing __self__ everywhere. """ ========== END ============== From peter at engcorp.com Fri Apr 23 08:35:33 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 23 Apr 2004 08:35:33 -0400 Subject: Why we will use obj$func() often In-Reply-To: References: <84Uhc.22278$dZ1.5087@fed1read04> <8AWhc.23114$dZ1.11070@fed1read04> Message-ID: Mike C. Fletcher wrote: > instance, I would almost certainly consider the fishHeight$Somewhere() Mike, you haven't been keeping up with the other thread. I think the decision is now: fish_height$some_where() ;-) ;-) -Peter From madsurfer2000 at hotmail.com Sun Apr 11 06:40:40 2004 From: madsurfer2000 at hotmail.com (-) Date: 11 Apr 2004 03:40:40 -0700 Subject: a little problem References: Message-ID: tru wrote in message news:... > Would you advise > me what should I start with, because I got known about Python only from > his words two weeks ago. Please, do not advice me to read a lot of > books before bothering you , he gave me too little time to learn it and > to do it . One more thing-- I'm a student. ) > best wishes , Tru. If you're a student, you probably have experience with other languages. Try one of these: http://www.python.org/topics/learn/prog.html From __peter__ at web.de Wed Apr 7 12:46:32 2004 From: __peter__ at web.de (Peter Otten) Date: Wed, 07 Apr 2004 18:46:32 +0200 Subject: Dynamic creation of an object instance of a class by name References: <10f99b0f.0404070656.5960e2c8@posting.google.com> Message-ID: Diez B. Roggisch wrote: >> Don't listen to the voices whispering "Use eval()" or "globals() are the >> way to go", make it clean and explicit with a dictionary containing all >> classes you want to expose: > > Out of curiosity - why not to use eval? having a dict like yours makes > things look like your average java factory pattern - some explicit > structure, to which access has to be guaranteed and that requires a > registration. > > Of course, if you know that you will always only select the class from a > fixed num of classes, your approach ensures that no non-compliant classes > can be selected - but hey, we're dynamic here ;) You never can be totally > sure what you get.... It's probably a matter of taste, but most of the time the use of eval() suggests more freedom than there actually is. Let's suppose there are 3 classes A, B, and C that will be used by your eval(), that limitation may then be enforced in various parts of your code or in the documentation, while I tend to see exposed = dict(...) as self-documenting. You can go to the implementation of one class in the list to look up the interface. To take an (almost) real-world example from the library, what would you suppose the following to do? klass = eval(klass, vars(logging)) What would you do to make the above accept your special-purpose handler class? I think something like availableHandlers = {...} def registerHandler(name, klass, replace=False): if not replace and name in availableHandlers: raise NameClash availableHandlers[name] = klass formatterClass = availableHandlers[name] is much clearer. As a side note (not that I think this is important here), eval() is not the fastest of functions: $ timeit.py -s"class A: pass" -s"all=dict(A=A)" "all['A']" 10000000 loops, best of 3: 0.147 usec per loop $ timeit.py -s"class A: pass" "eval('A')" 10000 loops, best of 3: 19.7 usec per loop Peter From martin at v.loewis.de Fri Apr 9 06:24:34 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 09 Apr 2004 12:24:34 +0200 Subject: print u"\u0432": why is this so hard? UnciodeEncodeError In-Reply-To: References: Message-ID: David Eppstein wrote: > Well, no. > > Python 2.3 (#1, Sep 13 2003, 00:49:11) > [GCC 3.3 20030304 (Apple Computer, Inc. build 1495)] on darwin > Type "help", "copyright", "credits" or "license" for more information. > >>>>import sys;sys.stdin.encoding > > 'US-ASCII' You did not follow Hye-Shik's instructions closely enough. You failed to set the LANG environment variable before starting Python. Regards, Martin From deetsNOSPAM at web.de Tue Apr 27 05:08:09 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Tue, 27 Apr 2004 11:08:09 +0200 Subject: Regular Expressions References: Message-ID: Benjamin Arai wrote: > I would just use the re library because regular expressions will allow > you to get right down to the data on the first try anyways without > further parsing. If you use the htmlparser library first it may cause > some unneeded processing time. That depends on how well the html is written. You often end up writing complicated regexes to extract data from certain special cases, and sometimes even with two passes. So in general, its better to use the right tool for the job - if speed _is_ a concern you can still try to optimize. -- Regards, Diez B. Roggisch From stephen.no at spam.theboulets.net.please Fri Apr 30 22:26:40 2004 From: stephen.no at spam.theboulets.net.please (Stephen Boulet) Date: Fri, 30 Apr 2004 21:26:40 -0500 Subject: silent raw_input for passwords Message-ID: I need a password for a script and I would like to not have it stored in a file or shown in a terminal. "passphrase = raw_input()" still lets you see the input on the screen. Is there a way to have it be hidden? It's my gpg passphrase, so I don't want it anywhere except in my head. If anyone's interested, I'm wrapping the command for the duplicity program (incremental GPG encrypted backups to an FTP server; http://www.nongnu.org/duplicity/): =========================== #!/bin/env python from ftplib import FTP from os import popen dirfile = '/usr/local/backups.txt' dirs = file(dirfile).read().split('\n') host = 'ftphost' uname = 'ftpuname' password = 'ftppass' ftp = FTP(ftphost) ftp.login(ftpuname,ftppass) l=ftp.nlst() for i,dir in enumerate(dirs): if str(i+1) not in l: print 'Directory "%s" is not on the FTP server.' % dir print "Creating directory %d on server..." % (i+1) ftp.mkd(str(i+1)) ftp.quit() print "Starting duplicity synchronization ..." print "Enter your passphrase:" passphrase = raw_input() passphrase = "PASSPHRASE=" + passphrase for i in range(1,len(dirs)+1): command = passphrase + ' duplicity ftp://' command += ftpuname + '@' + ftphost + '/ "' command += dirs[i-1] + '" ' + str(i) print "Starting backup of directory %s" % dirs[i-1] popen(command).read() print "Done!" -- Stephen From here to there and there to here, funny things are everywhere. -- Dr Seuss From i.dont.like.spam at spamfree.final.nospam.co.unspammed.il Thu Apr 29 14:12:55 2004 From: i.dont.like.spam at spamfree.final.nospam.co.unspammed.il (Ori Berger) Date: Thu, 29 Apr 2004 21:12:55 +0300 Subject: Automatic caching and dependency evaluation among variables? Message-ID: <409145d1@news.bezeqint.net> I *think* I saw a post some time ago enabling "spreadsheet" like computations, that allows something along the lines of: >>> vars.a = 10 >>> vars.b = dependency("vars.a * 20") >>> print vars.b 200 >>> vars.a = 50 >>> print vars.b 1000 (Not sure what the actual syntax definitions were) And vars.b was only re-computed if vars.a was changed - otherwise a cached value was returned. I can write this myself, but the solution I'm thinking of is inelegant, and I remember the solution was extremely short and elegant; I can't find anything in the google archives, though. Anyone perhaps have a link or other helpful info? (My idea of how to do it: make vars a special dict that logs every __get__, and that can have callbacks when something is __set__. the dependency() code would evaluate the expression, see what __get__s were logged, and attach the same expression to be reevaluated when any of those were __set__. It becomes complicated, though, if I wish to track changes to vars.subvar1.subvar2.subvar3 as well, though). From shalabh at cafepy.com Tue Apr 13 09:23:16 2004 From: shalabh at cafepy.com (Shalabh Chaturvedi) Date: Tue, 13 Apr 2004 06:23:16 -0700 Subject: Once-only evaluation of default parameter values function definitions In-Reply-To: <407BB8F5.E694AA49@doe.carleton.ca> References: <407B79D7.424F65A1@doe.carleton.ca> <107n2g6q9an672b@corp.supernews.com> <407BB8F5.E694AA49@doe.carleton.ca> Message-ID: Fred Ma wrote: > Michael Geary wrote: > > >>> Example#1 >>> --------- >>> def f(a, L=[]): >>> L.append(a) >>> return L >>> >>> Example#2 >>> --------- >>> def f(a, L=None): >>> if L is None: >>> L = [] >>> L.append(a) >>> return L >> >>Here's a simpler example: >> >> >>>>>a = [] >>>>>b = a >>>>>a >> >>[] >> >>>>>b >> >>[] >> >>>>>a.append(1) >>>>>a >> >>[1] >> >>>>>b >> >>[1] >> >>See what happened? The statement 'b = a' didn't make a copy of a and >>store it in b. Instead, it made the name b refer to the same object >>as a. So, when I said b.append(1), it meant exactly the same thing >>as if I'd said a.append(1). > > > Thanks, Mike. That's alot clearer. The default value looks like it's > a persistent object. It is similar to a static local variable in C++. > In Example#1, that object actually got changed. In contrast, in > Example#2, the code prevents L from remaining bound to None beyond the > first line, so the None object never gets changed. In fact, my 2nd > explanation was close: that there is an unnamed persistent object that > holds the default value to be bound to L for invocations that don't > explicity supply an argument for L. The place I went wrong was to say > that L never gets bound to None again, after it has been bound to a > caller supplied object on a previous invocation of the function. > > Fred That is correct, L will be bound to None whevever there is no argument supplied. Also note that the None object is immutable, and cannot be changed, so this mechanism is safe. The default value is as 'persistent' as the function itself. Functions are objects and spring into existance only after Python encounters and executes the 'def' statement. Python also evaluates the default values at this point and keeps these objects around, along with the function definition. If at a later point you do 'del f', you will delete the function and the default values (since there is no more use for them, the function cannot be called). Assuming, of course, that f was the only reference to the function. Since the 'name-binding' concept in Python is not exactly the same as references in C++, I suggest you also read 'How to think like a Pythonista': http://starship.python.net/crew/mwh/hacks/objectthink.html for an excellent coverage of one of Python's basic concepts. -- Shalabh From OlafMeding at noSpam.compuserve.com Tue Apr 13 08:28:35 2004 From: OlafMeding at noSpam.compuserve.com (Olaf Meding) Date: Tue, 13 Apr 2004 07:28:35 -0500 Subject: Logging Stacktrace To File References: <407bcbca$1_2@newspeer2.tds.net> Message-ID: <407bdce5$1_1@newspeer2.tds.net> > ... have to catch the exception and then log it to the file. Right. I do also know how to open a file and write to it. But how do I get at the stack trace? I would like to have it look the same in the file as what gets printed to the screen. Thanks again. Olaf From use_reply-to at empty.invalid Thu Apr 1 10:31:03 2004 From: use_reply-to at empty.invalid (jsaul) Date: Thu, 1 Apr 2004 17:31:03 +0200 Subject: splitting one dictionary into two Message-ID: <20040401153103.GC4577@jsaul.de> Hello all, I have to split a dict into two dicts. Depending on their values, the items shall remain in the original dict or be moved to another one and at the same time be removed from the original dict. OK, this is how I do it right now: dict1 = { "a":1, "b":3, "c":5, "d":4, "e":2 } dict2 = {} klist = [] for key in dict1: if dict1[key] > 3: # some criterion dict2[key] = dict1[key] klist.append(key) for key in klist: del dict1[key] print dict1 print dict2 That means that I store the keys of the items to be removed from the original dict in a list (klist) and subsequently remove the items using these keys. Is there an "even more pythonic" way? Cheers, jsaul From lbates at swamisoft.com Tue Apr 27 16:04:03 2004 From: lbates at swamisoft.com (Larry Bates) Date: Tue, 27 Apr 2004 15:04:03 -0500 Subject: debugging code References: <3064b51d.0404271139.6ec7057@posting.google.com> Message-ID: Since Python isn't "compiled", there is no such thing as conditional compilation. I always have _debug and _trace variables and use simple if _debug: and if _trace: statements to test them (actually I allow debug to have levels that show additional detail as I need it). I almost always read these from the argument list on the processor call so I can turn them on easily. I also read them from .INI file for those programs that have one. Seems to work very well and there is almost no overhead to them when turned off. FYI, Larry Bates Syscon, Inc. wrote in message news:3064b51d.0404271139.6ec7057 at posting.google.com... > If I have some debugging code in a Python program (mostly print > statements) and I want to turn it "off", two obvious methods are to > (1) comment out the code > (2) set a logical 'debug' variable at the beginning and use it to > conditionally run the debugging code. > > Is there a better way? Some other languages have conditional > compilation. (I don't know if that is better or worse). What is the > "best" way to maintain "production" and "debugging" versions of a > Python program at the same time, preferably in the same file? From jack at performancedrivers.com Fri Apr 16 22:26:46 2004 From: jack at performancedrivers.com (Jack Diederich) Date: Fri, 16 Apr 2004 22:26:46 -0400 Subject: CamelCase versus wide_names (Prothon) In-Reply-To: <69KdndtPUZT-5h3dRVn-uw@powergate.ca> References: <407ec022$0$54153$1b2cd167@news.wanadoo.nl> <69KdndtPUZT-5h3dRVn-uw@powergate.ca> Message-ID: <20040417022646.GD794@performancedrivers.com> On Fri, Apr 16, 2004 at 08:33:39PM -0400, Peter Hansen wrote: > Jack Diederich wrote: > >I'm a wide_case_fanboy, having done mixedCase and wide_names over the last > >fifteen years. It all comes down to personal preference, of course. IMO > >mixedCase people tend to be younger, and younger people tend to be more > >zealous on newsgroups. > > Define "younger". .. than "me" specifically people who know close to one language. Generally I've been happier with each language I've ever programmed in, and have been choosier at each junction. By the time I got out of uni it was C++, branching out into Java and Perl and settling on Python for a few years now. With many more (Objective C, Lisp, Haskell) used along the way for hobby projects. You start with what you know and then get pickier once you know more about what exists. Strength of the belief that you have found the one true way is inversely proportional to the number of things you have tried. Java and VB folks are more likely to have an N of one and a belief approaching unity. They are also more likely to be mixedCase people. That is my opinion. Variable naming isn't high on my list of religious wars[*], I mentioned in my other post I do write both mixed and wide words depending on the codebase. But when I get to pick, I pick wide words. -jackdied [*] for vi lovers, I've been know to order light beer 'by accident' when buying a round. Not really, but that is how tepid I am about my emacs preference. From no at spam.invalid Fri Apr 16 19:56:00 2004 From: no at spam.invalid (Russell E. Owen) Date: Fri, 16 Apr 2004 16:56:00 -0700 Subject: Tkinter: cut'n'paste from DISABLED window? References: <1076oovf3jd9b28@corp.supernews.com> Message-ID: In article , "Fredrik Lundh" wrote: >... >however, in recent versions, many Tk entry widgets supports both >state="disabled" >and state="readonly", but I don't think this is yet available for the Text >widget. > >as for the original poster, the best way to solve this is probably to add >custom >mouse bindings for this widget. here's a start... Glad to hear about the new state="readonly". Looking forward to that making it into the Text widget. Meanwhile, here's the function I use. No gurantees, but it seems to work for me. Any bug reports would be most welcome. -- Russell def makeReadOnly(tkWdg): """Makes a Tk widget (typically an Entry or Text) read-only, in the sense that the user cannot modify the text (but it can still be set programmatically). The user can still select and copy text and key bindings for <> and <> still work properly. Inputs: - tkWdg: a Tk widget """ def killEvent(evt): return "break" def doCopy(evt): tkWdg.event_generate("<>") def doSelectAll(evt): tkWdg.event_generate("<>") # kill all events that can change the text, # including all typing (even shortcuts for # copy and select all) tkWdg.bind("<>", killEvent) tkWdg.bind("<>", killEvent) tkWdg.bind("<>", killEvent) tkWdg.bind("<>", killEvent) tkWdg.bind("", killEvent) # restore copy and select all for evt in tkWdg.event_info("<>"): tkWdg.bind(evt, doCopy) for evt in tkWdg.event_info("<>"): tkWdg.bind(evt, doSelectAll) From mwh at python.net Mon Apr 12 16:33:14 2004 From: mwh at python.net (Michael Hudson) Date: Mon, 12 Apr 2004 20:33:14 GMT Subject: print u"\u0432": why is this so hard? UnciodeEncodeError References: <16505.58626.39783.581506@montanaro.dyndns.org> Message-ID: "Martin v. L?wis" writes: > Skip Montanaro wrote: > > Martin> I wonder how much would break if Python would assume the > > Martin> terminal encoding is UTF-8 on Darwin. Do people use different > > Martin> terminal encodings? > > I generally use xterm instead of Terminal.app. I think it's > > encoding is > > latin-1. > > Not on OS X. Terminal.App is a software package completely different > from xterm. For one thing, xterm is for X11, whereas Terminal.App is > for Window Server (or whatever the name of the Apple GUI is). I think Skip knows this :-) Cheers, mwh -- You can lead an idiot to knowledge but you cannot make him think. You can, however, rectally insert the information, printed on stone tablets, using a sharpened poker. -- Nicolai -- http://home.xnet.com/~raven/Sysadmin/ASR.Quotes.html From noemail at noemail4u.com Thu Apr 22 13:30:23 2004 From: noemail at noemail4u.com (Daniel 'Dang' Griffith) Date: Thu, 22 Apr 2004 17:30:23 GMT Subject: Simple question about mutable container iterator References: Message-ID: On Thu, 22 Apr 2004 09:48:14 -0400, "Neal D. Becker" wrote: >x = [1,2,3] > >for i in x: > i = 2 > >This doesn't change x. 2 questions: > >1) Why not? Why doesn't assign to an iterator of a mutable type change the >underlying object? > >2) What is the preferred way to do this? I'm not sure what you're trying to do, and others have given ideas. If you're trying to make x a list of 2's having the same length as x had when you started, you could do this, and avoid the iteration: x = [1,2,3] x = len(x) * [2] Or, if you're trying to set all elements to the average: x = [1,2,3] x = len(x) * [1.0 * sum(x) / len(x)] Or, if you're trying to set all elements to the middle element: x = [1,2,3] x = len(x) * [x[len(x) / 2)]] --dang From stewart at midwinter.ca Mon Apr 12 16:41:51 2004 From: stewart at midwinter.ca (Stewart Midwinter) Date: 12 Apr 2004 13:41:51 -0700 Subject: Best IDE? References: Message-ID: <9396ba6f.0404121241.2953ad84@posting.google.com> Josiah Carlson wrote in message news:... > I use PyPE, find it to be a satisfactory replacement for Idle, and is > quite fast. I wrote it, which is why I place it at the bottom. Josiah, I've tried PyPE and quite like it. It has some useful features beyond what SciTE, which I also use, has. One thing that I'd like to see in PyPE is a way to remember the window layout. Each time I open a file, I find myself dragging window margins around until I can see my ToDo list, the class list, etc. Or am I missing something? cheers Stewart in Calgary From humean at fea.st Thu Apr 29 19:55:30 2004 From: humean at fea.st (Steve) Date: Thu, 29 Apr 2004 19:55:30 -0400 Subject: Feedback on Sets, and Partitions Message-ID: <1083282930.25734.185379975@webmail.messagingengine.com> This post has two parts. First is my feedback on sets. (Hello? Last summer called, they want their discussion thread back...) Second is some questions about my implementation of a partition function for sets. Part 1. --- >From: Raymond Hettinger (vze4rx4y at verizon.net) >Subject: Py2.3: Feedback on Sets >Newsgroups: comp.lang.python >Date: 2003-08-11 23:02:18 PST > >I've gotten lots of feedback on the itertools module >but have not heard a peep about the new sets module. > >* Are you overjoyed/outraged by the choice of | and & > as set operators (instead of + and *)? I like '|' and '&', because union and intersection are more like or and and than they are like addition and multiplication. >* Is the support for sets of sets necessary for your work > and, if so, then is the implementation sufficiently > powerful? Sets would be far less interesting and useful if we could not have sets of sets. The implementation is sufficient, but not entirely intuitive. Of course, there is no distinction between immutable and mutable sets in normal set theory. I could live with only immutable sets, but it is nice being able to use: myset.add(x) instead of: newmyset = myset | Set([x]) I would like (I think) syntactic support where curly-braces could replace the class constructor. Another unintutive feature is that there can be multiple sets with the same members. I.e., you can have sets A and B such that "A == B" is true and "A is B" is false. I would like more information on the reasons for this choice and whether there would be anything to gain or lose by having "A == B" entail "A is B". >* Is there a compelling need for additional set methods like > Set.powerset() and Set.isdisjoint(s) or are the current > offerings sufficient? I don't know if the need is compelling, but I consider the implementation incomplete without powerset() and some other functions. However, please see my discussion of a partition function below. >* Does the performance meet your expectations? I don't know. For memory usage, I did some tests and it looks like a set that is the singleton of an integer takes about 200 bytes, maybe a little less. On the one hand that isn't bad, on the other, it's kind of big. 50 bytes would be great. Does or could Set use __slots__? As for speed, see below. >* Do you care that sets can only contain hashable elements? Is this required for efficiently preventing duplicate elements or at least for having lookups be O(1)? Then I can live with it. In general though I would think that the more types of things that are eligible to be elements, the better. >* How about the design constraint that the argument to most > set methods must be another Set (as opposed to any iterable)? Fine with me. It is not obvious in the first place what you should expect the union of a set and a tuple to be (in set theory, not Python). >* Are the docs clear? Can you suggest improvements? 5.13.1 Set Objects. The table of operations could list proper subset as well as subset. Also, I would be happy to see as much information as possible about O() properties of sets. (Explicit, not "same as a dictionary".) Maybe that doesn't belong in the documentation proper. >* Are sets helpful in your daily work or does the need arise > only rarely? I am strongly in favor of moving sets into the core language with supporting syntax and a C implementation. Part 2 --- What is true of the performance of a partition function for the most part should be true of a powerset, combination, and permutation (for ordered subsets) function. In general, I don't know if a partition function has much use when you're dealing with sets with moderately large numbers of members. The problem with these functions is that their size grows quickly. I have ruled out making one giant set of all the partitions because it is too big (1 million sets uses 200MB memory). Instead I have a generator function that yields a different partition on each iteration. The problem then is that it takes too long. I fear that, despite what I said above about including them in a complete implementation of sets for Python, there may not be any practical use for these functions except in limited domains with small numbers of elements. So my question is for advice on improving my implementation (by a constant factor would be great, by a factor of n would be amazing, although maybe impossible), and also general advice on the best performance I could ever hope for with these sorts of functions. Below are some numbers, and then the code. For those who don't know, a partition P of a set A is a set of mutually exclusive and jointly exhaustive subsets of A. In other words, every member of A is a member of exactly one member of P. As I learned when working on this implementation, the number of partitions for a set of size n is the Bell Number of n. The formula for computing the Bell Number isn't really relevant at the moment, but here are the Bell Numbers for 0,...,14: 1, 1, 2, 5, 15, 52, 203, 877, 4140, 21147, 115975, 678570, 4213597, 27644437, 190899322 This means that a set with 3 elements has 5 partitions. Here is an example: Partitions({a,b,c}) = { { {a,b,c} } { {a,b},{c} } { {a,c},{b} } { {b,c},{a} } { {a},{b},{c} } } This shows one big set of all the partitions, where each partition is a set of sets of elements. The function below, being a generator, does not return one big set of all partitions, but a different partition on each iteration. Now, my computer is a 1.8GHz Athlon with 512MB RAM (PC133 unfortunately). I use Fedora Core 1 Linux and Python 2.3 RPM from python.org. For a benchmark, the following code takes about 10 seconds to run: i = 10000000 #ten million while i > 0: i -= 1 So here are some times for generating the partitions of sets of increasing sizes: 1, <1s 2, <1s 3, <1s 4, <1s 5, <1s 6, <1s 7, <1s 8, <1s 9, 1.6s 10, 9s 11, 53s 12, 5m25s For my current project, I need to generate partitions of sets up to size 25. I am rather hopeless it will ever be feasible, and I have begun looking for a different approach. Thanks for any replies! #begin code from sets import Set, ImmutableSet #def singleton(s): # return Set([s]) def partitions(s): if len(s) <= 1: yield Set([s]) else: x = Set([iter(s).next()]) for t in partitions(s - x): yield t | Set([x]) for u in t: yield (t - Set([u])) | Set([u | x]) s = Set("abcdefghij") #10 elements, which is 9s runtime count = 0 for p in partitions(s): count += 1 print count From davecook at nowhere.net Wed Apr 14 02:35:41 2004 From: davecook at nowhere.net (David M. Cook) Date: Wed, 14 Apr 2004 06:35:41 GMT Subject: Looking for Python Definition References: Message-ID: In article , Dave wrote: > Python22 is installed on my WINXP Home PC. > I have no idea what is does, or why it is installed. You mean they didn't also install Perl, awk, sed, bash, grep, find, and gcc?* Any modern computer will ship with at least 40GB of drive space, and those things are free, so why not? Python is an interpreted programming language. You're vendor probably needed a Python interpreter for some extra functionality. Or maybe they are just really thoughtful folks, because they have made it easier for you to run Python programs written by other people (not that installing Python is hard), and also easier for people who want to write Python programs for you. *To remedy these crippling deficiencies, go to http://cygwin.com Dave Cook From NAIGIMSESRIMAIL at gims.com Thu Apr 1 07:18:00 2004 From: NAIGIMSESRIMAIL at gims.com (GroupShield for Exchange (ESRIMAIL)) Date: Thu, 1 Apr 2004 14:18:00 +0200 Subject: ALERT - GroupShield ticket number OB72_1080821869_ESRIMAIL_3 was generated Message-ID: Action Taken: The message was blocked because of its subject. To: python-list at python.org From: Michael Hudson Sent: 1501768448,29628387 Subject: Re: test for nan Attachment Details:- Attachment Name: N/A File: Infected.msg Infected? No Repaired? No Blocked? Yes Deleted? No Virus Name: -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/ms-tnef Size: 1805 bytes Desc: not available URL: From cpl.19.ghum at spamgourmet.com Mon Apr 5 21:13:52 2004 From: cpl.19.ghum at spamgourmet.com (Harald Massa) Date: Tue, 6 Apr 2004 03:13:52 +0200 Subject: Does Python compete with Java? References: <8b336527.0404051337.51bb4a1b@posting.google.com> <1073su4etm95p35@news.supernews.com> Message-ID: Roy Smith wrote in news:roy-094613.21022405042004 @reader1.panix.com: > http://www-users.cs.york.ac.uk/~susan/joke/foot.htm >They don't have one for Python, but I expect it would be something like >this: I think the most common solution is: > How to Shoot Yourself In the Foot Python you discover that Guido used his time machine to shoot you in the foot years ago From hungjunglu at yahoo.com Tue Apr 6 03:47:43 2004 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 6 Apr 2004 00:47:43 -0700 Subject: __import__() with packages References: <1070cph9hedq9ee@news.supernews.com> Message-ID: <8ef9bea6.0404052347.4ac7d911@posting.google.com> Marco Herrn wrote in message news:... > Thanks, > but in my application I read the names of the modules from a file, > so I do not know them when writing (in this case I wouldn't know the > name 'eggs'). Since the solution from Paul works for me, I will use > that. There is an easier way: all imported modules are listed in the sys.modules namespace dictionary. So, import sys __import__('spam.eggs') my_module = sys.modules['spam.eggs'] regards, Hung Jung From python at holdenweb.com Wed Apr 14 21:37:45 2004 From: python at holdenweb.com (Steve Holden) Date: Wed, 14 Apr 2004 21:37:45 -0400 Subject: Pygame In-Reply-To: References: Message-ID: Alexander R?dseth wrote: [...]> (Note: "ipv6" is just an example, for the sake of the name, I know that it's > not a standard Python-module). > In point of fact since Python 2.3 the socket module has handled IPv6. But if you mean that geeks like, and therefore tend to include, geeky things in their langauge distributions, you could have a point. Nothing in the license stops you from building and distributing "friendly Python", though, so you might consider putting your own distribution together. If that's too hard, you will at least begin to get the idea why PyGame (and this, that and the other) aren't in the standard distribution. If you get it together I believe you would increase Python's popularity. regards Steve From eric at zomething.com Sun Apr 4 23:27:46 2004 From: eric at zomething.com (Eric @ Zomething) Date: Sun, 4 Apr 2004 19:27:46 -0800 Subject: OT (was Re: But it still doesn't explain the joke) Message-ID: <20040404192746.669306216.eric@zomething.com> "Terry Reedy" wrote > discussion Python, and leave such political discussions to more appropriate > fora. still OT... I agree and think, further, we should refrain from discussions of post grammar, such as if I had been to point out the apparent English impropriety of the string 'discussion Python' (I would have then queried, "Discussion: Python" or "discussing Python"?, but I will not stoop to highlighting such). :-) hey, we may all be guilty of the occassional grammatical typo, or of thinking for ourselves, from time to time. Whatever other political opinions may hold sway, I think we all enjoy the open exchange of ideas and technology (code! porgramming languages! algorithms!) that is currently allowed. It was a scant few years back we in the U.S. could not export (including discussions in a forum such as this) basic information technology, without risk (of being a traitor of losing our liberty?). It requires (peace) a certain world (peace) situation (peace) to allow this (peace), and I do not think we (peace) should take it for granted (peace). There are many who would like to wall up the world and I think that would be a shame for newsgroups like this.... hide your code away and never let anyone outside the building see it... in Python brotherhood, [insert here hands extended within and across all borders in friendship and comraderie... and with regards] Eric Pederson [http://www.songzilla.blogspot.com] From peter at engcorp.com Fri Apr 16 10:04:27 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 16 Apr 2004 10:04:27 -0400 Subject: Difficulty Finding Python Developers In-Reply-To: References: <65cbc3dd.0404140641.3501fde8@posting.google.com><5d83790c.0404150701.605782a7@posting.google.com><7xpta8hqe7.fsf@ruckus.brouhaha.com><7xsmf4kbac.fsf@ruckus.brouhaha.com><7x7jwg7ipn.fsf@ruckus.brouhaha.com> Message-ID: Fredrik Lundh wrote: > Peter Hansen wrote. > >>>They're not, but the discussion was serious production projects. >> >>I thought the discussion was a 3-month project. To me, that's >>definitely not something I would classify as a "serious production >>project". I know, I know, the length alone shouldn't be enough >>to call it serious or production or not. It's just not the term >>I would apply to something that short. "Experiment", maybe, or >>"quickie", or "co-op student project" or something... > > hmm. have I been posting to the wrong newsgroup? Maybe, but not in this thread, so far, unless my news providers is dropping messages. (I'm sure there's a subtle point you're making, but it's too subtle for my simple brain; forgive me.) (And in case my point was unclear: the OP asked about something which seemed like a very simple experimental project to get their feet wet with Python. Others seemed to be justifying their points by shifting it towards major software engineering efforts. I understand their point, but just don't believe it applies in the OP's case, unless I misinterpreted the OP's situation in which case we'll probably hear back soon...) -Peter From calfdog at yahoo.com Tue Apr 20 14:40:57 2004 From: calfdog at yahoo.com (calfdog at yahoo.com) Date: 20 Apr 2004 11:40:57 -0700 Subject: imitating user input References: <4083CB4D.7050101@zoran.com> Message-ID: Greg, There are lots of ways to do this. Pamie is just one method. basically you want to set the value of a two textboxes and submit the form. If you have an instance of the browse you can access it's methods and attributes. In Python you could do it this way: #Instantiate a new instance of the IE browser: ieBrowser = DispatchEx('InternetExplorer.Application') Now you have access to the textboxes and it's buttons Since you have and instance of the browser ieBrowser you can begin: For example a simple login page with username textbox, password textbox and submit button. ieBrowser.Document.forms[0].elements.all[username].value = "YourUsername" ieBrowser.Document.forms[0].elements.all[password ].value = "YourPassword" ieBrowser.Document.forms[0].elements.all[SubmitButtonName].form.submit() You can get the actual names for your username, password and SubmitButtonName from viewing the source of the Webpage and doing a find on the word "input" You can do the above in Perl VB ruby etc.. although the syntax may be a little different. Hope this helps. Enjoy RLM Pamie creator For more information: http://msdn.microsoft.com/library/default.asp?url=/workshop/author/dhtml/reference/dhtml_reference_entry.asp From jf at ypsilon.net Thu Apr 1 10:07:25 2004 From: jf at ypsilon.net (fu) Date: Thu, 01 Apr 2004 17:07:25 +0200 Subject: Using python with C Library In-Reply-To: References: Message-ID: hi there, i got the following problem: I have a set of compiled C files, providing a API for a special encryption / decrytion of messages to be exchanged over the internet, well documented and with a lot of programming examples of how to work with it and its functions (in this case the examples are all in C). Now i want to use it with twisted/python together, to have all the advantages of twisted (especially the reactor instead of threading, deferred and so on), but the C API to do the last step before messages are send out. The C API should just play some kind of middleware between the tcp-ip protokoll and the twisted server. Is it possible to extending python / twisted with that library by "just import" them? Any kind of advice / suggestions would help thanks J.F. From jcarlson at uci.edu Sat Apr 3 16:53:45 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Sat, 03 Apr 2004 13:53:45 -0800 Subject: Indent testers needed (Prothon) In-Reply-To: <106tqq5e6gn8aaf@corp.supernews.com> References: <2Msbc.136673$cx5.2385@fed1read04> <106tqq5e6gn8aaf@corp.supernews.com> Message-ID: >>The above code shows how you can make Prothon code >>extraordinarily ugly by exploting the continuation rules. >>Certainly most people don't see such ugly continuations >>in Python, but I think rule #3 is begging for trouble. > > That's a strawman. The fact that you *could* write strange code like that > doesn't mean that there is anything wrong with Mark's continuation rules. I state almost as much, "most people don't see such ugly continuations in Python", which expresses that we don't see that kind of ugly code in Python. I believe that the reason for it is because most people don't like to see such ugly code. However, as I said, I think that #3 is begging for some schmuck to exploit it. > I could write a long Python program that uses no functions, classes, or > anything else to break it into smaller understandable pieces. Just one big > long piece of code that is indented to twenty levels. While I'm at it, I'll > use variable names that obscure what the code does. > > Does that imply that there should be a maximum length to a Python source > file, a limit on the level of indenting, and restrictions on what variable > names I can use? Of course not. You're going a few steps beyond what I was saying. I stated that it makes sense to discourage ugly code. The code that you are describing is functionally impossible to maintain (unless it was generated by inlining all module-level function calls, something that you, I, or anyone else could technically do, or even write a program to do). I think that by people using Python (or in this case Prothon), by definition it is implied that we should be writing maintainable code. Personally, I don't find implicitly continued lines to be more maintainable than explicitly continued lines, and because explicit continuations (with '\') do the job already, if this were Python, it would violate both the "flat is better than nested" and "there should be one-- and preferably only one --obvious way to do it" zens. As for whether Mark wants to follow the Zen of Python, that is up to him. However, considering that he's using the c.l.py newsgroup to discuss Prothon, using a very large portion of the syntax of Python, and has talked about translating a large portion of the standard library of Python to Prothon via some sort of automatic method, I would say that violating the Zen is a foolish "early optimization". - Josiah From mickel at csc.fi Fri Apr 2 07:09:45 2004 From: mickel at csc.fi (=?ISO-8859-1?Q?Mickel_Gr=F6nroos?=) Date: Fri, 2 Apr 2004 15:09:45 +0300 (EEST) Subject: emergent/swarm/evolutionary systems etc In-Reply-To: References: Message-ID: On Fri, 2 Apr 2004, Peter MacKenzie wrote: > import sys You don't need the sys module for file I/O. > file = 'myfile.txt' > open(file,'r+b') > file.write("some string of what you want to write") > file.close() "file" is a str object containing the string "myfile.txt". What you need to do is catch the return value (a file object) of the open() function and use that for writing: file = "myfile.txt" fh = open(file, "r+") ## Do you need "b" (binary) for a text file? fh.write("something") fh.close() 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 fumanchu at amor.org Mon Apr 26 11:35:10 2004 From: fumanchu at amor.org (Robert Brewer) Date: Mon, 26 Apr 2004 08:35:10 -0700 Subject: Regular Expressions Message-ID: sjf wrote: > I would like to please to help me with build a regular expression. > There are following piece of html code in my files: > > A - TYPE1: any_text
> B - TYPE2: any_text_2
> C - TYPE2: any_text_3
> w - any_text_15
>
> html code > > > I need to have only following data: > (B, any_text_2) > (C, any_text_3) > that is, these data TYPE2 in which. If you can guarantee that every TYPE2 is on its own line with the same formatting: >>> s = 'A - TYPE1: any_text
\nB - TYPE2: any_text_2
\nC - TYPE2: any_text_3
\nw - any_text_15
\n
\nhtml code' >>> import re >>> re.findall(r'(?m)^(.) - TYPE2: (.*)
$', s) [('B', 'any_text_2'), ('C', 'any_text_3')] Robert Brewer MIS Amor Ministries fumanchu at amor.org From michael at foord.net Tue Apr 13 10:39:00 2004 From: michael at foord.net (Fuzzyman) Date: 13 Apr 2004 07:39:00 -0700 Subject: 3D Graphics Engine Message-ID: <8089854e.0404130639.3eb0db62@posting.google.com> I've seen various references to 3D graphics engines - and it's a little difficult to know where to look. I would like (in the long run) to be able to create and explore 3d worlds - so texture mapping, light sourcing or shading and mesh shapes would be nice - but I *don't* need the quality of a commercial game system. Collision detection etc would be nice too. Platform for development (!) is win32 - so I would like an engine with precompiled binaries and a documented python binding available. A freeware object modeller So far I've seen : Crystal Spaces - undocumented python binding, no 'easily' available installation package (I can't see it anyway !!) panda 3d - only accepts 3d objects from a comemrcial app (?) vpython - very basic ! soya 3d - still unstable (??) Can anyone reccomend a 3d engine for me to 'muck around with'. Regards, Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html From peter at engcorp.com Fri Apr 2 06:58:29 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 02 Apr 2004 06:58:29 -0500 Subject: Apologies In-Reply-To: References: Message-ID: Tim Golden wrote: > Apologies to all on the last for my rampant out-of-office > messages. I'm using Exchange (over which I have no control), > and I thought it did the right thing by list replies. > > I'll make sure next time. Maybe to help others who have sometimes been or will be in the same boat, you could explain exactly what didn't and then did work...? Thank you, -Peter From scott.b.drummonds.nospam at intel.com Thu Apr 15 12:38:20 2004 From: scott.b.drummonds.nospam at intel.com (Scott Brady Drummonds) Date: Thu, 15 Apr 2004 09:38:20 -0700 Subject: Fast Data Comparison (dict v. list. v string) References: Message-ID: "Larry Bates" wrote in message news:hIWdnXU6rJ7fC-PdRVn-iQ at comcast.com... > Scott, > > You should take a close look at list comprehensions > and possibly sets (new in V2.3). I'm not all that > familiar with sets, but your problem sounds like > they might come in handy. Excellent suggestion! Thanks so much for the idea. Scott From jepler at unpythonic.net Wed Apr 21 07:20:33 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 21 Apr 2004 06:20:33 -0500 Subject: Can't spawn, or popen from daemon In-Reply-To: <1082481539.1395.21.camel@localhost> References: <1082481539.1395.21.camel@localhost> Message-ID: <20040421112032.GC5589@unpythonic.net> Imagine that /usr/bin/lp has something like the following Python code at the top: sys.stderr.write("something\n") sys.stderr (stdio's stderr in C) in the called program is closed, so this will return an error. Whatever the error was, lp may be trying to print *that* to stderr, too. If there's some sort of failure, you're not going to see the message. You could try: os.popen('/usr/bin/lp -d printer1 %s 2>&1' % (filename)) to capture both stdout and stderr, or you could use the popen2 module to get multiple handles for I/O with the child, or you could try (in daemonize): nullfd = os.open("/dev/null", os.O_RDWR) os.dup2(nullfd, 0) os.dup2(nullfd, 1) os.dup2(nullfd, 2) os.close(nullfd) to make the standard C files point at /dev/null (writes succeed, but the data is discarded), in case it's an error reading stdin or writing to stderr that is killing lp. Jeff From alloydflanagan at comcast.net Thu Apr 29 10:29:25 2004 From: alloydflanagan at comcast.net (A. Lloyd Flanagan) Date: 29 Apr 2004 07:29:25 -0700 Subject: String formatting (%) References: Message-ID: pascal.parent at free.fr (Pascal) wrote in message news:... > Hello, > I've a float number 123456789.01 and, I'de like to format it like this > "123 456 789.01". > Is this possible with % character? No, but this works with integers. Not sure how it compares to the other approaches mentioned. You could adapt it to do floats by stopping at the decimal point: def addCommas(aNumber): if len(aNumber) < 4: return aNumber #how many digits before first ,? prefix = len(aNumber) % 3 #need special case if digits is multiple of 3 if prefix == 0: prefix = 3 result = [aNumber[:prefix]] for a in range(len(aNumber) / 3): #get next 'segment' of three digits segment = aNumber[prefix + 3*a: prefix + 3*a + 3] if segment: #can be '' if len(aNumber) divisible by 3 result.append(segment) return ','.join(result) I'm sure this can be improved. From asdf at asdf.com Tue Apr 13 14:11:05 2004 From: asdf at asdf.com (asdf sdf) Date: Tue, 13 Apr 2004 18:11:05 GMT Subject: Best IDE? In-Reply-To: References: <4ace7f9f.0404111147.3120288a@posting.google.com> Message-ID: Timothy Wu wrote: > rakanishu wrote: > >> I don't know if I'd call 'em IDEs but it's worth taking the time to >> learn either emacs or vim. Both are very powerful editors that run on >> multiple platforms. I tried emacs three times, but couldn't get into >> it. I'm now getting hooked on vim. YMMV. > > > I love Vim. I really do. And it works wonderfully on both Linux and > Windows with Exuberant ctags (http://ctags.sourceforge.net/) on Python > code. However the only thing that's bugging me is once I'm used to using > Vi(that's practically the only editor I've ever use), I'm forever stuck > with using Vi. I wish all other real IDEs comes with Vi mode, or I can > somehow embed Vim in there (or someone else doing it for me as I'm not > that technical). I would love to be using an IDE if it doesn't slow me > down. > > Timothy > Check out Visual SlickEdit from Slickedit.com. I would say this is an editor rather than an IDE. But it is certainly an IDE if vi is one. It emulates several other editors, including vi. It can generate tag libraries, supporting autocomplete and function help for numerous languages with syntax coloring. It can run build scripts. Available on multiple platforms. It is scriptable and extensible. Too many features to mention. If anyone can suggest a tool that is as powerful, that is not specific to a single language, please mention it. Python, Javascript, HTML, C, C++, Perl, Java, TCL, ksh, bsh, COBOL, CFML, PL/SQL, PHP, Fortran, ADA ... It must have support for 50 languages. From eddie at holyrood.ed.ac.uk Thu Apr 8 12:24:42 2004 From: eddie at holyrood.ed.ac.uk (Eddie Corns) Date: Thu, 8 Apr 2004 16:24:42 +0000 (UTC) Subject: Distributing a Python based application on Linux References: <98013c51.0404080807.6f08f1a3@posting.google.com> Message-ID: kramakrishnan at novell.com (Ramki) writes: >Hi !! >I have written an install script to deploy some of my product rpms. >The install script does OS Version Check, OS Memory check, logging the >status of install into a log file amongst other things. >Now the size of my product rpms is around 3 MB. If I am to distribute >Python along with the install, it is taking around 12 MB totally (the >python gz tar is around 9 MB), which is not ideal. >Is there way I can avoid this by distributing only the bare minimum >Python related binary along with my rpms ? Many versions of Linux have Python already so it may not be a problem. Maybe someone could concoct a Perl script that checks if Python is on the machine and if not downloads it from a suitable location (either to a local directory or to the system depending on need/access). That way, only people who aren't hip enough to have Python installed get penalised! Eddie From me at privacy.net Wed Apr 7 06:56:08 2004 From: me at privacy.net (Heather Coppersmith) Date: 07 Apr 2004 06:56:08 -0400 Subject: min() with custom compare. References: <20040407114407.0a07d143@pistache.sara.nl> Message-ID: On Wed, 7 Apr 2004 11:44:07 +0200, Bram Stolk wrote: [ example of sort with custom compare function snipped ] > What if I need only a max, or min value, and not a complete > sort, but I do want to have a custom compare func. What could I > do? > min() and max() built-ins cannot take a compare func. Use reduce: def absolulte_minimum_function( x, y ): x, y = abs( x ), abs( y ) if x < y: return x else: return y minimum = reduce( absolute_minimum_function, l ) There's probably some (awfully horrible) lambda-embeddable equivalent to absolute_minimum_function, but I'm not about to try to figure it out right now, and even if I did, I'd probably end up not using it anyway. HTH, Heather -- Heather Coppersmith That's not right; that's not even wrong. -- Wolfgang Pauli From fumanchu at amor.org Fri Apr 23 10:54:40 2004 From: fumanchu at amor.org (Robert Brewer) Date: Fri, 23 Apr 2004 07:54:40 -0700 Subject: bytecode JUMP_IF_* always followed by POP_TOP? Message-ID: Christos "TZOTZIOY" Georgiou wrote: > On Thu, 22 Apr 2004 13:48:16 -0700, rumours say that "Robert Brewer" > might have written: > > >I notice that, whether JUMP_IF_FALSE jumps or not, the next > instruction > >it executes is POP_TOP (in the above, instruction numbers 6 and 14). > > The following thread is relevant : > > -8&threadm=bpr6musc14m74uqss78iehtl72h9qrmu7o%404ax.com&rnum=1 > &prev=/groups%3Fq%3Dgroup%253Acomp.lang.python%2BPOP_TOP%2Baut > hor%253ATZOTZIOY%26ie%3DUTF-8%26oe%3DUTF-8%26hl%3Den> It doesn't have to be *quite* that long: http://groups.google.com/groups?threadm=bpr6musc14m74uqss78iehtl72h9qrmu 7o%404ax.com ;) > Check also my next message in that thread. > > I remember the results were not that impressive in pystone and some > other benchmarks (1-2% or less). Yes, as you noted, it's more of a purity issue than anything else. I actually ran across it while writing a decompiler...wondering if I could check "next instruction is POP_TOP" to tell me anything useful about the current JUMP code. But I'm past that now. :) Robert Brewer MIS Amor Ministries fumanchu at amor.org From nmkolev at uni-bonn.de Sun Apr 4 10:42:22 2004 From: nmkolev at uni-bonn.de (Nickolay Kolev) Date: 4 Apr 2004 14:42:22 GMT Subject: =?utf-8?q?Re=3A_Working_with_a_list_in_a_more_=E2=80=9Epythonic?= =?utf-8?b?4oCcIHdheQ==?= References: <20040404124833458+0200@news.rhrz.uni-bonn.de> <40700e82$1@nntp0.pdx.net> Message-ID: <20040404164229129+0200@news.rhrz.uni-bonn.de> > This is the part I'd change: > > # Setup: transitionScore['AF'] = soundScoreMatrix[0][5]. > transitionScore = {} > for i in range(26): > first = chr(65+i) > row = soundScoreMatrix[i] > for j in range(26): > transitionScore[first + chr(65+j)] = row[j] That would create another list containing all possible transitions, right? Are you doing this just to avoid indexing the matrix later when going over the phrase letter by letter? > def scoreit(phrase): > score = 0 > for i in range(len(phrase) - 1): > score += transitionScore.get(phrase[i : i+2], 0) > return score > > But if you insist on a more functional style: > > def scoreterse(phrase): > return sum([transitionScore.get(phrase[i : i+2], 0) > for i in range(len(phrase) - 1)]) It is just those *for i in range(len(x))* things I was hoping to get rid of. As mentioned, I have a solution that works and produces the expected results. I wanted to see if there was a clearer way to write what I had in mind. You see, writing the factorial function using "reduce" was a breakthrough for me... :-) Thanks for your reply! Nicky From fxn at hashref.com Fri Apr 2 11:44:07 2004 From: fxn at hashref.com (Xavier Noria) Date: 2 Apr 2004 08:44:07 -0800 Subject: outline.el usage? References: <31a13074.0404010226.6aba9509@posting.google.com> Message-ID: <31a13074.0404020844.5020099@posting.google.com> fxn at hashref.com (Xavier Noria) wrote in message news:<31a13074.0404010226.6aba9509 at posting.google.com>... > A Google search here for folding Python code in Emacs pointed to > outline.el, but when I try to use some *-hide-* commands I get "Wrong > type argument: stringp, nil". The header of the file has no > introduction. What is the basic configuration for Python and what's > the basic usage? I am sorry twice: on one hand I meant outdent.el, and on the other hand the problem was that I had a compiled .emacs I had completely forgotten. Now is working. -- fxn From gianluca.trombetta at tin.it Tue Apr 13 11:01:31 2004 From: gianluca.trombetta at tin.it (Gianluca Trombetta) Date: Tue, 13 Apr 2004 17:01:31 +0200 Subject: mcmillan installer References: Message-ID: thank you Larry, but I need to compile for linux platform and py2exe only work on windows :-( Gianluca "Larry Bates" ha scritto nel messaggio news:BMmdnUQEpNTsb-bdRVn-iQ at comcast.com... > You might also want to take a look at py2exe. It seems to > be under active development and Thomas Heller (author) > monitors this list frequently. > > http://starship.python.net/crew/theller/py2exe/ > > Larry Bates > Syscon, Inc. > > > "Gianluca Trombetta" wrote in message > news:mailman.575.1081855698.20120.python-list at python.org... > > Hi all, > > > > I'm searching a tool that compile python script to an executable binary. > > I found the mcmillan installer but i can't find a valid url to download > it. > > > > Do someone know a valid url to download it or know another similar tool? > > > > Thanks. > > Gianluca > > > > > > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > From dwelch91 at comcast.net Wed Apr 14 11:26:19 2004 From: dwelch91 at comcast.net (djw) Date: Wed, 14 Apr 2004 15:26:19 GMT Subject: interpreter limits In-Reply-To: <7xisg3vfat.fsf@ruckus.brouhaha.com> References: <407c23bf$0$570$e4fe514c@news.xs4all.nl> <407c2ecc$0$574$e4fe514c@news.xs4all.nl> <7xisg3vfat.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Irmen de Jong writes: > >>Can't you do something smart with signals, threads, alarm() and kill() ? >>Like running the code in a worker thread, where the main thread >>keeps track of how long it has been running and if not finished >>within a certain time, kill() it. > > > How do you kill a thread from another thread? I don't know of any way > to do that. > > Maybe it's safest to run the user script in a separate process and > communicate through a socket or through shm. That allows using the > normal OS features for resource limits, file protection, etc. My exploration into threads indicated that you can't kill one thread from another. -Don From bo at systemhouse.dk Thu Apr 22 12:52:48 2004 From: bo at systemhouse.dk (Bo Jacobsen) Date: Thu, 22 Apr 2004 18:52:48 +0200 Subject: How to get the ip addresses of a nic References: <2e262238.0404211825.2f6231b@posting.google.com> Message-ID: > > Is there a simple way to get all the ip addresses of a nic, beyound parsing > > /etc/sysconfig/..... > > Depending on your needs: > > >>> socket.gethostbyname(socket.gethostname()) > '192.168.0.18' > > Justin Dubs I need to get addresses on hosts with mulitiple nics, and with multiple aliases. Trying to parse output from "$ip addr show" on those hosts are not easy. Bo From loic at fejoz.net Fri Apr 9 04:00:18 2004 From: loic at fejoz.net (Yermat) Date: Fri, 09 Apr 2004 10:00:18 +0200 Subject: Special Method and Class In-Reply-To: References: <20040408184749.GA5285@performancedrivers.com> Message-ID: Jack Diederich wrote: > On Thu, Apr 08, 2004 at 02:47:49PM -0400, Jack Diederich wrote: > >>On Thu, Apr 08, 2004 at 08:07:01PM +0200, Yermat wrote: >> >>>Hi all, >>> >>>Why does special methods not work on class ? Or how to make them work ? >>>Here a simple example : >>> >>> >>>>>>class Test(object): >>> >>>... def __repr__(cls): >>>... return "" % cls.__name__ >>>... __repr__ = classmethod(__repr__) >>>... >>> >>>>>>print repr(Test) >>> >>> > >This is your clue, this didn't print >for the same reason the __iter__ does work below. >The special __method__'s only work for instances of >the class and not for the class itself. > >> >>>>>print repr(Test) >> >> >> >>>>>print repr(Test()) >> >> > > > This deserves a better explanation, > repr(some_instance) will call the __repr__ method of the thing that foo > is an instance of. > > You normally think of objects as instances of a class, but classes are > also an instances of a type. Now you're in metaclass territory which > is overkill for what you want to do. > > illustration: > > class MetaFoo(type): > """define our own type""" > def __repr__(self): > return 'this is an instance of MetaFoo' > > class Foo(object): > """define a class which is an instance of our own type""" > __metaclass__ = MetaFoo > def __repr__(self): > return 'this is an instance of Foo' > > >>>>repr(Foo) > > 'this is an instance of MetaFoo' > >>>>repr(Foo()) > > 'this is an instance of Foo' > > I can't think of a reason that classmethod() would be useful or legal > when applied to magic methods like __repr__. Maybe it should throw > an exception instead. It is possible to do things with a classmethod > __repr__ but it is a very obscure way to get the end effect. > > def Foo(object): > which = 'class' > def __init__(self): > self.which = 'instance' > def __repr__(cls): > return "Foo with which of " + cls.which > __repr__ = classmethod(__repr__) > > >>>>repr(Foo()) > > 'Foo with which of class' > > > -jackdied > Ok thanks, I see my mistake ! I thought that those special method were bounded methods but they are not... >>> class toto(object): ... def __init__(self, name): ... self.name = name ... def __repr__(self): ... return "toto('%s')" % self.name ... >>> >>> t = toto('titi') >>> repr(t) "toto('titi')" >>> t.__repr__ >>> t.__init__ That also mean that I can't change the __repr__ for only one instance : >>> def anotherRepr(self): ... return "anotherRepr('%s')" % self.name ... >>> >>> t.__repr__ = anotherRepr >>> >>> repr(t) "toto('titi')" Is it really consistent ? Should'nt it be also bounded methods even for clas instead of using MetaClass ? Yermat From newsgroups at jhrothjr.com Wed Apr 28 22:48:12 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Wed, 28 Apr 2004 22:48:12 -0400 Subject: Is classless worth consideration References: Message-ID: <1090r77d97k0tb1@news.supernews.com> "David MacQuigg" wrote in message news:g9k090lhocd1nbd7g230br6ooub113hjt6 at 4ax.com... > On 27 Apr 2004 16:34:56 -0700, has.temp2 at virgin.net (has) wrote: > > >David MacQuigg wrote in message news:... > > > >> Example of Simplified Classes ( Prototypes ) > >> ============================================ > > > >[SNIP] > > > >Class-based OOP by any other name. But then, I've pointed this out > >already. See Emperor, clothes; lack of. > > > >Here; while I don't claim them to be paragons of programming, I > >suggest taking a look at my old AppleScript libraries at > >. (Note: scripts are compiled, so > >you'll need a Mac to view source.) See Types, HTMLTemplate and ASTest > >for examples of OO programming that isn't class-fixated. Might lend > >some useful perspective. > > The problem we Python programmers are having is understanding the > fundamental advantage of eliminating classes and working only with > instances. The theoretical discussions put me to sleep. I can't see > the point of the examples above. What we need is a simple use case. > > I've included the ability to clone one instance from another in my > "Python 3" proposal > http://ece.arizona.edu/~edatools/Python/PrototypeSyntax.htm > This will allow the user to completely ignore classes, and just make > one instance from another, then another, and so on, modifying each > instance along the way, whenever the urge is felt. > > Here is what I have so far in the Pros and Cons on this feature: > > Pro: Allows "on-the-fly" programming style with no classes. > Con: Can lead to more undisciplined programming. > > Perhaps you can help us here. So far, I have one use case: text adventure game programming. Most of the objects in such games are one-off, and having to create a class and an instance for each piece of scenery is more than a bit much. This is one of the reasons that standard programming languages have never gotten much traction in that domain. It's just occured to me that backing into that particular issue might work: use class methods and never bother with instantiating the classes at all. I'm not sure what we'd lose. (possibly descriptors?) John Roth > > -- Dave > From jacek.generowicz at cern.ch Mon Apr 26 08:07:07 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 26 Apr 2004 14:07:07 +0200 Subject: Magic methods in extension types References: Message-ID: Michael Hudson writes: > Not finding the tp_as_number->nb_inplace_add field? ( ... or tp_as_sequence ... ) I was afraid you (someone) was going to say that. > I think *all* magic methods correspond to slots in (or near) the type > object -- it's practically the definition of "magic method"! Hmmm >>> class foo: ... def __iadd__(self,other): ... print "__iadd__ running" ... return self ... >>> f = foo() >>> f += 2 __iadd__ running I'd be surprised if I've added __iadd__ to a type object here, yet it seems to work. Python manages to map "+=" to the method called "__iadd__" in user-defined classes, but not for extension types. What is the essential difference that makes that mapping work in one case but not in the other? From nicksjacobson at yahoo.com Thu Apr 29 10:07:39 2004 From: nicksjacobson at yahoo.com (Nick Jacobson) Date: 29 Apr 2004 07:07:39 -0700 Subject: static keyword Message-ID: I believe the following "static" command would be useful in Python. def foo(): static i = [10, 11] static firstcall = True if firstcall: print "First pass" firstcall = False i[0] += 1 print i[0] foo() foo() This would output: First pass 11 12 Just like in C, the variables i and firstcall are only assigned the first time foo() is called. To get this effect currently, one could use default arguments or wrapping the whole thing in a class. Both of these solutions seem like hacks, the above method IMO is more Pythonic. :) I have a feeling this has been discussed before, but I can't find anything on it. Thanks, --Nick From mcfletch at rogers.com Wed Apr 14 17:02:47 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Wed, 14 Apr 2004 17:02:47 -0400 Subject: Difficulty Finding Python Developers In-Reply-To: <1081975009.10988.2@ersa.uk.clara.net> References: <65cbc3dd.0404140641.3501fde8@posting.google.com> <1081975009.10988.2@ersa.uk.clara.net> Message-ID: <407DA6F7.7000405@rogers.com> Garry Knight wrote: >In message , Mike C. >Fletcher wrote: > > > >> I'm an alumni, so UofW is obviously not all it's cracked up to be ;) >> >> > >Apparently not. 'Alumni' is the plural form. You're an alumnus. :o) > > Good thing I didn't take any English courses while there; you can blame that one on my high-school :) . *poof* _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From imbosol at aerojockey.invalid Sun Apr 4 20:14:58 2004 From: imbosol at aerojockey.invalid (Carl Banks) Date: Mon, 05 Apr 2004 00:14:58 GMT Subject: Working with a list in a more ?pythonic? way References: <20040404124833458+0200@news.rhrz.uni-bonn.de> Message-ID: <6y1cc.1344$Qv6.220@fe2.columbus.rr.com> Nickolay Kolev wrote: > I have come up with the following solution, but I hope some of you might > suggest a more _functional_ (reduce and map) way of diong it. > > n = 0 # the final score of the string > > for i in range(len(phrase)): > try: > n += soundScoreMatrix[ord(x[i]) - 65][ord(x[i + 1]) - 65] > except IndexError: > pass > > I was thinking about using "reduce", but that would not work as the > input and output of the function I would use are different (string input, > integer output). IMO, the clearest functional way to do it (where, for the sake of argument, we're defining functional not to include list comps) is to use offset slices. The idea is to use one slice of phrase to represent the first index, and a second slice, offset by one, to represent the second index in the matrix. I'd also map the phrase into integers beforehand. Take a look: iphrase = map(lambda x:ord(x)-65,phrase) n = sum(map(lambda a,b: soundScoreMatrix[a][b], iphrase[:-1], iphrase[1:])) If you want to use reduce instead of sum (say you're not yet at Python 2.3), then replace "sum(x)" with "reduce(operator.add,x)". -- CARL BANKS http://www.aerojockey.com/software "If you believe in yourself, drink your school, stay on drugs, and don't do milk, you can get work." -- Parody of Mr. T from a Robert Smigel Cartoon From grey at despair.dmiyu.org Wed Apr 28 19:32:18 2004 From: grey at despair.dmiyu.org (Steve Lamb) Date: Wed, 28 Apr 2004 23:32:18 GMT Subject: Is Perl *that* good? References: <87fzaqmm8t.fsf@strauser.com> <38ec68a6.0404262308.50029919@posting.google.com> Message-ID: On 2004-04-28, Carl Banks wrote: > Because if regexp objects are local, they have to be recompiled every > time you call the function. If you're doing that, you could be taking > a performance hit. I guess it depends on your functional style, > though. If your scripts have only one or two functions where all the > regexps are and it only gets called a few times, then it probably > won't matter too much to you. Hrm, this gives me a hint on why one of my work scripts seems to be running so slowly. I think I might be compiling REs every pass and it shouldn't be. -- Steve C. Lamb | I'm your priest, I'm your shrink, I'm your PGP Key: 8B6E99C5 | main connection to the switchboard of souls. -------------------------------+--------------------------------------------- From jwsacksteder at ramprecision.com Mon Apr 19 09:08:59 2004 From: jwsacksteder at ramprecision.com (jwsacksteder at ramprecision.com) Date: Mon, 19 Apr 2004 09:08:59 -0400 Subject: outline-style sorting algorithm Message-ID: <71650A6F73F1D411BE8000805F65E3CB3B3A4D@SRV-03> I have a need to sort a list of elements that represent sections of a document in dot-separated notation. The built in sort does the wrong thing. This seems a rather complex problem and I was hoping someone smarter than me had already worked out the best way to approach this. For example, consider the following list- >>> foo ['1.0', '1.0.1', '1.1.1', '1.2', '1.9', '1.10', '1.11', '1.20', '1.20.1', '1.30'] >>> foo.sort() >>> foo ['1.0', '1.0.1', '1.1.1', '1.10', '1.11', '1.2', '1.20', '1.20.1', '1.30', '1.9'] Obviously 1.20.1 should be after 1.9 if we look at this as dot-delimited integers, not as decimal numbers. Does anyone have pointers to existing code? From donn at u.washington.edu Wed Apr 28 14:02:49 2004 From: donn at u.washington.edu (Donn Cave) Date: Wed, 28 Apr 2004 11:02:49 -0700 Subject: Why we will use obj$func() often References: <84Uhc.22278$dZ1.5087@fed1read04> <8AWhc.23114$dZ1.11070@fed1read04> <40883BFE.B381518A@alcyone.com> <27_hc.23801$dZ1.2716@fed1read04> <40887145.789A2FE8@alcyone.com> <7cki80hj976bia36lhf9er97v073o1pqvm@4ax.com> <5vJjc.13116$Qy.1954@fed1read04> Message-ID: In article <5vJjc.13116$Qy.1954 at fed1read04>, "Mark Hahn" wrote: ... > I guess the whole problem is my insistence on simple scope indentification > by looking at the variable. It causes the var to need to be tagged. Well, in a sense this is a simplistic avoidance of scope. Scope is how unqualified identifiers are resolved. You hope that actual usage is simple enough that a relative qualifier will prop up the weaknesses of Python's half-lexical, half-dynamic system; Greg points out that it doesn't handle more complex usage like nested functions (and Simon's list comprehension / loop). You can dismiss those as uncommon problems, but then this whole feature addresses a problem that bothers only those who choose to be afflicted. > I feel strongly that the Python mixture of declaration (global), default > (where assigned) and broken (closures) is broken overall and has to be fixed > in Prothon. I take this as a given. So I see these possible solutions: > > 1) My Ruby-like symbols, which I think are readable and fast-compilable. > > 2) Word-like symbols, which are large, less readable (too me) and > cluttering. > > 3) Declarations, which cause the compiler and user to look around and are > not Pythonic. > > Am I missing any other solutions? I've already talked about making scope purely lexical, only explicit dynamic name space binding. http://groups.google.com/groups?selm=1082827791.810981%40yasure&oe=UTF-8& output=gplain As I said there, declaration isn't an interesting part of that, but the idea that declarations are "not Pythonic" strikes me as particularly absurd (not to mention just seeing you, of all people, offer this criticism.) What is "class"? What is "def"? Donn Cave, donn at u.washington.edu From imbosol at aerojockey.com Thu Apr 8 17:00:31 2004 From: imbosol at aerojockey.com (Carl Banks) Date: 8 Apr 2004 14:00:31 -0700 Subject: surface fitting library for Python? References: <40748902$0$17253$a1866201@newsreader.visi.com> Message-ID: <60dfb6f6.0404081300.78bbe0f9@posting.google.com> Grant Edwards wrote in message news:<40748902$0$17253$a1866201 at newsreader.visi.com>... > I'm looking for a surface fitting library for Python. > > Something like the least-squares module in scientific python, > except I want to fit a surface (z = f(x,y)) instead of a curve > (y = f(x)). Idea: see if you can use the versatility of Python to fool SciPy into fitting a surface when it thinks it's fitting a curve. I don't know the exact interface of the function you speak of, but I assume you pass in a function taking two arguments (a paramter vector and an independent variable), a data vector of x values, and a data vector of f(x) values. I wonder if these vectors can be Python vectors, or do they have to be a Numeric vectors? If a Python vector suffices, then you can perhaps write your function to accept a tuple rather than a single independent value: def f(paramters,(x,y)): whatever Then, for your independent values vector, instead of [1,2,3,4] you'd use with a 2-D curve, use [(1,1),(1,2),(2,1)]. Even if a Scipy requires Numeric vectors, I think there's a good chance it can still do this. Knowing what I know about Numeric, I suspect SciPy might do the right thing if you pass in a rank 2 array as the independent variable vector. It might directly pass the an element of your rank 2 array, which is a rank 1 array, to your function (and it might not). > I found a couple other curve fitting libraries (some are > wrappers to C/Fortran libs I don't have), and I found a > curve and surface-fitting web page (www.zuzun.com) that's > written in Python -- I found a couple postings by James R. > Phillips (zunzun's author) and I suspect he's calling a > non-Python library of some sort. > > What's the recommended method for doing surface fitting in > Python? If SciPy can't do it, it's not too hard to do it by hand, unless there are bounds or unless you want to minimize a non-Euclidean distance. The setup is the hard part; Numeric can do solve a linear least squares problem in one call. -- CARL BANKS From ramen at lackingtalent.com Mon Apr 12 18:35:16 2004 From: ramen at lackingtalent.com (Dave Benjamin) Date: Mon, 12 Apr 2004 22:35:16 -0000 Subject: list comprehensions References: Message-ID: In article , Aahz wrote: > In article , > Elaine Jackson wrote: >> >>List comprehensions don't work the way you intuitively expect them >>to work. I realize many people have no intuitions about how list >>comprehensions 'should' work, so if you recognize yourself in this >>description, feel free to go back to whatever you were doing before. If >>you're still here, though, I invite you to consider the following >>definition: > > Short response: don't write complex listcomps. Would you consider a 2D loop too complex for a listcomp? -- .:[ dave benjamin: ramen/[sp00] -:- spoomusic.com -:- ramenfest.com ]:. : please talk to your son or daughter about parametric polymorphism. : From newsgroups at jhrothjr.com Wed Apr 14 11:05:34 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Wed, 14 Apr 2004 11:05:34 -0400 Subject: Pygame References: Message-ID: <107qkrbhnjpmh9b@news.supernews.com> "Alexander R?dseth" wrote in message news:c5jdv2$s4$1 at orkan.itea.ntnu.no... > Hi! > > Why isn't Pygame a part of Python? Why should it be? In looking thorough the libarary, I find that everything there is a developer tool of some sort. The few executables are things like unittest which are standard parts of the developer's tool chain. John Roth > > Cheers, > Alexander R?dseth > > From jdhunter at ace.bsd.uchicago.edu Sun Apr 18 14:05:38 2004 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Sun, 18 Apr 2004 13:05:38 -0500 Subject: python module for interactive web charts In-Reply-To: ("Moosebumps"'s message of "Sat, 17 Apr 2004 21:18:05 GMT") References: Message-ID: >>>>> "Moosebumps" == Moosebumps writes: Moosebumps> Is there anything that is made to generate web pages Moosebumps> which have charts similar to the yahoo finance stock Moosebumps> charts? Not looking to graph stocks specifically, but Moosebumps> anything. I like how you can zoom on each axis, and Moosebumps> maybe click to see numerical values and such. Moosebumps> If there isn't anything in Python, what do people Moosebumps> typically use for that kind of stuff, or is it all Moosebumps> hand-rolled? matplotlib is a 2D plotting library that supports a number of plot types - http://matplotlib.sourceforge.net/screenshots.html. The library can generate plots either to GUIs or just generate images if you want to use it in a web application server. See this link http://matplotlib.sourceforge.net/faq.html#APPSERVER for more information about using matplotlib in a web server. There are interactive navigation tools for panning and zooming, etc. The next release 0.53 due out early next week will have a lot of support for making date plots, using python datetimes, mx.Datetime, or other, with a hodge podge of minor and major date tick locators and formatters. There is also a financial module in the works which will be finished soon for candlestick plots and the like. If you're interested in getting announcements when these features are ready, you may want to join the mailing list http://lists.sourceforge.net/mailman/listinfo/matplotlib-users. Cheers, John Hunter From nhodgson at bigpond.net.au Sat Apr 3 17:37:29 2004 From: nhodgson at bigpond.net.au (Neil Hodgson) Date: Sat, 03 Apr 2004 22:37:29 GMT Subject: Indent testers needed (Prothon) References: Message-ID: Aahz: > It's not precisely a rumor; Guido has stated that this is one of the > things he's thinking seriously about for Python 3.0. There will be > enough incompatibilities that this one won't add much extra strain, > given that the official rules for Python (PEP 8) have mandated only > spaces for several years. PEP 8 is a 'style guide' which does not 'mandate' anything. It does not deprecate tab usage, merely strongly recommends spaces-only for new projects. Neil From peter at engcorp.com Sun Apr 11 22:14:33 2004 From: peter at engcorp.com (Peter Hansen) Date: Sun, 11 Apr 2004 22:14:33 -0400 Subject: maximum length of a list & tuple In-Reply-To: References: Message-ID: Josiah Carlson wrote: >>> Run the following and the last thing it prints out is your limit... >>> >>> c = 1 >>> while c < 2**32: >>> try: >>> d = [1]*c >>> print c >>> c *= 2 >>> except: >>> break >> >> >> >> Interesting experiment. I get 64M on my 384MB machine, which suggests 4 >> bytes per list entry. Of course, now my swap file is packed full, and >> all >> my apps are running slowly while they page themselves back in... > > > Far more than 4 bytes per list entry. 4 bytes to store the integers > themselves, but since integers are Python objects, and lists are arrays > of pointers to list objects, there is quite a bit of other extra stuff > attached. Actually, unless I'm mistaken that stores only one integer, and a whole lot of references to it... which are just pointers (4 bytes each). The technique is probably flawed in other ways, however, as it is likely subject to memory fragmentation and other problems. -Peter From eric at zomething.com Sun Apr 18 18:16:46 2004 From: eric at zomething.com (Eric @ Zomething) Date: Sun, 18 Apr 2004 14:16:46 -0800 Subject: New scripts directory Message-ID: <20040418141646.1249365013.eric@zomething.com> Mikl?s wrote: > > That's sorta funny. Or is it? You annouce a new website on comp.lang.python > and there's no Python section on that site.. Python? Who is Python? [I am not sure who he is, but apparently he needs Vicodin and Viagra] From RIACS at riacs.edu Tue Apr 6 02:34:50 2004 From: RIACS at riacs.edu (RIACS at riacs.edu) Date: Mon, 5 Apr 2004 23:34:50 -0700 (PDT) Subject: (no subject) Message-ID: <200404060634.i366Yoo17626@icarus.riacs.edu> Barry Leiner passed away on April 2, 2003. Please contact leiner_request at riacs.edu for all inquiries. From no at spam.invalid Wed Apr 21 15:54:59 2004 From: no at spam.invalid (Russell E. Owen) Date: Wed, 21 Apr 2004 12:54:59 -0700 Subject: Easiest way to *add a column* to a 2d matrix/array in numarray??? References: Message-ID: In article , seberino at spawar.navy.mil (Christian Seberino) wrote: >How add a column to a 2d array/matrix in numarray??? > >The unelegant way I found was to: > >1. Create a new array with an extra column (e.g. using 'zeros' function). >2. Copy original array into new array. >3. Copy new column into last column. > >Is there a slicker way to do this? Try numarray.resize -- Russell From opengeometry at yahoo.ca Fri Apr 23 15:41:01 2004 From: opengeometry at yahoo.ca (William Park) Date: 23 Apr 2004 19:41:01 GMT Subject: Regexp optimization question References: Message-ID: Magnus Lie Hetland wrote: > Now I can do something like this: > > hits = [] > for pat in pats: > hits.extend(pat.finditer(text)) > # Maybe sort them in order of occurrence > > *Or* I can do something like this: > > bigPat = '(' + '|'.join(pats) + ')' > hits = list(bigPat.finditer(text)) > > The last one is *much* faster -- but only if I forego named groups. > And without them, I can't find out which patterns matched at which > locations. (I can, as suggested, use .lastindex to find *one* of them, > but not all, as I need.) Since you want both the matched strings and their locations in file, you pretty much have to this manually, one by one. -- William Park, Open Geometry Consulting, Linux solution/training/migration, Thin-client From donn at drizzle.com Sat Apr 24 13:29:53 2004 From: donn at drizzle.com (Donn Cave) Date: Sat, 24 Apr 2004 17:29:53 -0000 Subject: Why we will use obj$func() often References: <84Uhc.22278$dZ1.5087@fed1read04> <8AWhc.23114$dZ1.11070@fed1read04> <40883BFE.B381518A@alcyone.com> <27_hc.23801$dZ1.2716@fed1read04> <40887145.789A2FE8@alcyone.com> <7cki80hj976bia36lhf9er97v073o1pqvm@4ax.com> <1082783076.585831@yasure> Message-ID: <1082827791.810981@yasure> Quoth "Mark Hahn" : | "Donn Cave" wrote ... ... |> I might seriously |> consider what I believe we call lexical scoping, and a declaration - |> not assigning a type, but an initial value, like "let x = 0". |> Namespaces like Python's would be for objects - modules, classes, |> class instances, whatever - not functions - and would be purely |> explicit, not implicit like a scope (I think that would most |> conspicuously require some alternative for "def" statements, |> for example.) | | I'm not following you exactly, but I think what you are asking for is the | declaration of variables with "let x = 0", or what some languages use is | just "var x" that specify that the variable belongs in the scope of that | declaration. This resolves the ambiguity of local versus global variables | and even gives a nice solution for closures. The declaration is probably the most trivial part of it. The notation could be omitted - may as well, since "x = 0" would be implicitly the the same as "let x = 0" anyway. The point is that scope is purely lexical, defined by source structure - top to bottom, left to right, outside to inside. My hunch is that this would be less confusing, especially multiple nested scopes are no problem with lexical scoping. It should also make for more efficient execution, because compiler/interpreter is looking at the complete story on what's what. For example, you can have true global constants, a common programming notion that Python doesn't support. It would be fatal for closures of the counter type, because that takes a runtime binding somewhere. This would be legal code - mkCounter = function (): i = 0 countup = function (): i = i + 1 print i return countup ... but the countup function would always print "1". You'd need an explicit function namespace, like - mkCounter = function (): countup = function (): .i = .i + 1 print .i countup.i = 0 return countup ... but maybe this is where we realize that this functionality belongs to objects. Donn Cave, donn at drizzle.com From fumanchu at amor.org Sat Apr 17 00:28:18 2004 From: fumanchu at amor.org (Robert Brewer) Date: Fri, 16 Apr 2004 21:28:18 -0700 Subject: Python OS Message-ID: Paul Watson wrote: > What if we had a machine whose native instruction set was > Parrot bytecode? That's been suggested before: http://z.iwethey.org/forums/render/content/show?contentid=120862 FuManChu (sorry for the double-post--$%^&* Outlook) From Mike at DeleteThis.Geary.com Fri Apr 16 02:45:42 2004 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Thu, 15 Apr 2004 23:45:42 -0700 Subject: CamelCase versus wide_names (Prothon) References: <7xekqo36ia.fsf@ruckus.brouhaha.com> Message-ID: <107v08mopdgr9e9@corp.supernews.com> > Mark Hahn wrote: > > 1) CamelCase is more elegant, modern, more readable, and more efficient in > > character usage. Paul Rubin wrote: > IfCamelCaseWereReallyMoreReadable, We'dWriteOrdinaryEnglishLikeUsingIt. > SoThatClaimIsRidiculousAndNeedsToBeThrownOutTheWindowPostHaste. > > 2) Wide_names is cleaner, more readable, compatible with C, which is the > > standard module language for Python and Prothon. Wide_names is also the > > Python standard. > Sounds_ok_with_me. I_find_it_a_heck_of_a_lot_more_readable_than_camel_case. > I_vote_for_wide_names. If we were writing English sentences and for some reason were forced to write an entire sentence as a single word in one of these two styles, then I would be persuaded by your examples. But, we're not writing English, and we're not writing an entire sentence as a single word. We are writing program code where we compose a single name out of multiple words. That name is combined with several other names in a statement or expression with much more punctuation than you'd use in English prose. To me, names_with_underscores are easy to read in isolation. But when they are combined with multiple other names_with_underscores and a lot of punctuation, the result for me is visually confusing. I have a hard time seeing where one name ends and another one begins. Underscore is a punctuation mark too. But since you're using English to make the point, let's run with it a bit. However, instead of contrived examples that no one would ever write, we'll use a real English paragraph with real names: I edit my Python code with SlickEdit and ActiveState Komodo. I use an IBM ThinkPad, largely because I like its TrackPoint pointing device. I enjoy taking pictures with my Canon PowerShot camera, and I use a PreSonus BlueTube preamp when I play harmonica. Today I drove by OfficeMax, and I saw ads for the DoubleTree hotel and Lufthansa's PrivateBeds and FlyNet. What if I wrote this instead: I edit my Python code with Slick_edit and Active_state Komodo. I use an IBM Think_pad, largely because I like its Track_point pointing device. I enjoy taking pictures with my Canon Power_shot camera, and I use a Pre_sonus Blue_tube preamp when I play harmonica. Today I drove by Office_max, and I saw ads for the Double_tree hotel and Lufthansa's Private_beds and Fly_net. Is that easier to read? -Mike From __peter__ at web.de Sat Apr 10 11:24:41 2004 From: __peter__ at web.de (Peter Otten) Date: Sat, 10 Apr 2004 17:24:41 +0200 Subject: Static Data? References: <2FTdc.56817$Id.5813@news-binary.blueyonder.co.uk> Message-ID: Stevie_mac wrote: > I need to have a static class data member like c (see semi pseudo-like > code below). How can I achieve this? class Object: # Python already has a builtin object class; # use uppercase Object to avoid nameclash _ID = 1 def __init__(self): self.ID = Object._ID Object._ID += 1 # An alternative implementation # import itertools # class Object: # IDGen = itertools.count(1) # def __init__(self): # self.ID = self.IDGen.next() # successive calls yield 1, 2, 3, ... class Group(dict): # you could make this more dict-like def addObject(self, obj): self[obj.ID] = obj def getObject(self, iWhich): return self[iWhich] g = Group() o1 = Object() o2 = Object() o3 = Object() g.addObject(o2) g.addObject(o3) g.addObject(o1) print g.getObject(1).ID print g.getObject(2).ID print g.getObject(3).ID The above works, but I've got a hunch that you are on the wrong track here. Most likely you should pass o1, o2, ... around instead of the IDs. Peter From richie at entrian.com Thu Apr 1 02:10:29 2004 From: richie at entrian.com (Richie Hindle) Date: Thu, 01 Apr 2004 08:10:29 +0100 Subject: ANNOUNCE: 'goto' for Python Message-ID: Entrian Solutions is pleased to announce version 1.0 of the 'goto' module. This adds the 'goto' and 'comefrom' keywords to Python 2.3, adding flexibility to Python's control flow mechanisms and allowing Python programmers to use many common control flow idioms that were previously denied to them. 'goto' example: breaking out from a deeply nested loop: from goto import goto, label for i in range(1, 10): for j in range(1, 20): for k in range(1, 30): print i, j, k if k == 3: goto .end label .end print "Finished\n" 'comefrom' example: letting cleanup code take control after an error. from goto import comefrom, label def bigFunction(): setUp() if not doFirstTask(): label .failed if not doSecondTask(): label .failed if not doThirdTask(): label .failed comefrom .failed cleanUp() Computed 'goto's are also supported - see the documentation for details. Computed 'comefrom's are planned for a future release. Documentation and further examples: http://entrian.com/goto/index.html Downloads: http://entrian.com/goto/download.html The 'goto' module is released under the Python Software Foundation license, and requires Python 2.3 or later. Please note that this version does not work at the interactive Python prompt - code importing 'goto' must be in a .py file. This restriction will hopefully be lifted in a future release. -- Richie Hindle richie at entrian.com From fumanchu at amor.org Fri Apr 16 19:31:37 2004 From: fumanchu at amor.org (Robert Brewer) Date: Fri, 16 Apr 2004 16:31:37 -0700 Subject: datetimes, tzinfo and gmtime epoch Message-ID: John Hunter wrote: > Robert> John Hunter wrote: > >> I have a python2.3 datetime instance and a tzinfo instance (eg > >> Eastern from the python library reference). > >> > >> What is the best way to convert that datetime instance to > >> seconds since the epoch, gmtime? > > Robert> You might try time.mktime(t), where t is a 9-tuple as > Robert> desribed at: > > > Yes, but you still have to account for the offset to gmtime, which is > dependent on daylight savings time. Sometimes I settle for giving general directions, not free rides. :D FuManChu From achim.marcel at uqam.ca Thu Apr 8 13:07:51 2004 From: achim.marcel at uqam.ca (Marcel Achim) Date: Thu, 08 Apr 2004 17:07:51 GMT Subject: Tcl/Tk extension access from python under windows Message-ID: Hi, I found a tcl extension that does exactly what I need to access a DLL and it would require a large amount of SWIG glue to generate an equivalent python extension. I want to access it via root.tk.call("eval", "package require extension"). I placed the extension dll (as well as the target DLL) in my Python DLLs path at the same place where the tcl/tk DLLs are. The eval fails because it doesn't find the extension. Is there a special initialisation/registration/setup change to be made to python ? thanks Marcel Achim From littlejohn.75 at news.noos.fr Thu Apr 8 05:01:44 2004 From: littlejohn.75 at news.noos.fr (F. Petitjean) Date: 08 Apr 2004 09:01:44 GMT Subject: regex help for a newbie References: Message-ID: <407514f8$0$22878$626a14ce@news.free.fr> On 6 Apr 2004 22:38:24 GMT, Marco Herrn wrote: > On 2004-04-06, marco wrote: >> Marco Herrn writes: >> >>> On 2004-04-06, marco wrote: >>> > Marco Herrn writes: >>> >> the parts in a recursive function. So the thing I want to achieve here >>> >> is to extract %(BBB%(CCC)BBB) and %(DDD). >>> > >> >> Does the "aaa"-type string really show up three times? Or is it actually: >> >> "maybeeggs%(BBB%(CCC)BBB)maybeham%(DDD)maybespam" > > Yes, it is this. I just used the same strings to indicate the nesting > levels. All strings in this expression are arbitrary strings. > >> (but I doubt it -- I guess you'll need a real parser :) > > Yes, I already realized that :-) > > Marco > A solution without any re nor parser : the basic idea is nesting, wrapping of parsplit as a true recursive function is left as an exercice to the reader. #! /usr/bin/env python # -*- coding: iso-8859-1 -*- # # parparse.py # class NestingParenError(Exception): """Parens %( ) do not match""" def parsplit(s, begin='%(', end=')'): """returns before, inside, after or s, None, None raises NestingParenError if begin, end pairs are not nested""" pbegin = s.find(begin) if pbegin == -1: return s, None, None before = s[:pbegin] pend = s.rfind(end) if pend == -1: raise NestingParenError("in '%s' '%s' found without matching '%s'" %\ (s, begin, end)) inside = s[pbegin+len(begin):pend] return before, inside, s[pend+len(end):] def usage(s): """Typical use of parsplit""" before, inside, after = parsplit(s) if inside is None: print "'%s' has no %%( ) part" % (s,) return # process : print "before %s\ninside %s\nafter %s" % (before, inside, after) while inside: before, inside, after = parsplit(inside) # process : print "before %s\ninside %s\nafter %s" % (before, inside, after) if __name__ == '__main__': """basic tests""" s1 = """aaaa a%(bbb bbb%(iiii) ccc)dddd""" print "nested case %s" % (s1,) usage(s1) print print usage("""0123before%()""") print usage("""%(inside)""") print usage("""%()after""") print s2 = """without closing %( paren""" s3 = """without opening ) paren""" try: usage(s2) except NestingParenError, e: print e print usage(s3) Hope that helps Regards From opengeometry at yahoo.ca Tue Apr 20 01:55:18 2004 From: opengeometry at yahoo.ca (William Park) Date: 20 Apr 2004 05:55:18 GMT Subject: CamelCase versus wide_names (Prothon) References: <6ee58e07.0404192141.2229efd6@posting.google.com> Message-ID: Lothar Scholz wrote: > After writing a few hundert thousands lines of code in Eiffel and a > few ten thousands lines in Java i must say that lowercase wide_names > are much much better to read. Someone else already mentioned this > problem: > > smtp_message <-> SMTPMessage <-> SmtpMessage Agreed. 2nd example illustrates the main problem, where the part of word is all uppercase. Likewise, 'smtpMESSAGE' is equally bad. -- William Park, Open Geometry Consulting, Linux solution/training/migration, Thin-client From andrew.henshaw at gtri.gatech.edu Fri Apr 16 14:07:35 2004 From: andrew.henshaw at gtri.gatech.edu (Andrew Henshaw) Date: Fri, 16 Apr 2004 14:07:35 -0400 Subject: CamelCase versus wide_names (Prothon) References: Message-ID: <1080877ckml9o70@corp.supernews.com> Fran?ois Pinard wrote: ...snip... > Given full power and choice, what I would prefer is that identifiers be > allowed to contain spaces -- would they have to be unbreakable spaces. > That would be the most legible avenue, especially given that my editors > and enscripters would then bold or colour Python/Prothon keywords, making > it clear the extent of each identifier. Take this very message, save > it in two files, then edit the first copy to replace all spaces within > a sentence with underlines, and edit the second copy to replace all > spaces within a sentence with the empty string, but capitalising the > next character. My guess, which some might challenge, is that there > will almost be a concensus that the first copy is easier to decipher. > > Legibility should be the overwhelming concern. > Your comments bring to mind something that might be nice to see in an editor: black text with automatic light gray underscores. This might provide a less jarring alternative to the full underscore, but there would be no confusion as to whether or not the separator was meant to be a space. postscript: just tried it in my word processor and it's a pretty good effect -- Andy From michael at foord.net Tue Apr 6 03:48:40 2004 From: michael at foord.net (Fuzzyman) Date: 6 Apr 2004 00:48:40 -0700 Subject: ANNOUNCE : dataenc.py and Pythonutils Message-ID: <8089854e.0404052348.15e3a04e@posting.google.com> http://www.voidspace.org.uk/atlantibots/pythonutils.html Various Python Resources Home of : Nanagram - anagram finder. Tkinter GUI version and a CGI for including in your own websites. Voidspace Python Guestbook Modules : *NEW* dataenc.py - a definable binary to ascii encoding with timestamping and binary interleaving. ConfigObj 2 - a simple config file parser that behaves like a dictionary. listparser - parsing strings into lists, elements of lists can themselves be lists dateutils - functions for handling dates, leap years, future dates etc csv_s - simple and straightforward CSV file reading and writing Dataenc : Version 1.1.0 This is a set of functions that provide a binary to ASCII encoding (based on a user definable TABLE) and binary interleaving which can be used for combining files or time/datestamping data. The purpose of this is that an encrypted password can be timestamped and then included as ASCII in a hidden form field - in the HTML output of a CGI. This gives a convenient way of providing a 'user login' with a CGI - but the password (or it's SHA hash) that is hidden in the HTML is 'time stamped' so that even if is extracted from the HTML it can't be used once it has expired. Conceivably, the binary interweave functions could be used for combining, 'watermarking' or timestamping any data. The binary to ascii function is no 'better' than the binascii module - but the mapping is user definable. It can be used for storing *any* binary data as ascii - e.g. an SHA hash in a ConfigObj ! Dateutils : Version 1.0.2 This is a set of functions for dealing with dates - written for a little tool called 'Victory Days'. They are particularly useful for dealing with appointments - e.g. the second Tuesday in March etc... The functions will tell you what day of the week a date is, work out the 'Julian day number' of a date is, correctly add numbers of days (weeks, months etc) to a date and tell you the number of days between a date, format a datestring etc. Full correction for leap years and much more. ConfigObj : Version 2.0.0 ConfigObj is a lightweight and easy to use config file parser. It allows you and your users to write simple text config files - and for you to easily load, parse, change and save them. In practise, you hand ConfigObj a filename and it parses the values from keywords in the file. For adding, retreiving or changing values/keywords it then behaves like a normal python dictionary. You can then write the edited data back to file if you need to with a simple configobj.write() command. You can give it a list of keywords to parse - or simply have it find all the keywords in the file. Comments inline with keywords are preserved. Listparse : Not only this, but each value can either be a single value *or* a list of values. This now includes lists of lists !! In other words each element of a list, can itself be a list. This is implemented using listparser - a simple module with functions for reading lists from a string and also turning lists back into strings. A useful way of storing data in a readable format. This module is available seperately if you want but included in the configobj2 zip. csv_s : Functions for reading, writing and comparing CSV files. Very simple to use. Useful for places where you haven't got Python 2.3 installed or don't need the complexity of the CSV module. A few other 'simple' goodies that some may find useful............ *Also* : YAPLP - Yet Another Python Links Page http://www.voidspace.org.uk/coollinks/python_links.shtml Regards, Fuzzy From skip at pobox.com Tue Apr 20 18:05:07 2004 From: skip at pobox.com (Skip Montanaro) Date: Tue, 20 Apr 2004 17:05:07 -0500 Subject: emacs for OS X In-Reply-To: <1gckdxe.x3vsll1r5u4tfN%fabio.trezziCANCELLAMI@email.it> References: <1gcjrc7.1s60i39g5q0kiN%fabio.trezziCANCELLAMI@email.it> <1gckdxe.x3vsll1r5u4tfN%fabio.trezziCANCELLAMI@email.it> Message-ID: <16517.40595.544466.38684@montanaro.dyndns.org> >> The current release of python-mode.el is no longer maintained on this >> website. Check the python-mode project on Sourceforge instead. Wezzy> Today when i post my message i've opened Wezzy> http://www.python.org/emacs/python-mode/ and followed the link to Wezzy> sf.net but the project hasn't released any file yet, so i've Wezzy> posted the url to the www.python.org version that is still Wezzy> online. You've shamed me into releasing the single file which is part of the project. The new release is "barking-up-the-wrong-tree". If we get more formal with the releases perhaps I'll adopt a numeric release schedule. Wezzy> (Anyway the old one is still online) I'll see about deleting it. Skip From peter at engcorp.com Mon Apr 12 14:11:23 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 12 Apr 2004 14:11:23 -0400 Subject: String + number split In-Reply-To: <2SAec.70005$Id.6002@news-binary.blueyonder.co.uk> References: <2SAec.70005$Id.6002@news-binary.blueyonder.co.uk> Message-ID: Stevie_mac wrote: > Hello again, I can do this, but I'm sure there is a much more elegant way... > > A string, with a number on the end, strip off the number & discard any underscores > > eg... > > font12 becomes ('font',12) > arial_14 becomes ('arial',14) It's impossible to say if it's more elegant, since you didn't post your attempt. (Homework? I'll assume not.) >>> import re >>> def fsplit(fs): ... return tuple(re.split('(\d+)', fs.replace('_', ''))[:2]) ... >>> fsplit('font12') ('font', '12') >>> fsplit('arial_14') ('arial', '14') I wouldn't actually code it this way myself, but it meets your requirements as stated. -Peter From max at alcyone.com Fri Apr 23 23:06:13 2004 From: max at alcyone.com (Erik Max Francis) Date: Fri, 23 Apr 2004 20:06:13 -0700 Subject: deleting items within a for loop - mutable indices References: <4089cb21$1_2@mk-nntp-2.news.uk.tiscali.com> Message-ID: <4089D9A5.1A0C9C02@alcyone.com> SnuSnu wrote: > Okay - here's a (probably) really easy question: > > I can't do the following, so what's the best way to handle this > case of wanting to delete within a loop? > > x = [0,1,2,3,4,5,6,7,8] > deletion_list = [2,7,8] > > for i in deletion_list: > del x[i] > > This obviously doesn't work because the list keeps changing > each time I delete something, so the indices are no longer valid > after the first delete (so I get an IndexError on teh last delete). The solution is usually to either iterate over an explicit copy of the list, or use functional means to build the final list up from the original list without mutating it at all. In this case it's probably best to just iterate backwards over the indices, since you know what you're getting and can control the order in which you delete the items. > deletion_list.sort() > deletion_list.reverse() > # BTW: It's a shame I can't do deletion_list.sort().reverse() This is a deliberate design decision. These methods are made to return None so you're explicitly aware that they mutate the object, rather than return a duplicate. You can always define your own functional version: def mySort(seq): result = seq[:] result.sort() return result -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis \__/ Awards are merely the badges of mediocrity. -- Charles Ives From roy at panix.com Tue Apr 27 19:43:45 2004 From: roy at panix.com (Roy Smith) Date: Tue, 27 Apr 2004 19:43:45 -0400 Subject: Is Perl *that* good? References: <108q51j4dscn7dc@corp.supernews.com> <87fzaqmm8t.fsf@strauser.com> <38ec68a6.0404262308.50029919@posting.google.com> Message-ID: Carl Banks wrote: > Hmm. The reason this hasn't been done is that it makes the match > method non-reentrant. For example, suppose you call some functions in > between the matching and use of the matched object, like this: > > if myregex.match(line): > xyz = (subprocess(line[myregex.lastm.end():]) > + myregex.lastm.group(1)) > > And suppose subprocess goes on to use the same regexp. By the time > subprocess returns, myregex.lastm could have been overwritten. This > is not a far-fetched example at all; one could easily encounter this > problem when writing, say, a recursive descent parser. I don't see that this is any worse than any other stateful object. If you change the state of the object, you can't expect to get the same data from it as you did before. From antiego at nospam.rocketmail.com Thu Apr 1 09:56:37 2004 From: antiego at nospam.rocketmail.com (Greg) Date: Thu, 01 Apr 2004 09:56:37 -0500 Subject: Microsoft making Python.NET Message-ID: The following article from microsoft describes a workaroind for a bug in hte beta version of VISUAL PYTHON DOT NET http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnaskdr/html/askgui04032001.asp When did microsoft put python into the visual studio beta? How did this not make big news in developmnt circles? A.E. Here is the body of the article: FIX: Memory Leak after pickling in Visual Python .NET Beta 1 View products that this article applies to. This article was previously published under Q114345321 IMPORTANT: This article contains information about modifying the registry. Before you modify the registry, make sure to back it up and make sure that you understand how to restore the registry if a problem occurs. For information about how to back up, restore, and edit the registry, click the following article number to view the article in the Microsoft Knowledge Base: 114345321/8 Description of the Microsoft Windows Registry SYMPTOMS When pickling an object containing a cyclic graph, the Visual Python .NET Beta 1 can create references that will not be garbage collected. CAUSE Visual Python .NET Beta 1 does not impose a recursion limit by default. In this mode, an objects references are evaluated lazily durring pickling. If the garbage collector runs durring this process, some objects can be incorrectly referenced. The failure is due to registry key data that was installed by Visual Python .NET Beta 1. RESOLUTION WARNING: If you use Registry Editor incorrectly, you may cause serious problems that may require you to reinstall your operating system. Microsoft cannot guarantee that you can solve problems that result from using Registry Editor incorrectly. Use Registry Editor at your own risk. Open Regedit.exe and browse to HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\8.0\P++\RecursionLimit. To be safe, back up this registry key: From the File menu, click Export and save the key to an .reg file. Set the RecusionLimit key from 0 to 1000. STATUS Microsoft has confirmed that this is a bug in the Microsoft products that are listed at the beginning of this article. This bug will be corrected in Visual Python .NET (2004). The information in this article applies to: Microsoft Visual Studio .NET 8.0, Beta 1 From richie at entrian.com Fri Apr 2 09:52:56 2004 From: richie at entrian.com (Richie Hindle) Date: Fri, 02 Apr 2004 15:52:56 +0100 Subject: Making the Zen of Python more useful In-Reply-To: <106qp0uivlefo40@corp.supernews.com> References: <106qp0uivlefo40@corp.supernews.com> Message-ID: <8tuq60dlg9v5lkt3pu5q70a13nr9738gj0@4ax.com> [Andrew] > Any thoughts [on how to get the output of "import this" programmatically]? Fresh from the "Well it works but you'd never use it" factory: import os, tokenize, token libDir = os.path.split(tokenize.__file__)[0] thisPathname = os.path.join(libDir, 'this.py') for tokenType, tokenString, (startRow, startCol), (endRow, endCol), line \ in tokenize.generate_tokens(open(thisPathname, 'r').readline): if tokenType == token.STRING: # It had better be the first string! print tokenString.decode('rot13') break else: print "Someone edited this.py!" -- Richie Hindle richie at entrian.com From cmg at dok.org Mon Apr 12 22:52:02 2004 From: cmg at dok.org (Chris Green) Date: Mon, 12 Apr 2004 22:52:02 -0400 Subject: pdb + unittest Message-ID: After forcing myself to start unittest each module I write from the get go versus writing some simple apps to excercise some subset of functionality, I realized it's pretty hard to use pdb + unittest. The standard place is a test case is failing, aborting with an assert and I want to debug the statement prior to find out what went wrong. def test_method(self): res = self.obj.do_something() self.assertEqual(res, 42) res = foo(res) Often I want to debug at the first do something so I replace it with: import pdb res = pdb.runcall(self.obj.do_something) This work great but I don't want pdb to exit from interactive control until perhaps after the foo(res) call. Is there a simple way I could get pdb to shove itself higher up in the flow control? How about a mildly complex one? :) Thanks, Chris -- Chris Green A watched process never cores. From simoninusa2001 at yahoo.co.uk Sun Apr 4 22:58:52 2004 From: simoninusa2001 at yahoo.co.uk (simo) Date: 4 Apr 2004 19:58:52 -0700 Subject: where download mcmillan installer References: Message-ID: <30260531.0404041858.91c5229@posting.google.com> I've got a copy of 5 beta 5 too (same as the SpamBayes one I think): http://www.the-jedi.co.uk/comps/downloads/installer_5b5_5.zip http://www.the-jedi.co.uk/comps/downloads/installer_5b5_5.tar.gz They both have the same files inside the archives. I don't know what's happened with Installer, there was some talk of Gordon having hosting problems, but that was weeks ago. Dunno why Sourceforge couldn't be used instead.... From alloydflanagan at comcast.net Wed Apr 21 17:50:42 2004 From: alloydflanagan at comcast.net (A. Lloyd Flanagan) Date: 21 Apr 2004 14:50:42 -0700 Subject: inheritance and private attributes References: Message-ID: KN wrote in message news:... > I've run into such problem: > > I have something like this: > > class A(object): > def __init__(self): > self.__value = None > > class B(A): > def test(self): > if self.__value: > print "Ok." > else: > print "Empty." > > >>> b = B() > >>> b.test() > Traceback (most recent call last): > File "", line 1, in ? > File "", line 3, in test > AttributeError: 'B' object has no attribute '_B__value' > > Why I have no access to private attribute from a class that > inherits other class? I just want to have access to the same > private variables but also to extend its functionality by > adding a method that operates on those private attributes and > I'm unable to do so. > > Is this normal behaviour? What should I do if I want to > override method and use private attribute, or just add > some other method which changes this attribute? > > /K This is normal behavior (by design). In general a derived class has no special access to the attributes defined in its parent; there is no equivalent of C++'s "protected" variables. I see two solutions: 1) Have the child use an accessor function (if class A above had a getValue() method, you could call it with A.getValue(self)). 2) Cheat. In class B, access self._A__value. This duplicates the "mangling" that python does to hide variables with double underscore in front. I'd recommend 1), unless you have some urgent performance problem. 2) is probably a bit faster. Fast example of 2): >>> class a: ... def __init__(self): ... a.val = 3 ... def getValue(self): ... return a.__val ... def __init__(self): ... a.__val = 3 >>> x = a() >>> a.getValue() 3 >>> class b(a): ... def __init__(self): ... a.__init__(self) ... def getValue(self): ... return a._a__val + 2 ... >>> y = b() >>> y.getValue() 5 From rogerb at rogerbinns.com Sat Apr 3 15:40:04 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Sat, 3 Apr 2004 12:40:04 -0800 Subject: [maybe OT] Making posters References: <95aa1afa.0404030143.58c32975@posting.google.com> Message-ID: <02k3k1-1nc.ln1@home.rogerbinns.com> Michele Simionato wrote: > Perhaps this is a bit off topic, but I haven't had look browsing on the > net, so I thought I will try my chance here. I am looking for a > tool taking a postscript file and enlarging it to make a poster. Well, it was on topic enough for PyCon :-) http://www.python.org/pycon/dc2004/papers/52/main.html Roger From viruswall at heinz.vodafone-is.de Wed Apr 14 04:24:31 2004 From: viruswall at heinz.vodafone-is.de (viruswall at heinz.vodafone-is.de) Date: Wed, 14 Apr 2004 10:24:31 +0200 (MEST) Subject: Virus Alert Message-ID: <200404140824.i3E8OLm08524@heinz.vodafone-is.de> The mail message (file: file.zip) you sent to contains a virus. (on heinz.vodafone-is.de) From igouy at yahoo.com Thu Apr 8 11:38:57 2004 From: igouy at yahoo.com (Isaac Gouy) Date: 8 Apr 2004 08:38:57 -0700 Subject: why is python better than eg. smalltalk?? References: <20031028061245.12451.00000133@mb-m01.aol.com> Message-ID: "Daniel Dittmar" wrote in message news:... > When I started using Python, there were two reasons: > - no good free eimplementation of Smalltalk > - Smalltalk doesn't scale well to small tasks > > Point 1 has probably changed with Squeak. But I'd really have to use it for > a while to be confident enough to inflict it upon others. Yes Smalltalk has been around since the days when software was sold as a product, so the main Smalltalk implementations are commercial - IBM, VisualWorks (VisualWorks is available gratis for non-commercial use), Dolphin. GNU Smalltalk is a fine open-source implementation for POSIX. Pocket Smalltalk is a fine open-source implementation for Palm. > Don't know about point 2: When I had a new version of some small 'script', I > had only the alternatives > * to distribute full images Most Smalltalks provide for distribution of a stripped compressed image. Several Smalltalks provide for distribution of an EXE on MSWin. > * to distribute source which the users had to integrate into their images > Maybe this has changed as well. It was never true ;-) The commonplace approach is to have the Smalltalk runtime check a known location for source code patches, and then automatically update. From aahz at pythoncraft.com Thu Apr 1 08:48:33 2004 From: aahz at pythoncraft.com (Aahz) Date: 1 Apr 2004 08:48:33 -0500 Subject: Prothon, metaclasses, Zope [Was: A 'Python like' language] References: <95aa1afa.0403272243.78d60724@posting.google.com> <95aa1afa.0404010017.2f1683b8@posting.google.com> Message-ID: In article <95aa1afa.0404010017.2f1683b8 at posting.google.com>, Michele Simionato wrote: > > [...] Michele, I just got a mailbox full error when I tried sending you e-mail. Please fix. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "usenet imitates usenet" --Darkhawk From joe at notcharles.ca Thu Apr 15 15:42:26 2004 From: joe at notcharles.ca (Joe Mason) Date: Thu, 15 Apr 2004 19:42:26 GMT Subject: CamelCase versus wide_names (Prothon) References: Message-ID: In article , Mark Hahn wrote: > Of course in the Python world you alread have wide_names as your standard, > but could you for the moment pretend you were picking your standard from > scratch (as we are doing in the Prothon world) and give your vote for which > you'd prefer? Wasn't one of the Prothon design goals "when in doubt, follow Python"? Joe From moranar at daleclick.com Fri Apr 2 11:09:19 2004 From: moranar at daleclick.com (Adriano Varoli Piazza) Date: Fri, 2 Apr 2004 13:09:19 -0300 Subject: Python conference slogan In-Reply-To: References: Message-ID: <200404021309.19766.moranar@daleclick.com> El Mi? 31 Mar 2004 15:58, Shane Hathaway escribi?: > Here's a Python slogan suggestion by Ken Manheimer. > > One Nation Under Under Python > > I thought it was pretty funny. I don't know if international folks > will get it, though. :-) > > Shane Another suggestion: "Python Programming Language: So clean it _squeaks_". (squeaks italicized). Cheers -- Adriano Varoli Piazza The Inside Out: http://moranar.com.ar ICQ: 4410132 MSN: adrianomd at hotmail.com Claves gpg / pgp en hkp://subkeys.pgp.net From ed-no at spam-eepatents.com Thu Apr 8 20:37:04 2004 From: ed-no at spam-eepatents.com (Ed Suominen) Date: Thu, 08 Apr 2004 17:37:04 -0700 Subject: maximum length of a list & tuple References: Message-ID: I think the limit is 1000 recursion levels, but you shouldn't need to ever get anywhere near that. Use generators to break up the iteration of your list comparisons. -Ed Suominen Lupe wrote: > hi, > > I'm finishing a small program which uses recursion for less than 100 > levels. > > Each time the function is called, it compares an element of a list (which > is a list too) to other elements, which all amounts to millions of > comparisons. > > The program is working for short lists but not for longer ones. I think > there are two possible problems: either disk space is not enough to save > lists as the program is executed or there is a finite manageable list > lenght that is reached by the program. > > hence my question: > > is there a limit? which one? I'm using list.append() > what about for tuples? > > I'll rewrite that part of the code and will overcome the problem, since I > only need a few elements of the list generated, but I'm still curious > about the answers > > Thanks in advanve > > Lupe From griffph at aol.com Mon Apr 19 13:45:07 2004 From: griffph at aol.com (Griff) Date: 19 Apr 2004 10:45:07 -0700 Subject: Problems using modulo Message-ID: Mike, Thanks for this. I haven't used %r before, in fact it doesn't even seem to be mentioned in my "Python Essential Reference" book so I probably wouldn't have come across it for ages. I've since tried to run a similar piece of code on my 'C' compiler and pretty quickly discovered/remembered that C doesn't allow you to do modulo operations on floats full stop ... so I regard whatever Python gives us as a bonus! The quickest workaround I've found is to do ( round(t,5) % round(interval,5)) which seems to give the results I need. cheers - Griff From des at DouganConsulting.com Mon Apr 12 19:36:40 2004 From: des at DouganConsulting.com (Des Dougan) Date: Mon, 12 Apr 2004 16:36:40 -0700 Subject: Problems compiling on a Red Hat 7.3 based system In-Reply-To: <20040412143357.GO6139@unpythonic.net> References: <1081750846.2069.80.camel@p133.douganconsulting.com> <20040412143357.GO6139@unpythonic.net> Message-ID: <1081812999.2067.93.camel@p133.douganconsulting.com> On Mon, 2004-04-12 at 07:33, Jeff Epler wrote: > I have compiled Python 2.3.3 on a RedHat 7.2 machine, though I didn't > use an RPM. I'm not sure about the "/lib/cpp fails sanity check" > message, but maybe the second problem is due to a missing package. > I have a on my system: > $ rpm -qf /usr/include/linux/errno.h > kernel-headers-2.4.7-10 The package wasn't actually missing - but I did find two missing symlinks. Linking them: ln -s /usr/src/linux-2.4/include/linux /usr/include/linux ln -s /usr/src/linux-2.4/include/asm /usr/include/asm fixed the problem. Many thanks for your help. -- Des Dougan From mark at prothon.org Sun Apr 18 00:07:30 2004 From: mark at prothon.org (Mark Hahn) Date: Sat, 17 Apr 2004 21:07:30 -0700 Subject: CamelCase versus wide_names (Prothon) References: Message-ID: "Dan Bishop" wrote... > I'd prefer it if built-in types were uppercase too, so I wouldn't have > to remember not to use "list" and "file" as variable names. > Unforunately, that would break a lot of code. Then switch to Prothon :) That's the beauty of Prothon, getting to fix the mistakes. (I swore I'd never do that, but I just couldn't resist putting in a blatant ad. I won't do it again. Please resume your normally scheduled programming...). From newsgroups at jhrothjr.com Tue Apr 13 13:50:40 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Tue, 13 Apr 2004 13:50:40 -0400 Subject: Adding properties to objects References: <3a8e83d2.0404130906.2ea796e9@posting.google.com> Message-ID: <107oa56g7n3un1c@news.supernews.com> "Matthew Barnes" wrote in message news:3a8e83d2.0404130906.2ea796e9 at posting.google.com... > Is it possible to add properties to objects dynamically? > > I have an instance (x) of some new-style class (Foo), and I would like > to be able to do something like: > > >>> x = Foo() > >>> x.myproperty = property(getsomething, setsomething, delsomething); > >>> x.myproperty # invokes getsomething > >>> x.myproperty = 1 # invokes setsomething > >>> del x.myproperty # invokes delsomething > > However, when I evaluate x.myproperty I get back a property object > (which makes sense). I get the feeling I'm missing a step to "bind" > the property object to the class instance. > > Is this possible (it's Python... of course it's possible, right?), and > if so, how? The property definition only lives in a class; you cannot add a property to an instance by itself. Well, you can but it won't be evaluated as a property by the default __getattribute__() magic method. To make a property work on an instance basis you'd have to have a specialty __getattribute__() magic method in the class. That's left as an exercise for the reader. John Roth > > Matthew Barnes From raymond.hettinger at verizon.net Mon Apr 19 08:54:41 2004 From: raymond.hettinger at verizon.net (Raymond Hettinger) Date: Mon, 19 Apr 2004 08:54:41 -0400 Subject: PEP 329: Treating Builtins as Constants in the Standard Library Message-ID: <00cb01c4260d$80b9b120$e841fea9@oemcomputer> Comments are invited on a new pep: http://www.python.org/peps/pep-0329.html Based on feedback received so far, there were several changes to the original draft: * The module is public * The module name reflects its nature as a bytecode hack * There is a flag to disable binding * Added summaries of how it works, when it is called, and the effect on startup time (near zero). * Included a reference to Jython FAQs supporting the means for automatically doing nothing in environments without bytecodes. From deetsNOSPAM at web.de Tue Apr 13 08:06:19 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Tue, 13 Apr 2004 14:06:19 +0200 Subject: Reommended compiler toolkit References: Message-ID: Miki Tebeka wrote: > ply (which I like most) > SPARK > Yapps > PyLR > kwParsing > Plex > FlexModule > > Which one do you recommend? If you like ply - use it. I personally use spark, because its declarative nature and the early parsing method - but thats just a matter of taste. -- Regards, Diez B. Roggisch From junkmail at solumslekt.org Fri Apr 2 04:24:04 2004 From: junkmail at solumslekt.org (Leif B. Kristensen) Date: Fri, 02 Apr 2004 11:24:04 +0200 Subject: String concatenation References: <7xisgi24fm.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > "Leif B. Kristensen" writes: >> for i in range(5): >> tmp = res[i] >> if tmp[:1] != '-' and len(tmp) != 0: >> place = place + ', ' + (res[i]) >> return place[2:] > > tmp = [x for x in res if x and x[0] != '-'] > return ', '.join(tmp) Now I got it working, and it's really neat! It's almost incredible that you can do all this with just two lines of code. Thank you very much. regards, -- Leif Biberg Kristensen http://solumslekt.org/ Validare necesse est From google at lelandwoodbury.com Wed Apr 14 19:23:14 2004 From: google at lelandwoodbury.com (Leland Woodbury) Date: 14 Apr 2004 16:23:14 -0700 Subject: Python 2.2.x core dumping Message-ID: We have a stable Python app that's causing Python 2.2.1 and 2.2.3 (on Solaris) to core dump with segmention violation on certain new inputs. The core files have their stack trashed, so we don't have a lot to go on other than the obvious indication of a memory problem. We moved the app to Linux so we could run valgrind on it, that pretty much just told us that we're getting a stack overflow, which is a clue, but I'm not sure what to do with it. One obvious alternative is to upgrade to Python 2.3.3, but this has some local consequences that I'd rather avoid until I have some assurance that it will solve the problem. Anyone have any advice on next steps to track down the problem? Thanks for whatever you know. L From vardhman at students.iiit.net Wed Apr 7 11:48:21 2004 From: vardhman at students.iiit.net (Vardhman Jain) Date: Wed, 7 Apr 2004 21:18:21 +0530 (IST) Subject: query regarding embeding python in C In-Reply-To: Message-ID: Hi, No replies. I need it urgently please help!!!! Vardhman On Wed, 7 Apr 2004, Vardhman Jain wrote: > Date: Wed, 7 Apr 2004 14:36:32 +0530 (IST) > From: Vardhman Jain > To: python-list at python.org > Subject: query regarding embeding python in C > > Hi, > I am trying out the concept of python code being executed from a C > program. I got a peice of code from the tutorial but I don't know how to > compile/use it > > The code is > #include > > int > main(int argc, char *argv[]) > { > Py_Initialize(); > PyRun_SimpleString("from time import time,ctime\n" > "print 'Today is',ctime(time())\n"); > Py_Finalize(); > return 0; > } > ~ > ~ > > > Now If I do "c++ temp.c -I /usr/include/python2.2/" I get the errors > [vardhman at linuxAddict TA]$ c++ temp.c -I /usr/include/python2.2/ > /tmp/ccnpr9em.o(.text+0x11): In function `main': > : undefined reference to `Py_Initialize' > /tmp/ccnpr9em.o(.text+0x1e): In function `main': > : undefined reference to `PyRun_SimpleString' > /tmp/ccnpr9em.o(.text+0x26): In function `main': > : undefined reference to `Py_Finalize' > collect2: ld returned 1 exit status > > Can some one tell me how to compile and use this code. > > > Vardhman > > > -- > Vardhman Jain > III Year B.Tech. CSE > IIIT-Hyderabad > Address: > Room No 27, NBH, IIIT-Hyderabad,Hyderabad 500019 > > presence on net: > http://students.iiit.net/~vardhman > > > > -- Vardhman Jain III Year B.Tech. CSE IIIT-Hyderabad Address: Room No 27, NBH, IIIT-Hyderabad,Hyderabad 500019 presence on net: http://students.iiit.net/~vardhman From k.robert at gmx.de Tue Apr 13 04:29:33 2004 From: k.robert at gmx.de (Robert) Date: 13 Apr 2004 01:29:33 -0700 Subject: How to read & write standard password encrypted ZIP files? References: <19804fd8.0404120411.3497925d@posting.google.com> Message-ID: <19804fd8.0404130029.7b33d6f3@posting.google.com> > > Is it possible to write & read standard password encrypted ZIP files > > easily (using zipfile.ZipFile?) > > It may be supported via some undocumented method. > any more information on that? > One thing you should be aware of, is that ZIP files have a known > cryptographic attack for >= 3 files encrypted with the same password in > a zip file. When there are more than 3 files in a zip file, all > encrypted with the same password, only 15 bits of the password is > required to decrypt the archive, then (I believe) recover the original > password. > > Generally, you would be better off using Python to create the original > archive (without encryption), then use some encryption method to secure > it. I hear that mxCrypto is a very spiffy library for Python cryptography. > is there a secure encrypted format, that could be read also by common tools like WinZIP, WinRAR ? Robert From dwelch91 at comcast.net Sun Apr 4 18:16:38 2004 From: dwelch91 at comcast.net (djw) Date: Sun, 04 Apr 2004 22:16:38 GMT Subject: splitting a long token across lines In-Reply-To: References: Message-ID: djw wrote: > Nakamura wrote: > >> Hi all, >> >> Say, I have a very long integer constant , how can >> I split across lines ? >> I tried something like >> MODULUS = 7567567567567567567567567567567\ >> 7567507546546986094860986094860\ >> 2345646986598695869548498698989\ >> ... >> but it doesn't compile. >> Is there another way to write a long numeric constant besides writing >> it as a string and then converting to long? I also wouldn't like to put >> it all on one very long line. >> >> Thanks! > > > Well, I _suppose_ you could do this: > > > MODULUS = "7567567567567567567567567567567"\ > 7567507546546986094860986094860"\ > 2345646986598695869548498698989"\ > ... > > MODULUS = int(MODULUS) > > I'm sure I'm going to have to take some flak for this, though. I > wouldn't do it. What's wrong with really long lines? Anything you do > that I can see is going to obscure your code. > > -D Oops, I forgot some quotation marks there, but you get the idea. -D From af at faino.org Mon Apr 12 06:09:54 2004 From: af at faino.org (Andrea Fino) Date: Mon, 12 Apr 2004 12:09:54 +0200 Subject: embedding python Message-ID: Hi, I am studying how to get a python 2.3 interpreter running in a small embedded system ie. 8MB flash ans 32MB ram, after some search with google on thiw newgroup looks like others already did this kind of stuff, Could I have some hints how to proceed, and/or url to read about it? there is any doc? Thanks, Andrea -- Andrea Fino 8-) - "Sistemi su misura di qualita' industriale" "Handcrafted systems with industrial quality" [Phone: +39 071 2070104]+[Fax: +39 071 2077919]+[iaxtel:17002876594] [Web: http://www.faino.org]+[Email: af at faino.org] -----BEGIN GEEK CODE BLOCK----- Version: 3.1 GCS: d- s: a+ C+++ UL++++ P++ L++++ E--- W++ N++ o? K w--- O M V PS++ PE+ Y+ PGP t+ 5? X-- R* tv- b-- DI+++ D G++ e* h r y+ ------END GEEK CODE BLOCK------ From me at privacy.net Fri Apr 2 21:35:18 2004 From: me at privacy.net (Heather Coppersmith) Date: 02 Apr 2004 21:35:18 -0500 Subject: Why '==' ?? (now veering OT) References: <8089854e.0403300510.1971c24@posting.google.com> <1080653301.114229@master.nyc.kbcfp.com> Message-ID: On Fri, 02 Apr 2004 17:14:23 -0800, Tim Roberts wrote: > LISP uses -- well, no one really knows what the actual syntax is > for LISP. The syntax is simple: (equality-operator comparand-1 comparand-2) There are, howver, several equality-operators; some are more equal than others. HTH, Heather -- Heather Coppersmith That's not right; that's not even wrong. -- Wolfgang Pauli From des at DouganConsulting.com Mon Apr 12 02:20:48 2004 From: des at DouganConsulting.com (Des Dougan) Date: Sun, 11 Apr 2004 23:20:48 -0700 Subject: Problems compiling on a Red Hat 7.3 based system Message-ID: <1081750846.2069.80.camel@p133.douganconsulting.com> I'm very interested in using Plone; consequently, I downloaded the source RPM for Python 2.3.3 and ran the rpm --rebuild process. The compilation failed with: checking for suffix of executables... checking for suffix of object files... o checking whether we are using the GNU C compiler... yes checking whether gcc accepts -g... yes checking for gcc option to accept ANSI C... none needed checking how to run the C preprocessor... /lib/cpp configure: error: C preprocessor "/lib/cpp" fails sanity check See `config.log' for more details. error: Bad exit status from /var/tmp/rpm-tmp.44328 (%build) RPM build errors: Bad exit status from /var/tmp/rpm-tmp.44328 (%build) I therefore thought I'd try 2.2.3; however, this also failed: checking for build directories... done updating cache ./config.cache creating ./config.status creating Makefile.pre creating Modules/Setup.config creating pyconfig.h creating Setup creating Setup.local creating Makefile + make gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONFIG_H -o Modules/python.o Modules/python.c In file included from /usr/include/errno.h:36, from Include/Python.h:48, from Modules/python.c:3: /usr/include/bits/errno.h:25:26: linux/errno.h: No such file or directory make: *** [Modules/python.o] Error 1 error: Bad exit status from /var/tmp/rpm-tmp.72880 (%build) RPM build errors: Bad exit status from /var/tmp/rpm-tmp.72880 (%build) My server runs Mitel SME Server v6.0, which is a Red Hat 7.3 derivative. The kernel, and kernel sources, are version 2.4.18-5, and the current python 2 version is python2-2.2.2-11.7.3. Am I out of luck on this platform, or is there a straightforward way to have either of these versions compile cleanly (for example, I'm running glibc 2.2.5, and I'd rather not try to upgrade to 2.3.x)? Thanks for any help you can provide. -- Des Dougan From gnosticray at aol.com Fri Apr 16 03:46:18 2004 From: gnosticray at aol.com (A B Carter) Date: 16 Apr 2004 00:46:18 -0700 Subject: Difficulty Finding Python Developers References: <65cbc3dd.0404140641.3501fde8@posting.google.com> <65cbc3dd.0404141018.36d9d4ce@posting.google.com> Message-ID: Peter Hansen wrote in message news:... > A B Carter wrote: > > 2 - Start setting expectations with management. For example, explain > > that if there are not a lot of Python programmers it's because it's a > > new language that > > it builds on the strengths of langauges such as C++, Java and perl > > while avoiding their weaknesses. > > If I were his management, here I might say, "But I thought you > said Python was older than Java! If it's so good, why hasn't it > caught on more than Java?" or "How can it build on the strengths > of Java when it's older?" > First let me express embarrassment that I had no idea Python was as old as it was. No doubt I'm biased by the fact that I've only begun to use Python seriously this year. But damn, I still want to say that it just seems really new and that yes, it builds on the strengths of languages such as Java and Perl while avoiding their weaknesses. So this changes the story you have to tell but certainly not the reason your telling the story, which is to explain the lack of Python programmers in a way that reveals a strength rather than a weakness. You could talk about how Python was originally developed by a single programmer for an in-house project which should have vanished in obscurity except that it was so well designed that a kind of grass roots campaign has made it the second most popular scripting language in use. Think Guido=Linus and Python=Linux and so long as management has read "Business Week", they'll be listening. > > Mention that when you do find a > > Python programmer he'll probably be better than your average perl or > > Java programmer. > > And here I would ask, "Why do you say that? If there are so > few of them around, how could anyone know whether they're better > or worse? And wouldn't the best programmers be using the most > popular languages, because they would make more money that way?" > > > Make the argument that you get what you pay for, and > > the extra expense of Python is worth it. > OK, this was contentious even for comp.lang.python. To this group I can sum up the argument by saying the "Learn Python in 21 Days" and "Python for Dummies" books are much better written than the ones for Java and other languages. What you can tell management is that Python is not an over-hyped language like Java (and yes if the manager was once a Java developer then mention .NET instead) and that Python programmers are people who really love the field and discovered Python because of their dissatisfaction with other languages. If management is willing to do a bit of reading have them read Eric Raymond's essay on why he switched from Perl to Python. > "I thought you said Python was free... now you're telling me it's > going to cost us more than the other languages because it's so hard > to hire anyone who knows it?" > Sorry, but this I don't buy. If management thought they were getting something for free then both parties are at fault. The choice of any language is a matter of balancing trade-offs and management should have been informed of both the benefits and the risks; and if management didn't ask about the risks then they just weren't doing their job. > > 3 - With 2 out of the way consider rethinking how this three month > > project should be done. If Python talent is scarce then it might make > > more sense to develop in-house talent. This may no longer be a three > > month project but down the road your in a more solid position, which > > ,if you think about it, is a basic part of what Python is all about. > > Good advice here, IMHO. :-) This is what we did when first considering > Python, by the way, and I had a co-op student learn the langauge and > develop a GPIB interface with a wrapper around a DLL using "calldll". > It took him about a week to learn Python, about a week to get a basic > calldll wrapper working, about a week to implement a simple RF test > for one of the devices the company made (controlling two signal > generators and a spectrum analyzer) and about a week to figure out how > to slap a simple GUI on it using Tkinter. > Thank you, but if you accept point 3 then something along the lines of point 2 is an absolute must because you've gone from asking money to pay for three months of consulting to hiring a full-time programmer. Strictly in terms of dollars spent that is, by my accounting, roughly five times more expensive. You got some explaining to do. Regards, A B From aahz at pythoncraft.com Mon Apr 12 22:18:10 2004 From: aahz at pythoncraft.com (Aahz) Date: 12 Apr 2004 22:18:10 -0400 Subject: why is python better than eg. smalltalk?? no one has any solid arguments! you should all go to church with all that religious talk! References: <2004041209261081776382@k2.sage.att.com> Message-ID: In article <2004041209261081776382 at k2.sage.att.com>, Garry Hodgson wrote: >aahz at pythoncraft.com (Aahz) wrote: >> >> I found my editor fifteen years ago. Guess which it is. > >i wrote my editor 15 years ago. still use it everyday. it's small, >fast, minimalist, and does exactly what i want. i occasionally flirt >with more powerful things, but always end up back with fred. That's a good answer, but fred won't be available on random computer systems. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Why is this newsgroup different from all other newsgroups? From __peter__ at web.de Wed Apr 14 05:05:26 2004 From: __peter__ at web.de (Peter Otten) Date: Wed, 14 Apr 2004 11:05:26 +0200 Subject: Deleting objects with method reference References: Message-ID: Martin wrote: > I can't delete this object after I call the Set() function. > > Why is this so special, and are there any way around it besides removing > the ref ? > > class B: > def __del__(self): > print "del" > def F(self): > print "f" > def Set(self): > self.v = self.F > > > o1 = B() > o1.Set() > del o1 > > > o2 = B() > o2.Set() > o2.v = None > del o2 >>>> "del" self.F consists of a function and an instance reference, so you are introducing a cycle with o1 referring self.F and self.F referring to o1. Cycles can only be garbage-collected if the objects involved do not have a __del__() method. In your example o1 would be collected if you weren't looking, i. e. B wouldn't attempt to trace the deletion with __del__(). See http://www.python.org/doc/current/lib/module-gc.html, especially the "garbage" section for details. You can verify this with a weakref.ref object with an appropriate callback: import weakref def ondel(o): print "del" class B: def F(self): print "f" def Set(self): self.v = self.F o1 = B() o1.Set() w = weakref.ref(o1, ondel) del o1 Peter From peter at engcorp.com Thu Apr 15 11:32:29 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 15 Apr 2004 11:32:29 -0400 Subject: CamelCase versus wide_names (Prothon) In-Reply-To: References: Message-ID: Mark Hahn wrote: > We have agreed in Prothon that unlike Python we are going to be 100% > consistant in our var and method naming. We will not have run-together > words like iteritems, we are going to always have seperated words like > has_key. > > Now we are in the midst of a discussion of camelCase versus wide_names. So > far our arguments are: > > 1) CamelCase is more elegant, modern, more readable, and more efficient in > character usage. > > 2) Wide_names is cleaner, more readable, compatible with C, which is the > standard module language for Python and Prothon. Wide_names is also the > Python standard. > > Of course in the Python world you alread have wide_names as your standard, > but could you for the moment pretend you were picking your standard from > scratch (as we are doing in the Prothon world) and give your vote for which > you'd prefer? camelCase, provided acronyms (if any) are treated as words and capitalized appropriate. For example, updateGui() is preferred to updateGUI() (or update_GUI or update_gui). IBM did it right with the OS/2 API (at some point, finally). Of course, someone once said that a foolish consistency is the hobgoblin of little minds... -Peter From vincent at visualtrans.de Wed Apr 28 13:53:57 2004 From: vincent at visualtrans.de (vincent wehren) Date: Wed, 28 Apr 2004 19:53:57 +0200 Subject: String formatting (%) In-Reply-To: References: Message-ID: Pascal wrote: > Hello, > I've a float number 123456789.01 and, I'de like to format it like this > "123 456 789.01". > Is this possible with % character? The following should do what you want, although the commafy_float I quickly added is probably a little naive: def commafy(numstring, thousep=","): """ Commafy the given numeric string numstring By default the thousands separator is a comma """ numlist = list(numstring) numlist.reverse() tmp = [] for i in range(0, len(numlist), 3): tmp.append("".join(numlist[i:i+3])) numlist = thousep.join(tmp) numlist = list(numlist) numlist.reverse() return "".join(numlist) def commafy_float(flStr, thousep=","): whole, dec = flStr.split(".") return ".".join([commafy(whole, thousep=thousep) , dec]) if __name__ == "__main__": units = "56746781250450" unitsWithThouSeps = commafy(units) print unitsWithThouSeps aFloatAsString = "1128058.23" aFloatAsStringWithThouSeps = commafy_float(aFloatAsString ,thousep=" ") print aFloatAsStringWithThouSeps Regards -- Vincent Wehren From stewart at midwinter.ca Tue Apr 13 22:17:52 2004 From: stewart at midwinter.ca (Stewart Midwinter) Date: 13 Apr 2004 19:17:52 -0700 Subject: Simple pyhon-based CMS Message-ID: <9396ba6f.0404131817.1219c695@posting.google.com> I'm looking for a simple python-based CMS (content management system), maybe with some blog-like features, ability to add articles - nothing too fancy. Do you have any suggestions? I've looked at Zope / Plone: very easy to install using the rpm I found. But it's obviously quite complex and powerful, which is no doubt of benefit on a site that has many users. But I'm just one person. All I want is a pythonic replacement for my current tool, postNuke. I looked at NewzBruiser: this would probably be simple enough, maybe even too simple, but it requires that I enable SSI support on Apache, something I seem to be unable to accomplish (I run SME server from contribs.org and it uses a byzantine templating system for its configuring, which leaves me in the dark on how to modify httpd.conf there). Any other ideas? thanks Stewart in Calgary From rschroev_nospam_ml at fastmail.fm Tue Apr 20 03:21:51 2004 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Tue, 20 Apr 2004 07:21:51 GMT Subject: Dollar sign ($) on foriegn keyboards? (prothon) In-Reply-To: References: Message-ID: Mark Hahn wrote: > Can people from outside the U.S. tell me if typing the dollar sign often > would be a problem in writing code? Is it available and somewhat easy to > type on international keyboards? Belgian azerty: no problem. Easier to type, in fact, than several other symbols that are frequently used while programming, e.g. []{}_. -- "Codito ergo sum" Roel Schroeven From benjamin.golinvaux at euresys.com Sun Apr 11 09:21:22 2004 From: benjamin.golinvaux at euresys.com (Benjamin Golinvaux) Date: 11 Apr 2004 06:21:22 -0700 Subject: building Python extensions with XCode Message-ID: Dear list members, I am experienced at building and debugging Python extension DLLs under Windows, but I would like to do the same using my Mac. I would like to know how i can create a library that is recognized as as Python extension. I know i could use distutils with a setup.py file, but i would like to exactly understand what's going on wrt compiler flags, etc.... Also, i would like to be able to debug my extension using XCode. I know that, under Windows, one needs to use a debug build of Python to run debug extensions, and that the _d suffix needs to be appended to the extension name for it to be loaded by python_d. Is it specific to Window or is it the same under Mac OS X as well ? Thanks so much for your help. I've googled quite hard for this answer but couldn't find a simple tutorial. Best Benjamin Golinvaux From rtw at freenet.REMOVE.co.uk Tue Apr 6 09:23:45 2004 From: rtw at freenet.REMOVE.co.uk (Rob Williscroft) Date: 06 Apr 2004 13:23:45 GMT Subject: How to do [1]*4 for a tuple References: Message-ID: Vineet Jain wrote in news:mailman.375.1081213535.20120.python- list at python.org: > I'm not sure I understand why [1]*4 and (1)*4 work differently? [1]*4 > results in [1, 1, 1, 1] while (1)*4 results in 4. There are times when > I have to do the following: > >>> (1,) * 4 (1, 1, 1, 1) >>> > '%s some value %s and some other text %s' % (a)*3 > >>> a = "" >>> '%s some value %s and some other text %s' % ((a,)*3) ' some value and some other text ' > as apposed to > > '%s some value %s and some other text %s' % (a, a, a) > > In this case I always end up doing > > '%s some value %s and some other text %s' % [a]*3 > tuples are comma seperated items, parenthesis just bracket: >>> b = 1, 3 >>> b (1, 3) >>> type( b ) >>> c = 1, >>> c (1,) >>> type( c ) >>> Rob. -- http://www.victim-prime.dsl.pipex.com/ From marklists at mceahern.com Thu Apr 29 22:44:33 2004 From: marklists at mceahern.com (Mark McEahern) Date: Thu, 29 Apr 2004 21:44:33 -0500 Subject: Why cannot jump out the loop? In-Reply-To: <16529.47951.692940.903411@montanaro.dyndns.org> References: <16529.47951.692940.903411@montanaro.dyndns.org> Message-ID: <4091BD91.4050100@mceahern.com> Sorry for top-posting: I just wanted to add that in the OP's case, what he really needs is for not while. import sys n = int(sys.argv[1]) for i in range(n): print locals() // m p.s. Others have already noted that sys.argv returns a sequence of strings. > Jinming> I have a very simple python program, which includes a while > Jinming> loop. But to my surprise, it cannot jump out the while > Jinming> loop. Does anyone know why? > > Jinming> Here is the program: > Jinming> ___________________________ > Jinming> #!/usr/bin/env python > Jinming> import sys > Jinming> n=sys.argv[1] > Jinming> i=0 > Jinming> while i Jinming> print "i=",i," n=",n > Jinming> i+=1 > Jinming> ----------------------------------------------------- > From jack at performancedrivers.com Fri Apr 9 15:22:44 2004 From: jack at performancedrivers.com (Jack Diederich) Date: Fri, 9 Apr 2004 15:22:44 -0400 Subject: module not callable - why not? In-Reply-To: <107dras2heahcb6@news.supernews.com> References: <107dras2heahcb6@news.supernews.com> Message-ID: <20040409192244.GA13415@performancedrivers.com> On Fri, Apr 09, 2004 at 02:35:33PM -0400, John Roth wrote: > > "Diez B. Roggisch" wrote in message > news:c56jph$rrk$05$1 at news.t-online.com... > > Now usually I'd create a file called "quaternion.py", define my quaternion > > class in there and then import and create an instance like this: > > > > import quaternion > > > > q = quaternion.quaternion() > > > > Thats a lot to type. doing a > > > > from quaternion import quaternion > > > > would solve that - but AFAIK thats considered bad for some reasons. > > I don't know why that's bad. Its fairly common in fact. > What's usually bad is "from foobar import *" which loads > your module namespace with a bunch of identifiers that > are not documented in the source of that module, and that > may change if the imported module changes. > > In fact, I'd probably do: "from quaternion import quaternion as q" > to minimize typing later. > Naming style and imports came up on python-dev recently. There were some good suggestions to make life easier: - Don't name the module and a class in it the same thing import Queue # Queue is a module from Queue import Queue # Queue is a class .. 50 lines later ... ob = Queue() # do I want to do this? ob = Queue.Queue() # or this? - Do name modules more generically than the first class you put in them. from your example a good name may be 'quatmath' because there will also be some methods to manipulate Quaternion instances in there too. import quatmath q1 = quatmath.Quaternion(a, bi, ck, dk) q2 = quatmath.Quaternion(a*2, bi, ck, dk*2) result = quatmath.concat(q1, q2) As a personal preference I'd avoid overriding __add__ __mult__ and other operators in the Quaternion class. It is easy to forget what 'q1 * q2' is doing but hard to miss 'quatmath.product(q1, q2)'. -jackdied From fnord at u.washington.edu Wed Apr 14 17:27:00 2004 From: fnord at u.washington.edu (Lonnie Princehouse) Date: 14 Apr 2004 14:27:00 -0700 Subject: A solution to distutils' habit of installing data_files inconsistantly Message-ID: I've just spent an hour or so being frustrated at the way distutils installs data files, and a quick search of c.l.py shows that I'm not the first. For posterity, here's an easy (albeit limited) solution. The Problem: Distutils installs data files by default in sys.prefix or sys.exec_prefix, and the installation location is not always consistant between Win32 and Unix. This means that you have to duplicate distutils' logic in order to find out where your package's data files got installed :( What you really want is to have your data files in the same place as your Python code, so that you can find them easily. The Solution: More complicated packages like PyXML and OpenGLContext address this by subclassing distutils.command.install_data and/or distutils.command.install, and then using the cmdclass argument to setup() to override distutils' built in command handlers. This is overkill if you only have a few data files and you just want them to go into the same directories as your Python code. Here's an easier way. Do this before you call setup(): from distutils.command.install import INSTALL_SCHEMES for scheme in INSTALL_SCHEMES.values(): scheme['data'] = scheme['purelib'] Alternately, that should read 'platlib' instead of 'purelib' if your data files are platform specific. This sets the default data directory to the default pure python directory, lib/site-packages in most cases. -ljp From grante at visi.com Wed Apr 28 11:24:35 2004 From: grante at visi.com (Grant Edwards) Date: 28 Apr 2004 15:24:35 GMT Subject: Path ... where is my application's home dir? References: <408fbc0a$0$17256$a1866201@newsreader.visi.com> Message-ID: <408fccb3$0$17264$a1866201@newsreader.visi.com> On 2004-04-28, Marco Aschwanden wrote: > - I want to store the current state of the application when leaving the > application in an ini-file. > - It is a "single-user" pc! > - It is Windows. I could tell you the right thing to do under Unix. In Windows, I'm lost. I sort of assumed you were writing for a Unix system, since your question is asked constantly in various newsgroups and it's almost always being asked by a Win32 programmer working on his first Unix application. -- Grant Edwards grante Yow! I just had a MAJOR at CONTRACT DISPUTE with visi.com SUZANNE SOMERS!! From fumanchu at amor.org Sat Apr 3 15:30:38 2004 From: fumanchu at amor.org (Robert Brewer) Date: Sat, 3 Apr 2004 12:30:38 -0800 Subject: Python is faster than C Message-ID: Armin Rigo wrote: > This is a rant against the optimization trend of the Python > interpreter. > ...Iterators, for example, are great in limited cases > but I consider their introduction a significant complication in the > language; before, you could expect that some function from which you > would expect a sequence returned a list. Python was all lists and > dicts, with dicts used as namespaces here and there. > > >>> enumerate([6,7,8,9]) # uh ? > > > enumerate() should return a normal list, and > it should be someone else's job to ensure that it is > correctly optimized > away if possible (and I'm not even talking about Psyco, it > could be done > in the current Python implementation with a reasonable amount of > effort). I'd like to think I'm not understanding your point, but you made it so danged *clear*. Enumerate should absolutely *not* return a normal list. The use case I think you're missing is when I do not want the enumeration optimized at all; I want it performed on-the-fly on purpose: for i, line in enumerate(file('40GB.csv')): if i % 600000: do_special() else: do_normal() Forcing enumerate to return a list would drag not only the entire 40GB.csv into memory, but also the entire set of i. Using an iterator in this case instead of a list *is* the optimization. > I know you can always do list(_). My point is that this is a > user-visible optimization. Iterators are not lists and shouldn't be confused/substituted with them. The use cases are by no means limited; I have thousands of lines of code which use iterators, not lists, precisely for their differences. If you want a list instead of an iterator, this _should be_ user-visible. Robert Brewer MIS Amor Ministries fumanchu at amor.org From ravi_b_m at yahoo.com Thu Apr 8 11:01:26 2004 From: ravi_b_m at yahoo.com (Ravi) Date: 8 Apr 2004 08:01:26 -0700 Subject: Python thread problem Message-ID: <117cce06.0404080701.2ed5ca1b@posting.google.com> Hi all, I am running a python cgi which inturn calls a python thread. This python thread executes some commands and sends an email to the admin. I am facing a strange problem, in the cgi script when I set the python thread to run as Daemon, then it does not send the email, but when I donot set the thread as daemon, it does send the email. Can somebody help me as to this behaviour ? I am running the cgi and python scripts on linux. The only problem I can see is that the email module is present in python2.3 and I have python 2.3 installed at /usr/local/lib/python2.3 and also have python1.5 installed at /usr/lib/python1.5. Is this the problem for such behaviour? Is there a way to fix ? Could somebody help me out please? Thank you in advance. Ravi. From mcfletch at rogers.com Mon Apr 26 22:00:50 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Mon, 26 Apr 2004 22:00:50 -0400 Subject: What is good about Prothon? In-Reply-To: References: Message-ID: <408DBED2.3010600@rogers.com> David MacQuigg wrote: ... >All methods look like functions (which students already understand). > > I think it might be more proper to say that you've made all functions methods with an implicitly defined target, but I suppose the statement is still technically true. >Benefits of Proposed Syntax >=========================== >-- Unification of all function forms ( bound, unbound, static, class, >lambda ). All will have the same form as a normal function >definition. This will make it easier to teach OOP. Students will >already understand functions and modules. OOP is a small step up. A >prototype will look just like a module ( except for the instance >variables ). See Parallels between Prototypes and Modules below. > > This is nice. Not "I'm going to rush out to adopt a language because of it" nice, but nice enough. I'm curious about one thing: proto x( object ): flog :( x, y ): .x = x a = x() b = x() a.flog = b.flog a.flog() print b.x In other words, how do I hold a reference to a bound method/function if there are no such things and only the "last access" determines what the implicit target is? Just to be clear, I'm assuming you're going to have storage *somewhere* so that: a = module.do a() works. >-- Using an explicit __self__ variable avoids the magic first >argument, and makes it easier to explain instance variables. See the >sections below comparing a brief explanation of instance variables in >Python vs the simplified form. A full presentation of OOP, like pages >295-390 in Learning Python, 2nd ed. will likely be 1/2 the number of >pages. Not only is the basic presentation simpler, but we can >eliminate a lot of discussion of lambda functions, static methods, >etc. > > This is a wash IMO, with the explicit "self" having a slight edge on "Explicit is better than Implicit" grounds. You now have to explain where the magic __self__ comes from instead of how self is bound when you access the instance's method. They're both magic, the Python stuff is just explicitly visible. Still, since you're coding it deep into this new language, it'll be first nature to the Whateverthon programmer. On a personal note, the moment where I "got" the concept of methods (Python was my first OO language) was seeing "self" in the argument list of a function and realising that it's just a parameter curried into the function by doing x.method lookup. That is, it just looked like any other function, the parameter was just a parameter, nothing special, nothing requiring any extra knowledge save how it got bound (and that's pretty darn simple). Coming from a structures+functions background it made complete sense. >-- All attributes of a prototype ( both data and functions ) will be >in a neat column, making it easier to find a particular attribute when >visually scanning a program. Understanding the structure of a program >will be almost as quick as seeing a UML diagram. > > Can't say I find it particularly compelling as an argument, not if introducing punctuation-itis is the cost, anyway. Most people I know use syntax colouring editors, after all. >-- Lambda keyword will be gone. An anonymous function using normal >function syntax can be extremely compact. ( :x,y:x+y ) > > That particular example almost screams "don't do this", doesn't it? :(x,y): x+y I can see as an improvement, but yawn, really. Making function definitions expressions rather than statements would have the same effect. By the way, how do you know when your lambda is finished? I gather the ()s are required if using as an expression? >-- Method definitions will be less cluttered and less typing with >__self__ as a hidden variable. > > I personally prefer explicit to implicit, but I know there's lots of people who are big into saving a few keystrokes. >-- Changing numerous attributes of an instance will be more >convenient. ( need use case ) > > That's nice, but honestly, if you're doing a lot of this in cases trivial enough to warrant the addition you should likely be refactoring with a domain-modelling system anyway. Still, if you modify the with to work something like this: with x: .this = 32 .that = 43 temp = 'this'*repeat .something = temp[:55] i.e. to just alter the implicit target of the block, not force all variables to be assigned to the object, it seems a nice enough feature. >Pro2: Replace lambdas with standard function syntax. > >Con2: ??? > > Fine, but no need to redefine the spelling for that save to make the definition itself an expression that returns the function as a value and allows one to drop the name. i.e. a = def ( y,z ): y+z would work just as well if you could assign the result to a variable and figured out how you wanted to handle the indentation-continuation thing to know when the function ended. >Explicit __self__ > >Pro1: Allows the unification of methods and functions. > >Con1: ??? > > Is hidden (implicit) magic that requires the user to learn rules as to what the target is when treating functions/methods as first-class objects. Not a big deal, really. >Pro2: Explanation of instance variables is simpler. > >Con2: Using __self__ instead of a special first argument is less >explicit. > > Um, can't say I see this as a huge pedagogical win. A function either takes an argument self and can set attributes of the object, or a function has access to a magical "global" __self__ on which it can set attributes. I'll agree that it's nice having the same concept for module and class variables, but seeing that as a huge win assumes, I think, that those being taught are coming from a "globals and functions" background rather than a structures and functions background. One type is accustomed to altering their execution environment, the other to altering solely those things which are passed into the function as parameters. >Pro3: Less typing and less clutter in method definitions. > >Con3: Can use "s" or "_" instead of "self" to minimize typing and >clutter. > > That's a counter, not a con. Similarly "Explicit is better than Implicit" is only a counter, not a con. A con would be: "presence of variable of implicit origin" or "too much punctuation". Don't think either is a huge concern. >"Assignment" Syntax for Function Definitions > >Pro1: See all the variables at a glance in one column. > >Con1: ??? > > Doesn't seem a particularly strong pro. IOW seems pretty minimal in benefit. As for a con, the eye, particularly in a syntax-colouring editor picks out keywords very well, while punctuation tends to blur into other punctuation. >Pro2: Emphasize the similarity between data and functions as >attributes of an object. > >Con2: ??? > > I see the pro, seems approx. the same to me. >With Block > >Pro: Saves typing the object name on each line. > >Con: Making it too easy to modify prototypes after they have been >created will lead to more undisciplined programming. > > As specified, makes it only useful for trivial assignments. If you're going to all the trouble of introducing .x notation to save keystrokes, why not simply have with alter __self__ for the block so you can still distinguish between temporary and instance variables? In the final analysis, this really seems like about 3 separate proposals: * I like the .x notation's universal applicability, it does seem simple and elegant from a certain point of view o I don't like the implicit __self__, but that's an integral part of the proposal, so a wash o I'd want clarification of how to store a reference to another object's (bound) method (which is *extremely* common in Python code for storing, e.g. callbacks) * I really dislike the :( ): function definition notation, "Readability Counts". Why clutter the proposal with that? * I'm neutral on the with: stuff, I'd much prefer a real block mechanism similar to Ruby with (if we're using implicit targets), the ability to specify the .x target for the block So, the .x notation seems like it would be nice enough, but nothing else really makes me jump up and down for it... That said, I'd probably be willing to use a language that was running on the PythonVM with a parser/compiler that supported the syntax. I'd be totally uninterested in automated translation of Python code to the new form. That's the kind of thing that can be handled by running on the same VM just as easily as anything else and you then avoid lots of migration headaches. So, just as a marketing data-point; I'm not convinced that this is markedly superior, but I'd be willing to try a language that differed from Python in just the .x aspects to see whether it was worthwhile. Have fun, Mike _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From google at evpopov.com Wed Apr 14 04:17:34 2004 From: google at evpopov.com (popov) Date: 14 Apr 2004 01:17:34 -0700 Subject: 3D Graphics Engine References: <8089854e.0404130639.3eb0db62@posting.google.com> Message-ID: <7eecf173.0404140017.6d7b06a4@posting.google.com> > Can anyone reccomend a 3d engine for me to 'muck around with'. You can have a look to Ogre: www.ogre3d.org. Python bindings may not be up to date, but they should be at the first official release (which should now happen in a not so far future). From fumanchu at amor.org Tue Apr 27 11:18:35 2004 From: fumanchu at amor.org (Robert Brewer) Date: Tue, 27 Apr 2004 08:18:35 -0700 Subject: Is Perl *that* good? Message-ID: [Roger Binns] > To solve the same problems, Netscape invented yet another language and > put "marketing flavour of the day" in front, blessing us with Javascript. > I really wish Tcl had won that one. [Paul Prescod] > I wish Python had won. ;) I wish Python had won, as well. But time is linear (in my mind). I now wish only that we could leverage the similarity of JS and Python (execution and binding models) into more Python users. Marketing needs to run with the line, "So you know Javascript? Then you know Python!" Is anyone using AXScript extensively? Robert Brewer MIS Amor Ministries fumanchu at amor.org From tuure at laurinolli.net Mon Apr 5 18:17:14 2004 From: tuure at laurinolli.net (Tuure Laurinolli) Date: Tue, 06 Apr 2004 01:17:14 +0300 Subject: Session variables? In-Reply-To: <4070bad0$1@clarion.carno.net.au> References: <4070bad0$1@clarion.carno.net.au> Message-ID: Steve wrote: > Hi, > > I'm trying to find a clean way of sharing variables across different > python webpages and scripts and I need something like a session variable > for each user. Is this possible in Python? I've been "pickling" stuff > and this doesn't work at all with mutliple users as things get mixed up. > Is there any clean way of doing this? Thanks, The session module in jonpy package seems to be a nice base for sessions, though it lacks some features like explicitly deleting a session. From mark at prothon.org Thu Apr 15 19:35:44 2004 From: mark at prothon.org (Mark Hahn) Date: Thu, 15 Apr 2004 16:35:44 -0700 Subject: CamelCase versus wide_names (Prothon) References: Message-ID: Fran?ois Pinard wrote: > Both cannot be "more readable" simultaneously! :-) I was wondering if anyone would catch that :) You win the prize! I was giving each argument from the perspective of the one who wants that choice. P.S. Has anyone noticed that I have finally taught myself how to not top-post? I have been practicing the last few weeks on the Prothon list. I has NOT been easy to un-teach 30 years of email posting method. I hope the people that black-holed me can forgive me now and let me back in. From mcherm at mcherm.com Fri Apr 16 13:55:48 2004 From: mcherm at mcherm.com (Michael Chermside) Date: Fri, 16 Apr 2004 10:55:48 -0700 Subject: Python OS Message-ID: <1082138148.40801e2433478@mcherm.com> A Evans writes: > I am by no means a programmer at this stage. > But as I learn more and more I see Python as the > Holy Grail of programming languages Then you have much to learn. Different languages have different strengths, and a skilled programmer will realize that. Python is an excellent language for expressing algorithms, doing rapid prototyping, and a GREAT many other tasks. But it is poorly suited to performing low-level register and bit manipulation. If I wanted an inference engine, I might use prolog rather than Python. In the world of OSes, I think a core done in something like C with the higher level kernel functionality in Python would make an interesting system for experimenting with OS design. But performance is likely to be unreasonable for a "production" OS. Remember too, that much of what is nice about Python is that it provides you with easy access to OS facilities (everything from sockets (as a library) to memory management (in the language). If you were developing an OS then that wouldn't be available until you had built it. -- Michael Chermside From daniel at syrinx.net Sat Apr 3 06:30:22 2004 From: daniel at syrinx.net (Daniel Ellison) Date: Sat, 3 Apr 2004 06:30:22 -0500 Subject: [maybe OT] Making posters References: <95aa1afa.0404030143.58c32975@posting.google.com> Message-ID: "Richie Hindle" wrote in message news:mailman.300.1080987238.20120.python-list at python.org... > > [Michele] > > Perhaps this is a bit off topic, but I haven't had look browsing on the > > net, so I thought I will try my chance here. I am looking for a > > tool taking a postscript file and enlarging it to make a poster. > > For instance I want to convert a picture taking a sheet in a poster > > made by four sheet that I can compose. Any suggestion? A Python > > suggestion would help me to stay on topic ;) > > You don't mention your platform, but my printer driver (WinXP driver for > the Samsumg ML-1210 laser printer) will do this itself for any document - > have you had a good dig though your printer driver options? > > -- > Richie Hindle > richie at entrian.com > > If you have the raw Postscript file, you can simply add a line near the beginning that looks something like this: 400 400 scale which will scale the image by 400%. It's been quite a while since I did Postscript programming so the example might not be 100% correct, but a bit of research will get you on the right track. It's not Python, but it'll work. Dan From roman.yakovenko at actimize.com Wed Apr 14 09:05:33 2004 From: roman.yakovenko at actimize.com (Roman Yakovenko) Date: Wed, 14 Apr 2004 16:05:33 +0300 Subject: Unable to create com object - need help Message-ID: <2D89F6C4A80FA547BF5D5B8FDDD04523060C63@exchange.adrembi.com> I tried your module. It seems that you generate code right :-) but IEnumUnknown doesn't defined in any file. I can try to edit ctypes.com.__init__.py to get the desired result. But before I do this I'd like to ask you do you have more recent version that fix it. If so I'll be glad. If not I will try to write a patch. Roman > -----Original Message----- > From: Roman Yakovenko > Sent: Wednesday, April 14, 2004 3:34 PM > To: python-list at python.org > Subject: RE: Unable to create com object - need help > > > Thank you very much. I definitly will try your module. > Also I still have to questions: > 1. How does VB success to work with this dll? > 2. Why after using makepy utility I don't get interface > registered in DiaSource class > > I understand that the first question is generic one, and has > nothing to do with python. > But any reference to this specifiec topic will be > appreciated. Also I'd like to know the answer > to the second question. It will help me a lot in my future work > > Roman. > > > > -----Original Message----- > > From: Thomas Heller [mailto:theller at python.net] > > Sent: Wednesday, April 14, 2004 2:57 PM > > To: python-list at python.org > > Subject: Re: Unable to create com object - need help > > > > > > "Roman Yakovenko" writes: > > > > > Hi. I need some help. > > > Here is my situation. It is a little bit difficult to > > explain and/or understand. > > > I'd like to use msdia71.dll. This dll gives you access to > > program database files > > > created during a build. I register this dll. This is pure > com dll. > > > This dll contains 3 top classes. I'd like to create one of > > them - DiaSource. > > > This class implements IDiaDataSource interface. This fact I > > can see in dia2.idl. > > > > > > importlib("stdole2.tlb"); > > > [ > > > uuid(e60afbee-502d-46ae-858f-8272a09bd707), > > > helpstring("DiaSource Class") > > > ] > > > coclass DiaSource > > > { > > > [default] interface IDiaDataSource; > > > }; > > > > > > after using makepy I get > > > > > > class DiaSource(CoClassBaseClass): # A CoClass > > > # DiaSource Class > > > CLSID = IID('{E60AFBEE-502D-46AE-858F-8272A09BD707}') > > > coclass_sources = [ > > > ] > > > coclass_interfaces = [ > > > ] > > > If I understand right DiaSource doesn't implements > > IDiaDataSource interface at all. > > > May be this is a bug, may be I don't understand something. > > Clarifying this point will be great. > > > > I think this has to do with the fact that with pywin32 you > > cannot access > > arbitrary com interfaces - only interfaces that either have > > been wrapped > > in pythoncom.dll or that derive from IDispatch. The DIA > > interfaces all > > derive from IUnknown, so it seems you cannot call them. > > > > There is ongoing work in pywin32 named 'universal' or something like > > that, but I don't know how far it is. > > > > Another possibility is to use ctypes com layer, it has a > tool somewhat > > similar to makepy - it's called readtlb.py, and creates > > python wrappers > > for com interfaces. ctypes.com has some samples > > demonstrating all this. > > > > HTH, > > > > Thomas > > > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > -- > http://mail.python.org/mailman/listinfo/python-list > From peter at engcorp.com Sun Apr 25 18:17:57 2004 From: peter at engcorp.com (Peter Hansen) Date: Sun, 25 Apr 2004 18:17:57 -0400 Subject: Andreas' practical language comparison In-Reply-To: <408c23b8$0$41746$5fc3050@dreader2.news.tiscali.nl> References: <408c23b8$0$41746$5fc3050@dreader2.news.tiscali.nl> Message-ID: GerritM wrote: > I really would like to see the linecount. I do belive that it is one of the > indicators of the power of the language and its batteries. Somehow it would > be nice to have a figure for "readability", but I don't have a clue how to > generate such a figure in an automatic way. Maybe you need some panel of > experts that gives a readability figure? I'd reply to this, but as there is already a discussion on comp.lang.misc (as Andreas said) it would probably be silly to continue one in parallel here... -Peter From blacksqr at usa.net Thu Apr 15 14:57:38 2004 From: blacksqr at usa.net (Stephen Huntley) Date: 15 Apr 2004 11:57:38 -0700 Subject: Goodbye TCL References: <0LudnSads6NmpuPdRVn-vw@centurytel.net> Message-ID: Ed: I think your post is valuable. Instead of trying to invalidate your arguments, I will outline my reasons why I stick to Tcl. Then we can perhaps glimpse how strengths and weaknesses counterbalance. The main reasons I stick with Tcl are: 1. Rock-solid stability. I'm too old to spare time wondering if frequent crashes in my software are my fault or the underlying technology's fault. Tcl largely removes this consideration from the equation. America Online's web server is written in Tcl. It is highly unlikely I will ever need to scale a product of mine to that level, so there's a lot of headroom for me. I have occasionally looked into new technologies, like Python, PHP, Ruby, etc; but I've noticed that if you look beyond the FAQ's deep into the developer mailing lists, you'll generally find statements like: 'development of the core is going really really well, and within the next few releases we actually expect it to be stable!' Hold me. I frequently use Tcl to write wrappers for other products to catch and compensate for their shortcomings. This would be pointless if it weren't for the fact that Tcl is at least an order of magnitude more stable and reliable than any other technology I've tried. 2. Freedom from bugs. For years after college I did almost no coding because I was sick of the fact that I would have to rewrite literally everything I wrote two or three times to find a syntactically correct version that didn't hit a deadly bug. Imagine my surprise when my first Tcl scripts Just Worked. And the docs were accurate and complete too, so I didn't have to spend half my time reverse-engineering (another new experience). For this reason alone Tcl is almost single-handedly responsible for the fact that I am still working in the computer world. In ten years of Tcl scripting, I think I've encountered three bugs in the core. I found upon reporting that each one was already fixed in the latest version. I just don't bother to upgrade my core very often because of 1. and 2. 3. Platform agnosticism. Since Tcl was originally designed to be embedded it play no favorites in terms of platform features. It's available on a wide variety of platforms and I suspect will be there on the platforms of the future in equally reliable forms. I started with computers on Unix as a student, as a professional worked first with Macintosh v 7, then on to Windows, and now a bit of everything (five *nix versions, four Win*s and handheld devices). AS/400 was in there somewhere. Tcl has been there every step of the way. I'm too old to relearn my chops every time a new OS fad blows through, and I don't want to have to predict winners and losers. I feel Tcl minimizes the likelihood I will have to. Here at work I suggested we use a free Tcl installer program rather than a for-pay Java one. Management chose the Java option. Why? Because the Java company officially supported all the platforms we needed to be on, and management felt they couldn't take the risk of going without assurances. It's turned out that the installer has required special handling or patches for every OS (and almost every OS version) we've tried it on, resulting in numerous gotchas and release-note warnings for our customers. And "official support" is a bulletin board where their engineers' response is always "we're working on it." Meanwhile my build and test scripts run merrily and without alteration everywhere. Alternative technologies tend nakedly to favor *nix, and seem only to offer a subset of function on other OS's grudgingly. Python and similar technologies treat platform-specific issues like pathnames and line terminators as special cases with their own commands or compensating strategies to handle them. Tcl largely handles them tranparently. It was years before I was even aware of some of these issues because Tcl handled them so well. Python uses ASCII as a default string encoding, but recently managed to bolt on a Unicode library (same with PHP I think). I haven't looked into its Shift-JIS suppport, which I need for work (and is included with Tcl). 4. Tk. Other technologies say 'We don't have a native GUI interface, but there's a binding to the Tk library.' For all intents and purposes, Tk is the only game in town for cross-platform GUI scripting. When I'm using Tcl I know I have access to 100% of Tk's features and the latest Tk version. Is that true with other languages' bindings? I don't know, but if I had to bet money I'd say no. Tk follow's Tcl's logic, and it's a lot easier to program Tk interfaces when in the Tcl mindset then try to access Tk's features by switching gears from another language's mindset. I don't do GUI programming very often, but when I have to, it's nice to know that I can do it as a trivial extension of my existing Tcl skills. Ed, your voice-recognition project looks very interesting, and I look forward to using it when it's ready for prime time. I spend 90% of my time in front of a Windows computer (my boss's choice, not mine): how does it run on Windows? How stable is it? How does Twisted's event architecture compare to Tcl's? Steve Huntley From jorg at neoplex.org Sat Apr 10 09:13:11 2004 From: jorg at neoplex.org (=?ISO-8859-1?Q?Jorg_R=F8dsj=F8?=) Date: Sat, 10 Apr 2004 15:13:11 +0200 Subject: recording sound from mic in Windows? Message-ID: <4077f42a@news.broadpark.no> I looking for a way to record a voice with a microphone and save the recording in wav format using python. Does anybody know any module which would let me do this? This is for a school project where we are going to use this recording to send voice-messages to cell-phones regards Jorg R?dsj? From greg at cosc.canterbury.ac.nz Tue Apr 20 02:25:23 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Tue, 20 Apr 2004 18:25:23 +1200 Subject: campaining for PEP 238 - integer division In-Reply-To: References: Message-ID: Sebastian Haase wrote: > The fact is that changing something as fundamental as the division > operator WILL BRAKE LOTS OF CODE !! ^^^^^ Ah, so *that's* why my code isn't running fast enough... -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From matt at themattfella.zzzz.com Sun Apr 11 23:23:58 2004 From: matt at themattfella.zzzz.com (Matt) Date: Mon, 12 Apr 2004 03:23:58 GMT Subject: Python OS In-Reply-To: <107jq68ao58o7ff@corp.supernews.com> References: <107j4eu6ffn2c68@corp.supernews.com> <107jq68ao58o7ff@corp.supernews.com> Message-ID: > From: torvalds at klaava.Helsinki.FI (Linus Benedict Torvalds) > Newsgroups: comp.os.minix > Subject: What would you like to see most in minix? > Date: 25 Aug 91 20:57:08 GMT > > > Hello everybody out there using minix - > > I'm doing a (free) operating system (just a hobby, won't be big and > professional like gnu) for 386(486) AT clones. This has been brewing > since april, and is starting to get ready. I'd like any feedback on > things people like/dislike in minix, as my OS resembles it somewhat > (same physical layout of the file-system (due to practical reasons) > among other things). > > I've currently ported bash(1.08) and gcc(1.40), and things seem to work. > This implies that I'll get something practical within a few months, and > I'd like to know what features most people would want. Any suggestions > are welcome, but I won't promise I'll implement them :-) > > Linus (torvalds at kruuna.helsinki.fi) > > PS. Yes - it's free of any minix code, and it has a multi-threaded fs. > It is NOT protable (uses 386 task switching etc), and it probably never > will support anything other than AT-harddisks, as that's all I have :-(. From peter at engcorp.com Fri Apr 9 13:17:09 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 09 Apr 2004 13:17:09 -0400 Subject: module not callable - why not? In-Reply-To: References: Message-ID: <8Mqdnb5WObgLR-vd4p2dnA@powergate.ca> djw wrote: > Diez B. Roggisch wrote: > >> import quaternion >> q = quaternion.quaternion() >> >> Thats a lot to type. doing a >> from quaternion import quaternion >> would solve that - but AFAIK thats considered bad for some reasons. > > I think what people consider dangerous is 'from import *'. The > form you give here is OK, as far as I know. Even "from xxx import yyy" can be dangerous if you don't know what you're doing. More specifically, any time the yyy thing might be dynamic (i.e. replace in the original module with something else at a later time), you will end up with a situation in which everyone who did the "from xxx import yyy" before the change has a binding to something other than what xxx.yyy is currently bound to. Generally speaking it's safe to do (and so is "from xxx import *") but considered poor form, extremely so in the latter case. And it's not an arbitrary thing: doing this makes code less readable and maintainable because it becomes unclear where names are coming from without constant reference to the list of imports at the top. -Peter From peter.maas at mplusr.de Thu Apr 22 10:04:58 2004 From: peter.maas at mplusr.de (Peter Maas) Date: Thu, 22 Apr 2004 16:04:58 +0200 Subject: Problem with xml.dom parser and xmlns attribute In-Reply-To: References: Message-ID: Richard Brodie wrote: > "Peter Maas" wrote in message news:c682uu$sco$1 at swifty.westend.com... [...] >>but if I replace by [...] >>A lot of HTML documents on Internet have this xmlns=.... Are >>they wrong or is this a PyXML bug? > > > If they are genuine XHTML documents, they should be well-formed XML, > so you should be able to use an XML rather than an SGML parser. > > from xml.dom.ext.reader import Sax2 > r = Sax2.Reader() Thanks, Richard. But in the Internet most of the time I don't know what kind of document I'm dealing with when I start parsing. I guess I should use HTMLParser (?). Mit freundlichen Gruessen, Peter Maas -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Hubert-Wienen-Str. 24 Tel +49-241-93878-0 Fax +49-241-93878-20 eMail peter.maas at mplusr.de ------------------------------------------------------------------- From newsgroups at jhrothjr.com Fri Apr 9 14:35:33 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Fri, 9 Apr 2004 14:35:33 -0400 Subject: module not callable - why not? References: Message-ID: <107dras2heahcb6@news.supernews.com> "Diez B. Roggisch" wrote in message news:c56jph$rrk$05$1 at news.t-online.com... > Hi, > > I just thought about creating a module for quaternions (as an personal > exercise, so I'm not after pointers to classlibs here). > > Now usually I'd create a file called "quaternion.py", define my quaternion > class in there and then import and create an instance like this: > > import quaternion > > q = quaternion.quaternion() > > Thats a lot to type. doing a > > from quaternion import quaternion > > would solve that - but AFAIK thats considered bad for some reasons. I don't know why that's bad. Its fairly common in fact. What's usually bad is "from foobar import *" which loads your module namespace with a bunch of identifiers that are not documented in the source of that module, and that may change if the imported module changes. In fact, I'd probably do: "from quaternion import quaternion as q" to minimize typing later. > Now I thought about defining a __call__ operator at module level to allow > this: > > import quaternion > > q = quaternion() > > > where the call looks like this: > > def __call__(*a, *kw): > return quaternion() > > But that doesn't work. > > Now my question is: Is there a way to make a module callable that way? And > wouldn't it make sense to allow the implementation of a call operator on > module level? No, and probably not. There's no really earthshaking reason why a module object couldn't be a callable, and I suspect it would be rather simple to do. However, it would add some complexity to the model, and IMO your use case isn't compelling enough. Other people may disagree with me on that, though. John Roth > -- > Regards, > > Diez B. Roggisch From greg at cosc.canterbury.ac.nz Sun Apr 25 23:24:33 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Mon, 26 Apr 2004 15:24:33 +1200 Subject: Why we will use obj$func() often In-Reply-To: References: <84Uhc.22278$dZ1.5087@fed1read04> <8AWhc.23114$dZ1.11070@fed1read04> <40883BFE.B381518A@alcyone.com> <27_hc.23801$dZ1.2716@fed1read04> <40887145.789A2FE8@alcyone.com> <7cki80hj976bia36lhf9er97v073o1pqvm@4ax.com> <1082783076.585831@yasure> Message-ID: Mark Hahn wrote: > The advantage of prefix symbols that Ruby and Prothon use right now is that > the compiler and the program reader don't have to scan the code at all to > see what scope the var belongs to. When you see the & you know it's in the > surrounding function, Hang on a minute. Do you literally mean the immediately surrounding function, and not one further out? In def f(): def g(): def h(): &x = 42 h() g() print x does the &x in h refer to the x in f? If it does, then I don't see how you can deduce that in a single pass. If it doesn't, then how do you refer to the x in f from h? -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From jacek.generowicz at cern.ch Thu Apr 1 03:38:30 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 01 Apr 2004 10:38:30 +0200 Subject: [OT] Top posting is a PITA [was : Prothon Prototypes vs Python Classes] References: <569c605ld1cj8fc1emolk08ete0s1prls1@4ax.com> <106di86neu1qh4d@news.supernews.com> <4069a001$0$4237$afc38c87@news.easynet.co.uk> <4069e9d9$0$8915$636a15ce@news.free.fr> <406a98ee$0$290$edfadb0f@dread12.news.tele.dk> Message-ID: Markus Wankus writes: > Right. So if we'd all just settle on top-posting things wouldn't be > so bad after all. It's all you bottom-posters that are screwing > things up for the rest of us. ;o) Did you actually _understand_ what he wrote? Yes, I did notice the smiley, but I also noticed the apparent complete failure to get the point. Complete failure to get the point, I find, is often strongly correlated to top-posting. Even if _everyone_ top-posts, then the reading direction is still inconsisitent and requires the reader to jump back and-forth, to understand what is going on. Please _think_ about it. It really doesn't take very much thought to understand that top-posting sucks, but it does require some. More than top-posters seem to be able to muster, it seems. From dmq at gain.com Wed Apr 28 21:07:31 2004 From: dmq at gain.com (David MacQuigg) Date: Wed, 28 Apr 2004 18:07:31 -0700 Subject: Is classless worth consideration Message-ID: On 27 Apr 2004 16:34:56 -0700, has.temp2 at virgin.net (has) wrote: >David MacQuigg wrote in message news:... > >> Example of Simplified Classes ( Prototypes ) >> ============================================ > >[SNIP] > >Class-based OOP by any other name. But then, I've pointed this out >already. See Emperor, clothes; lack of. > >Here; while I don't claim them to be paragons of programming, I >suggest taking a look at my old AppleScript libraries at >. (Note: scripts are compiled, so >you'll need a Mac to view source.) See Types, HTMLTemplate and ASTest >for examples of OO programming that isn't class-fixated. Might lend >some useful perspective. The problem we Python programmers are having is understanding the fundamental advantage of eliminating classes and working only with instances. The theoretical discussions put me to sleep. I can't see the point of the examples above. What we need is a simple use case. I've included the ability to clone one instance from another in my "Python 3" proposal http://ece.arizona.edu/~edatools/Python/PrototypeSyntax.htm This will allow the user to completely ignore classes, and just make one instance from another, then another, and so on, modifying each instance along the way, whenever the urge is felt. Here is what I have so far in the Pros and Cons on this feature: Pro: Allows "on-the-fly" programming style with no classes. Con: Can lead to more undisciplined programming. Perhaps you can help us here. -- Dave From peter at engcorp.com Tue Apr 13 08:39:02 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 13 Apr 2004 08:39:02 -0400 Subject: How to kill a SocketServer? In-Reply-To: References: Message-ID: <6tadnU3-4_n7QubdRVn-tw@powergate.ca> Josiah Carlson wrote: >> Since the whole application uses much CPU power, the performance (esp. >> the >> reaction time) of an asynchronous server is too low. >> >> We found out that a threading server is much the better choise for >> this, but >> we'd need a way to stop a server and start it again (wich new >> parameters). > > > That is very interesting. > > After doing some research into heavily multi-threaded servers in Python > a few years back, I discovered that for raw throughput, a properly > written async server could do far better than a threaded one. > > If your request processing takes the most time, you may consider a > communication thread and a processing thread. > > If your processing thread does a lot of waiting on a database or > something else, it may make sense to have one communication thread, and > a handful of database query threads. > > What part of a request takes up the most time? The OP indicated that "esp. the reaction time" was his concern, not throughput. If he's right about that, then in principal he could well be right that an async server would not be the most appropriate. (I don't really believe that either, though...) -Peter From erik at heneryd.com Tue Apr 6 04:29:11 2004 From: erik at heneryd.com (Erik Heneryd) Date: Tue, 06 Apr 2004 10:29:11 +0200 Subject: slightly OT: BUT NEEDs to be said In-Reply-To: <4078daf265c69e9353e8af72542da703@dizum.com> References: <4078daf265c69e9353e8af72542da703@dizum.com> Message-ID: <40726A57.4040906@heneryd.com> Nomen Nescio wrote: > Hi I downloaded this document about Python recently: > > http://datamining.anu.edu.au/~ole/publications/python.pdf > > I loved the cute little Snake graphic. > FYI: That's not a Python snake, but a Pythonware one (notice the white x on blue) and probably used without the artists (Joakim L?w) knowledge. /Erik Heneryd (formerly at Pythonware/Secret Labs) From ville at spammers.com Thu Apr 1 09:42:14 2004 From: ville at spammers.com (Ville Vainio) Date: 01 Apr 2004 17:42:14 +0300 Subject: ANNOUNCE: 'goto' for Python References: Message-ID: That's mostly true. I'm the first to admit that occasionally a predictable and dull language is useful, but there is a lot of virtue in being to express yourself with the language, and give a personal touch to all the code you write. The code I write should scream that "this is by Ville down the hall!". The idiosynchracies (sp?) in our code leave a lasting mark for the generations to come, show off the proficiency we have been able to acquire in the language (and thus make the monthly salary easy to calculate), and make us who we are. -- Ville Vainio http://tinyurl.com/2prnb >>>>> "Peter" == Peter Maas writes: Peter> Great!!! This will enhance Python's yet poor capabilities Peter> to write code with a behaviour hard to predict by Peter> programmers thereby adding a human touch to the sometimes Peter> too clean and dull Python language! (Wow, this top posting seems like lots of fun!) From __peter__ at web.de Tue Apr 13 14:37:37 2004 From: __peter__ at web.de (Peter Otten) Date: Tue, 13 Apr 2004 20:37:37 +0200 Subject: Adding properties to objects References: <3a8e83d2.0404130906.2ea796e9@posting.google.com> Message-ID: Matthew Barnes wrote: > Is it possible to add properties to objects dynamically? > > I have an instance (x) of some new-style class (Foo), and I would like > to be able to do something like: > >>>> x = Foo() >>>> x.myproperty = property(getsomething, setsomething, delsomething); >>>> x.myproperty # invokes getsomething >>>> x.myproperty = 1 # invokes setsomething >>>> del x.myproperty # invokes delsomething > > However, when I evaluate x.myproperty I get back a property object > (which makes sense). I get the feeling I'm missing a step to "bind" > the property object to the class instance. > > Is this possible (it's Python... of course it's possible, right?), and > if so, how? Fresh from the mad coders' department, here's how to dynamically change an object's class to get the desired effect: import new class Foo(object): def __setattr__(self, name, value): if isinstance(value, property): klass = new.classobj(self.__class__.__name__, (self.__class__,), {}) setattr(klass, name, value) self.__class__ = klass else: object.__setattr__(self, name, value) f1 = Foo() f1.name = "first" def set1(self, v): self.name = v[1:-1] def get1(self): return "(%s)" % self.name f1.prp = property(get1, set1) f2 = Foo() f2.name = "second" def set2(self, v): self.name = v[2:-2] def get2(self): return "<<%s>>" % self.name f2.prp = property(get2, set2) print f1.prp, f2.prp f2.prp = "((was second))" print f1.prp, f2.prp f2.__class__.prp = f1.__class__.prp print f1.prp, f2.prp If you try the above approach, you will of course end up with more classes than instances - if you only expect a limited number of dynamic properties you could put all combinations into a class cache. :-) Peter From gerrit at nl.linux.org Tue Apr 20 06:57:47 2004 From: gerrit at nl.linux.org (Gerrit) Date: Tue, 20 Apr 2004 12:57:47 +0200 Subject: CamelCase versus wide_names (Prothon) In-Reply-To: References: <6ee58e07.0404192141.2229efd6@posting.google.com> Message-ID: <20040420105747.GA17588@nl.linux.org> Mark Hahn wrote: > "William Park" wrote ... > > Someone else already mentioned this > > > problem: > > > > > > smtp_message <-> SMTPMessage <-> SmtpMessage > > If you consider the capital letter as just a replacement for the underbar, > then the answer is definitely smtpMessage. I don't see any problem. SMTP is an acronym. Because it's an acronym, it's most often spelled in allcaps. A problem with capitalizing names by default, is that capitalization loses a function it has in written language. Further, I like to use capitalization naming for giving different cased names to instances, Classes, VeryLongClassNames or CONSTANTS. But I don't think the language should fiddle with capitalization itself. Moreover, I like a case-insensitive language. I find smtpMessage quite ugly to read. I find every name with caps in the middle but no caps at the start ugly to read - I think it's called mixedCase. I prefer lower_case_with_underscores. I haven't followed the Prothon capitalization naming convention in detail. But in my opinion, a multi-word name should read as a multi word name. Underscores serve better to do so than capitalization does. Gerrit. -- Weather in Twenthe, Netherlands 20/04 12:25: 12.0?C Scattered clouds partly cloudy wind 4.0 m/s SSW (57 m above NAP) -- Experiences with Asperger's Syndrome: EN http://topjaklont.student.utwente.nl/english/ NL http://topjaklont.student.utwente.nl/ From jcarlson at uci.edu Mon Apr 12 14:43:58 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Mon, 12 Apr 2004 11:43:58 -0700 Subject: maximum length of a list & tuple In-Reply-To: References: Message-ID: >> You can't just store the integer. How would you differentiate between >> an integer in a list and a pointer? Answer: you must use >> PyIntObjects. Use the source. > > > Python does not recognize anything called "pointers" at the language > level, only internally. > > What I was saying is that the only PyIntObject created was one with > the ob_ival of 1. Then a list containing one pointer to it was > created. Then it was replicated "c" times. Only one integer. Yeah, I was thinking of the case in generating a sequence of integers via range. In that case, range(N) produces 12-byte intobjects and 4 byte pointers. In the case of c*[1), indeed you are right, one object gets created, and some c pointers to that object are generated for the list. Seems I got off topic and we are both right. - Josiah From pwatson at redlinepy.com Sat Apr 3 21:58:14 2004 From: pwatson at redlinepy.com (Paul Watson) Date: Sat, 3 Apr 2004 20:58:14 -0600 Subject: Typing \n in strings References: Message-ID: <406f79ca$1_1@themost.net> "Edward Diener" wrote in message news:RGKbc.11130$yN6.10939 at newsread2.news.atl.earthlink.net... > Python 2.3.3 on Win2K. In the Python tutorial it says that typing \n in > string literals is the new-line character. I open the interpreter and type a > string with a \n in it but instead of outputting a string with a new line, > it outputs the \n as literal characters of the string. Is the tutorial > wrong, is the interpreter broken, or what is happening ? > What exactly are you entering and what is output? Python 2.3.3 (#51, Dec 18 2003, 20:22:39) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> "now\nis\nthe\ntime" 'now\nis\nthe\ntime' >>> print "now\nis\nthe\ntime" now is the time >>> s = 'now\nis\nthe\ntime' >>> s 'now\nis\nthe\ntime' >>> print s now is the time From alexanro at stud.ntnu.no Wed Apr 14 12:41:46 2004 From: alexanro at stud.ntnu.no (Alexander Rødseth) Date: Wed, 14 Apr 2004 18:41:46 +0200 Subject: Pygame References: <107qkrbhnjpmh9b@news.supernews.com> Message-ID: > Why should it be? Because it's inconsistent that Python includes many platform-specific and hardware-specific modules, and even gui-modules like Tkinter, but, afaik, no way at all to create fullscreen and/or hw-accelerated graphics. > In looking thorough the libarary, I find that > everything there is a developer tool of some > sort. The few executables are things like > unittest which are standard parts of the > developer's tool chain. I agree pretty much with Peter's reply. How exactly did you "look through the library"? Looking at http://docs.python.org/modindex.html, I find modules for sound, xml, graphics, mail, a web-server and even the deprecated and insecure "Enigma-like encryption and decryption". :-) Python is supposed to be "batteries included", but still hasn't got native support for fullscreen graphics. Granted, Pygame might not be the optimal solution, due to licensing issues (or whatever other reason might appeal to you), but IMHO, there should be a module included that allowed for similar functionality. - Alexander From stjahn at gmx.de Tue Apr 13 16:47:51 2004 From: stjahn at gmx.de (Steffen Jahn) Date: 13 Apr 2004 13:47:51 -0700 Subject: Import / export values to/from C program Message-ID: Hi, I stumbled across Python when trying to invoke *scripts* from C programs. The idea is to set up some variables in the C program, export them, run a Python script, and, after completion, import some variables back into the C program. This way, I can keep the C program very flexible for certain types of changes. Unfortunately, I can't see an API to export/import an PyObject directly. I see currently only an indirect way: Implement import and export functions in C which have to be called in the Python script (import function at beginning and export function at end). Though I would prefer a *direct* access. At the moment, I start thinking whether direct access is really better since the script needs anyways to *know* of the variables which are available (makes not much difference whether variable or function...) Anyways, maybe somebody can tell me if such direct access is possible. A kick in the right direction would be highly appreciated. Thx, Steffen From usenet at datahansa.com Thu Apr 15 01:56:37 2004 From: usenet at datahansa.com (Oleg Paraschenko) Date: 14 Apr 2004 22:56:37 -0700 Subject: Python GUI wrapper for a long operation Message-ID: Hello, maybe of some interest: A complete Python Tkinter sample application for a long operation http://uucode.com/texts/pylongopgui/pyguiapp.html A complete Python Tkinter application demonstrates one of the ways to implement a GUI wrapper for a long operation. The long operation works in a separated thread without frozing a GUI. A progress bar visializes a progress in calculations. A notification widget displays log messages. User can cancel the operation. Log messages are stored in a viewable history buffer. Regards, Oleg From deetsNOSPAM at web.de Mon Apr 19 11:51:53 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Mon, 19 Apr 2004 17:51:53 +0200 Subject: Problems using modulo References: Message-ID: Griff wrote: > > Would be grateful for any suggestions Try this: t = 5.9 interval = 2.0 while t < 6.1: print (t, interval, t % interval) t+=0.1 Then you see what actually gets divided.... I'm not sure what you actually try to do, but AFAIK modulo is mathematically only properly defined on integers - so you should stick to them. If you need fractions, it might be sufficient to use fixed-point arithmetics by simply multiplying by 10 ar 100. -- Regards, Diez B. Roggisch From no.email at please.com Tue Apr 13 12:45:35 2004 From: no.email at please.com (Stevie_mac) Date: Tue, 13 Apr 2004 17:45:35 +0100 Subject: Python crashes - cannot pin it down! References: Message-ID: Nearly forgot... PythonWin 2.3.3 (#51, Dec 18 2003, 20:22:39) [MSC v.1200 32 bit (Intel)] on win32. wxPython 2.4.2.4 WINXP SP1 BOA 0.28 From mogmios at mlug.missouri.edu Mon Apr 26 03:19:18 2004 From: mogmios at mlug.missouri.edu (Michael) Date: Mon, 26 Apr 2004 00:19:18 -0700 Subject: How's ruby compare to it older brother python In-Reply-To: References: Message-ID: <408CB7F6.6070509@mlug.missouri.edu> >in term of its OO features, syntax consistencies, ease of use, and their >development progress. I have not use python but heard about it quite often; >and ruby, is it mature enough to be use for developing serious application, >e.g web application as it has not many features in it yet. > >I've given up on Perl for its ugly syntax and it is not the easiest language >to learn. How about PHP? > IMO Ruby is closer to Perl than Python as far as clearness of it's syntax. I really like Python better. PHP isn't as garbled as Perl but it isn't as flexible either and it's still not nearly as clean as Python. Of the four languages (Perl, Python, PHP, and Ruby) I find Python the easiest to work in. I use Python for command-line programming, web programming (mod_python), and GUI programming (wxPython and Pygame) and find it a good general purpose language. From claird at lairds.com Thu Apr 1 07:50:08 2004 From: claird at lairds.com (Cameron Laird) Date: Thu, 01 Apr 2004 12:50:08 -0000 Subject: Python from the command line (was: Choosing Perl/Python for my particular niche) References: <40652B0D.7C313F77@doe.carleton.ca> <4069F1FD.601C9079@doe.carleton.ca> <106n8kj2t5n7m11@corp.supernews.com> <406BB6C4.7F3ADD4@doe.carleton.ca> Message-ID: <106o400l16eub3f@corp.supernews.com> In article <406BB6C4.7F3ADD4 at doe.carleton.ca>, Fred Ma wrote: . . . >I've put in a request to my sysadmin to install python. The >way to get hooked on it is to start small, with mundane tasks >(same as with any new shell, I suppose). If it doesn't get >installed due to lack of priority, I can always get it >bundled with my next cygwin update. Cygwin is an absolute >blessing. Everything comes prebuilt (lots of stuff) and >you have superuser priveleges, as well as simultaneous >access to Windows. Just as long as your HDD isn't FAT >(that prevents chmod from working). . . . Oh! Apparently Win* is the platform of interest; that hadn't occurred to me. There's a LOT to say specifically on the topic of Python- for-Windows-system-administration. You might want to start with Mark Hammond's book. I'm no great fan of CYGWIN for my own use, although I certainly recognize it's been historically important. It occurs to me that perhaps we haven't made adequately clear how easy it is to install native Python on Windows. It should take less time doing it than talking about do- ing it. I'm not arguing with your approach; I just want to ensure we've been clear about the alternatives. Follow-ups narrowed. -- Cameron Laird Business: http://www.Phaseit.net From scrutinizer at gmx.at Wed Apr 7 04:39:07 2004 From: scrutinizer at gmx.at (Francesco) Date: Wed, 07 Apr 2004 10:39:07 +0200 Subject: Python Filemanager and Shell Context Menu References: <87oeq4211c.fsf@pobox.com> Message-ID: On 06 Apr 2004 23:29:19 +0100, jjl at pobox.com (John J. Lee) wrote: >Francesco writes: > >> Hello Pythonnian's >> >[...] >> I have no idea, how to accomplish this. >> For what I can imagine: >> Either use ctypes and the kernel or shell dll, or win32 extensions. >> >> Have someone done such a task before? >> Can someone help me? >[...] > Hello John, >There's a good O'Reilly book about this, which certainly covers what >you want: > >"Visual Basic Shell Programming", J.P. Hamilton > > >I used that book to write a trivial IE plugin that I posted to the >ctypes mailing list -- not directly relevant, but may set you on the >right track (it shows how to implement COM interfaces that aren't >defined in any type library). interesting, I will take a look. > >Generally, for all this Windows shell programming, you implement some >COM interfaces, and then set up set up some registry keys to tell >Windows what you've done. The book tells you which interfaces and >which keys you need, documents some bugs and oddities and gives some >example code. You just have to translate the VB code to Python+ctypes >(which is not necessarily an entirely hitch-free process ;-). >Obviously, there's no Python-specific info in the book. > thank you for your explanation. best regards, -- Francesco From rogerb at rogerbinns.com Thu Apr 1 12:13:11 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Thu, 1 Apr 2004 09:13:11 -0800 Subject: xmlrpc, httplib and SSL (HTTP 1.1 XMLRPC client) References: Message-ID: <56vtj1-2rp.ln1@home.rogerbinns.com> > I wanted to do keep the connections on which my clients do XMLRPC calls > open, and after staring at the xmlrpclib.py source for a while, came up > with the class at the bottom of the message. Are you sure you are actually getting persistent connections? The code will auto-close and auto-open the connection even just keeping the same HTTP connection object. In order for the connection to not be auto-closed, the remote end must return a HTTP/1.1 response (see httplib.HTTPResponse._check_close). If your server end is Python, then it will always close the connection unless the request was HTTP/1.1 *and* a 'Connection: keep-alive' header was sent, which the Python client does not do. The above is all true for Python 2.3. For 2.2 it does HTTP/1.0 IIRC so you have no hope. Roger From Scott.Daniels at Acm.Org Mon Apr 5 18:04:00 2004 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Mon, 05 Apr 2004 15:04:00 -0700 Subject: Newbie need help In-Reply-To: References: <1072gkc3e3oif19@corp.supernews.com> Message-ID: <4071dec1$1@nntp0.pdx.net> Tony Ha wrote: > ... instead of >os.chdir("C:\Python23\Lib\site-packages\PythonCardPrototype\tools") >you need >os.chdir("C:\\Python23\\Lib\\site-packages\\PythonCardPrototype\\tools\\codeEditor") > I also found out you can you u' raw string. i.e. > os.chdir(u'C:\Python23\Lib\site-packages\PythonCardPrototype') > this also work. Nope, you just lucked out by using a different string. the problem with using a backslash is that it normally an instruction to the source translator to construct special characters. Because your previous directory name included tools, you had a sequence with a backslash followed by a lower case t. That is shorthand for a tab (ASCII 9). As Peter Hansen tells you in another note, you can use an r directly before the string to tell the source translator to "treat backslashes as regular characters." So, you'll notice that, for example, 'abc\tex' != r'abc\tex', but 'abc\Tex' == r'abc\Tex', because '\t' is the tab character, not '\T'. -- -Scott David Daniels Scott.Daniels at Acm.Org From andymac at bullseye.apana.org.au Tue Apr 6 08:02:49 2004 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Tue, 6 Apr 2004 22:02:49 +1000 (EST) Subject: Using python23 to develop an extension for an application that has python22 embedded In-Reply-To: References: <1073eeubflmchd5@corp.supernews.com> Message-ID: <20040406214820.L97937@bullseye.apana.org.au> On Mon, 5 Apr 2004, John Underwood wrote: > Since I do have python23.dll and python23_d.dll (from a successful > build of 2.3), can I use these to develop an extension for the > aforementioned commercial application if I stay away from any new > features in 2.3 (but not in 2.2)? You can do the development, but you won't be able to directly distribute the resulting extension because it will have been linked with python23.dll when it needs to be linked with python22.dll. To make things easier to fudge later, you make sure that your extension is Distutils'ified from the beginning. You can then use another compiler supported by the Distutils (MS CL non-optimising compiler, MinGW, Borland etc) to build the distributable extension in either a Python 2.2 or 2.3 installation, without risking mixing C runtime library mismatches (VS.NET uses a different CRT than VS6 I understand). If using a 2.3 installation, you'll need to substitute a 2.2 import library when building the final distributable version. The Distutils setup.py script can then provide the installation harness. -- 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 mwilson at the-wire.com Fri Apr 23 15:52:30 2004 From: mwilson at the-wire.com (Mel Wilson) Date: Fri, 23 Apr 2004 15:52:30 -0400 Subject: Why we will use obj$func() often References: <84Uhc.22278$dZ1.5087@fed1read04> <8AWhc.23114$dZ1.11070@fed1read04> Message-ID: <+PXiAls/Kj/Q089yn@the-wire.com> In article , "Mike C. Fletcher" wrote: >Mark Hahn wrote: >>My inability to understand this stuff is what drove me to do Prothon . >>All the hidden wrapped this and wrapped that confused me to no end. >Fascinating. Most users never even notice this stuff, let alone getting >so worked up about it that they start a whole separate language ;) . >After all, they don't generally even know that metaclasses *exist* and >just know that it all works exactly as they would expect. You for >instance, were describing how the interpreter just knows that a class >can't be the target of an unbound class method. Sure, *maybe* it's all >a hideously complex mess that has people running screaming from Python >in horror, but from where I sit it is an extremely elegant system that >most people use without any impedance mismatch at all. I perhaps encountered this.. connection = serial.Serial ( ... ) # connection is a file-like object, # having the usual `write` method engine = MyFiniteStateMachine () # engine happens to have a `writer` method that # funnels out the machines products # The default is effectively `def writer (self, s): print s` engine.writer = connection.write # we channel engine's output through the serial connection Plugged together, it just works, as Mike says. No trouble when engine's internal calls to `self.writer` end up accessing a completely different object's method. It's only lately that I've stopped to gawp at it, and wonder. Regards. Mel. From apocalypznow at yahoo.com Wed Apr 7 04:52:13 2004 From: apocalypznow at yahoo.com (jason willows) Date: Wed, 07 Apr 2004 08:52:13 GMT Subject: Obfuscator, EXE, etc. - a solution Message-ID: <1jPcc.41986$oR5.1890@pd7tw3no> There have been many many many many discussions about obfuscating python. To my dismay, most who answer are those who frequently post, and they say things such as: 1) what's the point, in theory anything could eventually be decompiled 2) python is used for mostly internal stuff anyway, cuz its a "glue" language, so why bother 3) use licensing and a good lawyer, it's the ONLY way 4) many programmers seem comfortable releasing their java and .net and other interpreted code products into the market, so why not you? I found most of these comments dismissive, and sometimes quite arrogant. Frankly, the reasons why anyone would want to protect their code is simple and should be observed because we are all programmers: we want to protect our hard work. Addressing the above points: 1) Anything could eventually be decompiled.... yes that's true. In a perfect world. Have you ever tried to decompile C code and make sense of it? Try a large C program. Good luck, you philosophers. 2) I don't see Python as merely a glue language. I see it as a serious language for serious applications. Indeed, there are many commercial examples of this, and Python works very well and is cost-efficient to use. Incidentally, IBM and Microsoft have adopted Python for various applications.... not that in itself should necessarily mean anything. 3) Using licensing and a good lawyer. I'm all for that! Now your code has been stolen... and you are going to hire a lawyer to fight it out in court. Months go by, maybe into years. The law offers no guarantees, except to law makers. You've mortgaged your house to protect your investment. If you win. 4) Others release their java and .net programs. Many obfuscate their code before doing so, for the very same reasons a Python programmer would want to do so. I'm sick and tired of intelligent people acting like idiots. Programmers should offer solutions, rather than anecdotal discussions based on obvious points. Here's my solution, it's not perfect, but it works well: Use Pyrex, which translates your python sources (virtually unchanged) to .c and then links them. You get natively compiled .pyd files (ie: dll), just as though you had written a C program and compiled & linked it yourself. I used this on all my source files except the one that starts my program. I used py2exe (latest version) on the source file that starts my program to create an EXE, and it also puts all my .pyd files into the library.zip. The result is a program that is as difficult to understand after decompile as a natively compiled C program, except for the beginning source file (which should contain only a very small fraction of your program logic anyway). I have done this on a client-side python program that is composed of over 40 .py files and from between 200 to 500 lines each file. It uses the wxPython widgets for the GUI, Twisted for client/server communication, Pyro for peer-to-peer communication, and the Crypto package for RSA public key encryption. It runs without problems of any kind, especially ones that may be related to the GUI or Twisted or Pyro or Crypto, and the increase in speed of execution is very obvious. Note on Pyrex: it can't handle "import *" and this addition construct "x += 1". So you may have to do a little bit of recoding, but that is all the recoding I found that I had to do. If you would like to discuss this constructively, email me at apocalypznow at yahoo.com . I welcome a good programmer's discussion. From cedmunds at spamless.rochester.rr.com Mon Apr 12 18:01:43 2004 From: cedmunds at spamless.rochester.rr.com (Cy Edmunds) Date: Mon, 12 Apr 2004 22:01:43 GMT Subject: Missing Console in Pythonwin Message-ID: Here's a weird one for you. Running Pythonwin on a Win2000 machine the console suddenly stopped showing. I can turn it on and off and the checkmark comes and goes but nothing is visible. I can do a print preview and see it but that's it. I uninstalled and reinstalled (upgrading from 3.2.2 to 3.2.3) but still no luck. Any ideas? -- Cy http://home.rochester.rr.com/cyhome/ From iv at an.voras.fer Fri Apr 2 10:01:11 2004 From: iv at an.voras.fer (Ivan Voras) Date: Fri, 02 Apr 2004 17:01:11 +0200 Subject: Creating a matrix? Message-ID: Is there a nice(r) way of creating a list of uniform values? I'm currently using: list('0'*N), which makes a string and then chops it up into a list. I need it to create a NxN matrix: matrix = [list('0'*N) for i in range(N)] (elements need to be mutable afterwards, a shallow copy is bad) While this is short and concise, it also feels odd :) From richie at entrian.com Wed Apr 7 05:33:53 2004 From: richie at entrian.com (Richie Hindle) Date: Wed, 07 Apr 2004 10:33:53 +0100 Subject: what relationship between this mail list and the python group on Google? In-Reply-To: <4073B147.1010604@tom.com> References: <4073B147.1010604@tom.com> Message-ID: [huzhenghui37] > what relationship between this mail list and the python group on Google? > i saw the same info on both They are the same thing - messages posted to one are mirrored to the other. You can choose to access the messages either via email or news (and hence Google Groups) according to your preference. -- Richie Hindle richie at entrian.com From FBatista at uniFON.com.ar Wed Apr 7 10:35:27 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Wed, 7 Apr 2004 11:35:27 -0300 Subject: Are line continuations needed? Message-ID: [wallacethinmintr at eircom.net] #- Python lets you continue a single logical line across more than one #- physical line, either by putting a \ at the end or letting it happen #- automatically with an incomplete infix operator. #- #- I'm wondering how often is this feature needed? Would there be any #- problems if it weren't part of the language? The issue is: How important is to remove this feature, considering that it'll break zillions of lines of code around the world? . Facundo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA La informaci?n contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener informaci?n confidencial o propietaria, cuya divulgaci?n es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no est? autorizado a divulgar, copiar, distribuir o retener informaci?n (o parte de ella) contenida en este mensaje. Por favor notif?quenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magn?tico) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telef?nica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electr?nicos pueden ser alterados, motivo por el cual Telef?nica Comunicaciones Personales S.A. no aceptar? ninguna obligaci?n cualquiera sea el resultante de este mensaje. Muchas Gracias. -------------- next part -------------- An HTML attachment was scrubbed... URL: From andrew-pythonlist at puzzling.org Wed Apr 21 18:57:33 2004 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Thu, 22 Apr 2004 08:57:33 +1000 Subject: Generator inside a class prevent __del__ ?? In-Reply-To: <40866ECD.A45758B9@free.fr> References: <4085BA96.651D2E4A@free.fr> <40866ECD.A45758B9@free.fr> Message-ID: <20040421225733.GA10800@frobozz> On Wed, Apr 21, 2004 at 02:53:33PM +0200, Emmanuel wrote: > > Trouble is, I _would_ like not to care about the lifetime of the object, and I > don't know where it will be destroyed. Then don't use __del__. Python can and will automatically collect cycles when the objects *don't* define __del__ methods. Out of curiousity, why are you defining __del__ anyway? -Andrew. From taliesin at ananzi.co.za Wed Apr 14 15:17:46 2004 From: taliesin at ananzi.co.za (Tally) Date: 14 Apr 2004 12:17:46 -0700 Subject: audio input? Message-ID: <3fa378e7.0404141117.5e9f0428@posting.google.com> I am writing a nifty app that plays a series of sinewaves at different frequencies where they are fed into a simple circuit involving either an inductor or capacitor of unknown value. Another waveform is read back in via the Line In of the computer and through various little tricks my Python program will calculate the inductance or capitance of the part. So... I've checked out PySnack, and it doesn't do what I want. Does anyone know of a clean, simple audio library or wrapper for Python that is friendly to capturing low-latency audio to memory? It would be nice if it had functions like RMS power and that kind of thing but I can always write that myself in C... Thanks for your time, Tally From andymac at bullseye.apana.org.au Fri Apr 16 19:26:09 2004 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Sat, 17 Apr 2004 09:26:09 +1000 (EST) Subject: Wrapper round x86 Assembler In-Reply-To: <8089854e.0404160530.5b7c23aa@posting.google.com> References: <8089854e.0404082353.7bf163a2@posting.google.com> <4dKdnQlIXMIXIevdRVn-gg@powergate.ca> <8089854e.0404100204.504186a0@posting.google.com> <8089854e.0404122329.5dfe5ce1@posting.google.com> <8089854e.0404132323.3283390@posting.google.com> <8089854e.0404141105.37d09320@posting.google.com> <8089854e.0404160530.5b7c23aa@posting.google.com> Message-ID: <20040417092307.F89016@bullseye.apana.org.au> On Fri, 16 Apr 2004, Fuzzyman wrote: > MinGW seems easy enough to install - I've even compiled example C > programs with gcc - but getting disutils to use it is another > matter... Distutils won't use MinGW by default, as VS6 is the "native" compiler. You use MinGW by specifying the compiler on the command line with the "-compiler=mingw" option to the setup script - note that this is from memory, but there is a page on www.python.org that contains more information about using MinGW to build extensions. -- 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 stach at fr.USUN.pl Thu Apr 15 17:12:17 2004 From: stach at fr.USUN.pl (Krzysztof Stachlewski) Date: Thu, 15 Apr 2004 23:12:17 +0200 Subject: newbie question In-Reply-To: References: Message-ID: jeff wrote: > ex: > > a = "text str" > if a == "text str": print a > > why doesn't that work? i couldn't find much help about variable types in > the manual, does it need a property like a.text? It works - at least on my computer. That is: it prints "text str" to the console. What did you expect it to do? -- Stach Jabber: stach at jabber atman pl From bokr at oz.net Wed Apr 28 21:10:21 2004 From: bokr at oz.net (Bengt Richter) Date: 29 Apr 2004 01:10:21 GMT Subject: Explanation of Instance Variables in Python References: Message-ID: On Wed, 28 Apr 2004 11:25:08 -0700, David MacQuigg wrote: > >I am writing a chapter for teaching OOP in Python. This chapter is >intended as a brief introduction to replace the more complete >discussion in Learning Python, 2nd ed, pp. 295-390. I need to explain >instance variables. > >What I'm looking for is the best compromise between brevity and a full >explanation. The students are non-CIS technical professionals ( >engineers and scientists ). At the point they need this explanation, >they have covered functions and modules, but not classes. They are >new to object-oriented programming. They have just been shown a class >definition with some data attributes and methods. > >The non-CIS background is important, because I can't assume any >experience with other computer languages. > >I would like to hear from users who have a similar background, or >anyone who has taught such users. What is your background? Which of >the alternatives below do you like or dislike? Can you think back on >your own learning experience, and write something better? > >Here are some alternatives I have collected: > [... snip ...] > >===================================== > >Thanks for your help on this project. > I find well-annotated examples best for understanding something new. It also gives me working code to play with, to explore variations. How things break is often as instructive as how they work. I would suggest you encourage your students to experiment interactively. E.g., ask who can explain the following, and see what you get, and then collaborate with them to write sufficient comments to where they feel they "get it." >>> class C(object): pass ... >>> def f(*args): print 'f was called with', args ... >>> f('hello') f was called with ('hello',) >>> c=C() >>> c.f('hi') Traceback (most recent call last): File "", line 1, in ? AttributeError: 'C' object has no attribute 'f' >>> c.f = f >>> c.f('hi') f was called with ('hi',) >>> C.f = f >>> c.f('greetings') f was called with ('greetings',) >>> del c.f >>> c.f('greetings') f was called with (<__main__.C object at 0x00901330>, 'greetings') MRO can wait a little ;-) Regards, Bengt Richter From HughMacdonald at brokenpipefilms.com Thu Apr 15 11:34:30 2004 From: HughMacdonald at brokenpipefilms.com (Hugh Macdonald) Date: Thu, 15 Apr 2004 16:34:30 +0100 Subject: CamelCase versus wide_names (Prothon) In-Reply-To: References: Message-ID: <20040415163430.1ef4419a.HughMacdonald@brokenpipefilms.com> On Thu, 15 Apr 2004 08:17:08 -0700 "Mark Hahn" wrote: > pretend you were picking your standard from > scratch (as we are doing in the Prothon world) and give your vote for > which you'd prefer? I've not really been following Prothon in general, but I'm happy to give my opinion on this.... I think most people use whatever they 'grew up with' (in the programming sense...). I started programming in UnrealScript (Unreal/UnrealTournament coding) and I still use the naming schemes that they used in their code... camelCaseAllTheWay (unless I'm extending someone else's code and they've used wide_names) I also use kinda-hungarian notation, in that all of my boolean (or pseudo-boolean) variables are: bVariable (by pseudo-boolean I mean an int acting as a boolean, for example) When I'm reading code, this makes sense, as I read: if bTurnedOn: as If be turned on: Anyway, I think the answer that you're looking for from me is camelCaps all the way.... -- Hugh Macdonald The Moving Picture Company From heikowu at ceosg.de Tue Apr 27 17:35:05 2004 From: heikowu at ceosg.de (Heiko Wundram) Date: Tue, 27 Apr 2004 23:35:05 +0200 Subject: Tkinter vs. wxPython? In-Reply-To: <3Xzjc.459$6A2.9498@nnrp1.ozemail.com.au> References: <408E9DCA.EC753FE6@shaw.ca> <3Xzjc.459$6A2.9498@nnrp1.ozemail.com.au> Message-ID: <200404272335.05760.heikowu@ceosg.de> Am Dienstag, 27. April 2004 23:06 schrieb Peter Milliken: > I haven't remained in touch with > the wxPython community, but last I heard, that book on wxPython was still > in the "real soon now" category :-) There's a german book on GUI Programming with Python, which covers Tkinter, wxPython, PyQT and PyGTK+ 2... I actually liked the read, the author creates a lightweight contact management program in each of the four, and discusses step by step how the functionality is implemented, showing the differences between the event handling code in each of the four, etc. You might wonder how he achieves to go through all four different programming environments in a single book, but I think he manages quite well to keep it simple and short, and showing relevant links to the available documentation where it is needed as a starting-point for further projects. Anyway, if anybody's interested: Name: Python und GUI-Toolkits Author: Michael Lauer ISBN: 3-8266-0844-5 Publisher: mitp-Verlag First published in 2002 (I have the first edition, IIRC there's a second edition out already) I can only recommend to have a look at this book if you speak german,learn easily from example, and would like to get insight knowledge on GUI-Programming with Python... Heiko. From peter.maas at mplusr.de Tue Apr 20 08:19:29 2004 From: peter.maas at mplusr.de (Peter Maas) Date: Tue, 20 Apr 2004 14:19:29 +0200 Subject: Dollar sign ($) on foriegn keyboards? (prothon) In-Reply-To: References: Message-ID: Peter Otten wrote: > In Germany every serious programmer has to switch to the American > layout anyway because of {}[]@\~| (all odd AltGr combinations). Oh, I didn't know that. Fortunately I'm not a serious programmer. ;) Mit freundlichen Gruessen, Peter Maas -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Hubert-Wienen-Str. 24 Tel +49-241-93878-0 Fax +49-241-93878-20 eMail peter.maas at mplusr.de ------------------------------------------------------------------- From joe at notcharles.ca Sat Apr 17 02:02:16 2004 From: joe at notcharles.ca (Joe Mason) Date: Sat, 17 Apr 2004 06:02:16 GMT Subject: AOP use cases References: <84fc4588.0404140106.3fa0c55@posting.google.com> <0pydnSB4WYuieuLdRVn-hQ@powergate.ca> <35qdnT4kNsX1kB3dRVn-gg@powergate.ca> Message-ID: In article <35qdnT4kNsX1kB3dRVn-gg at powergate.ca>, Peter Hansen wrote: > The logging example is okay, yes, but another problem I have > with it is that it's very development-oriented. It doesn't > do anything directly for the user in terms of helping implement > user functionality. Same goes for the contract aspect, which It does if generating usage reports is a user requirement. Call logging in a telephony app, for instance. Joe From andrew.henshaw at gtri.gatech.edu Fri Apr 2 16:05:46 2004 From: andrew.henshaw at gtri.gatech.edu (Andrew Henshaw) Date: Fri, 2 Apr 2004 21:05:46 +0000 (UTC) Subject: Making the Zen of Python more useful References: Message-ID: In article , n3613 at klaff.org says... > > >from this import s >s.decode('rot13') > Thanks for the response. Unfortunately, this still has the (generally desired) behavior of the text being printed to stdout. For the less general case of using the text to feed some test code, I don't think that is best. Unfortunately, I can't think of a way to accomplish both by simply modifying the 'this' module (for future releases). Adding another module would do it; but, I was hoping someone could suggest a better way. -- Andy From try_vanevery_at_mycompanyname at yahoo.com Mon Apr 26 18:02:16 2004 From: try_vanevery_at_mycompanyname at yahoo.com (Brandon J. Van Every) Date: Mon, 26 Apr 2004 15:02:16 -0700 Subject: How's ruby compare to it older brother python References: <108qk9dft7h7o52@corp.supernews.com> Message-ID: Phil Tomson wrote: > In article , > Brandon J. Van Every wrote: >> >> You need a filter of some kind for cutting down the options. I >> suggest asking people, and seeing what languages actually got used >> for jobs relevant to your software problem / industry. > > It seems as though he has already done this. He may very well have... I'm late to the thread. Consider it embedded advice for anyone *other* than him who may be reading, now or in the future. -- Cheers, www.indiegamedesign.com Brandon Van Every Seattle, WA "Trollhunter" - (n.) A person who habitually accuses people of being Trolls. From jcarlson at uci.edu Sun Apr 4 14:40:43 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Sun, 04 Apr 2004 11:40:43 -0700 Subject: Recursively expand all branches ox wxTreeCtrl In-Reply-To: <39cbe663.0404032353.6944c9fe@posting.google.com> References: <39cbe663.0404032353.6944c9fe@posting.google.com> Message-ID: Try the following modifications... def OnPopup1(self,event): item = self.Tree.GetSelection() self.parent.msgbox(self,self.Tree.GetItemText(item),"Kein Titel",wxOK) #self.Tree.Expand(item) * self.ExpandCompleteBranch(self.Tree,item,wxNewId()) def ExpandCompleteBranch(self,tree,treeitem,cookie): self.parent.msgbox(self,"Durchlauf "+str(cookie),"Kein Titel",wxOK) if tree.ItemHasChildren(treeitem): lastchild = tree.GetLastChild(treeitem) tree.Expand(treeitem) (child,cookie) = tree.GetFirstChild(treeitem,cookie) self.ExpandCompleteBranch(tree,child,cookie+1) while child != lastchild: * #cookie = cookie + 1 (child,cookie) = tree.GetNextChild(treeitem,cookie) * self.ExpandCompleteBranch(tree,child,wxNewId()) I use wxNewId() for cookie ids so that all calls will have unique cookie ids. I'm not sure this is technically necessary, but it can't hurt. Also, by altering the cookie id during the while loop, you are destroying the cookie that is necessary to access the remainder of the branch. Give the above (without the '*' at the beginning of the line) a try. - Josiah From simoninusa2001 at yahoo.co.uk Sun Apr 11 17:31:09 2004 From: simoninusa2001 at yahoo.co.uk (simo) Date: 11 Apr 2004 14:31:09 -0700 Subject: solaris install of python References: Message-ID: <30260531.0404111331.78b681d7@posting.google.com> ActiveState have an "AS installer" for Solaris8 - it doesn't even need root access. From jacek.generowicz at cern.ch Mon Apr 26 07:04:06 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 26 Apr 2004 13:04:06 +0200 Subject: Magic methods in extension types Message-ID: I am writing an extension type, and wish to add some magic methods which are not catered for by the tp_ slots (eg tp_init -> __init__) in PyTypeObject. My methods seem to work correctly when invoked explicitly (eg obj.__iadd__(3)) but the method seems not to be associated with the corresponding operator (ie obj += 3 does NOT work). What am I likely to be doing wrong ? From jdhunter at ace.bsd.uchicago.edu Fri Apr 16 10:33:15 2004 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Fri, 16 Apr 2004 09:33:15 -0500 Subject: datetimes, tzinfo and gmtime epoch Message-ID: I have a python2.3 datetime instance and a tzinfo instance (eg Eastern from the python library reference). What is the best way to convert that datetime instance to seconds since the epoch, gmtime? s1 = '2-Apr-04' # before dst s2 = '5-Apr-04' # after dst y,month,d,h,m,s,wd,jd,ds = time.strptime(s1, '%d-%b-%y') dt1 = datetime.datetime(y,month,d,h,m,s,tzinfo=Eastern) y,month,d,h,m,s,wd,jd,ds = time.strptime(s2, '%d-%b-%y') dt2 = datetime.datetime(y,month,d,h,m,s,tzinfo=Eastern) print dt1, Eastern.utcoffset(dt1) print dt2, Eastern.utcoffset(dt2) But I'm not sure how to convert this to epoch gmtime .... Thanks, John Hunter From cybermanxu at hotmail.com Thu Apr 22 12:02:07 2004 From: cybermanxu at hotmail.com (Jinming Xu) Date: Thu, 22 Apr 2004 11:02:07 -0500 Subject: A python telnet entry level question Message-ID: Eddie, Thank you very much for your answer. I checked the prompt of the server, findint its prompt is "login:", in stead of "login: ". That's all the problem I have. Thanks again. Have a nice day! Jinming >From: eddie at holyrood.ed.ac.uk (Eddie Corns) >To: python-list at python.org >Subject: Re: A python telnet entry level question >Date: Thu, 22 Apr 2004 10:11:23 +0000 (UTC) > >"Jinming Xu" writes: > > >Hello Everyone, > > >I am trying to write a python script to telnet to a server and then do > >something there. As the first step, I practiced the python example in Lib > >Reference 11.13.2. But I am finding the script stops after I supplied the > >password. Does anyone know why? > > > >Thanks in advance! > > >Jinming Xu > > >PS: Here is the script: > > >import getpass > >import sys > >import telnetlib > > >HOST = "localhost" > >user = raw_input("Enter your remote account: ") > >password = getpass.getpass() > > >tn = telnetlib.Telnet(HOST) > > >tn.read_until("login: ") > >tn.write(user + "\n") > >if password: > > tn.read_until("Password: ") > > tn.write(password + "\n") > > >tn.write("ls\n") > >tn.write("exit\n") > > >print tn.read_all() > >You are maybe being too specific in what you match for. At least one of my >machines prompts: > > Pasword for : > >rather than just "Password: ". I tend to match things like > >"ogin" (in case of Login vs login) >"assword" (will this get filtered out by censoring s/w?) > >Eddie >-- >http://mail.python.org/mailman/listinfo/python-list _________________________________________________________________ MSN Toolbar provides one-click access to Hotmail from any Web page ? FREE download! http://toolbar.msn.com/go/onm00200413ave/direct/01/ From bignose-hates-spam at and-benfinney-does-too.id.au Fri Apr 2 19:32:47 2004 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 3 Apr 2004 10:22:47 +0950 Subject: Making the Zen of Python more useful References: Message-ID: On Sat, 03 Apr 2004 00:23:45 GMT, Joe Mason wrote: > I'm assuming that providing and printing the Zen of Python is the > module's main purpose, BTW, since I'm not familiar with it. What is > the 'this' module, anyway? It's a name that's pretty much impossible > to Google for... No need to assume or search Google. It's part of the Python distribution: >>> import this The Zen of Python, by Tim Peters [...] >>> this.s "Gur Mra bs Clguba, ol Gvz Crgref\n\nOrnhgvshy [...] You're right that, if we're going to be separating the "make the Zen available" functionality, then the "this" module should wrap the "make Zen available" module, instead of some new module wrapping "this" and disabling its output. -- \ "If you go flying back through time and you see somebody else | `\ flying forward into the future, it's probably best to avoid eye | _o__) contact." -- Jack Handey | Ben Finney From http Thu Apr 15 20:37:47 2004 From: http (Paul Rubin) Date: 15 Apr 2004 17:37:47 -0700 Subject: Difficulty Finding Python Developers References: <65cbc3dd.0404140641.3501fde8@posting.google.com> <5d83790c.0404150701.605782a7@posting.google.com> <7xpta8hqe7.fsf@ruckus.brouhaha.com> Message-ID: <7xsmf4kbac.fsf@ruckus.brouhaha.com> Roy Smith writes: > > I think anyone using Python in a serious production project has to be > > ready to extend or debug the library modules and/or write new C > > extensions. > > I guess it depends on what you mean by "serious production project". > I've played with several of the extension APIs just to get a feel for > what they're like, but I've never actually used any of them in anger. Yes, the point is you never know when you're going to need to use it, and having a deadline breathing down your neck isn't the right time to learn about it. Especially in a startup company, there are just too many situations where the fate of the whole company depends on your making something work RIGHT NOW, sometimes even with an investor or customer looking over your shoulder. > Of course, I've used plenty of add-on modules (DB, LDAP, SNMP, etc), but > I just downloaded them and started using them. Certainly, *somebody* > had to muck about in the C API (or SWIG, or Boost, or whatever) to get > that done, but I've never felt the need. Oh yes, that brings up another matter, there's tons of stuff that's just plain *missing* from the library, like DB, LDAP, SNAP, web templates, GUI components that look less crude than TKinter, cryptography, etc. Sure, that stuff is around in various third party libraries, but you have to get a sense of what kind of stuff is out there and know where to find it, and that takes more acclimation to Python than you can get in a weekend. And now, instead of just deciding that Python is stable enough for your needs, you have to make a similar decision about each of those third party projects (see below). > Of course, I learned C in the days when it was assumed that anybody > doing any "serious production project" in C would have to be able to > dive into assembler once in a while :-) I think this is still true. It's certainly happened in projects that I've worked on recently. > > There are just too many surprising little gaps in the > > standard library and you run into them when you least expect it. > > I'm sure there are, but can you give some examples of ones you've > run up against? Here are a few, besides the missing modules described earlier: 1) Python's regexp module has no way to search backwards in a string for a regexp, i.e. find the last occurence of the regexp before location x. This is useful for things like text editors and web robots (at one point I was writing a lot of web robots that wanted it). The underlying C library takes a direction flag, but the Python wrapper doesn't give any way to set the flag. Python's string module has an rfind operation for substrings, but it doesn't do regexps. I've had an SF bug open for this for at least a year. I haven't bothered doing a patch, since I've been able to find kludgy workarounds for my specific requirements, but I if were trying to deliver a product to customers, then the kludges wouldn't be acceptable and I'd have to fix the library. 2) The socket module doesn't support ancillary messages for AF_UNIX sockets. Ancillary messages are used to pass file descriptors between processes (e.g. you can have a daemon that gives unprivileged processes access to privileged network ports) and for passing credentials around (you can have a server check the login ID of a client process). I opened an SF bug and was invited to submit a patch, which I might get around to doing sometime, but I instead just didn't bother implementing the feature I was thinking about that needed it. In a project with more urgency, I would again have had to stop what I was doing and code that patch. I will have to do it if I ever release that particular piece of code to the public, since without the feature, the code can only run in some constrained ways that I don't want to impose on users other than myself. 3) There's no access to the system random number generator (CryptGenRandom) in Windows, needed for all kinds of security purposes (not just cryptography). There are no published or supported third party modules for it either, AFAIK. There's a nice one that's been floating around informally, but I know about that only by having been on the right mailing lists at the right time. It does look like that may make it into the library soon; however, in a production environment you can't rely on such luck. When things need to happen, you have to be able to *make* them happen. 4) There's no built-in cryptography module, for partly technical and partly political reasons. I found and downloaded a third-party AES module and it seemed to work, so I put it in my program. But of course, any assurances you (or your manager) might feel about Python based on its code stability and QA process don't apply to third party modules. And sure enough, the AES module had a memory leak that made it unusable in a long-running server. Finding and fixing the leak took something like a whole day of figuring out not only how the C API worked but also how the SWIG wrapper worked. I don't blame the module developer, since he had coded it as a personal project and released it for free, and he never made any of the kind of marketing claims for it that are sometimes made for Python. But there's a case where you can deploy code into production, see it seem to work fine until your site is getting a lot of traffic, and then your site starts crashing and you have to fix it immediately and there's NO way to fix it except by messing with the C API while you're under a lot of pressure. There are also any number of missing things for which there's a workaround, but you're not necessarily likely to discover that workaround so easily. For example, in cryptography you often have to convert 1024 bit integers to 128-byte character strings and vice versa. How would you do it in Python? It turns out there's a pretty fast way (I'll let you figure it out for yourself) but at least in my case, it took a fair amount of head scratching to hit on it. I think with just a weekend of Python exposure, it would have been quite hard to spot something like that. > > And the C API is quite cumbersome and not something a typical > > programmer can really come up to speed on in a weekend. > > No debate about that, but the C API is (IMHO) a very advanced topic and > something that only a small fraction of Python programmers would ever > need even know exists. You certainly don't need to know about it to get > useful work done with a basic subset of the language. I have no doubt that you can get useful work done with a basic subset, but being a solid developer calls for a much higher standard than "get useful work done". You're trying to do things that nobody else is doing, which pretty often means you're trying to push something to its limits, and you can't always wait around for answers from other people. From http Mon Apr 5 01:36:49 2004 From: http (Paul Rubin) Date: 04 Apr 2004 22:36:49 -0700 Subject: Siginificant figures calculating zprob References: <9405c70f.0404031852.155d17d5@posting.google.com> <9405c70f.0404042109.55b9f827@posting.google.com> Message-ID: <7xad1r9ea6.fsf@ruckus.brouhaha.com> sarah_wang23 at hotmail.com (Sarah Wang) writes: > > > But the problem is that the function calculates the result > > > with only a few significant figures. If I want to get the > > > 20th number of the result(z-prob) what should I do? > > > > Why would you need this degree of precision? > > I'm doing some exploration into the statistical part of "Six Sigma" > (as someone on the thread noted) with my most powerful exploratory > tool "Python Interactive Shell". :) The thing is you don't really need all that precision even still. Math libraries usually implement the error function in two forms, erf(x) which is basically what you call z, and erfc(x) which is 1-erf(x). So when erf(x) is close to 1, erfc(x) is close to 0 and therefore has an accurate floating point representation. You don't get the precision loss of subtracting two nearly equal floats, so you don't need so much precision to start with. From joe at notcharles.ca Thu Apr 15 15:38:29 2004 From: joe at notcharles.ca (Joe Mason) Date: Thu, 15 Apr 2004 19:38:29 GMT Subject: Aspect Programming Module References: <84fc4588.0404140106.3fa0c55@posting.google.com> <8ef9bea6.0404142155.90b41ef@posting.google.com> <407E394B.2050709@mxm.dk> Message-ID: In article <407E394B.2050709 at mxm.dk>, Max M wrote: > Hung Jung Lu wrote: > >> Python does not even have codeblocks. So how can you say AOP is not >> needed for Python programmers? > > I am probably rather dense, but I have not seen aspect oriented examples > that could not have been done with simple mixins. > > Isn't it needed in Java because it doesn't have multiple inheritance? AOP is a design technique, not just a set of tools. If it's true that you can just use simple mixins in Python to get the same effect as ApectJ, then you can say, "AOP is implemented on Python with mixins, but Java requires language extensions such as AspectJ." That doesn't mean Python doesn't "need" AOP - nobody really "needs" it, they just find it a useful way of approaching problems, and moving to Python doesn't make it a less useful approach. In fact, if it's easier on Python, it's more useful. Joe From drs at remove-to-send-mail-ecpsoftware.com Sat Apr 17 02:30:14 2004 From: drs at remove-to-send-mail-ecpsoftware.com (drs) Date: Sat, 17 Apr 2004 06:30:14 GMT Subject: Passing COM VB6 strings weirdness References: Message-ID: "U-CDK_CHARLES\Charles" <"Charles Krug"@cdksystems.com> wrote in message news:z3Rfc.66372$QQ6.4420 at nwrdny02.gnilink.net... > List: > > I've a Python COM server that keeps an event logs. > > I've been using it from VB6: > > * * * > > When I log certain events from VB, I also display a message box for the > user or for me, depending on the specific message. > > If I call messageBox BEFORE I invoke logEntry, all is well. > > BUT if I invoke logEntry first, the passed string becomes a literal > zero. > > Any thoughts on this? I'm not certain why I'm getting the returned > value from this at all, let alone why it's being assigned to the > argument string. I don't know if this is the same thing, but I have found that often passing variables from VB to Python COM servers mucks up the variables on the VB side. I think I have posted this issue here (probably a few years back), but I have never gotten a reason why -- i think. Also, I have never really pinned down exectly what circumstances lead to it. Instead, I have gotten used to declaring two identicle variables in VB when I need to do what you are doing. It is an awful hack, but it works. Sorry for such a lame answer. -doug From jmeile at hotmail.com Wed Apr 21 14:31:52 2004 From: jmeile at hotmail.com (Josef Meile) Date: Wed, 21 Apr 2004 20:31:52 +0200 Subject: Python 2.3.3 super() behaviour In-Reply-To: References: <40863bd7$0$25528$afc38c87@news.easynet.fr> Message-ID: <4086bdfc$1@pfaff2.ethz.ch> Peter Otten wrote: > As soon as a test() method without the super(...).test() is reached, no > further test methods will be invoked. Only the first in the list of base > classes will be invoked. If I'm getting it right you have to do something > like: > > class Base(object): > def test(self): > print "base" > > class D1(Base): > def test(self): > super(D1, self).test() > print "derived 1" > > class D2(Base): > def test(self): > super(D2, self).test() > print "derived 2" > > class All(D1, D2): > pass > > All().test() Ok, this produces almost what the original poster wanted. You just have to invert the order of the base classes in All: >>>class All(D2, D1): ... pass ... then you will get: >>> All().test() base derived 1 derived 2 However, I don't understand jet why this doesn't print: base derived 1 base derived 2 The method test of Base is called just once? Why? I taught it was something like: All.test() -> D1.test() + D2.test() which is the same as: (Base.test() + print "derived 1") + (Base.test() + print derived 2") Thanks in advanced, Josef From jepler at unpythonic.net Wed Apr 21 22:20:06 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 21 Apr 2004 21:20:06 -0500 Subject: zip 2 sequences into 1 In-Reply-To: References: Message-ID: <20040422022005.GA18172@unpythonic.net> def flatten(s): for i in s: for j in i: yield j flatten(zip([1,2,3], "abc")) Jeff From fredrik at pythonware.com Fri Apr 23 07:17:25 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 23 Apr 2004 13:17:25 +0200 Subject: [Q] C-api: string|int|... construction References: <788E231C269961418F38D3E360D165259B408C@tndefr-ws00021.tenovis.corp.lan> Message-ID: Ames Andreas wrote: > is it possible (within a C extension) to create a python string (or > integer or other type) from an existing C string *without* copying the > string? *you* don't need to copy the string; if you create an object that needs a copy, the type constructor will copy it for you. you cannot create Python string objects that point to your own strings. if you want to create a string-like object that points to your own C strings, create your own type and implement the buffer interface. see the "extending and embedding" and "c api" documents for details. (but note that unless you're talking about strings in the 100+ megabyte range, or run on relatively old hardware, chances are that you're wasting your time. modern computers can copy things really, really fast). From skip at pobox.com Sun Apr 11 20:38:26 2004 From: skip at pobox.com (Skip Montanaro) Date: Sun, 11 Apr 2004 19:38:26 -0500 Subject: print u"\u0432": why is this so hard? UnciodeEncodeError In-Reply-To: References: Message-ID: <16505.58626.39783.581506@montanaro.dyndns.org> Martin> I wonder how much would break if Python would assume the Martin> terminal encoding is UTF-8 on Darwin. Do people use different Martin> terminal encodings? I generally use xterm instead of Terminal.app. I think it's encoding is latin-1. Skip From jepler at unpythonic.net Fri Apr 9 16:54:56 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Fri, 9 Apr 2004 15:54:56 -0500 Subject: Python-2.3.3 install -> no "make" In-Reply-To: <2278156.F9pO2Pa3OA@Lumina-verte.org> References: <2278156.F9pO2Pa3OA@Lumina-verte.org> Message-ID: <20040409205456.GB19461@unpythonic.net> "make" is a program that is installed on most Unix-type systems with the compiler. It maybe /usr/bin/make, /usr/local/bin/gmake, or somewhere else. If you don't have it, you'll need to install it. "Makefile" is the file read by make, which contains rules for building Python. Jeff From simoninusa2001 at yahoo.co.uk Thu Apr 1 11:33:53 2004 From: simoninusa2001 at yahoo.co.uk (simo) Date: 1 Apr 2004 08:33:53 -0800 Subject: Python conference slogan References: Message-ID: <30260531.0404010833.1b834032@posting.google.com> Peter Maas wrote: > I surrender immediately and have to admit that I don't get it (One > Nation Under Under Python). Google was no help. I couldn't find the > source, only echoes (seems to be a wide spread joke pattern in the > US). Care to give us ignorants a hint? Yeah, as an Englishman, I don't get it either (despite living in the US). Is it some sort of Bush/Iraq joke again (Americans are obsessed with them)? What about, "Don't be constricted by Java, try Python"? From mark at prothon.org Wed Apr 21 14:31:30 2004 From: mark at prothon.org (Mark Hahn) Date: Wed, 21 Apr 2004 11:31:30 -0700 Subject: Dollar sign ($) on foriegn keyboards? (prothon) References: Message-ID: <66zhc.19122$dZ1.9432@fed1read04> "Fredrik Lundh" wrote in ... > you can get a lot better results and generate a lot > less noise by doing a web-based questionaire, and > post a single invitation here > and in other forums where Pythoneers gather. That is a very good idea. I will do that in the future. Of course, people will still start babbling on the list about the question anyway, but that I can't control. > strangely enough, I don't see any top Pythoneers contributing to the Prothon > threads. who are they? Oh, you are calling my bluff, eh? I remember Tim Peters off the top of my head, I'd have to go back through the archives to find the others. Do you want urls of the archived messages ? From nish20 at netzero.net Thu Apr 15 10:18:27 2004 From: nish20 at netzero.net (Mike Nishizawa) Date: 15 Apr 2004 07:18:27 -0700 Subject: OFF-TOPIC:: Why Lisp is not my favorite programming language References: <165b3efa.0403030443.4d591f04@posting.google.com> <40460dd5$0$5916$7a628cd7@news.club-internet.fr> Message-ID: Jacek Generowicz wrote in message news:... > nish20 at netzero.net (Mike Nishizawa) writes: > > > If it beats LISP at it's own game which is, list processing, > > > an especially good application for a LISt Processing language. > > [lots more uninformed garbage elided] > > Please get a clue about what Lisp is in the 21st century (hell, even > what it was in the last 2 decades of the 20th century), before posting > any more of your drivel. > > For example, you could look at http://franz.com/success/ for a little > insight into what is being done (mereyly by processing lists and > parsing files, according to your view of the world) in Lisp today. 2 words pal, settle down. If you weren't such a fanatic you would realize that we are not not saying anything that different. I have simply used a different, more simple example. I learned AI development with LISP. I have used it in web applications in the past. I realize that it is used for more advanced applications and I am not limiting the functionality of it to a parser. I am saying that it's native functionality is list processing and had to defend my earlier position that it makes it good for parsing files because you seem to want to zealously attack me if I don't present LISP in it's greatest possible light. The original point of the post was simply to say one language is the best for all applications is stupid. If you plan to develop something, choose the language that it is most suited to solving the problem instead of trying to say that EVERYTHING from drivers to enterprise applications should be developed in one language. If I had known you were out there ready to pounce on anyone who might give a simple example of LISP and therefore, in your opinion, simplify the language or what it can do, I would have said AI instead of parser and saved myself the trouble of being persecuted by a zealot. From rjgruet at yahoo.com Sat Apr 10 19:11:16 2004 From: rjgruet at yahoo.com (Richard Gruet) Date: Sun, 11 Apr 2004 01:11:16 +0200 Subject: new-style class instance check Message-ID: Hi all, How to determine that an object o is for sure an instance of a new-style class, without knowing of which specific class ? That is, if I define a function: def isNewStyleClassInstance(o): pass ## to be completed .. I want to pass the following test: def C: pass def CNew(object): pass assert not isNewStyleClassInstance(C()) # InstanceType assert isNewStyleClassInstance(CNew()) assert not isNewStyleClassInstance(1) # instance of type int # and naturally for all other types of o the function should return False. Richard From rick.ratzel at magma-da.com Wed Apr 28 14:16:02 2004 From: rick.ratzel at magma-da.com (Rick Ratzel) Date: Wed, 28 Apr 2004 13:16:02 -0500 Subject: Good examples for Embedding python in C, C++ In-Reply-To: References: Message-ID: <408ff4e3$0$3714$39cecf19@news.twtelecom.net> I did a presentation on this very topic at PyCon this year: http://elmer.sourceforge.net/PyCon04/elmer_pycon04.html ...and here is the complete example code: http://elmer.sourceforge.net/PyCon04/Elmer_PyCon04.tgz You can use Elmer (http://elmer.sourceforge.net) to automatically generate the C equivalent to a Python API. When run in "frozen" mode, the resulting application is self-contained...but when run in "warm" mode, a user can modify the python sources without any code recompilation, like you said. -Rick Ratzel Henko Gouws (H) wrote: > Hallo > > I am looking for good examples on how to call a python script from C, > C++ and pass parameters (list of strings) to the python script. The > aim is to ultimately allow the end-user to modify the python script, > without any code recompilation, to suit the needs of the end-user. > The C, C++ part will remain intact. > > I could not find good examples, that could help me with this, in the > references from python.org. I would appreciate your help. > > thanks > Henko > From imbosol at aerojockey.invalid Thu Apr 1 02:23:13 2004 From: imbosol at aerojockey.invalid (Carl Banks) Date: Thu, 01 Apr 2004 07:23:13 GMT Subject: From python-dev, space vs. tab controversy finally settled Message-ID: Here's a summary of the final decision Guido made concerning how Python will indent code in the future, from python-dev: Guido had been planning to deprecate tabs in favor of spaces for awhile, although there have been good arguments for both tabs and spaces. But he was never really comfortable pulling the rug out from half the user base. However, today he finally decided on a compromise that has all the benefits of both spaces and tabs. His decision was predicated by the recent decision of the Unicode Consortium to allocate some new codes for special use in programming languages. The Consortium allocated codes for (among other things): several sets of left and right braces, several sets of quote characters, a couple universal comment markers, and several metacharacters for use in regular expressions. However, the code that influenced Guido was a special indent code. Here's how it works: at the beginning of the line, you put in one "indent character" for each level of indentation. Because Python will support Unicode fully by 3.0, Guido decided that this new Unicode character will be the one and only way to indent Python code. Now, I'm sure everyone's aware that Unicode is getting kind of full, and so, rather than allocating precious ununsed slots to the new programming characters, the Consortium decided reallocate some codes that had been rarely used. These codes fall in the range 0001 through 001F, excepting 000A and 001A (all codes in hexadecimal). The new indent character has code 0009. So, you should start using Unicode character 0009 to indent right away. Python 2.4 will deprecate all indentation not using the new indent character, and Python 3.0 will not support any other indentation. -- CARL BANKS http://www.aerojockey.com/software "If you believe in yourself, drink your school, stay on drugs, and don't do milk, you can get work." -- Parody of Mr. T from a Robert Smigel Cartoon From jcarlson at uci.edu Thu Apr 1 19:20:43 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Thu, 01 Apr 2004 16:20:43 -0800 Subject: emergent/swarm/evolutionary systems etc In-Reply-To: References: Message-ID: > rules. Given that I have only a basic foothold on the language, does > anybody foresee difficulties for me learning enough to impliment simple and > experimentally flexible sim-city style simulations (minus fancy graphics and > llamas) in no more than 2 months (to allow for time to conduct actual > experiments + field observations etc)? I would be able to engender aid from > various staff, and the university library should carry titles on the > subject. Failing that, I could do it the old fashioned way and buy a how-to > book, but I'd like some opinions on the difficulty of the goal from people > who've already trancended the non-programmer/programmer barrier. Two months is a pretty tight schedule. If you're on your toes, I would bet you could learn enough of the langauge to support your ideas in 2 months. Actually programming the thing in 2 months; I wouldn't be able to make that kind of judgement about your abilities. I wish you luck. - Josiah From graham__fawcett at hotmail.com Fri Apr 23 10:55:25 2004 From: graham__fawcett at hotmail.com (Graham Fawcett) Date: 23 Apr 2004 07:55:25 -0700 Subject: Python-list, Exotic sex is urgently necessary for you! References: Message-ID: Timo Virkkala wrote in message news:... > [disgusting content snipped] > > I've heard of sex with lots of kinds of animals, but Pythons? Wouldn't > that be a) difficult b) VERY dangerous? It's no surprise you're not into snakes, Timo. Everyone knows that Finns have fixations for flightless, fat waterfowl. BTW, I think that "Python-list, Exotic sex is urgently necessary for you!" should be the slogan for the next PyCon conference. It would definitely increase registrations. -- Graham From PeterAbel at gmx.net Tue Apr 13 12:12:05 2004 From: PeterAbel at gmx.net (Peter Abel) Date: 13 Apr 2004 09:12:05 -0700 Subject: how to break tuple to separate variables References: Message-ID: <21064255.0404130812.529c98f8@posting.google.com> Stano Paska wrote in message news:... > Hi. > > I need pass variables to function like tuple, but function accepts > separate variables. > > Is there some elegant solution? > > My example: > > # ------------------------------- > import datetime > > def date2tuple(aaa): > try: > y = int(aaa[:4]) > m = int(aaa[5:7]) > d = int(aaa[8:10]) > except: > y = m = d = 0 > return (y, m, d) > > # i need some like this > bbb = datetime.date(date2tuple('2004-11-03')) > > # but date requires > bbb = datetime.date(2004, 11, 03) > > # ------------------------------- > > Thanks. > > Stano Paska Sorry, I didn't read your post seriously enough. >> map(int,'2004-11-03'.split('-')) [2004, 11, 3] bbb = datetime.date(*map(int,'2004-11-03'.split('-'))) as Paul Rubin pointed out. Regards Peter From python at rcn.com Fri Apr 16 07:19:37 2004 From: python at rcn.com (Raymond Hettinger) Date: 16 Apr 2004 04:19:37 -0700 Subject: Automatic, portable optimization of global access References: <5d83790c.0404150721.46a3b5d0@posting.google.com> <7xvfk17zeg.fsf@ruckus.brouhaha.com> <5d83790c.0404151803.598c1807@posting.google.com> <7xbrlseclf.fsf@ruckus.brouhaha.com> Message-ID: <5d83790c.0404160319.f46f2f9@posting.google.com> [Paul Rubin] > Well, it's possible that builtins get changed too. I've used "len" as > a variable a few times without realizing that I was clobbering a builtin. Paul, I don't know how to say this more clearly. Don't use constant binding in places where the underlying values can change. Raymond From kfast at poczta.onet.pl Tue Apr 13 18:59:59 2004 From: kfast at poczta.onet.pl (Jakub Fast) Date: Wed, 14 Apr 2004 00:59:59 +0200 Subject: Does Python compete with Java? In-Reply-To: References: <8b336527.0404051337.51bb4a1b@posting.google.com> Message-ID: <407C70EF.7080100@poczta.onet.pl> > No, it isn't. People would not like it because it looks like line noise. I guess that qualifies as a definite answer. Shame, though, in my stubborn and incorrigible ways i still kind of think a well-constructed operator saves the day, especially when exposing your language in a "custom" environment, such as embedded scripting or a neatly defined collection of 'special' tasks. Of course you can always resort to getting the user to provide text files that you parse yourself according to some custom grammar (which is what i'll probably end up doing), but that has disadvantages in regards to a nice side effect of getting people to pick up some python on the way and actually feel like they're really programming. and yes, i do think this is enough of a reason to look at other languages that do permit op overloading for you embedded scripting in some cases (like when you don't want to confuse the average user too much and make typical tasks as easy as possible while retaining the versatility of a full-fledged language). of course custom operators (if they permit alphanumeric shapes for instance...) can make one major mess of your code, but then, isn't the zen of python more along the way of: "the master hits the student repeatedly with a stick and the student experiences enlightenment" rather than "the master takes the toys away from the student". Is just the inclusion of a feature like this into the language considered evil, especially taking into account that it does not intervene with whatever else there is in the language? >> S ==> (NP and VP) or VP > > If it is the structure, you should be able to write this as > > S.implies(NP.and_(VP).or_(VP)) > This is completely fine and actually quite cool if you've had your OO practice, but the point is that the parts you actually felt missing and which made my formulation unreadable to you are absolutely obvious for anyone who has had anything to do with linguistics -- which definitely would be the case with whomever i'd show the module to :) -- and the sample form i give would require 0.5 degrees of learning effort, as opposed to 10.5 degrees or way more if you're completely new to programming. Is there really no chance this goes into python on an "if you really have to do this, be warned, but here are the tools" basis? Anyway, hope i'm not boring you to death and thank you for your answers Kuba From michael at foord.net Mon Apr 19 03:14:02 2004 From: michael at foord.net (Fuzzyman) Date: 19 Apr 2004 00:14:02 -0700 Subject: Wrapper round x86 Assembler References: <8089854e.0404082353.7bf163a2@posting.google.com> <2ae25c6b.0404100840.10668dca@posting.google.com> Message-ID: <8089854e.0404182314.2c9b8dba@posting.google.com> paddy3118 at netscape.net (Paddy McCarthy) wrote in message news:<2ae25c6b.0404100840.10668dca at posting.google.com>... > michael at foord.net (Fuzzyman) wrote in message news:<8089854e.0404082353.7bf163a2 at posting.google.com>... > > There might be a really good reason why this hasn't been done *or* > > someone might have done it and I just can't find it..... *but* > > > > what about a wrapper to an assembler (presumably for x86 assembly !) > > !! > > I just wrote some code doing binary operations which would have been > > about a zillion times faster in a few lines of assembly code. > > > > I also have fond memories of programming in BBC Basic which had an > > inline assembler - so you could wrap your assembly program in Basic. > > It meant some commercial games started with Basic ! > > > > Anyway - it would be easy to reserve some memory with a string like > > object to pass to an 'assembly object' and allow some really nifty > > (and fast) stuff ?? For simple algorithms it would be very neat. > > Avoiding memory overflow etc would be up to the assembly code 'chunk' > > of course. > > > > Regards, > > > > > > Fuzzy > > > > http://www.voidspace.org.uk/atlantibots/pythonutils.html > I.m sure that what I am about to suggest isn't as high tech as you > were expecting , > but I thought that Python already has a way of accessing functions in > a Unix > shared library, or Windows DLL. > If you cancompile Python on the platform than you no doubt have an > assembler handy too. > So, you could put your assemble language in a string; write the string > to a file; > assemble the file to create a shered library or DLL, then call the > function from Python! > > I don't think I'd do it that way though :-) > > Cheers, Pad. I've just discovered Weave - a package that is part of the SciPy project and allows for (sort-of) inline C functions that can be dynamically compiled at run-time. So it effectively allows what you've suggested - but with C-functions !! As I'd like to learn Pyrex (and so need to learn C) - I think I'll experiment with Weave. Regards, Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html From spam.trap.vrai.stacey at spam.trap.kbcfp.com Thu Apr 8 09:56:54 2004 From: spam.trap.vrai.stacey at spam.trap.kbcfp.com (Vrai Stacey) Date: Thu, 08 Apr 2004 14:56:54 +0100 Subject: if 'hallo' in ['hallooo','halloooooooo'] problem In-Reply-To: References: Message-ID: <1081432643.152843@master.nyc.kbcfp.com> Robert wrote: > I have a little problem and mybe one of you has got the solution. > I would like to check if a string is in a list of strings. > The following returns true: > if 'hallo' in ['halloooo','hallooooooooo']: > pass What version of Python are you using? With 2.2.3 I get the behavior you want using your first example. So ... > if 'hallo' in ['halloooo','hallooooooooo']: print "Hallo!"; > if 'hallo' in ['halloooo','hallo' ]: print "Hallo!"; Hallo! vrai. From leeg at teaching.physics.ox.ac.uk.valid Mon Apr 26 12:36:04 2004 From: leeg at teaching.physics.ox.ac.uk.valid (leeg) Date: Mon, 26 Apr 2004 17:36:04 +0100 Subject: Is Perl *that* good? (was: How's ruby compare to it older bro References: <2tOdna6S8a4pqxDdRVn_iw@powergate.ca> Message-ID: Peter Hansen wrote: > leeg wrote: > >> Peter Hansen wrote: >> >>>I guess it would be interesting to pose the question back to >>>them "If you could not use regexes in Perl, would you still >>>like to program in it?" or "If you couldn't use mysql in PHP >>>would you still use it?" >>> >>>What similar question, if any, would be a difficult one for >>>us Python types? >>> >> >> "If you couldn't write any program your imagination came up with in >> Python, or couldn't at least prototype it, or it took longer to write in >> Python than it did in C or Objective-C, would you still use it?" > > I guess it's pretty easy to come up with such questions if > you leave it wide open. > > Perhaps I should have said "limit yourself to questions involving > key pieces of functionality, external libraries, or specific > syntax" or something like that... > OK, fair enough. In that case, there is no reason for me to be using Python (except that it's easy to write and easy to read, which is good enough for me). I use POSIX-ey stuff and interfaces to lumps of code written in other languages, so Python could be Perl or Objective-C or C or Pascal or anything as far as I care; I just happen to be able to write correct code fairly quickly in Python. I hope that makes sense :-) -- Graham Lee I am leeg, for we are many "Computer Science is the only discipline in which we view adding a new wing to a building as being maintenance." - Jim Horning http://users.ox.ac.uk/~wadh1342 From claird at lairds.com Mon Apr 5 10:11:29 2004 From: claird at lairds.com (Cameron Laird) Date: Mon, 05 Apr 2004 14:11:29 -0000 Subject: Advocacy opportunity References: <10719mdp83juif4@corp.supernews.com> <1071eiaddi7mo95@news.supernews.com> Message-ID: <1072q8hdr0ustf7@corp.supernews.com> In article <1071eiaddi7mo95 at news.supernews.com>, John Roth wrote: . . . >the Python column. Some of them I don't know how to fill out, >and a few of them I don't know what he's talking about, frankly. . . . And a few make me laugh, in the well-we-know-what-*you*-have- on-your-mind vein (see how high on the list tail reduction is?). -- Cameron Laird Business: http://www.Phaseit.net From rzantow at ntelos.net Mon Apr 5 08:05:50 2004 From: rzantow at ntelos.net (rzed) Date: Mon, 05 Apr 2004 12:05:50 GMT Subject: How to assign a default constant value in a function declaration References: Message-ID: "Vineet Jain" wrote in news:mailman.341.1081121191.20120.python-list at python.org: > The following does not work although it seems like something you > should be able to do. > > def someFunction(option=Constants.DEFAULT_VALUE): > Do you mean in a context like this? >>> class Const: ... someVal=255 ... otherVal=0 ... >>> Const.someVal 255 >>> someVal=255 >>> someVal 255 >>> def blip(Const.someVal): File "", line 1 def blip(Const.someVal): ^ SyntaxError: invalid syntax >>> def blip(someVal): ... (no syntax error) I've wondered about that, too. -- rzed From 2002 at weholt.org Fri Apr 30 17:03:30 2004 From: 2002 at weholt.org (Thomas Weholt) Date: Fri, 30 Apr 2004 23:03:30 +0200 Subject: Adding and modifying methods at run-time Message-ID: <4092c014$1@news.broadpark.no> Hi, I want to add methods to a class instance at run-time based on a base method, but modify one of the existing ( or add if possible ) params of the base method. Say a class like this : class A: def __init__(self): self.obj1() # some dummy object having a name attribute self.obj2() # some dummy object having a name attribute def __method1__(self, param1, param2, param3 = None): # use some property on param3 in some operations def addNewMethod(self, param1, new_obj): new_func = copy.copy(self.__method1__) # modify a copy of self.__method1__ and change the param3 to point new_obj # and add the method setattr(self, 'method4%s' % new_obj.name, new_func) use the class like so : a = A() a.addNewMethod(1, a.obj1) # use new dynamically method a.method4obj1(1,2) # now the third param with a default is set to point to obj1 instead of None I'm crashing at the copy-method in addNewMethod. It crashes with the exception "TypeError: function() takes at least 2 arguments (0 given)". This is deep inside the copy-module. Any hints or clues? Best regards, Thomas From peter at engcorp.com Fri Apr 16 10:07:25 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 16 Apr 2004 10:07:25 -0400 Subject: List code of function in interpreter In-Reply-To: <407fe1aa$0$16036$3b214f66@usenet.univie.ac.at> References: <407fe1aa$0$16036$3b214f66@usenet.univie.ac.at> Message-ID: a9605473 at unet.univie.ac.at wrote: > A simple question. > > Is it possible in the python (or ipython) interpreter to > review the source code of a self defined function? That depends. The source is actually "lost" in at least one sense, because Python is compiled to bytecode (similar in some ways to how Java works) behind the scenes, and the interpreter executes this bytecode and not the source. On the other hand, the source file is still right there, usually, and if you are looking for a programmatic way of finding it and listing it, I believe the inspect module is what you are looking for: http://docs.python.org/lib/module-inspect.html Another and much less suitable (I suspect) option for you is to disassemble the function using the dis module. -Peter From newsgroups at jhrothjr.com Thu Apr 15 10:57:51 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Thu, 15 Apr 2004 10:57:51 -0400 Subject: Newbie question: Returning mutable vs. immutable References: <997a06e0.0404150627.5fb95d9b@posting.google.com> Message-ID: <107t8opa3b6iia5@news.supernews.com> wrote in message news:997a06e0.0404150627.5fb95d9b at posting.google.com... > Hi, Does anyone have an opinion as to whether functions/methods should > return mutable or immutable objects? In some circumstances, I could > see that mutable objects might be more convenient, but if the function > is to be reused, it might be a good idea to return only immutables. > > Or is this question moot, since the function returns control to the > caller and is out of the picture at that point? > > Thanks, > > --p I'm not sure I understand the question. The entire reason (well, not the *entire* reason, but close enough on the novice level) you write functions is to use them again and again and again. So your function should return whatever it needs to. In thinking about this, it seems there is really only one place where you would have a choice of mutable or immutable: a list or a tuple. Think of a tuple as a packaging method for a number of distinct values that you want to return. For example, if I say: return spam, eggs, juice the compiler builds a tuple. If I wanted to return a list, I'd have to say: return [spam, eggs, juice] John Roth From python at rcn.com Mon Apr 5 04:01:14 2004 From: python at rcn.com (Raymond Hettinger) Date: 5 Apr 2004 01:01:14 -0700 Subject: Python is faster than C References: <406F0907.96F37EA1@tunes.org> <5d83790c.0404032144.482787bd@posting.google.com> <6y1cc.1346$Qv6.482@fe2.columbus.rr.com> Message-ID: <5d83790c.0404042306.497e0384@posting.google.com> > >>>> enumerate('abcdefgh') > > >>>> list(_) > > [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e'), (5, 'f'), (6, 'g'), > > (7, 'h'), (8, 'i'), (9, 'j'), (10, 'k'), (11, 'l'), (12, 'm'), (13, > > 'n')] [Carl Banks] > I thought this myself, but what if the iterator is computationally > intensive? Since no more than three items are displayed, the interactive prompt will still handle this much better than something like range(10000000) which takes a while to compute and display. Besides, everything you do in Python pays a little performance penalty just to make sure you can break out of computationally intensive tasks. For me, these almost never arise at the interactive prompt. Likewise, I program in a less hostile world than Andrew Dalke who has to contend with pandora's box iterators which ruin the lives of mortal men who think they can call .next() with impunity ;-) Raymond Hettinger From michael at foord.net Thu Apr 8 03:52:05 2004 From: michael at foord.net (Fuzzyman) Date: 8 Apr 2004 00:52:05 -0700 Subject: ANNOUNCE : dataenc.py and Pythonutils References: <8089854e.0404052348.15e3a04e@posting.google.com> Message-ID: <8089854e.0404072352.764ae09d@posting.google.com> Python Utils http://www.voidspace.org.uk/atlantibots/pythonutils.html Already a few updates : *NEW* StandOut 2 Well, sort of new... actually an update - but a complete rewrite. StandOut is a Flexible Output Object - it allows you to implement vary degrees of 'verbosity' for command line programs *and* to allow logging to a file (with the same or a different degree of verbosity) - yet messages are printed just using the normal print command. Messages can be given a general 'priority', a priority for individual messages can be specified, an additional function can be passed in to print with - to display output to a GUI window, or perhaps to format ouput - plus a few other bits besides. Very easy to use and with full docs. dataenc Version 1.1.1 Fixes two bugs - one in interleaving files with a watermark file bigger than 64k, the other when watermarking files with a watermark less than 65536 times the size of the main file. Made the ouput from the tests look a bit nicer. ConfigObj Version 2.1.0 Made a couple of the parameters keywords, and added a couple of extra keywords that affect the way it treats creating configobjs for config files that don't yet exist. (Throw an error ? Create the file ?) Regards, Fuzzy From junkmail at solumslekt.org Fri Apr 16 05:23:23 2004 From: junkmail at solumslekt.org (Leif B. Kristensen) Date: Fri, 16 Apr 2004 11:23:23 +0200 Subject: CamelCase versus wide_names (Prothon) References: <87hdvl2dny.fsf@blakie.riol> <87d6692ar8.fsf@blakie.riol> Message-ID: Hugh Macdonald rose and spake: > On a qwerty keyboard, _ is SHIFT+- (to the right of 0) In my part of the world, _ is also Shift+-, but it's to the right of the . (period). In OO programming in general that's a bit awkward as I frequently type a dot where I want an underscore and vice versa. This is an error that often can be very hard to spot. So, this may be an argument for camelCasing, - which I actually haven't used much since my TurboPascal days. regards, -- Leif Biberg Kristensen http://solumslekt.org/ Validare necesse est From paul at prescod.net Sat Apr 24 18:40:08 2004 From: paul at prescod.net (Paul Prescod) Date: Sat, 24 Apr 2004 22:40:08 GMT Subject: Why we will use obj$func() often In-Reply-To: References: <84Uhc.22278$dZ1.5087@fed1read04> <8AWhc.23114$dZ1.11070@fed1read04> Message-ID: <408AECC7.7020601@prescod.net> Mark Hahn wrote: >... > > My biggest problem right now is stupid aesthetics. I have to decide where > to place Prothon on the continuum between lisp and perl. When I crossed the > line and added $ for self people screamed bloody murder that it looked like > Perl. Before when I had a period for self they thought it looked great. I > can't believe how much they care about something so silly. Yes, people are irrational. But if you care about language popularity you have to take that into account. Else you end up with a language that never goes mainstream like Lisp. Paul Prescod From skip at pobox.com Sat Apr 24 12:55:40 2004 From: skip at pobox.com (Skip Montanaro) Date: Sat, 24 Apr 2004 11:55:40 -0500 Subject: site.py In-Reply-To: References: Message-ID: <16522.39948.407186.498424@montanaro.dyndns.org> Chad> I have a patch / feature enhancement for python that affects Chad> site.py. Is there a moderator for this file? Chad> From what I have read, my code doesnt seem to fit into a PEP, its Chad> not a bug fix either. This is why I wanted to see if a moderator Chad> could answer some questions. Submit a patch to the Python project on SourceForge. Skip From junkmail at solumslekt.org Tue Apr 27 10:09:02 2004 From: junkmail at solumslekt.org (Leif B. Kristensen) Date: Tue, 27 Apr 2004 16:09:02 +0200 Subject: Is it possible to choose a better way? References: Message-ID: Alpha wrote: > Although there might not be anything wrong with simple honest work > Ask yourself if you would prefer smarter work, that produces more, or > simpler work, that produces less? > To receive fast confidential delivery send 10* to: Yeah, everyone who wants to know how to get money for nothing can just send me 10 bucks in an envelope. How it actually works is left as an exercise for the reader. regards, -- Leif Biberg Kristensen http://solumslekt.org/ Validare necesse est From rebirth at orcon.net.nz Fri Apr 9 06:20:34 2004 From: rebirth at orcon.net.nz (David McNab) Date: Fri, 09 Apr 2004 22:20:34 +1200 Subject: ANN: SPIRO - a cPython->Jython bridge (amongst other uses) Message-ID: <407678F2.1000509@orcon.net.nz> Hi, Announcing SPIRO - an easy cPython to Java bridge. Background: I spent some time looking for ways to interface between python and java. Jython is great - but it comes at a price where one must forego all python modules containing binaries. Pyro is great too - but presently cannot support running servers under jython. I tried JPE - but its brittleness rules it out for distributing code to others. So I gave up and wrote a new ORB myself: SPIRO - Simple Python Interface to Remote Objects http://www.freenet.org.nz/python/spiro SPIRO allows cPython programs to manipulate Java objects via jython. While it's not exactly CORBA-compliant, it is an easy and simple way to bridge between cPython and Java, with the advantage that it doesn't require any binary compilation. The server-side of SPIRO can be easily built into a standalone .jar file, which together with the cPython Spiro client class, will give your cPython programs access to the full catalogue of java software. Please note - this is an early alpha release, so stability is not guaranteed. If you're a tinkerer, and you feel like joining the development effort, let me know and I'll open a sourceforge account. Present limitations - no support for subclassing Java objects in cPython, no support for exceptions. Cheers David From paul at prescod.net Mon Apr 5 05:57:50 2004 From: paul at prescod.net (Paul Prescod) Date: Mon, 05 Apr 2004 02:57:50 -0700 Subject: Type checking inside a C extension In-Reply-To: References: Message-ID: <40712D9E.3050802@prescod.net> Jon Perez wrote: > > The problem is that neither PyLong_AsLong() nor > PyString_AsString() does any type checking so the > interpreter crashes when I try to use the values > returned by PyLong_AsLong() and PyString_AsString() if > they happen to be fed objects - the tuple elements in > this case - of the wrong type. It isn't true that PyLong_AsLong does no type checking. It does. It reports problems through the standard Python exception system. > I could certainly do a type check using PyLong_Check() and > PyString_Check() on the tuple items and raise a TypeError exception > to avoid leading to a crash, but I am concerned about the speed hit > as this is the innermost loop of a routine which gets called really > often (I use it for text block transfers). PyLong_Check is pretty cheap: #define PyObject_TypeCheck(ob, tp) \ ((ob)->ob_type == (tp) || PyType_IsSubtype((ob)->ob_type, (tp))) #define PyLong_Check(op) PyObject_TypeCheck(op, &PyLong_Type) Note that it is basically just a dereference and comparison check. I wouldn't worry about that even in an inner loop. > Is there a less expensive way to check the type, or somehow > avoid a crashing situation (i.e. an exception gets properly raised) > without calling PyLong_Check() and PyString_Check() the elements > of each and every tuple? I would usually use Pyrex for a job like this. But barring that, I often use its output to remember how to do little Python/C things. Given this input program: def foo(b): cdef int a a = b it generates code like this: /* "/private/tmp/foo.pyx":3 */ __pyx_1 = PyInt_AsLong(__pyx_v_b); if (PyErr_Occurred()) {error handling and return} By PyErr_Occurred() is a real function call and is probably slower than PyLong_Check. Paul Prescod From exarkun at divmod.com Wed Apr 7 12:20:19 2004 From: exarkun at divmod.com (exarkun at divmod.com) Date: Wed, 07 Apr 2004 16:20:19 GMT Subject: python thread scheduler? Message-ID: <20040407162019.28169.252570721.divmod.quotient.10@ohm> On Wed, 07 Apr 2004 11:27:58 +0100, project2501 wrote: > > to clarifgy, i'm seeing responec times as low as 0.3 seconds when the > client has 5 worker threads... rising to an average of about 8 seconds > with 50 threads... and more ith 100 threads. > The CPython interpreter utilizes a global lock which prevents more than one Python thread from running at any particular time. You will not see performance scale well with large numbers of threads (indeed, performance will probably be worse). Threads which do not run Python code (for example, code in an extension module) can release the global interpreter lock to take advantage of multiple CPUs. An alternative is to use concurrency without using threads. It sounds like you are working on a network server, so I would recommend taking a look at Twisted: http://www.twistedmatrix.com/ Jp From peter at engcorp.com Tue Apr 20 20:23:37 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 20 Apr 2004 20:23:37 -0400 Subject: md5.hexdigest() converting unicode string to ascii In-Reply-To: <77b925de.0404201516.7941cd83@posting.google.com> References: <77b925de.0404151450.5c1f720a@posting.google.com> <77b925de.0404161337.3917ef56@posting.google.com> <77b925de.0404201516.7941cd83@posting.google.com> Message-ID: uebertester wrote: > I've attempted the suggested solution specifying different encodings, > however, the hash value that is returned does not match what I expect > based upon another utility I'm checking against. Hash value returned > by python specifying utf16 encoding: 731f46dd88cb3a67a4ee1392aa84c6f4 > . Hash value returned by other utility: > 0b0ebc769e2b89cf61a10a72d5a11dda . Note: I've tried other encoding > also. As the utility I'm verifying against is extensively used, I'm > assuming it is returning the correct value. If this utility is so extensively used, it's almost certain that someone, somewhere, knows precisely what encoding scheme was used for Unicode strings. Isn't there documentation on how it calculates the hash? Source code? An expert? A vendor? This is not exactly something that is standardized or obvious, so it seems very unlikely they just picked some weird scheme and didn't note anywhere what they did. It's not, however, a Python question at this point, so you've probably got no choice but to search elsewhere. (What is the utility, by the way?) -Peter From ngps at netmemetic.com Wed Apr 7 19:54:53 2004 From: ngps at netmemetic.com (Ng Pheng Siong) Date: 7 Apr 2004 23:54:53 GMT Subject: Zope - how to import whole folder at once? References: Message-ID: According to Lukasz Indyk : > i have existing web site (written in html and javascript only, no php > etc.), and i want to integrate it with zope. i can add every page, image > etc. one by one using import, but i would like to add it at once. LocalFS, a Zope product, lets Zope serve files directly from the filesystem. For bonus points you might want to then export the LocalFS folder to a Zope zexp file for subsequent reimport into ZODB. (I haven't tried this. Dunno if it works.) Look for it on zope.org. -- Ng Pheng Siong http://firewall.rulemaker.net -+- Firewall Change Management & Version Control http://sandbox.rulemaker.net/ngps -+- Open Source Python Crypto & SSL From grante at visi.com Tue Apr 27 18:05:44 2004 From: grante at visi.com (Grant Edwards) Date: 27 Apr 2004 22:05:44 GMT Subject: Don't understand wxPython ids Message-ID: <408ed938$0$17263$a1866201@newsreader.visi.com> I've decided to learn wxPython, and I'm afraid I just don't grok the whole "id" thing where you have to pull unique integers out of your, er, the air and then use those to refer to objects: >From whe wxPython wiki examples: self.button =wxButton(self, 10, "Save", wxPoint(200, 325)) EVT_BUTTON(self, 10, self.OnClick) Does the 10 have any function other than as a handle that allows you to refer to self.button in the EVT* call? You're supposed to just make up unique id numbers for objects when a) they've already got unique id numbers [at least the id builtin thinks so] and b) they've got names that make things even more readable? This feels very assmebly-level. No, it's even worse than assembly language, since even assembly language has labels and symbols. Why not this: self.button =wxButton(self, 10, "Save", wxPoint(200, 325)) EVT_BUTTON(self, self.button, self.OnClick) Or better yet this: self.button =wxButton(self, 10, "Save", wxPoint(200, 325), action=self.OnClick) This last way seems pretty intuitive... Can somebody clue me in on the advantages of the progrmmer-generated integer id numbers for objects? -- Grant Edwards grante Yow! Now KEN and BARBIE at are PERMANENTLY ADDICTED to visi.com MIND-ALTERING DRUGS... From simoninusa2001 at yahoo.co.uk Tue Apr 20 14:20:04 2004 From: simoninusa2001 at yahoo.co.uk (simo) Date: 20 Apr 2004 11:20:04 -0700 Subject: wxListCtrl with CheckBox? References: <30260531.0404092256.6b58e3a1@posting.google.com> Message-ID: <30260531.0404201020.58660a46@posting.google.com> Josiah Carlson wrote: > > I've got a report list and want to have a checkbox in the last column > > of each row. > Use wx.Grid, it can place checkboxes in cells. I can't get that to work either, and I certainly can't get the grid cells to line up with the listctrl rows anyway. This is really holding up my program now, to move on any further I really need some way of having a checkbox at the end of every row of a few listctrl's. I can't believe this hasn't already been written - someone must have needed to have a "delete row" checkbox or button in a report before..... The only thing I can think of now is some sort of dynamic GridSizer that works out the position of every row, but that's really nasty. From jack at performancedrivers.com Fri Apr 16 18:04:07 2004 From: jack at performancedrivers.com (Jack Diederich) Date: Fri, 16 Apr 2004 18:04:07 -0400 Subject: CamelCase versus wide_names (Prothon) In-Reply-To: References: <407ec022$0$54153$1b2cd167@news.wanadoo.nl> Message-ID: <20040416220407.GB794@performancedrivers.com> On Thu, Apr 15, 2004 at 11:05:29AM -0700, Mark Hahn wrote: > > "Roy Smith" wrote... > > > It's entirely unclear how any of the above should influence your > > decisions on language design :-) > > It may not technically be part of the language design, but aesthic issues > like this need to be decided up front or they will be decided randomly. > Users on the Prothon mailing list were asking me (I'm the BDFL there) to > change from wide_names to camelCase and I wasn't letting them, because > Python used wide_names and I have a rule about following Python unless there > is a good reason to change. > > Then I came here and asked and to my surprise I'm finding out that 100% of > python users want camelCase. This kind of blows away my argument against > it. So camelCase it will be. > > Now I'll go through all the Python method and var names and convert them all > to camelCase for Prothon. It shouldn't be a problem for users since the > conversion is mechanical. Noooooo! As others have pointed out down the thread, don't just go on the first several replies. I'm a wide_case_fanboy, having done mixedCase and wide_names over the last fifteen years. It all comes down to personal preference, of course. IMO mixedCase people tend to be younger, and younger people tend to be more zealous on newsgroups. I'm also a native English speaker, so this_looks_like_words while thisLooksAwkward. I can read/write both and do depending on who is paying for the project, but I much prefer the underscores. I can also type 100+ words per minute (much faster than I can think) so I'm limited by figuring out what I want to do and not by hitting shift-minus. Mixed case works fine on two word variables because twoWords are as easy to read as two_words. But it gets painful forLongerVariableNames. I'm a big fan of descriptive names and since mixed case seems to discourage them when N > 2 that is enough reason to dislike it. My assertion that mixed case fanboys are young and therefore loud while at the same time being too inexperienced to know the difference is harsh and I'm sure a 65 year old programmer will post as a counter example. They are called stereotypes because they work /most/ of the time, if they worked /all/ of the time they would just call them truths. *wink* -jackdied From jcarlson at uci.edu Mon Apr 26 03:33:46 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Mon, 26 Apr 2004 00:33:46 -0700 Subject: Python editors for Windows question In-Reply-To: <6ee58e07.0404220803.24aeefe1@posting.google.com> References: <6ee58e07.0404220803.24aeefe1@posting.google.com> Message-ID: > But keep in mind that auto-completion is by concepts miles away from > what you see in Java. The problem for us who try to implement this > feature is always that most people don't understand why this is > impossible in a dynamically typed language. Not quite impossible, but very difficult. It is impossible in a practical sense for editors that don't use a parser capable of creating an abstract syntax tree (generally compiler.ast or the tokenizer module are used in editors written in Python). Furthermore, it usually involves questions like "how many levels of imports should we deal with, and how much namespace emulation should be done", which involves potentially expensive namespace creation, modification, and later recreation ("from module import *" becoming "import module" being one of them) in more than a single level of namespace. Quite an ugly problem that you're hard-pressed to find an editor (for dynamically typed languages) with a decent implementation. WingIDE's method for getting past some inference checks is nifty, though I would be a bit irked if I used autocompletion (I don't) and needed to pepper my code with (unneeded) assert statements just to get it to work all the time. - Josiah From a-steinhoff at web.de Fri Apr 2 08:23:08 2004 From: a-steinhoff at web.de (Armin Steinhoff) Date: Fri, 02 Apr 2004 15:23:08 +0200 Subject: Just magic ... In-Reply-To: References: Message-ID: root wrote: > Jeff Epler wrote: > >> I don't know, and since the code you posted doesn't run I can't find >> out. > > > #it's only a subset of the code ... > > class SlaveParSet(QDialog): > def __init__(self,parent = None, name=None, modal = 0, fl = 0, > Conf='PROFIBUS', saddr= 0): > > if name == None: > self.setName('SlaveParSet') > > self.config_name=conf > self.slave_addr = saddr > > self.gsd_connect = sqlite.connect("gsd_db") > self.gsd_curs = self.gsd_connect.cursor() > > # open project data base > self.prj_connect = sqlite.connect("proj_db") > self.prj_curs = self.prj_connect.cursor() > > self.ID = '' > self.IMpos = 0 > > > # insert selected module into installed modules > def ModuleSelectionval(self, nr): > module = str(self.ModuleSelection.text(nr)) > > #rebuild pos/module relationship > Sel = str("""select mod_pos, mod_name, proj, saddr, > mod_config_data, mod_prm_data > from INSTMODULE where proj= %s and saddr = %s""") > Key = (self.config_name, self.slave_addr) > self.prj_curs.execute(Sel, Key) > ins_list = self.prj_curs.fetchall() > > #ins_list is a list and contains now one tuple > > if len(ins_list): > self.IMpos +=1 > InsPos = self.IMpos > > Ins = str("""insert into INSTMODULE(mod_pos, mod_name, proj, > saddr, mod_config_data, mod_prm_data) > values (%s, %s, %s, %s, %s, %s)""") > > self.IMpos =0 > for set in ins_list: > setdata = (self.IMpos,) + set[1:] > > # set should reference a tuple but it refers to class instance .. WHY?? >>> set.__class__ >>> So why is 'set' ( a local var of a procedure defined in the class SetSlavePar ) now a 'class instance' of the class sqlite ?? Armin > > self.prj_curs.execute(Ins, setdata) > self.InstModules.insertItem(set[1], self.IMpos) > self.IMpos +=1 > if InsPos == self.IMpos: > self.InstModules.insertItem(new_item[1], self.IMpos) > self.prj_curs.execute(self.Ins, new_item) > self.IMpos +=1 > if self.IMpos > 0: > self.IMpos -= 1 > > self.InstModules.setCurrentItem(self.IMpos) > self.prj_connect.commit() > else: > self.IMpos = 0 > self.InstModules.clear() > self.InstModules.insertItem(module, self.IMpos) > self.InstModules.setCurrentItem(self.IMpos) > > > >> >> >>>>> self.IMpos =0 >> >> >> Traceback (most recent call last): >> File "", line 1, in ? >> NameError: name 'self' is not defined >> >> Jeff >> From imbosol at aerojockey.com Wed Apr 14 19:41:31 2004 From: imbosol at aerojockey.com (Carl Banks) Date: 14 Apr 2004 16:41:31 -0700 Subject: Difficulty Finding Python Developers References: <65cbc3dd.0404140641.3501fde8@posting.google.com> Message-ID: <60dfb6f6.0404141541.79cbb54f@posting.google.com> pm_mon at yahoo.com (Paul Morrow) wrote in message news:<65cbc3dd.0404140641.3501fde8 at posting.google.com>... > We've worked hard to convince our company to migrate our core > applications to Python, and now we're looking for a Python developer > in Atlanta to handle a short-term (approx. 3 month) project. But our > initial searches have been fairly unsuccessful. We haven't actually > posted a job on Monster, but we have been talking with various > headhunters in our area and they don't have many resumes that show > Python experience. An so now, of course, mgt is wondering whether > selecting Python was a mistake. > > As anyone had a similar experience? Suggestions? Yeah, relocate. :) Seriously, it seems to me that headhunters are machines designed to funnel in the drones colleges spit out. I don't think they're all that interested, or knowledgable, of less common skills. I think you'll have luck posting the job on Monster. Also, I agree with Peter Hanson here. I am very amazed (although not surprised at all) that firms are often reluctant to switch to a language like Python because there are relatively few people with experience in it. C and C++ are so bug-prone (buffer overruns, anyone? segfaults?) I think it would be in a firm's best interests to hire those C and C++ drones and train them for Python; the cost of training someone in Python probably would more than offset the cost of fixing all those bugs. -- CARL BANKS From jzgoda at gazeta.usun.pl Sat Apr 10 18:57:25 2004 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Sat, 10 Apr 2004 22:57:25 +0000 (UTC) Subject: Python is the best and most popular general purpose scripting language; the universal scripting language References: Message-ID: Roy Smith pisze: > So, what makes something a "scripting language" as opposed to a > "programming language"? I think the opposition of "scripting language" would be "general purpose language", not "programming language". -- Jarek Zgoda http://jpa.berlios.de/ From pcaffrey at iel.ie Thu Apr 1 10:04:13 2004 From: pcaffrey at iel.ie (Paul) Date: 1 Apr 2004 07:04:13 -0800 Subject: recursive acquire of GIL Message-ID: Hi I have seen this discussed already on the newgroup but have not seen if the problem is solved Using embedded python in c++ we use PyEval_RestoreThread(context); to acquire the GIL. We then use swig to call back into c++ which again calls out to python Essentially we have c++ -> python -> c++ -> python The second RestoreThread uses a different python context of course. However it hangs PyEval_RestoreThread(context2); is hanging. We're using python 2.2.1 Has a solution to this been added to later versions? Regards Paul From mcfletch at rogers.com Thu Apr 22 16:21:59 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Thu, 22 Apr 2004 16:21:59 -0400 Subject: Why we will use obj$func() often In-Reply-To: <84Uhc.22278$dZ1.5087@fed1read04> References: <84Uhc.22278$dZ1.5087@fed1read04> Message-ID: <40882967.3000209@rogers.com> Mark Hahn wrote: >My apologies. I posted this to c.l.p. by accident. I meant to post this >to Prothon-users. > > Oh, no problem, there's some Python content (see below for some comments on it)... ... >># Python >> >>class klass: >> def __init__(self): >> self.me = 1 >> def func(self): >> print "func1,self"+str(self.me), >> >>class klass2(klass): >> def __init__(self): >> self.me = 2 >> def func(self): >> klass.func(self) # delegation >> print "func2,self"+str(self.me), >> >>inst = klass2() >>inst.func() # prints func1,self2 func2,self2 >> >> >> ... >>In Python the call klass.func() was different because Python knows that >>klass is a class and therefore obviously cannot be the target of call (an >>instance), so it made the programmer pass the instance self to use as a >>parameter. >> >> This isn't really a very clear description of what's going on in Python. It won't matter to the Prothon users, but don't want any Python users to get confused... Looking up klass.func returns an unbound instance method, this is a function wrapper which basically just says "hey, you're a member function of a class, check to be sure that your first argument is a member of that class". This is done by the function's descriptor hooks which allow it to return a wrapped object when the user attempts to retrieve the value from another object (such as a class or an instance). So, in a sense, yes, the class cannot be the target of that *particular* call, as the unbound method object you retrieved will reject anything other than an instance of the class. Bound instance methods are a similar wrapper, but they say "curry/bind your first argument (normally self) to this value then call the underlying function". They are created on object.method access by the same function descriptor hooks. The point of all that being that classes most definitely *can* be the target of a call. Python's classes are first-class objects. In particular, they are instances of metaclasses, and can have meta-methods defined which take the class as their first parameter just like a normal method-call. >>> class k(type): ... def r( cls ): ... return 42 ... >>> class x: ... __metaclass__ = k ... >>> x.r() 42 >>> There's very little "special" about classes other than that they have some syntactic shortcuts for creating them and for looking up attributes of their instances within them. Python isn't looking at every method call and saying "hey, that's a class, that can't be the first parameter to a function/method!", it (particularly the unbound instance object) is saying "hey, you're not an instance of my class, go to heck" and never thinks about whether the object is *particularly* a class or not. Classes are special in Python, but not nearly as special as you might think from a class-less perspective :) , Mike By the way, the modern Python idiom is: super( klass2, self ).func( ) but that wouldn't help in explaining the logic for the Prothon choice, so no biggie :) . _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From video at esfera.cl Thu Apr 1 12:16:52 2004 From: video at esfera.cl (Cristian Hasbun from Chile) Date: 1 Apr 2004 09:16:52 -0800 Subject: Another gen_py coclass_interfaces COM problem References: Message-ID: Still Waiting video at esfera.cl (Cristian Hasbun from Chile) wrote in message news:... > I need a win32com guru please... > > i'm not python expert, but i understand mi trouble... > > Requirements: > Hook EyesWeb 3.2.0 (http://www.eyesweb.org) COM Module with Python > 2.0.1 > i used win32com libraries and generate an early binding for module > (using prog_id) > > the problem is the file generated has a Class EyeswebSystem that is a > CoClassBaseClass with coclass_interfaces Like IEywApplication that is > a DispatchBaseClass... > > after reading other post with similar problem i saw that the other > problems are about coclass_interfaces with objects DispatchBaseClass > only... > > i try > > """ > import win32com.client > Eyes=win32com.client.Dispatch('Eyesweb.Remotesystem') > App=win32com.client.Dispatch(Eyes,resultCLSID='{clsid}') > """ > > an have more accurate result > > """ > >>> Eyes > > >>> App > 0x19740672> > """ > > but i can't reach "EyesWeb System.IEywApplication.Methods()" yet > > with diferents try and error, i get com_errors like: > 'the server threw an exception' > 'invalid access to memory location' > > here is a link of my gen_py generated file, easy for understand class > structure of the module with a browse class > > http://www.kitesurf.cl/flash/0971C42C-F8CA-45F1-BC6B-A55F23EE2A40x0x1x0.py > > Sorry my English... Mark Hammond if are you out there give me some > light From jepler at unpythonic.net Mon Apr 12 10:33:58 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 12 Apr 2004 09:33:58 -0500 Subject: Problems compiling on a Red Hat 7.3 based system In-Reply-To: <1081750846.2069.80.camel@p133.douganconsulting.com> References: <1081750846.2069.80.camel@p133.douganconsulting.com> Message-ID: <20040412143357.GO6139@unpythonic.net> I have compiled Python 2.3.3 on a RedHat 7.2 machine, though I didn't use an RPM. I'm not sure about the "/lib/cpp fails sanity check" message, but maybe the second problem is due to a missing package. I have a on my system: $ rpm -qf /usr/include/linux/errno.h kernel-headers-2.4.7-10 good luck Jeff From mark at prothon.org Fri Apr 23 13:55:55 2004 From: mark at prothon.org (Mark Hahn) Date: Fri, 23 Apr 2004 10:55:55 -0700 Subject: Why we will use obj$func() often References: <84Uhc.22278$dZ1.5087@fed1read04> <8AWhc.23114$dZ1.11070@fed1read04> <40883BFE.B381518A@alcyone.com> <27_hc.23801$dZ1.2716@fed1read04> <40887145.789A2FE8@alcyone.com> Message-ID: "A.M. Kuchling" wrote in message news:WqWdnfW7RpSmhRTdRVn-uw at speakeasy.net... > On Thu, 22 Apr 2004 18:28:37 -0700, > Erik Max Francis wrote: > > Being a fan of Io, I think prototype-languages are interesting. Even so > > far, I lost interest in looking at the actual main feature of Prothon, > > after seeing all the extra baggage that was brought on in unecessary > > stylistic changes. > > There's a rule in experiments that you should only change one thing at a > time, trying to answer a single question with each change. Prothon started > out asking two questions: Well, we didn't really start out to ask questions. We started out to design a new language. We happened to like Python so we stole most of the syntax from Python. Tim Peters and some other Pythoneers saw the existence of Prothon as an opportunity to get some of these questions answered though for Python. > * Does implementing an interpreter on top of the Apache Portable Runtime > for the sake of free threading work? (Presumably the answer is yes, since > Prothon does run. I haven't seen performance numbers on Prothon, though.) > * Is prototyping a workable replacement for a class-based object system? > Unclear, since I don't know that anyone has written sizable systems > in Prothon yet. > > The problem is that if you then make a whole bunch of additional changes -- > a 'with' statement, This was required. Not having a class statement meant there was no way to group the definition of functions and other attribute assignments together when building a prototype or even a plain object. When playing with early versions of the language it was unusable without the "with". > changing the rules for indenting Actually no rules changed for indenting. Well, we added a rule that you couldn't mix tabs and spaces within a single block, but that is not an unreasonable requirement. We also added a new way to do continuations, but that is optional. > changing the names of various built-in methods The names are totally unchanged. We just changed the style to camelCase and added ! and ? for readability. These are all mechanical changes and no memorization is required. > it becomes harder for Python users to try out > the new language for a while because there are more changes they have to > cope with. After a certain point the number of crossover users dwindles to > near-zero. Yes, many people are afraid to try new things. That is a shame. Of course if it was identical to Python many people still wouldn't try it. I think everyone here is operating under fear, uncertainty, and doubt. Most of the reports on the Prothon mailing list of people who have actually picked up Prothon and played with it have been happy. People look at the surface and are prejudiced, just like looking at people with different skin color. The best example is the current suggestion that self be changed to the dollar-sign. Now anyone with any intelligence knows that changing the 4 letters "self" to the one symbol $ does nothing to change the language, but several people here on c. l. p. claim that because you see dollar-signs Prothon has now "become Perl". That is narrow-minded prejudice. What's funny is that many people were happy with the current Prothon's use of period for self but object to dollar-sign because now it looks like Perl. Go figure. > None of these changes is critical or results in a 100% > improvement in functionality (or even a 10% one), but their collective > effect is to make the distance too great to cross conveniently; you might as > well start a new language with a blank sheet of paper at that point. Don't forget that we are not claiming to be Python. We intended from the beginning to be a new language. We are using everything from Python that isn't broken, and we get to define what is broken in Python :) We are definitely fighting a battle to improve things while keeping the best of Python. There is no way to make everyone happy. There have been people who have come to our mailing list whose "suggestions" for Prothon were to basicly keep Prothon exactly like Python and not change anything. There are also people who claim that any change from the Self language means that it is not a real Prototype-based language. And of course a smattering of people who claim it must be like Lisp :) From jjl at pobox.com Sat Apr 17 20:15:00 2004 From: jjl at pobox.com (John J. Lee) Date: 18 Apr 2004 01:15:00 +0100 Subject: Arbitary VTABLE/Python References: Message-ID: <87isfy5egr.fsf@pobox.com> John Smith writes: [...] > We have very,very large C++ applications > that talk to third part COM based server(s), > both in-proc & out-of-proc > > - For large arbitary vtable based interfaces, > what is the best approach from Python? > > We looked at FAQs, DOCs (including ActiveState), WEB > searches, and saw references to SWIG, PythonCOM extensions > BOOST.Python etc, and some problems people have reported using arbitary > vtable interfaces from PythonCOM (BTW: where is are DOCs on > one using/creating PythonCOM extensions? From our > WEB searhces, it looks like 'makepy' may not > work under all situations?) [...] makepy applies only to IDispatch-based interfaces. PythonCOM doesn't call arbitrary vtable interfaces yet (unless it has very recently grown that ability). It has, only quite recently, acquired the ability to implement arbitrary vtable interfaces. Of course, you can always write an extension in C or C++, and integrate that with win32all, but that's a bore, and I'm not sure it's a well-documented process. (Just to clear up any possible confusion: PythonCOM is part of win32all (which itself is also bundled with ActiveState's Python distribution, if they're still doing that). Mind you, I can never remember whether PythonCOM is an internal part of win32all, or an umbrella name for win32all's COM functionality, or what... so I always just say 'win32all', or win32com, if I specifically mean that module :-) So, win32all is nice, but it doesn't do what you want (call arbitrary vtable COM interfaces), at least without doing some wrapping and knowing about win32com's / pythoncom's internals. The most Pythonic route is ctypes. ctypes is quite elegant, thin and small (in contrast to win32all). It's still fairly new, but because it's relatively small, if you've got highly experienced COM developers on board, I'd imagine you're not going to struggle too much with any problems that do crop up. I used an earlier release and bumped into two bugs when I played with it, but found they were already fixed in CVS. It's more stable now (6 months or more since the version I used was released). Recent testimony: http://mail.python.org/pipermail/python-list/2004-April/214912.html The other way is to write your client code in C++, then wrap it. Boost Python is pretty much the standard way to do that for Python. I've never used it. I guess it's useful as an insurance policy if ctypes fails at some task for you. I think Mark Hammond (primary win32all author) )has his own ways of wrapping COM interfaces, but whether they're suitable for public consumption I don't know. If my goal were at all related to C++, I wouldn't use SWIG, unless it has advanced quite a bit since I last looked (a year or so ago). Boost Python is generally agreed to be a better solution unless you need to expose things to multiple scripting languages. John From timr at probo.com Sun Apr 11 00:09:27 2004 From: timr at probo.com (Tim Roberts) Date: Sat, 10 Apr 2004 21:09:27 -0700 Subject: Non-math-geek needs help with CRCs (binascii.crc32) References: <4073c865$0$27642$61ce578d@news.syd.swiftdsl.com.au> <40751603$0$27643$61ce578d@news.syd.swiftdsl.com.au> <4076ff3d$0$27642$61ce578d@news.syd.swiftdsl.com.au> Message-ID: "nobody" wrote: >> >Somehow, depending on how the numbers are massaged, the old code based on >> >$EDB88320 is compatible with what the above site documents as $04C11DB7. >> Did you notice that those two numbers are mirror images of each other? >> Could just be a difference in interpretation. > >How does one get the same result with a reflected and non-reflected >algorithm using the exact same input? Well, what I was saying was that perhaps the two algorithms are doing their computations in the opposite order. It's just suspicious that they are reflections of each other. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From ed-no at spam-eepatents.com Thu Apr 8 20:27:01 2004 From: ed-no at spam-eepatents.com (Ed Suominen) Date: Thu, 08 Apr 2004 17:27:01 -0700 Subject: Tcl/Tk extension access from python under windows References: Message-ID: Marcel Achim wrote: > I found a tcl extension that does exactly what I need to access a DLL > and it would require a large amount of SWIG glue to generate an > equivalent python extension. Wow... in nearly three years of programming with TCL (something I now regret), I've had the *opposite* experience too many times to count. That's one of the reasons I recently switched to Python -- I got sick of searching for TCL packages and finding mostly nothing but "Page Not Found" 404 Errors or ancient, bit-rotted code. Now that I've been learning Python and exploring the wonders of OOP, I am kicking myself for learning a "simple" language to make things "easier." HA! -Ed Suominen From newsuser at itgoesclick.com Tue Apr 20 10:53:16 2004 From: newsuser at itgoesclick.com (Noah from IT Goes Click) Date: Tue, 20 Apr 2004 14:53:16 GMT Subject: initialization object In-Reply-To: References: Message-ID: Have 2 modules a wrapper and then the foundation. The user can load the real module which basically just lets them create an initialization object which then sets a bunch of very oddly named globals and then loads your desired module which looks for those.. Sort of an icky way of doing it but it's not bad From hungjunglu at yahoo.com Mon Apr 19 13:02:51 2004 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 19 Apr 2004 10:02:51 -0700 Subject: module not callable - why not? References: Message-ID: <8ef9bea6.0404190902.78d2a95d@posting.google.com> "Robert Brewer" wrote in message news:... > Josiah Carlson wrote: > > Singletons aren't nearly as prevalent as you seem to believe. > > ... Truth be told, I've used singletons before, but only once. > > I thought I had twice, > But now I can see there was > Only one instance. Ha. As I have said, "singleton pattern" is symptom of a disease. But the concept of "singleton" itself, that is, a unique instance of a class, is ubiquitous. Just about any decent-size program that you write will have lots of singletons: classes that have one single instance. Therefore, you have used singletons tons of times. You just have not followed recipes for "singleton pattern", which is good, because it is symptom of a disease. regards, Hung Jung From altis at semi-retired.com Thu Apr 15 12:00:14 2004 From: altis at semi-retired.com (Kevin Altis) Date: Thu, 15 Apr 2004 09:00:14 -0700 Subject: CamelCase versus wide_names (Prothon) References: Message-ID: If you're using PEP 8 terminology then CamelCase is different than mixedCase. CamelCase is often used for class names and mixedCase for everything else. """ - CapitalizedWords (or CapWords, or CamelCase -- so named because of the bumpy look of its letters[4]). This is also sometimes known as StudlyCaps. - mixedCase (differs from CapitalizedWords by initial lowercase character!) """ ka "Mark Hahn" wrote in message news:UHxfc.9323$dZ1.3740 at fed1read04... > We have agreed in Prothon that unlike Python we are going to be 100% > consistant in our var and method naming. We will not have run-together > words like iteritems, we are going to always have seperated words like > has_key. > > Now we are in the midst of a discussion of camelCase versus wide_names. So > far our arguments are: > > 1) CamelCase is more elegant, modern, more readable, and more efficient in > character usage. > > 2) Wide_names is cleaner, more readable, compatible with C, which is the > standard module language for Python and Prothon. Wide_names is also the > Python standard. > > Of course in the Python world you alread have wide_names as your standard, > but could you for the moment pretend you were picking your standard from > scratch (as we are doing in the Prothon world) and give your vote for which > you'd prefer? > > Thanks in advance... > > From eddie at holyrood.ed.ac.uk Wed Apr 21 07:33:09 2004 From: eddie at holyrood.ed.ac.uk (Eddie Corns) Date: Wed, 21 Apr 2004 11:33:09 +0000 (UTC) Subject: here document as script and read from stdin References: <408596DE.10004@jessikat.fsnet.co.uk> Message-ID: Robin Becker writes: >Is it possible to use python with a shell HERE document as the script >and read the standard input? In other words make python usable as a >filter with a side input? >It doesn't seem to be obvous unless I can somehow use the -c option. >-- >Robin Becker python -c "`cat < <5d83790c.0404150701.605782a7@posting.google.com> <7xpta8hqe7.fsf@ruckus.brouhaha.com> <7xsmf4kbac.fsf@ruckus.brouhaha.com> <7x7jwg7ipn.fsf@ruckus.brouhaha.com> Message-ID: <7xwu4gzff2.fsf@ruckus.brouhaha.com> Peter Hansen writes: > I thought the discussion was a 3-month project. To me, that's > definitely not something I would classify as a "serious production > project". I know, I know, the length alone shouldn't be enough to > call it serious or production or not. It's just not the term I > would apply to something that short. "Experiment", maybe, or > "quickie", or "co-op student project" or something... It often means "we have a huge deadline in three months and are forced to bring in contractors because the in-house staff is and overstretched and not sufficiently up to speed on this stuff". In which case the contractor better need zero ramp-up time. From aahz at pythoncraft.com Fri Apr 30 20:20:43 2004 From: aahz at pythoncraft.com (Aahz) Date: 30 Apr 2004 20:20:43 -0400 Subject: File access and threads References: <4084b3eb@newsflash.abo.fi> <40864030$1@newsflash.abo.fi> Message-ID: In article <40864030$1 at newsflash.abo.fi>, =?ISO-8859-1?Q?Petter_Holmstr=F6m?= wrote: >Aahz wrote: >> >> Could you at least post a full traceback? > >Is this enough? Looking at the code, I'd bet on a permissions problem of some kind. It's pretty much either that or a bug in the underlying C libraries that gets exposed by threads -- that's a dirt-simple piece of code, really. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I used to have a .sig but I found it impossible to please everyone..." --SFJ From kkto at csis.hku.hk Sun Apr 4 23:44:46 2004 From: kkto at csis.hku.hk (Isaac To) Date: Mon, 05 Apr 2004 11:44:46 +0800 Subject: Python is faster than C References: Message-ID: <7i3c7jrsup.fsf@enark.csis.hku.hk> >>>>> "Robert" == Robert Brewer writes: Robert> This would not bring joy to not-repeatable iterators... :( Perhaps the OP likes Haskell more than Python. :) Regards, Isaac. From wweston at att.net Wed Apr 21 12:21:22 2004 From: wweston at att.net (wes weston) Date: Wed, 21 Apr 2004 16:21:22 GMT Subject: This is very simple question In-Reply-To: References: Message-ID: <6cxhc.15285$um3.339900@bgtnsc04-news.ops.worldnet.att.net> Eric wrote: > I would want to obtain a list of factors (multiples of 2) given a > prime number in python. > > For example 13=[8,4,1], 5=[4,1], 7=[4,2,1], 15=[8,4,2,1] > > I would appreciate a fuction which would do this. > > Eric Eric, Is the last test 17 vs 15? With not much checking: >>> 13 [8, 4, 1] 5 [4, 1] 7 [4, 2, 1] 17 [16, 1] >>> #------------------------------------------------------------------ import math #For example 13=[8,4,1], 5=[4,1], 7=[4,2,1], 15=[8,4,2,1] #For example 13=[8,4,1], 5=[4,1], 7=[4,2,1], 17=[16,1] def LargestPrimeLessThanOrEqualTo(n): i = 0 while 1: x = int(math.pow(2,i)) if x == n: return x if x > n: return prevx prevx = x i += 1 def foo(x): list = [] temp = x while(temp > 0): z = LargestPrimeLessThanOrEqualTo(temp) temp -= z list.append(z) return list for x in [13,5,7,17]: print x,foo(x) wes From anton at vredegoor.doge.nl Sun Apr 18 06:39:49 2004 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Sun, 18 Apr 2004 12:39:49 +0200 Subject: Static Modules... References: Message-ID: <40825ae1$0$151$3a628fcd@reader2.nntp.hccnet.nl> Grzegorz Dostatni: >Here is another version of the autoload module. This is now at 0.3 and >moving on. Thanks. Seems to work here under Cygwin (my main Python interactive shell). What's in a name anyway. Anton From peter at engcorp.com Thu Apr 15 10:11:12 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 15 Apr 2004 10:11:12 -0400 Subject: Python style of accessing bools? In-Reply-To: References: Message-ID: <4I2dnfHLZq5iCuPdRVn-uw@powergate.ca> Jonathon McKitrick wrote: > I'm trying to avoid leftover C-style in my new Python programs. > > If a class has a boolean property, and I am branching based on that > property, which of these is preferred? > > if MyClass.boolProp: > This is preferred. > OR > > if MyClass.IsTrueProp(): > > > In other words, do you use accessors or just access the variable directly? Go with direct access. If you need to change that in the future you can switch the attribute to a property and have the equivalent of isTrueProp() called automatically without having to change any calling code. -Peter From jonas at jonasgalvez.com Wed Apr 21 12:30:10 2004 From: jonas at jonasgalvez.com (Jonas Galvez) Date: Wed, 21 Apr 2004 13:30:10 -0300 Subject: Stupid Regex Question Message-ID: I'm feeling dumb: str = "textmoretexttext" How can I get a list like ["textmoretext", "text"] using regexes? I'm starting to believe it's not possible. Yeah, I know about the terror stories about using regexes to parse HTML, but in this particular case, using a SAX parser would be an horrendous overhead (I mean, it's a ridiculously simple string). =- Jonas Galvez jonasgalvez.com/blog macromedia.com/go/team From gerrit at nl.linux.org Tue Apr 13 07:08:13 2004 From: gerrit at nl.linux.org (Gerrit) Date: Tue, 13 Apr 2004 13:08:13 +0200 Subject: A new OS In-Reply-To: References: <107k441hitt2ld9@corp.supernews.com> Message-ID: <20040413110813.GA8877@nl.linux.org> Corey Coughlin wrote: > "A Evans" wrote in message news:<107k441hitt2ld9 at corp.supernews.com>... > > Hello Everyone I am working towards starting a project developing a new > > Operating System using the Python language (or a derivative thereof). As > > recommended on this forum I am asking if people are interested in something > > like this and ask who would be willing to support a project this large. > > > > Any and all ideas are welcome this message is just to see what kind of > > support this project would recieve http://sourceforge.net/projects/cleese http://cleese.sourceforge.net/ I don't believe in it. Gerrit. -- Weather in Amsterdam Airport Schiphol, Netherlands 13/04 12:25: 11.0?C Few clouds mostly cloudy wind 3.6 m/s NE (-2 m above NAP) -- Experiences with Asperger's Syndrome: EN http://topjaklont.student.utwente.nl/english/ NL http://topjaklont.student.utwente.nl/ From irmen at -nospam-remove-this-xs4all.nl Tue Apr 13 13:30:40 2004 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Tue, 13 Apr 2004 19:30:40 +0200 Subject: interpreter limits In-Reply-To: References: Message-ID: <407c23bf$0$570$e4fe514c@news.xs4all.nl> Joseph T. Bore wrote: > I dont know a heck of a lot about the implementation of the > interpreter/vm but would it be possible to implement exec or eval with > an optional argument, that argument would be a maximum number of byte > codes the interpreter would execute before throwing an exception. Interesting. I know it's not of any help but 'back then', most MUD engines did exactly this (at least, LP and MudOS did). When a user-written module ran too long, it was aborted, to avoid hanging the mud :) --Irmen From claird at lairds.com Wed Apr 28 09:58:10 2004 From: claird at lairds.com (Cameron Laird) Date: Wed, 28 Apr 2004 13:58:10 -0000 Subject: Is Perl *that* good? References: <108v74768o9sb9f@corp.supernews.com> Message-ID: <108ve3ig6ii5ec@corp.supernews.com> In article , Ville Vainio wrote: . . . >not knowing Python. Somehow people acquire weird proconceptions (tcl >is best for quick uis, perl for string handling, ...) and refuse to >reconsider them even if the realities that originally created the >preconceptions have changed, rendering the original claim >categorically false. . . . Oh, yes. A particular concentration of this I know is in Unix system administration. People will sometimes stand on their heads to do things in ways that made a lot of sense in 1994, say, but are multiply suboptimal in 2004 (construction of fragile shell-coded if-file-appears-in-FTP-listing algorithms when any sane sysad supports ssh and friends, and so on). Some of the best books are from the early '90s, and ... well, we get ourselves into funny states. -- Cameron Laird Business: http://www.Phaseit.net From kmmcdonald at wisc.edu Sun Apr 4 20:10:39 2004 From: kmmcdonald at wisc.edu (Kenneth McDonald) Date: Mon, 05 Apr 2004 00:10:39 GMT Subject: So near and yet so far... (trying to install PyQt on OS X) Message-ID: I'm trying to get QT, SIP, and PyQt installed so I can try out the Python editor eric. Both sip and qt appear to have compiled and installed properly. Unfortunately, PyQt, after compiling most of the files and starting what I suspect is the final link step, fails with the follwing message (I've included a few lines above for context): --------------- [Kenneth-McDonalds-Computer:~/Downloads/PyQt-mac-gpl-3.11] ken% make c++ -prebind -dynamiclib -headerpad_max_install_names -install_name libqtcmodule.so -framework Python -o libqtcmodule.so qtcmodule.o sipqtQWorkspace.o sipqtQWMatrix.o sipqtQW ... (lots more files) ...sipqtQPen.o sipqtQt.o moc_qtcmodule.o -L/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/site-packages -L/Developer/qt/lib -lqassistantclient -lsip -lqt /usr/bin/libtool: can't locate file for: -lsip /usr/bin/libtool: file: -lsip is not an object file (not allowed in a library) make[1]: *** [libqtcmodule.so] Error 1 make: *** [all] Error 2 ------------- and, though I can do some fiddling with make files, I sure as heck have no idea what to do about this. I would really appreciate advice on this one, because I'll never solve it on my own. Thanks, Ken From p_s_oberoi at hotmail.com Tue Apr 27 23:18:23 2004 From: p_s_oberoi at hotmail.com (Paramjit Oberoi) Date: Tue, 27 Apr 2004 22:18:23 -0500 Subject: Is Perl *that* good? References: <108q51j4dscn7dc@corp.supernews.com> <87fzaqmm8t.fsf@strauser.com> <38ec68a6.0404262308.50029919@posting.google.com> Message-ID: >> If only compiled regular expression objects allowed easy access to the >> last match object, python regxes would become significantly more >> convenient. For example, today you have to write: > > Hmm. The reason this hasn't been done is that it makes the match > method non-reentrant. For example, suppose you call some functions in > between the matching and use of the matched object, like this: I agree that that's a good reason... So: to make regular expressions convenient, it should be possible to use them without necessarily declaring a variable for the regular expression object or the match objects. The former is fairly easy; the latter is not. The match object needs to have local scope; but, a function cannot access the caller's locals without mucking around with sys._getframe(). Is there any other way of injecting objects into the caller's namespace? Are there any objects that exist per-frame that could be co-opted for this purpose? I suppose a convenience module that uses sys._getframe() could be written, but I don't think it would be suitable for the standard library. Of course, once we get decorators, it would be possible to munge functions to make them more amenable to regexes... but then, we don't want such hackery in the standard library either. Question about decorators: are they only going to be for methods, or for all functions? From rich_NOSPAM_ at _NOSPAM_holmteam.net Mon Apr 19 23:05:32 2004 From: rich_NOSPAM_ at _NOSPAM_holmteam.net (RichH) Date: Mon, 19 Apr 2004 22:05:32 -0500 Subject: Threats to the: Daily Python URL! References: <2ae25c6b.0404182250.4c5bc870@posting.google.com> Message-ID: You are doing an excellent job. 'Daily Python' is the first thing I read each morning. Please keep up the great work! Cheers, Rich In article , fredrik at pythonware.com says... > Paddy McCarthy wrote: > > > Please don't stop the excellent work that you do. > > I don't know what threats and insults you suffered but I would like to > > ensure you that I for one read the column and value it. > > the daily URL won't go away. we'll continue to provide fresh links to > potentially interesting stuff for as long as we possibly can (if you want > old links, use google or gigablast). > > and in the future, we'll just redirect abusive posts to /dev/null (and it's > up to us to decide what's abusive). no need to upset our readers just > because we got upset... > > thanks /F > > > > > From teiffel at attglobal.net Wed Apr 28 14:37:42 2004 From: teiffel at attglobal.net (Marcello Pietrobon) Date: Wed, 28 Apr 2004 14:37:42 -0400 Subject: uuid generator Message-ID: <408FF9F6.8020501@attglobal.net> Hello, I need to read newly generated uuid from Python but I am not sure if http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/163604 is the right code Maybe there is already the library in Python 2.3 Maybe I can use the one generated with uuidgen under cygwin but this would not be portable In this last case I would like to know how can I capture the output of uuidgen so I can use it in my script Thank you if you know the answer ! Cheers, Marcello From roy at panix.com Thu Apr 1 08:41:21 2004 From: roy at panix.com (Roy Smith) Date: Thu, 01 Apr 2004 08:41:21 -0500 Subject: [OT] Top posting is a PITA References: <569c605ld1cj8fc1emolk08ete0s1prls1@4ax.com> <106di86neu1qh4d@news.supernews.com> <4069a001$0$4237$afc38c87@news.easynet.co.uk> <4069e9d9$0$8915$636a15ce@news.free.fr> <406a98ee$0$290$edfadb0f@dread12.news.tele.dk> <106lh64rda8t9d4@news.supernews.com> Message-ID: What makes you think people who top post don't also put a lot of effort into carefully organizing their replies and trimming the original post down to the most relevant points? Jacek Generowicz wrote: > top-posters tend to write codswallop more often that those who trim > and organize their replies carefully. > > This is partly because the process of trimming the original post, > forces you to identfy the relevant points being made From deetsNOSPAM at web.de Tue Apr 27 14:26:03 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Tue, 27 Apr 2004 20:26:03 +0200 Subject: Intercepting method calls References: Message-ID: Matt Leslie wrote: > I took a look at the language reference and it is not immediately clear > to me how or if I could do this in Python, perhaps I need to override > the __call__ methods for all the instancemethods in the class? I'm not > even sure how I could do this... Any help or suggestions appreciated. A way to accomplish this is the usage of metaclasses. A metaclass gives you a sort of callback that gets invoked with the classname, the base classes and the class dictionary before the actual class object is created. Here you then can creat wrappers around all callables that implement your desired behaviour. See this reciepe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/198078 -- Regards, Diez B. Roggisch From bignose-hates-spam at and-benfinney-does-too.id.au Fri Apr 2 18:49:08 2004 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 3 Apr 2004 09:39:08 +0950 Subject: Translate escaped characters in a string References: Message-ID: On 2 Apr 2004 15:57:59 -0800, - wrote: > (\n is slash+n, and not LF) No, "\n" is backslash + n. Slash + n would be "/n". > I would like to use \n and other supported escape sequences when I > write the text to a file. Once you know the proper name for the character you're talking about, you can find modules like this one: which may be helpful. -- \ "The best is the enemy of the good." -- Voltaire | `\ | _o__) | Ben Finney From mwh at python.net Wed Apr 28 07:24:49 2004 From: mwh at python.net (Michael Hudson) Date: Wed, 28 Apr 2004 11:24:49 GMT Subject: locale.CODESET / different in python shell and scripts References: Message-ID: "Martin v. L?wis" writes: > Nuff Said wrote: > > When I type the following code in the interactive python shell, > > I get 'UTF-8'; but if I put the code into a Python script and > > run the script - in the same terminal on my Linux box in which > > I opened the python shell before -, I get 'ANSI_X3.4-1968'. > > How does that come? > > Because, for some reason, locale.setlocale() is called in your > interactive startup, but not in the normal startup. > > It is uncertain why this happens - setlocale is not normally > called automatically; not even in interactive mode. Perhaps > you have created your own startup file? readline calls setlocale() iirc. Cheers, mwh -- Not only does the English Language borrow words from other languages, it sometimes chases them down dark alleys, hits them over the head, and goes through their pockets. -- Eddy Peters From dialton3#NOSPAM#.despammed at virgilio.it Sat Apr 3 06:44:58 2004 From: dialton3#NOSPAM#.despammed at virgilio.it (Valentino Volonghi aka Dialtone) Date: Sat, 03 Apr 2004 11:44:58 GMT Subject: Parrot for Python References: <930ba99a.0404030251.c2d2107@posting.google.com> Message-ID: <871xn5i8xn.fsf@vercingetorix.caesar.org> sridharinfinity at yahoo.com (Sridhar R) writes: > Why is Java so popular than Python. Are the technologies for Java > available for Python (no ... no jython)? We can implement them in > python if we want. But the difference is speed. There is no reason... Sun is behind java, who is behind Python? Java has a very little library advantage IMHO. Python is growing everyday, as Tim Bray says in his blog here: http://www.tbray.org/ongoing/When/200x/2003/05/08/FutureLanguage -- Valentino Volonghi aka Dialtone Linux User #310274, Gentoo Proud User X Python Newsreader developer http://sourceforge.net/projects/xpn/ From elainejackson7355 at home.com Fri Apr 9 15:32:22 2004 From: elainejackson7355 at home.com (Elaine Jackson) Date: Fri, 09 Apr 2004 19:32:22 GMT Subject: Function args References: Message-ID: I see from further on in the discussion that you've got the picture, so I'll just add a couple of things that may be useful for you to know: The keyword 'is' compares actual identity instead of just equality. (In other words, 'a is b' returns the same value as 'id(a)==id(b)') The function call 'globals()' returns a dictionary representing the current global namespace. "Jean-Michel Caricand" wrote in message news:c55g8u$vvg$1 at s1.read.news.oleane.net... | Bonjour Michel et mer?i pour la r?ponse tr?s rapide. Je tiens ? pr?ciser que | nous d?veloppons en interne | en langage Perl. Ma question peut donc sembler b?te pour des programmeurs | Python. | | Apr?s maintes recherches, je n'ai pas trouv? d'exemples me permettant de | comprendre le m?canisme employ? | par Python pour passer un simple nombre ? une fonction et le modifier | r?ellement. | | Imaginons que je veuille ?crire une fonction qui permute deux variables, | j'?cris : | | def permuter(a,b): | c = b | b = a | a = c | | Si tout est objet, donc pass? par r?f?rence a et b devraient ?tre r?ellement | modifier ? Pourtant ce n'est pas le cas. | | Pourriez simplement me donner un exemple pour cette fonction. Encore mer?i | | "Michel Claveau/Hamster" a ?crit | dans le message de news: c55f5r$f2l$1 at news-reader4.wanadoo.fr... | > Bonjour ! | > | > En Python, les variables sont des sortes de pointeurs sur des objets. Tout | > passage de variable comme param?tres se fait forc?ment par r?f?rence (en | > fait, on passe la r?f?rence ? l'objet). | > De plus l'affectation d'une variable cr?e un autre objet, car la plupart | des | > objets ne sont pas modifiables. | > | > Seuls le sont les listes et les dictionnaires sont modifiables. Une cha?ne | > de caract?res n'est pas modifiable non plus. | > | > Cependant, il existe des modules contenant d'autres types ayant des | > comportement diff?rents. Il est ?galement possible de d?finir ses propres | > classes, dont on (re)-d?finira le comportement. | > | > | > | > PS : il existe aussi un newsgroup fr.comp.lang.python | > | > | > | > @-salutations | > -- | > Michel Claveau | > m?l : http://cerbermail.com/?6J1TthIa8B | > site : http://mclaveau.com | > | > | | From urnerk at qwest.net Wed Apr 14 22:11:40 2004 From: urnerk at qwest.net (urnerk at qwest.net) Date: Wed, 14 Apr 2004 22:11:40 -0400 Subject: List vs tuples References: <107bf8q8fhsmg5e@news.supernews.com> <7in05lfpqt.fsf@enark.csis.hku.hk> Message-ID: Isaac To wrote: >>>>>> "John" == John Roth writes: > > John> It's a common question. A list is a data structure that is > John> intended to be used with homogenous members; that is, with > members John> of the same type. > > I feel you argument very strange. Even that it might be the original > intention, I see nothing in the language that support your argument. > In Python, lists don't care about members being homogenous. There's a less-used array type for that, in the standard library. The principle distinction between lists and tuples is indeed in the mutability department. As for emulating C structs, I liked the suggestion of using a class with only data attributes. That's a logical analogy, as in C++, it's the struct that morphs into the basic class, with the addition of methods to data. However, if you really want to used a low level C struct, there's actually a struct in the standard library implemented using a C struct. Check out: >>> import struct >>> help(struct) etc. Kirby From mark at prothon.org Fri Apr 23 16:29:36 2004 From: mark at prothon.org (Mark Hahn) Date: Fri, 23 Apr 2004 13:29:36 -0700 Subject: Why we will use obj$func() often References: <84Uhc.22278$dZ1.5087@fed1read04><8AWhc.23114$dZ1.11070@fed1read04><40883BFE.B381518A@alcyone.com><27_hc.23801$dZ1.2716@fed1read04><40887145.789A2FE8@alcyone.com><7cki80hj976bia36lhf9er97v073o1pqvm@4ax.com> Message-ID: "Fredrik Lundh" wrote ... > > (by the way, Python cannot do this) > > sure can, if you use mutable integers. That's interesting. I've never heard of them. Can you show me a code example? From loic at fejoz.net Tue Apr 6 09:05:51 2004 From: loic at fejoz.net (Yermat) Date: Tue, 06 Apr 2004 15:05:51 +0200 Subject: design by contract versus doctest In-Reply-To: References: <407174ea$0$5066$4d4ebb8e@news.nl.uu.net> <40718ddb$0$5071$4d4ebb8e@news.nl.uu.net> <4071a6d4$0$5064$4d4ebb8e@news.nl.uu.net> Message-ID: Colin Blackburn wrote: > On Tue, 06 Apr 2004 13:50:02 +0200, Yermat wrote: > > >> Hi, >> Not really each time ! >> As it uses "assert", it is turn off by using -O option of python or >> by removing the metaclass ! So it work exactly as DBC implemented in >> Eiffel. > > > It doesn't work exactly as in Eiffel. In Eiffel it is *part* of the > language. Some aspects of DbC can be implemented in other languages but > not all (invariants for instance are not straightforward.) It does work exactly the same in effect even if the syntax is not the same. But we're both right. >> His author is Bertrand Meyer (with an 'e'). >> So please re-read it again ! > > > I am so sorry that I typed his name incorrectly. Please don't make me > read all 1000 pages again!! Sometime my fingers are typing without my head. That make things funny. ;-) > Colin > -- -- Yermat From loic at fejoz.net Tue Apr 6 09:07:30 2004 From: loic at fejoz.net (Yermat) Date: Tue, 06 Apr 2004 15:07:30 +0200 Subject: design by contract versus doctest In-Reply-To: References: <407174ea$0$5066$4d4ebb8e@news.nl.uu.net> <40718ddb$0$5071$4d4ebb8e@news.nl.uu.net> <4071a6d4$0$5064$4d4ebb8e@news.nl.uu.net> Message-ID: Colin Blackburn wrote: > On Tue, 06 Apr 2004 13:50:02 +0200, Yermat wrote: > > >> Hi, >> Not really each time ! >> As it uses "assert", it is turn off by using -O option of python or >> by removing the metaclass ! So it work exactly as DBC implemented in >> Eiffel. > > > It doesn't work exactly as in Eiffel. In Eiffel it is *part* of the > language. Some aspects of DbC can be implemented in other languages but > not all (invariants for instance are not straightforward.) > >> His author is Bertrand Meyer (with an 'e'). >> So please re-read it again ! > > > I am so sorry that I typed his name incorrectly. Please don't make me > read all 1000 pages again!! > > Colin > -- I forgot to say that the invariant can be checked each time a function is called or ended... Yermat From jdhunter at ace.bsd.uchicago.edu Mon Apr 26 17:27:30 2004 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Mon, 26 Apr 2004 16:27:30 -0500 Subject: Is there a Python library that packs binary data into one file? In-Reply-To: <85b54e91.0404261301.69d5c1e9@posting.google.com> (jacobsmail@postmark.net's message of "26 Apr 2004 14:01:33 -0700") References: <85b54e91.0404261301.69d5c1e9@posting.google.com> Message-ID: >>>>> "Jacob" == Jacob H writes: Jacob> Hello all, Today I began writing a utility script that Jacob> takes given binary files and puts them all into one Jacob> datafile. My idea is to be able to access any binary data I Jacob> want by indexing the datafile, e.g. wanted_image_data = Jacob> datafileobj[IMAGE_DATA]. The purpose is to hide external Jacob> image files from the user in a simple game I'm writing. Jacob> Though I have a good idea of how to implement this, before Jacob> I begin I am curious to know if some Python master out Jacob> there has already come out with a library that does the Jacob> same. Anyone? :) -- How about putting it into a tar file? There are many archive file formats (ISO9960, tar, zip). You could just reuse one of these and an existing python interface to them, compressing and encrypting as necessary if you need extra obscurity. JDH From arcane at deepfort.com Thu Apr 22 07:39:16 2004 From: arcane at deepfort.com (Arcane) Date: Thu, 22 Apr 2004 12:39:16 +0100 Subject: python web programming / CMS In-Reply-To: References: Message-ID: <4087AEE4.2090703@deepfort.com> news.telenet.be wrote: >Hi, > >i'm looking at python to do programming for the new intranet >here at the company. I'm looking at plone/zope also. >Before, I've used jsp for webprogramming but i'm considering >python for this. >One thing that isn't clear to me is if it's possible to include python >code in a html page like you would do with jsp and then have zope >"translate" that to html. With jsp, one could use an apache/tomcat >combo to accomplish this. >If one can't include python in html, is Zope the only alternative and >how does code look like then? > >Thanks > > > > There are various ways to implement a "PSP (Python Server Pages)"-type setup. I don't know how well regarded it is amongst other python users - in fact, I'd be interested to know, but I use the very lightweight Spyce : http://spyce.sourceforge.net. I use Spyce-flavoured apache, in combination with python cgi stuff to great effect on our intranet. Hope this helps. From daniel.dittmar at sap.com Tue Apr 6 11:00:04 2004 From: daniel.dittmar at sap.com (Daniel Dittmar) Date: Tue, 6 Apr 2004 17:00:04 +0200 Subject: design by contract versus doctest References: <407174ea$0$5066$4d4ebb8e@news.nl.uu.net> <40718ddb$0$5071$4d4ebb8e@news.nl.uu.net> <4071a6d4$0$5064$4d4ebb8e@news.nl.uu.net> Message-ID: Yermat wrote: > Colin Blackburn wrote: >> It doesn't work exactly as in Eiffel. In Eiffel it is *part* of the >> language. Some aspects of DbC can be implemented in other languages >> but not all (invariants for instance are not straightforward.) > > It does work exactly the same in effect even if the syntax is not the > same. But we're both right. - in Eiffel, postconditions of methods are inherited (because subclasses must guarantee at least as much). This is difficult to implement with a simple assert statement. - postconditions have access to the values parameters and instance variables had upon entry to the method. This is difficult to support even in a compiler that knows about these things, at least for mutable objects. Daniel From junkmail at solumslekt.org Fri Apr 16 05:23:23 2004 From: junkmail at solumslekt.org (Leif B. Kristensen) Date: Fri, 16 Apr 2004 11:23:23 +0200 Subject: CamelCase versus wide_names (Prothon) References: <87hdvl2dny.fsf@blakie.riol> <87d6692ar8.fsf@blakie.riol> Message-ID: <_CNfc.25593$zf6.94026@news4.e.nsc.no> Hugh Macdonald rose and spake: > On a qwerty keyboard, _ is SHIFT+- (to the right of 0) In my part of the world, _ is also Shift+-, but it's to the right of the . (period). In OO programming in general that's a bit awkward as I frequently type a dot where I want an underscore and vice versa. This is an error that often can be very hard to spot. So, this may be an argument for camelCasing, - which I actually haven't used much since my TurboPascal days. regards, -- Leif Biberg Kristensen http://solumslekt.org/ Validare necesse est From sholden at holdenweb.com Wed Apr 28 14:52:34 2004 From: sholden at holdenweb.com (Steve Holden) Date: Wed, 28 Apr 2004 14:52:34 -0400 Subject: MySQL Connectivity In-Reply-To: References: Message-ID: Gaz Oakley wrote: > Hi, > > I've looked through the mailing list archives trying to find the best ways > of connecting to a MySQL database using Python. From what I've seen, people > seem to be using http://sourceforge.net/projects/mysql-python/. First of > all, is this the recommended method of connectivity? (I'm assuming it is). > > If it is, I've experienced a problem here. I'd ideally like to have Python > 2.3 installed with MySQLdb. Following the instructions on > http://sourceforge.net/forum/forum.php?thread_id=948054&forum_id=70461 I > tried to build an RPM that would work with Python 2.3. It appears to be > using rpm -ba to build. I can fix that, but it would indicate that the build > script is somewhat out of date (rpmbuild has been around for a long time > now). Are there any newer RPM's for this anywhere or any newer build > scripts? Is the testing version relatively stable? (although I havent > checked this is fixing the build problem yet) > If all you want is to *install* the software, why not just run "python setup.py install" instead of trying to create an RPM then install that? regards Steve From faassen at infrae.com Tue Apr 13 07:29:25 2004 From: faassen at infrae.com (Martijn Faassen) Date: Tue, 13 Apr 2004 13:29:25 +0200 Subject: EuroPython: Python Frameworks Track submission deadline approaching Message-ID: <407bcd47$0$570$e4fe514c@news.xs4all.nl> Hi there, The deadline for a talk submission for EuroPython is approaching fast (april 15). I'm the track chair for the Python frameworks track, and could use some more talk submissions! Please see this overview for the place where you can submit talks: http://www.europython.org/conferences/epc2004/info/ Do you have an interesting Python based framework or library you'd like others to know about? Please submit a talk proposal on the frameworks track! Regards, Martijn From pclinch at internet-glue.co.uk Sun Apr 18 10:49:41 2004 From: pclinch at internet-glue.co.uk (Paul Clinch) Date: 18 Apr 2004 07:49:41 -0700 Subject: Cannot import cgi.py -- scripts broken References: Message-ID: <8cf2994e.0404180649.5b0eb071@posting.google.com> yazzoo wrote in message news:... > I've been banging my head over a long running script that has suddenly > stopped working when my ISP upgraded Apache and Suexec. They didn't > specify what they did, but I presume it was the latest updates. > > My problem is that any script that tries to import cgi.py breaks. > > For example, the following script: > > #!/usr/bin/python > print """Content-type: text/html\n\n""" > import cgi, sys, string, os > print """hi""" > > fails with the following message in apache's error log. > > Traceback (innermost last): > File "hello.py.cgi", line 3, in ? > import cgi, sys, string, os > File "/usr/lib/python1.5/cgi.py", line 422, in ? > import urllib > File "/usr/lib/python1.5/urllib.py", line 25, in ? > import socket > ImportError: libssl.so.2: cannot open shared object file: No such file > or directory > looking for libssl.so.2, > > My ISP's tech support confirms that the file is still available on the > server in the directory /usr/local/ssl/lib/libssl.so > libssl.so not the same as libssl.so.2 > any clue's? > > Thanks in advance, > Lester though functionaly they may be. Regards, Paul Clinch From jwsacksteder at ramprecision.com Tue Apr 27 16:49:27 2004 From: jwsacksteder at ramprecision.com (jwsacksteder at ramprecision.com) Date: Tue, 27 Apr 2004 16:49:27 -0400 Subject: Passing through keywork arguments Message-ID: <71650A6F73F1D411BE8000805F65E3CB3B3A8E@SRV-03> If I have a class method that accepts keywork arguments, how may I pass those arguments into a method call of some other class? This is some namespace thing I'm not understanding and I can't seem to find any examples. From jdhunter at ace.bsd.uchicago.edu Fri Apr 16 15:40:02 2004 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Fri, 16 Apr 2004 14:40:02 -0500 Subject: datetimes, tzinfo and gmtime epoch In-Reply-To: ("Robert Brewer"'s message of "Fri, 16 Apr 2004 10:42:12 -0700") References: Message-ID: >>>>> "Robert" == Robert Brewer writes: Robert> John Hunter wrote: >> I have a python2.3 datetime instance and a tzinfo instance (eg >> Eastern from the python library reference). >> >> What is the best way to convert that datetime instance to >> seconds since the epoch, gmtime? Robert> You might try time.mktime(t), where t is a 9-tuple as Robert> desribed at: Yes, but you still have to account for the offset to gmtime, which is dependent on daylight savings time. I *think* this is correct, where x is a datetime instance and tz is a tzinfo instance. offset = self.tz.utcoffset(x).days*SEC_PER_DAY + self.tz.utcoffset(x).seconds gmepoch = time.mktime(x.timetuple())+offset JDH From kfast at poczta.onet.pl Tue Apr 13 13:12:12 2004 From: kfast at poczta.onet.pl (Jakub Fast) Date: Tue, 13 Apr 2004 19:12:12 +0200 Subject: Does Python compete with Java? In-Reply-To: References: <8b336527.0404051337.51bb4a1b@posting.google.com> Message-ID: <407C1F6C.3010203@poczta.onet.pl> >>Over the long term, I think Python's biggest key to success will be that we >>will still be able to read the programs that we are writing now. > > > No argument here :) Hi, I'm totally fresh to python, and i'm enjoying the language, and the readability a lot, but i just bumped into something that -- from my purely subjective perspective -- surprised me with pretty awful, not-very-readable syntax: operator overloads and static methods. is this an issue that is argued over? i just find these particular bits to be 10x more intuitive the way they are implemented in c++... would having the possibility of using def static mymethod(): instead of the standard = staticmethod(...) do anything bad to python as it is? Same question goes for something along the lines of __operator__['='] (self, etc). On quite another note, is it possible to define your own operators in python? you could argue that this might actually make the code _less_ transparent, but then, at least for some cases, my experience shows that a few cleverly defined operators work magic in terms of bumping up the ease-of-use of a library. what i'm thiniking about, exactly, are the "--->"'s, "==>"'s, or "~~>"'s you'll see people using in prolog for instance. Also, can "and", "or", "not" etc. be overloaded? I've been pondering using python+NLTK to teach a computational semantics class this summer (precisely because i think the basics of python would be easy for the students to learn quickly, and, class aside, that learning them actually might turn out useful for whatever they want to do in the future -- more useful than, say, prolog) and nothing can beat the intuitive appeal of S ==> (NP and VP) or VP over CFGProduction(S, NP, VP), CFGProduction(S, VP) for specifying your simple cfg, dcg or ebnf rules if you're completely new to programming and have just been given a programming assignment :) Any comments, any answers? Thanks in advance. Kuba Fast From daniel.dittmar at sap.com Thu Apr 29 11:41:37 2004 From: daniel.dittmar at sap.com (Daniel Dittmar) Date: Thu, 29 Apr 2004 17:41:37 +0200 Subject: static keyword References: Message-ID: Nick Jacobson wrote: > I believe the following "static" command would be useful in Python. [...] > Just like in C, the variables i and firstcall are only assigned the > first time foo() is called. To get this effect currently, one could > use default arguments or wrapping the whole thing in a class. Both of > these solutions seem like hacks, the above method IMO is more > Pythonic. :) You could also use funtion properties >>> def statictest (): ... statictest.counter += 1 ... print statictest.counter ... >>> statictest.counter = 0 >>> statictest () 1 >>> statictest () 2 But this uses two lookups: one for the function in module scope and one for the property. Three if you want to do this in a method (class.method.property). Just to describe all the possibilities, I probably wouldn't use this myself. Daniel From peter at engcorp.com Fri Apr 2 07:59:17 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 02 Apr 2004 07:59:17 -0500 Subject: Python conference slogan In-Reply-To: <406D57FF.4040601@mplusr.de> References: <30260531.0404010833.1b834032@posting.google.com> <406C4DDF.5000907@zope.com> <406D57FF.4040601@mplusr.de> Message-ID: Peter Maas wrote: [slogans] - Wrap Python around your problem and crush it. From rnichol_rrc at yahoo.com Sun Apr 18 14:26:18 2004 From: rnichol_rrc at yahoo.com (Reid Nichol) Date: Sun, 18 Apr 2004 13:26:18 -0500 Subject: os.system help In-Reply-To: References: <78lgc.3445$AL1.7744@news1.mts.net> Message-ID: <5Lzgc.4355$AL1.9508@news1.mts.net> The registry contains certain data but not *exactly* the data I need. I could construct from that but according to the docs it's quite new so I'd rather not use it. I know there has to be a way to tell if I'm on a certain platorm. Something like: if __win32__: print 'on windows' But, I can't find any docs on that. I'm probably looking in the wrong place, so, could someone point me in the right direction or just give me that if statment. Thanks Jeremy Sanders wrote: > On Sat, 17 Apr 2004 23:32:01 -0500, Reid Nichol wrote: > > >>Unfortunately PIL only writes .eps files. I was going to get the users >>to install gs but of course it's install directory is variable. I've >>tried using shortcuts but that didn't work. >> >>Since most of my intended users use windows only... > > > I'm not familiar with GS on Windows, but it may be worth searching the > registry to see whether the install path is written there. > > Jeremy > From theller at python.net Wed Apr 14 08:46:56 2004 From: theller at python.net (Thomas Heller) Date: Wed, 14 Apr 2004 14:46:56 +0200 Subject: Unable to create com object - need help References: <2D89F6C4A80FA547BF5D5B8FDDD04523060C62@exchange.adrembi.com> Message-ID: "Roman Yakovenko" writes: > Thank you very much. I definitly will try your module. > Also I still have to questions: > 1. How does VB success to work with this dll? > 2. Why after using makepy utility I don't get interface registered in DiaSource class > > I understand that the first question is generic one, and has nothing > to do with python. But any reference to this specifiec topic will be > appreciated. Also I'd like to know the answer to the second > question. It will help me a lot in my future work > I'm afraid I'm not qualified to answer any of these questions. You might be able to gain further insights to the answer for the second by examining the makepy sources. Thomas From user_77 at hotmail.com Wed Apr 14 10:43:25 2004 From: user_77 at hotmail.com (Nobody) Date: Wed, 14 Apr 2004 14:43:25 GMT Subject: [wxPython] MVC example? Message-ID: I'm trying to wrap my mind around MVC. Does anyone have a _simple_ example of using the MVC pattern with wxPython? Maybe just a simple window with a dialog box that allows one to update some data. Please. Thanks, Wr From junkmail at solumslekt.org Wed Apr 28 03:00:19 2004 From: junkmail at solumslekt.org (Leif B. Kristensen) Date: Wed, 28 Apr 2004 09:00:19 +0200 Subject: Is Perl *that* good? References: <108q51j4dscn7dc@corp.supernews.com> Message-ID: S Koppelman wrote: [Leif B. Kristensen] >> In theory, the web routine for phonetic searches might have been >> implemented in PHP. The trouble with that is that I would have to >> maintain both a PHP and a Perl version of the same routine. I find it >> much easier to just copy and paste the whole mess (at present about >> 120 lines) between the encoding and the decoding routines in Perl, >> and run an exec("perl norphon.pl $name") from PHP. > > Well, that's not PHP's fault, especially with such straightforward > regexps. The only reason to user perl over PHP in that case is the > valid one you cite: you already wrote the damned code in perl. ;) I actually did rewrite the routine once in PHP, but I usually find regexps in any other language than Perl a PITA. > Meanwhile, wouldn't it run more efficiently if you hosted your perl > functions under mod_perl or some other persistent harness like a SOAP > or XML-RPC daemon and had the PHP call accross to that? I don't run my own Web server, so I have limited opportunities for configuration. Exec() seems to be the only viable alternative for now. > Execing out > and having perl launch, compile and run your script each time is a > waste of resources, not to mention needlessly slow. You might not > notice it if you're the only person using it, but if there's a sudden > uptick in traffic to your site from fellow Scandinavian diaspora > genaologists, you will. I had expected some penalty for running a Perl routine from PHP, but in practice, the process is blazingly fast. You may verify this for yourself if you visit http://solumslekt.org/slekta/innhold.php and enter some common Norwegian name like "Berte" in the "Fornavn" (given) field, and "Olsdatter" in the "Etternavn" (surname, or more likely a patronym) field. The page is generated and served in a fraction of a second, as you can see in the blue box at the bottom. I wonder if Apache is smart enough to keep the compiled Perl code cached in memory, even if mod_perl is not loaded? regards, -- Leif Biberg Kristensen http://solumslekt.org/ Validare necesse est From mikalzetTogli at interfree.it Tue Apr 6 05:12:53 2004 From: mikalzetTogli at interfree.it (TaeKyon) Date: Tue, 06 Apr 2004 09:12:53 GMT Subject: Compact Python library for math statistics References: Message-ID: Il Mon, 05 Apr 2004 19:41:52 -0700, Chris Fonnesbeck ha scritto: >> > I'm looking for a Python library for math statistics. This must be a cl >> ear set of general statistics functions like 'average', 'variance', 'cova >> riance' etc. You can also use R from within python; take a look at: http://www.omegahat.org/RSPython/ -- Michele Alzetta From eldiener at earthlink.net Sun Apr 4 08:40:20 2004 From: eldiener at earthlink.net (Edward Diener) Date: Sun, 04 Apr 2004 12:40:20 GMT Subject: Difference between default arguments and keyword arguments Message-ID: In the tutorial on functions there are sections on default arguments and keyword arguments, yet I don't see the syntactic difference between them. For default arguments the tutorial shows: def ask_ok(prompt, retries=4, complaint='Yes or no, please!'): while for keyword arguments the tutorial shows: def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'): The syntax 'keyword = value' is used for both as far as I can see. How does one distinguish between them or are they both part of the same combined concept, which is: if one calls the function with less than the required number of arguments but does specify keyword values, those values are used, else the defaults are supplied. Or is there really a syntactic difference between default arguments and keyword arguments which I have missed above ? From loic at yermat.net1.nerim.net Tue Apr 13 15:01:24 2004 From: loic at yermat.net1.nerim.net (Yermat) Date: Tue, 13 Apr 2004 21:01:24 +0200 Subject: A new OS In-Reply-To: <107k441hitt2ld9@corp.supernews.com> References: <107k441hitt2ld9@corp.supernews.com> Message-ID: A Evans a ?crit : > Hello Everyone I am working towards starting a project developing a new > Operating System using the Python language (or a derivative thereof). As > recommended on this forum I am asking if people are interested in something > like this and ask who would be willing to support a project this large. > > Any and all ideas are welcome this message is just to see what kind of > support this project would recieve > > Cheers > > Andrew > > Taking a look at the Isaac Project may give you some hints... http://www.isaacos.com/ It's based on an object-oriented and dynanism language named lisaac (even inheritage is dynamic). -- Yermat From faizan at jaredweb.com Tue Apr 20 20:28:40 2004 From: faizan at jaredweb.com (Fazer) Date: 20 Apr 2004 17:28:40 -0700 Subject: Opening MS Word files via Python Message-ID: <7b454334.0404201628.371b9e8@posting.google.com> Here comes another small question from me :-) I am curious as to how I should approach this issue. I would just want to parse simple text and maybe perhaps tables in the future. Would I have to save the word file and open it in a text editor? That would kind of....suck... Has anyone else tackled this issue? Thanks, From stewart at midtoad.homelinux.org Sat Apr 3 11:09:21 2004 From: stewart at midtoad.homelinux.org (Stewart Midwinter) Date: Sat, 03 Apr 2004 16:09:21 GMT Subject: rlght click menu missing in most Tk apps References: Message-ID: On Wed, 31 Mar 2004 22:09:57 -0500, eltronic wrote: > here is some code to add right click context menus. > in the few apps I've edited sofar, it just works, once > you run rCbinder with the root of the gui or bind B3 > all present and future widgets will have right click. how about a little example app showing how it is used? thanks S From sridharinfinity at yahoo.com Mon Apr 12 06:01:05 2004 From: sridharinfinity at yahoo.com (Sridhar R) Date: 12 Apr 2004 03:01:05 -0700 Subject: Documentation tool for python source code Message-ID: <930ba99a.0404120201.65203953@posting.google.com> Hi, I am just wondering why epydoc isn't mentioned (or atleast in main page) in the docsig section of www.python.org. Or what python source code documentation system is prefered. I feel I should decide on this before starting my project, as I should be formatting the docstrings acc. to the doc system. Happydoc seems to generate `not-so-good` looking HTML documentation, as epydoc does. Any thoughts? From nuffsaid at phreaker.net Fri Apr 30 12:16:13 2004 From: nuffsaid at phreaker.net (Nuff Said) Date: Fri, 30 Apr 2004 18:16:13 +0200 Subject: locale.CODESET / different in python shell and scripts References: <4091621F.5060307@v.loewis.de> <4091BA4A.4000608@v.loewis.de> Message-ID: On Fri, 30 Apr 2004 11:56:19 +0200, Nuff Said wrote: > But *I do use* the line > > # -*- coding: UTF-8 -*- > > from your PEP (directly after the shebang-line; s. the full source > code in my earlier posting). I thought, that allows me to write u"?" > (which - as described above - works in one of my two Pythons). Follow up to myself: Arrgh!!! Think I got it now. Your PEP 263: 'Source Code Encodings' was incorporated into Python 2.3 (i.e. my self-compiled Python) but not into Python 2.2 (Fedora's Python). Thanks for your help! From irmen at -nospam-remove-this-xs4all.nl Thu Apr 15 17:13:38 2004 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Thu, 15 Apr 2004 23:13:38 +0200 Subject: Socket error: 10053 software caused connection abort In-Reply-To: References: <407eda4e$0$576$e4fe514c@news.xs4all.nl> Message-ID: <407efb02$0$563$e4fe514c@news.xs4all.nl> Jean-Pierre Bergamin wrote: > But how can I know the amout of data I will receive? There's no way to do > that, since it's totally random how large the sent data will be. Ah! You have to adapt your program. The usual pattern here is to encode the length of the data that will be sent, send that size first (in a fixed amount of bytes for instance) and after that, send the data. The receiving side first grabs the encoded integer from the socket, and then starts to recv() the given amount of bytes. You can use the struct module to encode the length of the data stream in a fixed amount of bytes (say, 4). Send those 4 bytes first. Then send your message. The recipient first reads exactly 4 bytes, uses the struct module to decode that back into an integer, then reads the specified length. If you only use the socket connection for a single request/response, you can also shutdown() the socket after sending is complete. The recv() will notice this. HTH, --Irmen de Jong. PS: I once developed a low level socket protocol, that is used by Pyro. It essentially does the same as described above (but more complex). But since I now have Pyro, I usually don't have to think and bother about the low level stuff anymore ;-) From fumanchu at amor.org Thu Apr 29 11:52:47 2004 From: fumanchu at amor.org (Robert Brewer) Date: Thu, 29 Apr 2004 08:52:47 -0700 Subject: static keyword Message-ID: Nick Jacobson wrote: > I believe the following "static" command would be useful in Python. > > def foo(): > static i = [10, 11] > static firstcall = True > if firstcall: > print "First pass" > firstcall = False > i[0] += 1 > print i[0] > foo() > foo() > > > This would output: > > First pass > 11 > 12 Bah. All these old fogies with their default arg hacks, when Nick *clearly* wants a generator: >>> def foo(): ... i = 10 ... print "First pass" ... while True: ... i += 1 ... yield i ... >>> g = foo() >>> g.next() First pass 11 >>> g.next() 12 Robert Brewer MIS Amor Ministries fumanchu at amor.org From arifi at turk.net Sun Apr 11 02:33:25 2004 From: arifi at turk.net (Arifi Koseoglu) Date: 10 Apr 2004 23:33:25 -0700 Subject: Newbie Q: Extra spaces after conversion from utf-8 to utf-16-le ? Message-ID: <915dc3ae.0404102233.4248dc9a@posting.google.com> Hello everyone. I am an absolute Newbie who has done a good amount of googling with the keywords utf-8, utf-16, python, convert and has reasoned that the following code could be used to convert a utf-8 text file to a utf-16-le (I believe this is what Windows uses for Unicode): s1 = open("utf8_file_generated_with_perl.txt", "r").read() s2 = unicode(s1, "utf-8") s3 = s2.encode("utf-16-le") open ("new_file_supposedly_in_utf16le", "w").write(s3) Well, this code kind of works (meaning I do not get any errors), but the produced file contains an extra space after every character (l i k e t h i s) and Windows believes this is an ANSI (i.e. non-unicode file). Clearly, what I think is working is actually not. What do I need to do? Many thanks in advance, -arifi From deetsNOSPAM at web.de Wed Apr 28 12:29:00 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Wed, 28 Apr 2004 18:29:00 +0200 Subject: PyChecker does STATIC analysis? References: <3064b51d.0404280728.5fb7539e@posting.google.com> Message-ID: beliavsky at aol.com wrote: > before finding the out-of-bounds error. I have seen PyChecker > described as a "static analysis" tool, and it does find some problems > that such a tool ought to. But it seems that for the simple program I > have shown, it basically runs the program, and I could just run the > Python program to find the same errors. An aspect of Python > programming that sometimes frustrates me is that a program will run, > perhaps for a few minutes, before stopping because of a misspelled > variable or an out-of-bounds variable. It seems that currently, > PyChecker will not solve this problem. I wish there were a tool that > did (and would be willing to pay for it). > > The Lahey/Fujitsu Fortran 95 compiler is able to catch the > out-of-bounds error at COMPILE time for an analogous Fortran program. while there might be not-so-obvious cases that can be found using static analysis, the halting problem also applies here: There is no such thing as a automated analysis that finds out if your prgram is going to die or not. So automatically running a program as part of the analysis is as valid as any other technique - as long as there are no permantent sideeffects (you don't want your partitioning code accidentially ruin your hd while developing...) Given the fact that nobody prevents you from doing this: >>> xrange = lambda x: [1,2,3,4,5] >>> x = range(3) >>> print x[3] 4 you can fool a static analysis, I wont blame Pychecker too much. -- Regards, Diez B. Roggisch From claird at lairds.com Sat Apr 24 18:41:23 2004 From: claird at lairds.com (Cameron Laird) Date: Sat, 24 Apr 2004 22:41:23 -0000 Subject: A python telnet entry level question References: Message-ID: <108lr8jmr2u1202@corp.supernews.com> In article , Eddie Corns wrote: . . . >You are maybe being too specific in what you match for. At least one of my >machines prompts: > > Pasword for : > >rather than just "Password: ". I tend to match things like > >"ogin" (in case of Login vs login) >"assword" (will this get filtered out by censoring s/w?) > >Eddie This sort of tolerance can lead to its own problems (though I entirely agree you're right to recommend it). Some logins are so sensitive to timing (in essence) that matching "assword" rather than "assword:" results in the telnetd ignoring the first character or two of response. So what to do? At this level, there is *no* good answer. The most enlightened thought is simply to recognize that telnet forces one into a cascade of heuristic hacks. -- Cameron Laird Business: http://www.Phaseit.net From phil at riverbankcomputing.co.uk Mon Apr 19 14:14:55 2004 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Mon, 19 Apr 2004 19:14:55 +0100 Subject: using QFtp class in PyQT In-Reply-To: <2aa196bb.0404190559.3c41485d@posting.google.com> References: <2aa196bb.0404190559.3c41485d@posting.google.com> Message-ID: <200404191914.55928.phil@riverbankcomputing.co.uk> On Monday 19 April 2004 2:59 pm, Kim wrote: > Hi everybody, > I tried to write simple FTP program using PyQt version 3.11. The > document say that QFtp has been implemented, but i keep getting error > message from my simple program : > > My Program: > > from qt import * > from qtnetwork import * > > def gotSignalStart(*arg): > print "start ",arg > > def gotSignalState(*arg): > print "state ",arg > > def gotListInfo(*arg): > print "List info ",arg > > def doFTP(): > fh = QFtp() > QObject.connect(fh,SIGNAL("start()"),gotSignalStart); > QObject.connect(fh,SIGNAL("stateChanged()"),gotSignalState); > QObject.connect(fh,SIGNAL("listInfo()"),gotListInfo); > fh.connectToHost("ftp.trolltech.com") > fh.login() > print fh.state() > if fh.state() != QFtp.Unconnected : fh.close() > > doFTP(); > > Error messages: > > QObject::connect: No such signal QFtp::start() > QObject::connect: (sender name: 'unnamed') > QObject::connect: (receiver name: 'unnamed') > QObject::connect: No such signal QFtp::stateChanged() > QObject::connect: (sender name: 'unnamed') > QObject::connect: (receiver name: 'unnamed') > QObject::connect: No such signal QFtp::listInfo() > QObject::connect: (sender name: 'unnamed') > QObject::connect: (receiver name: 'unnamed') > 0 You must give the full (C++) signature of the signal, eg... SIGNAL("listInfo(const QUrlInfo &)") > QSocket::writeBlock: Socket is not open QFtp is asynchronous. You need an event loop to make sure things actually happen. Phil From fma at doe.carleton.ca Tue Apr 13 05:55:10 2004 From: fma at doe.carleton.ca (Fred Ma) Date: 13 Apr 2004 09:55:10 GMT Subject: Once-only evaluation of default parameter values function definitions References: <407B79D7.424F65A1@doe.carleton.ca> <107n2g6q9an672b@corp.supernews.com> Message-ID: <407BB8F5.E694AA49@doe.carleton.ca> Michael Geary wrote: > > Example#1 > > --------- > > def f(a, L=[]): > > L.append(a) > > return L > > > > Example#2 > > --------- > > def f(a, L=None): > > if L is None: > > L = [] > > L.append(a) > > return L > > Here's a simpler example: > > >>> a = [] > >>> b = a > >>> a > [] > >>> b > [] > >>> a.append(1) > >>> a > [1] > >>> b > [1] > > See what happened? The statement 'b = a' didn't make a copy of a and > store it in b. Instead, it made the name b refer to the same object > as a. So, when I said b.append(1), it meant exactly the same thing > as if I'd said a.append(1). Thanks, Mike. That's alot clearer. The default value looks like it's a persistent object. It is similar to a static local variable in C++. In Example#1, that object actually got changed. In contrast, in Example#2, the code prevents L from remaining bound to None beyond the first line, so the None object never gets changed. In fact, my 2nd explanation was close: that there is an unnamed persistent object that holds the default value to be bound to L for invocations that don't explicity supply an argument for L. The place I went wrong was to say that L never gets bound to None again, after it has been bound to a caller supplied object on a previous invocation of the function. Fred From drs at remove-to-send-mail-ecpsoftware.com Tue Apr 20 03:52:06 2004 From: drs at remove-to-send-mail-ecpsoftware.com (drs) Date: Tue, 20 Apr 2004 07:52:06 GMT Subject: Book "Programming on Win32" still useful? References: <39cbe663.0404192259.3e105972@posting.google.com> Message-ID: "Piet" wrote in message news:39cbe663.0404192259.3e105972 at posting.google.com... > Hi all, > I started programming (or hacking) python some time ago. Since python > offers a lot of Win32 specific extensions and since my OS will > probably stay Win2k for the next time, I would like to know the > possibilities of Win32 programming with python a little better. In > this context I stumbled over the book mentioned in the title, which > really looks like what I?ve been looking for, but I am a little afraid > because it was published 4 years ago and covers only python 1.52. Both > Python and the Win32 interface have been continuously developped, and > I don?t know whether the things I can learn from this book are still > useful today. Can somebody give me some advice whether this book is > still a good buy? I think it will surely be enough to get the basics, > but what if I want more? It is still very useful. While Python has changed, the parts that are covered in the book have not changed that much. Further, aside from .NET, win32 is about the same -- particularly since you are using the version of windows that was current when the book was published. -d From loic at fejoz.net Thu Apr 29 11:04:41 2004 From: loic at fejoz.net (Yermat) Date: Thu, 29 Apr 2004 17:04:41 +0200 Subject: python 2.3's lambda behaves old fashioned In-Reply-To: References: Message-ID: Uwe Schmitt wrote: > Hi, > > I just tried (Python 2.3) > > li = [ lambda x: x*a for a in range(10) ] > > which results in > > li[0](1) = 9 > ... > li[9](1) = 9 > > In order to achieve the intended result I had to fall back on the > following trick: > > li = [ lambda x,a=a: x*a for a in range(10)] > > which leads to the expected result. > > Any explanations ??? > > Greetings, Uwe. > > exactly like this thread : http://groups.google.fr/groups?hl=fr&lr=&ie=UTF-8&oe=UTF-8&threadm=tyfn0696x8w.fsf%40pcepsft001.cern.ch&rnum=2&prev=/groups%3Fq%3Dlambda%2Bdefault%2Bgroup:comp.lang.python%26hl%3Dfr%26lr%3D%26ie%3DUTF-8%26oe%3DUTF-8%26as_drrb%3Db%26as_mind%3D1%26as_minm%3D1%26as_miny%3D2004%26as_maxd%3D29%26as_maxm%3D4%26as_maxy%3D2004%26selm%3Dtyfn0696x8w.fsf%2540pcepsft001.cern.ch%26rnum%3D2 (search "lambda default group:comp.lang.python" on google, thread of the 6 jan 2004) or at : http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&oe=UTF-8&th=4bca1bec20119375&rnum=6 hint: this is a matter of scope... -- Yermat From mike at nospam.com Tue Apr 13 01:39:44 2004 From: mike at nospam.com (Mike) Date: Mon, 12 Apr 2004 22:39:44 -0700 Subject: FutureWarning question Message-ID: <16mnetilcmds6.1apnyu46tbjpw.dlg@40tude.net> I ran across the message below in 2.3.2 today. These are the lines of code: 402: if m1_hi >> 15 & 0x0001 == 1: 403: m1_hi = m1_hi | 0xFFFF0000 404: if m1_lo >> 15 & 0x0001 == 1: 405: m1_lo = m1_lo | 0xFFFF0000 This is the warning message: pwg.py:403: FutureWarning: hex/oct constants > sys.maxint will return positive values in Python 2.4 and up m1_hi = m1_hi | 0xFFFF0000 pwg.py:405: FutureWarning: hex/oct constants > sys.maxint will return positive values in Python 2.4 and up m1_lo = m1_lo | 0xFFFF0000 m1_hi and m1_lo are 32 bit values read from a file. It's not clear to me what the warning message means. The only constant is 0xffff0000; does the message mean that the result of the OR operation won't be what I think it is? Can anyone elucidate? Thanks, -- Mike -- From gerrit at nl.linux.org Fri Apr 9 09:08:31 2004 From: gerrit at nl.linux.org (Gerrit) Date: Fri, 9 Apr 2004 15:08:31 +0200 Subject: Indent testers needed (Prothon) In-Reply-To: References: Message-ID: <20040409130831.GA7434@nl.linux.org> Jacek Generowicz wrote: > Jon Perez writes: > > Perhaps the pro-spaces people can explain how they deal > > with it. > > Emacs Vim -- Weather in Amsterdam Airport Schiphol, Netherlands 09/04 14:25: 8.0?C Few clouds mostly cloudy wind 4.5 m/s NNW (-2 m above NAP) -- Experiences with Asperger's Syndrome: EN http://topjaklont.student.utwente.nl/english/ NL http://topjaklont.student.utwente.nl/ From tismer at stackless.com Fri Apr 2 08:36:20 2004 From: tismer at stackless.com (Christian Tismer) Date: Fri, 02 Apr 2004 15:36:20 +0200 Subject: Fake post alert(was: Stackless Website down, Project gone, I'm dead.) In-Reply-To: References: Message-ID: <406D6C54.7070900@stackless.com> Robert Brewer wrote: ... > I hope I'm hearing your words as worse than you mean them. I haven't > been on this list for long, but I've quickly learned to appreciate your > ingenuity, experience, and determination. I was going to tell you today > I ended up using your solution to my recent deduping problem > (sufficiently molded to my existing code, of course ;)--I really > appreciate your help with that! That's nice to hear! I'm interested to know how you got along with removing relationships between records. > If Stackless is truly gone, I pray you are able to find a new project or > group where you feel truly useful. I don't deserver this honor, since I didn't write that nonsense. But many thanks, anyway. sincerely -- 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 mobile +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 tim.one at comcast.net Mon Apr 19 22:48:48 2004 From: tim.one at comcast.net (Tim Peters) Date: Mon, 19 Apr 2004 22:48:48 -0400 Subject: datetimes, tzinfo and gmtime epoch In-Reply-To: Message-ID: [John Hunter] > ... > Thanks Tim Peters for defining all these nice tzinfo classes! Why > aren't these part of the standard datetime module, or are they lurking > somewhere in there? Guido & I wrote a handful of sample tzinfo classes, but none are in the distribution outside of documentation. People argued too much, and there wasn't time to sort that all out. The hope was that people who actually *use* time zones (not necessarily the same set of people as like to argue about them) would combine forces and contribute a comprehensive set of tzinfo classes. Alas, so far nobody has even contributed a PEP on the topic. supply-equals-supply-ly y'rs - tim From usenet at microtonal.co.uk Wed Apr 14 09:56:20 2004 From: usenet at microtonal.co.uk (Graham Breed) Date: Wed, 14 Apr 2004 14:56:20 +0100 Subject: Bug in eval function? In-Reply-To: References: Message-ID: Pascal wrote: >>>>eval('88200') > > 88200 > >>>>eval('00088200') > > > Traceback (most recent call last): > File "", line 1, in -toplevel- > eval('00088200') > File "", line 1 > 00088200 > ^ > SyntaxError: invalid token Yep! >>> eval('010') 8 A leading zero means an octal number. You can't have digits larger than 7 in octal. The token it says is invalid is invalid. It isn't invalid, unless you've spotted something more subtle being wrong. Graham From solution88pro at hotmail.com Wed Apr 7 08:05:59 2004 From: solution88pro at hotmail.com (Senthoorkumaran Punniamoorthy) Date: Wed, 07 Apr 2004 18:05:59 +0600 Subject: String comparison problem Message-ID: I am printing these information. print string.lower(info_res[2]) print string.lower(md5sum(f_md5)) print len(string.lower(info_res[2])) print len(string.lower(md5sum(f_md5))) print str(string.lower(md5sum(f_md5)) == string.lower(info_res[2])) and the output are 01b7ebfc27437a90cc421c50df8f9ac5 01b7ebfc27437a90cc421c50df8f9ac5 32 32 False I was wondering why the last print statement is returning false when two strings are identical? Senthoor _________________________________________________________________ Tired of spam? Get advanced junk mail protection with MSN 8. http://join.msn.com/?page=features/junkmail -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: theretriever1.01h.py URL: From pxlpluker at cfl.rr.com Sun Apr 4 15:00:46 2004 From: pxlpluker at cfl.rr.com (pxlpluker) Date: Sun, 04 Apr 2004 15:00:46 -0400 Subject: ANNOUNCE: 'goto' for Python In-Reply-To: References: Message-ID: <40705B5E.5010709@cfl.rr.com> Hi Richie, If i am reading the docs right we can only goto/comefrom within the same "container" that goto is defined in. I see it as a way to skip sections of code based on earlier decisions. If i am right i sure could have used this 2 weeks ago. I am a python noob and I eventually just set a "skip this" flag with an if statement. Richie Hindle wrote: >[Tim] > > >>Guido has already accepted your module for inclusion in Python 2.4, and I >>expect he'll use his time machine then to ensure that it's always been part >>of Python. >> >> > >Great! That will have saved me a lot of work, once the new time-line >comes into effect. I can re-use the time for the next job - enhancing >Python's parser to allow Duff's Device. > > > >>[Explanation of numeric labels snipped] >>Your introduction of alphanumeric labels to Python is already far advanced. >> >> > >Ah, OK, good. I won't have to re-learn anything when the new feature goes >into Python 0.1. > > > >>I must say, though, that the restriction to 5 digits in Fortran had the nice >>Pythonic effect of discouraging a subroutine from containing more than a >>hundred thousand branch targets >> >> > >That's a good point, but not really applicable here. I haven't limited >the number of labels, partly because I don't want any B&D to the feature, >and partly because alphanumeric labels ought to be more differentiable >than numeric ones. > > > >>Full speed ahead! >> >> > >Or backwards, or in fact to pretty much anywhere! > > > From opengeometry at yahoo.ca Thu Apr 22 16:49:06 2004 From: opengeometry at yahoo.ca (William Park) Date: 22 Apr 2004 20:49:06 GMT Subject: Regexp optimization question References: Message-ID: Magnus Lie Hetland wrote: > Any ideas? Few concrete examples, perhaps? Sadly, my telepathetic power is not what it used to be... -- William Park, Open Geometry Consulting, Linux solution/training/migration, Thin-client From bokr at oz.net Wed Apr 28 21:30:55 2004 From: bokr at oz.net (Bengt Richter) Date: 29 Apr 2004 01:30:55 GMT Subject: Explanation of Instance Variables in Python References: Message-ID: On 29 Apr 2004 01:10:21 GMT, bokr at oz.net (Bengt Richter) wrote: >On Wed, 28 Apr 2004 11:25:08 -0700, David MacQuigg wrote: > >> >>I am writing a chapter for teaching OOP in Python. This chapter is >>intended as a brief introduction to replace the more complete >>discussion in Learning Python, 2nd ed, pp. 295-390. I need to explain >>instance variables. You might want to mention early that they are a special subset of object attributes, and that understanding the Python rules for accessing attributes in general is critical to understanding its implementation of OOP. >> >>===================================== >> >>Thanks for your help on this project. >> >I find well-annotated examples best for understanding something new. >It also gives me working code to play with, to explore variations. >How things break is often as instructive as how they work. > >I would suggest you encourage your students to experiment interactively. >E.g., ask who can explain the following, and see what you get, and then >collaborate with them to write sufficient comments to where they feel >they "get it." > Actually, looking at my previous example, maybe this would give more hints, in case they don't discover for themselves (strongly urge teaching how to fish, not serving fish, though ;-): >>> class C(object): pass ... >>> def f(*args): print 'f was called with', args ... >>> f >>> C >>> f('hello') f was called with ('hello',) >>> c=C() >>> c <__main__.C object at 0x00901370> >>> c.f('hello') Traceback (most recent call last): File "", line 1, in ? AttributeError: 'C' object has no attribute 'f' >>> c.f = f >>> c.f >>> c.f('hello') f was called with ('hello',) >>> C.f = f >>> c.f >>> c.f('hello') f was called with ('hello',) >>> del c.f >>> c.f > >>> c.f('hello') f was called with (<__main__.C object at 0x00901370>, 'hello') Regards, Bengt Richter From paul at prescod.net Sat Apr 10 19:16:03 2004 From: paul at prescod.net (Paul Prescod) Date: Sat, 10 Apr 2004 16:16:03 -0700 Subject: Python is the best and most popular general purpose scripting language; the universal scripting language In-Reply-To: <20040410225019.GA16891@vulcan.cprogrammer.org> References: <20040410225019.GA16891@vulcan.cprogrammer.org> Message-ID: <40788033.3030209@prescod.net> Jonathan Daugherty wrote: > # So, what makes something a "scripting language" as opposed to a > # "programming language"? > > In a general sense I think "programming" languages are compiled and > "scripting" languages are interpreted. (If you want to go academic, > you could say python is both, but the internals of the interpreter are > irrelavant insofar as one might say it is an interpreted language.) > So which is Lisp? Prolog? Smalltalk? ML? What happens if I compile Python to a binary via Pyrex or to JVM bytecodes via Jython? I propose: A scripting language is a language that makes scripting (gluing together components) easy. A programming language is a language that makes programming (including the creation of components) easy. Python is both. Paul Prescod From fabio.trezziCANCELLAMI at email.it Tue Apr 20 17:20:28 2004 From: fabio.trezziCANCELLAMI at email.it (Wezzy) Date: Tue, 20 Apr 2004 23:20:28 +0200 Subject: emacs for OS X References: <1gcjrc7.1s60i39g5q0kiN%fabio.trezziCANCELLAMI@email.it> Message-ID: <1gckdxe.x3vsll1r5u4tfN%fabio.trezziCANCELLAMI@email.it> Skip Montanaro wrote: > Wezzy> Download python-mode from python.org: > Wezzy> http://www.python.org/emacs/python-mode/python-mode.el > > Ancient, ancient, ancient! > > Pop up a level to > > http://www.python.org/emacs/python-mode/ > > and you'll read: > > The current release of python-mode.el is no longer maintained on this > website. Check the python-mode project on Sourceforge instead. > Today when i post my message i've opened http://www.python.org/emacs/python-mode/ and followed the link to sf.net but the project hasn't released any file yet, so i've posted the url to the www.python.org version that is still online. > The version you referred to (which I don't think is any longer linked to > from the website) is 4.6. The current version is 4.54. > i've downloaded python-mode.el few time ago so i didn't know that there are new versions, thanks for this info. (Anyway the old one is still online) -- Ciao Fabio From http Thu Apr 22 02:30:00 2004 From: http (Paul Rubin) Date: 21 Apr 2004 23:30:00 -0700 Subject: Naming conventions References: <5a88ee0a.0404212223.15f50fe9@posting.google.com> Message-ID: <7xzn94sexj.fsf@ruckus.brouhaha.com> uzairaqeel at yahoo.com (Uzair) writes: > Why aren't the names of the modules in the standard library fixed so > that they follow some actual naming convention? That is probably the > biggest deterrent for new users -- having to dig through several > sources to find the module they're interested in. And, as with urllib > and urllib2, it isn't even clear at first glance which is more useful > and when it should be used... The usual convention with things like urllib/urllib2 is that someone writes urllib, people use it and gain experience with it, and learn that it would benefit from enhancements that would break existing code that uses it. So a new module gets implemented that has the enhancements but is incompatible with the old module. That way, new code can use the new module but old code can keep using the old module. From Mike at DeleteThis.Geary.com Thu Apr 15 14:06:22 2004 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Thu, 15 Apr 2004 11:06:22 -0700 Subject: CamelCase versus wide_names (Prothon) References: Message-ID: <107tjp2qvgof4b0@corp.supernews.com> Kevin Altis wrote: > If you're using PEP 8 terminology then CamelCase is different > than mixedCase. CamelCase is often used for class names and > mixedCase for everything else. Just to add to the confusing terminology, in some circles mixed case with an initial lowercase letter is called camelCase, while mixed case with initial uppercase is called PascalCase. :-) http://c2.com/cgi/wiki?CamelCase http://c2.com/cgi/wiki?PascalCase In any case ;-) Mark is referring to both forms, WithInitialCapital and withoutInitialCapital. The initial capital letter actually has significance in Prothon (I think--unless that has changed). So the question is whether to use NamesLikeThis and namesLikeThis, or Names_like_this and names_like_this. -Mike (instigator of the discussion and major fan of [Mm]ixedCaseNames, whatever they are called) From boblancaster at zxmail.com Tue Apr 27 10:47:48 2004 From: boblancaster at zxmail.com (Bob Lancaster) Date: 27 Apr 2004 07:47:48 -0700 Subject: Regular Expressions References: Message-ID: "Robert Brewer" wrote in message news:... > sjf wrote: > > I would like to please to help me with build a regular expression. > > There are following piece of html code in my files: > > > > A - TYPE1: any text
> > B - TYPE2: any text 2
> > C - TYPE2: any text 3
> > w - any text 15
> >
> > html code > > > > > > I need to have only following data: > > (B, any text 2) > > (C, any text 3) > > that is, these data TYPE2 in which. > > If you can guarantee that every TYPE2 is on its own line with the same > formatting: > > >>> s = 'A - TYPE1: any text
\nB - TYPE2: > any text 2
\nC - TYPE2: any text 3
\nw - > any text 15
\n
\nhtml code' > >>> import re > >>> re.findall(r'(?m)^(.) - TYPE2: (.*)
$', s) > [('B', 'any text 2'), ('C', 'any text 3')] > > > Robert Brewer > MIS > Amor Ministries > fumanchu at amor.org Thank you for this post. I am working on a completely different project, and this information was quite helpful for me in dealing with formatted output. -Bob Lancaster rlancasterATbruker-axsDOTcom From max at alcyone.com Fri Apr 2 04:05:25 2004 From: max at alcyone.com (Erik Max Francis) Date: Fri, 02 Apr 2004 01:05:25 -0800 Subject: String concatenation References: <7xisgi24fm.fsf@ruckus.brouhaha.com> <406D27A7.6550A00B@alcyone.com> Message-ID: <406D2CD5.878EBD4E@alcyone.com> "Leif B. Kristensen" wrote: > And here's what the interpreter says: > > tmp=[x for x in res if x and x[0] != '-'] > ^ > SyntaxError: invalid syntax > > The marker has moved to the right, maybe because I removed the spaces > on > both sides of the = sign? At this point I don't know what's going on since there's a communication problem; Python's exception specification is based on the code you entered, not the code it thought you meant, so you're having a cutting-and-pasting problem at least on one side here. If indentation is not to blame, it's possible that the problem is that you're not running a version of Python that understands list comprehensions. -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis \__/ They love too much that die for love. -- (an English proverb) From maxm at mxm.dk Fri Apr 2 07:09:54 2004 From: maxm at mxm.dk (Max M) Date: Fri, 02 Apr 2004 14:09:54 +0200 Subject: Stackless Website down, Project gone, I'm dead. In-Reply-To: References: Message-ID: <406d5800$0$206$edfadb0f@dread12.news.tele.dk> Christian Tismer wrote: > p.s.: I've taken the capsule, short time ago. > p.p.s.: This message was sent to you on April 2, to make > sure that it is not misinterpreted as a bad April 1 joke. > The bad joke was about that bad intruder. See you soon, > in heaven or somehwere else :-) If this is a joke, it is in poor taste. Max M From chrish at cryptocard.com Wed Apr 14 08:31:45 2004 From: chrish at cryptocard.com (Chris Herborth) Date: Wed, 14 Apr 2004 08:31:45 -0400 Subject: Simple pyhon-based CMS In-Reply-To: <9396ba6f.0404131817.1219c695@posting.google.com> References: <9396ba6f.0404131817.1219c695@posting.google.com> Message-ID: Stewart Midwinter wrote: > I'm looking for a simple python-based CMS (content management system), > maybe with some blog-like features, ability to add articles - nothing > too fancy. Do you have any suggestions? A friend of mine is working on one called MangoBery (http://sourceforge.net/projects/mangobery/), which is in use at several sites... not sure if it meets your needs, but take a look. > Stewart in Calgary MangoBery's developer is in BC, so if you need to chat with him the time zones won't screw you up. ;-) -- Chris Herborth chrish at cryptocard.com Documentation Overlord, CRYPTOCard Corp. http://www.cryptocard.com/ Never send a monster to do the work of an evil scientist. Postatem obscuri lateris nescitis. From peter at engcorp.com Tue Apr 27 10:03:16 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 27 Apr 2004 10:03:16 -0400 Subject: Is Perl *that* good? In-Reply-To: References: <108q51j4dscn7dc@corp.supernews.com> <87fzaqmm8t.fsf@strauser.com> <38ec68a6.0404262308.50029919@posting.google.com> Message-ID: Roy Smith wrote: > I don't see anything in the reference manual which says re.match() > caches compilations, but I suspect it does. Even a trivial check for > "thisRegEx is lastRegEx" would be sufficient to negate the speed > advantage of pre-compiling in most cases. Anybody know if it does this? Found after trying a half dozen different searches. (Short answer: yes.) http://groups.google.com/groups?q=comp.lang.python+cache+regular+match&selm=mailman.1058996747.17558.python-list%40python.org -Peter From nicksjacobson at yahoo.com Thu Apr 29 15:09:03 2004 From: nicksjacobson at yahoo.com (Nick Jacobson) Date: 29 Apr 2004 12:09:03 -0700 Subject: static keyword References: Message-ID: > > Why do you call using OO ("wrapping it in a class", as you say) > a "hack"? Generally speaking, using objects to contain state > information such as this is exactly what most people would call > the cleanest, best approach. > > class HasState: > def __init__(self): > self.firstCall = True > self.i = [10, 11] > > def foo(self): > if self.firstCall: > print "First pass" > self.firstCall = False > self.i[0] += 1 > print self.i[0] > > obj = HasState() > obj.foo() > obj.foo() > > Now, without arguing that it has 11 lines instead of 8 to do the > same thing (because then I'd just point out that this was a contrived > example anyway, and that it is more easily extended, and more obvious > what was going on, etc. :-) ), can you describe why you call this is > a "hack"? > > -Peter I don't know if "hack" is the right word. What I meant is it seems like overkill to have to make (and name) a class, plus add a second function, every time you want a function to have a static variable. From moosebumps at moosebumps.com Sat Apr 3 16:01:07 2004 From: moosebumps at moosebumps.com (Moosebumps) Date: Sat, 03 Apr 2004 21:01:07 GMT Subject: HTML writer References: <406D3C97.7020006@livinglogic.de> Message-ID: Thanks to all for the feedback -- that was very useful! I think I will go with XIST. MB "Tuure Laurinolli" wrote in message news:c4mh8n$bmv$1 at plaza.suomi.net... > Moosebumps wrote: > > > That is, I would not like any specific HTML tags anywhere in my own code, > > and it seems like that is what they will allow me to do. But I would be > > interested to hear opinions/experiences with these packages. > > I spent a couple of days last week getting to know each of these. I > found HTMLgen as I was getting desperate with the tag soup in my code > and quickly converted the code to use it. Then I found out it only does > HTML 3.2, missing end tags of elements and such. Some parts of the model > also weren't as generic as they should have been. > > Next I stumbled upon HyperText, which seemed to fix all the > incosistencies of HTMLgen, and also output XHTML 1.0. THe problem was > that I found no way to use web forms with it. The 'name'-attribute of an > input tag seemed to be impossible to set(ie. foo.name didn't do the > right thing, foo['name'] was illegal and there weren't any obvious false > names like klass <-> class). Fixing this would have been easy, but I > decided to look for alternatives. > > The final option seemed to be XIST, of which HTML seems to be only small > part. It seems to implement HTML in a consistent fashion, allowing all > the necessary tag attributes to be set and otherwise providing a nice > interface to the horrible world of web :) > > -- Tuure Laurinolli From fnord at u.washington.edu Fri Apr 16 17:46:00 2004 From: fnord at u.washington.edu (Lonnie Princehouse) Date: 16 Apr 2004 14:46:00 -0700 Subject: empty window when using askopenfile References: Message-ID: s_gherman at yahoo.com (Sorin Gherman) wrote in message news:... > Is there any way to minimize/hide the annoying default, empty Tk > window that shows behind the native file opening dialog , when using > askopenfile, etc, in tkCommonDialog? Ah, the pesky Tk root window. You can minimize it, but I don't think you can make it disappear completely (without nuking the rest of Tk). Try this- import Tkinter, tkFileDialog tkroot = Tkinter.Tk() tkroot.iconify() tkFileDialog.askopenfile() # If you're not doing anything with Tk besides prompting for the file, # you'll want to get ride of the root window after askopenfile- tkroot.destroy() Alternately, you could just put a pretty picture in the root window and call it a feature =) From jepler at unpythonic.net Tue Apr 20 14:55:38 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Tue, 20 Apr 2004 13:55:38 -0500 Subject: co_freevars question In-Reply-To: References: Message-ID: <20040420185537.GG2937@unpythonic.net> co_freevars names variables that come from an enclosing scope that is not module scope. def g(): return y print g.func_code.co_freevars # () def f(): y = 3 def g(): return y print g.func_code.co_freevars # ('y',) f() Jeff From temp1-nospam at nospam-hatless-nospam.com Wed Apr 28 01:48:35 2004 From: temp1-nospam at nospam-hatless-nospam.com (S Koppelman) Date: Wed, 28 Apr 2004 05:48:35 GMT Subject: Is Perl *that* good? In-Reply-To: References: <108q51j4dscn7dc@corp.supernews.com> Message-ID: Leif B. Kristensen wrote: > Cameron Laird rose and spake: >>In article , >>Leif B. Kristensen wrote: >> >>>getting dynamic HTML pages up and running quickly. Perl is great for >>>its string-handling abilities. (On my Web pages, I actually call a >>>Perl script from PHP precisely for this reason.) >>. >>I hear this more often than I understand it. Perl certainly >>does support many string-oriented operations. What's a speci- >>fic example, though, of an action you feel more comfortable >>coding in external Perl? I suspect there's something I need >>to learn about PHP's deficiencies, or Perl's power. > > I'm glad that you asked :-) > > The routine is for a phonetic search in Norwegian 18th century names, > which can be spelled in an amazing number of different ways. As I found > that the Soundex algorithm was useless for Norwegian spellings, I > invented my own. It's not really an algorithm, but a series of > substitutions that reduces names to a kind of primitives. Thus, eg..... > > Here's a small sample: > > $str =~ s/HN/N/g; # John --> JON > $str =~ s/TH/T/g; # Thor --> TOR .... > > [snip] > > In theory, the web routine for phonetic searches might have been > implemented in PHP. The trouble with that is that I would have to > maintain both a PHP and a Perl version of the same routine. I find it > much easier to just copy and paste the whole mess (at present about 120 > lines) between the encoding and the decoding routines in Perl, and run > an exec("perl norphon.pl $name") from PHP. Well, that's not PHP's fault, especially with such straightforward regexps. The only reason to user perl over PHP in that case is the valid one you cite: you already wrote the damned code in perl. ;) Meanwhile, wouldn't it run more efficiently if you hosted your perl functions under mod_perl or some other persistent harness like a SOAP or XML-RPC daemon and had the PHP call accross to that? Execing out and having perl launch, compile and run your script each time is a waste of resources, not to mention needlessly slow. You might not notice it if you're the only person using it, but if there's a sudden uptick in traffic to your site from fellow Scandinavian diaspora genaologists, you will. -sk From chris.cavalaria at free.fr Fri Apr 30 09:50:50 2004 From: chris.cavalaria at free.fr (Christophe Cavalaria) Date: Fri, 30 Apr 2004 15:50:50 +0200 Subject: operator double() surprise in cxx In-Reply-To: References: Message-ID: <409259b9$0$20177$636a15ce@news.free.fr> John Hunter wrote: >>>>>>"Beno?t" == Beno?t Dejean writes: > > >> double l( Py::Float(rect[0]) ); double b( Py::Float(rect[1]) ); > > Beno?t> everything that looks/tastes/sounds like a function > Beno?t> declaration is (even with parameters. > > double l( Py::Float(rect[0]) ); > > the compiler thinks I am declaring a function l that takes Py::Float* > as an argument and returns a double? Exactly > Hmm. This line was inside a > class method -- I didn't think you could declare functions in a class > method.... Well, you can declare a function nearly everywhere in fact. > Still confused, but perhaps on the road to enlightenment. Try that : double l(( Py::Float(rect[0]) )); From python at holdenweb.com Tue Apr 13 10:06:02 2004 From: python at holdenweb.com (Steve Holden) Date: Tue, 13 Apr 2004 10:06:02 -0400 Subject: mcmillan installer In-Reply-To: References: Message-ID: Gianluca Trombetta wrote: > Hi all, > > I'm searching a tool that compile python script to an executable binary. > I found the mcmillan installer but i can't find a valid url to download it. > > Do someone know a valid url to download it or know another similar tool? > > Thanks. > Gianluca > > > > Unfortunately Gordon Macmillan seems to have disappeared without trace, which is a great pity. The macmillan-inc domain registration appears to have expired without renewal: Whois Server Version 1.3 Domain names in the .com and .net domains can now be registered with many different competing registrars. Go to http://www.internic.net for detailed information. No match for "MACMILLAN-INC.COM". >>> Last update of whois database: Tue, 13 Apr 2004 07:17:14 EDT <<< If anybody has news of Gordon I'm sure many people would like to know he's OK. His work on the installer was much admired, and we should try to make sure it isn't lost. regards Steve From rstephens at vectron.com Sat Apr 10 17:50:11 2004 From: rstephens at vectron.com (Ron Stephens) Date: 10 Apr 2004 14:50:11 -0700 Subject: Python is the best and most popular general purpose scripting language; the universal scripting language Message-ID: Python is the best and most popular general purpose scripting language. That is, Python is the best and most popular general purpose, dynamic, interpreted language. Sure, there are other scripting languages that are more popular for specific application domains, and there are big company backed systems languages that are far more popular; but in its niche, Python is tops. Being open source, and not backed by big companies' marketing dollars, Python is not even in the same league as Java, and the .NET languages C# and VB.Net. Those corporate backed entities have incredibly powerful tools, IDE's and marketing dollars behind them. And, among scripting languages PHP is tops for server side web scripting, Perl is number one for text parsing and CGI, Ruby is perhaps most popular with object oriented purists who don't mind the Perl-like syntax, and Javascript is most popular for client side web scripting, given its nearly universal support by web browsers. But for general purpose scripting, Python is clearly number one and gaining in strength. That positions Python as the universal scripting language. Not only does the Python virtual machine run on almost every platform, but Jython is available for the JVM and IronPython is in the works for .Net and Mono. Let's face it, we could sit around and bemoan the fact that the big commercial "systems" languages have such incredible tool support and marketing muscle, such as the .Net juggernaut and the IBM, SUN, BEA and other IDE's for Java. But, better to take heart that for the pure writing of code, Python has the opportunity to become the universal solvent. It just may be that, twenty years from now, Python code will run everywhere, and will be the scripting language of choice on all the big company IDE's as well. There may by then be a lot of application areas where subject specialists create their own database front end's and customize real applications, by using big company tools that require no code to be written at all. But, computers will always need actual code, and Python can be the lingua franca. And on top of all that, while .NET, Eclipse, JBuilder etc. may outclass any one Python tool, we do have a plethora of good choices for almost any job requirement, including good access to about every important GUI toolkit imaginable, and we even have easy point and click GUI builders like PythonCard and the on-coming industrial strength Boa Constructor. So, Python is well on its way to world domination, just not in the same manner as Java or C#. Python is more like an underground movement that sneaks in around the edges and winds up playing a most significant role for the long run. Long live Python, the universal solvent! Ron Stephens www.awaretek.com/weblog/index.html From paul at prescod.net Mon Apr 12 00:13:03 2004 From: paul at prescod.net (Paul Prescod) Date: Sun, 11 Apr 2004 21:13:03 -0700 Subject: pythonwin crash (used to work) - please help quick. In-Reply-To: <5Reec.62668$Id.61067@news-binary.blueyonder.co.uk> References: <5Reec.62668$Id.61067@news-binary.blueyonder.co.uk> Message-ID: <407A174F.3000901@prescod.net> Stevie_mac wrote: > OS=XP, Python 2.3, wx2.5.1.5u > Not sure what's to blame here - or to be more precise, how to fix it!... > > If I do this in PythonWin... > import wx > d = wx.Dialog(None, -1, 'title') > BANG - IDE crashes It typically doesn't work to have two GUIs in one process. PythonWin uses MFC. Wx is a totally different GUI. Paul Prescod From donn at u.washington.edu Thu Apr 29 12:56:09 2004 From: donn at u.washington.edu (Donn Cave) Date: Thu, 29 Apr 2004 09:56:09 -0700 Subject: Why we will use obj$func() often References: <84Uhc.22278$dZ1.5087@fed1read04> <8AWhc.23114$dZ1.11070@fed1read04> <40883BFE.B381518A@alcyone.com> <27_hc.23801$dZ1.2716@fed1read04> <40887145.789A2FE8@alcyone.com> <7cki80hj976bia36lhf9er97v073o1pqvm@4ax.com> <5vJjc.13116$Qy.1954@fed1read04> <52Ujc.16275$Qy.3111@fed1read04> Message-ID: In article , "Mark Hahn" wrote: ... > Can you share some of your daydream ideas? Not really my ideas, it's pretty much all there in Haskell and Clean (though I have no experience with the latter.) Pure functional, strong static typing with type inference, compile to native. It isn't clear that it's ideal - there may be some inherent limitations to exception handling, the execution model is often awkward (cf. Monad) at least for the beginner programmer. So there's probably room for yet another variation on the theme, but I'd be using Haskell now if I could (weakness of platform support, institutional acceptance.) Haskell is good for you, though, even if you can't put it to use in practice. It's a thoroughly different approach that's at least good for perspective. And it's white space structured. Donn Cave, donn at u.washington.edu From news at ogre.nu Sat Apr 17 02:45:25 2004 From: news at ogre.nu (Anton Sherwood) Date: Fri, 16 Apr 2004 23:45:25 -0700 Subject: text storage: shelve vs anydbm vs ? Message-ID: <1081kgpq4qrsa79@corp.supernews.com> Rather newbie question here. My current project will build a database of solutions to a topology problem, which I'll eventually put (readonly) on my website. The entries are text of varying length. The keys are likewise of varying length. Is anydbm the way to go? Is shelve anything more than a wrapper for it? Should I be looking at something else? -- Anton Sherwood (prepend "1" to address) http://www.ogre.nu/ From michael at foord.net Sat Apr 10 05:57:30 2004 From: michael at foord.net (Fuzzyman) Date: 10 Apr 2004 02:57:30 -0700 Subject: Why Activestate Python ? References: <8089854e.0404090025.141f090c@posting.google.com> Message-ID: <8089854e.0404100157.2d253dac@posting.google.com> [snip..] > > Fuzzy > > > > http://www.voidspace.org.uk/atlantibots/pythonutils.html > > i think there is an impression generally that Win32 is a harder build > platform for OSS projects than Linux-Unix. Very unscientifically, I > think my reading of message boards supports that, at least for Apache, > Python, and their related modules. > > I've never tried to build it myself. > > The activestate distribution includes Help files in compiled html > format. Which I do not prefer. I just download the doc of interest > from the python site. The 'official' version also has docs in 'chm' format... which I personally find fine (particularly not having internet at home). Regards, Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html From pengz1 at netzero.com Fri Apr 9 00:37:57 2004 From: pengz1 at netzero.com (pengz1 at netzero.com) Date: Fri, 9 Apr 2004 04:37:57 GMT Subject: connection with MySQL with Python interface Message-ID: <20040408.213759.17969.265020@webmail21.nyc.untd.com> Hi! All When I tried to connect with MySQL database which run on XP from shell. I got following error message. Has anyone get similar error message and provide any suggestion? Thanks in advance. Zhiyong Traceback (most recent call last): File "C:\Python22\databaseAccess.py", line 4, in ? con=MySQLdb.connect(host="127.0.0.1",port=3306,user="pengz",passwd="zhiy4318",db="e_retail_store") File "C:\PYTHON22\Lib\site-packages\MySQLdb\__init__.py", line 63, in Connect return apply(Connection, args, kwargs) File "C:\PYTHON22\Lib\site-packages\MySQLdb\connections.py", line 115, in __init__ self._make_connection(args, kwargs2) File "C:\PYTHON22\Lib\site-packages\MySQLdb\connections.py", line 41, in _make_connection apply(super(ConnectionBase, self).__init__, args, kwargs) OperationalError: (2003, "Can't connect to MySQL server on '127.0.0.1' (10061)") Traceback (most recent call last): File "C:\Python22\databaseAccess.py", line 4, in ? con=MySQLdb.connect(host="127.0.0.1",port=3306,user="pengz",passwd="zhiy4318",db="e_retail_store") File "C:\PYTHON22\Lib\site-packages\MySQLdb\__init__.py", line 63, in Connect return apply(Connection, args, kwargs) File "C:\PYTHON22\Lib\site-packages\MySQLdb\connections.py", line 115, in __init__ self._make_connection(args, kwargs2) File "C:\PYTHON22\Lib\site-packages\MySQLdb\connections.py", line 41, in _make_connection apply(super(ConnectionBase, self).__init__, args, kwargs) OperationalError: (1250, 'Client does not support authentication protocol requested by server; consider upgrading MySQL client') ________________________________________________________________ The best thing to hit the Internet in years - NetZero HiSpeed! Surf the Web up to FIVE TIMES FASTER! Only $14.95/ month -visit www.netzero.com to sign up today! From peter.maas at mplusr.de Mon Apr 26 04:25:47 2004 From: peter.maas at mplusr.de (Peter Maas) Date: Mon, 26 Apr 2004 10:25:47 +0200 Subject: How's ruby compare to it older brother python In-Reply-To: References: Message-ID: Hunn E. Balsiche wrote: > I've given up on Perl for its ugly syntax and it is not the easiest language > to learn. How about PHP? I forgot http://dada.perl.it/shootout, which is great for performance comparisons. Source code of the tests can be viewed easily to get a feeling for the strengths and weaknesses of the syntax as well. Mit freundlichen Gruessen, Peter Maas -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Hubert-Wienen-Str. 24 Tel +49-241-93878-0 Fax +49-241-93878-20 eMail peter.maas at mplusr.de ------------------------------------------------------------------- From theller at python.net Mon Apr 26 03:54:46 2004 From: theller at python.net (Thomas Heller) Date: Mon, 26 Apr 2004 09:54:46 +0200 Subject: help: py2exe and com server References: <408a78f5$0$41761$5fc3050@dreader2.news.tiscali.nl> Message-ID: "Paul Mayal" writes: > Hi, > > I have written a com server in python 2.3 (ActiveState distribution). I have > build the dll with py2exe. > First of all, py2exe complain he can't find pythoncom module. > I can register the dll with regsvr32 on my development workstation. But when > I try to register the com dll on an another workstation, the registration > fail. I think you have to use a newer build of pywin32 (formerly called win32all) than that included with ActiveState python. Thomas From cookedm+news at physics.mcmaster.ca Fri Apr 2 14:42:24 2004 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Fri, 02 Apr 2004 14:42:24 -0500 Subject: Travelling salesman variation in python References: Message-ID: At some point, Nick Craig-Wood wrote: > Peter Maas wrote: >> Nick Craig-Wood wrote: >> > I used Simulated Annealing - have a search for the term and you'll see >> > plenty of references. Its good at finding a (local) minimum. >> >> I used to think that Simulated Annealing avoids local traps and >> is good at finding a global minimum, at least with a certain >> probability that depends on some temperature function. Am I wrong? > > You aren't wrong... It does avoid local traps - that is what the > simulated annealing bit is for - but it isn't guaranteed to find the > global minimum otherwise you'd have solved an NP-complete problem in > polynomial time... With the right cooling schedule simulated annealing *is* guaranteed to find the global minimum. Mind you, that cooling schedule is very slow: the temperature of the n'th step is T_n = T0/log(n). To get to 1% of your initial temperature, you'll need about 1e10 steps... polynomial time it ain't. Most SA cooling schedules you'll see use a quench (T_n = T0*a**n for some a) or a Cauchy distribution (T_n = T0/n) which are faster, but aren't guaranteed to give you a global minimum. -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From pellis.nospam at tampabay.rr.com Fri Apr 9 23:50:58 2004 From: pellis.nospam at tampabay.rr.com (Patrick Ellis) Date: Sat, 10 Apr 2004 03:50:58 GMT Subject: Simple Class Question - need clarity please References: <2tce701vv505395hcr6dqtvc8ot0fdmkrk@4ax.com> Message-ID: Stevie_mac wrote: > > > > I cut and pasted from your post into mywindow.py and test.py. When I ran test.py I got a window with a cancel button, that went away when I clicked the button. There were no error messages. From max at alcyone.com Sat Apr 17 00:12:07 2004 From: max at alcyone.com (Erik Max Francis) Date: Fri, 16 Apr 2004 21:12:07 -0700 Subject: Difficulty Finding Python Developers References: <65cbc3dd.0404140641.3501fde8@posting.google.com> <407D6269.3090909@engcorp.com> <40808FF1.7060204@cs.com> Message-ID: <4080AE97.C4CF0755@alcyone.com> "Robert M. Emmons" wrote: > I agree with Peter. I learned python in an afternoon. I'm not saying > I > was highly productive after 4 hours, but I could program and start > working immediately. Any good programmer should be able to do this. Note that doesn't mean it's a bad idea to hire a Python expert in order to lead a team or make sure that everyone's learning Python properly. -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis \__/ Have you ever loved somebody / Who didn't know -- Zhane From tjreedy at udel.edu Sat Apr 17 04:13:35 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 17 Apr 2004 04:13:35 -0400 Subject: AOP use cases References: <84fc4588.0404140106.3fa0c55@posting.google.com> <0pydnSB4WYuieuLdRVn-hQ@powergate.ca> <4080C6F3.5020309@zope.com> Message-ID: "Shane Hathaway" wrote in message news:4080C6F3.5020309 at zope.com... > This discussion makes me wonder if Zope has been dabbling in AOP > concepts for years without knowing it. I believe at least one person has posted about AOP in Zope. Quite aware of what doing ;-) tjr From viking_kiwi at yahoo.poofters.com Sat Apr 3 17:57:02 2004 From: viking_kiwi at yahoo.poofters.com (Rod Stephenson) Date: Sat, 03 Apr 2004 22:57:02 GMT Subject: Embedding python with mingw compilers Message-ID: I'm successfully created python extensions on windows using the mingw compiler (with swig), now I'm trying to embed python in a c-program. The simple example (included below) is from the manual. I compile it with gcc 3.2.3: gcc -o pytest -Ic:/python23/include -Lc:/python23/libs -lpython23 pytest.c I then get error messages for the python calls, eg C:\WINDOWS\TEMP/ccU2vhgb.o(.text+0x5b):pytest.c: undefined reference to `_imp__Py_Initialize' I notice however that the .def file I used to create libpython23.a does have references to _imp__Py_Initialize (as well as Py_Initialize) and these also seem to be in the generated library file. Any suggestions as to what else needs to be done to sort this out? ******************** #include int main(int argc, char *argv[]) { Py_Initialize(); PyRun_SimpleString("from time import time,ctime\n" "print 'Today is',ctime(time())\n"); Py_Finalize(); return 0; } -- Rule 1. From ptmcg at austin.rr._bogus_.com Wed Apr 14 07:06:49 2004 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Wed, 14 Apr 2004 11:06:49 GMT Subject: spherical coordinates References: <20040414111334.34b5d225@pistache.sara.nl> <7x1xmqua94.fsf@ruckus.brouhaha.com> Message-ID: "Paul Rubin" wrote in message news:7x1xmqua94.fsf at ruckus.brouhaha.com... > Peter Maas writes: > > r = sqrt(x**2 + y**2) > > phi = atan(y/x) > > Better use phi=atan2(y,x) in case x=0. Similarly for the other atan calls. These are formulas for cylindrical coordinates. The OP was asking for spherical coordinates rho, theta, and phi, where: rho = distance from origin (similar to r in cylindrical coords) theta = angle from the positive x axis of the xyz vector projection onto the x-y plane (just like theta in cylindrical coords) phi = angle of the xyz vector from the x-y plane To convert from spherical to Cartesian: x = rho * sin(phi) * cos(theta) y = rho * sin(phi) * sin(theta) z = rho * cos(phi) >From Cartesian to spherical: rho = sqrt(x**2 + y**2 + z**2) theta = atan2(y, x) if rho != 0.0: phi = acos( z / rho ) else: phi = pi / 2 * sgn(z) I can imagine that all these conversions could be a performance killer if done entirely in Python, and could stand to be done as a C extension. This is probably why the OP was asking if such a package already exists. -- Paul (Hmm, the math module doesn't have a sgn() function. Is this difficult to add?) From davidf at sjsoft.com Thu Apr 22 01:44:11 2004 From: davidf at sjsoft.com (David Fraser) Date: Thu, 22 Apr 2004 07:44:11 +0200 Subject: [wxPython] how to automatically resize a window? In-Reply-To: <408659aa$1@maser.urz.unibas.ch> References: <408659aa$1@maser.urz.unibas.ch> Message-ID: Curzio Basso wrote: > > Hi all, > > I have a problem for which I wasn't able to find an answer anywhere > else, maybe someone can give me a hint... > > I designed with XRCed a small GUI (the code is at the bottom of the > message) made up of a menu and a frame in which there are two panels, > placed by an horizontal sizer. > > Now, what I would like to do is to be able to load an image and display > it on the left panel, automatically resizing the panel depending on the > image size (the code is at the end again). There are actually two problems: > > 1) if I load an image the panel is not resized automatically > > 2) if I resize the panel manually after having loaded the image, the DC > is not repainted. that is, the portion of the image which was invisible > is not painted > > Is there anyone with a bit of time to explain me how to solve these > problems? > > thanks, qrz You probably want to go to the wxPython users mailing list for this (see the links on the wxpython home page) David From Mike at DeleteThis.Geary.com Mon Apr 19 16:44:36 2004 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Mon, 19 Apr 2004 13:44:36 -0700 Subject: outline-style sorting algorithm References: <71650A6F73F1D411BE8000805F65E3CB3B3A4D@SRV-03> Message-ID: <1088ehljpqq4195@corp.supernews.com> Terry Reedy wrote: > It it a well known problem that left-justified variable-length > number representations in strings do not sort well when the > strings are sorted in the standard manner. Even without dots, > directory listings will give you > > file1 > file10 > ... > file19 > file2 > file20 > ... > file29 > file3 > etc. Interestingly enough, in Windows XP, Windows Explorer lists these files in numerical order: file1 file2 ... file9 file10 file11 ... file19 file20 file21 ... file29 The DIR command CMD.EXE still sorts alphabetically, but DIR in the 4NT command shell from www.jpsoft.com displays the files in numerical order, with a command line option to use alphabetical order instead. It would be nice if more OS shells sorted filenames like this. -Mike From faizan at jaredweb.com Sat Apr 24 00:43:04 2004 From: faizan at jaredweb.com (Fazer) Date: 23 Apr 2004 21:43:04 -0700 Subject: Opening MS Word files via Python References: <7b454334.0404201628.371b9e8@posting.google.com> <3d06fae9.0404210536.3f277a37@posting.google.com> Message-ID: <7b454334.0404232043.32e95cf1@posting.google.com> jmdeschamps at cvm.qc.ca (jmdeschamps) wrote in message news:<3d06fae9.0404210536.3f277a37 at posting.google.com>... > Rob Nikander wrote in message news:... > > Fazer wrote: > > > I am curious as to how I should approach this issue. I would just > > > want to parse simple text and maybe perhaps tables in the future. > > > Would I have to save the word file and open it in a text editor? That > > > would kind of....suck... Has anyone else tackled this issue? > > > > The win32 extensions for python allow you to get at the COM objects for > > applications like Word, and that would let you get the text and tables. > > google: win32 python. > > > > word = win32com.client.Dispatch('Word.Application') > > word.Documents.Open('C:\\myfile.doc') > > > > But I don't know the best way to find out the methods and properties of > > the "word" object. > > > > Rob > > You can use VBA documentation for Word, and using dot notation and > normal Pythonesque way of calling functions, play with its diverses > objects, methods and attributes... > Here's some pretty straightforward code along these lines: > #************************ > import win32com.client > import tkFileDialog > > # Launch Word > MSWord = win32com.client.Dispatch("Word.Application") > MSWord.Visible = 0 > # Open a specific file > myWordDoc = tkFileDialog.askopenfilename() > MSWord.Documents.Open(myWordDoc) > #Get the textual content > docText = MSWord.Documents[0].Content > # Get a list of tables > listTables= MSWord.Documents[0].Tables > #************************ > > Happy parsing, > > Jean-Marc That is Awesome! Thanks! How would I save something in word format? I am guessing MSWord.Docments.Save(myWordDoc) or around those lines? where can I find more documentatin? Thanks. From jepler at unpythonic.net Sun Apr 18 16:35:47 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Sun, 18 Apr 2004 15:35:47 -0500 Subject: using a USB HID device In-Reply-To: <4082e29d.1177387563@news.xs4all.nl> References: <40827ce3.1151345337@news.xs4all.nl> <4082e29d.1177387563@news.xs4all.nl> Message-ID: <20040418203547.GB3074@unpythonic.net> libusb is portable to Linux, BSD including OS X, and Windows. I don't know of a Python wrapper, however, and my experience using libusb on windows is limited. http://libusb.sf.net http://libusb-win32.sf.net/ For my own application, I wrote my device's API in C and wrapped it using Pyrex. Jeff From SeeBelow at SeeBelow.Nut Fri Apr 16 14:21:49 2004 From: SeeBelow at SeeBelow.Nut (SeeBelow at SeeBelow.Nut) Date: Fri, 16 Apr 2004 18:21:49 GMT Subject: Python OS References: <107j4eu6ffn2c68@corp.supernews.com> <7xy8p29wc4.fsf@ruckus.brouhaha.com> Message-ID: <4080245D.A29E494E@shaw.ca> Paul Rubin wrote: > > The idea is not completely insane, but you'd have to do a LOT of work, > possibly including reimplementing the language. You might look at > some of the Lisp Machine publications for inspiration and an idea of > what you'd be getting yourself into. "not completely insane", but damn close to it! (IMO, of course, but it's an educated opinion.) Mitchell Timin -- "Many are stubborn in pursuit of the path they have chosen, few in pursuit of the goal." - Friedrich Nietzsche http://annevolve.sourceforge.net is what I'm into nowadays. Humans may write to me at this address: zenguy at shaw dot ca From joe at notcharles.ca Mon Apr 12 16:47:04 2004 From: joe at notcharles.ca (Joe Mason) Date: Mon, 12 Apr 2004 20:47:04 GMT Subject: String + number split References: <2SAec.70005$Id.6002@news-binary.blueyonder.co.uk> Message-ID: In article , Stevie_mac wrote: > PS, the number on the end may vary & the _ could be any non alpha char! > > font12 becomes ('font',12) > arial_14 becomes ('arial',14) > arial__8 becomes ('arial',8) > times 6 becomes ('times',6) >>> import re >>> def fsplit(fs): ... r = re.compile(""" ... ([A-Za-z]+) # group 1: 1 or more letters ... [^0-9]* # 0 or more non-digits; not a group because not in () ... ([0-9]+) # group 2: 1 or more numbers ... """, re.VERBOSE) ... m = r.match(fs) ... if m: return (m.group(1), m.group(2)) ... else: raise ValueError, "Badly formatted font string" ... >>> fsplit('font12') ('font', '12') >>> fsplit('arial_14') ('arial', '14') >>> fsplit('arial_8') ('arial', '8') >>> fsplit('times 6') ('times', '6') Joe From nikolai.kirsebom.NOJUNK at siemens.no Fri Apr 30 07:41:49 2004 From: nikolai.kirsebom.NOJUNK at siemens.no (Nikolai Kirsebom) Date: Fri, 30 Apr 2004 13:41:49 +0200 Subject: Automated installation framework References: Message-ID: On Fri, 30 Apr 2004 13:36:02 +0200, Thomas Heller wrote: > >Is it this that you have in mind? > >Martin von L?wis, packing Python with Microsoft Installer: >http://www.python.org/pycon/dc2004/papers/44/ > >Thomas > Not really. I'm looking for a system which can be used to install an application in an environment. As an example: Machine #1: Ensure Windows 2003 server SP3 installed. Install SQL Server 2003 Add SQL Server Package X Install Server part of application A Machine #2: Ensure Windows 2000 with SP 2a installed .... Install other part of application A Machine #3: Ensure Windows 2000 with SP 2a installed Install IBM WebSphere etc. In principle, there is no Python involved except the managing of the installation. There should be no requirement that Python must be installed on the target machines (if this is possible). I do not expect to have a system which will handle all the individual steps, but a system which assists in the process would probably be of great help. Nikolai From dwelch91 at comcast.net Mon Apr 5 09:55:22 2004 From: dwelch91 at comcast.net (djw) Date: Mon, 05 Apr 2004 13:55:22 GMT Subject: python processes names In-Reply-To: References: Message-ID: Sylwia wrote: > Hi! > > How to make python programs show up by name is ps (e.g ps -e). By > default if we have many different python processes running > simultaneously, then we can only see python python python for three > different python processes. I would much rather see > first_python_program_name.py, second_python_program_name.py and > third_python_program_name.py listed by ps. Is that possible without > downloading and installing any non-standard modules? > > Thank you in advance, > > Best wishes, > > Sylwia You could use proctitle: https://ftp.psychosis.com:4302/python/ -Don From mwh at python.net Tue Apr 20 08:42:44 2004 From: mwh at python.net (Michael Hudson) Date: Tue, 20 Apr 2004 12:42:44 GMT Subject: module not callable - why not? References: <107dras2heahcb6@news.supernews.com> <8ef9bea6.0404122025.36efc84e@posting.google.com> <7xsmf1fxd9.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin writes: > And yet, you can call a class instance if it has a __call__ > operation defined. I don't see why modules shouldn't be the same. Well, for a possible counter argument, consider that you can only call an instance of a new-style class if the CLASS defines the __call__ method... Cheers, mwh -- Premature optimization is the root of all evil. -- Donald E. Knuth, Structured Programming with goto Statements From theller at python.net Tue Apr 27 14:27:32 2004 From: theller at python.net (Thomas Heller) Date: Tue, 27 Apr 2004 20:27:32 +0200 Subject: Problem with PY2EXE and VPython References: Message-ID: Bruce, I could not reply to the private mail you sent me (some permanent error at the mail server), so here it goes: Bruce Peterson writes: > Thomas > Thanks -- here are the files in the distribution directory created > by PY2EXE for tower of Hanoi demo. > cvisual.dll > datetime.pyd > DDRAW.dll > dirlist.txt > GLU32.dll > hanoi.exe > library.zip > multiarray.pyd > OPENGL32.dll > python23.dll > umath.pyd > w9xpopen.exe > _numpy.pyd > _sre.pyd > Bruce, you should at least remove these files from the dist dir, and make sure in other ways that opengl and direct draw (is this directX, or how it's called?) is installed on the target system: > DDRAW.dll > GLU32.dll > OPENGL32.dll I'm not sure where cvisual.dll comes from. (10 seconds later, after googling around: ah, it's from VPython, so it must stay). The other files are Python extensions. Thomas From dippyd at yahoo.com.au Tue Apr 6 03:24:10 2004 From: dippyd at yahoo.com.au (Steve) Date: Tue, 06 Apr 2004 17:24:10 +1000 Subject: slightly OT: BUT NEEDs to be said References: <8b42d1998c978c8c1cddf15c52a1c57b@dizum.com> Message-ID: <40725B1A.4080706@yahoo.com.au> Greg Ewing wrote: > > Aha! I've been trying to decide what to name the next language > I invent, and now I know. It will be called: > > Buffy Nice choice! But I think "buffy" would surely have to be some sort of command-line buffer tool, or better still, anti-buffer overflow security software. Buffy could save the world from security holes. If you ask me, I think "xander" sounds more like a computer language, but "willow" would probably be more appropriate. And of course then when people write in to complain about how politically incorrect it is to name a programming language for a red-haired Jewish lesbian witch, we can deflect criticism by telling them it is named after the movie of the same name about the Little People. -- Steven D'Aprano From aahz at pythoncraft.com Sat Apr 17 19:50:19 2004 From: aahz at pythoncraft.com (Aahz) Date: 17 Apr 2004 19:50:19 -0400 Subject: Getters and setters in python, common practise References: <407e402c$1@newsflash.abo.fi> <407e6cf9@newsflash.abo.fi> Message-ID: In article , Peter Hansen wrote: >Yermat wrote: >> Petter Holmstr?m wrote: >>> >>> I have not found any documentation on this topic. Could you please >>> point me to some? >> >> see "property" at http://www.python.org/doc/2.3.3/lib/built-in-funcs.html >> >> You could also look at >> http://users.rcn.com/python/download/Descriptor.htm to understand how it >> does really work. > >Also helpful: http://www.python.org/2.2/descrintro.html#property Even more helpful: http://www.python.org/doc/newstyle.html (From "Documentation" | "New-style classes") -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I used to have a .sig but I found it impossible to please everyone..." --SFJ From fredrik at pythonware.com Wed Apr 21 14:27:49 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 21 Apr 2004 20:27:49 +0200 Subject: Dollar sign ($) on foriegn keyboards? (prothon) References: Message-ID: Tim Peters wrote: > Prothon is trying some design decisions that are very hard to try in > CPython now, and how they turn out is interesting to me. design by self-selecting newsgroup subsets has been tried before, also for CPython. it a great way to waste lots of time and get really lousy results (or no results at all, in CPython's case). From fredrik at pythonware.com Tue Apr 20 09:59:09 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 20 Apr 2004 15:59:09 +0200 Subject: outline-style sorting algorithm References: <71650A6F73F1D411BE8000805F65E3CB3B3A4D@SRV-03><1088ehljpqq4195@corp.supernews.com> <1089sl7ebr47k2e@corp.supernews.com> Message-ID: Michael Geary wrote: > It seems like a simple enough algorithm: Split each filename into groups of > numbers and non-numbers. When you do a sort comparison, take these character > groups from left to right, comparing the non-numeric parts alphabetically > and the numeric parts numerically. import re def split(name, findall=re.compile("(\d+)|(\D+)").findall): parts = [] for d, s in findall(name): if d: s = int(d) parts.append(s) return parts (preferrably combined with DSU, but if you don't have too many files, you can use sort(lambda a, b: cmp(split(a), split(b)))) From sng2004x at netscape.net Thu Apr 15 11:18:45 2004 From: sng2004x at netscape.net (Stephen Ng) Date: Thu, 15 Apr 2004 23:18:45 +0800 Subject: Python 2.3 on RedHat 9 Message-ID: <407EA7D5.1040704@netscape.net> Hi! Has anyone installed Python 2.3 on RedHat 9? Did you install on top of Python 2.2 or did you install in a separate directory (eg the default)? I'm trying to find out in advance if it's hassle free to install as I am planning to do it. Thanks. Stephen Ng From jcarlson at uci.edu Sun Apr 4 04:56:30 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Sun, 04 Apr 2004 00:56:30 -0800 Subject: OT (was Re: But it still doesn't explain the joke) In-Reply-To: References: <106o7vn56fgmt85@corp.supernews.com><406F3C29.6030504@freedom.place> Message-ID: > think it better that we, including you, maintain the political truce that > currently prevails on this newsgroup, which is a unique forum for > discussion Python, and leave such political discussions to more appropriate > fora. Sure, sounds good. For someone who is advocating political truce, you sure loaded your post. Practice what you preach my friend. - Josiah From ny_r_marquez at yahoo.com Fri Apr 16 14:54:20 2004 From: ny_r_marquez at yahoo.com (R.Marquez) Date: 16 Apr 2004 11:54:20 -0700 Subject: Convert from PDF to raster format image Message-ID: <8a27e309.0404161054.2a5c5ecc@posting.google.com> Does any one know of a way to convert PDF documents into a raster format, such as TIFF or JPEG? Of course to do it in Python would be my preference, but if you know of another way to do this programatically I would also be interested. Thanks. -Ruben From harry.g.george at boeing.com Tue Apr 20 12:16:15 2004 From: harry.g.george at boeing.com (Harry George) Date: Tue, 20 Apr 2004 16:16:15 GMT Subject: Tutorial References: Message-ID: "S?ren Kunst" writes: > hello, i need a good tutorial for Python, nothing for beginners > > wfw S?ren > > For non-beginners, I find "Python Essential Reference" by David Beaszley to be a good tutorial. In under 100 pages, you learn the control structures, data types, builtin functions, and many of the idioms. This is appropriate for people who are comfortable with several languages, and understand scripting from, e.g., perl experience. If you already know when and why you might use an exception handler or do a qualified import or need to redirect stdin, then this book could be for you. -- harry.g.george at boeing.com 6-6M21 BCA CompArch Design Engineering Phone: (425) 342-0007 From mwilson at the-wire.com Thu Apr 1 14:33:24 2004 From: mwilson at the-wire.com (Mel Wilson) Date: Thu, 01 Apr 2004 14:33:24 -0500 Subject: Why '==' ?? References: <8089854e.0403302319.1ab56af0@posting.google.com> <8089854e.0403312324.7de8710c@posting.google.com> Message-ID: In article <8089854e.0403312324.7de8710c at posting.google.com>, michael at foord.net (Fuzzyman) wrote: >Having said that I *Still* think that : > >if a = 3: >is unambiguous - so there's no real reason that the interpreter should >wag it's finger and say ... "you forgot to put in one of the '=' and I >refuse to continue until you do" :-) It causes trouble in the larger language.. if a == 0: some_thing() works, and c = a == 0 if c: some_thing() works the same but c = a = 0 if c: some_thing() has the opposite effect to your proposed if a = 0: # (not real python syntax) some_thing() Regards. Mel. From dmq at gain.com Wed Apr 28 10:15:32 2004 From: dmq at gain.com (David MacQuigg) Date: Wed, 28 Apr 2004 07:15:32 -0700 Subject: What is good about Prothon? References: Message-ID: Mike, Thanks for a very thorough and thoughtful review of this proposal. Please see my responses in the thread "Ideas for Python 3". -- Dave From leens_chacko at hotmail.com Fri Apr 16 10:42:04 2004 From: leens_chacko at hotmail.com (Leeny) Date: 16 Apr 2004 07:42:04 -0700 Subject: Python - matlab interface help!! Urgent References: Message-ID: leens_chacko at hotmail.com (Leeny) wrote in message news:... > Hi Group, > > Hope someone can help me with this problem. I am a new user to python > and am currently working with pymat module of python (for coursework). > > I tried to create plots thru pymat using pymat.eval(h, 'plot(x,y)') > This is working fine. However, i dont know how to print or save this > plot as a .tif image something like > > print(gcf, '-dtiff', 'test') > > using pymat. One suggestion I got was to use mathplotlib, but since i have done some work uisng pymat, I would like to know if there is some way it can be done using Pymat. > > Please help me!!!! > > Thanks > Leeny From martin at v.loewis.de Wed Apr 28 14:28:57 2004 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Wed, 28 Apr 2004 20:28:57 +0200 Subject: locale.CODESET / different in python shell and scripts In-Reply-To: References: Message-ID: <408FF7E9.90001@v.loewis.de> Michael Hudson wrote: >>It is uncertain why this happens - setlocale is not normally >>called automatically; not even in interactive mode. Perhaps >>you have created your own startup file? > > > readline calls setlocale() iirc. Sure. However, we restore the locale to what it was before readline initialization messes with the locale. Regards, Martin From stewart at midwinter.ca Fri Apr 16 09:20:01 2004 From: stewart at midwinter.ca (Stewart Midwinter) Date: 16 Apr 2004 06:20:01 -0700 Subject: Python GUI wrapper for a long operation References: Message-ID: <9396ba6f.0404160520.364699c4@posting.google.com> good stuff! I'll study your app for some clues for my own situation. I want to continually get data from a remote server, and then graph values that I have received, probably using Tkinter canvas widget. Understanding threads will be helpful for me, so I'll study how you used threads in your app. You may want to post your idea on the tkinter mailing list, thanks, Stewart in Calgary. From eldiener at earthlink.net Sat Apr 3 22:23:20 2004 From: eldiener at earthlink.net (Edward Diener) Date: Sun, 04 Apr 2004 03:23:20 GMT Subject: Typing \n in strings References: <406f79ca$1_1@themost.net> Message-ID: Paul Watson wrote: > "Edward Diener" wrote in message > news:RGKbc.11130$yN6.10939 at newsread2.news.atl.earthlink.net... >> Python 2.3.3 on Win2K. In the Python tutorial it says that typing \n >> in string literals is the new-line character. I open the interpreter >> and type a string with a \n in it but instead of outputting a string >> with a new line, it outputs the \n as literal characters of the >> string. Is the tutorial wrong, is the interpreter broken, or what is >> happening ? >> > > What exactly are you entering and what is output? > > Python 2.3.3 (#51, Dec 18 2003, 20:22:39) [MSC v.1200 32 bit (Intel)] > on win32 > Type "help", "copyright", "credits" or "license" for more information. >>>> "now\nis\nthe\ntime" > 'now\nis\nthe\ntime' >>>> print "now\nis\nthe\ntime" > now > is > the > time Right you are and my faux pas. I didn't notice the print statement in the tutorial. From michael at foord.net Wed Apr 14 11:25:26 2004 From: michael at foord.net (Fuzzyman) Date: 14 Apr 2004 08:25:26 -0700 Subject: 3D Graphics Engine References: <8089854e.0404130639.3eb0db62@posting.google.com> <7eecf173.0404140017.6d7b06a4@posting.google.com> Message-ID: <8089854e.0404140725.2434222d@posting.google.com> google at evpopov.com (popov) wrote in message news:<7eecf173.0404140017.6d7b06a4 at posting.google.com>... > > Can anyone reccomend a 3d engine for me to 'muck around with'. > > You can have a look to Ogre: www.ogre3d.org. > Python bindings may not be up to date, but they should be at the first > official release (which should now happen in a not so far future). On a brief inspection (bad, busy day) I couldn't see *either* python binaries *or* prebuilt binaries at the site you pointed to. On the other hand it looks interesting and so bears further investigation. Regards, Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html From jack at performancedrivers.com Fri Apr 23 14:34:51 2004 From: jack at performancedrivers.com (Jack Diederich) Date: Fri, 23 Apr 2004 14:34:51 -0400 Subject: Why we will use obj$func() often In-Reply-To: References: <84Uhc.22278$dZ1.5087@fed1read04> <8AWhc.23114$dZ1.11070@fed1read04> <40883BFE.B381518A@alcyone.com> <27_hc.23801$dZ1.2716@fed1read04> <40887145.789A2FE8@alcyone.com> Message-ID: <20040423183451.GC25755@performancedrivers.com> On Fri, Apr 23, 2004 at 10:55:55AM -0700, Mark Hahn wrote: > I think everyone here is operating under fear, uncertainty, and doubt. Most > of the reports on the Prothon mailing list of people who have actually > picked up Prothon and played with it have been happy. People look at the > surface and are prejudiced, just like looking at people with different skin > color. Oh please, don't conflate irrational prejudice (racism) with rational prejudice (it looks perl-ish, and I don't like the way perl looks, therefore I don't like the way Prothon looks). Your accusation isn't up to the level of that fellow spewing Totalitarian rhetoric about the "mental sickness" of people who wrote/use python, but it isn't far off. -jack From jsbenson at bensonsystems.com Sat Apr 3 17:03:16 2004 From: jsbenson at bensonsystems.com (John Benson) Date: Sat, 3 Apr 2004 14:03:16 -0800 Subject: browsing nuisance and a suggestion Message-ID: <014601c419c7$793db510$3709500a@jsbwxp3> Hi, I find myself plowing through much more collateral Pythonia trying to keep up with my favorite topics appearing on the list, given the recent explosion in activity. I'd like to suggest that the following boilerplate be moved from before the topics to after the topics: (begin quote) Send Python-list mailing list submissions to python-list at python.org To subscribe or unsubscribe via the World Wide Web, visit http://mail.python.org/mailman/listinfo/python-list or, via email, send a message with subject or body 'help' to python-list-request at python.org You can reach the person managing the list at python-list-owner at python.org When replying, please edit your Subject line so it is more specific than "Re: Contents of Python-list digest..." (end quote) The (admittedly slight) nuisance I experience is having to scroll down to see the last few topics because the boilerplate crowds them off the first screenful. By moving the boilerplate after the topics, I can easily see in one glance whether I want to further examine the items below or just delete the email and go on to the next. From jerry at jerrysievers.com Fri Apr 16 21:35:54 2004 From: jerry at jerrysievers.com (Jerry Sievers) Date: 16 Apr 2004 21:35:54 -0400 Subject: global variables extended to other objects/modules References: Message-ID: KN writes: > Hello, I'm new to this list, and I have an important > question at the beginning. > > There is a matter that concerns me - it's the globales > implementation. I've read nearly everything I found > about this and about problems people were having with > using it. Another poster made several good and I would say "correct" suggestions. Here's another for you to consider. At the risk of making your code unreadable and possibly buggy; Just "stick those pesky globals right down where you need em! Suppose you have a module named A which imports B and B imports C... >From A, it is possible to say B.C.var = something This works but is a nasty hack that should be saved only for extreme emergencies! Peace -- ------------------------------------------------------------------------------- Jerry Sievers 305 854-3001 (home) WWW ECommerce Consultant 305 321-1144 (mobile http://www.JerrySievers.com/ From jack at performancedrivers.com Thu Apr 29 15:36:21 2004 From: jack at performancedrivers.com (Jack Diederich) Date: Thu, 29 Apr 2004 15:36:21 -0400 Subject: static keyword In-Reply-To: References: Message-ID: <20040429193621.GB21368@performancedrivers.com> On Thu, Apr 29, 2004 at 12:09:03PM -0700, Nick Jacobson wrote: > > > > Why do you call using OO ("wrapping it in a class", as you say) > > a "hack"? Generally speaking, using objects to contain state > > information such as this is exactly what most people would call > > the cleanest, best approach. > > > > class HasState: > > def __init__(self): > > self.firstCall = True > > self.i = [10, 11] > > > > def foo(self): > > if self.firstCall: > > print "First pass" > > self.firstCall = False > > self.i[0] += 1 > > print self.i[0] > > > > obj = HasState() > > obj.foo() > > obj.foo() > > > > Now, without arguing that it has 11 lines instead of 8 to do the > > same thing (because then I'd just point out that this was a contrived > > example anyway, and that it is more easily extended, and more obvious > > what was going on, etc. :-) ), can you describe why you call this is > > a "hack"? > > > > -Peter > > I don't know if "hack" is the right word. What I meant is it seems > like overkill to have to make (and name) a class, plus add a second > function, every time you want a function to have a static variable. Keeping state in functions is usually a "hack." Class instances have state, functions just do stuff. That said you can get by just fine using default arguments for small amounts of state in functions. def foo(i=[]): if (not i): # only true once print "First!" i.extend([10, 11]) i[0] += 1 print i[0] But you really really don't want state in plain functions (as opposed to member functions of objects). I would consider any function that does something different when called twice with the same arguments broken. Unless the name of the function starts with 'random' *wink*. -jackdied From michael at foord.net Thu Apr 8 03:56:59 2004 From: michael at foord.net (Fuzzyman) Date: 8 Apr 2004 00:56:59 -0700 Subject: CGI Problems With Xitami Message-ID: <8089854e.0404072356.7f33f440@posting.google.com> OK, so this is n't strictly a Python problem *maybe* I'm writing a Customer Contact database for our intranet at work. I'm testing it using Xitami as a localhost server on my Windoze box. All of a sudden the 'POST' method has stopped working - when I specify 'POST' as the method in forms... the CGI gets no data... and I really don't want to use 'GET' as it makes the password visible in the URL... I've looked in the CGI options of the Xitami config and I can't find anything amiss, or even especially relevant. The Xitami docs say 'POST' should work fine (of course they don't mention python). Anyone any suggestions or experience. (Yes I've checked the form construction in the hTML templates - it's fine. The values don't even make it to Fieldstorage...) Regards, Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html From __peter__ at web.de Thu Apr 1 11:46:09 2004 From: __peter__ at web.de (Peter Otten) Date: Thu, 01 Apr 2004 18:46:09 +0200 Subject: splitting one dictionary into two References: <20040401153103.GC4577@jsaul.de> Message-ID: jsaul wrote: > I have to split a dict into two dicts. Depending on their values, > the items shall remain in the original dict or be moved to another > one and at the same time be removed from the original dict. > > OK, this is how I do it right now: > > dict1 = { "a":1, "b":3, "c":5, "d":4, "e":2 } > dict2 = {} > klist = [] > > for key in dict1: > if dict1[key] > 3: # some criterion > dict2[key] = dict1[key] > klist.append(key) > > for key in klist: > del dict1[key] > > print dict1 > print dict2 > > That means that I store the keys of the items to be removed from > the original dict in a list (klist) and subsequently remove the > items using these keys. > > Is there an "even more pythonic" way? Only a minor change to do away with the temporary list: for key in dict1: if dict1[key] > 3: # some criterion dict2[key] = dict1[key] for key in dict2: del dict1[key] Peter From greg at cosc.canterbury.ac.nz Thu Apr 29 00:47:51 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Thu, 29 Apr 2004 16:47:51 +1200 Subject: Don't understand wxPython ids In-Reply-To: <1a34m1-fml.ln1@home.rogerbinns.com> References: <408ed938$0$17263$a1866201@newsreader.visi.com> <1a34m1-fml.ln1@home.rogerbinns.com> Message-ID: Roger Binns wrote: > Here is how I use the same id in multiple locations. I can have a > menu entry, a toolbar button, and a button inside some HTML all > invoke the same function. The only coupling between them is > the id number. Giving an identifier to a command so that it can be invoked in multiple ways is a good idea, but it would be much more Pythonic if a *name* could be used as the identifier rather than a number. Use of a number here seems to be entirely the result of blindly carrying over a feature of the C++-oriented API into Python. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From jdhunter at ace.bsd.uchicago.edu Thu Apr 8 12:28:17 2004 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Thu, 08 Apr 2004 11:28:17 -0500 Subject: problems with compiling and loading C++ extension In-Reply-To: (Faheem Mitha's message of "Thu, 8 Apr 2004 11:52:31 -0400 (EDT)") References: Message-ID: >>>>> "Faheem" == Faheem Mitha writes: Faheem> Dear People, Faheem> I have been having an odd problem with compiling and Faheem> loading a simple C++ extension to python (as a .so file in Faheem> Linux). Unfortunately, I'll need to include my files in Faheem> here so I apologize in advance for the length of this Faheem> message. Try adding 'stdc++' to your module libraries. Another possibility is that the blitz library was compiled with a different version of g++ than you are using to compile your extension. You could try recompiling blitz with the same g++. Hope this helps, John Hunter From deetsNOSPAM at web.de Wed Apr 7 11:10:03 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Wed, 07 Apr 2004 17:10:03 +0200 Subject: Dynamic creation of an object instance of a class by name References: <10f99b0f.0404070656.5960e2c8@posting.google.com> Message-ID: cn = 'A' inst = eval('%s()' % cn) -- Regards, Diez B. Roggisch From lists at simplistix.co.uk Sat Apr 3 12:28:29 2004 From: lists at simplistix.co.uk (Chris Withers) Date: Sat, 03 Apr 2004 18:28:29 +0100 Subject: ZMySQLDA/MySQLdb: DON'T fix like this for Zope 2.7.0! In-Reply-To: <20040403171804.GA32655@calvados> References: <406E9DE4.2000604@simplistix.co.uk> <406EDE94.9000701@simplistix.co.uk> <406EEE33.9050901@simplistix.co.uk> <20040403171804.GA32655@calvados> Message-ID: <406EF43D.5040309@simplistix.co.uk> Michal Kurowski wrote: > transactional = self.db.server_capabilities & CLIENT.TRANSACTIONS > > to: > > transactional = CLIENT.TRANSACTIONS This is NOT a good fix. All you're doing is ignoring the server's capabilities, so if the server supports transactions and the client doesn't, or vice versa, you end up in a mess. I have a patch which I'm testing and will post soon. > db.py file from ZmySQLDA is requirement for python 2.3.3 based > zope to work. I think the idea is that you're supposed to use mysql-python 0.9.3b2 with Python 2.3, but there's no Windows binary for that. > Can anyone explain to me why "_mysql" (instead of "MySQLdb") is used > here in the first place ? > > Andy Dustman recommends against it for years now. Well, ZMySQLDA is Andy's code, so perhaps he could comment? ;-) Chris -- Simplistix - Content Management, Zope & Python Consulting - http://www.simplistix.co.uk From jcarlson at uci.edu Sat Apr 3 17:03:46 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Sat, 03 Apr 2004 14:03:46 -0800 Subject: Capturing stdout incrementally In-Reply-To: References: Message-ID: > I am on Windows by the way, so the utilities are printing to the windows > command shell. By default, popen in Windows buffers everything coming from the called app. I believe you can use various Windows system calls in pywin32 in order to get line buffered output, but I've never done it, so have little additional advice other than "check out pywin32". - Josiah From seberino at spawar.navy.mil Thu Apr 22 18:34:04 2004 From: seberino at spawar.navy.mil (Christian Seberino) Date: 22 Apr 2004 15:34:04 -0700 Subject: Easiest way to *add a column* to a 2d matrix/array in numarray??? References: Message-ID: Thanks for the reply. I appreciate all the help I can get. Your suggestion of using resize is excellent for adding *rows* but does not seem right for *columns*. Here is an example: >>> a array([[ 0, 1, 2, 3, 4, 5], [ 6, 7, 8, 9, 10, 11], [12, 13, 14, 15, 16, 17]]) >>> a.resize((4,6)) >>> a array([[ 0, 1, 2, 3, 4, 5], [ 6, 7, 8, 9, 10, 11], [12, 13, 14, 15, 16, 17], [ 0, 1, 2, 3, 4, 5]]) >>> a.resize((4,7)) >>> a array([[ 0, 1, 2, 3, 4, 5, 6], [ 7, 8, 9, 10, 11, 12, 13], [14, 15, 16, 17, 0, 1, 2], [ 3, 4, 5, 0, 1, 2, 3]]) Do you see how adding an extra row left old rows intact but adding an extra column messes up old columns? (i.e. data in (1,1) position is not the same after adding a column) Chris "Russell E. Owen" wrote in message news:... > In article , > seberino at spawar.navy.mil (Christian Seberino) wrote: > > >How add a column to a 2d array/matrix in numarray??? > > > >The unelegant way I found was to: > > > >1. Create a new array with an extra column (e.g. using 'zeros' function). > >2. Copy original array into new array. > >3. Copy new column into last column. > > > >Is there a slicker way to do this? > > Try numarray.resize > > -- Russell From alan.gauld at btinternet.com Thu Apr 22 18:52:57 2004 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 22 Apr 2004 23:52:57 +0100 Subject: equivalent to Tcl 'after' command? References: Message-ID: On Thu, 22 Apr 2004 17:42:37 GMT, Mark Harrison wrote: > I'm writing some event-driven programs, and I would like > to do the equivalent of the Tcl 'after' command, e.g.: > > after 1000 {puts "one second has elapsed"} > > 1. What's the most canonical way of doing this? I suspect its to start a thread that in turn starts with a sleep command. Not very pretty but approximately the same. > 2. What's the best reference that talks about non-gui event loop > programming in Python? My book(paperversion only discusses them briefly but its hardly a rference, more an intro to the convcept for beginners... Its not quite the same as a pure event loop environment but you could check out the cmd module for a text based command loop/menu system. If you haven't already.... HTH, Alan G. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld From thorsten at thorstenkampe.de Wed Apr 28 20:27:33 2004 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Thu, 29 Apr 2004 02:27:33 +0200 Subject: outline-style sorting algorithm References: Message-ID: * jwsacksteder at ramprecision.com (2004-04-19 15:08 +0100) > I have a need to sort a list of elements that represent sections of a > document in dot-separated notation. The built in sort does the wrong thing. > This seems a rather complex problem and I was hoping someone smarter than me > had already worked out the best way to approach this. For example, consider > the following list- > >>>> foo > ['1.0', '1.0.1', '1.1.1', '1.2', '1.9', '1.10', '1.11', '1.20', '1.20.1', > '1.30'] >>>> foo.sort() >>>> foo > ['1.0', '1.0.1', '1.1.1', '1.10', '1.11', '1.2', '1.20', '1.20.1', '1.30', > '1.9'] > > Obviously 1.20.1 should be after 1.9 if we look at this as dot-delimited > integers, not as decimal numbers. You need some general approach to avoid the DSU thing: def funcsort(seq, func): """ sort seq by func(item) """ seq = seq[:] seq.sort(lambda x, y: cmp(func(x), func(y))) return seq funcsort(foo, lambda x: map(int, x.split('.'))) Thorsten From pinard at iro.umontreal.ca Thu Apr 15 22:54:03 2004 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Thu, 15 Apr 2004 22:54:03 -0400 Subject: CamelCase versus wide_names (Prothon) In-Reply-To: References: Message-ID: <20040416025403.GA29314@alcyon.progiciels-bpi.ca> [Mark Hahn] > P.S. Has anyone noticed that I have finally taught myself how to not > top-post? Even more, to quote parsimoniously. Congratulations! :-) -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From mogmios at mlug.missouri.edu Sat Apr 24 10:35:33 2004 From: mogmios at mlug.missouri.edu (Michael) Date: Sat, 24 Apr 2004 07:35:33 -0700 Subject: command-line args In-Reply-To: References: Message-ID: <408A7B35.7040702@mlug.missouri.edu> > Create an empty module called "globals" and import that wherever > needed. Populate it with settings from the command-line parsing > stage. Get fancier and put defaults in there to begin with, and > override them only if specified in the command-line parsing > area. Flavour as needed... What do you do about multiple processes (of the same program) running at once? Save to /tmp//globals.py or something like that? > (That's just one option, but in many ways the simplest. Some of > us also use a simple "bag" type of object which we pass around > as required, but that's more awkward with really large applications.) I've done that before and yeh it is really a hassle with anything very large. From asdf at asdf.com Tue Apr 27 15:05:41 2004 From: asdf at asdf.com (asdf sdf) Date: Tue, 27 Apr 2004 19:05:41 GMT Subject: Python Documentation Blows! In-Reply-To: References: <20040330181802.04141.00000304@mb-m17.aol.com> Message-ID: <9ayjc.56946$Lg7.7637@newssvr25.news.prodigy.com> Chris Green wrote: > Peter Hansen writes: > > >>anton muhin wrote: >> >> >>>Maybe just start a wiki based on the current documentation? It >>>shouldn't be too difficult, should it? >> >>What part of http://wiki.wxpython.org/ is not adequate? > > > One problem wxpython's wiki seems to have is not enough time to > refactor it (coupled with the namespace changing from wxEVENT => > wx.EVENT ) and lots of nodes being empty or partially duplicated. > i'm trying out wxpython right now and trying to locate all the resources i can. wxpython is cool but, to be fair, the documentation is not there for the junior programmer type. i tried the 'obstacle course' tutorial, which looked promising, but most of it is just a table of contents waiting to be filled in. right now, newbies have a special problem because wxpython is in the middle of a 'break the world' upgrade. and some of the changes in the upgrade are being debated by the developers and might be changed again or rolled back. so the newbie is at risk of running across samples that may be the old style and not realize it. python documentation is great. wxpython doc is at an early stage of development. right now, wxpython offers the smoothest intro to someone who's comfortable using usenet for research (everyone here, but not everyone by any means), not dependent on rich IDEs, already familiar with python and python OOP, and is comfortable mentally mapping the documentation for the underlying C++ libraries into their wxPython counterparts. Junior Programmer Joe out there in VB Land is not ready for wxpython. OOT, the wxpython community and the mailing lists are an astonishing responsive and helpful group. By far the most help group per capita, I've ever run across. If you give wxpython a chance, the wxpython community will go more than the extra mile to help you out. From LimorH at Spediant.com Mon Apr 19 06:49:06 2004 From: LimorH at Spediant.com (Limor Hevroni) Date: Mon, 19 Apr 2004 12:49:06 +0200 Subject: python Message-ID: Hi , I consider using python as the programming language for an alpha testing project. I wonder whether any of you are using python in such a way, what is the best development environment for python, is anyone used python for massive project s with QA tendency ? is anyone used python with TestDirector ? I would love to get answers on taht since I am running out if time, development should start very soon. The programming language I am considering is python and java, I would love to get more info fro m people who use python in a working projects. 10x. limor hevrony Spediant Systems Ltd. _____ Upgrade Your Email - Click here! -------------- next part -------------- An HTML attachment was scrubbed... URL: From joe at notcharles.ca Tue Apr 20 17:08:34 2004 From: joe at notcharles.ca (Joe Mason) Date: Tue, 20 Apr 2004 21:08:34 GMT Subject: Dollar sign ($) on foriegn keyboards? (prothon) References: Message-ID: In article , Peter Otten wrote: >>> Apart from that obj$func() hurts my eye more than obj->func() and >>> obj!func(). As always, Python shines here with its obj.func() :-) >> >> I believe the suggestion is "$.func()" instead of "self.func()" (the >> Python way) or just ".func()" (the earlier Prothon way). Or possibly >> the suggestion is for "$func()", although I like $.func() much better. > > I skimmed too lightly over the first paragraph and missed that - but still > there is the obj$func() example in Mark's post, and with my Python mindset > (I didn't follow the Prothon discussion closely) I cannot figure out what > that is supposed to mean. Oops - I skimmed even more lightly than you did, cause I missed the obj$func example entirely. Joe From google0 at lazytwinacres.net Wed Apr 28 16:44:06 2004 From: google0 at lazytwinacres.net (Dan Dang Griffith) Date: 28 Apr 2004 13:44:06 -0700 Subject: Proposed API change for pyparsing CaselessLiteral - could break existing code References: Message-ID: <87274528.0404281244.3fde885f@posting.google.com> "Paul McGuire" wrote in message news:... > So for those of you who are still reading, and who use pyparsing, and have > CaselessLiterals in your code, and test on the returned text, what choice > would you prefer: > > 1. Keep the current behavior, and just change the docs. > 2. Fix the current behavior to match the docs, and fix up any code that uses > it. > > My personal preference is #2. We are still early in pyparsing's code life - > it has only been generally available for about 4 months - and I think it > really is the preferred way to go. I'm +1 on #2, i.e., change the code to match the docs. I have a use case where the parser is acting as a "cleanup" to the input, making it conform to a coding standard, and CaselessLiteral working as described in the docs would be perfect. I suppose I could make a setParseAction that would convert it to the appropriate case, but that would slow it down, plus I'd have to keep track of the literal in two places (well, I suppose I could define a name for the value and import it from my grammar and from the code that has the parse actions, but still...). Thanks for pyparsing. --dang From jbperez808 at yahoo.com Thu Apr 1 18:08:30 2004 From: jbperez808 at yahoo.com (Jon Perez) Date: Fri, 02 Apr 2004 07:08:30 +0800 Subject: Python passes the Turing test with a one-liner ! In-Reply-To: <406C7C1B.3080401@users.ch> References: <406C7C1B.3080401@users.ch> Message-ID: Morris Carr? wrote: > > filter(lambda W : W not in 'ILLITERATE','BULLSHIT') > The list comprehension version: [p for p in 'BULLSHITTER' if p not in 'ILLITERATE'] From mickel at csc.fi Thu Apr 15 01:57:43 2004 From: mickel at csc.fi (=?ISO-8859-1?Q?Mickel_Gr=F6nroos?=) Date: Thu, 15 Apr 2004 08:57:43 +0300 (EEST) Subject: saving a tkinter canvas to gif In-Reply-To: References: Message-ID: On Wed, 14 Apr 2004, biner wrote: > Is there any way to save a canvas created with tkinter to a gif (or > any other graphic) without using PIL (I cannot build it on our unix > machine)? Have you tried the postscript method of Tkinter.Canvas? > base=Canvas(root,width=50,height=50) > base.create_rectangle(0,0,50,25,fill='red') > base.create_rectangle(0,25,50,50,fill='blue') > base.pack() base.postscript("file.ps") /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 jepler at unpythonic.net Sun Apr 4 14:04:03 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Sun, 4 Apr 2004 13:04:03 -0500 Subject: Working with a list in a more "pythonic" way In-Reply-To: <20040404160940.GC3455@unpythonic.net> References: <20040404124833458+0200@news.rhrz.uni-bonn.de> <20040404160940.GC3455@unpythonic.net> Message-ID: <20040404180401.GD3455@unpythonic.net> [second try, python.org refused the message when the header contained non-ascii characters. As an aside, does anyone know how to configure mutt to quote non-ascii characters in headers?] First, you might want to map the letters to numbers all at once: phrase = [ord(x) - 65 for x in phrase] then you could use an iterator to give the pairs: def pairs(seq): seq = iter(seq) a = seq.next() for j in seq: yield a, j a = j Example usage: >>> list(pairs(range(5))) [(0, 1), (1, 2), (2, 3), (3, 4)] So now you can write n = 0 for first, second in pairs(phrase): n += soundScore[first][second] taking care of IndexError as above. You could also make soundScore a dictionary, which I think was discussed elsewhere. n = 0 for p in pairs(phrase): n += soundScore.get(p, 0) or n = sum([soundScore.get(p, 0) for p in pairs(phrase)]) Jeff From newsgroups at jhrothjr.com Mon Apr 26 13:56:45 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 26 Apr 2004 13:56:45 -0400 Subject: how to add new print %b format to python? References: <408D4480.8090104@draigBrady.com> Message-ID: <108qjbm70ason04@news.supernews.com>

wrote in message news:408D4480.8090104 at draigBrady.com... > Rusty Shackleford wrote: > > I have a Summer in front of me without any school, and I'd like to add a > > new format for python print strings that will show any number in a > > binary representation. For example: > > > > > >>>>'%b' % 3 > > > > 11 > > > >>>>'%b' % 5 > > > > 101 > > > > You get the idea. I've written functions that return strings, so that > > part is done, but where do I go to tinker with the python interpreter to > > add this new format? > > > > Please don't argue with me about whether this is an advisable goal in > > itself -- I'm using it as a method to learn about the internals of the > > python language. > > I don't think this will be accepted as the > format args are really a lowest common denominator > across all systems. For e.g. on linux you can use > the ' modifier to print numbers in locale format > (and example for mine is 1,234). I don't believe this is the case. I think the % operator does not use the C library's sprintf function., but I could be wrong. [snip] The rest of this is equally off base - he explicitly said he was not interested in ***whether*** he should do it, but only in *** where to look *** to find out how to do it as a summer programming exercise in the python core. John Roth > > P?draig. From lbates at swamisoft.com Thu Apr 22 10:24:57 2004 From: lbates at swamisoft.com (Larry Bates) Date: Thu, 22 Apr 2004 09:24:57 -0500 Subject: Newbie to client/server References: Message-ID: <-KedncVZStMqSBrdRVn-jg@comcast.com> Use SQL "joins" to create a single "logical" record from as many different tables as you want resulting in a single result record that contains all the fields on your form. If there is a one-many relationship between tables, you will loop over all the result records. That way you only need a single cursor. FYI, Larry Bates Syscon, Inc. "John Fabiani" wrote in message news:p6Qhc.39822$on5.30998 at newssvr29.news.prodigy.com... > I don't understand how to get data from multi tables for my forms/windows. > I have been reading how to connect and get data (using a SQL statement) > from MySQL. I think I understand. > Now the question if I have a form (i.e. AR invoice) that requires data from > more than one table (or I need multi SQL statements) where do I put it. It > appears that I can have only one cursor. This must be wrong. I can > understand that I can reuse the connect object but the returning > information ends up into the same cursor. I don't want code (just how to > do it right) but when I do something like the following it does not work: > Con=myconnection_string > Cursor=con.cursor() > Cursor.execute(somestatement) > newCursor=con.cursor() > newCursor.execute(somestatement) #does not work > John > -- > John Fabiani From tjreedy at udel.edu Thu Apr 1 11:34:16 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 1 Apr 2004 11:34:16 -0500 Subject: splitting one dictionary into two References: <20040401153103.GC4577@jsaul.de> Message-ID: "jsaul" wrote in message news:20040401153103.GC4577 at jsaul.de... > Hello all, > > I have to split a dict into two dicts. Depending on their values, > the items shall remain in the original dict or be moved to another > one and at the same time be removed from the original dict. > > OK, this is how I do it right now: > > dict1 = { "a":1, "b":3, "c":5, "d":4, "e":2 } > dict2 = {} > klist = [] > > for key in dict1: > if dict1[key] > 3: # some criterion > dict2[key] = dict1[key] > klist.append(key) > > for key in klist: > del dict1[key] > > print dict1 > print dict2 > > That means that I store the keys of the items to be removed from > the original dict in a list (klist) and subsequently remove the > items using these keys. > > Is there an "even more pythonic" way? Delete klist stuff and do deletion with for key in dict2: del dict1[key] tjr From skip at pobox.com Wed Apr 28 12:36:29 2004 From: skip at pobox.com (Skip Montanaro) Date: Wed, 28 Apr 2004 11:36:29 -0500 Subject: PyChecker does STATIC analysis? In-Reply-To: <3064b51d.0404280728.5fb7539e@posting.google.com> References: <3064b51d.0404280728.5fb7539e@posting.google.com> Message-ID: <16527.56717.323963.457874@montanaro.dyndns.org> beliavsky> If I run PyChecker on the following program, stored in xtry.py, beliavsky> m = 10000000 beliavsky> k = 0 beliavsky> for i in xrange(m): beliavsky> k = k + i beliavsky> print k beliavsky> x = range(3) beliavsky> print x[3] beliavsky> the output is beliavsky> 49999995000000 beliavsky> Warnings... beliavsky> xtry:1: NOT PROCESSED UNABLE TO IMPORT ... beliavsky> I am surprised that PyChecker actually needs to execute the beliavsky> code block beliavsky> for i in xrange(m): beliavsky> k = k + i beliavsky> print k beliavsky> before finding the out-of-bounds error. Try modifying your code to this: if __name__ == "__main__": m = 10000000 k = 0 for i in xrange(m): k = k + i print k x = range(3) print x[3] PyChecker simply imports your module. Importing a module causes the code at the top level to be executed. beliavsky> The Lahey/Fujitsu Fortran 95 compiler is able to catch the beliavsky> out-of-bounds error at COMPILE time for an analogous Fortran beliavsky> program. Python is just slightly more dynamic than Fortran, and I'm sure the Lahey/Fujitsu compiler has had a few more man-years of development put into it than PyChecker. As an example of the former point, note that PyChecker can't assume that the output of range(3) is a list of 3 elements. Another module may have modified builtins before the code was executed. Skip From peter.maas at mplusr.de Tue Apr 27 04:27:32 2004 From: peter.maas at mplusr.de (Peter Maas) Date: Tue, 27 Apr 2004 10:27:32 +0200 Subject: Is Perl *that* good? (was: How's ruby compare to it older bro In-Reply-To: References: Message-ID: Peter Hansen wrote: > I guess it would be interesting to pose the question back to > them "If you could not use regexes in Perl, would you still > like to program in it?" or "If you couldn't use mysql in PHP > would you still use it?" > > What similar question, if any, would be a difficult one for > us Python types? If you could not use block indentation in Python, would you still like to program in it? :-) Mit freundlichen Gruessen, Peter Maas -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Hubert-Wienen-Str. 24 Tel +49-241-93878-0 Fax +49-241-93878-20 eMail peter.maas at mplusr.de ------------------------------------------------------------------- From peter at engcorp.com Mon Apr 26 12:01:07 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 26 Apr 2004 12:01:07 -0400 Subject: AOP use cases In-Reply-To: References: <84fc4588.0404140106.3fa0c55@posting.google.com> <0pydnSB4WYuieuLdRVn-hQ@powergate.ca> Message-ID: <7NudnQB0EdLerxDdRVn_iw@powergate.ca> Eric Eide wrote: > Perhaps you would be interested in IBM's recent paper, which was presented at > the AOSD 2004 conference: > > Adrian Colyer and Andrew Clement. ``Large-Scale AOSD for Middleware.'' > In Proceedings of the 3rd International Conference on Aspect-Oriented > Software Development, Lancaster, UK, March 2004, pages 56--65. > Thanks, but """Full-Text is a controlled feature. To access this feature: * Please login with your ACM Web Account. * Please review the requirements below. """ And it appears memberships must be purchased. > Now you might discount this as primarily being "a project just to demonstrate > AOP," but I think that that would be unfair. Perhaps, but I'll reserve judgment until I see significant signs of it being used outside of such projects nevertheless. -Peter From snail at objmedia.demon.co.uk Thu Apr 1 13:41:49 2004 From: snail at objmedia.demon.co.uk (Stephen Kellett) Date: Thu, 1 Apr 2004 19:41:49 +0100 Subject: [OT] WARNING! - Dangerous new e-mail virus! References: Message-ID: In message , Robert Oschler writes >"A deadly new computer virus that is spreading rapidly by e-mail has already >caused massive damage to thousands of unprotected computers worldwide. The >virus is rumored to be the deadly brainchild of renegade microbiology >scientists, who have figured out how to cross the barrier from the digital >world to the analog, and create a real biological virus on the victim's >computer. For an actual photo of a ravaged computer, and further details on >this frightening new virus, visit http://www.robotsrule.com/ ". Oh, look it is April 1st. -- Stephen Kellett Object Media Limited http://www.objmedia.demon.co.uk RSI Information: http://www.objmedia.demon.co.uk/rsi.html From newsgroups at jhrothjr.com Fri Apr 9 14:42:15 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Fri, 9 Apr 2004 14:42:15 -0400 Subject: module not callable - why not? References: Message-ID: <107drne5pm4sfd7@news.supernews.com> "djw" wrote in message news:VKAdc.360$rC3.22993 at attbi_s53... > Diez B. Roggisch wrote: > > Hi, > > > > I just thought about creating a module for quaternions (as an personal > > exercise, so I'm not after pointers to classlibs here). > > > > Now usually I'd create a file called "quaternion.py", define my quaternion > > class in there and then import and create an instance like this: > > > > import quaternion > > > > q = quaternion.quaternion() > > > > Thats a lot to type. doing a > > > > from quaternion import quaternion > > > > would solve that - but AFAIK thats considered bad for some reasons. > > I think what people consider dangerous is 'from import *'. The > form you give here is OK, as far as I know. > > > > > Now I thought about defining a __call__ operator at module level to allow > > this: > > > > import quaternion > > > > q = quaternion() > > > > > > where the call looks like this: > > > > def __call__(*a, *kw): > > return quaternion() > > > > But that doesn't work. > > > > Now my question is: Is there a way to make a module callable that way? And > > wouldn't it make sense to allow the implementation of a call operator on > > module level? > > I know this has been discussed before (using __main__() instead). Try > googling for some discussions. The discussion on __main__() isn't quite the same thing. If I remember correctly, the use case for __main__ was to get rid of the two line suffix to a script to make it executable. This is rather obscure to novices, while __main__() would be a bit more understandable. At least, it's similar to what other languages do for a startup function. There was no intention that __main__() be called on an import, or that it be accessable via the normal call syntax on the module object. At least, I don't remember such. John Roth > > -Don > From michele.simionato at poste.it Thu Apr 29 09:17:45 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 29 Apr 2004 06:17:45 -0700 Subject: Generic constructors and duplication of internal Python logic References: <87ekqq41ya.fsf@pobox.com> <8dad5312.0404280217.21c2cfd1@posting.google.com> <95aa1afa.0404280619.778bd323@posting.google.com> <8dad5312.0404282313.8eb76b0@posting.google.com> Message-ID: <95aa1afa.0404290517.20cac261@posting.google.com> sdementen at hotmail.com (Sebastien de Menten) wrote in message news:<8dad5312.0404282313.8eb76b0 at posting.google.com>... > 2) I don't get the point about the .pyc inspect.getsource look at the .py file; in some situations (i.e. trying to obfuscate code) you may want to ship the .pyc file only; so inspect.getsource cannot work (unless you decompile the .pyc file and restore .py). For instance try $ cat example.py import inspect,sys print inspect.getsource(sys.modules["__main__" ]) run it and then remove example.py. Also, the approach breaks down if the code is executed dynamically; for instance C-c C-c in emacs would not work. Michele Simionato From james at ractive.ch Mon Apr 12 16:03:28 2004 From: james at ractive.ch (Jean-Pierre Bergamin) Date: Mon, 12 Apr 2004 22:03:28 +0200 Subject: How to kill a SocketServer? References: Message-ID: Diez B. Roggisch wrote: >> The problem is, that I found no way to interrupt the blocking call to >> self.rfile.readline(). Is there a way to do that? > > From the SocketServerDocs: > > --------------- > serve_forever() > > Handle an infinite number of requests. This simply calls > handle_request() inside an infinite loop. > > --------------- > > So simply call handle_request yourself, like this: > > while self.run_me: > s.server_forever() I'm already having such a construct. The problem is the following: The server waits for a connection and it calls in SocketServer.TCPServer.handle_request() the function self.socket.accept(). This call blocks until a connections is made. I have no chance to interrupt this call. I also tried: def stop_server: self.socket.shutdown(2) self.socket.close() self.run_me = False The accept() call still won't get interrupted. :-( Other ideas? James -- http://www.p800.info From jnfoster at cis.upenn.edu Tue Apr 27 14:55:48 2004 From: jnfoster at cis.upenn.edu (Nate Foster) Date: Tue, 27 Apr 2004 14:55:48 -0400 (EDT) Subject: Announcement: 2004 ICFP Programming Contest Message-ID: We are pleased to announce The Seventh Annual ICFP PROGRAMMING CONTEST 4 June - 7 June 2004 http://icfpcontest.org/ Convinced your favorite programming language provides unbeatable productivity? Convinced you and your friends are world-class programmers? If so, we're providing you the opportunity to prove it! We are pleased to announce the Seventh ICFP Programming Contest to be held in conjunction with the 2004 International Conference on Functional Programming (ICFP 2004). All programmers are invited to enter the contest, either individually or in teams; we especially encourage students to enter. You may use any programming language (or combination of languages) to show your skill. On Friday, 4 June 2004 at 12:00 Noon (EDT), we will publish a challenge task on the Web site and by e-mail to the contest mailing list. Teams will have 72 hours until Monday, 7 June 2004, 12:00 Noon (EDT) to implement a program to perform this task and submit it to the contest judges. We have designed the contest for direct, head-to-head comparison of language technology and programming skill. We have a range of prizes including cash awards and, of course, unlimited bragging rights for the winners. For more information about the contest, prizes, and registration, point your browser to the contest website: http://icfpcontest.org For more information about previous contests, see: http://icfpcontest.org/history.php -- Contest Team From rogerb at rogerbinns.com Wed Apr 28 15:43:28 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Wed, 28 Apr 2004 12:43:28 -0700 Subject: Path ... where is my application's home dir? References: <408fbc0a$0$17256$a1866201@newsreader.visi.com> Message-ID: Marco Aschwanden wrote: > - I want to store the current state of the application when leaving the > application in an ini-file. > - It is a "single-user" pc! Note that since Windows 95, you can have multiple users, but only one at a time could be logged in. With XP you can actually have multiple logged in at the same time (Press Windows Key + L) > - I don't like (others would say hate) to use the registry. Your users are going to be used to the registry being used. But it is your app with your rules :-) > - I prefer having ini-files in the application directory. Many people install the apps as administrator and then run as a ordinary user. They won't be able to write to that directory. (Note this is a VERY common configuration in a corporate environment). > > > sys.argv[0] does not work for my purposes... do you have any > > > other ideas. This works on Windows, Linux and Mac, even when the application has been frozen using py2exe, cx_Freeze and BundleBuilder respectively: p=sys.path[0] if p.lower().endswith(".zip"): # py2exe zip importer in action p=os.path.dirname(p) appdirectory=os.path.abspath(p) > And yes, the best place to store this information would be in the user's > home dir, but then: Where is it? How to find it under Windows - every > version of windows changes the place for home dirs. It would be nice to > have something like this in a system/version independet way: If the system is Windows 2000 or XP then os.path.expanduser("~") will give their home directory. (That also works on UNIX and Mac). If you want to do things properly on Windows, you should use the registry, or use this code to find the right folder. You need win32all installed. from win32com.shell import shell, shellcon path=shell.SHGetFolderPath(0, shellcon.CSIDL_PERSONAL, None, 0) The list of CSIDL constants is at MSDN: http://tinyurl.com/7hei Roger From claird at lairds.com Sun Apr 4 17:22:12 2004 From: claird at lairds.com (Cameron Laird) Date: Sun, 04 Apr 2004 21:22:12 -0000 Subject: Extending Python Syntax with @ References: <105jorolc069r50@news.supernews.com> Message-ID: <1070v44sjn9mmba@corp.supernews.com> In article , Heather Coppersmith wrote: . . . >The typical SmallTalk or Lisp environment might come close, but >their footprints are larger than Sasquatch's. Also, those . . . Squeak might interest you as a lightweight Smalltalk. -- Cameron Laird Business: http://www.Phaseit.net From mhuening at zedat.fu-berlin.de Wed Apr 7 14:54:32 2004 From: mhuening at zedat.fu-berlin.de (Matthias Huening) Date: 7 Apr 2004 18:54:32 GMT Subject: Tkinter MultiListbox Message-ID: Hello, I have used Bob Haucks MultiListbox.py (http://www.haucks.org/) in my (hobby-)projects. Now I am looking for an enhanced version, which overcomes the limitations of MultiListbox: # Limitations: # o Only single selection. # o No horizontal scrolling or column resizing. # o Vertical scrollbar is always present. # o Doesn't sort when column labels are clicked. Does somebody know of a MultiListbox with column resizing and sorting? Thanks, Matthias From opengeometry at yahoo.ca Sun Apr 11 15:16:03 2004 From: opengeometry at yahoo.ca (William Park) Date: 11 Apr 2004 19:16:03 GMT Subject: Python OS References: <107j4eu6ffn2c68@corp.supernews.com> Message-ID: A Evans wrote: > I have a question concerning the development of Python Based Operating > System. You see I have had sort of a dream to develop an Open Source > Operating System that would revolutionize the OS market and Since I > started using Python I have fallen in love with the language. Reading > articles here and there I have read that Python is a more secure > language than C. I also read another article (I can't remember which) > saying Python would not be able to develop an OS. I don't believe its > true however. I am by no means a programmer at this stage. But as I > learn more and more I see Python as the Holy Grail of programming > languages > > My questions would then be, is Python capable of creating an OS from > scratch and if so would it be plausible if possible This would be interesting thesis material. As someone else quoted, "In theory, there is no difference between theory and practice. But, in practice, there is." -- William Park, Open Geometry Consulting, Linux solution/training/migration, Thin-client From dmq at gain.com Fri Apr 23 20:17:22 2004 From: dmq at gain.com (David MacQuigg) Date: Fri, 23 Apr 2004 17:17:22 -0700 Subject: Why we will use obj$func() often References: <84Uhc.22278$dZ1.5087@fed1read04> <8AWhc.23114$dZ1.11070@fed1read04> <40883BFE.B381518A@alcyone.com> <27_hc.23801$dZ1.2716@fed1read04> <40887145.789A2FE8@alcyone.com> <7cki80hj976bia36lhf9er97v073o1pqvm@4ax.com> Message-ID: <27cj80pq3lh4reaeois9snd2cbbiifv2qt@4ax.com> On Fri, 23 Apr 2004 13:50:24 -0700, "Mark Hahn" wrote: >"Mel Wilson" wrote in message >news:ulXiAls/KH1K089yn at the-wire.com... > >> It can, if you spell '&' differently: >> >> def getfunc(): >> def count (n=[0]): >> n[0] += 1 >> print n[0] >> return count >> >> c = getfunc() >> c() >> c() >> c() > >True. A bit inelegant, but then so is &. > >Would you trade the "mutable integer" and "count(n=[0])" kludges for a >solution like &count ? Does anyone agree with me that a "closure variable >prefix" is more explicit and readable? > >Let's seperate the aesthetic issues of using "Perl-like" symbols from the >"closure variable prefix" functionality for a moment. I'd like feedback on >both issues, but try to keep them seperate. We need to see what the problem is before we can judge a solution. Just showing a code snippet and saying "do this" is not a good statement of the problem. As you have seen, there are simple elegant solutions that don't follow your code line-for-line, and there are inelegant solutions that are very close. Both categories seem to solve what we think the problem is, but you may have another problem in mind. A use-case would be helpful. As an alternative, we could work with a clear statement of the problem, something like: The proposed syntax will allow assigning values to (not just referencing) variables in a scope surrounding a nested function. This will be useful when the existing alternatives are not appropriate: 1) Attach the variable to an instance. 2) Make the variable global. 3) Add the variable to the function argument list. 4) ... I've probably mistated it, but you see what I'm getting at, something that de-couples the user-level problem from the particular mechanisms of the language. Trying to reproduce these mechanisms in Python will be the road to Per ... dition. :>) -- Dave From dmq at gain.com Thu Apr 29 15:35:55 2004 From: dmq at gain.com (David MacQuigg) Date: Thu, 29 Apr 2004 12:35:55 -0700 Subject: Is classless worth consideration References: <40905CF7.4A2625A4@alcyone.com> Message-ID: On Wed, 28 Apr 2004 18:40:07 -0700, Erik Max Francis wrote: >David MacQuigg wrote: > >> The problem we Python programmers are having is understanding the >> fundamental advantage of eliminating classes and working only with >> instances. The theoretical discussions put me to sleep. I can't see >> the point of the examples above. What we need is a simple use case. > >I certainly don't see the point in having a prototype-based system if >the declaration for defining a prototype (`proto' in your examples) >looks very much like the way you build a class. All that seems to >accomplish is a semantic change of "class" to "proto," which doesn't >gain anything. > >Compare that to, say, Io -- a prototype-based system -- where there is >no syntax at all for defining a "class" or "prototype." You simply >clone and attach messages as you go. I'm not familiar with Io. The syntax I am proposing will allow cloning instances and attaching attributes as you go. What do "messages" provide that are lacking in normal attributes? -- Dave From roy at panix.com Sat Apr 10 22:43:28 2004 From: roy at panix.com (Roy Smith) Date: Sat, 10 Apr 2004 22:43:28 -0400 Subject: Python is the best and most popular general purpose scripting language; the universal scripting language References: Message-ID: rstephens at vectron.com (Ron Stephens) wrote: > [...] > Python is the best general purpose scripting language. > [...] > Python is the most general purpose of the scripting languages > [...] > Python is the best and most popular general purpose scripting language. > [...] > Python is the best general purpose scripting language. Come on Ron, tell us how you really feel :-) From torsten.marek at student.uni-tuebingen.de Thu Apr 15 05:16:31 2004 From: torsten.marek at student.uni-tuebingen.de (Torsten Marek) Date: Thu, 15 Apr 2004 11:16:31 +0200 Subject: Threading question Message-ID: Hello to all, I have a simple question about threads in Python. I am starting a number of threads in my program and I want print out the amount of time needed after all threads stopped. Do I need to explictly join the threads, set a condition or is it possible to somehow work with try/finally like that: try: for i in range(0, num_threads): s = MyThread() s.start() finally: print "all threads finished" Thanks in advance Torsten From peter at engcorp.com Sun Apr 25 13:31:45 2004 From: peter at engcorp.com (Peter Hansen) Date: Sun, 25 Apr 2004 13:31:45 -0400 Subject: Andreas' practical language comparison In-Reply-To: References: Message-ID: <408BF601.30004@engcorp.com> Andreas Koch wrote: > i started a little "practical language comparison" - practical > in the sense that i compare how actual distributions and versions > and their libraries (not abstract language specifications) solve small > test cases like the 8 queens problem. > > http://www.kochandreas.com/home/language/lang.htm > > and mail me your code snippets (or critics) or post them here. The Java implementation of Bubble Sort doesn't follow the specification for the algorithm. It fails to use a "swapped" flag to determine when to terminate the loop. -Peter From me at privacy.net Sun Apr 4 07:43:28 2004 From: me at privacy.net (Duncan Booth) Date: 4 Apr 2004 11:43:28 GMT Subject: Python is faster than C References: <406F0907.96F37EA1@tunes.org> Message-ID: Joe Mason wrote in news:slrnc6ud7b.4u7.joe at gate.notcharles.ca: > In article <406F0907.96F37EA1 at tunes.org>, Armin Rigo wrote: >> The reason that Psyco manages to outperform the C implementation is not >> that gcc is a bad compiler (it is about 10 times better than Psyco's). >> The reason is that the C implementation must use a generic '<' operator >> to compare elements, while the Psyco version quickly figures out that it >> can expect to find ints in the list; it still has to check this >> assumption, but this is cheap and then the comparison is done with a >> single machine instruction. > > Why can't the C implementation do the same thing? > It easily could, however sorting a list of ints sounds to me like a comparatively unusual thing to do in any real application. Sorting strings, or sorting more complex data structures are much more usual. In other words it would be kind of pointless to introduce an optimisation that only helps speedup benchmarks. Also the builtin sort handles other cases which are important. Not all data you want to sort is randomly ordered. The builtin sort method should outperform quicksort in those cases where the input is already largely sorted. The builtin sort is also stable, although for a list of random integers you might be hard pushed to tell :-) From herrn at gmx.net Tue Apr 6 18:38:24 2004 From: herrn at gmx.net (Marco Herrn) Date: 6 Apr 2004 22:38:24 GMT Subject: regex help for a newbie References: Message-ID: On 2004-04-06, marco wrote: > Marco Herrn writes: > >> On 2004-04-06, marco wrote: >> > Marco Herrn writes: >> >> the parts in a recursive function. So the thing I want to achieve here >> >> is to extract %(BBB%(CCC)BBB) and %(DDD). >> > >> > p1, p2 = "aaa%(BBB%(CCC)BBB)aaa%(DDD)aaa".split("aaa")[1:-1] >> >> Doesn't help, since I do not know that there is the string "aaa". It was >> just an example. I do not know any of the strings/characters. The only >> thing I know is that a percent sign indicates that the content inside >> the following parentheses is an expression that has to be evaluated. > > Does the "aaa"-type string really show up three times? Or is it actually: > > "maybeeggs%(BBB%(CCC)BBB)maybeham%(DDD)maybespam" Yes, it is this. I just used the same strings to indicate the nesting levels. All strings in this expression are arbitrary strings. > (but I doubt it -- I guess you'll need a real parser :) Yes, I already realized that :-) Marco -- Marco Herrn herrn at gmx.net (GnuPG/PGP-signed and crypted mail preferred) Key ID: 0x94620736 From deetsNOSPAM at web.de Mon Apr 5 09:03:08 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Mon, 05 Apr 2004 15:03:08 +0200 Subject: regex help for a newbie References: Message-ID: Marco Herrn wrote: > I have the following string in my program: > > string= "aaa%(BBB%(CCC)BBB)aaa%(DDD)aaa" > > Now I need to extract the parts that are enclosed in %(). > There are 3 levels of nesting. The first level is named > 'aaa', the second 'BBB' and 'DDD' and the third 'CCC'. > I do not need to extract the third level at this moment, since I extract > the parts in a recursive function. So the thing I want to achieve here > is to extract %(BBB%(CCC)BBB) and %(DDD). Regexes aren't powerful enough for this - they are stateless, that means that they have no way to count the number of open parenthes already found. so you can't solve your problem with them. So what you need here is a parser that has state. You can either use one of the existing parser frameworks (I personally use spark) or you write it for yourself, as your problem is considerably easy: def parse(input): res = "" level = 0 for c in input: if c == "(": level += 1 elif c == ")": level -= 1 if level > 0 and c != "(": res += c return res -- Regards, Diez B. Roggisch From andrew.henshaw at gtri.gatech.edu Fri Apr 2 10:40:28 2004 From: andrew.henshaw at gtri.gatech.edu (Andrew Henshaw) Date: Fri, 2 Apr 2004 15:40:28 +0000 (UTC) Subject: Making the Zen of Python more useful References: <106qp0uivlefo40@corp.supernews.com> <-5ydnTEmxfuZHvDdRVn-iQ@powergate.ca> Message-ID: In article <-5ydnTEmxfuZHvDdRVn-iQ at powergate.ca>, peter at engcorp.com says... > >Andrew Henshaw wrote: > >> In article , peter at engcorp.com says... >>>I'm not sure why you had to do quite all that. The following is >>>sufficient, and you don't need a custom ROT-13 thingie: >>> >>>>>>import StringIO, sys >>>>>>s = StringIO.StringIO() >>>>>>sys.stdout = s >>>>>>import this >>>>>>sys.stdout = sys.__stdout__ >>>>>>s.getvalue() >>> >>>"The Zen of Python, by Tim Peters\n\nBeautiful is ... >> >> Much better. Still pretty awkward for the purpose I described. Perhaps, the >> best solution, overall. > >Okay then, how about this one? :-) > > >>> import this >The Zen of Python, by Tim Peters\n\nBeautiful is ... > >>> this.s.decode('rot-13') >u"The Zen of Python, by Tim Peters\n\nBeautiful is ... > >-Peter Hey, that's very slick! But ... (starting to feel like a whiner), my main problem was with the automatic printing of the text upon import. Obviously, that functionality needs to remain. It would just be nice if there was some clean way of (sometimes) using the module without it. Thanks again! -- Andy From peter at designtheory.org Thu Apr 29 14:58:26 2004 From: peter at designtheory.org (Peter Dobcsanyi) Date: 29 Apr 2004 18:58:26 GMT Subject: bags in collections - PEP 320 Message-ID: Dear All, I have just read PEP-320 and noticed the following comments regarding the "collections" package: ... - ? bag (only if use cases established) ... I would like to argue for such a use case. We at designtheory.org are working on a (maths / stats / comp. sci.) project in the area of Design Theory. Design theory intersects with many fields, to mention a few: combinatorics, graph theory, finite geometry, coding theory, and the design of statistical experiments (from which then name of the field comes). Most of our software development will be in Python, although the released python software so far is very modest. To show why bags are important for us and, in general, for discrete mathematicians, here is the definition of the most important type of designs. A binary block design is a multiset (that is a 'bag') of subsets of a 'base' set; the elements of the base set are called 'points' and its subsets are called 'blocks'. (Personally, I prefer the name bag but most mathematicians use multiset.) A non-binary block design is one whose blocks can also be multisets. The computations we are facing are very much combinatorial in nature so we are happy to see that Sets became a builtin and, of course, would like to see a C implementation for bags too. Our pydesign package (will) heavily use C extensions. So far we use numarray to compute statistical properties of designs, but many more combinatorial functionalities will be implemented in C. In particular, we are planning to implement a basic permutation group package whose core will eventually be a C extension. We would like to deal with automorphism groups and isomorphisms of designs on at least a basic level within the pydesign package without having to resort to specialized mathematical packages like GAP. These functionalities can be useful not only for design theorist, but for anybody using Python to deal with combinatorial structures, like graphs for example. In all of these areas the use of multisets (bags) is pervasive. Please, implement it -- so we don't have to :-) For more details on our project, please visit http://designtheory.org/ -- , Peter Dobcsanyi From jbperez808 at yahoo.com Sun Apr 4 21:47:53 2004 From: jbperez808 at yahoo.com (Jon Perez) Date: Mon, 05 Apr 2004 09:47:53 +0800 Subject: Type checking inside a C extension Message-ID: I have a C extension function into which I pass a list of lists of tuples: [ [ ("A",1), ("B",2) ("C",3) ], [ ("A",1), ("B",2) ("C",3) ], [ ("A",1), ("B",2) ("C",3) ], ] I then unpack the values (down to the tuple elements) into their C values using: PyLong_AsLong(PyTuple_GetItem(tupl,0)) to extract the int from the first element of the tuple and PyString_AsString(PyTuple_GetItem(tupl,1))[0] to get the char from the second element. The problem is that neither PyLong_AsLong() nor PyString_AsString() does any type checking so the interpreter crashes when I try to use the values returned by PyLong_AsLong() and PyString_AsString() if they happen to be fed objects - the tuple elements in this case - of the wrong type. I could certainly do a type check using PyLong_Check() and PyString_Check() on the tuple items and raise a TypeError exception to avoid leading to a crash, but I am concerned about the speed hit as this is the innermost loop of a routine which gets called really often (I use it for text block transfers). Is there a less expensive way to check the type, or somehow avoid a crashing situation (i.e. an exception gets properly raised) without calling PyLong_Check() and PyString_Check() the elements of each and every tuple? From nospam at nowhere.hu Sun Apr 18 15:26:18 2004 From: nospam at nowhere.hu (Miklós) Date: Sun, 18 Apr 2004 21:26:18 +0200 Subject: New scripts directory References: Message-ID: That's sorta funny. Or is it? You annouce a new website on comp.lang.python and there's no Python section on that site.. Mikl?s "CodeStreets.com" wrote in message news:mailman.736.1082255193.20120.python-list at python.org... Hi, We would like to announce a new scripts directory website - http://www.codestreets.com - and we invite you to add your scripts. It's FREE. Best regards, Vlad www.codestreets.com From r_b_lawson at yahoo.com Fri Apr 23 19:15:55 2004 From: r_b_lawson at yahoo.com (Rick Lawson) Date: 23 Apr 2004 16:15:55 -0700 Subject: tkinter widget collection project References: Message-ID: <14460e6d.0404231515.270e497d@posting.google.com> The wiki it is then, I see your point about being able to pick and choose. At least it will be a central place where widgets can accumulate. klappnase at web.de (klappnase) wrote in message news:... > rick.lawson at rbc.com wrote in message news:... > > I, like a lot of developers, have collected a homegrown set of widgets for > > Tkinter. > > > > Any thoughts on a central repository for Tkinter widgets or widget > > extensions? Stuff that's not in Tkinter or standard extensions like Pmw. > > > > It would be nice if you could go to sourceforge and download a package > > instead of hunting the Vaults, the Activestate cookbook, googling, etc. > > > > If there's enough interest I'd be willing to set the project up on > > sourceforge and provide some (limited) manpower towards packaging submitted > > widgets. > > > > Great idea! > > Maybe it might be even nicer if it was not necessary to download the > whole package; I was thinking of a page where you could directly copy > and paste the code of a widget into your application. > I'm not sure about that, but maybe the Tkinter wiki Cameron Laird > mentioned might be a good place for that, it might make it easier for > other people to extend existing widgets (or maybe fix bugs in more > complex ones). > > > > Thanks, > > Rick Lawson > > > > Thanks to you! > > Michael From thorsten at thorstenkampe.de Thu Apr 29 04:29:58 2004 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Thu, 29 Apr 2004 10:29:58 +0200 Subject: sorting a list References: <17i4tmtsfvae9$.dlg@thorstenkampe.de> Message-ID: [Snip fullquote] * Sean Berry (2004-04-29 02:50 +0100) >>>> a = ['A', 'D', 'F', 'a', 'f'] >>>> a.sort(lambda x, y: cmp(string.lower(x), string.lower(y))) >>>> a > ['a', 'A', 'D', 'f', 'F'] > > this will work too, if lower can come before upper. Yes indeed. But the main point of my posting was to use a general function sort so you don't have to reinvent the wheel everytime for every single sorting problem. Another advantage of my approach is to use a function of *one* variable (at the top level) and the other ones use a function of two variables. It doesn't make much difference with this trivial task, but when the function you want to sort by is much more complex it makes a hell of a difference. funcsort(foo, lambda x: x.lower()) is clean code and tells even without a comment that you want to sort case insensitively. Thorsten From ep at epoz.org Thu Apr 1 06:54:38 2004 From: ep at epoz.org (Etienne Posthumus) Date: Thu, 1 Apr 2004 13:54:38 +0200 Subject: xmlrpc, httplib and SSL (HTTP 1.1 XMLRPC client) In-Reply-To: References: Message-ID: <5A9E0238-83D3-11D8-B15E-0003935458F6@epoz.org> On Mar 27, 2004, at 5:03 AM, Roger Binns wrote: > However I was wondering if anyone was working on fixing the > (IMHO horrible) mess and wants any moral support? I wanted to do keep the connections on which my clients do XMLRPC calls open, and after staring at the xmlrpclib.py source for a while, came up with the class at the bottom of the message. Just thought I would post it here in the spirit of sharing. You would use it like this: import httplib, xmlrpclib s = xmlrpclib.ServerProxy('http://SOMEURL', transport=PersistTransport()) And then use as normal. When any error occurs, the connection is closed, seems a bit pessimistic, but I didn't want to do anything more fancy. cheers, Etienne Posthumus --- http://www.mnemosyne.org/ Cultural Heritage Research Python, Zope, XML expertise for hire. Amsterdam, Nederland ---- class PersistTransport(xmlrpclib.Transport): '''Provides a Transport for the xmlrpclib that uses httplib supporting persistent connections Does not close the connection after each request. ''' connection = None def request(self, host, handler, request_body, verbose=0): if not self.connection: host, extra_headers, x509 = self.get_host_info(host) self.connection = httplib.HTTPConnection(host) self.headers = {"User-Agent" : self.user_agent, "Content-Type" : "text/xml", "Accept": "text/xml"} if extra_headers: for key, item in extra_headers: self.headers[key] = item self.headers["Content-Length"] = str(len(request_body)) self.connection.request('POST', handler, request_body, self.headers) r = self.connection.getresponse() if r.status != 200: self.connection.close() self.connection = None raise xmlrpclib.ProtocolError( host + handler, r.status, r.reason, '' ) data = r.read() p, u = self.getparser() p.feed(data) p.close() return u.close() From peter at semantico.com Wed Apr 7 05:51:22 2004 From: peter at semantico.com (Peter Hickman) Date: Wed, 07 Apr 2004 10:51:22 +0100 Subject: design by contract versus doctest In-Reply-To: <4073c94a$0$5066$4d4ebb8e@news.nl.uu.net> References: <407174ea$0$5066$4d4ebb8e@news.nl.uu.net> <4072977b$0$1699$afc38c87@news.easynet.co.uk> <4073c94a$0$5066$4d4ebb8e@news.nl.uu.net> Message-ID: <4073cf1b$0$18217$afc38c87@news.easynet.co.uk> aku wrote: > If someone deserves the title "father of DBC" it surely must > be E. W. Dijkstra, the one who teached me in college;) How come? This is obviously some bit of CS history I have missed, do tell. From flupke at nonexistingdomain.com Thu Apr 22 19:24:15 2004 From: flupke at nonexistingdomain.com (flupke) Date: Thu, 22 Apr 2004 23:24:15 GMT Subject: python web programming / CMS References: <0kVhc.54316$eB7.29255@newssvr25.news.prodigy.com> <9YWhc.82882$%l7.5377160@phobos.telenet-ops.be> Message-ID: asdf sdf wrote: >> Well, i'm assigned a project where i have to choose a intranet >> sollution and a platform for future webbased tools development. >> I'm trying to get a clear idea of what is possible. >> For the moment 2 kinds of setup are considered >> OpenCMS - JBoss - Apache - Tomcat >> or >> Plone - Zope - Apache - Spyce / modpython >> > > with modpython/spyce you can use your own python objects. > > There's been a lot of discussion of Plone and Zope. Check Slashdot. > Both have a lot of rapid fans, but naysayers say they are too > complicated and too slow. Some say you're buy end user ease-of-use at > the cost of administrative complexity. you'll have to let me know > what you find out. Hehe :) Well i'm trying to figure out before i decide on what i'm going to use. Are there other good CMS around based on Python? Anyway, i saw a page ( forgot the link ) that had benchmarks between python, java, c++ and perl and it seemed that Python was indeed a lot slower than the other languages. But if you have a fast server, it might not be so much of a problem. flupke From stach at fr.USUN.pl Thu Apr 15 13:57:24 2004 From: stach at fr.USUN.pl (Krzysztof Stachlewski) Date: Thu, 15 Apr 2004 19:57:24 +0200 Subject: Socket error: 10053 software caused connection abort In-Reply-To: References: Message-ID: Jean-Pierre Bergamin wrote: > Jean-Pierre Bergamin wrote: > >>I'd be glad if someone could test theses scripts to see if this error >>also occurs on other coputers and systems. >> >>Or is there anything wrong with the code? > > > Could anyone reproduce this error? Yes I could observe this error some time ago. It is not related to Python but it is rather a Windows Sockets error. Searching the google I have found this description of the error message: http://support.ipswitch.com/kb/WSK-19980702-EM02.htm Try to use a sniffer like Ethereal and see what packets are sent and received from the network. -- Stach Tlen: stachobywatelpl, GG: 1811474 Jabber: stach at jabber atman pl From python at rcn.com Sat Apr 17 09:17:55 2004 From: python at rcn.com (Raymond Hettinger) Date: 17 Apr 2004 06:17:55 -0700 Subject: Automatic, portable optimization of global access References: <5d83790c.0404150721.46a3b5d0@posting.google.com> <7xvfk17zeg.fsf@ruckus.brouhaha.com> <5d83790c.0404151803.598c1807@posting.google.com> <7xbrlseclf.fsf@ruckus.brouhaha.com> <5d83790c.0404160319.f46f2f9@posting.google.com> <7x1xmnvg7o.fsf@ruckus.brouhaha.com> Message-ID: <5d83790c.0404170517.58332895@posting.google.com> [Paul Rubin] > I'm saying your optimization is important enough that it should be run > on everything, except the rare cases where it's invalid to do so ... Thanks. You might be interested in the latest refinement. Whole modules can now be optimized by just adding two lines: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/277940 I tried it out on some standard library modules. It was easy to add and the testsuites ran flawlessly: asynchat, asyncore, calendar, csv, difflib, dis, optparse, pickle, Queue, random, sets, sre, sre_compile, sre_parse, textwrap, unittest, urllib2, urlparse, and warnings. Raymond Hettinger From jcarlson at uci.edu Thu Apr 1 19:00:46 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Thu, 01 Apr 2004 16:00:46 -0800 Subject: Travelling salesman variation in python In-Reply-To: References: Message-ID: > An approximate solution would be good enough, do you have any > suggestions about how do do that? One approximate solution to the TSP is the bitonic TSP. That is, start at the leftmost point, find a path to the rightmost point, then find a return path to the leftmost point. Search for 'optimal bitonic tsp' in google, the second entry will have pseudocode for the algorithm. I've personally converted it to Python for other uses, but I'll leave it as an exercise for you. You can convert it into your 'maximum' by changing the line: if q < b[j - 1, j] then to: if q > b[j - 1, j] then - Josiah From tjreedy at udel.edu Wed Apr 21 14:21:28 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 21 Apr 2004 14:21:28 -0400 Subject: fmod and % References: Message-ID: "Zunbeltz Izaola" wrote in message news:cthbrlllkmc.fsf at lcpxdf.wm.lc.ehu.es... > > Hi, > > I have a problem with % operation. It returns a incorrect value in > this case: > > >>> -2.77555756156e-17%1 > 1.0 > > where the returned value should be -2.77555756156e-17. Wrong. As per the docs, x % positive number is defined as being positive and <= that positive number. So above should be about 1.0 - 2.8e17, which, for 32 bit machines, is 1.0, which is exactly what you got >>> 1 - 2.8e-17 1.0. as with >>> 1 - 5.5e-17 1.0 whereas >>> 1 - 5.6e-17 0.99999999999999989 > >>> -0.32768000000000003%1 > 0.67232000000000003 And this is 1.0 - .32768 Terry J. Reedy From jonas at jonasgalvez.com Tue Apr 20 22:55:52 2004 From: jonas at jonasgalvez.com (Jonas Galvez) Date: Tue, 20 Apr 2004 23:55:52 -0300 Subject: Regex'ing null bytes Message-ID: Hi, I'm trying to parse some binary data with regexes. It works well in the latest Python build, but I need to run this on Python 1.5.2. The binary data has a pattern like this: keyName1\002..(.*)\000.*keyName2\002..(.*)\000 (I'm using regex syntax to illustrate) So I wrote the following script: def amfKey(str): return "%s\002..([^\000]*)" % str keys = re.compile(amfKey("key"), re.DOTALL).findall(amfStr) Works on 2.3.3, but produces the following error on 1.5.2: Traceback (innermost last): File "test.py", line 26, in ? keys = re.compile(amfKey("key"), re.DOTALL).findall(amfStr) File "C:\Python152\Lib\re.py", line 79, in compile code=pcre_compile(pattern, flags, groupindex) TypeError: argument 1: expected string without null bytes, string found Does anyone know a workaround? The type of binary data I'm trying to parse is AMF (Action Message Format), Macromedia's proprietary format for fast communication between the Flash Player and their "Flash Remoting" servers (ColdFusion/.NET/Java implementations). But there are opensource "Flash Remoting" implementations in PHP (amfphp.org), Perl (simonf.com/flap/) and Java (openamf.org) already - I've started to work on the Python port. And I wanted to keep this Python 1.5.2-compatible... Thanks in advance, =- Jonas Galvez jonasgalvez.com/blog macromedia.com/go/team From tjreedy at udel.edu Sun Apr 4 16:26:11 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 4 Apr 2004 16:26:11 -0400 Subject: OT (was Re: But it still doesn't explain the joke) References: <106o7vn56fgmt85@corp.supernews.com><406F3C29.6030504@freedom.place> Message-ID: "Josiah Carlson" wrote in message news:c4oiq6$1hg$1 at news.service.uci.edu... > Sure, sounds good. Glad we agree. The same issue came up a year ago when a couple of people posted about Iraq but later agreed to stop. > For someone who is advocating political truce, you sure loaded your post. Yes, I intentionally mirrored your statements to illustrate why not to continue down that road ;-) > Practice what you preach my friend. I just as intentionally quoted my examples as belief or as what 'might be said' instead of presenting them syntactically as factual statements. Terry J. Reedy From sean at sands.beach.net Mon Apr 26 17:03:55 2004 From: sean at sands.beach.net (Sean Berry) Date: Mon, 26 Apr 2004 21:03:55 GMT Subject: How to read a file from another server? Newbie Message-ID: <%Oejc.16$ph.9@fed1read07> I am trying to read in a file from another server. If I try x = open("servername:/path/to/file", "r") I get the following error: IOError: [Errno 2] No such file or directory: 'servername:/path/to/file' Sorry for the easy question, but couldn't find anything on google. -- From sean_berry at cox.net Mon Apr 12 18:18:18 2004 From: sean_berry at cox.net (Sean Berry) Date: Mon, 12 Apr 2004 15:18:18 -0700 Subject: Escaping characters in MySQLdb query References: Message-ID: I was doing something like this: for item in values: item = item.replace("'", "//'") But I am looking for something a lot nicer. Sorry about my first post date... 12 hours off. "Sean Berry" wrote in message news:AkEec.271$U83.155 at fed1read03... > I wrote a little script that is inserting thousands of records into a mysql > database. > > How do I escape characters like ' in my insert statements? > > I have something like the following (much shorter) example: > > c.execute("INSERT INTO records (var1, var2) values ('%s', '%s')" %(value1, > value2)) > > My problem is when value1 is something like "Tom's auto supply". The ' in > Tom's needs to be escaped. How can I do this? > > Thanks. > > From me at privacy.net Sat Apr 10 18:35:16 2004 From: me at privacy.net (Heather Coppersmith) Date: 10 Apr 2004 18:35:16 -0400 Subject: how to know who calls a method References: <40771b75$0$15656$626a14ce@news.free.fr> Message-ID: On Fri, 09 Apr 2004 23:54:02 +0200, Alex Garel wrote: > It is because I would like an object to be aware of another > object reading it so it can signal future change in its value to > the last. I can use a getter which precise who is the reader but > my attempt was to be able to use a normal getter (x=y) in a > Phytonic fashion ! The usual solution involves some sort of "registration" (untested and definitely needs more details and error checking, etc.): class emitter: def __init__( self ): self.collectors = [ ] self.data = None def register_for_updates( self, collector ): self.collectors.append( collector ) def set_data( self, newdata ): self.data = newdata for collector in self.collectors: collector( self, newdata ) class collector: def __init__( self, watch_this_object ): watch_this_object.register_for_updates( self.collect_updates ) def collect_updates( self, other_object, new_data ): print other_object, "just got new data:", new_data Without this sort of set up, emitter.set_data wouldn't know exactly what to do when there's new data anyway. This approach is more flexible than a fixed method invocation should you have a many-to-many emitter-to-collector relationship. There's also no reason you couldn't wrap emitter.set_data up in some sort of property so it would work as part of the getter and/or setter for some attribute (but I don't like properties: explicit is better than implicit). HTH, Heather -- Heather Coppersmith That's not right; that's not even wrong. -- Wolfgang Pauli From cm at leetspeak.org Tue Apr 13 08:47:58 2004 From: cm at leetspeak.org (Michael Walter) Date: Tue, 13 Apr 2004 14:47:58 +0200 Subject: Escaping characters in MySQLdb query In-Reply-To: References: Message-ID: Rob Williscroft wrote: > Sean Berry wrote in news:AkEec.271$U83.155 at fed1read03 in > comp.lang.python: > > >>I wrote a little script that is inserting thousands of records into a >>mysql database. >> >>How do I escape characters like ' in my insert statements? >> >>I have something like the following (much shorter) example: >> >>c.execute("INSERT INTO records (var1, var2) values ('%s', '%s')" >>%(value1, value2)) >> >>My problem is when value1 is something like "Tom's auto supply". The >>' in Tom's needs to be escaped. How can I do this? >> > > > IIUC this is (mostly) a SQL question. No, this is a do-I-know-my-library-well-enough-to-make-my-life-easy question ;) Note that both richard and me are actually passing the format string arguments as a *separate* argument to execute(). If you then have a look at the MySQLdb source code, you will see that those arguments get quoted automagically using the connections' literal_blabla method. Hence, c.execute("SELECT %s", "fooo'bar") will actually execute "SELECT 'fooo\'bar'" in the database. Cheers, Michael From __peter__ at web.de Tue Apr 20 09:10:59 2004 From: __peter__ at web.de (Peter Otten) Date: Tue, 20 Apr 2004 15:10:59 +0200 Subject: [OT] Keyboard layout, was Re: Dollar sign ($) on foriegn keyboards? (prothon) References: Message-ID: Peter Maas wrote: > Peter Otten wrote: >> In Germany every serious programmer has to switch to the American > > layout anyway because of {}[]@\~| (all odd AltGr combinations). > > Oh, I didn't know that. Fortunately I'm not a serious programmer. ;) I hate people being apodictic - even myself. But I never felt comfortable with AltGr, so it was a great relief when I learned about switching kezboard lazouts and well worth the occasional y-z glitch. By the way, I once came across a whole book that had these characters swapped. Maybe my fingers just didn't grow in the right place to press AltGr+9 simultaneously, but somehow I can't see how that makes me the member of a minority. Mit freundlichen Gr[-en :-) Peter From tkpmep at hotmail.com Thu Apr 22 10:08:23 2004 From: tkpmep at hotmail.com (Thomas Philips) Date: 22 Apr 2004 07:08:23 -0700 Subject: Deleting objects Message-ID: I'm teaching myself OOP using Michael Dawson's "Python Programming For The Absolute Beginner" and have a question about deleting objects. My game has two classes: Player and Alien, essentially identical, instances of which can shoot at each other. Player is described below class Player(object): #Class attributes for class Player n=0 #n is the number of players #Private methods for class Player def __init__(self,name): self.name = name self.strength = 100 Player.n +=1 def __del__(self): Player.n -=1 print "I guess I lost this battle" #Public methods for class Player def blast(self,enemy,energy): enemy.hit(energy) def hit(self,energy): self.strength -= energy if(self.strength <= 50): self.__del__() I instantiate one instance of each class: Hero = Player("Me") Villain = Alien("Not Me") If Hero hits Villain with Hero.blast(Villain, 100), Villain dies and executes its destructor (__del__). The game then ends. However, when I execute the program in IDLE, IT FINISHES BY EXECUTING THE DESTRUCTOR FOR BOTH HERO AND VILLAIN. How can this be? As one of the two objects was destroyed prior to the end of the game, how can it be re-destroyed when the program ends? Thomas Philips From afriere at yahoo.co.uk Tue Apr 27 22:02:04 2004 From: afriere at yahoo.co.uk (Asun Friere) Date: 27 Apr 2004 19:02:04 -0700 Subject: Is Perl *that* good? References: <108q51j4dscn7dc@corp.supernews.com> <87fzaqmm8t.fsf@strauser.com> <38ec68a6.0404262308.50029919@posting.google.com> Message-ID: <38ec68a6.0404271802.61e7a4c3@posting.google.com> Skip Montanaro wrote in message news:... > Sure, it's syntactically bound into the language. There will always be an > extra constant overhead to enable regular expressions in Python. That > doesn't make them any less powerful than the Perl variety. It's simply a > pair of different design decisions Guido and Larry made (along with a few > others). Sure. > Asun> Probably the only time I would reach for Perl rather than for > Asun> python is when I knew a task involved a lot of regex (and no > Asun> object orientation). > > Why? I write non-object-oriented Python code all the time. What I meant is that if it involves lots of regexp I'd probably use Perl If it involved lots of regex AND object orientation, I wouldn't consider Perl. > Python/Perl switch you'd still have to shift your mental gears to deal with > a different syntax, different way of getting at and using functionality that > isn't builtin, etc. Even with lots of regex fiddling to do, I think the > extra overhead of using regexes in Python would be swamped by the other > differences. It's good for the soul to shift your mental gears every now and then. From MAILsweeper at acxiom.com Tue Apr 13 13:07:01 2004 From: MAILsweeper at acxiom.com (MAILsweeper at acxiom.com) Date: Tue, 13 Apr 2004 11:07:01 -0600 (CST) Subject: Email Quarantined Due to Virus Message-ID: The Email Message: Word document, sent to: memberservices at acxiom.com contained the following virus that could not be cleaned: Scenarios/Incoming/Inbound Scan: Information 0x42060008, W32/Netsky-T The Email has been quarantined, and will not be delivered. Thank you, ********************************************************************** The information contained in this communication is confidential, is intended only for the use of the recipient named above, and may be legally privileged. If the reader of this message is not the intended recipient, you are hereby notified that any dissemination, distribution, or copying of this communication is strictly prohibited. If you have received this communication in error, please re-send this communication to the sender and delete the original message or any copy of it from your computer system. Thank You. From garry at sage.att.com Mon Apr 12 09:23:46 2004 From: garry at sage.att.com (Garry Hodgson) Date: Mon, 12 Apr 2004 13:23:46 GMT Subject: why is python better than eg. smalltalk?? no one has any solid arguments! you should all go to church with all that religious talk! In-Reply-To: References: Message-ID: <2004041209231081776226@k2.sage.att.com> aahz at pythoncraft.com (Aahz) wrote: > I found my editor fifteen years ago. Guess which it is. ed? ---- Garry Hodgson, Technology Consultant, AT&T Labs Be happy for this moment. This moment is your life. From cpl.19.ghum at spamgourmet.com Mon Apr 26 02:52:32 2004 From: cpl.19.ghum at spamgourmet.com (Harald Massa) Date: Mon, 26 Apr 2004 08:52:32 +0200 Subject: Maya API with Python? References: Message-ID: > Anybody tried that? Progress or horror stories to tell? > "Industrial Light & Magic Runs on Python" http://www.pythonology.com/success&story=ilm I am sure, they also use maya. Harald From michele.simionato at poste.it Thu Apr 1 06:52:34 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 1 Apr 2004 03:52:34 -0800 Subject: ANNOUNCE: 'goto' for Python References: Message-ID: <95aa1afa.0404010352.80de14e@posting.google.com> Richie Hindle wrote in message news:... Today is April the first ... ;) From tckanta1 at compuserve.com Mon Apr 12 06:55:53 2004 From: tckanta1 at compuserve.com (Tckanta1) Date: Mon, 12 Apr 2004 10:55:53 +0000 Subject: have any trouble with health ? we may help you... more In-Reply-To: References: Message-ID: <6FA4C0D8ABCL6HH4@compuserve.com> http://CNBDGH.BIZ/PH009/?affiliate_id=233642&campaign_id=407 From sholden at holdenweb.com Wed Apr 28 11:40:31 2004 From: sholden at holdenweb.com (Steve Holden) Date: Wed, 28 Apr 2004 11:40:31 -0400 Subject: Backticks: What up? In-Reply-To: References: Message-ID: <408FD06F.20801@holdenweb.com> Steven Brent wrote: > Thanks! I didn't know you could use printf type syntax with return.... The "return" statement allows an arbitratu expression as its target, even complex objects like sequences, classes and instances. For example: >>> def tuplify(a, b): ... return a, b ... >>> tuplify([1, 2], [3, 4]) ([1, 2], [3, 4]) >>> thing, thong = tuplify("sing", (1, 2, 3)) >>> thing 'sing' >>> thong (1, 2, 3) >>> regards Steve From python at holdenweb.com Thu Apr 8 18:05:59 2004 From: python at holdenweb.com (Steve Holden) Date: Thu, 08 Apr 2004 18:05:59 -0400 Subject: does commands.getoutput() use nice()? In-Reply-To: <2004040810261081434393@k2.sage.att.com> References: <2004040810261081434393@k2.sage.att.com> Message-ID: Garry Hodgson wrote: > a friend is trying to track down the source of a mysterious > slowdown that's happening in a webware app he's doing. > > he's got an external precompiled application that he invokes > from python using commands.getoutput(). usually it runs quickly > (1-2 secs), but sometimes it take much longer (80-90 secs). > he's instrumented the program to verify that it's the query invocation > that's spending all the time. he's run the query in a test rig outside > of python, and it seems to run normally all the time. but when run > from python, via webware, he gets this wide performance variations. > > his current hypothesis is that when python runs his command, it > "nices" it down in priority, so it's more susceptible to other load > on the machine. i searched the python source, and don't see anyplace > that appears to do this. but i thought i'd check here anyway. > > can anyone support or reject his theory? > > thanks > Define "sometimes". It may be webware session cleanup that's hitting him, or some other phenomenon that only occurs when teh server is relatively heavily loaded. regards Steve From pwatson at redlinepy.com Sat Apr 3 19:14:54 2004 From: pwatson at redlinepy.com (Paul Watson) Date: Sat, 3 Apr 2004 18:14:54 -0600 Subject: Building 2.3.3 on AIX, term.h complaint Message-ID: <406f537f$1_1@themost.net> I am trying to build Python 2.3.3 on AIX. I believe that we are using gcc 2.95.3, but later in the ./configure output, it appears to say that gcc is not being used. Does this suggest a real problem? Any suggestions? $ uname -a AIX kbs80 3 4 000C30CD4C00 unknown $ whence cc /tools/bin/cc $ ls -al /tools/bin/cc lrwxrwxrwx 1 internal tools 3 Jul 2 2001 /tools/bin/cc -> gcc $ whence gcc /tools/bin/gcc $ gcc -v Reading specs from /tools/lib/gcc-lib/powerpc-ibm-aix4.3.3.0/2.95.3/specs gcc version 2.95.3 20010315 (release) checking term.h usability... no checking term.h presence... yes configure: WARNING: term.h: present but cannot be compiled configure: WARNING: term.h: check for missing prerequisite headers? configure: WARNING: term.h: proceeding with the preprocessor's result configure: WARNING: ## ------------------------------------ ## configure: WARNING: ## Report this to bug-autoconf at gnu.org. ## configure: WARNING: ## ------------------------------------ ## checking for term.h... yes From jburgy at hotmail.com Sat Apr 3 11:41:31 2004 From: jburgy at hotmail.com (Jan Burgy) Date: 3 Apr 2004 08:41:31 -0800 Subject: Subclassing file and getting around the file.__init__ rigidity References: <807692de.0404012244.53b476dc@posting.google.com> Message-ID: <807692de.0404030841.1c660c65@posting.google.com> Hi Franz, your idea is exactly the type of stuff I was thinking of. Unfortunately it doesn't work... Does anybody see what we're doing wrong? Thanks to all Jan Burgy "F. GEIGER" wrote in message news:... > # Untested code > > class BufferedFile(file): > > def __init__(self, name): > if type(name) == file: > self.__dict__.update(file.__dict__) # Kinda cctor > else: > file.__init__(self, name) > self.buffer = None > > Cheers > Franz > > "Jan Burgy" schrieb im Newsbeitrag > news:807692de.0404012244.53b476dc at posting.google.com... > > Hi all y'all, > > > > Consider the class down below. I've implemented it just because I > > needed the pushback method. Now of course the third line in __init__ > > doesn't work and I even understand why. My question is: is there any > > way to make it work? Somebody proposed a patch for fileobject.c to > > allow stuff like fp = file(fp1.fileno()) but it looks like it's been > > rejected. I won't so bold as to request a change in Python. Should I > > try to re-write this class in C? Although I know C I'm much to lazy to > > take on the entire python API, not that it doesn't look nice. > > > > Thanks for your help > > > > Jan Burgy > > > > class BufferedFile(file): > > > > def __init__(self, name): > > if type(name) == file: > > self = name # DOESN'T WORK! > > else: > > file.__init__(self, name) > > self.buffer = None > > > > def readline(self): > > if self.buffer: > > i = self.buffer.find("\n") > > line, self.buffer = self.buffer[:i], self.buffer[:i+1] > > else: > > line = file.readline(self) > > return line > > > > def pushback(self, line): > > self.buffer = line + self.buffer From roy at panix.com Thu Apr 29 10:45:31 2004 From: roy at panix.com (Roy Smith) Date: Thu, 29 Apr 2004 10:45:31 -0400 Subject: suggestions for using tuples instead of list (or vice versa) References: Message-ID: In article , Thorsten Kampe wrote: > I found out that I am rarely using tuples and almost always lists > because of the more flexible usability of lists (methods, etc.) There was an extensive thread on this topic within the last month or two. Like many threads, it rambled and wandered a bit, but covered the topic quite well. DAGS for list or tuple in the subject, date <= 2 months, and you should find it. From paul at prescod.net Mon Apr 12 00:14:55 2004 From: paul at prescod.net (Paul Prescod) Date: Sun, 11 Apr 2004 21:14:55 -0700 Subject: Parsing In-Reply-To: <40796E95.9090207@graffiti.idv.tw> References: <40796E95.9090207@graffiti.idv.tw> Message-ID: <407A17BF.9030001@prescod.net> Timothy Wu wrote: > I'm parsing Firefox bookmarks and writing the same bookmark to another > file. To make sure I read and write utf-8 correctly I make open files > like this for read and write: > > codecs.open(file, "r", "utf-8") The virtue of this code is that now you have a file object that will parse FROM UTF-8 into Python Unicode objects. The Unicode objects neither know nor care that they came from UTF-8. Paul Prescod From beans at bedford.net Mon Apr 19 21:22:35 2004 From: beans at bedford.net (TomH) Date: 19 Apr 2004 18:22:35 -0700 Subject: Python/Win based report generator for MySQL databases References: <%zCgc.59345$oj6.9111@bignews6.bellsouth.net> Message-ID: <7135e36e.0404191722.69703df5@posting.google.com> "Robert Oschler" wrote in message news:<%zCgc.59345$oj6.9111 at bignews6.bellsouth.net>... > Has anybody seen a nice Python 2.2+ compatible based module/package, running > on a Win2k box, that makes creating reports from a MySQL database easy? > > I am both a Python programmer and MySQL programmer so it doesn't have to be > too simple, just useful. ... If Excel is available, its easy to use ADO to get a ResultSet and load it into a spreadsheet. http://support.microsoft.com/default.aspx?scid=http://support.microsoft.com:80/support/kb/articles/q246/3/35.asp&NoWebContent=1 From aahz at pythoncraft.com Mon Apr 5 00:40:18 2004 From: aahz at pythoncraft.com (Aahz) Date: 5 Apr 2004 00:40:18 -0400 Subject: Difference between default arguments and keyword arguments References: <406FFEAF.3080400@netscape.net> Message-ID: In article <406FFEAF.3080400 at netscape.net>, DoubleM wrote: > >All arguments are keyword arguments. They may or may not have a default >value. Not quite true: def foo(a, b): pass args = 1, 2 foo(*args) def bar(*args): pass bar(1, 2) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "usenet imitates usenet" --Darkhawk From ndbecker2 at verizon.net Wed Apr 21 19:51:08 2004 From: ndbecker2 at verizon.net (Neal Becker) Date: Wed, 21 Apr 2004 19:51:08 -0400 Subject: zip 2 sequences into 1 Message-ID: What's an easy/efficient way to zip together 2 (or more) sequences into a single sequence? I noticed zip builtin. This combines a_0 ... a_n b_0 ... b_n into (a_0 b_0)(a_1 b_1)... What I want is a single sequence a_0 b_0 a_1 b_1... From jacob at cd.chalmers.se Thu Apr 1 04:55:46 2004 From: jacob at cd.chalmers.se (Jacob Hallen) Date: 1 Apr 2004 09:55:46 GMT Subject: Tapestry uncovered Message-ID: A magnificent discovery was made today, as a medeival tapstry foretelling the coming of Europython this summer was uncovered. "It is amazing in its precision" says Jacob Hall?n, one of the organisers of the event. "And all the work that must have gone into it." A digitised image of the tapestry has been made. It can be viewed at http://www.europython.org/conferences/epc2004/news/Tapestry -- From jcarlson at uci.edu Sat Apr 3 16:29:43 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Sat, 03 Apr 2004 13:29:43 -0800 Subject: Indent testers needed (Prothon) In-Reply-To: <8ivbc.141601$cx5.89434@fed1read04> References: <2Msbc.136673$cx5.2385@fed1read04> <8ivbc.141601$cx5.89434@fed1read04> Message-ID: >>>>/* loop 2 */ >>>>ix = 2 >>>>for \ >>>> item \ >>>> in \ >>>> blist \ >>>> : >>>> alist[ix] = \ >>>> alist[ \ >>>> ix \ >>>> ] Certainly that is uglier, but at least there are backslashes saying "hey, something is happening here". If this were Python, it would violate the "explicit is better than implicit" zen. - Josiah From Vincent.Raaijmakers at ge.com Mon Apr 5 16:39:30 2004 From: Vincent.Raaijmakers at ge.com (Raaijmakers, Vincent (GE Infrastructure)) Date: Mon, 5 Apr 2004 15:39:30 -0500 Subject: import question Message-ID: <971323274247EB44B9A01D0A3B424C8507FF1A55@FTWMLVEM02.e2k.ad.ge.com> Question: my src path looks like this: src\root\sub1 src\root\sub2 My main code is in root, lets say main.py and there is also a lib.py. In sub1 there if foo1.py and sub2 foo2.py Sorry for the long introduction...please don't stop reading... :-( In both sub1 and sub2 there is an empty __init__.py for making them a package. Ok the problem: this works fine: main.py from sub1 import foo1 from sub1 import foo2 However, in foo1 and foo2 I have this line "import lib". So lib.py is not in the same path as foo1.py and foo2.py, it seems to find lib.py in a higher path. (Reason for this is the import from main , which has lib.py in the same path?) However, if I'm in the subfolders sub1 or sub2, and I run foo1.py or foo2.py standalone, they can't find lib.py. Yeah of course. So, how to avoid this? How can I refer back to a module higher in the "hierarchical" path. Up is so easy.. just say import foo.foo2.foo3. But up, what is the correct way of doing that? Something to put in __init__.py, like sys.path.apppend('..')? Looks ugly to me.... Or, the way how I share lib for both files is wrong, please let me know. Anyway, I need this behavior because of my unittest structure. Thanks, Vincent From dkuhlman at rexx.com Fri Apr 23 12:18:51 2004 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Fri, 23 Apr 2004 09:18:51 -0700 Subject: AOP use cases References: <84fc4588.0404140106.3fa0c55@posting.google.com> <0pydnSB4WYuieuLdRVn-hQ@powergate.ca> <4087D662.6010209@yahoo.com> Message-ID: Michael Walter wrote: > Bryan wrote: >>> >>> Those of you using XML might want to visualize the program as a >>> DOM tree and >>> AOP as applying a XSLT stylesheet. (Now visualize applying >>> several different >>> stylesheets in arbitrary order) >>> >>> >>> Daniel >>> >> >> >> thank you for this explanation... it's the best explanation i've >> heard yet and now i have a grasp and can visualize what AOP is. >> >> bryan > > That sounds like a description of (CL/Scheme-style) macros :) So, arbitrarily complex transformations on the source code with the intent of hiding the intension of the source code are good, right? I wish I could say something to satirize this. But, the post about XML/XSLT seems satirical enough. Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From tjreedy at udel.edu Fri Apr 9 13:57:26 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 9 Apr 2004 13:57:26 -0400 Subject: maximum length of a list & tuple References: Message-ID: "Lupe" wrote in message news:c55okv$2o3eql$1 at ID-202776.news.uni-berlin.de... > I just would like to know if there is any limit to a list or tuple. Theoretically no, practically yes. For computer implementations, one limit is max int (usually 2billion+). The other, which usually kicks in first, is RAM memory. If you nest v e r y deeply, you may also run into a compiler limit or stack overflow. As an experiment, I tried t=() for i in range(100000): t = (t,) # runs fine print t ... MemoryError: stack overflow Feel free to experiment on your own system. Terry J. Reedy From cpl.19.ghum at spamgourmet.com Sat Apr 10 04:31:32 2004 From: cpl.19.ghum at spamgourmet.com (Harald Massa) Date: Sat, 10 Apr 2004 10:31:32 +0200 Subject: Wrapper round x86 Assembler References: <8089854e.0404082353.7bf163a2@posting.google.com> Message-ID: > what about a wrapper to an assembler (presumably for x86 assembly !) > I just wrote some code doing binary operations which would have been > about a zillion times faster in a few lines of assembly code. import psyco psyco.full() psyco will automagically and transparently translate python to X86 assembly where it is usefull. And psyco is Open Source, so you can dig HOW Dr. Armin Rigo implemented the "insert assembler code". Probably there is allready a solution within the psyco source. Harald From webmaster at privatevoyeur.com Tue Apr 20 23:20:27 2004 From: webmaster at privatevoyeur.com (Webmaster) Date: Tue, 20 Apr 2004 23:20:27 -0400 (EDT) Subject: Your product In-Reply-To: <200404210320.i3L3JvcS086999@ferguson.internal.realitychecknetwork.com> References: <200404210320.i3L3JvcS086999@ferguson.internal.realitychecknetwork.com> Message-ID: <200404210320.i3L3KRa2087058@ferguson.internal.realitychecknetwork.com> Your mail to: webmaster at privatevoyeur.com has been rejected because it contains an illegal email attachment. It was NOT received. Rule#2 From dmq at gain.com Fri Apr 30 12:47:05 2004 From: dmq at gain.com (David MacQuigg) Date: Fri, 30 Apr 2004 09:47:05 -0700 Subject: Unification of Methods and Functions Message-ID: I'm not getting any feedback on the most important benefit in my proposed "Ideas for Python 3" thread - the unification of methods and functions. Perhaps it was buried among too many other less important changes, so in this thread I would like to focus on that issue alone. I have edited the Proposed Syntax example below to take out the changes unecessary to this discussion. I left in the change of "instance variable" syntax ( self.sound --> .sound ) because that is necessary for the unification of all method forms. ( Compare the forms of the 'show' and 'talk' methods below.) I believe these changes in syntax will make teaching OOP in Python much easier. See "Prototypes.doc" at http://ece.arizona.edu/~edatools/Python/ The first eight pages are a basic, but complete presentation of the new OOP syntax. I expect this to expand to about 30 pages with more examples and exercises. This compares to about 60 pages in Learning Python 2nd ed. If we measure complexity by the number of pages needed for a "textbook explanation" of OOP, then I believe the new syntax has some real benefits. At this point in the learning process, students already know functions, modules, and global variables. The concept of using a global variable __self__ is no surprise at all. The only thing new in a class, compared to a module, is the instance variables, and they can be explained in one paragraph. All methods look just like normal functions. There is no need to explain "static methods" or any other form of method. In fact, I use the term "function" rather than "method" to emphasize the similarity. I'm especially interested in feedback from users who are now learning or have recently learned Python. I already know these changes seem trivial to many experts. I've also heard plenty from the people who think Python is so complex that we need to start a whole new language ( www.prothon.org ). I'm looking for a middle ground. I believe it is possible to adopt what is good about Prothon, and not lose ten years of software and community development. ======= Syntax Examples ============= ## Proposed Syntax: class Cat(Feline): numCats = 0 def __init__( n = "unknown", s = "Meow" ): Feline.__init__() Cat.numCats += 1 .name = n # Set instance variables. .sound = s def show(): # Define a "static method". Feline.show() print " Cats:", Cat.numCats def talk(): print "My name is ...", .name print "I am a %s from %s" % (.genus, .home) Mammal.talk() # Call an unbound function. print __self__ ### Diagnostic check. cat1 = Cat() # Create instance. bf = cat1.talk # Make a bound function. ## Equivalent Python: class Cat(Feline): numCats = 0 def __init__(self, n = "unknown", s = "Meow" ): Feline.__init__(self) Cat.numCats += 1 self.name = n self.sound = s def show(): Feline.show() print " Cats:", Cat.numCats show = staticmethod(show) def talk(self): print "My name is ...", self.name print "I am a %s from %s" % (self.genus, self.home) Mammal.talk(self) print self cat1 = Cat() # Create instance. bf = cat1.talk # Make a bound function. ========= End of Examples ======= Thanks for your help. -- Dave From rogerb at rogerbinns.com Sat Apr 24 05:53:30 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Sat, 24 Apr 2004 02:53:30 -0700 Subject: deleting items within a for loop - mutable indices References: <4089cb21$1_2@mk-nntp-2.news.uk.tiscali.com> Message-ID: SnuSnu wrote: > are deleted first), but this is not very elegant or quick: Here is a list comprehension that makes a new list without the deletion_list items. It does have the virtue of being a one liner :-) newx=[x[i] for i in range(len(x)) if i not in deletion_list] You will need to do timings to see what method is actually the fastest. Don't forget to do so with list sizes the same as you expect to be using in your real program. Search archives for this group for 'timeit' to see examples of how to do timings. (I think that the size of the deletion_list as a proportion of the original list is what best determines the relative speeds of the various methods available). Roger From jcarlson at uci.edu Sun Apr 18 18:08:26 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Sun, 18 Apr 2004 15:08:26 -0700 Subject: module not callable - why not? In-Reply-To: <8ef9bea6.0404180823.7a3bc189@posting.google.com> References: <107dras2heahcb6@news.supernews.com> <8ef9bea6.0404122025.36efc84e@posting.google.com> <7xsmf1fxd9.fsf@ruckus.brouhaha.com> <8ef9bea6.0404180823.7a3bc189@posting.google.com> Message-ID: > Look, here is a partial list of the symptoms of the illness of using > class-and-module-based OOP: > > (a) You need metaclasses. You have special syntax for usage of > metaclasses: you need to use the __metaclass__ name tag, in specific > places. I've never used metaclasses, and don't forsee a need for them in development I'll be undertaking any time in the near (or far) future. Standard inheritance works for me and a vast majority of users out there. In various cases, PEP 318 (decorator syntax) seems to alleviate many people's needs for metaclasses and the magic behind them. > (b) Singletons become a "design pattern", since classes usually cannot > be used as instances directly. Singletons aren't nearly as prevalent as you seem to believe. Take a peek in the standard library, and you'll find a large body of good code that has chosen not to use the "singleton design pattern". Truth be told, I've used singletons before, but only once. > (c) You have to create staticmethod and/or classmethod to make a class > functional. Please express what you mean by "functional". I believe you mean... class blah: def __call__(cls): print cls __call__ = classmethod(call) blah(object) #should print "" In this situation, I believe that a pure module-level function is preferable, def blah(cls): print cls If I have misinterpreted what you mean by 'functional', please correct me. > (d) Modules can't have properties, nor are callable. Yeah, I don't see a problem with this. However, if you feel really strongly about it, with a little work, you can create a pseduo-module with everything your heart desires. Of course it'll be ugly, and pretty much a hack, but it can be done (without metaclasses). The real trick is to understand the difference between "is a" and "has a" relations. Modules /are/ namespaces. They do not have __call__ semantics because namespaces shouldn't be called. Things /inside/ namespaces should be called. Honestly, I'd like to hear an example of a language where namespaces are callable Classes /have/ namespaces. To handle the encapsulation of data and functions into a single passable object, it is convenient for them to have namespaces. The explicit requirement to give a name to the instance being implicitly passed (usually 'self'), is to remind users "hey, I'm an instance method". Note that you can call 'self' anything you want, it is merely convention, in a similar fashion to using 'cls' for classmethods. > (e) You often need to create three objects: module, class, instance, > to do the job of one single object. Hence you often see usage of the > same name for all three of them, weird as it may seem. I've seen examples of a module and class having the same name, but I believe that with the exception of singletons (which are rare in the code that I've seen), naming an instance the same as a module or class where it came from, is generally frowned upon due to the shadowing of the original module/class name. I also believe that the general consensus for future standard library modules is to name classes different from the module that contains them. > (f) Module inheritance ('import' for containment, 'from ... import' > for inheritance) differs in syntax with class inheritance ('class > A(B):') I wouldn't call import statements inheritance, I would call it loading an external module and binding the results to a name. Just because you can emulate object inheritance with modules, doesn't mean it should be done. In fact, such things are frowned upon in Python. Take for example the following import statement... from module import * The above is frowned upon by Guido and basically everyone else in the Python community because it pollutes namespace. However... class foo(goo): pass ...is perfectly acceptable. Why? Because fewer people have issues with class inheritance than with module imports. I don't know why, I just try to answer questions like "I'm importing A from B and importing B from A, why doesn't it work?" in a way they'll understand. > (g) Module functions and class methods become two distinct types of > objects. Yeah, and it allows functions to exist without being bound to a class or an instance. Ahh, now I know, you're coming from a Java background! See, in many other languages (C, C++, Lisp, Pascal, SML, Prolog, etc.), functions are not required to be bound to classes or class instances. Personally, I like the flexibility, and can be found to fill entire modules with nothing but functions. In Java, I would have to make them static methods on some object, a fairly foolish (if arbitrary) requirement. > (h) In module-level functions, you need to use the 'global' statement > to access module-level attributes. In class (instance) methods, you > use the 'self' parameter to access instance attributes. (In class' > classmethods, you use 'cls'.) (Notice that there is a big difference > between saying "class method" and "classmethod".) You don't need to use the names 'self' or 'cls' if you don't want to, they are just standard convention. It helps the programmer understand that there may be a difference in terms of functionality. You should also realize that generally, handling module-level attributes from within the module, via global, is generally frowned upon. Again, if you feel strongly about it, you are free to destroy the meaning of your application by doing something like the following... class self(object): #module-level self class foo: def goo(self): pass def bar(self): pass bar = classmethod(bar) def baz(self): pass baz = staticmethod(baz) Again, the names are different so that there is a signal to the programmer that something different may be happening with this particular object. > In prototype-based OOP, you don't have any of these problems. You can > see that the usage of modules and classes introduces a whole lot of > repeated/redundant concepts and/or inconsistencies. That's the price > you pay. It's just an unfortunate historical development that lead us > to where we are today. I don't believe that Python is going the way of prototype-based OOP any time soon (if ever). If you are so prototype-fixated (goodness, you certainly seem to be), Prothon has prototypes, and I'm sure they will be delighted to have you. - Josiah From Felix.Wiemann at gmx.net Tue Apr 13 18:53:56 2004 From: Felix.Wiemann at gmx.net (Felix Wiemann) Date: Wed, 14 Apr 2004 00:53:56 +0200 Subject: Error with trace.py Message-ID: <87brlvcwvv.fsf@news2.ososo.de> $ cat test.py print "Hello World!" if 0: print "Never executed." if 1: print "Hi." $ python test.py Hello World! Hi. $ python /usr/lib/python2.3/trace.py --count test.py Hello World! Hi. trace: Could not open '/usr/lib/python2.3/threading.cover' for writing: [Errno 13] Permission denied: '/usr/lib/python2.3/threading.cover'- skipping Traceback (most recent call last): File "/usr/lib/python2.3/trace.py", line 690, in ? main() File "/usr/lib/python2.3/trace.py", line 687, in main results.write_results(missing, summary=summary, coverdir=coverdir) File "/usr/lib/python2.3/trace.py", line 271, in write_results lnotab, count) TypeError: unpack non-sequence Why doesn't it work? By the way, after running trace.py, there is a file test.cover in the directory: $ cat test.cover 1: print "Hello World!" if 0: print "Never executed." 1: if 1: 1: print "Hi." -- http://www.ososo.de/ From davidf at sjsoft.com Fri Apr 23 02:27:22 2004 From: davidf at sjsoft.com (David Fraser) Date: Fri, 23 Apr 2004 08:27:22 +0200 Subject: Multi-threaded printing and UIErrors in Windows In-Reply-To: <10nll1-rt5.ln1@home.rogerbinns.com> References: <10nll1-rt5.ln1@home.rogerbinns.com> Message-ID: Roger Binns wrote: > My program has a random smattering of print statements > scattered throughout that are mainly a debugging aid. > They are typically things like this: > > print "entering key mode" > > The code is multithreaded, and the printing typically > happens in both the main thread and a worker thread > doing serial port IO. The problem I am experiencing > when the program is packaged up with py2exe is that > exceptions happen: > > IOError: [Errno 9] Bad file descriptor > > This can happen in either thread. Why is this > happening? It doesn't happen on Linux or Mac, > and hasn't happened when not using py2exe. > > Python 2.3, wxPython 2.4, py2exe 0.5 (and the > previous version). > > Roger > > sys.stdout is not threadsafe - try wrapping each call with a mutext and see if that fixes it... From jonas at jonasgalvez.com Wed Apr 21 13:09:28 2004 From: jonas at jonasgalvez.com (Jonas Galvez) Date: Wed, 21 Apr 2004 14:09:28 -0300 Subject: Stupid Regex Question References: Message-ID: But now I'm puzzled. What is that '?' doing, exactly? Could you point me any references? Thanks again, =- Jonas Galvez jonasgalvez.com/blog macromedia.com/go/team > > [Fredrik Lundh] > > print re.findall("(.*?)", str) > > WOW! Thanks a bunch (again). > > Hehe, I had already written the following: > > def getIndices(str, base): > indices = [] > offset = 0 > while True: > i = base.find(str, offset) > if i == -1: break > indices.append(i) > offset = i+1 > return indices > > def getContent(a, b, str): > content = [] > startIndices = getIndices(a, str) > endIndices = getIndices(b, str) > startSlice = len(a) > def add(s, e): > content.append(str[s+startSlice:e]) > map(add, startIndices, endIndices) > return content > > Ouch. > > > > > > =- > Jonas Galvez > jonasgalvez.com/blog > macromedia.com/go/team From eldiener at earthlink.net Tue Apr 27 20:30:32 2004 From: eldiener at earthlink.net (Edward Diener) Date: Wed, 28 Apr 2004 00:30:32 GMT Subject: Debugging a python module as a form's action handler Message-ID: I am using Python in a CGI web application and need to be able to debug a Python module as a form handler. Is there a way to do this so that I can step through my module while it is handling the form's data ? I couldn't find much information at all in either IDLE or PythonWin about using the IDE's for debugging, so I thought I would ask here. From grante at visi.com Fri Apr 30 22:45:15 2004 From: grante at visi.com (Grant Edwards) Date: 01 May 2004 02:45:15 GMT Subject: calling functions at the same time References: <1095ijdb5jotvf1@corp.supernews.com> Message-ID: <40930f3a$0$17260$a1866201@newsreader.visi.com> In article , Bart Nessux wrote: > I need to ping 4 hosts at exactly the same time from the same machine That simply can't be done. > (I plan to timestamp the pings) to test and measure network > conditions over different routes to different hosts. Putting > all the ping hosts in a list and looping through it is not a > fair or balanced way to do this because of the time > differences. Exactly how many packets do you think are allowed on the wire at once with Ethernet?? > I mean it to mean: at the *exact* same time... concurrently. Like runners > starting a race together. Not physically possible unless you've got 4 cpus with, 4 separate PCI buses, 4 Ethernet boards on 4 different Ethernet segments, and some very special HW/SW to keep things synchronized. -- Grant Edwards grante Yow! I'm ANN LANDERS!! I at can SHOPLIFT!! visi.com From p_s_oberoi at hotmail.com Mon Apr 26 16:50:22 2004 From: p_s_oberoi at hotmail.com (Paramjit Oberoi) Date: Mon, 26 Apr 2004 15:50:22 -0500 Subject: Is Perl *that* good? (was: How's ruby compare to it older brother python) References: <108q51j4dscn7dc@corp.supernews.com> Message-ID: >>>getting dynamic HTML pages up and running quickly. Perl is great for >>>its string-handling abilities. (On my Web pages, I actually call a >>>Perl script from PHP precisely for this reason.) I have always felt that just like Jason Orendorff's path.py module makes working with paths so incredibly convenient, a similarly well-designed regex.py might make text processing as easy in python as it is in perl. Unfortunately I don't deal enough with regexes to have the motivation to actually put this idea into practice. Maybe someone who does can take a shot at it? -param From tjreedy at udel.edu Wed Apr 21 17:42:21 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 21 Apr 2004 17:42:21 -0400 Subject: NVidia Gelato has Python binding Message-ID: >From http://film.nvidia.com/page/gelato.html : Gelato is NVIDIA's new professional image rendering software, running on top of its new Quadro FX graphics hardware. In addition to its C++ API, "A Python binding also ships with Gelato, allowing users to script input, automatically generating geometries and shading instead of explicitly specifying them in advance. " This is the only such binding mentioned. They apparently feel that Python is well enough known that no explanatory phrase is needed. TJR From nicolas.lehuen at thecrmcompany.com Thu Apr 22 04:46:43 2004 From: nicolas.lehuen at thecrmcompany.com (Nicolas Lehuen) Date: Thu, 22 Apr 2004 10:46:43 +0200 Subject: Python 2.3.3 super() behaviour References: <40863bd7$0$25528$afc38c87@news.easynet.fr> <95aa1afa.0404210729.18f6de22@posting.google.com> Message-ID: <40878673$0$25006$afc38c87@news.easynet.fr> Duh, so it was a FAQ... What's interesting in your post is the fact that super is in fact a class (not a builtin function), and that you can inherit from it to get the expected behaviour : http://groups.google.it/groups?hl=it&lr=&ie=UTF-8&threadm=95aa1afa.0402172242.17334743%40posting.google.com&rnum=1&prev=/groups%3Fhl%3Dit%26lr%3D%26ie%3DISO-8859-1%26q%3Dsimionato%2Bsuper%26btnG%3DCerca%26meta%3Dgroup%253Dcomp.lang.python Maybe this should be the default behaviour ? Regards, Nicolas "Michele Simionato" a ?crit dans le message de news:95aa1afa.0404210729.18f6de22 at posting.google.com... > "Nicolas Lehuen" wrote in message news:<40863bd7$0$25528$afc38c87 at news.easynet.fr>... > > Hi, > > > > I hope this is not a FAQ, but I have trouble understanding the behaviour of > > the super() built-in function. > > Maybe this thread on super will interest you: > > http://groups.google.it/groups?hl=it&lr=&ie=UTF-8&threadm=95aa1afa.0402172242.17334743%40posting.google.com&rnum=1&prev=/groups%3Fhl%3Dit%26lr%3D%26ie%3DISO-8859-1%26q%3Dsimionato%2Bsuper%26btnG%3DCerca%26meta%3Dgroup%253Dcomp.lang.python.* > > > Michele Simionato From rogerb at rogerbinns.com Thu Apr 29 01:30:21 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Wed, 28 Apr 2004 22:30:21 -0700 Subject: Tkinter and XML-RPC References: <0jZjc.65$pw1.70887@news.uswest.net> Message-ID: Mark Bauman wrote: > I'm new to Python (C/C++/Delphi background), and so far I'm impressed with > the language, libraries and community. Anyway, I've just started poking > around with Tkinter and I'm wondering if anyone has any tips or caveats on > incorporating an XML-RPC client and server inside a Tkinter app. I have an > application in mind that would primarily be dealing with short string > messages and the occasional jpeg, so I'm wondering about blocking and > threading issues within the confines of the GUI. I'm just starting to dig > into the detailed docs on Tkinter and the XLM-RPC library, but I thought I > would ask since I'm sure that some folks have been there, done that. The main gotcha to worry about is if you will ever need security for the XML-RPC. It is fairly easy to add password authentication. It is however very difficult to tunnel it inside SSL unless you don't care about there being one connection per request (and a TCP establishment overhead with a SSL establishment as well). I actually ended up using Paramiko, a Python implementation of SSH. Roger From amireallyfat at yahoo.com.au Fri Apr 9 23:39:43 2004 From: amireallyfat at yahoo.com.au (mr_vocab) Date: Sat, 10 Apr 2004 13:39:43 +1000 Subject: program distribution References: <4075f5bb_1@news.iprimus.com.au> Message-ID: <40776c5e$1_1@news.iprimus.com.au> hi sorry i am using windows but great thanks for your help :) "Larry Bates" wrote in message news:RoqdnaFM0KTPJevdRVn-gQ at comcast.com... > Nathan, > > You didn't mention your platform. So > I'm going to give you instructions for > Windows. > > You will need to additional programs. > > 1) py2exe - This will run your program > through a process that gathers up all you > imported modules and creates a .EXE file > and supporting .pyd and .dll files. This > can be distributed to computers that do > NOT have Python installed. > > http://starship.python.net/crew/theller/py2exe/ > > 2) Some installer. I personally like > Inno. You provide Inno with a list of > files that should be installed (both > program and data files) and it creates > one big "setup.exe" file that can be > distributed. > > http://www.jrsoftware.org/isinfo.php > > If your platform is Linux take a look at > McMillan Installer. This page seems to > be down at this time: > > http://www.mcmillan-inc.com/install1.html > > > Regards, > Larry Bates > Syscon, Inc. > > "mr_vocab" wrote in message > news:4075f5bb_1 at news.iprimus.com.au... > > Hi im new to python but have made a few applications how can i save them > > and get the to run sort of like an application > > > > thanks > > > > Nathan > > > > > > From noemail at noemail4u.com Mon Apr 26 08:03:23 2004 From: noemail at noemail4u.com (Daniel 'Dang' Griffith) Date: Mon, 26 Apr 2004 12:03:23 GMT Subject: saving interpreter source? References: Message-ID: On Wed, 21 Apr 2004 10:36:48 -0600, Garett wrote: >Hello, I would like to be able to save source typed into the interpreter >to a file. Kind of like marshal, but I would like to have the file contain >the source so I can edit it later. Something like inspect.getsource() but >for source typed into the interpreter, not imported from a module. Is this >possible? Any ideas are greatly appreciated. -Garett Look into IPython. It's "An enhanced Interactive Python shell", and includes a "save" command, where you can even specify which lines you want saved. http://ipython.scipy.org/ --dang From nuffsaid at phreaker.net Wed Apr 28 18:47:56 2004 From: nuffsaid at phreaker.net (Nuff Said) Date: Thu, 29 Apr 2004 00:47:56 +0200 Subject: Scintilla/SciTE - Python folding Message-ID: Question: Is there a way to unfold a Python class *without* unfolding all its methods etc. so that you can get a quick overview of the class? Details: I normally open a file either with 'fold.on.open=1' set in the user's options file resp. I use 'toggle all folds' from the menu to fold everything in an unfolded file. But then, when I unfold e.g. a class, everything inside the class gets unfolded, too. What I would need is something like 'unfold one level only'. Thought, that maybe the keystroke 'Ctrl-Keypad*' was meant for that, but it doesn't work that way. I am using Scintilla/SciTE 1.59 (Linux / compiled from the sources). Thanks in advance for your answers! Nuff. From michaelmossey at yahoo.com Thu Apr 8 18:13:11 2004 From: michaelmossey at yahoo.com (Michael Mossey) Date: 8 Apr 2004 15:13:11 -0700 Subject: Intermittant slow startup References: <9badaf0.0404051033.9fec2db@posting.google.com> <4071A86D.97CA6CAE@alcyone.com> <9badaf0.0404051445.5b26b945@posting.google.com> Message-ID: <9badaf0.0404081413.5cc83413@posting.google.com> Michael Hudson wrote in message news:... > michaelmossey at yahoo.com (Michael Mossey) writes: > > > Erik Max Francis wrote in message news:<4071A86D.97CA6CAE at alcyone.com>... > > > Michael Mossey wrote: > > > > > > > Runnng python 2.2 on HP-UX, I get intermittant slow startup. > > > > Sometimes python starts up in a small fraction of a second, and > > > > sometimes takes 3-5 seconds. This applies to any script I run, or > > > > just typing 'python' at the prompt. > > > > > > > > I also observed something similar on Linux. > > > > > > > > Any ideas what would cause *intermittant* slow startup? > > > > > > Caching? Is it a long time between invocations that it takes a long > > > time to start up? > > > > It is quite intermittant without much of a pattern I can see. One > > thing that is definitely true is that if I start up python several > > times in a row one right after the other, some can be slow and some > > fast. I just observed it start fast twice, then start slow. I don't > > remember if it ever does the other way around but I think it does. > > Does HP-UX have a version of strace/truss/ktrace? > > Cheers, > mwh Yes, it has strace. What do I do with that? -Mike From martin at v.loewis.de Thu Apr 8 00:56:53 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 08 Apr 2004 06:56:53 +0200 Subject: When to use PyMem_Malloc()? In-Reply-To: References: Message-ID: Jon Perez wrote: > Are there any disadvantages to using PyMem_Malloc() such that > there are times when one would prefer to use a plain malloc()? Certainly. For example, you may have source code which is used in different projects, so changing the malloc calls may not be feasible. Or, you may use API function of other libraries that require you to use malloc(), as they invoke free() themselves. Regards, Martin From adalke at mindspring.com Mon Apr 12 16:45:31 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Mon, 12 Apr 2004 20:45:31 GMT Subject: Easy question on error catching References: <407A35E8.C669206D@alcyone.com> Message-ID: Erik Max Francis: > What you wrote will work, but catching a ValueError (except ValueError: > ...) is a better solution. Especially in dynamically typed languages > like Python, it's a good idea to catch the most restrictive error you > think you need, and then expand the net if it's required. To elaborate, suppose you press control-C inside of the try block. That the signal for Python to stop what it's doing. Python converts that into an exception. If nothing catches it then the top-level reports the normal exception and traceback. If you have a bare "except:" then in addition to telling Python to ignore the ValueError when the string doesn't contain an integer, you're also telling Python to ignore control-C, out-of- memory exceptions and a few others. I've actually had something like this happen to me try: v = flaot(s) except: v = 0.0 See the misspelling? It raised a NameError which was caught by the bare except: so for every case I was setting v to 0.0. Andrew dalke at dalkescientific.com From tzot at sil-tec.gr Mon Apr 19 18:23:43 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Tue, 20 Apr 2004 01:23:43 +0300 Subject: Static Modules... References: Message-ID: On Sat, 17 Apr 2004 15:11:16 -0400, rumours say that Peter Hansen might have written: >After all, what if I had a module called, perhaps inappropriately, >"launch" and it triggered the launch of my personal anti-aircraft >missile when imported? (Yes, bad style too, but I wrote this >control code long ago before I learned good style. ;-) Now in >one of my other modules, I have a subtle bug** which involves an >object named, perhaps unsurprisingly for this example, "launch". Peter, don't worry. There ain't no such thing as a free launch. -- TZOTZIOY, I speak England very best, Ils sont fous ces Redmontains! --Harddix From jeremy at jdyallop.freeserve.co.uk Fri Apr 30 07:23:42 2004 From: jeremy at jdyallop.freeserve.co.uk (Jeremy Yallop) Date: 30 Apr 2004 11:23:42 GMT Subject: operator double() surprise in cxx References: <7ivfjh988v.fsf@enark.csis.hku.hk> Message-ID: Isaac To wrote: >>>>>> "Beno?t" == Beno?t Dejean writes: > > Beno?t> Le Thu, 29 Apr 2004 21:35:51 -0500, John Hunter a ?crit?: > >> I am using pycxx 5.2.2 to generate some extension code. I want to > >> extract some doubles from some python sequences > >> > >> When I do > >> > >> double l( Py::Float(rect[0]) ); double b( Py::Float(rect[1]) ); > > Beno?t> everything that looks/tastes/sounds like a function declaration > Beno?t> is (even with parameters. > > Is it really a bug in g++? No. > No matter how I look at > > Py::Float(rect[0]) > > it does not look like a type "Py::Float*" that is indicated by the error > message. As a declaration, it's a zero-length array of Py::Float, with a parenthesized declarator, i.e. the same as Py::Float rect[0]; As a parameter declaration, it's equivalent to Py::Float *rect; because of the way C++ handles arrays. Jeremy. From getway at pelins.com Mon Apr 26 03:54:44 2004 From: getway at pelins.com (getway at pelins.com) Date: 26 Apr 2004 09:54:44 +0200 Subject: This is an alert from eSafe Message-ID: *** This is a massege from E-Safe server in Peltours *** *** Mail-server detected a hostile content in this email. *** Time: 10:05:00 04/26/04 Scan result: Mail modified to remove malicious content Protocol: SMTP in File Name / Mail Subject: C:\Program Files\eSafe\eSafeCR\SPOOL\1082876229 Source: python-list at python.org Destination: zvika at pelins.com Details: application.zip\details.txt .pif Infected with Win32.Netsky.q (Non-Removable), Blocked From michele.simionato at poste.it Wed Apr 28 05:20:06 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 28 Apr 2004 02:20:06 -0700 Subject: prototypes in Python [was: what is good in Prothon] Message-ID: <95aa1afa.0404280120.30176ca9@posting.google.com> So far, I have not installed Prothon, nor I have experience with Io, Self or other prototype-based languages. Still, from the discussion on the mailing list, I have got the strong impression that you do not actually need to fork Python in order to implement prototypes. It seems to me that Python metaclasses + descriptors are more than powerful enough to implementing prototypes in pure Python. I wrote a module that implements part of what David MacQuigg discussed in http://apache.ece.arizona.edu/~edatools/Python/Prototypes.htm in few lines of code (disclaimer: this is an horrible hack that changes Python semantics and makes "super" and "self" kinda of implicit reserved keywords, highly unpythonic). It requires Python 2.2+. I have not read the whole David MacQuigg's document, nor I have done any serious testing of the module, nor I claim I do understand what prototypes are; also I guarantee there will be bugs and surprising behaviors, but still I think they could be fixed if I was willing to spend more time on the issue. Here is an example of usage: from prototype import Prototype # prototypes are implemented as classes class Animal(Prototype): numAnimals = 0 home = "Earth" def __init__(): # no need to pass self around Animal.numAnimals += 1 def show(): print "Animals:", self.numAnimals class Feline(Animal): genus="Feline" def __init__(name,sound): # no need to pass self around super.__init__() self.name=name self.sound=sound def talk(): # no need to pass self around print "%s talking: %s!" % (self.genus,self.sound) class Cat(Feline): # how to call the super prototype numCats = 0 def __init__ ( n = "unknown", s = "Meow" ): super.__init__(n,s) Cat.numCats += 1 def show(): super.show() print " Cats:", self.numCats def talk(): print "My name is", self.name print "I am a %s from %s" % (self.genus, self.home) super.talk() cat1 = Cat() # abuse of notation: makes a new prototype, not an instance print cat1 # => # cat2 = Cat("Garfield") cat2.home = "Tucson" print cat2 # => # cat1.talk() # => # My name is unknown # I am a Feline from Earth # Feline talking: Meow! cat2.talk()# => # My name is Garfield # I am a Feline from Tucson # Feline talking: Meow! cat2.show() # => # Animals: 2 # Cats: 2 I am not sure this does what prototype people wants, but still it is a nice example of how to abuse Python ;) Originally, I tried to use "_" for "self" and "__" for "super", but with my fonts it was difficult to distinguish between them. With a preprocessor one could replace .name -> self.name and ..name -> super.name, but I did no bother to do that. Here is the module (not at all optimized): $ cat prototype.py import sys from types import FunctionType from inspect import isfunction class methodwrapper(object): # descriptor def __init__(self,func,cls): self.__func__=func self.__cls__=cls def __get__(self,none,cls): globs=sys.modules[cls.__module__].__dict__.copy() globs["self"]=cls globs["super"]=super(self.__cls__,cls) return FunctionType( self.__func__.func_code, globs, self.__func__.func_name, self.__func__.func_defaults, self.__func__.func_closure) class _Prototype(type): # metaclass def __init__(cls,name,bases,dic): for k,v in dic.iteritems(): if isfunction(v): setattr(cls,k,methodwrapper(v,cls)) super(_Prototype,cls).__init__(name,bases,dic) def __call__(cls,*args,**kw): newcls = type("Prototype:%s" % cls.__name__,(cls,), {"__module__": cls.__module__}) newcls.__init__(*args,**kw) return newcls class Prototype(object): # mother of all prototypes __metaclass__=_Prototype def __init__(*args,**kw): pass #### END #### Michele Simionato From insert at spam.here Wed Apr 28 01:16:12 2004 From: insert at spam.here (Doug Holton) Date: Wed, 28 Apr 2004 00:16:12 -0500 Subject: Don't understand wxPython ids In-Reply-To: <408f3061$0$17258$a1866201@newsreader.visi.com> References: <408ed938$0$17263$a1866201@newsreader.visi.com> <408f3061$0$17258$a1866201@newsreader.visi.com> Message-ID: >>I can only think of one reasn why they chose to use ids in the first >>place. Assigning many objects the same id allows you to use one EVT_* >>call for those objects. But is that really a useful feature? Who knows? > > > That's about the only thing I could think of. The few > situations where I'd have wanted to do someting like that I'd > gladly put a for-loop iterating over a list of objects in > exchange for being able to use single-line of code the other > 90% of the time. Right, there a couple of special cases to think of when designing event bindings for a gui toolkit. One is where you want multiple controls to share the same event handler (like a button and a menu item that do the same thing). Another case is allowing people to change event bindings "on the fly", after a window constructor has already been called and the window set up. I proposed some changes similar to you, see this thread: http://lists.wxwidgets.org/cgi-bin/ezmlm-cgi?11:sss:23979:200311:dcgnanikkojpgmpdpmio#b but nothing came out of it. I did code up an implementation for Wax (http://wiki.wxpython.org/index.cgi/Wax ), but I don't know if it was included. From fredrik at pythonware.com Fri Apr 16 14:46:30 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 16 Apr 2004 20:46:30 +0200 Subject: Initializing Python in Optimized mode from C++ References: Message-ID: JT wrote: > When embedding Python in C++, is there anyway to initialize the > interpreter so that it runs in optimized mode, equivalent to > specifying the -O flag when running the interpreter from the command > line? here's one way to do it: putenv("PYTHONOPTIMIZE=yes"); ... initialize interpreter as usual ... From eppstein at ics.uci.edu Sat Apr 3 14:25:08 2004 From: eppstein at ics.uci.edu (David Eppstein) Date: Sat, 03 Apr 2004 11:25:08 -0800 Subject: An attempt at guessing the encoding of a (non-unicode) string References: <106thmedmq162ce@news.supernews.com> Message-ID: In article <106thmedmq162ce at news.supernews.com>, "John Roth" wrote: > "David Eppstein" wrote in message > news:eppstein-8C467F.14490702042004 at news.service.uci.edu... > > I've been getting decent results by a much simpler approach: > > count the number of characters for which the encoding produces a symbol > > c for which c.isalpha() or c.isspace(), subtract a large penalty if > > using the encoding leads to UnicodeDecodeError, and take the encoding > > with the largest count. > > Shouldn't that be isalphanum()? Or does your data not have > very many numbers? It's only important if your text has many code positions which produce a digit in one encoding and not in another, and which are hard to disambiguate using isalpha() alone. I haven't encountered that situation. -- David Eppstein http://www.ics.uci.edu/~eppstein/ Univ. of California, Irvine, School of Information & Computer Science From python at quixs.com Thu Apr 29 13:57:40 2004 From: python at quixs.com (Lars Heuer) Date: Thu, 29 Apr 2004 19:57:40 +0200 Subject: uuid generator In-Reply-To: <4090830B.8010903@attglobal.net> References: <71djc.147368$Kc3.4878757@twister2.libero.it> <408DE4F3.7080804@magma-da.com> <4090830B.8010903@attglobal.net> Message-ID: <1186734003.20040429195740@quixs.com> Hi Marcello, > Maybe there is already the library in Python 2.3 I believe the OSAFoundation has something like an UUID generator for Python in C. http://osafoundation.org/ I'm afraid you've to download Chandler to get it. HTH, Lars From jepler at unpythonic.net Fri Apr 16 12:44:39 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Fri, 16 Apr 2004 11:44:39 -0500 Subject: a little math problem In-Reply-To: References: Message-ID: <20040416164439.GD26865@unpythonic.net> math.fmod might help Jeff From L.Leszczynski at aster.pl Sat Apr 24 07:26:51 2004 From: L.Leszczynski at aster.pl (Leszek Leszczynski) Date: Sat, 24 Apr 2004 13:26:51 +0200 Subject: Plone for Version Control Message-ID: Hello, is it possible to add version control capabilities to Plone? regards, LL From roy at panix.com Sat Apr 10 23:05:29 2004 From: roy at panix.com (Roy Smith) Date: Sat, 10 Apr 2004 23:05:29 -0400 Subject: why is python better than eg. smalltalk?? no one has any solid arguments! you should all go to church with all that religious talk! References: Message-ID: aahz at pythoncraft.com (Aahz) wrote: > I found my editor fifteen years ago. Guess which it is. My guess is emacs, in which case I've got 6 or 7 years on you :-) > (The point being that there are only two editors still in regular use > that were available fifteen years ago -- and those two editors are > still ubiquitous now. Doesn't matter much which you pick, they'll > still be available fifteen years in the future.) I suspect you're right, but I don't necessarily think that's a good thing. Both emacs and vi have had long runs, but it's logical to assume that better things will come along. I know it's possible to handle both news and email inside emacs, but I use dedicated GUI apps for both of those tasks. I still use emacs for programming, but there's some really good IDE's out there, and my guess is they will become more and more the norm. And while I curse and wail about how bad MS Word is, I also realize that troff just isn't happening any more (I did plenty of cursing and wailing about troff back in the "good old days"). From michele.simionato at poste.it Thu Apr 22 10:19:13 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 22 Apr 2004 07:19:13 -0700 Subject: AOP use cases References: <84fc4588.0404140106.3fa0c55@posting.google.com> <0pydnSB4WYuieuLdRVn-hQ@powergate.ca> Message-ID: <95aa1afa.0404220619.7128cc8b@posting.google.com> Peter Hansen wrote in message news:... > Could > you please provide an example from your own uses which demonstrates > the effectiveness of AOP versus "not AOP" in the same way that the > synchronization example posted earlier is clearly better when done > as a wrapper than with the code duplicated everywhere (i.e. with > the "concerns" not separated)? > > -Peter I think Jacek made a beautiful post, or maybe he just summarized the way I see AOP: nothing really different for "regular" programming, just another way to help separation of concerns. Since you (Peter) always ask for examples, here is a little script I posted few days ago on the mailing list, which solves the issue of separating the concern of checking the arguments of a constructor from the definition of the constructor. ==== quoting from a previous post of mine ===== class _WithConstructorChecked(type): # helper metaclass def __call__(cls, *args, **kw): assert len(args)<=2, "%s called with more than 2 args" % cls assert kw.has_key("kw"), "%s needs a 'kw=' argument" % cls return super(_WithConstructorChecked,cls).__call__(*args,**kw) class WithConstructorChecked(object): # mixin class __metaclass__ = _WithConstructorChecked class C(WithConstructorChecked): def __init__(self, *args, **kw): pass c=C(1,2,kw=3) # ok; try different signatures to get assertion errors In this example the mixin class WithConstructorChecked ensures that C is called with at least two positional arguments and a keyword argument named 'kw'. The code of class C is not touched at all, you just add WithConstructorChecked to the list of its bases. === end quote === I tend to avoid the usage of AOP techniques in my production code, since I feel them too magical and most of the time I can do what I want in "regular" Python. Personally, I hate the hype about AOP, but I do like the concept. Michele Simionato From sly_raymond at charter.net Sun Apr 25 23:56:20 2004 From: sly_raymond at charter.net (slyraymond) Date: Sun, 25 Apr 2004 22:56:20 -0500 Subject: Trouble Understanding O'Reilly Example Message-ID: <108p21f7asq1cc8@corp.supernews.com> On page 214 of _Learning Python_, the following function is described as one that will return the smallest item in a group of arguments: def min1(*args): res = args[0] for arg in args[1:]: if arg < args: res = arg return res However, when the function called with... print min1(3,4,1,2) ...it returns: 2 Why? From fredrik at pythonware.com Mon Apr 19 11:01:49 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 19 Apr 2004 17:01:49 +0200 Subject: equivalent to Java's toString()? References: <4083E52A.3030207@mediapulse.com> Message-ID: Gabriel Cooper wrote: > What is the python equivalent to java's toString()? > > When debugging I want to be able to basically be able to do this: > > print MyObjectInstance > > or > print str(MyObjectInstance) > > and have it print out formatted output along the lines of: > > Object properties: Red=0 Yellow=0 Blue=255 add __repr__ and/or __str__ methods to your class: http://docs.python.org/ref/customization.html From Mike at DeleteThis.Geary.com Tue Apr 27 04:10:04 2004 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Tue, 27 Apr 2004 01:10:04 -0700 Subject: Is Perl *that* good? References: <108qcobc4m8g972@corp.supernews.com> Message-ID: <108s5ato02jnrf9@corp.supernews.com> Paul Prescod wrote: > And I think Python has a claim to the first Web robot: > > http://www.webhistory.org/www.lists/www-talk.1993q1/0060.html That's a fascinating little bit of history, especially this: "I have written a robot that does this, except it doesn't check for valid SGML -- it just tries to map out the entire web. I believe I found roughly 50 or 60 different sites..." -Mike From fnord at u.washington.edu Mon Apr 26 13:56:39 2004 From: fnord at u.washington.edu (Lonnie Princehouse) Date: 26 Apr 2004 10:56:39 -0700 Subject: [OT] Plone References: <6ukic.84257$cd.5573763@phobos.telenet-ops.be> Message-ID: Zope has some very powerful features (ZODB, CMF, etc.), but its documentation - particularly from the developer viewpoint - is INSANELY FRUSTRATING. After writing a few simple products, I've found that it's often easier for simple applications to take a from-the-ground-up approach with twisted.web. "flupke" wrote in message news:<6ukic.84257$cd.5573763 at phobos.telenet-ops.be>... > Hi, > > i've read some user comments on Zope. As was to be expected some say > it's cool, others says it's difficult and not easy to debug. > I would use Plone as CMS for our intranet which will also be a platform > for our tools. Does plone make it even more difficult to get going or does > it > hide some of the difficulties of Zope? > I'm kind of in a dillema here, the more i read about Python, the more i like > it. As it seems mod_python/FCGI is a good combo to bring Python power > to the web but since they want a CMS and i don't have time to write one > from the ground up, i'm thinking of using Plone. > I have my doubts about Zope especially from the viewpoint > of administration. I will have to maitain the systems where it runs on also. > > Any comments? > flupke From samschul at pacbell.net Thu Apr 22 12:28:26 2004 From: samschul at pacbell.net (Samuel Schulenburg) Date: 22 Apr 2004 09:28:26 -0700 Subject: using a USB HID device References: <40827ce3.1151345337@news.xs4all.nl> Message-ID: wouter at voti.nl (Wouter van Ooijen (www.voti.nl)) wrote in message news:<40827ce3.1151345337 at news.xs4all.nl>... > I want to use Python to interface with an USB HID device (not a > keyboard or mouse, just something that uses the HID driver to avoid > the need for a specific driver). Is this possible in pure Python on > Windows, or even better, in a portable way? > > Wouter van Ooijen > > -- ------------------------------------ > http://www.voti.nl > PICmicro chips, programmers, consulting I have been trying different approches to accessing mass storage flash memory cards via the SCSIPASSTHROUGH layer under windows. I was able to issue the reduced instruction scsi command set with a windows DeviceIoControl() call. The main problem is finding information on how Microsoft merged the usb mass storage interface to the scsi routines. Sam Schulenburg From theller at python.net Fri Apr 16 13:34:55 2004 From: theller at python.net (Thomas Heller) Date: Fri, 16 Apr 2004 19:34:55 +0200 Subject: Passing a parameter to filter References: Message-ID: <4qrjaksg.fsf@python.net> "Fredrik Lundh" writes: > filter(lambda x: f(x, 3), range(20)) > > [x for x in range(20) if f(x, 3)] > > > > (this reply will be followed by 20 replies pointing you to 150-line scripts > that lets you do what you want by a combination of metaclasses, byte- > code rewriting, and iterators...) In your list you forgot the additional 20 replies talking about currying (and the replies to them that currying is something different) Thomas From amleczko at icpnet.pl Sun Apr 4 09:57:50 2004 From: amleczko at icpnet.pl (Andrzej Mleczko) Date: Sun, 4 Apr 2004 15:57:50 +0200 Subject: Creating Zope product Message-ID: I'm trying to create a new Plone Folderish Product which will add an event into itself after adding that product. From peter at engcorp.com Mon Apr 12 18:49:57 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 12 Apr 2004 18:49:57 -0400 Subject: How to kill a SocketServer? In-Reply-To: <20040412231840.630157e5.jules@REMOVETHIS.op59.net> References: <86GdndxCWrGil-bdRVn-gw@powergate.ca> <20040412231840.630157e5.jules@REMOVETHIS.op59.net> Message-ID: Julian Smith wrote: > Peter Hansen wrote: >>Jean-Pierre Bergamin wrote: >>>The accept() call still won't get interrupted. :-( >>You have three choices. >> [snip] > > I have a class that can be constructed from a socket and looks like a file > object, but whose blocking read() method can be interrupted by a different > thread. The read() method uses poll() to block on both the real underlying > file descriptor and an internal file descriptor created using os.pipe(). > > It works on OpenBSD and Cygwin, but I haven't tried it on anything else yet. > I'm a relative newcomer to Python, so I'm sure there are some subleties that > I've missed. > > See http://www.op59.net/cancelable.py if you're interested. Looks interesting. I guess I should have qualified my answer by saying something like "platform-specific code might allow for other solutions". :-) I'm pretty sure cancelable.py's solution wouldn't work on Windows (but if I'm wrong, then of course: "amongst our choices are separate process, non-blocking socket, connection from another thread, and cancelable.py, and of course an almost fanatical devotion to the Pope...") ;-) -Peter From andymac at bullseye.apana.org.au Fri Apr 9 19:22:48 2004 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Sat, 10 Apr 2004 09:22:48 +1000 (EST) Subject: CGI Problems With Xitami In-Reply-To: <8089854e.0404090633.7c8541ea@posting.google.com> References: <8089854e.0404072356.7f33f440@posting.google.com> <8089854e.0404090633.7c8541ea@posting.google.com> Message-ID: <20040410092005.J23153@bullseye.apana.org.au> On Sat, 9 Apr 2004, Fuzzyman wrote: > Andrew MacIntyre wrote in message news:... > > Are you using "python -u" when invoking your CGI script? Unbuffered I/O > > saves lots of headaches with CGI, especially on Windows. > > Hmmm... I'm not, I'll try it. > I might have fun working out how with Xitami.... and then with > whatever server we have at work :-) I vaguely recall that Xitami might honour the "#!" convention, so try heading your scripts with #!python -u -- 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 db3l at fitlinxx.com Tue Apr 6 15:40:08 2004 From: db3l at fitlinxx.com (David Bolen) Date: 06 Apr 2004 15:40:08 -0400 Subject: Filemon-ish behavior by Python? References: <5face74a.0403291936.4b1c2442@posting.google.com> Message-ID: google at chrislevis.com (Chris) writes: > I like filemon, but I'd like it better if I could run it at the > command line, and have the option of piping the output all over the > place. Does anyone out there know of an existing utility that can do > this, or, barring that, can you point me to a good place to start on > making such a tool using Python? I'm not sure what I would have to > hook into to watch these operations on the disk. Given the level of "guts" that filemon is doing to hook into filesystem access, and if you really want to use Python, I'd probably suggest an approach where you continued to use the sysinternals filemon device drivers (vxd/sys), and just replaced their GUI with your own Python code. You can get the source to filemon from the sysinternals site (or at least you could the last time I downloaded it), and see how it works. The key is dynamically loading and unloading the VXD, and then issuing IOCtls to it to retrieve information. My bet is you could handle that part of the interface with ctypes, although you'll have to work a bit to match up the precise IOCtl structures used by the driver. If you're not totally dead set on Python but just want better control over the output (and if you've got MSVC), you might even consider just modifying their GUI application to do what you want. -- David From piet at cs.uu.nl Sun Apr 4 11:43:48 2004 From: piet at cs.uu.nl (Piet van Oostrum) Date: 04 Apr 2004 17:43:48 +0200 Subject: Working with bytes. References: <406EE606.4000604@yahoo.com> <406f33b6$0$30963$3a628fcd@reader1.nntp.hccnet.nl> Message-ID: >>>>> anton at vredegoor.doge.nl (Anton Vredegoor) (AV) wrote: AV> "Adam T. Gautier" wrote: >> I came up with a solution using the binascii module's hexlify method. AV> That is the most obvious method, I think. However, the code below AV> stores 7 bits per byte and still remains ascii-compliant (the AV> binascii.hexlify method stores 4 bits per byte). .... AV> sample output: AV> ?????????????????????????????????????????????? Which includes quite a few NON-ASCII characters. So what is ASCII-compliant about it? You can't store 7 bits per byte and still be ASCII-compliant. At least if you don't want to include control characters. -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP] Private email: P.van.Oostrum at hccnet.nl From gabriel.cooper at mediapulse.com Wed Apr 14 13:02:15 2004 From: gabriel.cooper at mediapulse.com (Gabriel Cooper) Date: Wed, 14 Apr 2004 13:02:15 -0400 Subject: Difficulty Finding Python Developers In-Reply-To: <65cbc3dd.0404140641.3501fde8@posting.google.com> References: <65cbc3dd.0404140641.3501fde8@posting.google.com> Message-ID: <407D6E97.2080700@mediapulse.com> Paul Morrow wrote: >We've worked hard to convince our company to migrate our core >applications to Python, and now we're looking for a Python developer >in Atlanta to handle a short-term (approx. 3 month) project. But our >initial searches have been fairly unsuccessful. We haven't actually >posted a job on Monster, but we have been talking with various >headhunters in our area and they don't have many resumes that show >Python experience. An so now, of course, mgt is wondering whether >selecting Python was a mistake. > >As anyone had a similar experience? Suggestions? > > The company I work for has an interesting hiring technique. They anticipate and expect that the applicant knows little or nothing of Python and as such they interview the person for personality, compatibility, etc. first. If he seems competent then we hand him a project and boot him out. He has 10 days to complete the project. At the end of 10 days the applicant comes back for a second interview where he basically discusses what he was able to accomplish regarding the project and where he ran into trouble, etc. In our case, the project is a website (we're a website development company that does its work in python). We set up a server with a frontend and hand them the specification document. We give them data but it's up to them to normalize it (if they choose to do so) and put it into the database we give them access to. The project has to be done using python exclusively, of course, and is a great way to make sure your applicants aren't the type that "interview well." Also, you will be able to see exactly how these people code. Is it spaghetti code? Is it clean? Do they use debug vars? Log information for testing? etc. In my opinion it is a very accurate measure of an applicant's capabilities. In this case it makes it ///beneficial/// when the applicant has no python experience. We have tried this method for two separate rounds of hiring and both times have resulted in us hiring someone different than we would have if we had had only the initial interview to go on. It proves that the people we hire are smart, interested in learning, capable of learning, capable of *adapting*. Hope this helps. Gabriel. -------------- next part -------------- An HTML attachment was scrubbed... URL: From mir4uu at yahoo.com Tue Apr 20 09:05:18 2004 From: mir4uu at yahoo.com (mir nazim) Date: 20 Apr 2004 06:05:18 -0700 Subject: report generators Message-ID: <425cc8d1.0404200505.4bce8dc2@posting.google.com> hi, i wanted 2 know if there is any report generator for python/linux that produces reports in variety of formats e.g html/images/jpeg/png etc. i know about report lab but output is pdf. pdf is ok for printing but u need a pdf viewer for viewing it. there should be some thing that cen viewed from directly from application e.g gtkhtml for gtk, khtml for kde etc. From cs993442 at cs.yorku.ca Thu Apr 29 13:03:43 2004 From: cs993442 at cs.yorku.ca (Daniel Orner) Date: Thu, 29 Apr 2004 13:03:43 -0400 Subject: Cross-Language Encryption: Python/Java Message-ID: <4091356F.9060901@cs.yorku.ca> Hello, I'm working on a project that consists of a Java application on the desktop, and a server with Python CGI code. I'm trying to find an encryption algorithm, which would let me send encrypted information to the server, to work identically in both Python and Java. (I.e. which would let me encrypt data in Java, send it to the Python server, and decrypt it there.) For various reasons, I don't want to use the built-in Java encryption suite. I've found implementations of Rijndael/AES for both Java and Python, but the behavior is not identical (the strings that are produced are different). I tried porting the Python rotormodule.c to Java, but my C skills are not quite on the expert level, and I got bogged down trying to figure out which C types corresponded to Java types (and its behavior when casting and not casting, etc.). Does anyone have a good idea about what my options might be here? Truthfully I don't know a whole lot about encryption algorithms, so if you can point me to something I can adapt without having to understand all the niggling details, that would really be great. Thanks very much for your time and attention, --Daniel Orner From nuffsaid at phreaker.net Fri Apr 30 20:55:20 2004 From: nuffsaid at phreaker.net (Nuff Said) Date: Sat, 01 May 2004 02:55:20 +0200 Subject: IDE for Python References: Message-ID: On Fri, 30 Apr 2004 14:17:32 -0700, dont bother wrote: > Is there any good IDE for Python. I checked on > www.python.org and found some. Installed bluefish but > to my surprise its just an editor. I guess it cannot > even compile my code in python or maybe I am wrong. Why an IDE? Python is - IMO - (one of) THE languages, where a good editor (tabs2spaces, comment blocks, select encoding, syntax highlighting, auto-indentation, scriptable ...) is all you really need. (Bluefish ain't the editor of your choice here; write your own from scrap or write one using Scintilla; resp. use SciTE with a good customization file; or go for (X)Emacs resp. Vim.) HTH, Nuff. From mogmios at mlug.missouri.edu Mon Apr 26 22:52:28 2004 From: mogmios at mlug.missouri.edu (Michael) Date: Mon, 26 Apr 2004 19:52:28 -0700 Subject: Is Perl *that* good? In-Reply-To: References: <108q51j4dscn7dc@corp.supernews.com> Message-ID: <408DCAEC.4080701@mlug.missouri.edu> >In theory, the web routine for phonetic searches might have been >implemented in PHP. The trouble with that is that I would have to >maintain both a PHP and a Perl version of the same routine. I find it >much easier to just copy and paste the whole mess (at present about 120 >lines) between the encoding and the decoding routines in Perl, and run >an exec("perl norphon.pl $name") from PHP. > I've wondered if there is really a reason why a single language processor couldn't be made that Perl, Python, PHP, etc could all be compiled into. Not necesarily a byte code system like Java but just a shared language processing core. Then the various languages could directly work with libraries written in the other languages. How much does the syntax actually effect the abilities of the language? How much should it effect the abilities of the language? From aku at europe.com Thu Apr 8 06:09:35 2004 From: aku at europe.com (aku) Date: 08 Apr 2004 10:09:35 GMT Subject: why is python better than eg. smalltalk?? no one has any solid arguments! you should all go to church with all that religious talk! References: <20031028061245.12451.00000133@mb-m01.aol.com> <4074f954$0$5802$79c14f64@nan-newsreader-02.noos.net> Message-ID: <407524df$0$5066$4d4ebb8e@news.nl.uu.net> On 2004-04-08, francois lepoutre wrote: > > http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&oe=UTF-8&selm=3A2DD2CA.14A5D7E2%40engcorp.com&prev=/groups%3Fq%3Dpython%2520%2522van%2520rossum%2522%2520esperanto%26hl%3Den%26lr%3D%26ie%3DUTF-8%26oe%3DUTF-8%26sa%3DN%26tab%3Dwg The article talks about Esperanto and says: "Still widely spoken in that country" This is humor people. there's as many people speaking Esperanto here as that are walking on the moon right now. aku From dontbotherworld at yahoo.com Fri Apr 30 17:17:32 2004 From: dontbotherworld at yahoo.com (dont bother) Date: Fri, 30 Apr 2004 14:17:32 -0700 (PDT) Subject: IDE for Python Message-ID: <20040430211732.38504.qmail@web60802.mail.yahoo.com> Hi Guys: Is there any good IDE for Python. I checked on www.python.org and found some. Installed bluefish but to my surprise its just an editor. I guess it cannot even compile my code in python or maybe I am wrong. Any ideas/recommendations for a free IDE for Python Thanks Dont __________________________________ Do you Yahoo!? Win a $20,000 Career Makeover at Yahoo! HotJobs http://hotjobs.sweepstakes.yahoo.com/careermakeover From hugh-m at moving-picture.com Fri Apr 16 06:13:16 2004 From: hugh-m at moving-picture.com (Hugh Macdonald) Date: Fri, 16 Apr 2004 11:13:16 +0100 Subject: CamelCase versus wide_names (Prothon) In-Reply-To: <87wu4gjkwb.fsf@blakie.riol> References: <87hdvl2dny.fsf@blakie.riol> <87d6692ar8.fsf@blakie.riol> <87wu4gjkwb.fsf@blakie.riol> Message-ID: <20040416111316.6f086ad8.hugh-m@moving-picture.com> On Fri, 16 Apr 2004 12:07:48 +0200 Wilk wrote: > Why not - instead of _ ? > > def my-function() > > it doesn't need shift on azerty and qwerty isn'it ? > > and we already use it in natural langage... So what happens in the following code: data = 23 my = 2 my-data = 56 value = 3 new-value = my-data-value Or would it insist on: new-value = my-data - value or new-value = my - data - value I think having a character available for names that is also used elsewhere as an operator is a VeryBadThing(TM) (or should that be veryBadThing or very_bad_thing?).... -- Hugh Macdonald The Moving Picture Company From nobody at dizum.com Mon Apr 5 15:50:07 2004 From: nobody at dizum.com (Nomen Nescio) Date: Mon, 5 Apr 2004 21:50:07 +0200 (CEST) Subject: slightly OT: BUT NEEDs to be said References: Message-ID: <8b42d1998c978c8c1cddf15c52a1c57b@dizum.com> In article , Peter Hansen wrote: > Some people despise snakes, and are terrified of them. Everyone loves cute cuddly snakes and no one in their right mind is afraid of them. They don't carry any political baggage or meaning. > > Nor, perhaps, should you bring politics into your arguments, at least > not if you want to maintain credibility with a largely technical crowd. I think politics are introduced when the author uses MPFC as the basis. > So clearly you haven't used it even enough to get past this concern > about indentation, which generally goes away after only a few days > or perhaps weeks of use. That hurts your credibility as well... Ok. Well the indentation thing which is largely irrelivant... > If you've managed to read this far, which I doubt, then I want you > to know that you might actually have a point. At least about the > Monty Python references not being a particular _strength_ in > promoting Python. Sorry if I was ranting but here is some more rant: People have very real reason to fear MPFC: Highly educated/wealthy family background/private school/Oxford/Cambridge people jumping about and acting 'zany' and coming up with all sorts of useless sketches designed to appeal strictly to the liberal-elite is a fairly repulsive artistic concept especially if you do not find the style of MPFC even remotely amusing. Unfortunately this formula (hiring these sorts of people) was to become the bed rock of BBC alternative comedy for years to come (Ben Elton, Steven Fry etc etc) and remember people in the UK did not have the choice about this crap as it came out of their licence fee (that is another subject) So anyway I don't see quite those sorts of concepts woven into PHP, Perl,C,C++, Java or anything else....although there may well be similar things but *well* hidden as they should be If someone came up with a KKK language it might be attractive for members of the KKK but would generally be consideredly highly unacceptable and would attract much criticism. If someone came up with a language/interpreter based on their favourite TV show like I dunno 'Friends' or whatever it would be seen as ridiculous. If I came up with a scripting language called 'Ben Elton' then that would have extreme political overtones and just invoke all Ben Eltons extreme left wing radicalism. At the least MPFC is divisive (you either find it funny or you don't) Surely the uptake and use of a particular language (to solve a particular niche or set of problems) is at least in part due to the perceived politcal and artist *neutrality* of that language. If the author and contributors to Python wish to only encourage Python use on the basis that the end user has great admiration of MPFC (as amusingly hinted at by one of the other authors in this thread) you should perhaps restrict access to python.org and related sites and authenticate on that basis and call it a private members club.... Cuddly cartoon characters like the Snake, or various BSD creatures = highly acceptable and good. MPFC = too aristically/politically/socially 'loaded' to be acceptable. Please drag the Python and python.org image out of the stuffy past and in line with similar projects regards From fma at doe.carleton.ca Thu Apr 1 17:21:07 2004 From: fma at doe.carleton.ca (Fred Ma) Date: 1 Apr 2004 22:21:07 GMT Subject: Python from the command line (was: Choosing Perl/Python for my particular niche) References: <40652B0D.7C313F77@doe.carleton.ca> <4069F1FD.601C9079@doe.carleton.ca> <106n8kj2t5n7m11@corp.supernews.com> <406BB6C4.7F3ADD4@doe.carleton.ca> Message-ID: <406C95CD.F42B3D9@doe.carleton.ca> Cameron Laird wrote: > > >I've put in a request to my sysadmin to install python. The > >way to get hooked on it is to start small, with mundane tasks > >(same as with any new shell, I suppose). If it doesn't get > >installed due to lack of priority, I can always get it > >bundled with my next cygwin update. Cygwin is an absolute > >blessing. Everything comes prebuilt (lots of stuff) and > >you have superuser priveleges, as well as simultaneous > >access to Windows. Just as long as your HDD isn't FAT > >(that prevents chmod from working). > > Oh! Apparently Win* is the platform of interest; that > hadn't occurred to me. > > There's a LOT to say specifically on the topic of Python- > for-Windows-system-administration. You might want to > start with Mark Hammond's book. > > I'm no great fan of CYGWIN for my own use, although I > certainly recognize it's been historically important. > It occurs to me that perhaps we haven't made adequately > clear how easy it is to install native Python on Windows. > It should take less time doing it than talking about do- > ing it. I'm not arguing with your approach; I just want > to ensure we've been clear about the alternatives. Actually, didn't mean to cause a great deal of confusion here, but solaris is the main platform. But I access solaris boxes from a PC. And since I have a mapped network drive, I can use PC tools to work on my unix files. I agree, installing stuff on windows is easy. My comment about cygwin is that it's even easier than easy. I just have to check off the Python box. That gives me opportunity to try it for small things. By no means am I comparing cygwin to other unix environments for the PC. I enjoy it out of convenience. Most of my stuff is on the solaris, and cygwin gives me a nice posix shell without leaving the windows environment. Fred -- Fred Ma Dept. of Electronics, Carleton University 1125 Colonel By Drive, Ottawa, Ontario Canada, K1S 5B6 From RobMEmmons at cs.com Sun Apr 11 06:43:38 2004 From: RobMEmmons at cs.com (Robert M. Emmons) Date: Sun, 11 Apr 2004 05:43:38 -0500 Subject: what relationship between this mail list and the python group on Google? In-Reply-To: References: Message-ID: <4079215A.3010606@cs.com> > what relationship between this mail list and the python group on Google? > i saw the same info on both Just some background. USENET or Network News is the second oldest discussion forum group around. It's been around since the 1980's or maybe 1970's. The Python forum is part of that. Incidently, the first discussion forum network was "mailing lists". Often Newsgroups and mailing lists are gatewayed to one another to provide both types of access. Some other posters said this is true for the Python forum -- I don't know either way. Because Usenet discussions are so important in terms of information content and reference material people started to archive these. One was Dejanews (spelling?) which mirrored USENET so people could search archives a decade or more old. Google a few years ago took over this archiving and searching function which is nice. I use google group searchs quite frequently. Goggle also offers submittale and other news reading features also. The point I want to make is that USENET is a unique forum system based on collaboration among many many internet sites that put up and agreed to share news groups among themselves and Google is just one participant in this that provides some very nice user features. This is different from other forums you see on say Yahoo, AOL/Compuserve, and the like. Usenet is community based and not owned by any one group where the others are commerical. It also tends to have more technical content too. These are some of the reasons I prefer usenet. Rob From peter at engcorp.com Thu Apr 15 05:37:09 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 15 Apr 2004 05:37:09 -0400 Subject: Very Interesting Project for Python Person In-Reply-To: <854e9e55.0404141138.416c9ab1@posting.google.com> References: <854e9e55.0404141138.416c9ab1@posting.google.com> Message-ID: Zanke wrote: > This is part of an open source project at SourceForge. The Python > program would have to call some methods that were compiled from C > source code. > > We need someone to add 2D graphics & GUI to an existing C program. The > main program, graphics, & GUI would be python/tKinter. The graphics > would show the path of a virtual sailboat, which has a robot at the > helm. The robot is actually an Artificial Neural Network (ANN). We use > neuroevolution to discover a competent ANN yachtsman. > > Visit http://annevolve.sourceforge.net to learn more; especially the > sourceforge link. Your first post made it through to the list/newsgroup already. From harry.g.george at boeing.com Fri Apr 2 11:49:37 2004 From: harry.g.george at boeing.com (Harry George) Date: Fri, 2 Apr 2004 16:49:37 GMT Subject: ftpmirror.py in reverse? References: Message-ID: Carl Banks writes: > Harry George wrote: > > I maintain a website on a local machine, and want to maintain a clone > > of it on a www-visible remote machine via ftp. I.e., local to remote. > > > > Going remote to local, ftpmirror.py would (I understand) do the job. > > > > Is there some tool available (or even a parameter for ftpmirror.py) > > which can do local-->remote? > > > I've written such a script. > > http://www.aerojockey.com/software/#ftpupsync > > It's public domain, use at your own risk, n' at. It probably doesn't > work on Windows, but wouldn't be hard to modify it to. Sorry, no > documentation. I really should document it, tie up loose ends and > package it. > > Sorry about the tabs^H^H^H^H Unicode indent characters. > > > -- > CARL BANKS http://www.aerojockey.com/software > "If you believe in yourself, drink your school, stay on drugs, and > don't do milk, you can get work." > -- Parody of Mr. T from a Robert Smigel Cartoon Excellent; looks just right. I'll give it a try. -- harry.g.george at boeing.com 6-6M21 BCA CompArch Design Engineering Phone: (425) 342-0007 From claird at lairds.com Mon Apr 26 13:24:28 2004 From: claird at lairds.com (Cameron Laird) Date: Mon, 26 Apr 2004 17:24:28 -0000 Subject: Is Perl *that* good? (was: How's ruby compare to it older bro References: <108qcobc4m8g972@corp.supernews.com> Message-ID: <108qhecd7a4kt35@corp.supernews.com> In article , Roy Smith wrote: . . . >trying new things too. 5 years ago, Pythonistas (was the term even >invented then?) were crazy rebels. Today, they're the fashionable avant . . . Gordon McMillan, 1998 My first guess was almost exactly a year earlier. -- Cameron Laird Business: http://www.Phaseit.net From fumanchu at amor.org Thu Apr 22 01:31:01 2004 From: fumanchu at amor.org (Robert Brewer) Date: Wed, 21 Apr 2004 22:31:01 -0700 Subject: Cell objects and their values Message-ID: Jeff Epler wrote: > This seems to work, but it's undocumented (specifically, > func_closure as > an argument to new.function is undocumented) and makes my tummy feel > funny when I think about it. > > >>> import new > >>> def cell_get(cell): > ... def f(): return cell > ... return new.function(f.func_code, {}, "f", (), (cell,))() > ... Rock. On. That is frickin' brilliant in at least three ways I never would have thought of. :) Thanks! Looking back over Raymond's bytecode hack in PEP 329, I notice he also used func_closure as an arg to function(). In addition, he avoided importing the "new" module by just calling type(f)(). Danke. Robert Brewer MIS Amor Ministries fumanchu at amor.org From fabio.trezziCANCELLAMI at email.it Tue Apr 20 09:23:21 2004 From: fabio.trezziCANCELLAMI at email.it (Wezzy) Date: Tue, 20 Apr 2004 15:23:21 +0200 Subject: emacs for OS X References: Message-ID: <1gcjrc7.1s60i39g5q0kiN%fabio.trezziCANCELLAMI@email.it> Tuxtrax wrote: > Hi all > > My editor of choice on linux for python, bar none, is xemacs. I love the > python mode that detects a python file and handles indentation and > coloration for me automagically. > > I have been using a powerbook for a while now, and I finally found emacs > for aqua in OS X Jaguar (10.2.8). I downloaded it from porkrind.com. The > version of emacs is 21.3 I believe. Anyway, not only does it *not* > detect python files automatically, but it tries to use fundamental mode > to handle them which is a pain in the ass. I want my coloring and > indentation back, damn it all! > > I found python-mode.el in the python distribution folder, but not only > do I have no clue as to what to do with it, I can't find an emacs folder > or a .emac file. Just the emac program. Any help with this would be > greatly appreciated. If you have overcome this yourself I especially > want to hear from you. > > In other news..... > I use Emacs with Panther but i think that the situation is the same. Download python-mode from python.org: http://www.python.org/emacs/python-mode/python-mode.el Compile the file Move both file where emacs can find them Open Terminal The .emacs file is into your home folder (tipically /Users/) so when you open terminal you are already in the right place add the following lines to your .emacs file : (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) (global-font-lock-mode t) (setq font-lock-maximum-decoration t) (i've found this code in www.python.org) Now when you try to open a .py file emacs loads python-mode Hope this helps -- Ciao Fabio From sean_berry at cox.net Thu Apr 22 04:00:34 2004 From: sean_berry at cox.net (Sean Berry) Date: Thu, 22 Apr 2004 01:00:34 -0700 Subject: Python use large scale projects References: <47fc6058.0404212327.24163290@posting.google.com> Message-ID: I am in the process of writing a new store software in python. So far, about 8000 lines of code. Fairly large project, not completly in python. Uses some C as well. "David Fraser" wrote in message news:c67tdn$smf$1 at ctb-nnrp2.saix.net... > limor wrote: > > Hi, > > I am considering using Python in a new testing tool application we > > intend to build for out product. > > I must get references before starting develope in this language , > > since although lots of good things are said about this language , I > > still have my doubts how can it compete with languages like C++ and > > Java. > > I have found te sytax and some features if the language not as > > problematic in maintenance prospective (although I keep reading the > > contrary everywhere I read somthing about python) . For people who are > > used to write in C and C++ I think the python being typless makes the > > code hard to maintain. > On the contrary, I found coming from a C/C++ background that the dynamic > typing was an advantage. > > But still, In many prespective the language seems to really suit my > > needs and I would really like to talk with people who are using Python > > in their company to medium-large scale project. > > > > I'd really like to talk with someone who is using this language in his > > work for large scale projects. > > 10x allot for whoe ever reply me on that. > > With Regards, > > limor. > > We use Python for a few projects that are about 10000 lines of code. > Note however that this would probably be 40000 lines in C++. > The compact simplicity of Python has made this code much easier to manage... > > David From jepler at unpythonic.net Thu Apr 1 15:55:42 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Thu, 1 Apr 2004 14:55:42 -0600 Subject: Travelling salesman variation in python In-Reply-To: References: Message-ID: <20040401205541.GE20484@unpythonic.net> Can't TSP be converted to your problem? If you have TSP with distance(Xi, Xj)=Dij, then convert it to your problem by letting distance(X'i, X'j)=distance(X'j, X'i)=-Dij. or if only positive weights are allowed then use max(D)-Dij. Jeff From jcarlson at uci.edu Wed Apr 21 00:13:29 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Tue, 20 Apr 2004 21:13:29 -0700 Subject: how to calculate correctly the cluster size In-Reply-To: References: Message-ID: > These are all FAT32 partitions. Don't know how to, if possible, > change clusters on my XP laptop using NTFS. > > While I used Partition Magic to do the partitioning, the sizes > are the smallest cluster size possible in the partition size. One reason > I have so many partitions: The Windows 2k "Disk Administrator" software for 2K always uses 4k cluster sizes by default. I believe your varied cluster sizes are the result of using Partition Magic to create them. > It took forever to defrag a 300GB (two partitions) firewire > drive under NTFS (this drive is used with my XP laptop for miniDV > captures and editing). I actually had to double the memory of my laptop > (now 768 MB) before the defrag could run to completion. There exists an algorithm for defragmenting a drive that only needs to read and write the entire drive twice (I wrote one for a database defragmenter), and there likely exists one that reads and writes even less. If you have a 150 gig drive (and it is filled), your computer will need to read and write a around 600 gigs (read, write, each twice, 150 gigs). Even if your drive is fast, like say 30 megs/second (probably on the high-end for defragmenting), 600,000/30/3600 ~ 5.5 hours. In reality, you're probably getting closer to 5-15 megs/second during a defragment, which would give you 11-33 hours to defrag each of your 150 gig partitions. It's the whole capacity vs bandwidth issue on hard drives, which is similar to the bandwidth vs latency issue with RAM. Ahh, technology. - Josiah From __peter__ at web.de Thu Apr 29 12:32:12 2004 From: __peter__ at web.de (Peter Otten) Date: Thu, 29 Apr 2004 18:32:12 +0200 Subject: Generic constructors and duplication of internal Python logic References: <87ekqq41ya.fsf@pobox.com> <8dad5312.0404280217.21c2cfd1@posting.google.com> <95aa1afa.0404280619.778bd323@posting.google.com> Message-ID: Michele Simionato wrote: > sdementen at hotmail.com (Sebastien de Menten) wrote in message > news:<8dad5312.0404280217.21c2cfd1 at posting.google.com>... >> Here is a metaclass for uber-lazy user :-) >> >> Concretely, at the creation of the class it takes the source of the >> __init__ function and add, at the first line of __init__, the line >> that sets the attributes : >> > self.foo, self.bar, self.baz, self.optional1, self.optional2 = >> > foo, bar, baz, optional1, optional2 >> > > Unfortunately this approach does not work if the source is not available > (this happens when you are in the interpreter, or when you only have a > .pyc file). I was playing this kind of tricks some time ago, then I > decided that it was best to switch to Lisp/Scheme for this kind of stuff > ;) Here's a variant that operates on the byte code: import opcode class List(list): def ensure(self, value): try: return self.index(value) except ValueError: self.append(value) return len(self)-1 class Recorder(object): def __init__(self, code): self.func_code = code self._code = map(ord, code.co_code)[:-4] self._names = List(code.co_names) def __getattr__(self, name): opc = opcode.opmap[name.upper()] def record(self, arg=None): # XXX limit name resolution/addition to the proper opcodes if isinstance(arg, str): arg = self._names.ensure(arg) self._code.append(opc) if arg is not None: self._code.append(arg & 0xff) self._code.append(arg >> 8) setattr(self.__class__, name, record) return getattr(self, name) def code(self): return ''.join(map(chr, self._code)) def names(self): return tuple(self._names) def autoinit(f): co = f.func_code r = Recorder(co) for i in range(1, co.co_argcount): r.load_fast(i) r.load_fast(0) # self r.store_attr(co.co_varnames[i]) r.load_const(0) # None r.return_value() new_names = r.names() new_code = r.code() codeobj = type(co)(co.co_argcount, co.co_nlocals, co.co_stacksize, co.co_flags, new_code, co.co_consts, new_names, co.co_varnames, co.co_filename, co.co_name, co.co_firstlineno, co.co_lnotab, co.co_freevars, co.co_cellvars) return type(f)(codeobj, f.func_globals, f.func_name, f.func_defaults, f.func_closure) class AutoInit(type): def __new__(cls, classname, bases, classdict): classdict["__init__"] = autoinit(classdict["__init__"]) return type.__new__(cls, classname, bases, classdict) class Demo(object): __metaclass__ = AutoInit def __init__(self, baz, top, foo=3, r=None): if r is None: r = ["default"] foo *= 2 baz *= 3 helper = 42 #ignored def __str__(self): return ("Demo(baz=%(baz)r, top=%(top)r, foo=%(foo)r, r=%(r)r)" % self.__dict__) if __name__ == "__main__": print Demo(1, 2) print Demo(10, 20, 30, r=["other"]) print Demo(100, foo="other", top=200) I guess that was just a complicated way to fail the sanity check :) Peter From adeleinandjeremy at yahoo.com Tue Apr 6 15:22:20 2004 From: adeleinandjeremy at yahoo.com (Adelein and Jeremy) Date: Tue, 6 Apr 2004 12:22:20 -0700 (PDT) Subject: slightly OT: BUT NEEDs to be said Message-ID: <20040406192220.75664.qmail@web40811.mail.yahoo.com> Even if the original poster of this thread isn't serious, it brings to mind a real concern I have. RMS initiated the design of a free operating system - RMS wanted to name it humorously, so RMS named *his* idea GNU. Along comes Joe Netboy saying that GNU isn't marketable because it's mispronounced, inserious, and has the wrong philosophy behind it. Guido was the originator of the programming language we call Python - Guido liked Monty Python, so he named *his* language Python. Along comes Joe Netboy saying that Python is unmarketable due to political (??!??) concerns would be a good name if only it were in reference to something else other than what it is. There are other examples which paint a disturbing trend (because even if these are usually trollings, you know some people out there believe what is said), but on with my point.... Well, AFAIK, neither of these projects were started in order to sell the most copies. And, also AFAIK, both may be taken, repackaged, RENAMED (look at how this was done with GNU when it magically became Linux), and even sold by anyone anywhere to anyone else anywhere. So if there exist people who really care about the mascot (??!???!!) of a programming language, they are free to repackage this one with a new name and even some changes in documentation and source code to eliminate all references to Monty Python. Problem solved - *if* there really is such a concern and this whole post is not just the random trolling of a bored individual. Well, that was my two cents - it's easy to ignore this kind of thing, but I really think that attitudes like this tend to evolve into real threats to the goals of projects that were never intended to be commercial at the cost of all else - not that Python (or GNU, for that matter) wasn't intended to be commercial. - Jeremy __________________________________ Do you Yahoo!? Yahoo! Small Business $15K Web Design Giveaway http://promotions.yahoo.com/design_giveaway/ From dolzenko at rsu.ru Wed Apr 14 02:58:31 2004 From: dolzenko at rsu.ru (Eugeni Doljenko) Date: Wed, 14 Apr 2004 10:58:31 +0400 Subject: How to determine from which module function or class come? Message-ID: <407CE117.4000301@rsu.ru> I was confused when some plotting libraries (matplotlib, PyQwt) imported whole Numeric in current namespace. (Numeric redefine cos(), sin() and other math functions to operate properly on arrays). When I type "print cos()" it prints happily i know about UFuncs in numarray and Numeric and so i've found that these functions come from Numeric, or numarray. But I want something like this: >>> which some_function some_module.some_sub_module.some_function >>> which some_class some_module1.some_sub_module1.some_class i.e. something that shows from which module function or class come. Obscurely I suspect it's impossible in general, is it so or not? Sorry for my newbee question and stupid English :) From max at alcyone.com Thu Apr 22 21:28:37 2004 From: max at alcyone.com (Erik Max Francis) Date: Thu, 22 Apr 2004 18:28:37 -0700 Subject: Why we will use obj$func() often References: <84Uhc.22278$dZ1.5087@fed1read04> <8AWhc.23114$dZ1.11070@fed1read04> <40883BFE.B381518A@alcyone.com> <27_hc.23801$dZ1.2716@fed1read04> Message-ID: <40887145.789A2FE8@alcyone.com> Mark Hahn wrote: > Well, I do tend to exaggerate a bit. I can understand it when I study > it, > but in everyday coding it does not roll off my fingers. Also, it is > possible to design something new without understanding the old. It is _possible_. But it is not a very good idea. > I am serious when I say I think that Python has headed off into > egghead land > a bit and I feel that keeps a lot of people from switching to it. I > think > that this heady stuff scares them off. I really am trying to make > things > simpler in Prothon. Now, whether I can succeed or not is another > question. > Only time will tell. Other than the basic premise of Prothon, every single decision I've seen you make (or consider) looks wholly stylistic, awkward or even arcane, and the opposite of the one I, or I think Guido, would have chosen. Being a fan of Io, I think prototype-languages are interesting. Even so far, I lost interest in looking at the actual main feature of Prothon, after seeing all the extra baggage that was brought on in unecessary stylistic changes. Seriously considering every single possible proposal is not constructive. Without a strong sense of what the language should look like, Prothon is going to continue to look more and more like Perl. It's already most of the way there. -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis \__/ I love Mickey Mouse more than any woman I've ever known. -- Walt Disney From greg at cosc.canterbury.ac.nz Wed Apr 28 02:14:09 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Wed, 28 Apr 2004 18:14:09 +1200 Subject: Why we will use obj$func() often In-Reply-To: References: <84Uhc.22278$dZ1.5087@fed1read04> <8AWhc.23114$dZ1.11070@fed1read04> <40883BFE.B381518A@alcyone.com> <27_hc.23801$dZ1.2716@fed1read04> <40887145.789A2FE8@alcyone.com> <7cki80hj976bia36lhf9er97v073o1pqvm@4ax.com> Message-ID: Mark Hahn wrote: > What do you mean by keyword? Which do you mean? > > 1) outer x # x is declared to come from outer scope > > 2) outer.x # outer is prefix replacing & > > Form 1 is very non-P*thonic. I was happy to get rid of the global keyword > and I'd hate to see this one show up. I was thinking of it as a direct replacement for &, so that instead of &x = y + &z you'd write outer x = y + outer z But if you don't like the look of that, there's nothing more to be said. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From altis at semi-retired.com Tue Apr 13 13:00:44 2004 From: altis at semi-retired.com (Kevin Altis) Date: Tue, 13 Apr 2004 10:00:44 -0700 Subject: Announce: PythonCard 0.7.3.1 Message-ID: PythonCard is a GUI construction kit for building cross-platform desktop applications on Windows, Mac OS X, and Linux. Release 0.7.3.1 includes over 40 sample applications and tools to help users build applications in Python, including codeEditor, findfiles, and resourceEditor (layout editor). A list of changes since release 0.7.2 is at the end of this message. This is the last planned "prototype" release of PythonCard. We've started cleaning up the framework code and finalizing the API for a 1.0 release sometime in early summer. There will be at least two more releases before then, so if you would like to get involved in the PythonCard project, now is a great time to join the mailing list. All the information you need about PythonCard can be found on the project web page at: http://pythoncard.sourceforge.net/ The installation instructions and walkthroughs are available on the main documentation page: http://pythoncard.sourceforge.net/documentation.html You can download the latest release at: http://sourceforge.net/project/showfiles.php?group_id=19015 For a list of most of the samples that have been built with PythonCard and screenshots of them in action go to: http://pythoncard.sourceforge.net/samples/samples.html The kind people at SourceForge host the project: http://sourceforge.net/projects/pythoncard/ If you want to get involved the main contact point is the Mailing list: http://lists.sourceforge.net/lists/listinfo/pythoncard-users PythonCard requires Python 2.2.1 or later and wxPython 2.4.1.2 or later. Additional Notes: Remember to backup or just delete your old PythonCardPrototype directory before installing a new version, so that the old files aren't still in the package directory. If you installed a previous version of PythonCard on Windows using the binary installer, then you should be able to remove the old package via the Add/Remove Programs Control Panel. The distutils installer will put the framework, components, docs, samples, and tools in Lib\site-packages or your Python directory (typically C:\Python22 or C:\Python23). Of course, on Linux and Mac OS X that path will be slightly different and have forward slashes. Windows users should get a PythonCard menu in the Start->Programs menu with links to the documentation, samples, codeEditor, findfiles, and resourceEditor. The tools and most of the samples will now keep their config and data file info in the "pythoncard_config" directory created by the framework. On Unix, the directory will be ~/pythoncard_config. On Windows, the directory varies as described in the following post: http://aspn.activestate.com/ASPN/Mail/Message/PythonCard/1496793 So, if you run a PythonCard app with any of the runtime tools and select "Save Configuration" from the "Debug" menu, the window positions and sizes of your runtime windows (Shell, Message Watcher, etc.) will be saved in "pythoncard_config/pythoncard_config.txt" not the PythonCardPrototype directory. Likewise, when you change the text style used by the codeEditor via the "Styles..." menu item under the "Format" menu, the modification will be saved in "pythoncard_config/stc-styles.rc.cfg" ka --- Kevin Altis altis at semi-retired.com http://altis.pycs.net/ Release 0.7.3.1 2004-04-09 added _getId back to widget.py menu.py workaround for FindMenuItem and GTK exception updated MANIFEST.in and setup.py for PyPI/distutils added testevents sample for debugging cross-platform event order Release 0.7.3 2004-04-03 changed py2exe scripts for version 0.5 syntax dropped support of PyCrust in wxPython 2.4.0.7 and earlier added check to avoid unneeded widget initialization added TextArea workaround for GetValue on the Mac McPC and RanchBiz added to moreapplications.html added lowercase skip alias for Skip to dispatch.py switched to mixedCase style names for BitmapCanvas added new-style class properties to Background and CustomDialog classes: position, size, etc. added leading underscore to addEventListener and notifyEventListeners methods changed _getAttributeNames to use inspect module updated Windows installation docs for Python 2.3 and wxPython 2.4.2.4 added explicit Stop() for timers when app is closed added donations.html fixed default Mac menubar handling converted legacy class name comparisons to __class__.__name__ removed RightTextField component, use TextField with 'alignment':'right' attribute instead many modifications to support wxPython 2.5 and higher in general, just look for code starting with if wx.wxVERSION > (2, 5): to see the version specific changes also modified spacers for sizers to use tuples instead of separate w, h args some items are marked with a "wxPython 2.5 change" comment all changes are being done so that release 0.7.3 will work with wxPython 2.4.x or wxPython 2.5.x or higher future releases may drop support for wxPython 2.4.x EXIF.py updated to remove Python 2.3 warnings added support for Python 2.3 .chm file on Windows From roy at panix.com Thu Apr 1 21:00:40 2004 From: roy at panix.com (Roy Smith) Date: Thu, 01 Apr 2004 21:00:40 -0500 Subject: Timeline plots with Python References: Message-ID: In article , "Andy Salnikov" wrote: > Hi all, > > does anybody knows any plotting library which can do nice timeline plots? > Python is preffered, but not strictly necessary. Standalone utility might > also be OK if one can feed some data from a script into it. Check out gnuplot. From me at privacy.net Wed Apr 28 12:22:39 2004 From: me at privacy.net (Duncan Booth) Date: 28 Apr 2004 16:22:39 GMT Subject: Path ... where is my application's home dir? References: Message-ID: Tim Golden wrote in news:mailman.81.1083164606.25742.python-list at python.org: >>And yes, the best place to store this information would be in >>the user's >>home dir, but then: Where is it? How to find it under Windows - every >>version of windows changes the place for home dirs. It would >>be nice to >>have something like this in a system/version independet way: >> >>sys.users_home_dir >> >>Is there anything like it in Python? > > There's nothing that strictly does that. You could > use os.path.expanduser ("~") but in Windows (at least > on my Win2K box) it returns "c:/" which is just about > acceptable for a one-user machine, but obviously not > for multi-user. > > The usual way to do this on Windows is to use the > winshell functions from pywin32: > > > from win32com.shell import shell, shellcon > print shell.SHGetPathFromIDList ( > shell.SHGetSpecialFolderLocation (0, shellcon.CSIDL_APPDATA) > ) > > > which, on my machine, gives: > > C:\Documents and Settings\goldent\Application Data A simpler way to get the same information: import os print os.environ['APPDATA'] From mwh at python.net Fri Apr 23 06:31:33 2004 From: mwh at python.net (Michael Hudson) Date: Fri, 23 Apr 2004 10:31:33 GMT Subject: python web programming / CMS References: <0kVhc.54316$eB7.29255@newssvr25.news.prodigy.com> <9YWhc.82882$%l7.5377160@phobos.telenet-ops.be> Message-ID: "flupke" writes: > I know that with OpenCMS, i could make html pages with jsp > code inside. Is that also possible in Plone/Zope? I mean having plone > process pages with embedded Python through modpython or Spyce? Er. I'm not sure that really makes sense. > Or is plone going to send the pages to Zope? Or that :-) > That's a part that's not yet clear for me. You can certainly do dynamic content with Zope/Plone, using Page Templates and TAL and Scripts (Python) and so on (indeed, quite a large portion of Plone is a collection of Page Templates and Python scripts). It's probably possible to use Plone and Spyce at the same time, but I can't see why you'd want to. Cheers, mwh PS: Page Templates rule. -- I think if we have the choice, I'd rather we didn't explicitly put flaws in the reST syntax for the sole purpose of not insulting the almighty. -- /will on the doc-sig From http Sun Apr 4 16:25:41 2004 From: http (Paul Rubin) Date: 04 Apr 2004 13:25:41 -0700 Subject: Siginificant figures calculating zprob References: <9405c70f.0404031852.155d17d5@posting.google.com> Message-ID: <7xu0zz4hiy.fsf@ruckus.brouhaha.com> sarah_wang23 at hotmail.com (Sarah Wang) writes: > But the problem is that the function calculates the result > with only a few significant figures. If I want to get the > 20th number of the result(z-prob) what should I do? I want > to get the confidence level of "6sigma" and all I get at the > moment is "1". 6 sigma is a marketing term. The number you want is on the order of 10**-9, so it describes something almost never seen in real life. http://en.wikipedia.org/wiki/Six_Sigma > I remember that Python's long type has unlimited number of > significant figures as long as the memory allows. What about > floating point numbers? That's for integers only. Some math libraries have a function called "erfc" (complementary error function) which does what you want. You can evaluate it to arbitrary precision in a system like Mathematica. I think the number you want is 0.5*erfc(6/sqrt(2)) which according to the Emacs calculator "calc" is 9.86587644935e-10. From NAVMSE-EXCHSERVER1 at Scanbech.com Mon Apr 12 20:18:11 2004 From: NAVMSE-EXCHSERVER1 at Scanbech.com (NAV for Microsoft Exchange-EXCHSERVER1) Date: Tue, 13 Apr 2004 02:18:11 +0200 Subject: Norton AntiVirus detected a virus in a message you sent. The inf ected attachment was deleted. Message-ID: Recipient of the infected attachment: Marie Petersen\Inbox Subject of the message: Re: Improved document One or more attachments were deleted Attachment improved_document4.pif was Deleted for the following reasons: Virus W32.Netsky.T at mm was found. -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/ms-tnef Size: 1823 bytes Desc: not available URL: From sjf at autograf.pl Tue Apr 27 07:49:37 2004 From: sjf at autograf.pl (..:: sjf ::..) Date: Tue, 27 Apr 2004 13:49:37 +0200 Subject: Regular Expressions References: Message-ID: pewnego dnia niejaki Diez B. Roggisch deetsNOSPAM at web.de wstuka? by? ;-) >> A - TYPE1: any_text
>> B - TYPE2: any_text_2
>> C - TYPE2: any_text_3
>> w - any_text_15
>>
>> html code >> >> I need to have only following data: >> (B, any_text_2) >> (C, any_text_3) >> that is, these data TYPE2 in which. > you should utilize the htmlparser class to extract the text first. Then > this regular expression might help: > r"(.) TYPE. : (.*)" Thanks. And now, let's assume that I have a following strings: S1 = "B - TYPE2: any_text_2 TYPE3: any_text_23" S2 = "C - TYPE2: any_text_3" and I want to have one regular expression that produce only following data: ("B", "any_text_2") ("C", "any_text_3") that is, any characters starting TYPE3 till end will be omitted. How do make this? -- .:: sjf ::.. "Linux is like Wigwam. No gates, no windows... Apache inside ;-)" From newsgroups at jhrothjr.com Sat Apr 10 15:03:19 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 10 Apr 2004 15:03:19 -0400 Subject: Static Data? References: <2FTdc.56817$Id.5813@news-binary.blueyonder.co.uk> Message-ID: <107gh8pf4qlc6c9@news.supernews.com> "Stevie_mac" wrote in message news:2FTdc.56817$Id.5813 at news-binary.blueyonder.co.uk... > I need to have a static class data member like c (see semi pseudo-like code below). How can I achieve this? You want an updatable class member. There are two ways of doing this. 1) Reference the class directly: class MyObject: _id = 0 def __init__(self): MyObject._id += 1 self.ID = _id 2) use a class method: class MyObject(object): _id = 0 def nextID(klas): klas._id += 1 return klas._id nextID = classmethod(nextID) def __init__(self): self.ID = self.nextID() Method 1 works in all releases of Python. Method 2 requires release 2.2 or later. HTH John Roth From flupke at nonexistingdomain.com Fri Apr 23 07:22:14 2004 From: flupke at nonexistingdomain.com (flupke) Date: Fri, 23 Apr 2004 11:22:14 GMT Subject: python web programming / CMS References: <0kVhc.54316$eB7.29255@newssvr25.news.prodigy.com> <9YWhc.82882$%l7.5377160@phobos.telenet-ops.be> Message-ID: "Michael Hudson" schreef in bericht news:m3fzavnfy3.fsf at pc150.maths.bris.ac.uk... > You can certainly do dynamic content with Zope/Plone, using Page > Templates and TAL and Scripts (Python) and so on (indeed, quite a > large portion of Plone is a collection of Page Templates and Python > scripts). It's probably possible to use Plone and Spyce at the same > time, but I can't see why you'd want to. The reason why i would want to use Plone and Spyce is that Spyce provides an easy way to include/embed python code in a html file like one would do with a jsp page. I don't think that Plone supports something like that or at least not that nice but i could be wrong. flupke From jbperez808 at yahoo.com Sat Apr 10 01:09:52 2004 From: jbperez808 at yahoo.com (Jon Perez) Date: Sat, 10 Apr 2004 13:09:52 +0800 Subject: Indent testers needed (Prothon) In-Reply-To: <60dfb6f6.0404091317.4875c203@posting.google.com> References: <60dfb6f6.0404091317.4875c203@posting.google.com> Message-ID: Carl Banks wrote: > Jon Perez wrote in message news:... > >>Jacek Generowicz wrote: >> >> >>>>Perhaps the pro-spaces people can explain how they deal >>>>with it. >>> >>>Emacs >> >>Asking people to stop switch away from their favorite editors > > > He wasn't doing that, bub. My point is that it is a flippant answer that really doesn't help. The pro-tabs people have their reasons for not liking all spaces, and telling them that Emacs is how some of us are able to live with all spaces achieves nothing. I'm sure there Emacs users who still can't get used to all-spaces as well as pro-spaces people who don't need to use Emacs to prefer them (like me). I am pro all spaces, and the reason I can't stand tabs is the fact that tab width settings are not the same across different source code and that leads to code that's doesn't display properly with cat (if it doesn't use 8 space tabs) or with my default editor settings (I have to keep switching as there's no such thing as autodetect tabwidth). If the pro-tabs people explained to me how they deal with this, then maybe I wouldn't so anti-tabs. The converse applies to them - I'd like to hear what it is about all spaces that's giving them grief and maybe I can tell them how I deal with it (in a non editor-specific way as much as possible). It may not convince everyone on either side to switch religion, but the hope is that it would make dealing with source code that uses the opposite convention more palatable. From Bill.Scherer at VerizonWireless.com Thu Apr 15 11:26:57 2004 From: Bill.Scherer at VerizonWireless.com (Bill Scherer) Date: Thu, 15 Apr 2004 11:26:57 -0400 Subject: Python 2.3 on RedHat 9 Message-ID: <407EA9C1.2090400@VerizonWireless.com> Stephen Ng wrote: > Hi! > > Has anyone installed Python 2.3 on RedHat 9? Yes. > Did you install on top of Python 2.2 or did you install in a separate > directory (eg the default)? 2.3 prefix is /usr/local, RedHat's installed python prefix is /usr > I'm trying to find out in advance if it's hassle free to install as I > am planning to do it. It's no hassle having them side by side, for me anyway. > > > Thanks. > > Stephen Ng HTH, Bill From newsgroups at jhrothjr.com Sat Apr 10 10:13:24 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 10 Apr 2004 10:13:24 -0400 Subject: automatically generating file dependency information frompython tools References: Message-ID: <107g088n81i0gc8@news.supernews.com> "Moosebumps" wrote in message news:vnHdc.50052$rz3.17101 at newssvr25.news.prodigy.com... > > > > In answer to the question you /almost/ asked: > > > > http://www.google.com/search?q=python+make+replacement > > > > That is definitely of interest to me, but I would want to go one step > further and automatically generate the dependency info. I haven't looked > specifically at these make replacements, but I would assume you have to use > a makefile or specify dependency info in some form like a text file. What I > am looking for is a way to automatically generate it from the source code of > the individual tools that the make program will run, or by running the tools > in some special mode where they just spit out which files they will > read/write. SCons is what you want, then. It's got a scanner built in that can be subclassed to scan anything to pull out dependency information on the fly. Converting a build monstrosity to SCons isn't exactly simple, but it's a lot simpler than any of the alternatives I can think of. John Roth > > MB > > From donn at u.washington.edu Mon Apr 26 13:45:11 2004 From: donn at u.washington.edu (Donn Cave) Date: Mon, 26 Apr 2004 10:45:11 -0700 Subject: Why we will use obj$func() often References: <84Uhc.22278$dZ1.5087@fed1read04> <8AWhc.23114$dZ1.11070@fed1read04> <40883BFE.B381518A@alcyone.com> <27_hc.23801$dZ1.2716@fed1read04> <40887145.789A2FE8@alcyone.com> <7cki80hj976bia36lhf9er97v073o1pqvm@4ax.com> <1082783076.585831@yasure> Message-ID: In article , "Mike C. Fletcher" wrote: ... > How about: > > .this (surrounding scope, often an object) > ..this (surrounding scope + 1, such as a module or a nested-class' > parent Now this sounds like runtime namespace lookup. Consider def g(): print .x def f(): x = 5 g() That prints 5, right? Not, I suppose, but that's how object "scope" works. Nested function scope is at least to some extent inherently lexical, the way we normally expect it to work - you're referring to outer code blocks, not just any caller's namespace. > Seems elegant in a certain way. The construct is reminiscent of > directory specifiers, and meshes nicely with the attribute access > syntax. Gets a little unwieldy if you're having hugely nested > constructs, but then that's already unwieldy, so more pain too them :) . I still think elegant is not possible when this lexical notion of scope is bolted onto a runtime namespace lookup system (dynamic scope.) (I cringe with fear when I use these terms, but I swear I did look the Lisp definitions up.) Consider def f(): x = 5 def g(): print x x = 7 return g t = f() t() Does it print 5 or 7? Of course, we know it's going to be 7, because we understand this system and know how to use it, but I'm saying this is perverse in terms of what people ought to need to understand. (I also think it's an unfortunate feature to have to support, if it means preserving f()'s entire local scope dictionary for the lifetime of t.) But I admit my approach might not allow what I imagine people would expect in places, either. Suppose in the above, f invoked g instead of returning it. Then (I think) many would want x to be 7 in g. My `until a better idea comes along' response would be `too bad, use a function parameter', and I can talk about the value of this attitude towards programming, but I don't have enough charisma to make it popular. Similarly, I would certainly not allow any function to rebind variables in the caller. Donn Cave, donn at u.washington.edu From ramen at lackingtalent.com Fri Apr 30 17:55:57 2004 From: ramen at lackingtalent.com (Dave Benjamin) Date: Fri, 30 Apr 2004 21:55:57 -0000 Subject: Simple prototyping in Python References: <69cbbef2.0404300855.20dd436b@posting.google.com> <1095h4vc89hmcf@corp.supernews.com> Message-ID: In article <1095h4vc89hmcf at corp.supernews.com>, Michael Geary wrote: > As with any other object, you can put functions as well as data in an object > literal, e.g.: > > var o = > { > a: 5, > incr: function() { return ++this.a }, > } > > o.incr() will return 6, 7, 8, etc. if you call it repeatedly. Hey, I never knew that "this" could be used inside of an anonymous object in JavaScript. Thanks for pointing that out! In Python, you'd have to give the object a name, since there's no "self" to refer to. For instance (using the "obj" and "do" functions I defined earlier): def f(): o = obj(a=5, incr=lambda: do(o.set('a', o.a + 1), o.a)) return o >>> o = f() >>> o.a 5 >>> o.incr() 6 >>> o.incr() 7 Not exactly elegant, but not totally atrocious either... -- .:[ dave benjamin: ramen/[sp00] -:- spoomusic.com -:- ramenfest.com ]:. : please talk to your son or daughter about parametric polymorphism. : From mcfletch at rogers.com Mon Apr 26 01:03:58 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Mon, 26 Apr 2004 01:03:58 -0400 Subject: Why we will use obj$func() often In-Reply-To: References: <84Uhc.22278$dZ1.5087@fed1read04> <8AWhc.23114$dZ1.11070@fed1read04> <40883BFE.B381518A@alcyone.com> <27_hc.23801$dZ1.2716@fed1read04> <40887145.789A2FE8@alcyone.com> <7cki80hj976bia36lhf9er97v073o1pqvm@4ax.com> <1082783076.585831@yasure> Message-ID: <408C983E.1070101@rogers.com> Mark Hahn wrote: >"Greg Ewing" wrote in message >news:c6hvdk$bs63j$1 at ID-169208.news.uni-berlin.de... > > >>Mark Hahn wrote: >> >> ... >You cannot. Yes it literally means the immediately surrounding function. >In your example, I can't think of any scheme we've discussed that accesses x >in function f. Python surely cannot. > > Well, not yet, it was explicitly not implemented until something elegant came along IIRC. >I understand this is quite limiting, but it's simple. As always, I'm open to >suggestions... > > How about: .this (surrounding scope, often an object) ..this (surrounding scope + 1, such as a module or a nested-class' parent Seems elegant in a certain way. The construct is reminiscent of directory specifiers, and meshes nicely with the attribute access syntax. Gets a little unwieldy if you're having hugely nested constructs, but then that's already unwieldy, so more pain too them :) . Have fun, Mike _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From mr_organic at yourmamashouse.com Thu Apr 15 17:12:36 2004 From: mr_organic at yourmamashouse.com (mr_organic) Date: 15 Apr 2004 21:12:36 GMT Subject: newbie question References: Message-ID: jeff wrote in news:Xns94CCA389D3DA0plasticnospamplsxsin at 216.77.188.18: > ex: > > a = "text str" > if a == "text str": print a > > why doesn't that work? i couldn't find much help about variable types > in the manual, does it need a property like a.text? > If you're at the commandline, remember to push ENTER *twice* at the end of your last statement; a blank line causes the interpreter to execute your code. I just used your code and it worked fine. mr_organic From tjreedy at udel.edu Thu Apr 22 23:52:08 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 22 Apr 2004 23:52:08 -0400 Subject: AOP use cases References: <0pydnSB4WYuieuLdRVn-hQ@powergate.ca> <40888443$0$126$3a628fcd@reader3.nntp.hccnet.nl> Message-ID: "Anton Vredegoor" wrote in message news:40888443$0$126$3a628fcd at reader3.nntp.hccnet.nl... > "Terry Reedy" wrote: > > >Hmmm. When I started this reply, I was going to emphasize that 'separating > >concerns' is much less efficient than more directly writing > > The problem is *which* concerns are to be separated. > > def fgen(): > #generate fibonacci sequence > a,b = 0,1 # add yield a to define fib(0) as 0, as some do > while 1: > a,b = b,a+b > yield a > def fib(n, L = [], g = fgen()): > #interface with fibonacci generator > if n < 0 : > return 1 > while len(L) <= n: > L.append(g.next()) > return L[n] Nice. Generalizing the wrapper gives def listify(gen): it = gen() cache = [] def func(n): while len(cache) <= n: cache.append(it.next()) return cache[n] return func fib = listify(fgen) Alternative is def listify(iterable): it = iter(iterable) ... #which then requires fib = listify(fgen()) I agree that separating and wrapping the function as generator or iterator is even better that as regular function. I have use for this. Thanks. Terry J. Reedy From mday at apple.com Tue Apr 20 21:00:31 2004 From: mday at apple.com (Mark Day) Date: Tue, 20 Apr 2004 18:00:31 -0700 Subject: Generator inside a class prevent __del__ ?? References: <4085BA96.651D2E4A@free.fr> Message-ID: <200420041800310664%mday@apple.com> In article <4085BA96.651D2E4A at free.fr>, Emmanuel wrote: > >>> class toto: > def __init__(self): > print "init" > self.Coroutine = self.Gen() > def __del__(self): > print "del" > def Gen(self): > yield 1 > > >>> a = toto() > init > >>> c = [] > <--- Nothing there !!! First of all, "a" is still referencing your toto object. I think you meant "a = []" here. But even if you did "a = []", the destructor still isn't called. There must still be a reference to the object. My guess is that the generator (directly or indirectly) is referencing the object, creating a self referential loop. Consider the following modification that merely references a function, and does not create a generator: >>> class tata: ... def __init__(self): ... print "init" ... self.Coroutine = self.Gen ... def __del__(self): ... print "del" ... def Gen(self): ... pass ... >>> a=tata() init >>> a=[] >>> Here's how to break that loop: >>> b=tata() init >>> b.Coroutine=None >>> b=[] del >>> -Mark From garryknight at gmx.net Wed Apr 14 16:39:18 2004 From: garryknight at gmx.net (Garry Knight) Date: Wed, 14 Apr 2004 21:39:18 +0100 Subject: Python for PocketPC (Dell Axim - XScale processor) References: Message-ID: <1081975157.10988.3@ersa.uk.clara.net> In message , Chris wrote: > Is there a version of Python that will run on the PocketPC platform? > Specifically I have an Axim X5 with Xscale processor... PythonCE runs fine on my X5: http://mail.python.org/mailman/listinfo/pythonce http://www.murkworks.com/Research/Python/PythonCE/PythonCEWiki/FrontPage http://fore.validus.com/~kashtan/ -- Garry Knight garryknight at gmx.net ICQ 126351135 Linux registered user 182025 From sr1419 at yahoo.com Wed Apr 28 23:59:10 2004 From: sr1419 at yahoo.com (Mark Bauman) Date: Wed, 28 Apr 2004 20:59:10 -0700 Subject: Tkinter and XML-RPC Message-ID: <0jZjc.65$pw1.70887@news.uswest.net> I'm new to Python (C/C++/Delphi background), and so far I'm impressed with the language, libraries and community. Anyway, I've just started poking around with Tkinter and I'm wondering if anyone has any tips or caveats on incorporating an XML-RPC client and server inside a Tkinter app. I have an application in mind that would primarily be dealing with short string messages and the occasional jpeg, so I'm wondering about blocking and threading issues within the confines of the GUI. I'm just starting to dig into the detailed docs on Tkinter and the XLM-RPC library, but I thought I would ask since I'm sure that some folks have been there, done that. Regards, Mark... From no.email at please.com Mon Apr 12 05:57:46 2004 From: no.email at please.com (Stevie_Mac) Date: Mon, 12 Apr 2004 10:57:46 +0100 Subject: oopidstay outlookyay References: <5Reec.62668$Id.61067@news-binary.blueyonder.co.uk> Message-ID: Oopsyay on the ultiplemay ostspay :) "Paul Prescod" wrote in message news:mailman.537.1081743469.20120.python-list at python.org... > Stevie_mac wrote: > > > OS=XP, Python 2.3, wx2.5.1.5u > > Not sure what's to blame here - or to be more precise, how to fix it!... > > > > If I do this in PythonWin... > > import wx > > d = wx.Dialog(None, -1, 'title') > > BANG - IDE crashes > > It typically doesn't work to have two GUIs in one process. PythonWin > uses MFC. Wx is a totally different GUI. > > Paul Prescod > > > From oktaysafak at ixir.com Sat Apr 24 18:11:23 2004 From: oktaysafak at ixir.com (Oktay Safak) Date: Sun, 25 Apr 2004 01:11:23 +0300 Subject: ignore this post. just testing References: <494182a9.0404241322.8f3ec0a@posting.google.com> Message-ID: test --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.667 / Virus Database: 429 - Release Date: 23.04.2004 From peter.schwalm at epost.de Wed Apr 7 08:52:17 2004 From: peter.schwalm at epost.de (Peter Schwalm) Date: 7 Apr 2004 05:52:17 -0700 Subject: Customizing the python search path depending on source directory References: <5cf809e9.0404061853.41cd3c85@posting.google.com> Message-ID: <5cf809e9.0404070452.643b7053@posting.google.com> Peter Hansen wrote in message news:> > .... > > a) the source directory of the script is still not in sys.path > > Are you sure? Looking at site.py, it appears that the sitecustomize > import is done next-to-last, just before sys.setdefaultencoding is > deleted. If you concluded this by examining sys.path manually at > the point just as sitecustomize is imported, maybe you don't know > that the '' entry in sys.path actually represents the source > directory of the main script... Thank you for your answer. But I'm afraid it's not the source directory but the current working directory. You can see the difference if you copy the passage "for ix1, p1 in enumerate(sys.path): print "%02.02d: %s" % (ix1, p1)" to a "normal script". If you start that "normal script" from a directory other than the source directory, you can see that both directories are included in sys.path. If you run this code inside sitecustomize.py this is not the case. Thank you Peter From carroll at nospam-tjc.com Fri Apr 16 02:10:58 2004 From: carroll at nospam-tjc.com (Terry Carroll) Date: Thu, 15 Apr 2004 23:10:58 -0700 Subject: Python Documentation Blows! References: <40699A31.8000708@yahoo.com> <20040330161531.GA17112@vulcan.cprogrammer.org> Message-ID: <86uu70phciv8arhieh3gv51dbf0i33f9ir@4ax.com> On Tue, 30 Mar 2004 11:19:21 -0800, Michael wrote: >wxPython would be my example of some of the worst (non-existant) >documentation available for Python while PyGame would be my example of >some of the best. The state of wxPython's documentation is the major factor that's kept me from trying it. From jacek.generowicz at cern.ch Thu Apr 22 08:09:43 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 22 Apr 2004 14:09:43 +0200 Subject: AOP use cases References: <84fc4588.0404140106.3fa0c55@posting.google.com> <0pydnSB4WYuieuLdRVn-hQ@powergate.ca> <108f99vgg6ub501@news.supernews.com> Message-ID: "John Roth" writes: > there are no, and I mean no, examples of composable programs where > there was no planning on making it happen. Aaah, yes, Proof by Ignorance[*], one of my favourite logical tools :-) [*] I don't know a programming language whose name starts with "P" and ends with "n", therefore none exist. QED[+] [+] Best used in conjunction with Proof by Projection: None exist now, therefore none have existed in the past, and none will exist in the future. Ignorance is a powreful tool. From op73418 at mail.telepac.pt Mon Apr 5 11:29:17 2004 From: op73418 at mail.telepac.pt (Gonçalo Rodrigues) Date: Mon, 05 Apr 2004 16:29:17 +0100 Subject: Using function parameters to determine method kind References: <4qrzym6e.fsf@telus.net> <95aa1afa.0404050417.2d11b369@posting.google.com> Message-ID: On 5 Apr 2004 05:17:39 -0700, michele.simionato at poste.it (Michele Simionato) wrote: [text snipped] >I am also waiting for a better "super" but it seems nobody is talking >about it. Well then, here is your chance: what are the problems of super? I also found that it has a couple of glitches, but I'd like to know more. With my best regards, G. Rodrigues From paul at prescod.net Mon Apr 12 00:01:59 2004 From: paul at prescod.net (Paul Prescod) Date: Sun, 11 Apr 2004 21:01:59 -0700 Subject: Is there a boolean(somestring) equivalent of int(somestring). bool('false') -> True In-Reply-To: References: Message-ID: <407A14B7.2030603@prescod.net> Vineet Jain wrote: > Thanks for the code suggestion. > > From what I've read, most people (including me) are attracted to Python > because of how natural it is. Give that is a high priority for the language > designers: > > How can anyone argue that > > bool('false') = True > > is more natural (and what you would expect) than > > bool('false') = False For most (all?) built-in types there is one and only one false value. If you start to accept multiple false values then you run into the types of problems Perl programmers run into. You write code like this: a = input() if a: ... else: ... And knowing what it does requires you to keep in mind ALL of the false values for the type. So you test your program with one dataset and one day another of the false values pops up and your program behaves incorrectly. Python's rule is simpler. > Having just got over the surprise that int('2.1') fails while > int(float('2.1')) works the above surprises me even more. If the int case > was rejected because it is 'better to be explicit than not' then how can you > bool('false') be allowed?? "false" is just a random English word. The Python builtin is called "False". > Booleans are associated with (True, on, 1 and yes) and bool() on any them > should return True. Maybe in your mind. What about "true", "TRUE", "oui", "1.0", "positive" and "yeah". How far do you intend to go? Name a single language or system that treats "True", "on", "1" and "yes" as positive values and "False", "off", "0" and "no" as negative values. If Python started guessing what strings are vaguely affirmative, people would always "expect" it to read their minds just a little bit more effectively than it does. The current rule is very simple: the empty string is false. All others are true. It is trivially easy for you to redefine conversion to boolean for any particular data set: def mybool(): return mystring=="oui" Paul Prescod From http Mon Apr 12 18:48:34 2004 From: http (Paul Rubin) Date: 12 Apr 2004 15:48:34 -0700 Subject: OO Bug needs squashing References: <35f7b657.0404121341.6acb8a52@posting.google.com> Message-ID: <7xlll0dd8d.fsf@ruckus.brouhaha.com> billybugmaster at yahoo.com (nick) writes: > class Day: > name = None > events = [] > eventD = {} I think you mean: class Day: def __init__(self): self.name = None self.events = [] self.eventD = {} and similarly for the Event class. That creates those attributes in each newly-created instance. The way you have it, it makes attributes on the entire class, not separately for each instance. From nelson at monkey.org Thu Apr 8 11:52:01 2004 From: nelson at monkey.org (Nelson Minar) Date: Thu, 08 Apr 2004 15:52:01 GMT Subject: print u"\u0432": why is this so hard? UnciodeEncodeError References: Message-ID: Thanks for your answers. "Martin v. L?wis" writes: >As you have discovered, this is not so simple. Printing this character >might not be possible at all I know. I'm just trying to figure out an expedient way to get Python to make a best effort. > When you redirect the output to a file, it is not a terminal anymore, > and Python cannot guess the encoding. So when Python can't guess the encoding, it assumes that ASCII is the best it can do? Even as an American that annoys me; what do folks who need non-ASCII do in practice? Martin, what do you do when you write a Python script that prints your own name? I guess what I'd like is a way to set Python's default encoding and have that respected for files, terminals, etc. I'd also like some way to override the Unicode error mode. 'strict' is the right default, but I'd like the option to do 'ignore' or 'replace' globally. > Assigning sys.stdout is the right thing to do. I'm uncertain why > that could be an awful lot of work, as you do this only once... Now that I know the trick I can do it. But part of the joy of Python is that it makes simple things simple. For a beginner to the language having to learn about the difference between sys.stdout and sys.__stdout__ seems a bit much. From eric at zomething.com Fri Apr 2 00:59:08 2004 From: eric at zomething.com (Eric @ Zomething) Date: Thu, 1 Apr 2004 21:59:08 -0800 Subject: Stackless Website down, Project gone, I'm dead. Message-ID: <20040401215908.1792931349.eric@zomething.com> Christian Tismer wrote: > Dear Former Stackless Users, > > I have to use this list to announce something really bad to you, > since all the Stackless lists are defunct: > > The Stackless project is finally dead, now and forever. > [snip] > p.s.: I've taken the capsule, short time ago. > p.p.s.: This message was sent to you on April 2, to make > sure that it is not misinterpreted as a bad April 1 joke. > The bad joke was about that bad intruder. See you soon, > in heaven or somehwere else :-) Well, Christian's post was sent April 2nd (per the header), but it arrived here April 1st. I have little notion of the time-space groundrules for April Fools over the Internet continuum, but I hope this was a joke; perhaps (-1*(-1*(joke))). The deduping code shared the other day was, I thought, inspired. the whole April Fools thing leaves me spinning for 24 hours: the joke within the joke, within the joke: >>> def Fool(AprilFirst): if AprilFirst: print "April Fools" serious = 0 else: print "No, I'm serious" serious =1 Fool(serious) return "April 2nd" >>> April=1 >>> Fool(April) April Fools No, I'm serious April Fools No, I'm serious April Fools No, I'm serious April Fools No, I'm serious April Fools No, I'm serious April Fools No, I'm serious April Fools No, I'm serious April Fools No, I'm serious April Fools No, I'm serious . . . [where is April 2nd?] From peter at engcorp.com Thu Apr 29 11:07:47 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 29 Apr 2004 11:07:47 -0400 Subject: MATLAB2Python In-Reply-To: <3064b51d.0404290654.58e59124@posting.google.com> References: <3064b51d.0404290654.58e59124@posting.google.com> Message-ID: beliavsky at aol.com wrote: > The Fortran standards committee takes > backwards compatibility much more seriously, so that code you write > now will not take on a new meaning in future versions of the language. This is an unfair characterization. They most certainly take backwards compatibility *seriously*, but perhaps they put a higher value on making changes that, in their opinion, make significant improvements to the language, or fix serious mistakes they made in the original. Maybe that's a reason that Python is being adopted more, while FORTRAN growth is, uh, somewhat flat. I really doubt they sit around in their plush leather chairs, stroking their long-haired Persian cats, and saying "But won't that break old code? Yes, but screw the scientific programmers, BWAHAHAHAHA...." But I could be wrong. -Peter From Mike at DeleteThis.Geary.com Mon Apr 5 20:44:55 2004 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Mon, 5 Apr 2004 17:44:55 -0700 Subject: Using python23 to develop an extension for an application that has python22 embedded References: <1073eeubflmchd5@corp.supernews.com> Message-ID: <1073vcag51uufe9@corp.supernews.com> John Underwood wrote: > I have both 2.2 and 2.3 installed on my computer. My problem has to do > with Visual Studio .NET which will build 2.3 but will not build 2.2. > (MS removed largeint.h which is required by pythoncore in 2.2 when > they went from Visual C++ 6 to VS.NET. I tried supplying largeint.h to > VS.NET but that did not work.) > > Since I cannot build 2.2, I do not have python22.dll or python22_d.dll > (the debug version). (They are not shipped with python you have to > produce them yourself.) The executable Python installer for Windows does install pythonXX.dll. You should find python22.dll and python23.dll in your Windows system32 directory. Do you need python22_d.dll at all? I would think you'd need it only if you were actually debugging the Python interpreter itself. I've never needed a debug version of the Python DLL to debug ordinary Python code. > The commercial application to which I need to add an extension has > python22.dll in its runtime folder. I have no control over this > application and have to use whichever version they have chosen. Paint Shop Pro? > Since I do have python23.dll and python23_d.dll (from a successful > build of 2.3), can I use these to develop an extension for the > aforementioned commercial application if I stay away from any new > features in 2.3 (but not in 2.2)? Are you talking about source code compatibility only? Sure, as long as you use only language features available in both the old and new versions. You can't use .pyc bytecode files from one version with a different version. Anyway, I must be missing something here, because I would think you could simply develop with your installed Python 2.2 and run the code under your target application. You shouldn't have to be worrying about any of the stuff you're dealing with. -Mike From greg at cosc.canterbury.ac.nz Fri Apr 16 00:46:18 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Fri, 16 Apr 2004 16:46:18 +1200 Subject: raise Exception Syntax question In-Reply-To: References: Message-ID: chris wrote: > >>> import exceptions > >>> e = exceptions.Exception There's actually no need to import exceptions, since all the standard exception names are built-in. I think the exceptions module is just there for historical compatibility. > >>> raise e("MESSAGE") This is the preferred form. Again, the other one only exists for historical reasons. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From mlh at furu.idi.ntnu.no Fri Apr 23 11:47:09 2004 From: mlh at furu.idi.ntnu.no (Magnus Lie Hetland) Date: Fri, 23 Apr 2004 15:47:09 +0000 (UTC) Subject: Regexp optimization question References: Message-ID: In article , William Park wrote: >Magnus Lie Hetland wrote: >> Any ideas? > >Few concrete examples, perhaps? Sadly, my telepathetic power is not >what it used to be... Well... Hard to give specific examples, as the specifics will be user-specified. But in order to explain what I'm doing, I could give a rather generic example. I might have a bunch of regexps like 'foo1', 'foo2', 'foo3', ..., 'foo500' (these would be more complex, of course). Now I can do something like this: hits = [] for pat in pats: hits.extend(pat.finditer(text)) # Maybe sort them in order of occurrence *Or* I can do something like this: bigPat = '(' + '|'.join(pats) + ')' hits = list(bigPat.finditer(text)) The last one is *much* faster -- but only if I forego named groups. And without them, I can't find out which patterns matched at which locations. (I can, as suggested, use .lastindex to find *one* of them, but not all, as I need.) I'm sure there are plenty of bottlenecks in my code, but this seems to be one of them, and it's slow even if I run it alone (without any of the rest of my parsing code). -- Magnus Lie Hetland "Wake up!" - Rage Against The Machine http://hetland.org "Shut up!" - Linkin Park From sympa at ens.fr Fri Apr 16 04:02:54 2004 From: sympa at ens.fr (SYMPA) Date: Fri, 16 Apr 2004 10:02:54 +0200 (CEST) Subject: Results of your commands Message-ID: <200404160802.i3G82s6q024647@nef.ens.fr> > feel free to use it. Command not understood: ignoring end of message. No command found in message From simon at struktur.de Mon Apr 5 03:57:03 2004 From: simon at struktur.de (Simon Eisenmann) Date: Mon, 05 Apr 2004 09:57:03 +0200 Subject: Installing Python 2.3.3 on RH 7.3 In-Reply-To: <5fb57772.0404021802.a3e0e75@posting.google.com> References: <106e6nge2aiiqa9@corp.supernews.com> <5fb57772.0404021802.a3e0e75@posting.google.com> Message-ID: Carl L wrote: > "Rien Kok" wrote in message news:<106e6nge2aiiqa9 at corp.supernews.com>... > >>Hi, >> >>I have a strange problem. I want to install Plone >>(Plone2-2.0.0rh-2.i386.rpm) Because Plone 2.0 needs Python 2.3.3, I >>installed Python 2.3.3 from source (Python-2.3.3.tar). > > I have the same problem with install Plone 2 on Redhat 9.0. Did you > find an answer to the problem? Source installations are not supported by rpms. I managed to put a howto together now to get around these confusions :) See http://longsleep.org/howto/rh9-python233 and http://plone.org/downloads/rpm-notes cheers, Simon From http Sat Apr 3 04:26:51 2004 From: http (Paul Rubin) Date: 03 Apr 2004 01:26:51 -0800 Subject: String concatenation References: <7xisgi24fm.fsf@ruckus.brouhaha.com> Message-ID: <7xr7v5fm3o.fsf@ruckus.brouhaha.com> "Leif B. Kristensen" writes: > > tmp = [x for x in res if x and x[0] != '-'] > > return ', '.join(tmp) > > Substituting tmp with the real thing, it turns into a one-liner: > > return ', '.join([x for x in res if x and x[0] != '-']) > > Awesome :-) Yeah, I wrote it that way at first, but figured it was obscure enough already if you weren't used to list comprehensions, so I put back the tmp variable. From joe at notcharles.ca Tue Apr 6 05:12:52 2004 From: joe at notcharles.ca (Joe Mason) Date: Tue, 06 Apr 2004 09:12:52 GMT Subject: int('2.1') does not work while int(float('2.1')) does References: <40722555.66C70D40@alcyone.com> <40722E98.253B5FF2@alcyone.com> Message-ID: In article <40722E98.253B5FF2 at alcyone.com>, Erik Max Francis wrote: > Joe Mason wrote: > >> Why can it make this guess for "int(2.1)", then? It's got a rule for >> converting floats to ints - why not use it here? > > Because int(aFloat) means round toward zero. int(aString) means make an > int out of this string. So why can't int(string) mean round toward zero? Joe From cpl.19.ghum at spamgourmet.com Tue Apr 13 06:46:19 2004 From: cpl.19.ghum at spamgourmet.com (Harald Massa) Date: Tue, 13 Apr 2004 12:46:19 +0200 Subject: A new OS References: <107k441hitt2ld9@corp.supernews.com> <107lskfjvqvc3e5@corp.supernews.com> Message-ID: Hello A. Evans, I propose you should take a look at PyPy first. PyPy is an attempt to realise Python in Python. Because "IN THE END" your Operating System must run on existing hardware. And there is a step between Python and Assembler... With standard CPython it is C-language, with Jython it is Java. But there can be C-Errors in Python and C-Errors within Java ... so to get "only Python", you need a PythonPython first. Am I wrong? Harald From alanmk at hotmail.com Tue Apr 20 12:01:19 2004 From: alanmk at hotmail.com (Alan Kennedy) Date: Tue, 20 Apr 2004 17:01:19 +0100 Subject: Editing/Writing Word-Files from Python In-Reply-To: References: Message-ID: [Daniel Cloutier] > is it possible to edit or write Word-files out of a Python-Program? If you have access to Office 2003, are feeling brave, and have a lot of time on your hands, you could create and manipulate the XML structures that Word 2003 uses. It thought the group members might find it interesting to see such a file, so I have exported a "Hello World!" document as XML, and posted the result below. I had to tidy it up a little, the original came out all on one line. And I had to add an encoding declaration :-) In terms of generating such structures, well, everybody has their own favourite *ML templating language. I'd use TAL or XSLT in "Literal Result Element as Stylesheet" mode ... http://www.w3.org/TR/xslt#result-element-stylesheet #--------- helloworld.xml --- cut here ------------------------ Hello World Alan Alan 1 1 2004-04-20T15:38:00Z 2004-04-20T15:39:00Z 1 1 12 Alan 1 1 12 11.6113 Hello World! #--------- helloworld.xml --- cut here ------------------------ -- alan kennedy ------------------------------------------------------ check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/contact/alan From timr at probo.com Fri Apr 9 01:30:58 2004 From: timr at probo.com (Tim Roberts) Date: Thu, 08 Apr 2004 22:30:58 -0700 Subject: Non-math-geek needs help with CRCs (binascii.crc32) References: <4073c865$0$27642$61ce578d@news.syd.swiftdsl.com.au> <40751603$0$27643$61ce578d@news.syd.swiftdsl.com.au> Message-ID: "nobody" wrote: > >That doesn't seem to mention anything about poly $EDB88320, which is the >code I'm trying to a) be compatible with, b) define for future developers so >they don't have to go through this whole mess. It appears whatever Python >uses is compatible, but stating the poly by itself doesn't mean anything. > >Somehow, depending on how the numbers are massaged, the old code based on >$EDB88320 is compatible with what the above site documents as $04C11DB7. Did you notice that those two numbers are mirror images of each other? Could just be a difference in interpretation. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From imbosol at aerojockey.invalid Fri Apr 23 02:05:30 2004 From: imbosol at aerojockey.invalid (Carl Banks) Date: Fri, 23 Apr 2004 06:05:30 GMT Subject: Why we will use obj$func() often References: <84Uhc.22278$dZ1.5087@fed1read04> <8AWhc.23114$dZ1.11070@fed1read04> <40883BFE.B381518A@alcyone.com> <27_hc.23801$dZ1.2716@fed1read04> <40887145.789A2FE8@alcyone.com> Message-ID: Mark Hahn wrote: > > > > "Ben Finney" wrote ... > >> Please understand what an ad hominem attack is before accusing others of >> using it, thank you very much: > > What did I do? Prothon is accused of looking like Perl (which I mistakenly > took as an ad hominem slur, Ok, I gotta admit, that's understandable. -- CARL BANKS http://www.aerojockey.com/software "If you believe in yourself, drink your school, stay on drugs, and don't do milk, you can get work." -- Parody of Mr. T from a Robert Smigel Cartoon From perky at i18n.org Thu Apr 8 20:36:26 2004 From: perky at i18n.org (Hye-Shik Chang) Date: Fri, 9 Apr 2004 09:36:26 +0900 Subject: print u"\u0432": why is this so hard? UnciodeEncodeError In-Reply-To: References: Message-ID: <20040409003626.GA94453@i18n.org> On Thu, Apr 08, 2004 at 08:51:18PM +0200, "Martin v. L?wis" wrote: > David Eppstein wrote: > >Py2.3 sure doesn't discover the encoding of my terminal automatically: > > > >hyperbolic ~: python > >Python 2.3 (#1, Sep 13 2003, 00:49:11) > >[GCC 3.3 20030304 (Apple Computer, Inc. build 1495)] on darwin > > Ah, Darwin. You lose. > > If anybody can tell me how to programmatically discover the encoding > of Terminal.App, I'll happily incorporate a change into a 2.3.x release. > The encoding of darwin terminal can be discovered by the routine currently we have. perky$ LC_ALL=ko_KR.UTF-8 python Python 2.3 (#1, Sep 13 2003, 00:49:11) [GCC 3.3 20030304 (Apple Computer, Inc. build 1495)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import sys;sys.stdin.encoding 'UTF-8' >>> ^D perky$ LC_ALL=ko_KR.eucKR python Python 2.3 (#1, Sep 13 2003, 00:49:11) [GCC 3.3 20030304 (Apple Computer, Inc. build 1495)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import sys;sys.stdin.encoding 'eucKR' Regards, Hye-Shik From guettli at thomas-guettler.de Tue Apr 27 08:16:25 2004 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Tue, 27 Apr 2004 14:16:25 +0200 Subject: xml.parsers.expat vs. xml.sax Message-ID: Hi! What are the difference between xml.parsers.expat and xml.sax? Up to now I used xml.sax.make_parser and subclass from ContentHandler. I think xml.sax.make_parser uses expat as default. Why should I want to use xml.parsers.expat? Regards, Thomas From http Fri Apr 16 00:13:01 2004 From: http (Paul Rubin) Date: 15 Apr 2004 21:13:01 -0700 Subject: CamelCase versus wide_names (Prothon) References: Message-ID: <7xekqo36ia.fsf@ruckus.brouhaha.com> "Mark Hahn" writes: > 1) CamelCase is more elegant, modern, more readable, and more efficient in > character usage. IfCamelCaseWereReallyMoreReadable, We'dWriteOrdinaryEnglishLikeUsingIt. SoThatClaimIsRidiculousAndNeedsToBeThrownOutTheWindowPostHaste. > 2) Wide_names is cleaner, more readable, compatible with C, which is the > standard module language for Python and Prothon. Wide_names is also the > Python standard. Sounds_ok_with_me. I_find_it_a_heck_of_a_lot_more_readable_than_camel_case. I_vote_for_wide_names. From stuart at stuartbishop.net Wed Apr 14 22:02:20 2004 From: stuart at stuartbishop.net (Stuart Bishop) Date: Thu, 15 Apr 2004 12:02:20 +1000 Subject: 3D Graphics Engine In-Reply-To: <8089854e.0404130639.3eb0db62@posting.google.com> References: <8089854e.0404130639.3eb0db62@posting.google.com> Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On 14/04/2004, at 12:39 AM, Fuzzyman wrote: > I've seen various references to 3D graphics engines - and it's a > little difficult to know where to look. > > I would like (in the long run) to be able to create and explore 3d > worlds - so texture mapping, light sourcing or shading and mesh shapes > would be nice - but I *don't* need the quality of a commercial game > system. Collision detection etc would be nice too. > > Platform for development (!) is win32 - so I would like an engine with > precompiled binaries and a documented python binding available. A > freeware object modeller A full featured and well documented alternative might be Java3D. Jython didn't exist when I last played with it, but I see no problems with driving the toolkit from Jython rather than Python. Java3D is available from sun for a number of platforms, including Windows. > Can anyone reccomend a 3d engine for me to 'muck around with'. I think it is a good alternative to 'muck around with' as it is high level and documented. It might even be a good options for writing real applications with (When I last looked at it, you would get a slight freeze every 30 seconds as the JVM's garbage collector kicked in. This was a few *years* ago though, so this might now be fixed :-) ) - -- Stuart Bishop http://www.stuartbishop.net/ -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.3 (Darwin) iD4DBQFAfe0wAfqZj7rGN0oRAiKaAJihNxMoCsMj/pwXHd3fXUJC61amAJ9ggTU/ gbYysAZ+D6O0HEJTzCLBQA== =0OS4 -----END PGP SIGNATURE----- From srijit at yahoo.com Tue Apr 20 07:39:55 2004 From: srijit at yahoo.com (srijit at yahoo.com) Date: 20 Apr 2004 04:39:55 -0700 Subject: Dollar sign ($) on foriegn keyboards? (prothon) References: Message-ID: <221d8dbe.0404200339.268c39de@posting.google.com> Hello Mark, IMO typing dollar($) sign should not be a problem in Sweden and Germany. Regards, Srijit "Mark Hahn" wrote in message news:... > We are considering switching to the dollar sign ($) for self, instead of the > period ( . ) we are using now in Prothon. Ruby uses the at-sign (@) for > self, but our new usage of self also includes replacing the period for some > attribute references, as in obj$func() versus obj.func(), and too many > programs treat that as an email address and screw it up. Also the S in the > symbol $ reminds one of the S in $elf. > > Can people from outside the U.S. tell me if typing the dollar sign often > would be a problem in writing code? Is it available and somewhat easy to > type on international keyboards? From chris at suse.localdomain Sat Apr 10 14:04:02 2004 From: chris at suse.localdomain (Chris) Date: Sat, 10 Apr 2004 13:04:02 -0500 Subject: New user - Now what ? References: Message-ID: <107gdh6l3odcddc@corp.supernews.com> gordonisnz wrote: > > Hi there > > Im a new user to python > > (although not new to CGI (Perl) / PHP ) > > Ive installed Python on my home server (testing)... > > Now what ? > > Any tutorials I can use to utilise Python on my web-pages ? > > G try: http://www.python.org/doc/ From andrew.henshaw at gtri.gatech.edu Fri Apr 2 12:53:42 2004 From: andrew.henshaw at gtri.gatech.edu (Andrew Henshaw) Date: Fri, 2 Apr 2004 17:53:42 +0000 (UTC) Subject: Making the Zen of Python more useful References: <106qp0uivlefo40@corp.supernews.com> <-5ydnTEmxfuZHvDdRVn-iQ@powergate.ca> Message-ID: In article , peter at engcorp.com says... > >Andrew Henshaw wrote: > >> In article <-5ydnTEmxfuZHvDdRVn-iQ at powergate.ca>, peter at engcorp.com says... >> my main >> problem was with the automatic printing of the text upon import. Obviously, >> that functionality needs to remain. It would just be nice if there was >> some clean way of (sometimes) using the module without it. > >I don't think your particular use case was known to the developers >when they implemented that module. Maybe you should suggest it as >an enhancement on Sourceforge. Be sure to include a patch! ;-) > >-Peter I'm sure that is true. Unfortunately, I can't write a patch since I can't think of a way to provide both functions; except, by wrapping in another module - which I mentioned in my original post and was repeated by Joe Mason. It's not a big deal, obviously. It would just be nice if there was a way to do both using the one module. For my use, wrapping it in another module is okay. I just thought that since we had the 'this' module as part of the standard distribution, and, I suspect, that lots of coders have unittests that could use some line-oriented text, then it would have reasonably broad applicability. -- Andy From ptmcg at austin.rr._bogus_.com Fri Apr 2 11:24:27 2004 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Fri, 02 Apr 2004 16:24:27 GMT Subject: Simple BMP files Message-ID: <%sgbc.9990$Tx6.6980@fe2.texas.rr.com> Here is a link to a simple Python script for creating BMP files if your needs are simple (drawing lines, circles, and rectangles). Something you could drop into a cgi-bin to create simple graphics on the fly. http://www.geocities.com/ptmcg/python/index.html#bmp -- Paul From lbates at swamisoft.com Fri Apr 30 14:55:37 2004 From: lbates at swamisoft.com (Larry Bates) Date: Fri, 30 Apr 2004 13:55:37 -0500 Subject: sending email notification References: <18e22d94.0404301048.35e0e701@posting.google.com> Message-ID: <_eadneLrYOy6PA_dRVn-hw@comcast.com> Sure it is possible. You will need proper configuration on Exchange Server (you called it an outlook server) and us IP address of that server as your outgoing email server. I have a client that has such a configuration and they did get it working (I didn't do the Exchange configuration so I can't help you there). Larry Bates Syscon, Inc. "Rene Aguirre" wrote in message news:18e22d94.0404301048.35e0e701 at posting.google.com... > Hello, > > I'd like to make a sort of web tracking system for internal stuff at > my office. > But I'm having problems about how to add email notification to my > script. > > I already tried to send email by using the 'email' module, with no > success (the connection can't be stablished). I think my case is a > very specific enviroment (may be very common): > * Local /corporate intranet controlled through NTFS proxy. > * I don't have access to a regular SMTP mail server, regular email > access is through outlook email server, so, I'll have to send emai > messages to the corporate outlook server. > * Desktop / server enviroment is windows (if I make a cgi script the > server where it'll run is a regular Windows XP machine here in the > office running Apache). > > Any ideas, is it possible? > > Rene From scs at lokkur.dexter.mi.us Fri Apr 30 11:09:27 2004 From: scs at lokkur.dexter.mi.us (Steve Simmons) Date: Fri, 30 Apr 2004 15:09:27 GMT Subject: static keyword References: Message-ID: Peter wrote on 04/29/04 at 14:37: > I'm not sure how to interpret the smiley, but I'll take it > you weren't actually joking... > Why do you call using OO ("wrapping it in a class", as you say) > a "hack"? Generally speaking, using objects to contain state > information such as this is exactly what most people would call > the cleanest, best approach. I'm not the original poster, but I'm going to side with him. Class, to me, implies a fair number of things about the intended use of what the author has written. Jacobson is talking about a much simpler construct/feature than what one would normally use a class for. His proposal might seem like mere syntactic sugar to avoid making a class, but IMHO it will lead to code that is more readable - code that doesn't imply it's anything other than a function with a persistant, stateful variable. Steve From kirk at strauser.com Mon Apr 12 11:25:07 2004 From: kirk at strauser.com (Kirk Strauser) Date: Mon, 12 Apr 2004 15:25:07 GMT Subject: why is python better than eg. smalltalk?? no one has any solid arguments! you should all go to church with all that religious talk! References: Message-ID: <873c792pb0.fsf@strauser.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 At 2004-04-11T03:08:25Z, "Daniel Ellison" writes: > Yes, who in their right mind would use emacs when there's a perfectly good > alternative in vi? Noone. As soon as vi comes up with that perfectly good alternative, let me know. ;-) - -- Kirk Strauser The Strauser Group Open. Solutions. Simple. http://www.strausergroup.com/ -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.4 (GNU/Linux) iD8DBQFAerRj5sRg+Y0CpvERAhiNAJ9NiTpkg5szCGwrvQWLG7KaPprEqQCfcbNS kt3oc/kUyHowyA7HRl8IQiM= =ZpMO -----END PGP SIGNATURE----- From RobMEmmons at cs.com Sat Apr 17 10:53:40 2004 From: RobMEmmons at cs.com (Robert M. Emmons) Date: Sat, 17 Apr 2004 09:53:40 -0500 Subject: Difficulty Finding Python Developers In-Reply-To: References: <65cbc3dd.0404140641.3501fde8@posting.google.com> <407D6269.3090909@engcorp.com> <40808FF1.7060204@cs.com> <4080AE97.C4CF0755@alcyone.com> <408110CE.7030402@cs.com> Message-ID: <408144F4.9050109@cs.com> > Likewise, in any project involving more than about 2 people, software > process engineering starts to become as critical as programming. Things > like poor configuration management, quality control, requirements > gathering and documentation are more likely to sink a big project than > bad coding. Simply understanding all of the true stake holders in a project and the boundary conditions they represent on one hand -- and getting a group of people to understand these issues and to work together effectively to satisfy the multiple and often conflicting conditions is always an enormous challange in any team project environment. There are always oh so many ways to fail, and even when you "succeed" it may be only a very partial success and only in the eye of a fraction of the stake-holders. I always walk away from these things feeling like it's a "messy business" and wondering if I could have done it a better way or have made better decisions or communicated better or faciliated better or supported people more. Rob From michael at foord.net Thu Apr 1 02:24:00 2004 From: michael at foord.net (Fuzzyman) Date: 31 Mar 2004 23:24:00 -0800 Subject: Why '==' ?? References: <8089854e.0403302319.1ab56af0@posting.google.com> Message-ID: <8089854e.0403312324.7de8710c@posting.google.com> [snip..] > > Why not ! > Stop complain about choice ! > > If you want another syntax, you can imagine yours. > What you need is rather simple : > Create a parser and an Abstract Syntax Tree from the parser. Then you > can still use python to bytecompile it ( with compiler.pycodegen ). > That way you will be able to use the python library but have your > favorite syntax with brackets, '=' or ':=' assignement, etc... > > Also had a hook on the import statement to automatically byte-compile > your file when requested and that's all ! > > I'm playing with that kind of stuff. That is really fun and easy... > > Yermat My goodness !! Now there's an option..... Define my own syntax - but use the CPython compiler............. lol Actually I think python is fine - just pointing out a couple of features of syntax that seemed unnecessary. In actual fact I accept the explanation for '==' it was a 'feature' of language that I didn't realise existed. (Like a = value or default which I discovered recently... very useful in certain circumstances). Having said that I *Still* think that : if a = 3: is unambiguous - so there's no real reason that the interpreter should wag it's finger and say ... "you forgot to put in one of the '=' and I refuse to continue until you do" :-) Regards, Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html From eltronic at juno.com Thu Apr 8 04:50:40 2004 From: eltronic at juno.com (eltronic at juno.com) Date: Thu, 8 Apr 2004 04:50:40 -0400 Subject: why is python better than eg. smalltalk?? no one has any solid arguments! you should all go to church with all that religious talk! Message-ID: <20040408.045041.-327839.0.eltronic@juno.com> > From: "Carlo v. Dango" > > On Thu, 30 Oct 2003 , Andy Jewell wrote: > OK, I'm on the python wagon as well, but I do not really se much > improvement over JAVA... especially when it comes to maintaining and > reusing code (e.g. API's)... here the types are really helpful. So just > saying typing is bad, is to me, plain wrong. > > Also, I see all this advocacy of python which to me seems more like > religion.. there is no concretenes in it, and I completely fail to see how > python beats any of the other dynamically typed languages such as > smalltalk or self... what is it with you guys? :) isn't there a convention in blind tests when something is so obviously better, effective, cheaper, that the test is stopped and the placebo group are given the real thing? it ain't hype if it's true! at some point quantifying what is obvious through anecdote after similar anecdote is a criminal waste of time, brain and cpu power. to me, Python is fun, compared to every other language. but am I more productive? only if you consider that the distance between getting an idea and having working code is shorter. that having working code that is readable promotes reuse and now the distance between idea and code is getting even shorter. what is impossible to measure is that more complicated ideas are now, to me, cost effective. time is saved when you can easily send to or return a tuple to a function. w/o worrying about static storage space. lazy evaluation, huge debugging win when you can isolate when something breaks non withstanding the argument "the compiler would've caught that", as the static typers like to say. how did I avoid python for so long? I've been searching for most of the past 14 years first on Usenet at $0.40 cents/minute dialup, then the web and long before that in books and magazines and BBs's and libraries for code, algorithms, ideas. as it turns out I was looking for what python already has had. a way to turn ideas into programs, to turn keys & clicks into repeatable actions in the real world. It wasn't until I had already started converting all my scripts and tools to python that I realalized how many times python turns up in searches, why had I only followed the link to flawfinder and Leo? and only then even bothered to read the FAQ. half way through the FAQ and a few minutes with the interpreter was all it took for me, was the python association with Zope early insecurities a deterrence? > the beauty of Python... and by the facilities, libraries and support > infrastructure (i.e. c.l.py). > > Python does seem to magnify the flaws in other languages: everything else > seems (to me at least) to be second-best now. > > Slither On! > > -andyj > > e http://rClick.netfirms.com/rCpython.htm ________________________________________________________________ The best thing to hit the Internet in years - Juno SpeedBand! Surf the Web up to FIVE TIMES FASTER! Only $14.95/ month - visit www.juno.com to sign up today! From aku at europe.com Mon Apr 5 14:35:00 2004 From: aku at europe.com (aku) Date: 05 Apr 2004 18:35:00 GMT Subject: design by contract versus doctest References: <407174ea$0$5066$4d4ebb8e@news.nl.uu.net> <40718ddb$0$5071$4d4ebb8e@news.nl.uu.net> Message-ID: <4071a6d4$0$5064$4d4ebb8e@news.nl.uu.net> On 2004-04-05, Peter Hansen wrote: > aku wrote: > > > On 2004-04-05, Peter Hansen wrote: > > > >> aku wrote: > >> > >> > >>>Isn't it so, that by applying DBC, a lot of unittests can be > >>>made redundant? > >> > >> How would you propose verifying that your code will work if you > >> don't run tests before you ship? > > > > > > in debugging mode you obviously have to ensure that the caller > > makes sure that all preconditions are met...then - by contract - > > the postconditions are met on returning from the function. > > What is "debugging mode"? > > You aren't actually talking about _manual_ testing of some > kind, are you? no I'm not > If not, I don't understand how you can be > talking about automated testing, yet claiming that unit > tests are redundant. Or are you simply saying that proper > use of DBC can somewhat _reduce_ the number of unit tests > you have to write? yes - the latter. Indeed reduce, not omit. A nr of unittests will still be necessary to ensure preconditions, but in the (oversimplified) example I gave (n = 1), the test "if n < 0: ..." isn't necessary anymore and certainly not *in* the called function itself. The "downside" with DBC I see is: when the caller *cannot* ensure a precondition, then the behavior in the called function becomes unpredictable. (In which case I ask how do you propose > to verify that your precondition contracts are written properly?) > > -Peter From davidf at sjsoft.com Thu Apr 22 01:59:48 2004 From: davidf at sjsoft.com (David Fraser) Date: Thu, 22 Apr 2004 07:59:48 +0200 Subject: Dealing with multiple versions of packages... In-Reply-To: <62c819a5.0404201235.c1649c5@posting.google.com> References: <62c819a5.0404201235.c1649c5@posting.google.com> Message-ID: Chris Barker wrote: > Hi all, > > We've been having a discussion over on the wxPython-users mailing list > about how to deal with multiple versions of wxPython. During the > discussion it came up that this isn't a problem faced only by > wxPython, but would have to be dealt with by virtually all packages. > > The root of the problem is what to do when you install a new version > of wxPython, and want to be able to keep using the old one. This > question comes up frequently on the users list, and various schemes > are used by a variety of people. These schemes mostly involve having > some sort of script that re-names or re-links the site-packages/wx > directory, so the chosen version can be used. > > This works fine if your goal is to be able to switch back an forth for > testing, and during the process of moving your app(s) to a new > version. > > However, my goal (and I don't think I'm alone) is to have both > versions installed and working at the same time, and have the app able > to select between them. I want this because I have a bunch of small > utilities that use wxPython, and I don't want them to break when I > upgrade, forcing me to go back and port all of them to a new > version...if it ain't broke, I don't want to fix it. What I would like > is analogous to using: > > #/usr/bin/env python2.2 > > and > > #/usr/bin/env python2.3 > > at the top of my python programs... I can have all my old 2.2 scripts > work just fine, while I write new ones for 2.3. > > The easiest proposal is: > > 1) wxPython gets installed into: > > site-packages/wxXXX (with XXX) being the version number > > You could put a link to wx if you want, so as not to change anything > for people who don't want to change. > > For this to work, ALL the stuff in the demo and libs would have to > import this way" > > import wxXXX as wx > > This creates problem when the user needs sub-packages: This won't > work: > > import wx251 as wx > import wx.lib.buttons > > Which I think points out a problem with the package import mechanism, > but I won't go there at the moment.... > > Another proposal is: > > 2) put wx251 deeper in the structure: > > from wxPythonVersions.251 import wx > from wxPythonVersions.251 import wx.lib.buttons > > wxPythonVersions (or a shorter, catchier name) would live in > site-packages. You could put a symlink: > > site-packages/wx --> site-packages/wxPythonVersions/251/wx > > for backward compatibility. > > I think this would work great, but I also think there will be a strong > push to have a default: > > import wx > > which would require a symlink, and you can't symlink on Windows. > > So ... What have other folks done to deal with this? > Would either of the above methods work well? > What pitfalls am I missing? > Is there a standard Pythonesque way to handle this? > > -Chris How about introducing some new syntax: import wx where wx.version >= "2.5" Then we just need a means of determining the version. You could use a directory name of wx-2.5 for the package rather than wx Or maybe have an enhanced version of .pth files that specifies package attributes. It would be nice if the above could be combined with the Python Package Index to automatically fetch packages... Davod From guettli at thomas-guettler.de Tue Apr 13 06:29:44 2004 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Tue, 13 Apr 2004 12:29:44 +0200 Subject: Simple discussion of python cgi approaches? References: <153fa67.0404121727.45b23c30@posting.google.com> Message-ID: Am Mon, 12 Apr 2004 18:27:58 -0700 schrieb Kylotan: [cut] > All I want is a short description on the technologies that very > closely resemble standard CGI, what they have to offer me, and what > sort of alterations I would have to make to my installation or code in > order to use these. Does such a comparison exist already? If not, is > anybody able to comment on their own experiences with Python CGI apps? Hi, I started with Zope in 2001. This is very different than CGI. Then I switched to quixote. It is very much like CGI. Every HTTP-Request results in an method call which gets an request object as argument. In my situation it is enough to run quixote with plain cgi (no SCGI, mod_python, ...): About three request per minute. Loading the interpreter for every request is not the bottleneck. HTH, Thomas From peter at engcorp.com Thu Apr 29 11:47:50 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 29 Apr 2004 11:47:50 -0400 Subject: reading and removing first x bytes of a file In-Reply-To: <40911B85.5080107@hotmail.com> References: <40911B85.5080107@hotmail.com> Message-ID: bart_nessux wrote: > Thanks Peter, the below code recursively read the first 128B... am I > right in saying that? Well, your indentation is screwed up, for one thing, so I can't guarantee the code does what you want. I'll leave actually testing it up to you... > If so, now that I can read these bytes from all > .bin files in a directory, what would be the safest and fastest way of > removing them? Define 'safe' and describe how fast you want it to run. Anyway, you can't actually "remove" bytes from the files, so what you really need to do is then read the *rest* of the bytes (i.e. keep the file open after the first read, and do a .read() of the rest of the data) and then write the shortened data to a temporary file (module tempfile can be helpful here), then once that's worked, use os.remove to remove the old file, and os.rename to rename the temp file to the same name as the old file. -Peter From peter at engcorp.com Fri Apr 30 15:48:01 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 30 Apr 2004 15:48:01 -0400 Subject: Is classless worth consideration In-Reply-To: <8ef9bea6.0404301017.575c91d7@posting.google.com> References: <69cbbef2.0404290259.fd8d71c@posting.google.com> <69cbbef2.0404291209.7a98a799@posting.google.com> <8ef9bea6.0404292307.66b78b83@posting.google.com> <84Kdnfu3OoN4oA_dRVn-vg@powergate.ca> <8ef9bea6.0404301017.575c91d7@posting.google.com> Message-ID: <662dnX_AL5_sMA_d4p2dnA@powergate.ca> Hung Jung Lu wrote: > Peter Hansen wrote in message news:<84Kdnfu3OoN4oA_dRVn-vg at powergate.ca>... >>Well, (c) module is merely a packaging technique, > > Are you sure about that? Have you seen how people put an class > instance in sys.modules so they could use it as a module (an old trick > by now)? Have you seen people asking __call__() to make modules > callable, and/or property getters/setters for modules? "Merely a > packaging technique"? Have you seen people using modules as > singletons? Do you realize that "from ... import ..." is nothing but a > form of module inheritance? Think again. Let me say it again: think > outside the box. It's hard to do when you are inside the box. But try. > Try hard. You are being extraordinarily insulting. I was going to give some other reply, but it's just not worth it. "Bog off", as 'has' might say. -Peter From maheshpop1 at yahoo.com Tue Apr 27 04:36:44 2004 From: maheshpop1 at yahoo.com (mahesh) Date: 27 Apr 2004 01:36:44 -0700 Subject: Basic Class + Dialogs doubt Message-ID: Hi all, I have a doubt with OOAD and Dialogs. I have a Dialog Class. tkSimple.py It contains a class body as below. Now I am calling the tkSimple.py in another python program and using the default body, and everything from tkSimple.py. Now my requirement is as follows I need to popup a couple of other dialog boxes with a little difference in between each dialog and take different values. Summarising as below Main window ----> tkSimple.py Main window--ButtonClick ---> New dialog 1 Main window--Button 2 Click---> Another New Dialog 2. Now I am wondering how I can put three different types of dialogs in the same tksimple.py and call them at different conditions in my main class I am including the code here. Right now I have created multiple copies of the tkSimple.py like tkSimple1.py tkSimple2.py and importing them whereever I need them regards, Mahesh Main Program --------------- from Tkinter import * from tkSimpleDialog import Dialog import tkMessageBox import tkSimple class SampleDialog(tkSimple.Dialog): ..................... .................. ................. def body(self, master): self.title("Tool ") self.geometry("400x500") # All the constant values goes here. # Labels Label(master, text='BSS ATTRIB TOOL').grid(row=1, sticky=W) Label(master, text=' ').grid(row=2, sticky=W) Label(master, text=' ').grid(row=3, sticky=W) Label(master, text=' ').grid(row=4, sticky=W) Label(master, text='BSS Name').grid(row=5, sticky=W) Label(master, text='MIT VErsion').grid(row=6, sticky=W) #Choosing the device type belonging to which class goes here. v = IntVar() global CnType CnType = IntVar() Label(master, text='').grid(row=7, sticky=W) Label(master, text='').grid(row=8, sticky=W) Label(master, text='Select a button below to add a device').grid(row=9, sticky=W) optTp = Button(master, text ="Click here to add a Class A device", comma nd=self.ShowA).grid(row=10, column=0, sticky=W) @ def apply(self): Name1 = self.bssName.get() Name2 = self.mitName.get() global CnType global deviceClass deviceClass = CnType.get() print deviceClass #Boby's Code to place the above values in the file pass def ShowA(self): global DialogType DialogType = 2 getValue = tkSimple1.Dialog(self) -------------..............end of main program TkSimple.py Code ----------------------------- from Tkinter import * import os class Dialog(Toplevel): def __init__(self, parent, title = None): Toplevel.__init__(self, parent) self.transient(parent) if title: self.title(title) self.parent = parent self.result = None body = Frame(self) self.initial_focus = self.body(body) body.pack(padx=5, pady=5) self.buttonbox() self.protocol("WM_DELETE_WINDOW", self.cancel) self.geometry("+%d+%d" % (parent.winfo_rootx()+50, parent.winfo_rooty( )+50)) self.initial_focus.focus_set() self.wait_window(self) # construction hooks def body(self, master): # create dialog body. return widget that should have intial focus. pass def buttonbox(self): box = Frame(self) w = Button(box, text="Save", width=10, command=self.ok, default=ACTIVE) w.pack(side=LEFT, padx=5, pady=5) #Need to change the command here . w = Button(box, text="Run Tool", width=10, command=self.ok) w = Button(box, text="Run Tool", width=10, command=self.ok) w.pack(side=LEFT, padx=5, pady=5) #w = Button(box, text="Help", width=10, command=self.help) #w.pack(side=LEFT, padx=5, pady=5) w = Button(box, text="Cancel", width=10, command=self.cancel) w.pack(side=LEFT, padx=5, pady=5) self.bind("<Return.", self.ok) self.bind("<:Escape.", self.cancel) box.pack() def ok(self, event=None): if not self.validate(): self.initial_focus.focus_set() return self.withdraw() self.update_idletasks() self.apply() self.cancel() def cancel(self, event=None): self.parent.focus_set() self.destroy() def validate(self): return 1 def apply(self): pass From project5 at redrival.net Mon Apr 5 14:37:41 2004 From: project5 at redrival.net (Andrei) Date: Mon, 5 Apr 2004 20:37:41 +0200 Subject: slightly OT: BUT NEEDs to be said References: <4078daf265c69e9353e8af72542da703@dizum.com> Message-ID: <1fi14c5u22tzn.19a14muyfl3da.dlg@40tude.net> Nomen Nescio wrote on Mon, 5 Apr 2004 16:50:04 +0200 (CEST): > I think it would be great for Python.org/people behind Python to adopt this > as an official mascot and DROP the god awful references to Monty Pythons's > Flying Circus. It is the later which is causing a slow take up and reluctance > of many individuals using Python. MPFC is a very very dated concept and because > of it's strange whacky 'humour' has dubious extreme and loony left wing allegiences > is not a good backdrop for Python. You should never bring politics into your LOL! Nobody expects the Spanish Inquisition! (Somebody had to say it...) > MPFC shit which I hate and will use Perl or PHP instead which are considerably You do know what next-gen Perl will compile to, right? Parrot! Guess where that name *really* comes from :). > a powerfully slippery creature Yeeewwwwww... -- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5 at jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From stevenbee at removethis.part.att.net Wed Apr 28 10:49:13 2004 From: stevenbee at removethis.part.att.net (Steven Brent) Date: Wed, 28 Apr 2004 10:49:13 -0400 Subject: Backticks: What up? In-Reply-To: References: Message-ID: Thanks! I didn't know you could use printf type syntax with return.... From chrisl_ak at hotmail.com Wed Apr 14 13:19:27 2004 From: chrisl_ak at hotmail.com (Chris) Date: 14 Apr 2004 10:19:27 -0700 Subject: Python for PocketPC (Dell Axim - XScale processor) Message-ID: Is there a version of Python that will run on the PocketPC platform? Specifically I have an Axim X5 with Xscale processor... From ptkwt at aracnet.com Mon Apr 26 16:20:14 2004 From: ptkwt at aracnet.com (Phil Tomson) Date: 26 Apr 2004 20:20:14 GMT Subject: How's ruby compare to it older brother python References: <108qk9dft7h7o52@corp.supernews.com> Message-ID: In article , Brandon J. Van Every wrote: >Cameron Laird wrote: >> . >> It's not just that "You won't know until you try" ("is it better >> to have children, or join the monastery?"); it's that you won't >> know until you try, *and it's inexpensive to try*! It's eminently >> feasible to gain experience in either language with a few hours (!) >> of work, as opposed to the weeks that must precede enlightenment >> about, say, J2EE servers. > >Of course, those of us who are more into the Complete Waste Of Time [TM] >theory of selecting software components will simply give you the bottom >line: > >- If you like Perl, you'll like Ruby. If you think Perl is a bletcherous >hack, you'll like Python. >- The Python community dwarfs the Ruby community. >- Both languages are slow. >- Python has lotsa libraries but not everything. Ask here regarding your >specific needs. Even if Python were the most elegant language in the world, >that's not useful if you must write everything from scratch and don't have >time to do it. > >This is the kind of information you get by simply asking people and reading >lotsa archives. Some people say "Try it yourself!" is the only way to >learn. They are wrong, and they often don't value people's time. You >really can rely on other people's reported experiences of the nuclear >mushroom cloud exploding over the horizon. It is not strictly necessary to >walk into Ground Zero yourself. > >Now, if you're going to argue "it's just a little Ruby code..." why don't >you try multiplying that by all the languages in the comp.lang.* hierarchy >that you could potentially be selecting from? Take a spin by the Language >Shootouts if you want to spin your head some more. >http://www.bagley.org/~doug/shootout/ >http://dada.perl.it/shootout/ >You need a filter of some kind for cutting down the options. I suggest >asking people, and seeing what languages actually got used for jobs relevant >to your software problem / industry. > It seems as though he has already done this. He was interested in Ruby and Python (N=2). From there a couple of people (including myself) suggested that he make the determination about which to study indepth by actually doing a bit of coding in both languages. Spending a day or two on this exercise doesn't seem excessive if you're serious about selecting your 'next language' to learn in depth. Phil From fredrik at pythonware.com Wed Apr 21 12:48:00 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 21 Apr 2004 18:48:00 +0200 Subject: python shutting down sloooooooowly/tuning dictionaries References: <20040421153923.GA13234%till@score.is.tsukuba.ac.jp> Message-ID: Till Plewe wrote: > Since the entire database is too large I typically run the same > program 10-100 times on smaller parts. The annoying bit is that the > time for finishing one instance of a program before starting the next > instance can take a lot of time. I have started using a shell script to > check whether certain files have been written and then kill the > program from the os to speed up everything. But this solution is way > too ugly. There should be a better way, but I don't seem to be able to > find one. have you tried using os._exit() instead of sys.exit() From jcarlson at uci.edu Thu Apr 1 14:25:22 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Thu, 01 Apr 2004 11:25:22 -0800 Subject: PLEASE STOP!!! In-Reply-To: References: <95aa1afa.0404010352.80de14e@posting.google.com> <406C40E8.10209@prescod.net> Message-ID: > You can't count Camilo in with the spoilers - Camilo obviously believes > that my 'goto' module is some kind of prank fiction, when in fact it's a > working module ready to be downloaded and used. There's probably a word > for this but I've no idea what it is... While I (generally) dislike april fools pranks, after reading this I gave it a shot. Low and behold, it works. Perhaps you should have released it on April 4 or so, just to not be accused of trying to dupe people. Of course, I suppose the prank is that people think it is a prank, when in fact, is actually truth. - Josiah From piotrus at sympatico.ca Fri Apr 16 04:23:41 2004 From: piotrus at sympatico.ca (peter) Date: Fri, 16 Apr 2004 08:23:41 GMT Subject: newbie question on gnuplot.py References: <337e6cd5.0404152030.17da017e@posting.google.com> Message-ID: "SunX" wrote in message news:337e6cd5.0404152030.17da017e at posting.google.com... > I've got python, Numeric, gnuplot all installed but am having a hard > time to install gnuplot.py correctly. Tried to follow the documents, > including the readme, ... but always getting "ImportError: No module > named gnuplot" or "ImportError: No module named Gnuplot". And my > directorey only has _Gnuplot.py, not Gnuplot anyway. > Help please. you should probably look where Gnuplot.py got installed (have no idea what platform you're on, or how you installed it) and make sure that this directory is in your PYTHONPATH.. also, since you're looking at plotting packages, you might want to check out matplotlib.. cheers. peter From news at bolognini.net Fri Apr 30 20:32:26 2004 From: news at bolognini.net (Lorenzo Bolognini) Date: Sat, 1 May 2004 02:32:26 +0200 Subject: Web development class Message-ID: Hi all, it's been a while I haven't looked at Python but I remember that there once was a class (I think it was just a class) that helped in web development. Can't remember the name of the project: it was a kind of a parser which would allow you to do this sort of stuff: h1.red (assigning properties to html entities) I think the project's web page was on a kind of red background. Any hints? Cheers, Lorenzo Bolognini From __peter__ at web.de Sun Apr 4 06:11:25 2004 From: __peter__ at web.de (Peter Otten) Date: Sun, 04 Apr 2004 12:11:25 +0200 Subject: recursive file editing References: Message-ID: TaeKyon wrote: > I'm a python newbie; here are a few questions relative to a > problem I'm trying to solve; I'm wandering if python is the best > instrument or if awk or a mix of bash and sed would be better: > > 1) how would I get recursively descend > through all files in all subdirectories of > the one in which my script is called ? > > 2) each file examined should be edited; IF a string of this type is found > > foo.asp=dev?bar (where bar can be a digit or an empty space) > > it should always be substituted with this string > > foo-bar.html (if bar is an empty space the new string is foo-.html) > > 3) the names of files read may themselves be of the sort foo.asp=dev?bar; > the edited output file should also be renamed according to the same rule > as above ... or would this be better handled by a bash script ? > > Any hints appreciated > The following code comes with no warranties. Be sure to backup valuable data before trying it. You may need to edit the regular expressions. Call the script with the directory you want to process. Peter import os, re, sys class Path(object): def __init__(self, folder, name): self.folder = folder self.name = name def _get_path(self): return os.path.join(self.folder, self.name) path = property(_get_path) def rename(self, newname): if self.name != newname: os.rename(self.path, os.path.join(self.folder, newname)) self.name = newname def processContents(self, operation): data = file(self.path).read() newdata = operation(data) if data != newdata: file(self.path, "w").write(newdata) def __str__(self): return self.path def files(rootfolder): for folder, folders, files in os.walk(rootfolder): for name in files: yield Path(folder, name) fileExpr = re.compile(r"^(.+?)\.asp\=dev\?(.*)$") filePattern = r"\1-\2.html" textExpr = re.compile(r"([/\'\"])(.+?)\.asp\=dev\?(.*?)([\'\"])") textPattern = r"\1\2-\3.html\4" if __name__ == "__main__": for f in files(sys.argv[1]): f.rename(fileExpr.sub(filePattern, f.name)) f.processContents(lambda s: textExpr.sub(textPattern, s)) From greg at cosc.canterbury.ac.nz Wed Apr 7 05:06:29 2004 From: greg at cosc.canterbury.ac.nz (greg) Date: Wed, 07 Apr 2004 21:06:29 +1200 Subject: GUI Frameworks in Python? References: <930ba99a.0404030246.786455f5@posting.google.com> <8ef9bea6.0404041009.26ae2683@posting.google.com> Message-ID: <4073C495.2050106@cosc.canterbury.ac.nz> Josiah Carlson wrote: > Simpler? According to Greg, passing ids of the widget was a > pain...well, in 2.5 you can pass the widget. Apparently that is > significant enough to warrant Greg complaining about it, and Robin Dunn > to fix it. Like I said, it's not a big deal on its own, just something that seemed needlessly awkward, among many others. Some other examples: You can't create a widget until there's a parent for it, forcing you to create widgets in a certain order. When you create a widget, you have to either specify an ID number, or -1 to say you don't care what its ID number is (I didn't, mostly), instead of just letting it default. Most widget constructors seem to take about half a dozen parameters that you have to get in the right order because you can't specify them using keywords. And so on. All these small things added up to an experience that I didn't enjoy much overall. -- Greg From bart_nessux at hotmail.com Thu Apr 29 10:00:54 2004 From: bart_nessux at hotmail.com (bart_nessux) Date: Thu, 29 Apr 2004 10:00:54 -0400 Subject: reading and removing first x bytes of a file Message-ID: Hello, I have some Macbinary files on a PC. I want to recursively read these files and remove the first 128 bytes of the files if they contain the macbinary header info. I know how to read directories recursively, but how would I read the first 128 bytes of each file in the path? Thanks, Bart From jussij at zeusedit.com Tue Apr 13 09:31:22 2004 From: jussij at zeusedit.com (Jussi Jumppanen) Date: Tue, 13 Apr 2004 23:31:22 +1000 Subject: Best IDE? References: Message-ID: <407BEBAA.4DA9@zeusedit.com> Stevie_mac wrote: > What's the best MSwindows editor for python? Take a look at the Zeus programmer's editor (shareware): http://www.zeusedit.com/lookmain.html > I'm currently using PythonWin (ActiveState) at the moment, its > a bit buggy - but not too bad. I mean, its got autocomplete & > tips & help & autoindentaion (not always good tho). Zeus has code completion and intellisensing for all files in the current workspace. Some other features include: + Fully configurable syntax highlighting + Project/workspace management + Seamless FTP editing + Integrated class browser + Integrated version control using the Microsoft Source Code Control (SCC) interface, including CVS integration. + Quick Help context sensitive help engine Jussi Jumppanen http://www.zeusedit.com From SeeBelow at SeeBelow.Nut Fri Apr 30 17:47:37 2004 From: SeeBelow at SeeBelow.Nut (SeeBelow at SeeBelow.Nut) Date: Fri, 30 Apr 2004 21:47:37 GMT Subject: calling functions at the same time References: Message-ID: <4092C97E.EEC4F797@shaw.ca> bart_nessux wrote: > > I need a script to call several functions at the same time. How does one > call more than one function simultaneously? You can call them pseudo-concurrently by starting a new thread for each one. You cannot call them truly concurrently unless you have a separate CPU for each function. Mitchell Timin -- "Many are stubborn in pursuit of the path they have chosen, few in pursuit of the goal." - Friedrich Nietzsche http://annevolve.sourceforge.net is what I'm into nowadays. Humans may write to me at this address: zenguy at shaw dot ca From fumanchu at amor.org Sat Apr 17 00:27:10 2004 From: fumanchu at amor.org (Robert Brewer) Date: Fri, 16 Apr 2004 21:27:10 -0700 Subject: Python OS Message-ID: Paul Watson wondered: > What if we had a machine whose native instruction set was > Parrot bytecode? That's been suggested before: From huggiepython at graffiti.idv.tw Sun Apr 11 12:13:09 2004 From: huggiepython at graffiti.idv.tw (Timothy Wu) Date: Mon, 12 Apr 2004 00:13:09 +0800 Subject: Parsing Message-ID: <40796E95.9090207@graffiti.idv.tw> I'm parsing Firefox bookmarks and writing the same bookmark to another file. To make sure I read and write utf-8 correctly I make open files like this for read and write: codecs.open(file, "r", "utf-8") For regular expression I parse like this: m = re.search("(.*?)", line, re.I) How do I tell the regular expression to parse in utf-8? From the docs it seems like I can do re.compile("(.*?)", 'U') for unicode. But does it need to be specified to be utf-8 instead of some other unicode standards? Or does that matter at all? And, I'm not calling compile() directly at all. I'm simply calling re.search(). How would I specify unicode? Is it simply re.flags = 'U' before any call search? Timothy From alloydflanagan at comcast.net Tue Apr 13 11:48:49 2004 From: alloydflanagan at comcast.net (A. Lloyd Flanagan) Date: 13 Apr 2004 08:48:49 -0700 Subject: Does Python compete with Java? References: <8b336527.0404051337.51bb4a1b@posting.google.com> Message-ID: Dave Benjamin wrote in message news:... > > Over the long term, I think Python's biggest key to success will be that we > will still be able to read the programs that we are writing now. No argument here :) From peter at engcorp.com Tue Apr 27 14:45:05 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 27 Apr 2004 14:45:05 -0400 Subject: Trying to write comments after escaping newline In-Reply-To: References: Message-ID: p brian wrote: > mystring = "hello " + someVariable + \ #comment > "multiple lines 4 clarity" + \ #comment > someothervariable #comment > > it stops working because instead of escaping a newline I am now just > escaping a space or tab. > Is there some clever thing i have missed? Yeah, don't do that. :-) Do this instead; mystring = ("hello " + someVariable + # comment "multiple lines 4 clarity" + # another comment someOtherVariable) # last comment Better yet, consider finding a way to write your code that doesn't require comments in the middle of strings like that. It's not necessarily a good idea to write comments just for comments' sake. Try going for "self-documenting" code. Finally, you could also just use string substitution to clean this stuff up even more: mystring = "hello %s multiple lines not needed %s" % (someVar, someOtherVar) That's often easier on the eyes and the fingers than all those concatenation operators. -Peter From chrisdewinN0SPAM at yahoo.com.au Wed Apr 7 15:26:44 2004 From: chrisdewinN0SPAM at yahoo.com.au (Dfenestr8) Date: Thu, 08 Apr 2004 04:26:44 +0900 Subject: My firefox script Message-ID: Hi. I use mozilla firefox on linux. It's a great browser, but the *nix version has an annoying problem, that it won't let you open a new instance from the desktop if the browser is already running. So, in my amateurish way I wrote a little script to fix that. Here it is...... #! /usr/bin/python #fox_launch.py import sys, os if len(sys.argv) > 1: URL = str(sys.argv[1]) else: URL = "" a = os.popen("ps ax |grep firefox") detect_fox = a.read() if detect_fox.count("firefox-bin") > 0: os.popen2("firefox -remote 'openURL(" + URL + ",new-window)'") else: os.popen2("firefox " + URL) From Kyler at news.Lairds.org Thu Apr 8 11:08:22 2004 From: Kyler at news.Lairds.org (Kyler Laird) Date: Thu, 08 Apr 2004 15:08:22 GMT Subject: Pyrex list is down References: <74jek1-3qs.ln1@snout.lairds.org> Message-ID: <074gk1-8u1.ln1@snout.lairds.org> Duncan Booth writes: >> I hate mailing lists anyway. I'd much rather use Usenet. >So why don't you just run a local news-server and filter any mailing list >messages through to locally generated newsgroups? Because it doesn't provide what Usenet does - a consistent interface that everyone can efficiently use (to read and to search). --kyler From shalabh at cafepy.com Tue Apr 13 09:48:52 2004 From: shalabh at cafepy.com (Shalabh Chaturvedi) Date: Tue, 13 Apr 2004 06:48:52 -0700 Subject: how to break tuple to separate variables In-Reply-To: <407BA940.8000405@kios.sk> References: <407BA940.8000405@kios.sk> Message-ID: Stano Paska wrote: > Hi. > > I need pass variables to function like tuple, but function accepts > separate variables. > > Is there some elegant solution? > > My example: > > # ------------------------------- > import datetime > > def date2tuple(aaa): > try: > y = int(aaa[:4]) > m = int(aaa[5:7]) > d = int(aaa[8:10]) > except: > y = m = d = 0 > return (y, m, d) > > # i need some like this > bbb = datetime.date(date2tuple('2004-11-03')) > > # but date requires > bbb = datetime.date(2004, 11, 03) > > # ------------------------------- Here's a hint (section 4.7.4 of Python tutorial): http://docs.python.org/tut/node6.html#SECTION006740000000000000000 > > Thanks. > > Stano Paska > -- Shalabh From dkuhlman at rexx.com Thu Apr 15 15:12:05 2004 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Thu, 15 Apr 2004 12:12:05 -0700 Subject: Kuhlman's tutorials pretty good References: <407E1E20.D0216E92@doe.carleton.ca> <200404150710.i3F7A0Hw010978@locutus.doe.carleton.ca> <407E40CC.C06FA9E3@doe.carleton.ca> Message-ID: Fred Ma wrote: [snip] >> However, in looking over 201, I see some scrambling of source >> code examples, vs. surrounding text, e.g. when he's getting into >> regular expressions, some of the examples have nothing to do with >> the explanations that follow. >> Notably sections 2.2, 2.3, 2.4, 2.5. 2.6 is mostly OK except: >> >> """ >> Put together a new string with string concatenation from pieces >> of the original string and replacement values. You can use string >> slices to get the sub-strings of the original string. In our >> case, the following gets the start of the string, adds the first >> replacement, adds the middle of the original string, adds the >> second replacement, and finally, adds the last part of the >> original string: >> >> lineDef = delimitedList(fieldDef) >> """ > > Yes, they seem rearranged. I'm not sure what Dr. Kuhlman's time > is like, but his tutorials are very good, and thus of great value > to > Python newbies everywhere. ;) Whoa! How did all that happen? I believe I tried one too many fancy things in TeX/LaTeX, which is definitely not my native language. I've simplified a few things in the source document, and I believe that these errors are fixed, now. Thanks for pointing this out to me. Also, thanks for the compliments. Dave -- http://www.rexx.com/~dkuhlman From thorsten at thorstenkampe.de Thu Apr 29 16:34:02 2004 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Thu, 29 Apr 2004 22:34:02 +0200 Subject: outline-style sorting algorithm References: Message-ID: <1bwymbk9pe6sk$.dlg@thorstenkampe.de> * Terry Reedy (2004-04-29 20:03 +0100) > "Thorsten Kampe" wrote in message > news:c2bdjg9l06p2.dlg at thorstenkampe.de... >> If made some tests with lists of one million items: >> >> The first test was with a randomized sequence of numbers from 1 - >> 1000000. Duplicate numbers were allowed. The comparing function was >> the identity (lambda x: x). > > I do not understand what you did, and therefore cannot judge results. A > compare function takes two args (the objects to be compared) and > returns -1, 0, 1. (I believe 0, 1 for <= or >t may be sufficient > currently). That's the "traditional" approach (and it doesn't make much sense - see the "Searching and Sorting FAQ" in the Python Cookbook from Tim Peters: "Why does Python use the three out-come cmp for sorting? Why doesn't it use a simple less-than comparison instead?". It better to abstract the function from the comparison. > How did you use the one-param identity? I assembled my "pass function" approach and TCD's DSU approach into a single program[1] Then I generated two lists[2]: >>> a = range(1000000); a.reverse() and >>> b = randseq(1, 1000000, 1000000, 'repeat') (meaning: create a list with one million integers 1 <= n <= 1000000; allow duplicate numbers) Then I timed [3] timer(funcsort, a, lambda x: x, 'dsu')) -> 43 sec timer(funcsort, a, lambda x: x, 'pass')) -> 86 sec timer(funcsort, b, lambda x: x, 'dsu')) -> 24 sec timer(funcsort, b, lambda x: x, 'pass')) -> 5 sec [1] def funcsort(seq, func, modus = 'dsu'): """ sort seq by func(item) """ if func is None: seq = seq[:] seq.sort() return seq elif modus == 'dsu': seq = [(func(item), index, item) for index, item in enumerate(seq)] seq.sort() return [item[2] for item in seq] elif modus == 'pass': seq = seq[:] seq.sort(lambda x, y: cmp(func(x), func(y))) return seq [2] def randseq(range_start, range_end = 0, count = 0, modus = 'norepeat'): from random import randint if modus == 'repeat': return [randint(range_start, range_end) for index in range(count)] elif isinstance(range_start, int): return randseq(range(range_start, range_end + 1))[:count] else: # 'range_start' is a seq, so shuffle range_start = range_start[:] randomseq = [] for i in range(len(range_start)): itemindex = randint(0, len(range_start) - 1) randomseq.append(range_start[itemindex]) del range_start[itemindex] return randomseq [3] def timer(iteration, *func_and_args): """ print the time elapsed (in seconds) evaluating func iteration times (default is '1') """ import gc, \ time from colour import ltyellow, \ reset_color if isinstance(iteration, int): func, args = func_and_args[0], func_and_args[1:] else: # if first argument is not a number, set func to iteration and iteration # to '1' iteration, func, args = 1, iteration, func_and_args iteration = range(iteration) gc.collect() # force garbage collection start_time_cpu = time.clock() start_time_total = time.time() for i in iteration: func(*args) print ltyellow, 'cpu: %(cpu).3f,' % {'cpu': time.clock() - start_time_cpu}, \ 'total: %(total).3f' % {'total': time.time() - start_time_total}, reset_color From mlh at furu.idi.ntnu.no Fri Apr 23 11:52:53 2004 From: mlh at furu.idi.ntnu.no (Magnus Lie Hetland) Date: Fri, 23 Apr 2004 15:52:53 +0000 (UTC) Subject: Regexp optimization question References: Message-ID: In article , G?nter Jantzen wrote: > >"Magnus Lie Hetland" schrieb im Newsbeitrag >news:slrnc8gal3.9da.mlh at furu.idi.ntnu.no... >> >> Any ideas? >> > >Maybe Plex is helpful. I did not use it already, but it seems to adress your >problem Ahah. >The author of Plex is Greg Ewing. He build Pyrex on top of Plex Yeah, I know -- I just never looked at Plex in detail. >The documentation >http://www.cosc.canterbury.ac.nz/~greg/python/Plex/version/doc/index.html >contains [snip] Yeah, I looked at the docs, and it looks very promising! One of the reasons I've avoided existing lexers is that I don't do standard tokenization -- I don't partition all of the text into regexp tokens. I allow the lexer to skip over text -- somewhat like how whitespace is normally handled, except that this can be *any* text -- and to return the next token that is of any use to the current parsing rule. But who knows -- I may be able to use Plex anyway. One problem might be that the regexp format seems to be quite stripped-down (although, of course, a regexp is a regexp, theoretically speaking ;) No non-greedy matching, no lookahead/lookback etc. But if Plex gives a real performance boost, I may be able to live with that. (The regexp part is functionality that is available to the user, in my case.) >Hope I could help you It might. Thanks. >Guenter -- Magnus Lie Hetland "Wake up!" - Rage Against The Machine http://hetland.org "Shut up!" - Linkin Park From joe at notcharles.ca Fri Apr 2 19:23:45 2004 From: joe at notcharles.ca (Joe Mason) Date: Sat, 03 Apr 2004 00:23:45 GMT Subject: Making the Zen of Python more useful References: Message-ID: In article , Andrew Henshaw wrote: > In article , > n3613 at klaff.org says... >> >> >>from this import s >>s.decode('rot13') >> > Thanks for the response. Unfortunately, this still has the (generally > desired) behavior of the text being printed to stdout. For the less general > case of using the text to feed some test code, I don't think that is best. > Unfortunately, I can't think of a way to accomplish both by simply modifying > the 'this' module (for future releases). Adding another module would do it; > but, I was hoping someone could suggest a better way. I don't see the problem with an extra module. Seems to me that there should be one module which makes the Zen of Python available to the program, and another which has the behaviour of printing on import. The given solutions wrap the one that does the printing, which is inside out - the one which prints should call into the one which provides the text, if they're being distributed together. I'm assuming that providing and printing the Zen of Python is the module's main purpose, BTW, since I'm not familiar with it. What is the 'this' module, anyway? It's a name that's pretty much impossible to Google for... Joe From claird at lairds.com Mon Apr 26 12:42:14 2004 From: claird at lairds.com (Cameron Laird) Date: Mon, 26 Apr 2004 16:42:14 -0000 Subject: Is Perl *that* good? (was: How's ruby compare to it older bro References: Message-ID: <108qev6fn542h4f@corp.supernews.com> In article , leeg wrote: . . . >That's my question. I don't write operating systems or control nuclear >reactors (not real ones anyway). . . . But then, from the reliable rumors that reach me, at least some of the software used in nuclear reactors is done in C++ and Visual Basic and ... well, let's not overdo our apologies. -- Cameron Laird Business: http://www.Phaseit.net From heikowu at ceosg.de Fri Apr 23 04:49:22 2004 From: heikowu at ceosg.de (Heiko Wundram) Date: Fri, 23 Apr 2004 10:49:22 +0200 Subject: Python CGI: how to retrieve variables passed by URL In-Reply-To: References: Message-ID: <200404231049.22398.heikowu@ceosg.de> Am Freitag 23 April 2004 07:42 schrieb Sean Berry: > print os.environ["QUERY_STRING"].split("=")[1] > > prints value if I use localhost/cgi-bin/script-name.cgi?variable=value and > this will work... but is there a better way? Start python, and type import cgi and then help(cgi). The cgi module should take care of what you need perfectly. If the docstrings aren't enough to get you started, go to www.python.org -> Documentation -> Global Module Index and check the documentation of the cgi module there. HTH! Heiko. From bj_666 at gmx.net Mon Apr 26 02:16:06 2004 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Mon, 26 Apr 2004 08:16:06 +0200 Subject: Help a newbie revise my program References: <5SZic.98241$U83.18636@fed1read03> Message-ID: In , Paul McGuire wrote: >>>> import cgi >>>> print cgi.parse_qs("shaped=5&sized=7") > {'sized': ['7'], 'shaped': ['5']} >>>> >>>> > I can't explain why the dictionary values are lists, though - I would have > expected scalar strings. It's allowed to use the same key in URLs twice or more: >>> import cgi >>> print cgi.parse_qs("shaped=5&sized=7&sized=42") {'sized': ['7', '42'], 'shaped': ['5']} >>> Ciao, Marc 'BlackJack' Rintsch From drs at remove-to-send-mail-ecpsoftware.com Tue Apr 27 01:17:29 2004 From: drs at remove-to-send-mail-ecpsoftware.com (drs) Date: Tue, 27 Apr 2004 05:17:29 GMT Subject: Uploading files from a server References: Message-ID: "Edward Diener" wrote in message news:m1gjc.3688$g31.2919 at newsread2.news.atl.earthlink.net... > What is the easiest way in Python in a web server to upload a client file, > once the file name on the client's machine has been entered, to a directory > on the server ? > > I think this is what you want ... this is for mod_python with the publisher handler. It will allow a user to upload a file and save it on a server. It provides no protection or checking, however. other server configurations will be slightly different. first, use a form tag and input tag like

The above will get the file to your server. then use an upload function like: def upload_function(req, uploaded_file=None): if uploaded_file: fn1 = str(uploaded_file.filename).split('\\')[-1] fn = fn1.split('/')[-1] # the weird file splitting is because os.path on Freebsd, where this ran, # didn't deal with win32 and unix file paths for uploaded files d = uploaded_file.read() f = open('/save/path/%s' % fn, 'w') f.write(d) f.close() return 'uploaded' else: return 'no file' -d From simoninusa2001 at yahoo.co.uk Wed Apr 21 12:34:36 2004 From: simoninusa2001 at yahoo.co.uk (simo) Date: 21 Apr 2004 09:34:36 -0700 Subject: wxListCtrl with CheckBox? References: <30260531.0404092256.6b58e3a1@posting.google.com> <30260531.0404201020.58660a46@posting.google.com> Message-ID: <30260531.0404210834.34984f95@posting.google.com> Josiah Carlson wrote: > What I meant was that you should replace your listctrl with a wx.Grid > instance. You can emulate every bit of functionality (except perhaps > the row-selection) of a listctrl with a Grid. You just need to rewrite > the subclass properly. > > In terms of being /able/ to have checkboxes in the Grid, check out the > wxPython demo, it has an example with a checkbox in a cell. Yeah, I looked at GridCustTable.py and that's a pretty close approximation of a ListCtrl, but the checkbox (bool) really is nasty - having to triple-click to check the box, and then the whole cell gets highlighted instead of just the box, and it's looks awful on Linux (kinda weird checkbox on Windows too!) I'm afraid I'm never going to find a satisfactory solution. Anyone got a tutorial on how to make custom wxPython widgets? This was the one thing I was hoping for in 2.5 :-( Thanks for the help anyway.... From adalke at mindspring.com Sun Apr 4 13:40:20 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Sun, 04 Apr 2004 17:40:20 GMT Subject: Python is faster than C References: <406F0907.96F37EA1@tunes.org> <7xy8pcogaa.fsf@ruckus.brouhaha.com> <406F454B.C4CC8063@tunes.org> <7xekr4vdek.fsf@ruckus.brouhaha.com> <406F5E95.EBE6D3E8@tunes.org> Message-ID: <8MXbc.15576$lt2.13470@newsread1.news.pas.earthlink.net> Armin Rigo: > Another example would be 'a'*999999999: the result is a string, but > there is no reason that it takes 100MB of memory. Instead, store it > into a C structure that contains a pointer to the original string object > 'a' and the repetition counter, but still give this C structure the > Python type str, so that the difference doesn't show up and the Python > language remains simple. I've written lazy code like this for my own projects, where the concrete object wasn't fully created until needed. One of the problems I had with it was error behaviour. In this case, suppose there isn't enough memory available. Python as is will attempt to allocate enough space when you request it and raise a MemoryError if there isn't enough space. Python as you propose it may allocate the string-like object and only later (eg, when passing the object to some external C function which expects a char *) realize the full string. There isn't enough memory so the allocation fails, raising a MemoryError. But how is the programmer to realize which operations may raise a MemoryError? Instead, will everything need a try/except guard around it? Andrew dalke at dalkescientific.com From loic at fejoz.net Thu Apr 15 07:48:27 2004 From: loic at fejoz.net (Yermat) Date: Thu, 15 Apr 2004 13:48:27 +0200 Subject: Getters and setters in python, common practise In-Reply-To: <407e6cf9@newsflash.abo.fi> References: <407e402c$1@newsflash.abo.fi> <407e6cf9@newsflash.abo.fi> Message-ID: Petter Holmstr?m wrote: > Peter Hansen wrote: > >>> Having a Delphi/Object Pascal-background, I'm very used to using >>> getters and setters when designing my classes. What is the common >>> practise in the Python world? Should one use them or not? >> >> >> Max described the common practice (don't use them until you actually >> need them) but forgot to mention that in recent versions of Python >> you can use "properties", in pretty much the same manner as Delphi >> uses them. > > > I have not found any documentation on this topic. Could you please point > me to some? > > -Petter- see "property" at http://www.python.org/doc/2.3.3/lib/built-in-funcs.html You could also look at http://users.rcn.com/python/download/Descriptor.htm to understand how it does really work. -- Yermat From leeg at teaching.physics.ox.ac.uk.valid Mon Apr 26 13:50:57 2004 From: leeg at teaching.physics.ox.ac.uk.valid (leeg) Date: Mon, 26 Apr 2004 18:50:57 +0100 Subject: Is Perl *that* good? (was: How's ruby compare to it older bro References: <2tOdna6S8a4pqxDdRVn_iw@powergate.ca> <108qf42r54jld3f@corp.supernews.com> Message-ID: Cameron Laird wrote: > In article , > leeg wrote: >>I use POSIX-ey stuff and interfaces to lumps of code written in >>other languages, so Python could be Perl or Objective-C or C or Pascal or >>anything as far as I care; I just happen to be able to write correct code >>fairly quickly in Python. I hope that makes sense :-) > . > So we're concluding that people use most languages because they > must, to access some specific curd of functionality, but Python > is different, and simply doesn't get in the way? How flattering! Well, it doesn't get in the way for *coding*. It does for *running*; so sometimes I code in Python then rewrite in C to run. But yeah, that's the general idea :-) -- Graham Lee I am leeg, for we are many "If we knew what we were doing, it wouldn't be called research, would it?" - Albert Einstein http://users.ox.ac.uk/~wadh1342 From skchim0 at engr.uky.edu Thu Apr 8 10:23:42 2004 From: skchim0 at engr.uky.edu (Satish Chimakurthi) Date: Thu, 8 Apr 2004 10:23:42 -0400 Subject: Embedding python in ANSYS: Anyone tried it? Message-ID: <004601c41d75$183df7f0$559ea380@D4XN6B41> Hello Mr. Berthold, A few months ago, I contemplated interfacing/wrapping ANSYS to Python. I looked at SWIG, BABEL, Boost.Python for this purpose at that time, only to realise that such direct wrapping is not possible since ANSYS libraries are basically Fortran based. I thought of the following work-around to the problem. ANSYS allows users to compile their own customized version. It gives the user access to its vast libraries with the help of some UPF routines ( look at ANSYS-UPF documentation here http://www.cesup.ufrgs.br/ansys/prog_55/g-upf/UPS1.htm ). You may be knowing this. There is a file called ANSCUSTOM in "/usr/local/ansys/v71/ansys/customize/user" directory. First, I wrote a "Makefile" and a "make.inc" file based on the information in ANSCUSTOM. I then wrote a Fortran code in which I used all the UPF routines I needed to be used with ANSYS. I compiled the Fortran code with "make.inc" simultaneously to get a binary executable. And that's it, I was ready to go. The binary executable could be executed using a specific command which could be found in ANSYS Installation and Configuration manual, I think. In my case, I was using ANSYS 7.1, so, I had to execute it as: "anscust71 -custom ./executable -p ANSYSRF". Now, with all that I described above, link between Fortran and ANSYS has become possible. You can look at F2PY (Fortran to Python Interface Generator) here http://cens.ioc.ee/projects/f2py2e/ to have an interface between your Python script and Fortran code that you would be writing for the purpose. At the moment, my Python-Fortran interface is very loose. I use Fortran to ANSYS mostly and do postprocessing work in Python. Please let me know if you think of any other ideas about wrapping Python and ANSYS directly. I would appreciate your assistance. Thanks Best Regards, Satish Kumar Chimakurthi SATISH KUMAR CHIMAKURTHI Graduate Research Assistant CFD GROUP Mechanical Engineering UNIVERSITY OF KENTUCKY Lexington KENTUCKY - 40508 U.S.A Email: skchim0 at engr.uky.edu Mobile:859-420-9890 Office: 859-257-6336 X 80691 -------------- next part -------------- An HTML attachment was scrubbed... URL: From dmq at gain.com Tue Apr 27 10:56:11 2004 From: dmq at gain.com (David MacQuigg) Date: Tue, 27 Apr 2004 07:56:11 -0700 Subject: What is good about Prothon? References: Message-ID: On Mon, 26 Apr 2004 12:36:51 -0700, "Mark Hahn" wrote: >Ignoring the problem of calling the ancestor's version of a method by just >using the same old obj.func() will not work. You don't have to use the >current suggestion of obj$func() (we Prothonites may not use it either), but >you cannot live in denial about the need for it. I'll take this as a Question: How does the iterpreter know that Mammal.talk is an unbound function and not a new binding to Mammal? Answer: For reference, I have marked the line in question with !!! proto Cat(Feline): numCats = 0 __init__ :( n = "unknown", s = "Meow" ): Feline.__init__() Cat.numCats += 1 .name = n # Set instance variables. .sound = s show :(): # Define a "static method". Feline.show() print " Cats:", Cat.numCats talk :(): print "My name is ...", .name print "I am a %s from %s" % (.genus, .home) Mammal.talk() # Call an unbound function. <== <== !!! print __self__ ### Diagnostic check. I am assuming the same implicit rule that Python follows. Mammal is a prototype (class). When you access a function from a class in Python, you get an unbound function. When you access that same function from an instance, you get a function bound to that instance. >>> cat1 = Cat("Garfield","Meow") >>> cat2 = Cat("Fluffy","Purr") >>> bf = cat1.talk # function Cat.talk bound to cat1 >>> bf > >>> bf() My name is ... Garfield I am a feline from Earth Mammal sound: Meow <__main__.Cat object at 0x00A83D10> >>> uf = Mammal.talk # unbound function >>> uf In the rare situation where we need to explicitly change the current instance: >>> __self__ = cat2 >>> uf() Mammal sound: Purr >>> Python's syntax does violate the "Explicit" rule, but it seems in this case the "Practicality" rule over-rides. By making the function bound or unbound, depending implicitly on the type of the object before the dot, Python has avoided the need for an explicit binding syntax. If we could come up with an explicit binding syntax that was not a burden on either readability or clarity, then I would vote for a change. To summarize the current proposals: Prothon: $var # var is attribute of self ^var # var is an attribute of a proto of self obj.func() # func is an attribute of obj and bound to obj obj$func() # func is an attribute of obj and bound to current self x = obj.func # x is bound method of func attribute of obj and obj x = obj$func # x is bound method of func attribute of obj and self x = obj.attr(func) # x is unbound func Python 3: bf = cat1.talk # bound function uf = Cat.talk # unbound function bf() # call a bound function uf() # call unbound function with current __self__ __self__ = cat2 # change __self__ ... rarely needed uf() # call with cat2 The "Python 3" proposal follows current Python syntax except for the use of a global __self__ variable instead of a special first argument. -- Dave From mark at prothon.org Fri Apr 23 04:24:42 2004 From: mark at prothon.org (Mark Hahn) Date: Fri, 23 Apr 2004 01:24:42 -0700 Subject: Why we will use obj$func() often References: <84Uhc.22278$dZ1.5087@fed1read04> <8AWhc.23114$dZ1.11070@fed1read04> Message-ID: Mike C. Fletcher wrote: > Fascinating. Most users never even notice this stuff, let alone getting > so worked up about it that they start a whole separate language ;) . Well, I do exaggerate a bit :) > super(), in other words, is a practical solution to avoiding the > explicit dependencies that crop up when you directly reference a > super-class. Prothon also has a seperate super operator ( ^ ). ^var means to get the first attrbute named var from a prototype of self instead of self itself. It uses the ordered list of prototypes like Python does. So ^func() does what you are referring to. Internally in the interpreter I have the full Python super function almost exactly. It's no coincidence. You need that to make inheritance work. I can bring it out for the Prothon user, but I originally designed prothon with keywords and symbols, not functions, something I'm taking a lot of heat for now. > Sure, the magic you sprinkle through your system is part of its > flavour > and character, that character is how languages sell themselves. > Though honestly, if someone seriously came up to me and said: > > "Switch to Frobnaz, it has explicit syntax for referencing a > superclass rather than that archaic explicit invocation stuff in > Python" > > I'd probably dismiss them out of hand as being so totally out of touch > with reality as to be not worth the effort of listening (well, not > really, I *try* not to dismiss people out of hand no matter how crazy > they are). Addressing a few of Python's warts is *not* going to make > the world beat a path to your door. You've stretched my "one more thing to pitch" statement to the extreme statement of "switch to this because of this one thing". Of course one isn't going to care about one thing. > Your language *will* have it's own warts, that's a simple reality, > pointing out that you don't have the same warts *in the same places* > as another language is not a compelling argument for switching. For > instance, I would almost certainly consider the fishHeight$Somewhere() > syntax to be a wart ;) You may very well be right. I'm trying to get it to fit into an overall scheme, but it may not work. By itself it definitely is a wart. Don't forget that you are looking at it in the context of Python. It is being put into a different language with different problems. My biggest problem right now is stupid aesthetics. I have to decide where to place Prothon on the continuum between lisp and perl. When I crossed the line and added $ for self people screamed bloody murder that it looked like Perl. Before when I had a period for self they thought it looked great. I can't believe how much they care about something so silly. Anyway, thanks very much for your input. I'm sorry if you wore out your keyboard. Luckily the prices have really come down :) From simoninusa2001 at yahoo.co.uk Tue Apr 6 16:31:52 2004 From: simoninusa2001 at yahoo.co.uk (simo) Date: 6 Apr 2004 13:31:52 -0700 Subject: GUI Frameworks in Python? References: Message-ID: <30260531.0404061231.308898e2@posting.google.com> I've found that on 3 PC's (1.6GHz/7200rpm/XP Pro, 500MHz/4200rpm/2K Pro, dual 400MHz/5400rpm/2K Pro) it always takes 3 seconds to get to the demo splash screen, on Python 2.3.3 and wxPython 2.4.2.4/2.5.1.5 On the dual PII/400, Hugh's script takes repeatedly about 1.125s, unless you run it from within IDLE, whereby the first run takes about 1.7s and then it takes 0.03s, so I guess IDLE caches the compiled version (I've see this before). It doesn't seem to be wxPython specific either, I've got similar wx/Qt/Tk apps that seem to take the same time to start. This leads me to believe it's the Python interpreter starting up that takes a specific amount of time (does it wait or something odd?). Unless it's so heavily optimised that a processor 3x as fast makes no speed difference! ;o) From peter at engcorp.com Thu Apr 1 21:31:18 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 01 Apr 2004 21:31:18 -0500 Subject: Richards bench benchmark In-Reply-To: <6748553f.0403302317.4595844@posting.google.com> References: <6748553f.0403291446.27fb7b93@posting.google.com> <6748553f.0403300836.744e3e22@posting.google.com> <6748553f.0403302317.4595844@posting.google.com> Message-ID: <406CD076.9000408@engcorp.com> Duncan Lissett wrote: > Peter Hansen wrote: >>I'd implement it in Python for kicks, but I'm not sure how I'd know >>whether my version was doing the right thing. Are there any tests >>for it? Ways of ensuring the output is correct? > > Martin Richards original spec and debug/trace information is reposted > here: > http://www.lissett.com/ben/com/benchspec.htm Okay, as a starting point I've turned the "gold output" part of that spec into a first acceptance test, and have a shell bench.py which runs but fails ('pass' statements tend to do that a lot during TDD). The code should be available with svn co svn://fortress.engcorp.com/public/bench I don't really expect anyone to check it out at this stage, but if you happen to have a free moment, I wouldn't mind knowing if subversion is properly visible through my firewall. -Peter From peter at engcorp.com Thu Apr 29 22:20:57 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 29 Apr 2004 22:20:57 -0400 Subject: Is classless worth consideration In-Reply-To: <69cbbef2.0404291209.7a98a799@posting.google.com> References: <69cbbef2.0404290259.fd8d71c@posting.google.com> <69cbbef2.0404291209.7a98a799@posting.google.com> Message-ID: has wrote: > Peter Hansen wrote in message news:... > >>has wrote: >>>Well, as far as Python itself is concerned, it'd go a long way in >>>eliminating the hideously baroque and increasingly brittle OO model it >> >>I find it especially hard to find the enthusiasm to read past >>the highly inflammatory phrase "hideously baroque". I had to >>do a double-take just to confirm that the poster is indeed >>talking about Python. > > Compared to C++, I expect it's a real breath of fresh air. But > compared to how something like Self does OO, it is indeed hideously > baroque. Oh, now you're qualifying the statement. In comparison to something less baroque, it's baroque. Fair enough... But at least you say what you think. That counts for something. :-) -Peter P.S. You've got an art background, I've got an engineering background, neither of us has a CS background. Maybe that ought to tell us how well we're likely to communicate about software and we can just stop here. ;-) From anton at vredegoor.doge.nl Fri Apr 30 13:06:02 2004 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Fri, 30 Apr 2004 19:06:02 +0200 Subject: [module] vector.py Message-ID: <40928802$0$144$3a628fcd@reader2.nntp.hccnet.nl> http://home.hccnet.nl/a.vredegoor/vector/ A highly experimental Vector and StringVector implementation. The objective is to provide an alternative for dictionary type objects which has inherent order and where "substructures" can be manipulated more efficiently. Your comments please. Anton From newsgroups at jhrothjr.com Sat Apr 10 18:39:01 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 10 Apr 2004 18:39:01 -0400 Subject: Python is the best and most popular general purpose scripting language; the universal scripting language References: Message-ID: <107gttk8j6or775@news.supernews.com> "Roy Smith" wrote in message news:roy-22B4DA.18282210042004 at reader1.panix.com... > rstephens at vectron.com (Ron Stephens) wrote: > > Python is the best and most popular general purpose scripting > > language. > > Which raises the question, exactly what makes something a "scripting" > langauge? When I tell people I do Python, they often say something > like, "that's a scripting language, right?". My usual response is > something along the lines of "Well, I suppose that depends on who you > ask" and I'm not sure what to say after that. > > So, what makes something a "scripting language" as opposed to a > "programming language"? The distinction isn't "scripting" versus "programming" language, it's "scripting" versus something that doesn't really have a name. Scripts are executed from the top down once. In other languages (such as Java and C++) there's a designated starting point (main()) that the compiler locates. Python is a scripting language because each module is executed from the top down as its loaded. As far as being most popular, I think Perl is still well ahead of it, and it's still well ahead of Ruby. I don't have a good feel for where either PHP or TCL stand in the "most popular" sweepstakes. John Roth From __peter__ at web.de Tue Apr 6 18:02:11 2004 From: __peter__ at web.de (Peter Otten) Date: Wed, 07 Apr 2004 00:02:11 +0200 Subject: Tkinter radiobutton border References: Message-ID: Mike wrote: > I've placed a radiobutton on a green panel. The background of the > radiobutton is also green. Borderwidth is 0 and relief is FLAT. I > still get a thin gray border around the radiobutton. What is this > border, and how can I get rid of it. Thanks. Try highlightthickness=0 Peter From fma at doe.carleton.ca Tue Apr 13 16:41:31 2004 From: fma at doe.carleton.ca (Fred Ma) Date: 13 Apr 2004 20:41:31 GMT Subject: Once-only evaluation of default parameter values function definitions References: <407B79D7.424F65A1@doe.carleton.ca> <107n2g6q9an672b@corp.supernews.com> <407BB8F5.E694AA49@doe.carleton.ca> Message-ID: <407C5074.E6E6B962@doe.carleton.ca> Mike, Shalabh, Thanks for the confirmations and pointer to more info on the python paradigm. Regarding the progress in one day, I was actually looking at another data munging language on the first half of that day, but was a bit concerned about the intricacies of the syntax, and the medium term impact on development time. Programs start to get more involved when I'm trying to "reconstitute" textual circuit design info that crosses several physical lines, spanning several files, so I would like the code to be very clear about exactly what is happening without having several info terminals open. I'm actually surprised that I haven't gotten working code yet, as I thought I would just "fall into" this cleaner syntax. Kind of worried, too, since it seems there's more conceptual infrastructure to establish before creating useful code, though I'm sure not all of it is needed to do the data munging I need. Maybe the documentation is "top-down" rather than "bottom- up". Actually, that's not fair either, there's lots of simple, clean examples of small tasks. Knowing what is necessary to know is just always clearer in hindsight. Fred -- Fred Ma Dept. of Electronics, Carleton University 1125 Colonel By Drive, Ottawa, Ontario Canada, K1S 5B6 From peter at engcorp.com Tue Apr 20 18:13:12 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 20 Apr 2004 18:13:12 -0400 Subject: if (__name__ == '__main__'): main(sys.argv[1:]) In-Reply-To: References: Message-ID: Eli Stevens (WG.c) wrote: > I have a question about proper Python style when it comes to having a main > function in a module. I'm fairly new to Python - a few months of > very-part-time tinkering (lots'o'Java at work, shrug); my apologies if this > has been hashed out before. Random Googling didn't enlighten me, so instead > I'll ask here. :) > > if (__name__ == '__main__'): > main(sys.argv[1:]) vs. > if (__name__ == '__main__'): > main() As I think you suspected, "good style" is best determined in this case by testability. Go with the former and you aren't likely to regret it. -Peter From claird at lairds.com Thu Apr 22 10:21:37 2004 From: claird at lairds.com (Cameron Laird) Date: Thu, 22 Apr 2004 14:21:37 -0000 Subject: This is very simple question References: <108dbd1aftmkc48@corp.supernews.com> <4087a0f6$0$25552$afc38c87@news.easynet.fr> Message-ID: <108fl7h8oocmm5c@corp.supernews.com> In article <4087a0f6$0$25552$afc38c87 at news.easynet.fr>, Nicolas Lehuen wrote: . . . >You can also use divmod : > >def decompose(i,base=2): > result=[] > factor=1 > while i>0: > i,r=divmod(i,base) > if r: > result.append(r*factor) # or result.extend([factor]*r), >depending on style > factor*=base > return result.reverse() # if you really want it reversed . . . I agree that divmod() improves the algorithm, and thank you for pointing that out. I'm reasonably certain that the return value of reverse() is not what you believe it to be. -- Cameron Laird Business: http://www.Phaseit.net From lbates at swamisoft.com Tue Apr 6 18:23:50 2004 From: lbates at swamisoft.com (Larry Bates) Date: Tue, 6 Apr 2004 17:23:50 -0500 Subject: Registry Key extraction and migration References: <7d7e723a.0404050927.12611c86@posting.google.com> Message-ID: Ed, Take a look at _winreg module. It supports everything you are looking for. You were not perfectly clear on what keys/values you needed so the code below is a guess... Larry Bates Syscon, Inc. import _winreg regkey='software\old_lcoation' # Copied your spelling value_name="XXX" key=_winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, regkey) value=_winreg.QueryValueEx(key, value_name)[0] new_value="YYY" key=_winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, regkey, 0, _winreg.KEY_SET_VALUE) _winreg.SetValueEx(key, value_name, 0, _winreg.REG_SZ, new_value) "ed" wrote in message news:7d7e723a.0404050927.12611c86 at posting.google.com... > Hi I want to write a tool to do the following: > 1. extract and display registry keys under abritrary starting point, > for example: > source are: HKey_Local_machine\software\old_lcoation or > HKey_current_user\software\XXX\YYY > > a) then, I can specify where the Keys can be copied and compare the > new location to the new location. For example: destination are: > HKEY_local_mahcine\software\New_location. > > b) if the keys are not there flags error message > > how canI do that? From dmq at gain.com Fri Apr 23 16:01:10 2004 From: dmq at gain.com (David MacQuigg) Date: Fri, 23 Apr 2004 13:01:10 -0700 Subject: Why we will use obj$func() often References: <84Uhc.22278$dZ1.5087@fed1read04> <8AWhc.23114$dZ1.11070@fed1read04> <40883BFE.B381518A@alcyone.com> <27_hc.23801$dZ1.2716@fed1read04> <40887145.789A2FE8@alcyone.com> <7cki80hj976bia36lhf9er97v073o1pqvm@4ax.com> Message-ID: On Fri, 23 Apr 2004 11:21:16 -0700, "Mark Hahn" wrote: >"David MacQuigg" wrote >> Adding syntax or making changes just because it allows you to do >> something that can't be done in Python is not good. We have to look at >> *use cases* for these features and compare them to a well-written >> Python equivalent. Then, we can see if the benefit is worth the extra >> syntax. We spend far to much time debating syntax without a clear >> benefit in mind. Show us a nice closure. > >The benefits of closures are well known. I'll give you the canonical >example, but I'm sure textbooks can give you many more (by the way, Python >cannot do this): Sorry for my ignorance, oh master. :>) ># tested example >def getFunc(): > counter = 0 > def count(): > &counter += 1 > print &counter > return count > >c = getFunc() >c() # prints 1 >c() # prints 2 >c() # prints 3 Here is how I would do it in Python: class Accumulator: def __init__(self): self.count = 0 def bump(self): self.count += 1 print self.count c = Accumulator() c.bump() c.bump() c.bump() It took me a few minutes to understand what the "closure" was doing. The Python code is more clear ( at least for anyone who will have to be working with classes anyway). There is nothing new to learn. Functionality = same Size of Source Code = same Transparency = Python wins -- Dave P.S. A sincere apology for my gibe above. I couldn't resist. :>) From andrew.henshaw at gtri.gatech.edu Fri Apr 2 13:29:27 2004 From: andrew.henshaw at gtri.gatech.edu (Andrew Henshaw) Date: Fri, 2 Apr 2004 18:29:27 +0000 (UTC) Subject: Making the Zen of Python more useful References: <106qp0uivlefo40@corp.supernews.com> <-5ydnTEmxfuZHvDdRVn-iQ@powergate.ca> Message-ID: In article , peter at engcorp.com says... >Maybe (in the spirit of a couple of days ago) what is needed is >*adverbial* keywords. Then you could do: > > import this quietly > >One could expand on that idea as well, such as to satisfy those who >are overly obsessed with performance issues: > > import wxPython rapidly > >or those with intermittent problems in their own code: > > import flakymodule reliably > :-) I think I could make use of all of those examples. -- Andy From __peter__ at web.de Sun Apr 4 10:23:40 2004 From: __peter__ at web.de (Peter Otten) Date: Sun, 04 Apr 2004 16:23:40 +0200 Subject: Working with a list in a more ?pythonic? way References: <20040404124833458+0200@news.rhrz.uni-bonn.de> Message-ID: Nickolay Kolev wrote: > I was thinking about using "reduce", but that would not work as the > input and output of the function I would use are different (string input, > integer output). reduce() does not impose such a restriction. Optimized for minimal robustness and readability (but working, I hope, and functional in the _narrow_ sense): def calcScore(phrase): return reduce( lambda (sigma, last), i: (sigma + soundScoreMatrix[last][i], i), map(lambda c: ord(c)-65, phrase[1:]), (0, ord(phrase[0])-65))[0] Seriously, trying to apply a particular style does often result in bad design. Either go with Scott Daniels' approach or debug your initial idea to something that works. Both ways are more "pythonic" than the above. Peter From thorsten at thorstenkampe.de Thu Apr 29 06:59:03 2004 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Thu, 29 Apr 2004 12:59:03 +0200 Subject: outline-style sorting algorithm References: Message-ID: * Delaney, Timothy C (Timothy) (2004-04-29 02:52 +0100) > Thorsten Kampe wrote: >>>>>> foo >>> ['1.0', '1.0.1', '1.1.1', '1.2', '1.9', '1.10', '1.11', '1.20', >>> '1.20.1', '1.30'] >>>>>> foo.sort() >>>>>> foo >>> ['1.0', '1.0.1', '1.1.1', '1.10', '1.11', '1.2', '1.20', '1.20.1', >>> '1.30', '1.9'] >>> >>> Obviously 1.20.1 should be after 1.9 if we look at this as >>> dot-delimited integers, not as decimal numbers. >> >> You need some general approach to avoid the DSU thing: >> >> def funcsort(seq, func): >> """ sort seq by func(item) """ >> seq = seq[:] >> seq.sort(lambda x, y: cmp(func(x), func(y))) >> return seq >> >> funcsort(foo, lambda x: map(int, x.split('.'))) > > I've seen you give this advice several times, today, and IMO it's > completely wrong. > > DSU is *exactly* what you want to do. If you want to wrap it inside a > general function, that's fine, but DSU is in almost all cases preferred > to passing a comparison function - it's much faster. My advice was to use a more general approach like 'funcsort' to avoid reiventing the wheel for every problem. DSU is okay for funcsort. > def sorted (seq, cmp=None, key=None): What is 'cmp=None' for? > """ sort seq by func(item) """ > if key is None: > seq = seq[:] > else: > seq = [(key(e), i, e) for i, e in enumerate(seq)] > > seq.sort(cmp) Are you passing a second comparison function? And if, isn't that the same as I did and to which you said "preferred to passing a comparison function"? Are you shadowing the builtin cmp function? > if key is None: > return seq > else: > return [i[-1] for i in seq] What is 'key=None' for? Is that for speeding up if someone wants to pass the indentity function (f(x)=x; lambda x: x)? > Note that Python 2.4 will have DSU as a built-in idiom to `list.sort` > i.e. `list.sort(key=func)` but will be somewhat more efficient than the > above. Likewise there will be a new builtin `sorted` which has exactly > the same semantics as the above - it is stable, and it does not ever > compare the actual value if a key function is supplied - only the key > value (the above also compares the position, but that's an > implementation detail and has no visible effect). If it has no visible effects than it would be useless. In my opinion it has the effect that two items that have the same func(x) stay in the same position as before. Is that desirable? Was that your goal? >>> sorted([4, 2], None, lambda x: x % 2) [4, 2], but [2, 4] if the index was omitted Thorsten From mwilson at the-wire.com Mon Apr 12 11:00:36 2004 From: mwilson at the-wire.com (Mel Wilson) Date: Mon, 12 Apr 2004 11:00:36 -0400 Subject: Is there a boolean(somestring) equivalent of int(somestring). References: Message-ID: In article , "Vineet Jain" wrote: >Thanks for the code suggestion. > >>From what I've read, most people (including me) are attracted to Python >because of how natural it is. Give that is a high priority for the language >designers: > >How can anyone argue that > >bool('false') = True > >is more natural (and what you would expect) than > >bool('false') = False bool("False") == True because "False" isn't a null string. eval ("False") == False because False is the name of the object named False, and eval exists in order to take strings and execute them as Python code, which includes referring to named objects. What did "Vineet Jain" have for lunch? Regards. Mel. From skip at pobox.com Fri Apr 2 14:50:10 2004 From: skip at pobox.com (Skip Montanaro) Date: Fri, 2 Apr 2004 13:50:10 -0600 Subject: PLEASE STOP!!! In-Reply-To: References: <95aa1afa.0404010352.80de14e@posting.google.com> <406C40E8.10209@prescod.net> Message-ID: <16493.50162.306997.216459@montanaro.dyndns.org> Josiah> While I (generally) dislike april fools pranks, after reading Josiah> this I gave it a shot. Low and behold, it works. Josiah> Perhaps you should have released it on April 4 or so, just to Josiah> not be accused of trying to dupe people. Nah, that's what makes it such a great AFJ. Over-the-top *and* it's real. Josiah> Of course, I suppose the prank is that people think it is a Josiah> prank, when in fact, is actually truth. There ya go. Skip From rogerb at rogerbinns.com Mon Apr 26 20:30:14 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Mon, 26 Apr 2004 17:30:14 -0700 Subject: Is Perl *that* good? (was: How's ruby compare to it older bro References: <108qcobc4m8g972@corp.supernews.com> Message-ID: Roy Smith wrote: > What Tcl lacks in power and expressiveness, it > makes up for in simplicity of use, quick learning curve, and ease of > embedding/extending. I've written a lot of Tcl code, and never used > either Expect or Tk. That was how I originally came to Tcl. Never used Expect either (although some colleagues did) and never did Tk (until Tkinter!) Tcl does have power and expressiveness. It is one of the few languages where you can trivially define your own control structures. Object orientation was added without changing the language (almost SmallTalk like). Tcl also had a shot at stardom. I added it to the Mosaic browser where it was used in a similar capacity to JavaScript today. Details are in the proceedings of the 2nd WWW conference. (The audience were in awe of a demo that printed an entire book based on following the rel links in web page headers, got everything in the right order, loaded the pages and printed). To solve the same problems, Netscape invented yet another language and put "marketing flavour of the day" in front, blessing us with Javascript. I really wish Tcl had won that one. Roger From rmanx at gmx.de Thu Apr 8 10:36:56 2004 From: rmanx at gmx.de (Robert) Date: Thu, 8 Apr 2004 16:36:56 +0200 Subject: if 'hallo' in ['hallooo','halloooooooo'] problem References: Message-ID: Sorry!!!! the example I gave I did not check. Of course it works. The problem is somewhere else. My programm was doing this: if 'hallo' in 'hallooooo': .... instead of (what I was thinking): if 'hallo' in ['hallo']: .... so , everything is fine. I did not see, that the variable holding the second string is a string instead of a list. Thanks for your replies!!!!!! "Robert" wrote in message news:c53k55$mm2$1 at news.mch.sbs.de... > Hi, > > I have a little problem and mybe one of you has got the solution. > I would like to check if a string is in a list of strings. > The following returns true: > if 'hallo' in ['halloooo','hallooooooooo']: > pass > > but I want to check if the string is exactly equal to any string in the > list. > How can I do this without the need to do something like this: > def stringInList(self,string,list): > for oneStr in list: > if string == oneStr: > return 1 > return 0 > > > Thank you in advance, > > Robert > > From rogerb at rogerbinns.com Tue Apr 6 13:53:23 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Tue, 6 Apr 2004 10:53:23 -0700 Subject: Python and USB References: <407162b0$1@news.vo.lu> <5ns8k1-3q4.ln1@home.rogerbinns.com> <40727912$1@news.vo.lu> Message-ID: > it was exactly the thing i'am was looking for. > Now i only have to get my device running. Under > C i was allready using the libusb, and so this code should > be easily to be adapted. Yes, you get a straight wrapping of libusb, as well as a more Pythonic interface (in libusb.py and usb.py respectively). There are some issues unresolved, mainly due to the APIs that libusb exposes. For example it makes no mention of being thread safe (my wrapper does release the GIL around read/writes) and the lists of busses/devices/configs are freed and reallocated if you call usb_find_busses/usb_find_devices. Consequently the Python objects could be pointing at freed memory. Roger From ramen at lackingtalent.com Wed Apr 21 12:28:21 2004 From: ramen at lackingtalent.com (Dave Benjamin) Date: Wed, 21 Apr 2004 16:28:21 -0000 Subject: CamelCase versus wide_names (Prothon) References: <6ee58e07.0404192141.2229efd6@posting.google.com> <1082549174.163233@ns.topconrd.ru> Message-ID: In article <1082549174.163233 at ns.topconrd.ru>, Sergei Organov wrote: > Gerrit writes: > >> Mark Hahn wrote: >> > "William Park" wrote ... >> > >> > Someone else already mentioned this >> > > > problem: >> > > > >> > > > smtp_message <-> SMTPMessage <-> SmtpMessage >> > >> > If you consider the capital letter as just a replacement for the underbar, >> > then the answer is definitely smtpMessage. I don't see any problem. >> >> SMTP is an acronym. Because it's an acronym, it's most often spelled in >> allcaps. > > Yet nobody mentioned that we don't have lower-case digits ;) > > usb201_driver <-> usb201Driver <-> usb2??Driver Hey, as long as Perl is adding French quotes to the language, why don't we dig around in Unicode for some lower case numerals? I bet you could find some if you looked hard enough, in between the Klingon alphabet and Dingbats 47 perhaps... =) -- .:[ dave benjamin: ramen/[sp00] -:- spoomusic.com -:- ramenfest.com ]:. : please talk to your son or daughter about parametric polymorphism. : From ncom01/srv/olympus-sg at olympus.com.sg Thu Apr 1 22:13:40 2004 From: ncom01/srv/olympus-sg at olympus.com.sg (ncom01/srv/olympus-sg at olympus.com.sg) Date: Fri, 2 Apr 2004 11:13:40 +0800 Subject: File blocked - ScanMail for Lotus Notes --> Re: Your picture Message-ID: ScanMail has removed an attachment during a real-time scan of the mail traffic. Please zip your file and resend, sorry for any inconvenience Date: 04/02/2004 11:13:40 AM Subject: Re: Your picture Virus: File: your_picture.pif From: python-list at python.org To: ostmaster at olympus.com.sg Action: Blocked by Filter Rules; Scanned by ScanMail for Lotus Notes 2.6 with scanengine 7.000-1004 and patternfile lpt$vpn.847 From moosebumps at moosebumps.com Sun Apr 18 16:16:50 2004 From: moosebumps at moosebumps.com (Moosebumps) Date: Sun, 18 Apr 2004 20:16:50 GMT Subject: python module for interactive web charts References: Message-ID: Thanks, that looks great -- just what I'm looking for! As a note, it's nice that all the figures are anti-aliased -- even a lot of commercial packages that I looked at don't have that. MB "John Hunter" wrote in message news:mailman.743.1082312877.20120.python-list at python.org... > >>>>> "Moosebumps" == Moosebumps writes: > > Moosebumps> Is there anything that is made to generate web pages > Moosebumps> which have charts similar to the yahoo finance stock > Moosebumps> charts? Not looking to graph stocks specifically, but > Moosebumps> anything. I like how you can zoom on each axis, and > Moosebumps> maybe click to see numerical values and such. > > Moosebumps> If there isn't anything in Python, what do people > Moosebumps> typically use for that kind of stuff, or is it all > Moosebumps> hand-rolled? > > matplotlib is a 2D plotting library that supports a number of plot > types - http://matplotlib.sourceforge.net/screenshots.html. The > library can generate plots either to GUIs or just generate images if > you want to use it in a web application server. See this link > http://matplotlib.sourceforge.net/faq.html#APPSERVER for more > information about using matplotlib in a web server. There are > interactive navigation tools for panning and zooming, etc. > > The next release 0.53 due out early next week will have a lot of > support for making date plots, using python datetimes, mx.Datetime, or > other, with a hodge podge of minor and major date tick locators and > formatters. There is also a financial module in the works which will > be finished soon for candlestick plots and the like. > > If you're interested in getting announcements when these features are > ready, you may want to join the mailing list > http://lists.sourceforge.net/mailman/listinfo/matplotlib-users. > > Cheers, > John Hunter > > From alexanro at stud.ntnu.no Wed Apr 14 12:20:40 2004 From: alexanro at stud.ntnu.no (Alexander Rødseth) Date: Wed, 14 Apr 2004 18:20:40 +0200 Subject: Pygame References: Message-ID: > pygame (and sdl) are lgpl licensed and as such they are not > commercial-friendly. Good point. Thanks. :) From claird at lairds.com Sat Apr 3 18:49:21 2004 From: claird at lairds.com (Cameron Laird) Date: Sat, 03 Apr 2004 23:49:21 -0000 Subject: emergent/swarm/evolutionary systems etc References: <2de080a12a9c6c488149f4b031bb46be@news.teranews.com> Message-ID: <106ujc1frj9o889@corp.supernews.com> In article , Peter MacKenzie wrote: >I think then that I might stick with spreadsheets as far a possible. Do you >know of any simulation programs that might be more suited? Also, how would >you extract data from a spreadsheet for use in another program? I'm not >familiar with means of linking spreadsheets to external applications, though >I don't doubt that it can be done. > > Software people *constantly* talk about "means of linking ... to external applications"; it's one of our obsessions, for reasons best left to another time. Here's a way you can practice thinking about it: a spreadsheet can write its "answers" to a file--just a simple document, the sort you might write as a human, yourself. Another program can read that file. That establishes communication between the spreadsheet and the other program. Mission accomplished. Spreadsheets typically have *dozens* of distinct ways of talking to "outsiders", although that's often apparent only to software specialists. -- Cameron Laird Business: http://www.Phaseit.net From jcarlson at uci.edu Mon Apr 26 01:25:52 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Sun, 25 Apr 2004 22:25:52 -0700 Subject: A new OS In-Reply-To: <408c8baa$1@news.unimelb.edu.au> References: <107k441hitt2ld9@corp.supernews.com> <408c8baa$1@news.unimelb.edu.au> Message-ID: > Is it possible to program a python virtual machine into an EEPROM > (eletrically erasable programmable read-only memory) and then set the > BIOS to access this VM as the bootloader? So in directly, we have a very > low level python VM in the system when it boots up...... Two key issues: Memory; depending on your EEPROM, you may or may not be able to fit a Python VM. OS Services; traditionally, Python has relied on the operating system for various services that are important to a large number of nontrivial applications (sockets, filesystem interfaces, malloc, etc.) - Josiah From fma at doe.carleton.ca Thu Apr 15 20:14:33 2004 From: fma at doe.carleton.ca (Fred Ma) Date: 16 Apr 2004 00:14:33 GMT Subject: Kuhlman's tutorials pretty good References: <407E1E20.D0216E92@doe.carleton.ca> <200404150710.i3F7A0Hw010978@locutus.doe.carleton.ca> <407E40CC.C06FA9E3@doe.carleton.ca> Message-ID: <407F2565.4A3BF11A@doe.carleton.ca> Dave Kuhlman wrote: > > Whoa! How did all that happen? I believe I tried one too many > fancy things in TeX/LaTeX, which is definitely not my native > language. > > I've simplified a few things in the source document, and I believe > that these errors are fixed, now. > > Thanks for pointing this out to me. Also, thanks for the > compliments. That's hilarious. Talk about shocking feedback. Thanks for the fix, and for creating the tutorials in the first place. By the way, it seems there are two different sections at referring to tutorials for programmers: http://www.python.org/doc/Intros.html http://www.python.org/topics/learn/prog.html Wouldn't it be good if both included Dave's tutorials? Fred P.S. Thanks to Kirby and AMK for pointing out the 2nd location. -- Fred Ma Dept. of Electronics, Carleton University 1125 Colonel By Drive, Ottawa, Ontario Canada, K1S 5B6 From timr at probo.com Mon Apr 19 00:37:01 2004 From: timr at probo.com (Tim Roberts) Date: Sun, 18 Apr 2004 21:37:01 -0700 Subject: module not callable - why not? References: <107dras2heahcb6@news.supernews.com> <8ef9bea6.0404122025.36efc84e@posting.google.com> <7xsmf1fxd9.fsf@ruckus.brouhaha.com> <8ef9bea6.0404180823.7a3bc189@posting.google.com> Message-ID: Josiah Carlson wrote: > >Truth be told, I've used singletons before, but only once. Is that a pun? -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From gomoSINSPAM at datafull.com Mon Apr 19 17:29:49 2004 From: gomoSINSPAM at datafull.com (=?iso-8859-1?q?Gonzalo_Sainz-Tr=E1paga_=28GomoX=29?=) Date: Mon, 19 Apr 2004 18:29:49 -0300 Subject: Problems using modulo References: Message-ID: On Mon, 19 Apr 2004 17:51:53 +0200, Diez B. Roggisch wrote: > AFAIK modulo is mathematically only properly defined on > integers - so you should stick to them. Modulo is fine for any number (even irrational ones). For example, acos(sqrt(3)/2) is congruent to pi/6 mod 2*pi. Technically, two numbers are congruent mod n when the rest of the division by n is the same, it doesn't matter whether n is an integer or not. From "schwartz+ at usenet " at bio.cse.psu.edu Tue Apr 13 23:12:39 2004 From: "schwartz+ at usenet " at bio.cse.psu.edu (Scott Schwartz) Date: 13 Apr 2004 23:12:39 -0400 Subject: print u"\u0432": why is this so hard? UnciodeEncodeError References: <16505.58626.39783.581506@montanaro.dyndns.org> Message-ID: <8gekqrz1zs.fsf@galapagos.bx.psu.edu> Skip Montanaro writes: > I run xterms under XDarwin. I don't think the default encoding is different > than xterms in any other X environment. If I execute These days you can invoke it as uxterm to force it into utf-8 mode. From newsgroups at jhrothjr.com Thu Apr 15 11:04:15 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Thu, 15 Apr 2004 11:04:15 -0400 Subject: Difficulty Finding Python Developers References: <65cbc3dd.0404140641.3501fde8@posting.google.com> <65cbc3dd.0404141018.36d9d4ce@posting.google.com> Message-ID: <107t94otjnfs96c@news.supernews.com> "Ville Vainio" wrote in message news:du7pta9l4s0.fsf at amadeus.cc.tut.fi... > Offering some comebacks in advance... > > >>>>> "Peter" == Peter Hansen writes: > > >> Mention that when you do find a > >> Python programmer he'll probably be better than your average perl or > >> Java programmer. > > Peter> And here I would ask, "Why do you say that? If there are > Peter> so few of them around, how could anyone know whether > Peter> they're better or worse? And wouldn't the best programmers > > I guess the braindeadness of perl can be argued as an indication of > the quality of programmers - if the Perl people are unable to see how > much the language stinks, they might be lacking in other areas of > programming also. It's not a problem of being brain dead - it's a problem that Perl's philosophy encourages "cowboy coders" that enjoy the technical wizardry of doing the same things different ways. Python's philosophy encourages you to learn what you need quickly so you can pay attention to the job. > Java OTOH is the lowest common denominator, pretty much everyone knows > it, which drags the average quality down. I thought that was COBOL. The arguement against Java is very simple: It takes twice as much coding (that is, keystrokes) to do something in Java as it does in Python. There is no evidence that the additional *security* from static typing is worth the additional cost of the coding effort, and there is mounting evidence (but no credible studies I'm aware of) that it isn't. John Roth > -- > Ville Vainio http://tinyurl.com/2prnb From timr at probo.com Fri Apr 2 20:14:23 2004 From: timr at probo.com (Tim Roberts) Date: Fri, 02 Apr 2004 17:14:23 -0800 Subject: Why '==' ?? References: <8089854e.0403300510.1971c24@posting.google.com> <1080653301.114229@master.nyc.kbcfp.com> Message-ID: Vrai Stacey wrote: > >I would assume it's because most people come to Python having programmed >other languages. In most other languages (excepting stuff like >Pascal/Modula-2/etc ...) '=' is used for assignment and '==' for >equality. Interesting you would put it that way. I would have guessed that "most" was not accurate. "In the languages most programmers use", yes, but not "In most other languages". C, C++, Java, C#, and Javascript all use = for assignment, == for compare-equal. Basic, VBScript, Cobol and SQL use = for both. Pascal, Modula-X, Algol, Ada, Oberon, and Eiffel use := for assignment, = for compare-equal. Fortran uses = for assignment and .EQ. for compare-equal. APL uses squiggle quad bang hack splat over splat dot splat. LISP uses -- well, no one really knows what the actual syntax is for LISP. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From joe at notcharles.ca Thu Apr 1 10:36:12 2004 From: joe at notcharles.ca (Joe Mason) Date: Thu, 01 Apr 2004 15:36:12 GMT Subject: Prothon Prototypes vs Python Classes References: <569c605ld1cj8fc1emolk08ete0s1prls1@4ax.com> <69cbbef2.0403280928.438d194f@posting.google.com> <69cbbef2.0403311324.32837704@posting.google.com> Message-ID: In article , Glenn Andreas wrote: >> There certainly is a standard syntax for making objects. I need to know >> how to "duplicate an existing object". Is it "obj.dup()"? >> "obj.clone()"? "duplicate obj"? Most probably, the language (or >> standard library) defines one of these, and I expect most objects to be >> duplicated in the same way. >> > It can be a bit more subtle than that in a prototype based system, since > there are two things that are different, but have nearly identical > results, but could both be considered "duplicate an object". > > In general, you don't want to _duplicate_ the object, but rather use > that object as "prototype" for the new object. > > First, you can make a new object that has all the same > slots/properties/attributes as the first object - let's just call that > "clone" for now (and we'll assume single inheritence, via a slot called > "__parent") > and we'll make the second object that has first object as the __parent > (and we'll pretend that the syntax is "new " This is certainly how Self does it. Other prototype based languages (such as Io) do not make this distinction. In Io, you use "clone" to make a new object whose parent is the object it was cloned from, and that's it. Joe From insert at spam.here Thu Apr 22 10:25:18 2004 From: insert at spam.here (Doug Holton) Date: Thu, 22 Apr 2004 09:25:18 -0500 Subject: python web programming / CMS In-Reply-To: References: Message-ID: news.telenet.be wrote: > Hi, > > i'm looking at python to do programming for the new intranet > here at the company. I'm looking at plone/zope also. > Before, I've used jsp for webprogramming but i'm considering > python for this. > One thing that isn't clear to me is if it's possible to include python > code in a html page like you would do with jsp and then have zope > "translate" that to html. With jsp, one could use an apache/tomcat > combo to accomplish this. > If one can't include python in html, is Zope the only alternative and > how does code look like then? > > Thanks > > Check out http://www.python.org/cgi-bin/moinmoin/WebProgramming for all the python options. I'd recommend checking out mod_python. You can embed Python in HTML using mod_python's PSP. From claird at lairds.com Tue Apr 6 21:55:43 2004 From: claird at lairds.com (Cameron Laird) Date: Wed, 07 Apr 2004 01:55:43 -0000 Subject: jpg, jpeg metadata References: <8a560941.0403301948.146d251@posting.google.com> Message-ID: <1076nsv7khdaod6@corp.supernews.com> In article , Larry Bates wrote: >Take a look a jhead.exe. You can easily use os.system >to call it from python. > >http://www.sentex.net/~mwandel/jhead/usage.html . . . >"helmi03" wrote in message >news:8a560941.0403301948.146d251 at posting.google.com... >> does anyone know how to get/set jpg or other image types metadata using >Python. >> I had search in vault of parnassus and PIL, but only can read the EXIF. >> >> Long live Python! > > It *is* possible in pure-Python, though: . -- Cameron Laird Business: http://www.Phaseit.net From tismer at stackless.com Fri Apr 2 08:30:29 2004 From: tismer at stackless.com (Christian Tismer) Date: Fri, 02 Apr 2004 15:30:29 +0200 Subject: Nonsense (was: Stackless Website down, Project gone, I'm dead.) In-Reply-To: <406CD030.5010506@stackless.com> References: <406CD030.5010506@stackless.com> Message-ID: <406D6AF5.1060809@stackless.com> Christian Tismer *not* wrote: > Dear Former Stackless Users, ... No idea which fool tried to make fun of me. The truth is: Stackless is in best helth, ever, nothing is lost, and I'd like to know how they faked my emails. Have a nice weekend -- 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 mobile +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 faassen at infrae.com Thu Apr 29 18:06:45 2004 From: faassen at infrae.com (Martijn Faassen) Date: Fri, 30 Apr 2004 00:06:45 +0200 Subject: EuroPython early bird deadline very soon! Message-ID: EuroPython news update april 30 =============================== EuroPython early bird registration deadline is may 1, next saturday! After that you pay 60 euros more. Some cheap accomodation also still available, so if you want to attend, hurry and register now! EuroPython is the European Python and Zope Conference. This year in its third edition, we are holding the conference in the beautiful locale of G?teborg, Sweden. Hundreds of Python users and Zope users are expected. The conference is from june 7 to june 9. - The talk submission deadline has now passed. We now have an enormous selection of talks and are struggling to fit them all in the program. For the list of talks that have already been accepted (definitely not yet complete), see here: http://www.europython.org/conferences/epc2004/info/talks/acceptedTalksOverview Many well known names in the Python community will be presenting, including keynote speaker Guido van Rossum. For those interested in Zope, look at the lineup of well-known people in the Zope community that are giving talks. It's a "can't miss" event in the Zope community! - Our keynote speakers will be Mark Shuttleworth and Guido van Rossum. Mark Shuttleworth is many things, not least what we think was the first Python programmer in space. He is also is the sponsor of the schooltool project to develop an open source school administration system in Python. More about about him can be found at http://www.markshuttleworth.com/ If you don't know who Guido van Rossum is, you really need to come to EuroPython to find out and meet him. More information can be found at http://www.europython.org. Hope to see you at EuroPython 2004! From chris at suse.local Mon Apr 26 00:12:46 2004 From: chris at suse.local (Chris) Date: Sun, 25 Apr 2004 23:12:46 -0500 Subject: Trouble Understanding O'Reilly Example References: <108p21f7asq1cc8@corp.supernews.com> Message-ID: <108p2o7j6lqqmc5@corp.supernews.com> slyraymond wrote: > def min1(*args): > res?=?args[0] > for?arg?in?args[1:]: > if?arg? res?=?arg > return?res Apologizing for whatever damage knode did to the formatting, try: if arg < res: instead of if arg < args For debugging purposes, add the line print args just before the return statement to see exactly what is going on. Chris From donal.k.fellows at man.ac.uk Mon Apr 19 08:55:08 2004 From: donal.k.fellows at man.ac.uk (Donal K. Fellows) Date: Mon, 19 Apr 2004 13:55:08 +0100 Subject: Goodbye TCL In-Reply-To: <1080ml0hdpp6tdf@corp.supernews.com> References: <0LudnSads6NmpuPdRVn-vw@centurytel.net> <21ccedf1.0404160639.14c2d852@posting.google.com> <1080ml0hdpp6tdf@corp.supernews.com> Message-ID: Cameron Laird wrote: > 'Different way to say this: "database", in this sense, is a dirty > subject, in that it's far more tied to grungy details of specific > implementations than the masses generally realize, or than either > Python or Tcl, both of which prize purity in their own ways, > generally support. A general database abstraction is about as > rarefied as a general GUI abstraction. I had a quick look into general DB APIs in the past, and the response I got from the DB community at the time was "but this doesn't support this *vital* feature only implemented in one DB that 0.01% of users really need and therefore we could never ever use your proposal for a standard API". It's kind of discouraging. FWIW, I think some mostly-common subset of functionality is possible (if we assume SQL underneath; without that, you can't get anywhere) and it would be enough to get most of the low-end and casual users total satisfaction. And maybe this would encourage alteration in the high-end interfaces to be more like each other too. Donal. From mcfletch at rogers.com Fri Apr 23 15:48:21 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Fri, 23 Apr 2004 15:48:21 -0400 Subject: Why we will use obj$func() often In-Reply-To: References: <84Uhc.22278$dZ1.5087@fed1read04> <8AWhc.23114$dZ1.11070@fed1read04> Message-ID: <40897305.6010008@rogers.com> Mark Hahn wrote: ... >Peter: You were making fun of how of fast I'm changing things in Prothon, >right? I was going along with that humour in my message. Someone in a >private message accused me of making fun of you, which I was definitely not >doing. > > Ah, too bad, you might have fit in if you did ;) . He's just *so* much fun to poke fun at. For crimminy's sake, he's from Canada, and you know how ridiculous they all are... blubber-eating igloo-wardens every last one of them. It's practically impossible to take one of them seriously as a computer programmer, I mean, really, a modern computer would just melt the igloo down around their heads. *poof* _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From richie at entrian.com Sun Apr 4 11:41:59 2004 From: richie at entrian.com (Richie Hindle) Date: Sun, 04 Apr 2004 16:41:59 +0100 Subject: ANNOUNCE: 'goto' for Python In-Reply-To: References: Message-ID: [Tim] > Guido has already accepted your module for inclusion in Python 2.4, and I > expect he'll use his time machine then to ensure that it's always been part > of Python. Great! That will have saved me a lot of work, once the new time-line comes into effect. I can re-use the time for the next job - enhancing Python's parser to allow Duff's Device. > [Explanation of numeric labels snipped] > Your introduction of alphanumeric labels to Python is already far advanced. Ah, OK, good. I won't have to re-learn anything when the new feature goes into Python 0.1. > I must say, though, that the restriction to 5 digits in Fortran had the nice > Pythonic effect of discouraging a subroutine from containing more than a > hundred thousand branch targets That's a good point, but not really applicable here. I haven't limited the number of labels, partly because I don't want any B&D to the feature, and partly because alphanumeric labels ought to be more differentiable than numeric ones. > Full speed ahead! Or backwards, or in fact to pretty much anywhere! -- Richie Hindle richie at entrian.com From jepler at unpythonic.net Sat Apr 17 13:10:14 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Sat, 17 Apr 2004 12:10:14 -0500 Subject: Static Modules... In-Reply-To: References: Message-ID: <20040417171013.GA18480@unpythonic.net> I tossed this in my PYTHONSTARTUP file, to see how I like it. No complaints so far, and it might make the interactive prompt even easier to use. Jeff From youngdubliner at hotmail.com Wed Apr 21 22:15:07 2004 From: youngdubliner at hotmail.com (youngdubliner at hotmail.com) Date: 21 Apr 2004 19:15:07 -0700 Subject: Py_ParseTuple Problem References: <4039221c.0404202256.3f21d817@posting.google.com> <40867D57.3050705@magma-da.com> Message-ID: <4039221c.0404211815.2cad28f7@posting.google.com> Thanks Rick , Thats excellent I tried your code , changed it a little and it works really well. I didn't even know that PyTuple_Size() existed , handy little function that. Thanks again ! Keith. From jacob at cd.chalmers.se Wed Apr 14 11:22:40 2004 From: jacob at cd.chalmers.se (Jacob Hallen) Date: 14 Apr 2004 15:22:40 GMT Subject: Europython update Message-ID: Europython news update ====================== - Due to our earlier delays, we have decided to push the deadline for submitting talks until the 26th of April. While we have a nice set of proposals in several tracks, there are some that neeed a boost. Submit your talk today! - Early Bird registration is open, as is registration for cheap accomodation. Deadline for both of these is 1 May 2004. This deadline will not move. - Our keynote speakers will be Guido van Rossum and Mark Shuttleworth. If you don't know who Mark Shuttleworth is, find out at http://www.markshuttleworth.com/. If you don't know who Guido van Rossum is, you really need to come to Europython to find out. About Europython ================ Europython is a community Python and Zope conference that is now in its third year. It will be held in G?teborg, Sweden from 7 June 2004 until 9 June 2004. There will be many tracks, tutorials, sprints, good food, good weather and lots of fun. G?teborg offers lots of fun things to do, so it is a good opportunity to bring your family. Find out more at http://www.europython.org -- From skip at pobox.com Wed Apr 28 09:19:06 2004 From: skip at pobox.com (Skip Montanaro) Date: Wed, 28 Apr 2004 08:19:06 -0500 Subject: Can't import Object Craft's Sybase module... Message-ID: <16527.44875.3535.268001@montanaro.dyndns.org> I downloaded and built Object Craft's Sybase module but can't import it: % PYTHONSTARTUP= python Python 2.4a0 (#4, Mar 31 2004, 15:02:21) [GCC 3.3.2] on sunos5 Type "help", "copyright", "credits" or "license" for more information. >>> import Sybase Traceback (most recent call last): File "", line 1, in ? File "/home/titan/skipm/local/lib/python2.4/site-packages/Sybase.py", line 20, in ? from sybasect import * ImportError: ld.so.1: python: fatal: relocation error: file /opt/sybase/lib/libblk.so: symbol srv__get_xdrrecv: referenced symbol not found The comp.lang.python archives from late 2001 contain a message from Dave Cole about this same problem, but as far as I could tell there was never any resolution. My environment for this mini-project is Solaris 9 on Intel. I've scanned every directory I can think of (/usr/lib, /opt/sybase/lib, /opt/Forte*, etc) looking for .so files containing that symbol but haven't found anything. I wasn't able to fine anything on the Sybase website either. Any suggestions appreciated. Skip From rmmcgettigan at nospam.students.latrobe.edu.au Tue Apr 6 23:42:53 2004 From: rmmcgettigan at nospam.students.latrobe.edu.au (mcgetts) Date: Tue, 06 Apr 2004 23:42:53 -0400 Subject: Forgotten passwords? Message-ID: Any suggestions as to what 2 do if password to programme such as webct / lola is forgotten? From no.email at please.com Tue Apr 13 15:42:00 2004 From: no.email at please.com (Stevie_mac) Date: Tue, 13 Apr 2004 20:42:00 +0100 Subject: Python crashes - cannot pin it down! References: Message-ID: Woo hoo - It works! Had to be something I was doing! Couple of questions... * Do I need this in every py file (where wx is used) - or just once in say - main() ? * Do I need to test app == None (or just let app = wxPySimpleApp() occur every time) * Do I need to Del app afterwards or app.Destroy() or ... ? Last question, what's happening here! I mean... >>> app = wxPySimpleApp() >>> app.MainLoop() Is this some form of *required* initialisation of wx? Finally, Thanks very much for taking the time to respond - Stevie_Mac :happy again: From rastm2 at aol.com Tue Apr 13 09:29:16 2004 From: rastm2 at aol.com (RASTM2) Date: 13 Apr 2004 13:29:16 GMT Subject: Newbie Question about Python win 32 -200 Message-ID: <20040413092916.10047.00000337@mb-m17.aol.com> Hello, I installed the python2.3.3exe for windows then installed the pywin32-200.win32-py23.exe and when pywin ide loads it hangs with this traceback """Python Traceback when executing Initinstance handler""" File "C:\PYTHON23\Lib\site-packages\Pythonwin\pywin\framework\intpyapp.py", line 163, in InitInstance import interact File "C:\PYTHON23\Lib\site-packages\Pythonwin\pywin\framework\interact.py", line 26, in ? import winout File "C:\PYTHON23\Lib\site-packages\Pythonwin\pywin\framework\winout.py", line 26, in ? from pywintypes import UnicodeType File "C:\PYTHON23\Lib\site-packages\win32\lib\pywintypes.py", line 55, in ? __import_pywin32_system_module__("pywintypes", globals()) File "C:\PYTHON23\Lib\site-packages\win32\lib\pywintypes.py", line 48, in __import_pywin32_system_module__ raise ImportError, "Can not locate " + filename exceptions.ImportError: Can not locate pywintypes23.dll I'm on windows 98. Can someone please explain too me what this means and maybe tell me how to fix it. Thank you, Ray St. Marie Rastm2 at aol.com From has.temp2 at virgin.net Fri Apr 30 16:43:07 2004 From: has.temp2 at virgin.net (has) Date: 30 Apr 2004 13:43:07 -0700 Subject: Is classless worth consideration References: <69cbbef2.0404290259.fd8d71c@posting.google.com> <69cbbef2.0404291209.7a98a799@posting.google.com> <8ef9bea6.0404292307.66b78b83@posting.google.com> <84Kdnfu3OoN4oA_dRVn-vg@powergate.ca> Message-ID: <69cbbef2.0404301243.451c7b26@posting.google.com> Peter Hansen wrote in message news:<84Kdnfu3OoN4oA_dRVn-vg at powergate.ca>... > Hung Jung Lu wrote: > > > I have also pointed out previously that > > Python uses 5 devices where prototype-based needs only one: (a) class, > > (b) instance, (c) module, (d) metaclass, (e) scope. If this is not > > hideously baroque, then, Houston, we've got a problem. If you can > > really think outside the box, you'd pitch in also: (f) aspect. > > Well, (c) module is merely a packaging technique, not anything > to do specifically with OOP, so it shouldn't appear in a list > of "what do you think makes Python's OO model hideously baroque". Modules are an encapsulation mechanism, just like class instances, so I'd say the large and obvious overlap counts as unnecessary duplication of functionality that by rights ought to have been factored out of the language design early on. So I think it's reasonable to count them, especially seeing how proto-OO languages have no problems eliminating them as a distinct type. > As for class and instance, unless all other languages that > have class and instance are also considered baroque, it > hardly seems fair to separate them. Classes and instances are the foundation upon which baroqueness is subsequently built. Eliminating the former not only gets rid of another unnecessary type, it also removes the need for a lot of the shenannigans that its presence encourages. > Scope doesn't quite seem to fit in this either, but not > being a theoretician I'll just leave the discussion at > this point and point out that for the purposes of a *large* > majority of the people using Python, these issues do not > arise and Python OO is very much a breath of fresh air > compared to anything else they've used. Which still makes > it hard for me to see a claim of "hideous baroqueness" as > anything other than deliberately inflammatory, but wrong. Oh, I dunno. Let's see now... aside from classes and instances, which proto-OO has already established is one more type than you need, we also have (off the top of my head and in no particular order): magic methods, magic hidden slots, funny privacy, __init__, descriptors, self as argument, class methods (and variables), making calls to superclasses, old-style/new-style classes, 'class' vs. 'type' distinction, coercion, more magic methods (e.g. __slots__), super(), the usual complaints about inheritance breaking encapsulation and multiple inheritance gotchas, *anything* beginning with 'meta'... ech, I could probably go on, but that ought to get you rolling. You really should go check out Self, NewtonScript, etc. to broaden your perspective of what OO is, and can be. Don't worry; the fresh air'll do you good, and I'm sure Python will withstand my mean ol' attacks upon its fine name in the meantime. :) From claird at lairds.com Mon Apr 26 11:57:33 2004 From: claird at lairds.com (Cameron Laird) Date: Mon, 26 Apr 2004 15:57:33 -0000 Subject: IronPythoneers in the house? (was: interfacing to a remote excel app) References: <20040426150428.69010a3c@pistache.sara.nl> Message-ID: <108qcbd1c3glf05@corp.supernews.com> In article , Harry George wrote: . [considerable wisdom about security, MS lock-in, and archi- tecture] . . >.NET remoting, and try to reach that from Mono or DotGNU. But .NET >and its clones are not very Python-friendly, so the bindings may not >be available. Even if you got it to work, you would be in a Microsoft . . . I suspect we should be careful what we say (at least in public) about compatibility with .NET. I hope someone more knowledgeable on this score than I will jump in soon. I entirely agree with the conclusion that the original poster has ... well, he's going to need changes, no matter what Python's capabilities are. -- Cameron Laird Business: http://www.Phaseit.net From peter at engcorp.com Tue Apr 13 08:39:56 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 13 Apr 2004 08:39:56 -0400 Subject: Random Numbers and a thought In-Reply-To: References: <107m6f0t4i0gnff@corp.supernews.com> <107m8qvphrjd303@corp.supernews.com> Message-ID: <407BDF9C.1050908@engcorp.com> Moosebumps wrote: > Yeah, this is not really a python question at all... go ask on sci.math or > comp.programming and have people discourage and flame you there. : ) Was anyone flaming anyone here? From roy at panix.com Sun Apr 11 09:00:24 2004 From: roy at panix.com (Roy Smith) Date: Sun, 11 Apr 2004 09:00:24 -0400 Subject: Python is the best and most popular general purpose scripting language; the universal scripting language References: <30260531.0404102015.5d74be7b@posting.google.com> Message-ID: simoninusa2001 at yahoo.co.uk (simo) wrote: > I always thought "scripting language" means interpreted instead of > compiled into machine code (not bytecode). When Apple first came out with the PowerPC processors, they emulated the old 68k instruction set in software, so you could continue to run 68k binaries. Did those old programs suddenly become scripts instead of programs because they were no longer running on the hardware? :-) From haim at babysnakes.org Wed Apr 14 09:59:46 2004 From: haim at babysnakes.org (Haim Ashkenazi) Date: Wed, 14 Apr 2004 16:59:46 +0300 Subject: pyKDE won't build References: Message-ID: Steven wrote: > Hi folks, > I'm trying to install pyKDE. > python, pyQT and sip are installed and working. > > I run python build.py and get the error shown at the end. > sip -V gives 3.10.1 (3.10.1-192) > PyQt version is 3.11 > >>From the traceback it detects the wrong sip version, but I don't know how >>to > make it detect the correct version. There is only one version of sip on my > system. (slackware linux 9.1) > I don't understand python, but need pyKDE to make something else work. > > Any help greatfully appreciated, afaik, you have to have the same version of pyqt, sip and pykde. pykde 3.11 is on it's way, but not ready yet. take a look at the pykde mailing list. Bye -- Haim From grahamd at dscpl.com.au Thu Apr 22 06:42:21 2004 From: grahamd at dscpl.com.au (Graham Dumpleton) Date: 22 Apr 2004 03:42:21 -0700 Subject: Dealing with multiple versions of packages... References: <62c819a5.0404201235.c1649c5@posting.google.com> Message-ID: Chris.Barker at noaa.gov (Chris Barker) wrote in message news:<62c819a5.0404201235.c1649c5 at posting.google.com>... > Hi all, > > We've been having a discussion over on the wxPython-users mailing list > about how to deal with multiple versions of wxPython. During the > discussion it came up that this isn't a problem faced only by > wxPython, but would have to be dealt with by virtually all packages. Check out Pmw (pmw.sourceforge.net) for ideas. It stores stuff under a root of Pmw, but then has separate directories under that for each version. Ie., Pmw_1_1, Pmw_1_2, etc. The __init__.py in the root is then a special lazy loader which by default uses the latest version, but you can specify a specific version by using a setversion() method. Whatever version you end up using, everything is still referenced as Pmw.SomeClass rather than having to hard code the version everywhere. From Holger.Joukl at LBBW.de Tue Apr 13 04:39:49 2004 From: Holger.Joukl at LBBW.de (Holger Joukl) Date: Tue, 13 Apr 2004 10:39:49 +0200 Subject: compiling Python 2.3.3 Solaris 9 x86 question Message-ID: Stefan wrote: > Hi, > > I am trying to build Python 2.3.3 on Solaris 9 x86. Everything goes fine > except that I have some issues with curses module ... > Hi Stefan, I had some python 2.3.3 build problems a while ago on a solaris 8 system. I ended up modifying setup.py to know about the "non-standard" paths where our stuff is installed, e.g. the detect_modules method: 241 def detect_modules(self): 242 ### Ensure that /usr/local is always used 243 ##add_dir_to_list(self.compiler.library_dirs, '/usr/local/lib') 244 ##add_dir_to_list(self.compiler.include_dirs, '/usr/local/include') 245 246 # add_dir inserts as first list element, so /apps/prod should come last 247 add_dir_to_list(self.compiler.library_dirs, '/apps/local/lib') 248 add_dir_to_list(self.compiler.include_dirs, '/apps/local/include') 249 add_dir_to_list(self.compiler.library_dirs, '/apps/prod/lib') 250 add_dir_to_list(self.compiler.include_dirs, '/apps/prod/include') 251 252 # fink installs lots of goodies in /sw/... - make sure we 253 # check there 254 if sys.platform == "darwin": 255 add_dir_to_list(self.compiler.library_dirs, '/sw/lib') 256 add_dir_to_list(self.compiler.include_dirs, '/sw/include') 257 258 ##??? Why would I want to set -I and -L paths for the destination dir? 259 ## (sys.prefix == --prefix= 260 ##if os.path.normpath(sys.prefix) != '/usr': 261 ## add_dir_to_list(self.compiler.library_dirs, 262 ## sysconfig.get_config_var("LIBDIR")) 263 ## add_dir_to_list(self.compiler.include_dirs, 264 ## sysconfig.get_config_var("INCLUDEDIR")) 265 and also some runtime lib paths: 667 # Curses support, requring the System V version of curses, often 668 # provided by the ncurses library. 669 if platform == 'sunos4': 670 inc_dirs += ['/usr/5include'] 671 lib_dirs += ['/usr/5lib'] 672 673 if (self.compiler.find_library_file(lib_dirs, 'ncurses')): 674 curses_libs = ['ncurses'] 675 exts.append( Extension('_curses', ['_cursesmodule.c'], 676 define_macros=[('HAVE_NCURSES_H', 1)], 677 runtime_library_dirs=['/apps/prod/lib'], 678 libraries = curses_libs) ) Without the modifications, some of the extension modules (gdbm, curses, readline) would not build. Not exactly nice and portable, but I do not have the time right now. >Regarding this problem looks like 'configure' does not pickup >Solaris's curses library. >I had to manually pass to configure command libncurses library > > >LDFLAGS="-L/opt/sfw/lib -R/opt/sfw/lib -lncurses" >CPPFLAGS="-I/optsfw/include" ./configure --prefix=/usr/local >--with-threads --enable-shared > Does this work for you when you finally run setup.py? >Does this mean that python needs libncurses and can not work with >Solaris curses library !? I?m afraid I have no clues. Where does the Solaris curses reside? Bye, Holger Der Inhalt dieser E-Mail ist vertraulich. Falls Sie nicht der angegebene Empf?nger sind oder falls diese E-Mail irrt?mlich an Sie adressiert wurde, verst?ndigen Sie bitte den Absender sofort und l?schen Sie die E-Mail sodann. Das unerlaubte Kopieren sowie die unbefugte ?bermittlung sind nicht gestattet. Die Sicherheit von ?bermittlungen per E-Mail kann nicht garantiert werden. Falls Sie eine Best?tigung w?nschen, fordern Sie bitte den Inhalt der E-Mail als Hardcopy an. The contents of this e-mail are confidential. If you are not the named addressee or if this transmission has been addressed to you in error, please notify the sender immediately and then delete this e-mail. Any unauthorized copying and transmission is forbidden. E-Mail transmission cannot be guaranteed to be secure. If verification is required, please request a hard copy version. From stach at fr.USUN.pl Thu Apr 15 11:58:19 2004 From: stach at fr.USUN.pl (Krzysztof Stachlewski) Date: Thu, 15 Apr 2004 17:58:19 +0200 Subject: Error copying a file In-Reply-To: References: Message-ID: Stephen Boulet wrote: > I know that the name of this file is somewhat pathological, but this if > weird: > > >>> print myfile > E:\Fritz Reiner\Rimsky-Korsakov--Scheherazade.Debussy--La Mer\01 > Symphonic Suite after "A Thousand and One Nights" - The Sea and Sinbad's > Ship.ogg It seems you are on Windows box. What filesystem do you use? I have just tried to create such a file, but the filesystem (NTFS) refuses to use " as part of the name. -- Stach Tlen: stachobywatelpl, GG: 1811474 Jabber: stach at jabber atman pl From jacek.generowicz at cern.ch Fri Apr 23 03:43:22 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 23 Apr 2004 09:43:22 +0200 Subject: AOP use cases References: <84fc4588.0404140106.3fa0c55@posting.google.com> <0pydnSB4WYuieuLdRVn-hQ@powergate.ca> Message-ID: "Terry Reedy" writes: > The funny thing about this example is that its success critically depends > on fib *not* being 'optimized' by having the recursive calls being either > compiled as or replaced by (as with Hettinger's recent proposal) efficient > local calls. Please remember that the _point_ of the example is to show what separation of concerns is, in the context of the claim that C moving IO from language to library constitutes separation of concerns. Picking nits in the implementation details is completely missing the point. From jeffh at activestate.com Tue Apr 20 00:16:29 2004 From: jeffh at activestate.com (Jeff Hobbs) Date: Tue, 20 Apr 2004 04:16:29 GMT Subject: Goodbye TCL In-Reply-To: References: <0LudnSads6NmpuPdRVn-vw@centurytel.net> <107u6ef5a2ise19@news.supernews.com> Message-ID: <4084A419.3020004@activestate.com> Roy Smith wrote: > In article , > blacksqr at usa.net (Stephen Huntley) wrote: > > >>I would be curious to know what is the biggest-capacity Python network >>application in use? How does it scale in comparison with AOLServer? >>Any ideas? > > > How about the one you're using to post your articles -- Google. This is no longer true - google did use Python at one point, but now it is reserved for internal company stuff only, as google really required hard-core C/C++ for the speed and scale at which it performs. -- Jeff Hobbs, The Tcl Guy http://www.ActiveState.com/, a division of Sophos From theller at python.net Fri Apr 23 13:00:58 2004 From: theller at python.net (Thomas Heller) Date: Fri, 23 Apr 2004 19:00:58 +0200 Subject: Multi-threaded printing and IOErrors in Windows References: <10nll1-rt5.ln1@home.rogerbinns.com> Message-ID: "Roger Binns" writes: > David Fraser wrote: >> sys.stdout is not threadsafe - try wrapping each call with a mutext and >> see if that fixes it... > > Having to wrap hundreds of random print statements just using for > debugging seems really silly. Note that I don't care if the > output gets garbled. (It doesn't on Mac or Linux ever). > > And I am only hitting this problem on Windows when wrapped > with py2exe. If running outside of py2exe there is never > any problem. > > When using py2exe, the stdout doesn't go anywhere anyway > (it is gui app not a console app). > > The bizarre thing is that the IOError is very infrequent, > but very annoying when it happens. If you have a small program which allows to reproduce this, I'll look into it. Thomas From roy at panix.com Thu Apr 8 16:52:35 2004 From: roy at panix.com (Roy Smith) Date: Thu, 08 Apr 2004 16:52:35 -0400 Subject: List vs tuples References: Message-ID: In article , "Mitja" wrote: > A neewbie's question here, probably discussed before: > what's the purpose of having both lists AND tuples? > At the first (and second and third, to be honest) glance lists are just > tuples with extended functionality, so why have tuples around? > I've been working with Python for a few months now but haven't yet come > across a problem that would really require tuples. > > Thanks in advance, > Mitja The biggest reason that I can think of is that tuples are immutable, and you need an immutable object to be a dictionary key. Also, without knowing the details of how they are implemented, my guess would be that tuples are more efficient, as a direct result of their immutability. From franck.lepoutre at caramail.com Mon Apr 26 03:03:05 2004 From: franck.lepoutre at caramail.com (francois lepoutre) Date: Mon, 26 Apr 2004 09:03:05 +0200 Subject: Paris python user group? References: <408795ee$0$25893$79c14f64@nan-newsreader-02.noos.net> Message-ID: <408cb35f$0$20699$79c14f64@nan-newsreader-02.noos.net> > L'id?e est int?ressante. Je serait assez tent?, s'il n'y avait pas cette > s?gr?gation pro-parisienne. Pas plus de de tropisme parisien, d'anglicisation sauvage que de beurre en broche ... Il s'agit simplement de permettre aux pythonistes parisiens de se retrouver pour boire ensemble et ? ?changes au gr? des affinit?s. S'ils le souhaitent et comme le font les perlistes parisiens. > C'est vrai, quoi ! Pourquoi vous limiter ? Paris ? Il y a des coins > nettement moins pollu?s que Paris, et donc plus productif > (pythoniquement parlant). Eh oui, c'est un provincial "exil? de l'int?rieur" qui a v?cu et boss? jusqu'il y a peu au bord de l'eau (iod?) qui prend cette initiative. > Vive l'Ard?che ! Le fait de monter un groupe sur Paris (il en existe dans de nombreuses grandes villes) n'interdit pas ? d'autres de monter des "python user group" partout ailleurs ... http://www.python.org/community/user-groups.html L'objectif des "python user groups" est de proposer une rencontre "non-virtuelle" r?guli?re, typiquement mensuelle, et le plus souvent en d?but de soir?e, soit autour d'un pot informel soit autour d'un th?me de discussion. Peut-?tre peut-on envisager d'autres formes de de r?unions ? Aux ard?chois et aux autres de plancher :) A+ From opengeometry at yahoo.ca Sun Apr 4 03:16:21 2004 From: opengeometry at yahoo.ca (William Park) Date: 4 Apr 2004 07:16:21 GMT Subject: Simulate socket with files or stdin/stdout References: Message-ID: Jean-Pierre Bergamin wrote: > Dear python-Community > > We are forced to use a quite old simulation software that's based on > Modula-2. The idea is now to let this software "talk" to the outside world > over a TCP/IP network. > > Since the program has no possibility to use sockets or other mechanisms to > send data over the network we have the idea to let python do the network > part and let the simu software communicate with the python script in some > other way: > > One idea is to use stdout and stdin (but I'm not even sure if stdout/in are > available in the simulation software). This might be important, so you should find out... don't you think? > > +------------+ stdout stdin +------------+ socket.write > | |------------------->| python- |---------------- > | Simulation | | script | > | |<-------------------| |<--------------- > +------------+ stdin stdout +------------+ socket.read In Bash, Ksh, exec 3<>/dev/tcp/remote.host/4000 0<&3 1>&3 simulation exec 3<&- You can achieve the same thing, by running 'simulation' under 'inetd'. > > > The other idea is to use files to communicate between the simultion program > and the python script. > > +------------+ +------+ +------------+ socket.write > | |---->| |---->| python- |-------------- > | Simulation | | File | | script | > | |<----| |<----| |<------------- > +------------+ +------+ +------------+ socket.read Bad design. Outgoing data from 'file' can go to 'simulation' or to 'python-script'. How do you know what data should go to what direction? That is, how does 'file' know whether 'simulation' or 'python-script' is reading it? If "input" and "output" files are different, then it's different story. -- William Park, Open Geometry Consulting, Linux solution for data processing and document management. From jdhunter at ace.bsd.uchicago.edu Thu Apr 1 08:11:19 2004 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Thu, 01 Apr 2004 07:11:19 -0600 Subject: test for nan In-Reply-To: (Michael Hudson's message of "Thu, 1 Apr 2004 11:03:20 GMT") References: Message-ID: >>>>> "Michael" == Michael Hudson writes: Michael> This will work with 2.3 on Windows (I believe), current Michael> CVS on Windows (if compiled with VC7.1), current CVS on Michael> Linux (assuming an even vaguely recent gcc), but not Michael> current CVS on Windows compiled with VC6, nor Python 2.3 Michael> on Linux/gcc. Confused yet? Fortunately I only need linux for this particular app, so I can use one of the platform dependent solutions, but the bevy of proposed solutions and gotchas have definitely been interesting. Out of curiosity, are there any platforms where this is known to fail? def is_nan(x): return str(x).lower().find('nan')>=0 JDH From bokr at oz.net Wed Apr 28 20:30:57 2004 From: bokr at oz.net (Bengt Richter) Date: 29 Apr 2004 00:30:57 GMT Subject: Why we will use obj$func() often References: <84Uhc.22278$dZ1.5087@fed1read04> <8AWhc.23114$dZ1.11070@fed1read04> <40883BFE.B381518A@alcyone.com> <27_hc.23801$dZ1.2716@fed1read04> <40887145.789A2FE8@alcyone.com> <7cki80hj976bia36lhf9er97v073o1pqvm@4ax.com> <5vJjc.13116$Qy.1954@fed1read04> <52Ujc.16275$Qy.3111@fed1read04> Message-ID: On Wed, 28 Apr 2004 14:21:18 -0700, Donn Cave wrote: [...] >work. When I dream of a better language, it's not pasting new >gimmicks on Python, it's really a radically different direction. You teaser ;-) Regards, Bengt Richter From dankoski at cisco.com Mon Apr 19 15:36:48 2004 From: dankoski at cisco.com (Paul Dankoski) Date: Mon, 19 Apr 2004 12:36:48 -0700 Subject: Python IDLE GUI Message-ID: <1082403283.261220@sj-nntpcache-5> Hello. I downloaded and installed Windows Python-2.3.exe. The install appears to be successful. There is a Start menu item showing "Python 2.3" --> "IDLE (Python GUI)". When I select this, nothing appears on my Windows 2000 screen. However, if I look at the task manager, I see "pythonw.exe", which I assume applies that the process is indeed running. I expect some sort of GUI to open. I checked the INSTALL.LOG file. The only thing that possibly looks fishy is: Date/Time: Following file not copied. File Overwrite: C:\WINNT\system32\msvcirt.dll | 05-08-2001 | 06:00:00 | 6.1.8637.0 | 77878 | 571d0e6 Date/Time: Following file not copied. File Overwrite: C:\WINNT\system32\msvcrt.dll | 06-19-2003 | 12:05:04 | 6.1.9844.0 | 295000 | 770c8856 Any ideas on what I should try next? Thanks, Paul D. From fpetermaas at netscape.net Thu Apr 1 03:34:14 2004 From: fpetermaas at netscape.net (Peter Maas) Date: Thu, 01 Apr 2004 10:34:14 +0200 Subject: ANNOUNCE: 'goto' for Python In-Reply-To: References: Message-ID: Richie Hindle wrote: > Entrian Solutions is pleased to announce version 1.0 of the 'goto' module. > > This adds the 'goto' and 'comefrom' keywords to Python 2.3, adding > flexibility to Python's control flow mechanisms and allowing Python > programmers to use many common control flow idioms that were previously > denied to them. Great!!! This will enhance Python's yet poor capabilities to write code with a behaviour hard to predict by programmers thereby adding a human touch to the sometimes too clean and dull Python language! Mit freundlichen Gruessen, Peter Maas -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Hubert-Wienen-Str. 24 Tel +49-241-93878-0 Fax +49-241-93878-20 eMail peter.maas at mplusr.de ------------------------------------------------------------------- From martin at v.loewis.de Thu Apr 22 16:44:17 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 22 Apr 2004 22:44:17 +0200 Subject: Regexp optimization question In-Reply-To: References: Message-ID: Magnus Lie Hetland wrote: > I've tried to speed this up by using the same trick as SPARK, putting > all the regexps into a single or-group in a new regexp. That helped a > *lot* -- but now I have to find out which one of them matched at a > certain location. Are you using the .lastindex attribute of match objects yet? Martin From jacob at cd.chalmers.se Fri Apr 9 20:21:10 2004 From: jacob at cd.chalmers.se (Jacob Hallen) Date: 10 Apr 2004 00:21:10 GMT Subject: Europython update: Registration open Message-ID: Europython Update ================= - Registration is now open. We apologise for the delay, but we have had some technical problems. - Due to this, we have decided to keep the submission of abstracts for the refereed track open for one more day. Last submission time is now on Sunday 11 April at 23.59 CET. - We have a limited number of beds available in very affordable accomodation near the conference venue. Book early before it runs out. - We are still receiving submissions for regular talks and tutorials. Closing date is 15 April. - There is now a wiki at the Europython website for sprint organising. Start planning! About the conference ==================== EuroPython 2004 will be held 7-9 June in G?teborg, Sweden. The EuroPython conference will have tracks for Science, Business, Education, Applications, Frameworks, Zope and the Python language itself. Lightning talks, Open Space and BOF sessions are also planned. There will be tutorials as well, both for newcomers to Python and Python users interested in special subjects. In the days before and after the conference, programming sprints will be arranged. Important dates =============== Refereed paper proposals: until 11 April. Submission of talks: 1 March - 15 April. Early Bird registration: 9 April - 1 May. Accomodation booking: 9 April - 1 May (or until space runs out) More information at http://www.europython.org. -- From michele.simionato at poste.it Sat Apr 3 01:35:48 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 2 Apr 2004 22:35:48 -0800 Subject: Prothon, metaclasses, Zope [Was: A 'Python like' language] References: <95aa1afa.0403272243.78d60724@posting.google.com> <95aa1afa.0404010017.2f1683b8@posting.google.com> <95aa1afa.0404011933.5cc5e959@posting.google.com> Message-ID: <95aa1afa.0404022235.3962343@posting.google.com> aahz at pythoncraft.com (Aahz) wrote in message news:... > In article <95aa1afa.0404011933.5cc5e959 at posting.google.com>, > Michele Simionato wrote: > >My address michele.simionato at poste.it is mostly > >a span recipient I don't check often. Rea addresses I check every day are > >michelesimionato at libero.it and michele.simionato at partecs.com > > Then please make those addresses readily available by sticking them in > your .sig or something. Having a non-replyable address is about as rude > as top-posting. ;-) BTW, I tried to send you a message and got this: - These recipients of your message have been processed by the mail server: aahz at pythoncraft.com; Failed; 5.1.1 (bad destination mailbox address) Remote MTA iris2.directnic.com: SMTP diagnostic: 550 5.7.1 Mail from smtp1.libero.it (193.70.192.51) refused (blackholed by bl.spamcop.net); Blocked - see http://www.spamcop.net/bl.shtml?193.70.192.51 So it looks like spam is taking control of our lifes and making both of us to appear rude :-/ Michele Simionato From patrick at harsdorf.de Sun Apr 25 12:25:08 2004 From: patrick at harsdorf.de (Patrick von Harsdorf) Date: Sun, 25 Apr 2004 18:25:08 +0200 Subject: iterating over collection, deleting entries Message-ID: I want to iterate over a collection and delete all unwanted entries. for item in collection: del item of course doesn?t do anything useful. Two things come to mind: a) iterating backwards over the collection using indexing, something like: for i in range(len(collection)-1, -1, -1): item = collection[i] if isBad(item) del collection[i] b) duplicating the collection, iterating over one and deleting from the other. Both solutions seem both ugly and expensive to me, solution a) probably isn?t even O(x) anymore. Please tell me, what?s the best way to do this? -- Patrick von Harsdorf patrick at harsdorf.de From claird at lairds.com Sun Apr 4 13:15:39 2004 From: claird at lairds.com (Cameron Laird) Date: Sun, 04 Apr 2004 17:15:39 -0000 Subject: emergent/swarm/evolutionary systems etc References: <106um6hcr363u14@corp.supernews.com> Message-ID: <1070glr62jl65bd@corp.supernews.com> In article , Peter MacKenzie wrote: . . . >LISP brought it to mind. Although LISP doesn't look that much better than >Python code, are there any programs out there that let you program, um, >programs, using various shapes, colours etc? Just thinking about it brings . . . We often call that "visual programming", and it comes in several strengths http://www.cs.berkeley.edu/~maratb/cs263/paper/node2.html http://foldoc.doc.ic.ac.uk/foldoc/foldoc.cgi?query=visual+programming&action=Search news:comp.lang.visual -- Cameron Laird Business: http://www.Phaseit.net From JasonHarper at pobox.com Sun Apr 11 13:04:17 2004 From: JasonHarper at pobox.com (Jason Harper) Date: Sun, 11 Apr 2004 10:04:17 -0700 Subject: Tkinter Button image option References: <8d3ec.74988$Ig.46341@pd7tw2no> Message-ID: <40797A08.A8781BEA@pobox.com> Are you saving a reference to the image you loaded somewhere (perhaps as an attribute of the button, if that's the only user of the image)? Merely using an image in a Tkinter widget is NOT sufficient to keep it from being garbage collected. PIL is not required for basic use of images in Tkinter, although it does give you lots more options for working with them. Jason Harper From mark at prothon.org Fri Apr 23 15:08:11 2004 From: mark at prothon.org (Mark Hahn) Date: Fri, 23 Apr 2004 12:08:11 -0700 Subject: Why we will use obj$func() often References: <84Uhc.22278$dZ1.5087@fed1read04><8AWhc.23114$dZ1.11070@fed1read04> <40883BFE.B381518A@alcyone.com><27_hc.23801$dZ1.2716@fed1read04> <40887145.789A2FE8@alcyone.com> Message-ID: "Jack Diederich" wrote in message > Oh please, don't conflate irrational prejudice (racism) with rational > prejudice (it looks perl-ish, and I don't like the way perl looks, therefore > I don't like the way Prothon looks). Your accusation isn't up to the level > of that fellow spewing Totalitarian rhetoric about the "mental sickness" of > people who wrote/use python, but it isn't far off. I apologize to anyone that I offended by thinking that I related the problems of racism to language discussion. I realize now that the analogy was poorly chosen, even if based on something. I just meant that people "pre-judge" Prothon based on it's looks. From mcherm at mcherm.com Wed Apr 7 15:32:36 2004 From: mcherm at mcherm.com (Michael Chermside) Date: Wed, 7 Apr 2004 12:32:36 -0700 Subject: [Python-Dev] More imformative iterator representations Message-ID: <1081366356.4074575475316@mcherm.com> Raymond writes: > So, I posted an idea about changing the print part of the > read-eval-print loop to display more information: > > >>> enumerate('abcdefgh') > > > There a couple of problems with the approach. One is how to identify an > iterator object -- the presence of __iter__() and next() is a good but > not perfect indicator. > > The other issue was trying to leave the iterator undisturbed while > fetching the first three entries. The issue of leaving the iterator undisturbed is more significant than you think. It is an important feature of the iterator contract that iterators are NOT asked to produce their values until the iterator is actually USED. People take advantage of this by using iterators when producing output that requires lots of resources (like CPU). For example, I sometimes write simple code which runs through very large directories of logfiles and analyses the contents. Sometimes it takes noticable time (1-5 min) per directory processed. So I write an iterator which does one directory per invocation. I would hate to have it take 3-15 minutes to skip ahead (and waste gobs of memory keeping _3_ results in memory when it's never necessary to keep more than 1 at once) just in order to pretty-print the iterator. And yes, I do this in interactive mode. I guess I wouldn't mind if certain built-in iterators did this... list iterators, for instance, are easy. But I would object to any scheme which tried to impose it on user-defined iterators. If the user wants a nicely-printed iterator, they can override __repr__! -- Michael Chermside From lorenb2 at bezeqint.net Wed Apr 14 05:08:42 2004 From: lorenb2 at bezeqint.net (Bob Lub) Date: Wed, 14 Apr 2004 11:08:42 +0200 Subject: httplib.py problem Message-ID: <00dc01c42200$15290250$0a01a8c0@bobbia> hello all, while sending POST request using httplib.httpConnection class, i've noticed that the library sends my request in TWO packets, one for the http headers and the second for the post data (which is only 25 bytes long). direct consequence is slower connections and wasted bandwidth (it makes the http server to send an HTTP 100 continue message, too). how can i enforce the library to send everything in one packet ? thanks B -------------- next part -------------- An HTML attachment was scrubbed... URL: From halloleo at noospaam.myrealbox.com Thu Apr 8 03:23:02 2004 From: halloleo at noospaam.myrealbox.com (leo) Date: Thu, 8 Apr 2004 17:23:02 +1000 Subject: unc paths in os.path.walk on win2000? Message-ID: how can i use unc paths in os.path.walk on win2000? i tried the \\server\path representation in python 2.3 and it didn't work... thanks, leo From ciol__opuscic__ at o2.pl.bez.tego Tue Apr 27 04:46:47 2004 From: ciol__opuscic__ at o2.pl.bez.tego (Tut) Date: Tue, 27 Apr 2004 10:46:47 +0200 Subject: 404 errors References: <408dcc25$0$16577$5a62ac22@freenews.iinet.net.au> Message-ID: Tue, 27 Apr 2004 11:00:57 +0800, Derek Fountain wrote: > Some servers respond with a nicely formatted bit of HTML explaining the > problem, which is fine for a human, but not for a script. Is there some > flag or something definitive on the response which says "this is a 404 > error"? Maybe catch the urllib2.HTTPError? From deetsNOSPAM at web.de Thu Apr 29 09:04:21 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Thu, 29 Apr 2004 15:04:21 +0200 Subject: suggestions for using tuples instead of list (or vice versa) References: Message-ID: > Is there any advantage for using tuples? Are they "faster"? Consume > less memory? When is it better to use tuples instead of lists and when > better to use lists instead of tuples? AFAIK tuples are faster and less memory consuming. I personally prefer them for e.g. returning multiple values from a function or when I know I won't need the power of a list. But its largely considered a matter of taste. Google this newsgroup for a plethora of discussions on this subject.... -- Regards, Diez B. Roggisch From kkto at csis.hku.hk Fri Apr 30 04:32:00 2004 From: kkto at csis.hku.hk (Isaac To) Date: Fri, 30 Apr 2004 16:32:00 +0800 Subject: operator double() surprise in cxx References: Message-ID: <7ivfjh988v.fsf@enark.csis.hku.hk> >>>>> "Beno?t" == Beno?t Dejean writes: Beno?t> Le Thu, 29 Apr 2004 21:35:51 -0500, John Hunter a ?crit?: >> I am using pycxx 5.2.2 to generate some extension code. I want to >> extract some doubles from some python sequences >> >> When I do >> >> double l( Py::Float(rect[0]) ); double b( Py::Float(rect[1]) ); Beno?t> everything that looks/tastes/sounds like a function declaration Beno?t> is (even with parameters. Is it really a bug in g++? No matter how I look at Py::Float(rect[0]) it does not look like a type "Py::Float*" that is indicated by the error message. Perhaps it looks like a (Py::Float (*) (rect*)) if g++ think that rect is a type instead of a variable, but does it really know some type called rect, and if not, why no error about unknown type on the "function declaration"? Regards, Isaac. From tkpmep at hotmail.com Fri Apr 16 12:53:24 2004 From: tkpmep at hotmail.com (Thomas Philips) Date: 16 Apr 2004 09:53:24 -0700 Subject: Passing a parameter to filter Message-ID: To experiment with filtering, I define a function f(x,k) as follows >>> def f(x,k=2): return x%k==0 I can check that it works by typing >>> f(10,3) False Now, I try to filter a range using >>> filter(f(k=3),range(20)) Traceback (most recent call last): File "", line 1, in -toplevel- filter(f(k=3),range(20)) TypeError: f() takes at least 1 non-keyword argument (0 given) I next try >>> filter(f(3),range(20)) Traceback (most recent call last): File "", line 1, in -toplevel- filter(f(3),range(20)) TypeError: 'bool' object is not callable But, as k defaults to 2, I get exactly what I expect from >>> filter(f,range(20)) [0, 2, 4, 6, 8, 10, 12, 14, 16, 18] >>> What's wrong with my syntax when passing the parameter k=3? Sincerely Thomas Philips From jack at performancedrivers.com Mon Apr 19 14:06:22 2004 From: jack at performancedrivers.com (Jack Diederich) Date: Mon, 19 Apr 2004 14:06:22 -0400 Subject: module not callable - why not? In-Reply-To: <8ef9bea6.0404190902.78d2a95d@posting.google.com> References: <8ef9bea6.0404190902.78d2a95d@posting.google.com> Message-ID: <20040419180622.GC23507@performancedrivers.com> On Mon, Apr 19, 2004 at 10:02:51AM -0700, Hung Jung Lu wrote: > "Robert Brewer" wrote in message news:... > > Josiah Carlson wrote: > > > Singletons aren't nearly as prevalent as you seem to believe. > > > ... Truth be told, I've used singletons before, but only once. > > > > I thought I had twice, > > But now I can see there was > > Only one instance. > > Ha. As I have said, "singleton pattern" is symptom of a disease. But > the concept of "singleton" itself, that is, a unique instance of a > class, is ubiquitous. Just about any decent-size program that you > write will have lots of singletons: classes that have one single > instance. Therefore, you have used singletons tons of times. You just > have not followed recipes for "singleton pattern", which is good, > because it is symptom of a disease. Yes, as you've said many times. It may be language barrier but your posts about everyone else being completely wrong and dumb aren't winning you any converts. I'm glad you like prototype based languages, and have fun working on Prothon. Until it becomes more than vaporware (eg, finished compiler and used successfully in a project) it can't be more than a better idea. Since I need to actually get some work done I'll stick with python. -jackdied From missive at frontiernet.net Wed Apr 21 16:42:37 2004 From: missive at frontiernet.net (Lee Harr) Date: Wed, 21 Apr 2004 20:42:37 GMT Subject: __metaclass__ = type (was: Re: if (__name__ == '__main__'): main(sys.argv[1:])) References: <01c601c4271b$7f7300a0$b401010a@sparta> <4085A445.1050303@heneryd.com> Message-ID: <11Bhc.2149$hM2.1561@news02.roc.ny> On 2004-04-21, Fran?ois Pinard wrote: > > __metaclass__ = type > > class Main: > def __init__(self): > pass > > A word about the `__metaclass__' line. My intent is to forget all about > classic classes and go with the new type system as quickly as possible. > I do not want to derive each and every of my classes from `object', > and later edit all those `(object)' out when the classic classes will > effectively get deprecated. Much easier and cleaner to remove that > `__metaclass__' line then. Moreover, by using this `__metaclass__' line > in all my things, I do not risk obscure bugs because I forgot one of > these `object' derivation while I used more recent Python features. > Very interesting. Is there any reason to stick with old-style classes? Or would we all be well-advised to use something like this? I mostly just create classes the old way and never even think about subclassing object. From uwe.schmitt at procoders.net Thu Apr 29 10:35:04 2004 From: uwe.schmitt at procoders.net (Uwe Schmitt) Date: 29 Apr 2004 14:35:04 GMT Subject: python 2.3's lambda behaves old fashioned Message-ID: Hi, I just tried (Python 2.3) li = [ lambda x: x*a for a in range(10) ] which results in li[0](1) = 9 ... li[9](1) = 9 In order to achieve the intended result I had to fall back on the following trick: li = [ lambda x,a=a: x*a for a in range(10)] which leads to the expected result. Any explanations ??? Greetings, Uwe. -- Dr. rer. nat. Uwe Schmitt http://www.procoders.net schmitt at procoders.net "A service to open source is a service to mankind." From http Sun Apr 4 22:03:44 2004 From: http (Paul Rubin) Date: 04 Apr 2004 19:03:44 -0700 Subject: Session variables? References: <4070bad0$1@clarion.carno.net.au> Message-ID: <7xsmfjuqnz.fsf@ruckus.brouhaha.com> Steve writes: > I'm trying to find a clean way of sharing variables across different > python webpages and scripts and I need something like a session > variable for each user. Is this possible in Python? I've been > "pickling" stuff and this doesn't work at all with mutliple users as > things get mixed up. Is there any clean way of doing this? Thanks, One way is put all the variables into a browser cookie. You have to be careful about security when you do that though. Don't use a pickle. From peter at engcorp.com Sat Apr 10 08:33:44 2004 From: peter at engcorp.com (Peter Hansen) Date: Sat, 10 Apr 2004 08:33:44 -0400 Subject: python datetime repository In-Reply-To: References: Message-ID: Sakesun Roykiattisak wrote: > > During the moment of learning and using python + various API, I 've > come across many kinds of datetime classes. > > python 2.3 datetime.datetime > xmlrpclib.DateTime > pywintypes.Time > mxDateTime > Zope's DateTime > pyical's DateTime > > Anybody know any other python datetime class out there ? Just wonder if > there are more. > > According to Bruce Eckel, "Python reduce clutter". Perhaps datetime > clutter is badly need reduction. The list above contains one platform-specific case which can't just be made to disappear, and at least three types which predate the new standard datetime module. I don't know what pyical is but I suspect it's the same sort of thing. The best way to reduce the clutter is merely to start using the new datetime module where you can, and gradually refactor old code where possible to use it. Basically, "give folks a break, the standard datetime is new!" -Peter From joe at notcharles.ca Fri Apr 16 00:27:03 2004 From: joe at notcharles.ca (Joe Mason) Date: Fri, 16 Apr 2004 04:27:03 GMT Subject: CamelCase versus wide_names (Prothon) References: <7xekqo36ia.fsf@ruckus.brouhaha.com> Message-ID: In article <7xekqo36ia.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: > "Mark Hahn" writes: >> 1) CamelCase is more elegant, modern, more readable, and more efficient in >> character usage. > > IfCamelCaseWereReallyMoreReadable, We'dWriteOrdinaryEnglishLikeUsingIt. > SoThatClaimIsRidiculousAndNeedsToBeThrownOutTheWindowPostHaste. > >> 2) Wide_names is cleaner, more readable, compatible with C, which is the >> standard module language for Python and Prothon. Wide_names is also the >> Python standard. > > Sounds_ok_with_me. I_find_it_a_heck_of_a_lot_more_readable_than_camel_case. > I_vote_for_wide_names. If you actually write code with names that long, you deserver to be forced to read them in camelCase. Joe From LNOBALA/DROGA at droga.si Tue Apr 27 10:11:44 2004 From: LNOBALA/DROGA at droga.si (LNOBALA) Date: Tue, 27 Apr 2004 16:11:44 +0200 Subject: NAV detected a virus in a document you authored. Message-ID: Please contact your system administrator. The infected component in the scanned document was deleted. Virus Information: The attachment mail2424.pif contained the virus W32.Netsky.Q at mm and was deleted. From Scott.Daniels at Acm.Org Sun Apr 11 12:06:02 2004 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sun, 11 Apr 2004 09:06:02 -0700 Subject: Simple Class Question - need clarity please In-Reply-To: References: Message-ID: <4079739a$1@nntp0.pdx.net> Shalabh Chaturvedi (and before him Alan Gauld) gave lots of good advice to Stevie_mac, including: ... >>I'm also struggling with other things like... >>Where do I save .py files? >>Will 'import' find my files where ever they are? (obviously not but...) > > Look for PYTHONPATH and sys.path in the documentation. Hmm, now I urge you > to go through the entire tutorial - it doesn't take long! Another technique to consider: I drop a file in my .../Python23/Lib/site-packages directory. It contains a line with an unquoted directory name to add to the path. My file is named 'projects.pth', but use any name you like as long as it ends with '.pth' -- the name is unimportant. You don't want it to conflict with names you are likely to get from outside parties (third-party packages like PIL often use this technique). I should probably call it 'ScottsWorkingTopics.pth' by that logic. There is no restriction to naming a single directory, but each should be on its own line. If I ember correctly, starting a line with a hash mark (#) should make it a comment, but check your python docs to be sure. In my case, again, the line is: C:\Projects\Current\Python I've never tried using windows magic like: %USERPROFILE%\DeskTop\Py for the path names; you could try it and report on the results. >>What basic should be considerations when deriving classes? I also usually try to derive from object (for "new-style" classes. I don't even particularly need their features; I am simply getting used to the way all classes will eventually work. -- -Scott David Daniels Scott.Daniels at Acm.Org From See_my at Signature.com.invalid Sun Apr 18 18:36:14 2004 From: See_my at Signature.com.invalid (Tuxtrax) Date: Sun, 18 Apr 2004 22:36:14 GMT Subject: help with str() References: <40826776$0$136$3a628fcd@reader1.nntp.hccnet.nl> Message-ID: In article <40826776$0$136$3a628fcd at reader1.nntp.hccnet.nl>, anton at vredegoor.doge.nl (Anton Vredegoor) wrote: > Maybe this rings a bell: > > Python 2.3.2 (#1, Oct 9 2003, 12:03:29) > [GCC 3.3.1 (cygming special)] on cygwin > Type "help", "copyright", "credits" or "license" for more > information. > >>> str(5) > '5' > >>> str = "don't do this" > >>> str(5) > Traceback (most recent call last): > File "", line 1, in ? > TypeError: 'str' object is not callable > >>> > > Anton Thanks Anton. That was exactly it. I had a variable ealier in the program called str. Changed that variable name to another, and the str() function worked fine. DOH! I knew it was something simple. Most of my fopahs are. again, thanks, Mathew -- ROT 13 this address to mail me: bar jbeq abg guerr; uvtu qrfreg zna, gura nqq - ng lnubb qbg pbz. From mark at prothon.org Thu Apr 15 11:17:08 2004 From: mark at prothon.org (Mark Hahn) Date: Thu, 15 Apr 2004 08:17:08 -0700 Subject: CamelCase versus wide_names (Prothon) Message-ID: We have agreed in Prothon that unlike Python we are going to be 100% consistant in our var and method naming. We will not have run-together words like iteritems, we are going to always have seperated words like has_key. Now we are in the midst of a discussion of camelCase versus wide_names. So far our arguments are: 1) CamelCase is more elegant, modern, more readable, and more efficient in character usage. 2) Wide_names is cleaner, more readable, compatible with C, which is the standard module language for Python and Prothon. Wide_names is also the Python standard. Of course in the Python world you alread have wide_names as your standard, but could you for the moment pretend you were picking your standard from scratch (as we are doing in the Prothon world) and give your vote for which you'd prefer? Thanks in advance... From lbates at swamisoft.com Thu Apr 15 10:03:47 2004 From: lbates at swamisoft.com (Larry Bates) Date: Thu, 15 Apr 2004 09:03:47 -0500 Subject: Fast Data Comparison (dict v. list. v string) References: Message-ID: Scott, You should take a close look at list comprehensions and possibly sets (new in V2.3). I'm not all that familiar with sets, but your problem sounds like they might come in handy. Example list comprehension: list1notinlist2=[x for x in list1 if x not in list2] for item in list1notinlist: # Do some processing Note: In Python if you find yourself using [i] indexes into lists, there is "almost" always a better way (at least that is my experience). Larry Bates Syscon, Inc. "Scott Brady Drummonds" wrote in message news:c5k8rp$ql6$1 at news01.intel.com... > Hi, everyone, > > I'm a relative novice at Python and am working on some optimizations in my > first Python project. At its core, this tool I'm writing needs to perform > many comparisons to fixed-size lists of fixed-length strings. > > Currently, my implementation uses dictionaries to store each string. I > maintain a separate "key-mapping" dictionary that maps keys from one > dictionary to the other. Then, all I have to do to compare the two > dictionaries is as follows: > for metaKey in keyMap.keys(): > if dict1[metaKey] != dict2[keyMap[metaKey]]: > # Do some processing > > Since the sizes of the dictionaries never change, I tried implementing this > using lists. The solution looks something like this (and assumes that a > pre-processing phase has sorted the contents of each list so their indexes > are the same): > for i in len(list1): > if list1[i] != list2[i]: > # Do some processing > > As it turns out, this implementation appears to be about 33% faster than the > dictionary-based one. Now, assuming that the datum being stored at each > index can fit into one character, I could do a string-based implementation > like this: > for i in len(string1): > if string1[i] != string[i]: > # Do some processing > > This last solution actually runs about the same as the dictionary, which > takes 50% longer than the list implementation. > > Now, my questions are: > 1) Does anyone have another suggestion as to how I can organize these data > so that I can compare many elements many times? > 2) Is there a string comparison operator that will return which indexes > have different values? Maybe it would be faster than the iterative > comparison approach for the third implementation. > 3) Since my data are changing between the successive executions of the code > snippets above, I need a way of having the other parts of the program update > it. But, it appears that strings are constant as I can't assign individual > characters with "string1[i] = '0'". Is there any way around this? > > Thanks! > Scott > > -- > Remove ".nospam" from the user ID in my e-mail to reply via e-mail. > > From rob02omni at vodafone.it Tue Apr 20 05:26:34 2004 From: rob02omni at vodafone.it (Roberto) Date: Tue, 20 Apr 2004 11:26:34 +0200 Subject: Getting output from embedded python program References: <2aa196bb.0404190554.74631058@posting.google.com> <4084B179.6020807@magma-da.com> Message-ID: Hi there, > http://elmer.sourceforge.net/PyCon04/elmer_pycon04.html ) ...obviously, > if you evaluate a print statement, you will still get output on stdout This tutorial is quite good! The same thing can be done even with the py_runfile ?? I'm triyng to do such things with no result! Bye, Roberto "Rick L. Ratzel" ha scritto nel messaggio news:4084B179.6020807 at magma-da.com... > Kim wrote: > > Hi everyone, > > I'm writing a embeded python program, and I want to evaluate some > > expression by calling function: > > > > PyRun_SimpleString("print 'hello'") > > > > I don't want to output it to stdout but putting it into string somehow > > sothat I can process it. > > > > Here is a way to get the result of a Python expression eval from C > (derived from example at > http://elmer.sourceforge.net/PyCon04/elmer_pycon04.html ) ...obviously, > if you evaluate a print statement, you will still get output on stdout > though: > > ... > PyObject* evalModule; > PyObject* evalDict; > PyObject* evalVal; > char* retString; > > PyRun_SimpleString( "result = 'foo' + 'bar'" ) > > evalModule = PyImport_AddModule( (char*)"__main__" ); > evalDict = PyModule_GetDict( evalModule ); > evalVal = PyDict_GetItemString( evalDict, "result" ); > > if( evalVal == NULL ) { > PyErr_Print(); > exit( 1 ); > > } else { > /* > * PyString_AsString returns char* repr of PyObject, which should > * not be modified in any way...this should probably be copied for > * safety > */ > retString = PyString_AsString( evalVal ); > } > ... > > In this case, you need to know that the expression will evaluate to > a string result in order to call PyString_AsString(). If you don't know > this, you will have to check the type of the PyObject first. > > > From ekkilu at yahoo.com Fri Apr 30 00:08:21 2004 From: ekkilu at yahoo.com (Ekki) Date: 29 Apr 2004 21:08:21 -0700 Subject: static keyword References: Message-ID: nicksjacobson at yahoo.com (Nick Jacobson) wrote in message news:... > The bad news: I just hope I don't forget and call foo() instead of > g.next(). > I would rather the command foo() by default call the next iteration, > and, say, foo().reset() would recall the function from scratch. But > that's neither here nor there.. C++ functors (analogous to Python callables) do what you want and a lot more. I am sure your problem does not need to get to this level, but here is some food for thought. Notice the absence of if-statements. class F: def __call__(self): print "First pass" self.i = [10, 11] # initialization self.first_call = self.__call__ # metaprogramming fun self.__call__ = self.call # metaprogramming fun self() def call(self): self.i[0] += 1 print self.i[0] def reset(self): self.__call__ = self.first_call # metaprogramming fun f = F() f() f() f.reset() f() f() The full power of functors/callables only shows up when you combine them with inheritance. regards, Hung Jung From eric at enthought.com Fri Apr 23 02:13:32 2004 From: eric at enthought.com (eric) Date: 22 Apr 2004 23:13:32 -0700 Subject: ANN: SciPy 0.3 Released References: Message-ID: <16f9b1ea.0404222213.f8b821d@posting.google.com> Hey Enrique, Chaco has moved to a new package. We hope to have it released within the next few weeks. thanks, eric Enrique Castro wrote in message news:... > Travis N. Vaught wrote: > > SciPy 0.3 has been released and binaries are available from the > > scipy.org site. > > > > http://www.scipy.org > > > Hi, > What's the status of Chaco, the plotting package? > Is it now included in SciPy download? > > I have tried to follow the chaco link in Enthought's site > (http://www.enthought.com/) but it seems not working > > Tanks > Enrique Castro From roy at panix.com Mon Apr 26 13:31:18 2004 From: roy at panix.com (Roy Smith) Date: Mon, 26 Apr 2004 13:31:18 -0400 Subject: Is Perl *that* good? (was: How's ruby compare to it older brother python) References: <108q51j4dscn7dc@corp.supernews.com> <108qhidjthjpdc0@corp.supernews.com> Message-ID: In article <108qhidjthjpdc0 at corp.supernews.com>, claird at lairds.com (Cameron Laird) wrote: > In article , > Leif B. Kristensen wrote: > . > . > . > >which can be spelled in an amazing number of different ways. As I found > >that the Soundex algorithm was useless for Norwegian spellings, I > >invented my own. It's not really an algorithm, but a series of > >substitutions that reduces names to a kind of primitives. Thus, eg. > . > . > . > "Canonicalization" is one name in academic English for this transformation. But is it the cannonical name? From peter9547 at btinternet.com Sun Apr 4 12:07:14 2004 From: peter9547 at btinternet.com (Peter MacKenzie) Date: Sun, 4 Apr 2004 16:07:14 +0000 (UTC) Subject: emergent/swarm/evolutionary systems etc References: <106um6hcr363u14@corp.supernews.com> Message-ID: >You might like "The Outsider's Guide to Artificial Intelligence" >. Yes. It is interesting. I've been playing with the idea of graphical representations for programming 'phrases' for a while, and the reference to LISP brought it to mind. Although LISP doesn't look that much better than Python code, are there any programs out there that let you program, um, programs, using various shapes, colours etc? Just thinking about it brings up all manner of difficulties that would be encountered if you tried to create such a thing, but it would be nice if there was some immediately obvious graphical connection between pieces of code (so beginners like me didn't keep trying to put the square code through the round code ;-) ). Just a thought of the 'in the shower' variety. I also liked the idea of the metagame project (http://satirist.org/learn-game/projects/metagame.html), though I don't see myself taking on a challenge of that magnitude in the reasonably foreseeable future. Cameron Laird wrote in message news:106um6hcr363u14 at corp.supernews.com... > In article , > Peter MacKenzie wrote: > >(Hmm, this might appear as a double posting, but I don't think my last one > >made it through.) > > > >Thanks, but. > > > >("One approach to discussing and comparing AI > >problem solving strategies is to categorize them using the > >terms ''strong'' and ''weak'' methods. Generally, a weak > . > [much more] > . > . > You might like "The Outsider's Guide to Artificial Intelligence" > . > -- > > Cameron Laird > Business: http://www.Phaseit.net From kfast at poczta.onet.pl Wed Apr 14 16:39:14 2004 From: kfast at poczta.onet.pl (Jakub Fast) Date: Wed, 14 Apr 2004 22:39:14 +0200 Subject: Pygame In-Reply-To: References: Message-ID: <407DA172.1020102@poczta.onet.pl> > Well, if it's not due to the licensing [...] The fact that it has been used in commercial projects doesn't imply it really is _commercial-friendly_ -- lgpl does impose obligations that, albeit minor, still are a hassle and require some thought if you're going to use it in your closed-source project. moreover, including it in the python distribution would impose the burden of keeping track of different licenses in your standard modules, which definitely is something you wouldn't want to have ("ok, i used module this and module that, so i'm fine to do this with my program, ... but wait module x uses module y that uses module z which requires me to obey license a... doh). well, at least _i_ hate sifting through a library for a single module that i use that happens to have a more restrictive license... kuba From jbperez808 at wahoo.com Wed Apr 28 05:30:38 2004 From: jbperez808 at wahoo.com (Jon Perez) Date: 28 Apr 2004 09:30:38 GMT Subject: CPU usage of Python interpreter doing empty while loop under XP References: <7kpr805ou6g8ucm9rok4nodkolcp02viig@4ax.com> <8cidnWQfWLreOBPd4p2dnA@powergate.ca> Message-ID: Peter Hansen wrote: > Good, then what you are really looking for is to get away from the > print statement and learn to use "import pdb; pdb.set_trace()". > > This will drop you into a convenient interpreter prompt right in > the frame where it executes (well, one level down, so just type "r" > to return from the set_trace() call to the calling level). From > this prompt you can inspect any variable in your program, execute > code by single-stepping, and so forth. > > Very handy, and it completely obsoletes the "while 1: pass" idea. :-) > > -Peter Thanks for the tip, I'll keep it in mind for next time, although for this thing I'm doing, I might not be able to use pdb because the event driven framework I'm doing (built on top of Fredrik Lundh's console) has to do with a text user interface and I can't have things messing up the screen which is what would happen if I used the pdb technique. To illustrate how careful I have to be about preserving what's on the screen, I have a debugmsg() function which saves the current cursor position, prints out variable values (or whatever I like) to a small unused corner of the screen, then restores the cursor position. Because it's an event driven framework, program flow is hard to predict, so there are situations where I need the program to effectively 'hang' at certain portions (a kind of breakpoint if you will) so I can see the debug message as well as the current state of the screen without it being overwritten immediately by either pdb output or succeeding code that does a screen clear or refresh. I would be able to use pdb if Console allowed you to separate the screen buffer for the program output with that of the command line from which you invoked said program (where the error messages and pdb output should go to), but there doesn't seem to be a way to do that. From steve at ninereeds.fsnet.co.uk Tue Apr 6 12:10:25 2004 From: steve at ninereeds.fsnet.co.uk (Stephen Horne) Date: Tue, 06 Apr 2004 17:10:25 +0100 Subject: Python is faster than C References: <406F0907.96F37EA1@tunes.org> <7xy8pcogaa.fsf@ruckus.brouhaha.com> <406F454B.C4CC8063@tunes.org> <7xekr4vdek.fsf@ruckus.brouhaha.com> <406F5E95.EBE6D3E8@tunes.org> <7x65cgqy5s.fsf@ruckus.brouhaha.com> Message-ID: On 03 Apr 2004 18:23:11 -0800, Paul Rubin wrote: >Armin Rigo writes: >> Ideally: If you do x=range(100); x[50]='hi' then the interpreter first >> builds this optimized range representation and assigns it to x; and when >> in the next statement you modify this list x it says 'oops! i cannot do >> that with this representation', so it reverts to an array-like >> representation (i.e. it creates all 100 elements) and then changes the >> 50th. No gain here. If on the other hand you only ever do 'easy' >> things with your list, like iterate over it or read elements, then it >> can all be done with the range representation, without falling back to >> the array representation. > >Maybe there is something to this. The problem is, once you start where do you stop. At the moment, Armin suggests optimising the a list consisting of a single repeating item. But what about optimising a repeating list with one or two special cases, so that the "x[50]='hi'" above doesn't incur a penalty? Consider integer lists - what about optimising arithetic progressions? Geometric progressions? Progressions with special cases? Progressions that are the intersection, or union, or whatever of other progressions? If the internal implementation doesn't special-case the implementation of operations on these, all you have is lazy evaluation. But if the internal implementation adds special-case implementations of operations, you either end up with an huge number of special case implementation methods (other parameters can end up with special-case implementations, not just 'self') or you have to implement what amounts to a full algebraic solving engine in the Python interpreter. Or else you can just choose to special case the really important types and operations, which I believe Python already does to some degree (an integer is a special case of a long integer, for instance, and an iterator is a special case of a list with only a subset of the operations available to a standard list) and provide the programmer with the tools to easily implement any further special cases that he may need. -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From deetsNOSPAM at web.de Wed Apr 7 11:34:27 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Wed, 07 Apr 2004 17:34:27 +0200 Subject: pam on debian Message-ID: Hi, I want to authenticate users against the shadow mechanism. So I installed the python2.3-pam package and tried to run the example. It works in terms of beeing sucessully executed. But I don't get authenticated. The service name is set to "passwd". I have to admit that I'm no PAM expert, I've only a rough understanding of what happens there. Fiddling around with the service name didn't do anything. Not even turn up an error. Any help on this would be appreciated. -- Regards, Diez B. Roggisch From devnull at example.com Wed Apr 21 00:06:02 2004 From: devnull at example.com (Derek Fountain) Date: Wed, 21 Apr 2004 12:06:02 +0800 Subject: When is a __dict__ not a __dict__? Message-ID: <4085f2a4$0$16601$5a62ac22@freenews.iinet.net.au> Am I correct in thinking that a Python object which comes from a bit of C code doesn't have a __dict__ attribute? I'm trying to poke around inside the objects which control the expat XML parser, but they don't seem to have __dict__s. From sjf at autograf.pl Tue Apr 27 09:17:50 2004 From: sjf at autograf.pl (..:: sjf ::..) Date: Tue, 27 Apr 2004 15:17:50 +0200 Subject: Regular Expressions References: Message-ID: pewnego dnia niejaki Diez B. Roggisch deetsNOSPAM at web.de wstuka? by? ;-) > ..:: sjf ::.. wrote: >> Thanks. And now, let's assume that I have a following strings: >> S1 = "B - TYPE2: any_text_2 TYPE3: any_text_23" >> S2 = "C - TYPE2: any_text_3" >> and I want to have one regular expression that produce only following >> data: ("B", "any_text_2") >> ("C", "any_text_3") >> that is, any characters starting TYPE3 till end will be omitted. >> How do make this? > r"(.) TYPE. : ([^ ]*)" it works as long as any_text_2 and any_text_3 _not_ contains spaces, but in my files these contain spaces and then this regexp cuts any_text_2 (and any_text_3) after first space :(( -- .:: sjf ::.. "Linux is like Wigwam. No gates, no windows... Apache inside ;-)" From tdelaney at avaya.com Wed Apr 28 23:57:16 2004 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Thu, 29 Apr 2004 13:57:16 +1000 Subject: Is classless worth consideration Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE016BCB64@au3010avexu1.global.avaya.com> Michael wrote: > Is there any way to to call a class method without making an instance > of that class? To me that would be useful because you could mimic > modules without having to create a sepperate file. Or is there > already a way to do that? You are explicitly allowed to put anything you want into sys.modules. This was specifically permitted so people could add class *instances* as modules (they were already doing it), but putting a class there would work too. Of course, you'll want to add things like __file__ and __name__ to your class. Tim Delaney From huzhenghui37 at tom.com Wed Apr 7 03:44:07 2004 From: huzhenghui37 at tom.com (huzhenghui37) Date: Wed, 07 Apr 2004 15:44:07 +0800 Subject: what relationship between this mail list and the python group on Google? Message-ID: <4073B147.1010604@tom.com> what relationship between this mail list and the python group on Google? i saw the same info on both From alloydflanagan at comcast.net Wed Apr 21 17:35:41 2004 From: alloydflanagan at comcast.net (A. Lloyd Flanagan) Date: 21 Apr 2004 14:35:41 -0700 Subject: Python 2.3.3 super() behaviour References: <40863bd7$0$25528$afc38c87@news.easynet.fr> <40864674$0$24834$afc38c87@news.easynet.fr> <40864ea6$0$25528$afc38c87@news.easynet.fr> Message-ID: "Nicolas Lehuen" wrote in message news:<40864ea6$0$25528$afc38c87 at news.easynet.fr>... > > In this case, T.__init__ is not called, because list.__init__ does not use > super(). The only clean way to proceed is to change the inheritance order : > TL(T,list). This way, both constructors are called. > I'm surprised that a built-in type doesn't work with super(). Was this a design decision, and if so why, or is this something that should be fixed? From piet at cs.uu.nl Wed Apr 7 17:36:52 2004 From: piet at cs.uu.nl (Piet van Oostrum) Date: 07 Apr 2004 23:36:52 +0200 Subject: String comparison problem References: Message-ID: >>>>> "Senthoorkumaran Punniamoorthy" (SP) wrote: SP> I am printing these information. SP> print string.lower(info_res[2]) SP> print string.lower(md5sum(f_md5)) SP> print len(string.lower(info_res[2])) SP> print len(string.lower(md5sum(f_md5))) SP> print str(string.lower(md5sum(f_md5)) == string.lower(info_res[2])) SP> and the output are SP> 01b7ebfc27437a90cc421c50df8f9ac5 SP> 01b7ebfc27437a90cc421c50df8f9ac5 SP> 32 SP> 32 SP> False SP> I was wondering why the last print statement is returning false when two SP> strings are identical? They are not identical, because md5sum is reading from the file. -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP] Private email: P.van.Oostrum at hccnet.nl From greg at cosc.canterbury.ac.nz Fri Apr 16 00:21:43 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Fri, 16 Apr 2004 16:21:43 +1200 Subject: Wrapper round x86 Assembler In-Reply-To: <8089854e.0404141105.37d09320@posting.google.com> References: <8089854e.0404082353.7bf163a2@posting.google.com> <4dKdnQlIXMIXIevdRVn-gg@powergate.ca> <8089854e.0404100204.504186a0@posting.google.com> <8089854e.0404122329.5dfe5ce1@posting.google.com> <8089854e.0404132323.3283390@posting.google.com> <8089854e.0404141105.37d09320@posting.google.com> Message-ID: Fuzzyman wrote: > The only compielr I have is gcc under mingw - and I'm not at all sure > it's set up right. Does pyrex still need a C-compiler or *is* pyrex a > compiler ? It needs a C compiler. MinGW should be fine (once you get it set up properly, anyway:-). -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From elainejackson7355 at home.com Tue Apr 6 01:23:59 2004 From: elainejackson7355 at home.com (Elaine Jackson) Date: Tue, 06 Apr 2004 05:23:59 GMT Subject: syntax question References: Message-ID: >>> L=[(1,2),(10,20),(100,200)] >>> map(None,*L) [(1, 10, 100), (2, 20, 200)] >>> sum(map(None,*L)[0]) 111 "AF" wrote in message news:c10dc8.0404051323.4594717c at posting.google.com... | If I have a list of touples: | | l = [(x1, y1), (x2, y2), ...] | | Is there a 1 line way to extract and get the sum of each x and y | column. I can do it this way with 2 lines of code and iterating | through the list twice: | | sumx = sum([x for x, y in l]) | sumy = sum([y for x, y in l]) | | Is there a 1 liner way to get the sums of both x and y and only | iterate thru the list once? | | Also, is there a way to extract a list of x's and a list of y's from | the touple list? 1 line of course. | | Thanks! | | AF From jepler at unpythonic.net Wed Apr 21 18:35:03 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 21 Apr 2004 17:35:03 -0500 Subject: problem pickling objects created with the type function In-Reply-To: <85bc2819.0404211357.6ec10ec7@posting.google.com> References: <85bc2819.0404211357.6ec10ec7@posting.google.com> Message-ID: <20040421223503.GA13610@unpythonic.net> Yep. Pickle stores instances by pickling information about the instance, plus a string it uses to find the class. If you do something too clever, like you did above, it doesn't work. Jeff From unendliche at hanmail.net Mon Apr 5 11:14:54 2004 From: unendliche at hanmail.net (Seo Sanghyeon) Date: 5 Apr 2004 08:14:54 -0700 Subject: An attempt at guessing the encoding of a (non-unicode) string References: Message-ID: <45e6545c.0404050714.5db5ccc6@posting.google.com> I think you will find Mozilla's charset autodetection method interesting. A composite approach to language/encoding detection http://www.mozilla.org/projects/intl/UniversalCharsetDetection.html Perhaps this can be used with PyXPCOM. I don't know. From pythonguy at Hotpop.com Tue Apr 13 07:51:56 2004 From: pythonguy at Hotpop.com (Anand Pillai) Date: 13 Apr 2004 04:51:56 -0700 Subject: Making urllib2 work with proxy urls Message-ID: <84fc4588.0404130351.77a1faf0@posting.google.com> My company uses an automatic proxy configuration url of the form http://server.company.com/department/proxy.pac . I have made urllib2 work with normal proxies/firewalls, even the ones requiring authentication, but I am stuck with this problem. I tried getting the actual proxy server IP and configuring urllib2 with the normal way it works with proxies, but it has not worked for me. Any suggestions are welcome. Thanks -Anand From niemeyer at conectiva.com Thu Apr 29 17:04:02 2004 From: niemeyer at conectiva.com (Gustavo Niemeyer) Date: Thu, 29 Apr 2004 18:04:02 -0300 Subject: Closures Message-ID: <20040429210402.GA7316@burma.localdomain> > Would you trade the "mutable integer" and "count(n=[0])" kludges for a > solution like &count ? Does anyone agree with me that a "closure > variable prefix" is more explicit and readable? import sys class Closure: def __init__(self): self.__dict__ = sys._getframe().f_back.f_locals def getFunc(): counter = 0 c = Closure() def count(): c.counter += 1 print c.counter return count c = getFunc() c() c() c() -- Gustavo Niemeyer http://niemeyer.net From mwh at python.net Fri Apr 23 12:02:54 2004 From: mwh at python.net (Michael Hudson) Date: 23 Apr 2004 17:02:54 +0100 Subject: if (__name__ == '__main__'): main(sys.argv[1:]) In-Reply-To: <20040423155026.GB5587@alcyon.progiciels-bpi.ca> References: <01c601c4271b$7f7300a0$b401010a@sparta> <4085A445.1050303@heneryd.com> <20040423155026.GB5587@alcyon.progiciels-bpi.ca> Message-ID: Fran?ois Pinard writes: > [Michael Hudson] > > Fran?ois Pinard writes: > > > > A word about the `__metaclass__' line. My intent is to forget all about > > > classic classes and go with the new type system as quickly as possible. > > > I do not want to derive each and every of my classes from `object', > > > and later edit all those `(object)' out when the classic classes will > > > effectively get deprecated. > > > Why would you do that? > > Your question is surprising, after you just quoted the answer. I guess > I miss the real meaning of your question. In case I confused you, I meant the "edit the '(object)' out" bit. > > I don't like using a __metaclass__ global because it's a non-local > > effect. > > That's exactly why it is useful. You don't like it to be useful? :-) I like my code to do things similar to what it looks like it's doing. To me, class MyClass: ... says "classic class". Cheers, mwh -- Two decades later, well-known hacker Henry Spencer described the Perl scripting language as a "Swiss-Army chainsaw", intending to convey his evaluation of the language as exceedingly powerful but ugly and noisy and prone to belch noxious fumes. -- the jargon file From jepler at unpythonic.net Thu Apr 22 13:57:41 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Thu, 22 Apr 2004 12:57:41 -0500 Subject: equivalent to Tcl 'after' command? In-Reply-To: References: Message-ID: <20040422175741.GD17776@unpythonic.net> Python doesn't define any event loop of its own. asyncore has one, but I don't think it has the concept of scheduling events at a future time, but only of reacting to the readability / writability of sockets. I'm sure that more advanced systems, like Twisted, can do the kind of thing you're asking for. Jeff From kheymann-news03 at ecology.uni-kiel.de Thu Apr 15 07:35:37 2004 From: kheymann-news03 at ecology.uni-kiel.de (Karsten Heymann) Date: Thu, 15 Apr 2004 13:35:37 +0200 Subject: Python for Presentations References: Message-ID: <2322284.zRWg8i6zR0@id-216798.user.uni-berlin.de> Chris wrote: > Is anyone aware of Python packages/software for generating > "presentations"-- something that can generate a nice XHTML/CSS or PDF > presentation would be cool. I am looking for a better alternative to > PowerPoint for building presentation slides, and if that alternative > used Python, that would be even better. > > Otherwise I could use LaTeX or something, I suppose. honestly, use latex! especially latex-beamer is awesome (latex-beamer.sf.net) if you have at least a little knowledge of latex. I use python for nearly all programming tasks, but presentations are another are. Karsten From http Tue Apr 20 15:14:03 2004 From: http (Paul Rubin) Date: 20 Apr 2004 12:14:03 -0700 Subject: PDF library? Message-ID: <7xad1631j8.fsf@ruckus.brouhaha.com> I have a big PDF file that I'd like to crunch, i.e. I want to select a certain rectangular area from each page and make a new PDF combining the selected areas from adjacent pages. I guess that means I need a Python wrapper for GhostScript, or something similar. Anyone know if that exists? Thanks. From gnuoytr at rcn.com Mon Apr 12 16:00:12 2004 From: gnuoytr at rcn.com (robert) Date: 12 Apr 2004 13:00:12 -0700 Subject: why is python better than eg. smalltalk?? no one has any solid arguments! you should all go to church with all that religious talk! References: Message-ID: aahz at pythoncraft.com (Aahz) wrote in message news:... > In article , > Roy Smith wrote: > >aahz at pythoncraft.com (Aahz) wrote: > >> > >> I found my editor fifteen years ago. Guess which it is. > > > >My guess is emacs, in which case I've got 6 or 7 years on you :-) > > Funny that two people made the same guess, when y'all could have gotten > the correct answer by going to my personal web page. ;-) > > http://rule6.info/ > > >> (The point being that there are only two editors still in regular use > >> that were available fifteen years ago -- and those two editors are > >> still ubiquitous now. Doesn't matter much which you pick, they'll > >> still be available fifteen years in the future.) > > > >I suspect you're right, but I don't necessarily think that's a good > >thing. Both emacs and vi have had long runs, but it's logical to assume > >that better things will come along. > > Not too bloody likely. There just isn't any development work on new > console editors these days, and many of us will give up our consoles > when you pry them from our cold, dead fingers. > > >I know it's possible to handle both news and email inside emacs, but I > >use dedicated GUI apps for both of those tasks. I still use emacs for > >programming, but there's some really good IDE's out there, and my guess > >is they will become more and more the norm. And while I curse and wail > >about how bad MS Word is, I also realize that troff just isn't happening > >any more (I did plenty of cursing and wailing about troff back in the > >"good old days"). > > You need to try reST. since my fingers only know vi, i've been using Visual SlickEdit on windoze for a long time, since it does vi. for java and C it does all that syntax stuff. anyone found a super-vi that does the same for python? From gandalf at geochemsource.com Thu Apr 15 02:46:55 2004 From: gandalf at geochemsource.com (Gandalf) Date: Thu, 15 Apr 2004 08:46:55 +0200 Subject: curses and unicode Message-ID: <407E2FDF.7070708@geochemsource.com> Hi All! I have to write an application that can display Chinese charaters in text mode under unix. I found several text mode console programs (like zhcon and big5d). They are able to use English and Chinese characters at the same time, in text mode. (In fact, they are using graphics, but they emulate a standard terminal.) Do somebody know how can I display chinese characters from curses (using one of these console programs)? I'm sure it can be done. For example, midnight commander or lynx can do this: http://zhcon.sourceforge.net/images/scr_mc.gif But I do not know how to do this from Python. I only have the curses module and the addstr method. The addstr method does not support unicode. Should I send a special character sequence with addstr? I'm totally lost. I tried to read the documentation of zhcon but it is in Chinese which I do not understand. :-( Please help me. G From jbore at tjtech.com Tue Apr 13 14:42:29 2004 From: jbore at tjtech.com (Joseph T. Bore) Date: Tue, 13 Apr 2004 18:42:29 GMT Subject: interpreter limits References: <407c23bf$0$570$e4fe514c@news.xs4all.nl> <407c2ecc$0$574$e4fe514c@news.xs4all.nl> Message-ID: Irmen de Jong writes: > Or use alarm() to get signaled after some time, then kill it in > the signal handler. I hadnt thought about using alarm like that, I have to experiment jb From eugine_python at ukr.net Fri Apr 2 05:22:15 2004 From: eugine_python at ukr.net (å×ÇÅÎÉÊ ëÏÓÅÎËÏ) Date: Fri, 02 Apr 2004 13:22:15 +0300 Subject: Compact Python library for math statistics Message-ID: I'm looking for a Python library for math statistics. This must be a clear set of general statistics functions like 'average', 'variance', 'covariance' etc. While googling I found only SalStat, which is rather stand-alone application with GUI on wxWidgets, and I need time and efforts to extract the core engine from it. Apart from this, it does not do some essential things for me, such as multi-component linear regression (y = a0 + a1 x1 + a2 x2 +...), only single-component (y = a0 + a1 x) is available. Does anyone know something more simple-to-use? Something like >> from stat import * >> a = [1, 2, 3, 4, 5, 6] >> print ave(a), var(a), correl(a, a) 3.5 17.3 1.0 Thanks in advance I started write something like for me for my own uses. Is it useful to publish it? -------------- next part -------------- A non-text attachment was scrubbed... Name: ????????????????.doc Type: application/octet-stream Size: 1794 bytes Desc: not available URL: From http Fri Apr 2 03:02:21 2004 From: http (Paul Rubin) Date: 02 Apr 2004 00:02:21 -0800 Subject: String concatenation References: Message-ID: <7xisgi24fm.fsf@ruckus.brouhaha.com> "Leif B. Kristensen" writes: > Having recently started with Python, I've written this little function > to retrieve place parts from a database and concatenate them to a > string. While it certainly works, and is also considerably shorter than > the PHP code that I originally wrote, I'm pretty convinced that there > should be an even better way to do it. Can anybody show me how to write > the string concatenation part in a more Pythonesque syntax? > ... > for i in range(5): > tmp = res[i] > if tmp[:1] != '-' and len(tmp) != 0: > place = place + ', ' + (res[i]) > return place[2:] Not tested: tmp = [x for x in res if x and x[0] != '-'] return ', '.join(tmp) Explanation: 1) you can use "for x in res" instead of looping through range(5), since you know that res has 5 elements (from the sql result). 2) x[:1] is the same as x[0] as long as x has at least 1 char (otherwise it throws an exception) 3) To prevent the exception, test for x being nonempty BEFORE examining x[0] 4) sep.join(stringlist) is the standard way to join a bunch of strings together, separated by sep. From andreas.lobinger at netsurf.de Tue Apr 6 05:14:57 2004 From: andreas.lobinger at netsurf.de (Andreas Lobinger) Date: Tue, 06 Apr 2004 11:14:57 +0200 Subject: FDF to PDF in Python? References: Message-ID: <40727511.A687138C@netsurf.de> Aloha, Sean Berry schrieb: > I am doing a project which will require me to take an FDF and convert it to > a PDF after some information has been filled out. > Is there anything in Python that can help me with this? > I go the FDFToolkitforUnix from Adobe, but it is in Perl and I would much > prefer Python. Has anyone out there done anything like this before? First of all, the FDFToolkit is (afair) a .so with Perl bindings, so using SWIG (or similar tools) you could build adequate Python bindings... The usual way to use .fdf is: - Create a .pdf with form functionality and a means to submit data - Open the file with a web-browser using the AcroReader as plugin - Insert and Submit data to a web-server (the data can be submitted in html/fdf) - Build another .pdf with the data The FDFToolkit is only a parser (afair) for .fdf files/data. To insert your data permanently (which means, you can save/copy/print the .pdf (with the AcroReader)) you need a solution to access (read/modify/write) .pdf files. For all 4 above points there are thinkable python solutions. f.e. i have (very experimentally) handcrafted an example with a .pdf using formfields and a (python) web-server that collects the data and inserts it at the end of the .pdf, so that the submitted data is logged in the file. If you're interested in this -> mail me. For more information about working with .fdf and solutions i would suggest to read comp.text.pdf . Wishing a happy day LOBI From davidf at sjsoft.com Fri Apr 30 04:26:12 2004 From: davidf at sjsoft.com (David Fraser) Date: Fri, 30 Apr 2004 10:26:12 +0200 Subject: Automated installation framework In-Reply-To: References: Message-ID: Nikolai Kirsebom wrote: > Does anyone know of an 'automated installation framework' written in > Python / accessible from Python ? > > Could it be an idea to use the unittest module as a framework for > making such a system, using the 'setup-action' to make precondition > testing, 'run' to do the actual installation and the 'teardown-action' > to do verification. > > Opinions are appreciated. > > > In our case, the target system is (multi-machine) Windows. > > > Nikolai > It sounds like you are looking for the distutils included in Python. Though they could use some enhancement :-) David From eddie at holyrood.ed.ac.uk Mon Apr 26 09:22:04 2004 From: eddie at holyrood.ed.ac.uk (Eddie Corns) Date: Mon, 26 Apr 2004 13:22:04 +0000 (UTC) Subject: A python telnet entry level question References: <108lr8jmr2u1202@corp.supernews.com> Message-ID: claird at lairds.com (Cameron Laird) writes: >In article , >Eddie Corns wrote: > . > . > . >>You are maybe being too specific in what you match for. At least one of my >>machines prompts: >> >> Pasword for : >> >>rather than just "Password: ". I tend to match things like >> >>"ogin" (in case of Login vs login) >>"assword" (will this get filtered out by censoring s/w?) >> >>Eddie >This sort of tolerance can lead to its own problems (though >I entirely agree you're right to recommend it). Some logins >are so sensitive to timing (in essence) that matching >"assword" rather than "assword:" results in the telnetd >ignoring the first character or two of response. >So what to do? At this level, there is *no* good answer. >The most enlightened thought is simply to recognize that >telnet forces one into a cascade of heuristic hacks. And then you get unhelpful router manufacturers that put code in to check whether passwords are typed too fast (or regularly spaced) and ignore them because they're obviously not dealing with a human! Took me ages to figure out why my scripts were failing (then about 10 seconds to defeat it). Yes, using telnet is more art than science but it's a lot better now than before we had expect (for heavy duty jobs) and telnetlib (for simpler jobs). Eddie From gerrit at nl.linux.org Thu Apr 1 14:31:09 2004 From: gerrit at nl.linux.org (Gerrit) Date: Thu, 1 Apr 2004 21:31:09 +0200 Subject: ANNOUNCE: 'goto' for Python In-Reply-To: References: Message-ID: <20040401193109.GA6475@nl.linux.org> Richie Hindle wrote: > This adds the 'goto' and 'comefrom' keywords to Python 2.3, adding > flexibility to Python's control flow mechanisms and allowing Python > programmers to use many common control flow idioms that were previously > denied to them. Why don't we call goto '$@' and comefrom '@$'? From has.temp2 at virgin.net Mon Apr 26 20:04:03 2004 From: has.temp2 at virgin.net (has) Date: 26 Apr 2004 17:04:03 -0700 Subject: seeking feedback and help on HTMLTemplate 0.4.0 Message-ID: <69cbbef2.0404261604.2b1fe5e7@posting.google.com> Hi all, I'm looking for feedback and/or help with preparing my HTMLTemplate module for its version 1.0 release: http://freespace.virgin.net/hamish.sanderson/htmltemplate.html The code and API are now stable, apart from a couple of outstanding issues described in the Manual's TO DO section that I'd like to get input on. The documentation is still very much a work in progress, and has just undergone an almost total rewrite since the previous release. Help on editing what's currently written would be greatly appreciated, as would suggestions on what additional information needs included (first-rate usability is a core ambition/feature). I'd like the 1.0.0 final release by end of next month (beyond which I plan to prepare and submit it for possible inclusion in Python's standard library), so the more spit-n-polish it gets before then the better. Many thanks in advance, has From tzot at sil-tec.gr Wed Apr 7 04:49:00 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Wed, 07 Apr 2004 11:49:00 +0300 Subject: An attempt at guessing the encoding of a (non-unicode) string References: <45e6545c.0404050714.5db5ccc6@posting.google.com> Message-ID: <62g770516sd9c4qeqm8o1rv2eisdc3b0eq@4ax.com> On 5 Apr 2004 08:14:54 -0700, rumours say that unendliche at hanmail.net (Seo Sanghyeon) might have written: >I think you will find Mozilla's charset autodetection method >interesting. > >A composite approach to language/encoding detection >http://www.mozilla.org/projects/intl/UniversalCharsetDetection.html Thank you! >Perhaps this can be used with PyXPCOM. I don't know. Neither do I... -- TZOTZIOY, I speak England very best, Ils sont fous ces Redmontains! --Harddix From t-meyer at ihug.co.nz Thu Apr 22 00:10:32 2004 From: t-meyer at ihug.co.nz (Tony Meyer) Date: Thu, 22 Apr 2004 16:10:32 +1200 Subject: zip 2 sequences into 1 In-Reply-To: <1ED4ECF91CDED24C8D012BCF2B034F1305FF65A3@its-xchg4.massey.ac.nz> Message-ID: <1ED4ECF91CDED24C8D012BCF2B034F1304677CB2@its-xchg4.massey.ac.nz> > How about > > itertools.chain(*zip(seq1, seq2, seq3, ...)) FWIW, this is faster (and nicer, IMO) than the suggestion I posted: [using the 'flatten' function posted] >>> flat.timeit() 8.434350455155613 [using my merge function] >>> merg.timeit() 7.6710651772781162 [using itertools.chain] >>> chai.timeit() 6.4707137359636491 =Tony Meyer From junkmail at solumslekt.org Fri Apr 2 04:00:49 2004 From: junkmail at solumslekt.org (Leif B. Kristensen) Date: Fri, 02 Apr 2004 11:00:49 +0200 Subject: String concatenation References: <7xisgi24fm.fsf@ruckus.brouhaha.com> <406D27A7.6550A00B@alcyone.com> Message-ID: Erik Max Francis wrote: > Probably you included the initial spaces, which is a no-no: No I didn't. The text is properly aligned. The relevant code now looks exactly like this: res=c.fetchone() tmp=[x?for?x?in?res?if?x?and?x[0]?!=?'-'] return?',?'.join(tmp) And here's what the interpreter says: tmp=[x?for?x?in?res?if?x?and?x[0]?!=?'-'] ^ SyntaxError: invalid syntax The marker has moved to the right, maybe because I removed the spaces on both sides of the = sign? regards, -- Leif Biberg Kristensen http://solumslekt.org/ Validare necesse est From newsuser at itgoesclick.com Tue Apr 20 10:48:15 2004 From: newsuser at itgoesclick.com (Noah from IT Goes Click) Date: Tue, 20 Apr 2004 14:48:15 GMT Subject: Thanks, and a URL correction In-Reply-To: References: Message-ID: Thanks Lucas the correct URL is (you got a . instead of a / after com) http://www.pythonware.com/library/tkinter/introduction/ and the PDF link so those who care don't have to dig http://www.pythonware.com/library/tkinter/an-introduction-to-tkinter.pdf From ruses at users.ch Thu Apr 1 15:31:23 2004 From: ruses at users.ch (=?ISO-8859-1?Q?Morris_Carr=E9?=) Date: Thu, 01 Apr 2004 22:31:23 +0200 Subject: Python passes the Turing test with a one-liner ! Message-ID: <406C7C1B.3080401@users.ch> filter(lambda W : W not in 'ILLITERATE','BULLSHIT') From p_s_oberoi at hotmail.com Wed Apr 14 03:43:06 2004 From: p_s_oberoi at hotmail.com (Paramjit Oberoi) Date: Wed, 14 Apr 2004 02:43:06 -0500 Subject: Reommended compiler toolkit References: Message-ID: On Tue, 13 Apr 2004 14:06:19 +0200, Diez B. Roggisch wrote: > Miki Tebeka wrote: > >> ply (which I like most) >> SPARK, Yapps, PyLR, kwParsing >> Plex, FlexModule >> >> Which one do you recommend? Also take a look at 'Toy Parser Generator' http://christophe.delord.free.fr/en/tpg/ I don't know how fast/slow it is, but the specification language is very nice. From cygnus at cprogrammer.org Sat Apr 10 18:50:19 2004 From: cygnus at cprogrammer.org (Jonathan Daugherty) Date: Sat, 10 Apr 2004 18:50:19 -0400 Subject: Python is the best and most popular general purpose scripting language; the universal scripting language In-Reply-To: References: Message-ID: <20040410225019.GA16891@vulcan.cprogrammer.org> # So, what makes something a "scripting language" as opposed to a # "programming language"? In a general sense I think "programming" languages are compiled and "scripting" languages are interpreted. (If you want to go academic, you could say python is both, but the internals of the interpreter are irrelavant insofar as one might say it is an interpreted language.) -- _ ,^. _ ,'/ -' '- \`. / | \ / | \ Jonathan Daugherty | | | | | | | \_,' `._/ | http://www.cprogrammer.org | | \ / `. .' `--._.--' From Marc.Poinot at onera.fr Wed Apr 28 12:18:01 2004 From: Marc.Poinot at onera.fr (Marc Poinot) Date: Wed, 28 Apr 2004 18:18:01 +0200 Subject: numarray on 64 bits Message-ID: <408FD939.7D386321@onera.fr> Did anybody use numarray on a 64 bits platform ? (e.g. SGI/Irix) The package works on our 64 bits platforms... using 32 bits mode, but not using 64 mode. Big crash in _ufunc... Is there a flag to set somewhere, trick, hint, noway ? -MP- ----------------------------------------------------------------------- Marc POINOT Alias: marcvs Email: poinot at onera.fr ONERA -MFE/DSNA/ELSA Tel: 01.46.73.42.84 Info: elsa-info at onera.fr 29, Div. Leclerc Fax: 01.46.73.41.66 Site: 92322 Chatillon FRANCE Project: elsA Web: http://www.onera.fr From Bang_Bang_Your at crawfishnet.com Tue Apr 13 11:00:44 2004 From: Bang_Bang_Your at crawfishnet.com (BANG BANG YOUR) Date: 13 Apr 2004 08:00:44 -0700 Subject: Like most hardcore criminals like Jeff Bond (jbond@nowhere.com) Message-ID: <2fc51cc6.0404130700.68094a77@posting.google.com> Like most hardcore criminals like Jeff Bond (jbond at nowhere.com) washed up firefighter fire boy Like most hard core criminals like Jeff Bond (jbond at nowhere.com) AKA Alan P (alan at nowhere.com AKA Frank he thinks he is smarter then everyone but thats why they end up on amw.com on the run from the cops and most the time in a body bag. Like most hardcore criminals like jeff bond who is a washed up fire boy who has enter the life of crime: Day & Night Stalker, mail theft, Auto theft, harassment phones calls, cyberstalking, Vandalism and more pls. email me for the jeff bond crimes on cd. statements from witness , video, pics. and police reports From fumanchu at amor.org Fri Apr 2 13:00:19 2004 From: fumanchu at amor.org (Robert Brewer) Date: Fri, 2 Apr 2004 10:00:19 -0800 Subject: Deduping (was Fake post) Message-ID: Christian Tismer wrote: > That's nice to hear! I'm interested to know how you got > along with removing relationships between records. With a bit of experimentation, I think the memory issue came down to having a single dict that was too large; at approx 5.5 million items, I believe the dict resized again and ended up thrashing in virtual memory. The quick and simple solution was simply to create 256 dictionaries, distributing them over the first byte. Since this worked with a dataset of 20 million items, I didn't bother taking the next step of SHA-digesting them. Since I had 3 fields on which to independently dedupe, I ended up building each list in a separate pass, as you did. Then, once the full list had been built, I made a single new dict out of the intermediate 256 dicts, passing on any item which only appeared once (this wouldn't work for every situation, but it fit my dataset pretty well, with about 10%-50% duplicates): product = {} for subindex in index.itervalues(): for i in xrange(len(subindex)): key, hits = subindex.popitem() if hits > 1: product[key] = hits return product I also did some validation on this pass, btw, before inserting into the index. Then, I did a second pass on the dataset where I checked for each value (in one of the indexed fields) in the appropriate list of duplicates. If present, I wrote a blank field per my client's request. As I went, I decremented the hitcounts until I reached 1: this should have been the last occurrence of the value, which I printed normally. # Check for dupes if atom in dupes[fieldname]: if dupes[fieldname][atom] <= 1: del dupes[fieldname][atom] else: dupes[fieldname][atom] -= 1 atom = '' The 20-million-record dataset took about 4 hours in total, mostly due to my typing at the keyboard and manually examining each source file to see what order the columns were in. The actual index-building took a few minutes. Robert Brewer MIS Amor Ministries fumanchu at amor.org From fumanchu at amor.org Wed Apr 21 19:06:41 2004 From: fumanchu at amor.org (Robert Brewer) Date: Wed, 21 Apr 2004 16:06:41 -0700 Subject: Cell objects and their values Message-ID: Say I obtain a cell object via: >>> def f(): ... y = 3 ... def g(): ... return y ... return g ... >>> f().func_closure[0] Is there a way to get the value of the int (f.y) which is referenced by the cell, without inspecting (or even having a reference to) f? That is, using only the object "g()" and its attributes, I'd like to obtain the same value for LOAD_DEREF that the interpreter does; in the same way that I can access g.func_globals, I'd like something similar to "g.func_cellvars" (not just the names as in g.func_code.co_cellvars, but the values)... Robert Brewer MIS Amor Ministries fumanchu at amor.org From tjreedy at udel.edu Wed Apr 21 14:48:49 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 21 Apr 2004 14:48:49 -0400 Subject: Optimizing a text statistics function References: <40869EC1.8030504@cenix-bioscience.com> Message-ID: "Neil Benn" wrote in message news:40869EC1.8030504 at cenix-bioscience.com... > In other languages I've used (mainly java although some C, C# VB > ), the way I woud look at speeding this up is to > avoid loading all the words into memory in one go and then working upon > them. I'd create one stream which reads through the file, then passes > onto a listener each word it finds from the lexing (making the input > into tokens) and then another stream listening to this which will then > sort out the detail from these tokens (parsing), finally an output > stream which put this data wherever it needs to be (DB, screen, file, > etc). This means that the program would scale better (if you pass the > European voting register through your system it would take exponentially > much longer as you must scan the information twice). You are talking about chaining iterators, which the generators and the new iterator protocol make easier than before -- intentionally. Something like following (untested). filename = 'whatever' def wordify(source): for line in source: for word in line.split(): yield word.strip() def tabulate(words): counts = {} for word in words: counts[word] = counts.get[word,0] for wordcount in count.iteritems(): yield wordcount def disposer(wordcounts): for wordcount in wordcounts: print wordcount disposer(tabulate(wordify(filename))) > However as more experienced python programmers have not suggested > this is this because there is : > > a. Something I'm not getting about python text handling Nothing obvious. > b. Not easy/possible in python Wrong (see above) c. The OPs question (speedup) was answered a half hour after posting by an experienced P. progammer (use dict.get) -- which answer makes the processing one-pass, which in turn makes chaining possible. d. It has been less than 5 hours since OP posted. e. The OP did not ask how to restructure program to make it more modular. Thinking ahead to make code more reusable and scaleable is a second order concern after learning basics like getting .get(). But since you brought the subject up ... Terry J. Reedy From mtadin66 at yahoo.com Mon Apr 12 07:22:25 2004 From: mtadin66 at yahoo.com (Marijan Tadin) Date: Mon, 12 Apr 2004 12:22:25 +0100 Subject: Best IDE? References: Message-ID: I love SciTE. "Stevie_mac" wrote in message news:c5bg1k$25vq$1 at news.wplus.net... > This has prolly been asked 100 times - so please refrain from flaming if you can... > > What's the best MSwindows editor for python? I'm currently using PythonWin (ActiveState) at the moment, its a bit > buggy - but not too bad. I mean, its got autocomplete & tips & help & autoindentaion (not always good tho). > > Thing is, I'm sure there is something better. Is there? > > (is there a VS.NET addin?) > > From alf at calvin.fayauffre.org Wed Apr 14 05:42:51 2004 From: alf at calvin.fayauffre.org (Alexandre Fayolle) Date: Wed, 14 Apr 2004 09:42:51 +0000 (UTC) Subject: Aspect Programming Module References: <84fc4588.0404140106.3fa0c55@posting.google.com> Message-ID: Le 14-04-2004, Anand Pillai a ?crit?: > Is there any module/toolkit or framework for doing > aspect oriented programming (AOP) in Python? You may want to try the logilab.aspects package, available at http://www.logilab.org/projects/aspects/ -- 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 fgeiger at datec.at Fri Apr 2 02:53:49 2004 From: fgeiger at datec.at (F. GEIGER) Date: Fri, 2 Apr 2004 09:53:49 +0200 Subject: Subclassing file and getting around the file.__init__ rigidity References: <807692de.0404012244.53b476dc@posting.google.com> Message-ID: # Untested code class BufferedFile(file): def __init__(self, name): if type(name) == file: self.__dict__.update(file.__dict__) # Kinda cctor else: file.__init__(self, name) self.buffer = None Cheers Franz "Jan Burgy" schrieb im Newsbeitrag news:807692de.0404012244.53b476dc at posting.google.com... > Hi all y'all, > > Consider the class down below. I've implemented it just because I > needed the pushback method. Now of course the third line in __init__ > doesn't work and I even understand why. My question is: is there any > way to make it work? Somebody proposed a patch for fileobject.c to > allow stuff like fp = file(fp1.fileno()) but it looks like it's been > rejected. I won't so bold as to request a change in Python. Should I > try to re-write this class in C? Although I know C I'm much to lazy to > take on the entire python API, not that it doesn't look nice. > > Thanks for your help > > Jan Burgy > > class BufferedFile(file): > > def __init__(self, name): > if type(name) == file: > self = name # DOESN'T WORK! > else: > file.__init__(self, name) > self.buffer = None > > def readline(self): > if self.buffer: > i = self.buffer.find("\n") > line, self.buffer = self.buffer[:i], self.buffer[:i+1] > else: > line = file.readline(self) > return line > > def pushback(self, line): > self.buffer = line + self.buffer From marbling at hey-diddley-ho.com Tue Apr 6 07:18:29 2004 From: marbling at hey-diddley-ho.com (McLuhan O. Ordain) Date: Tue, 06 Apr 2004 04:18:29 -0700 Subject: Up to 80 percent off on medication, Python. Message-ID: <010001c41bc8$dfac2ec2$29613e7d@hey-diddley-ho.com> HOLA! I suppose some editors are failed writers but so are most writers. Python, searching for a source to shop for medication? I is another. Gossip is the opiate of the oppressed. True courage is a result of reasoning. A brave mind is always impregnable. We ship worldwide He that will be angry for anything will be angry for nothing. Your easy solution is here http://feminie.utdhosw.com/d13/index.php?id=d13 You are absolutely anonymous! But his kiss was so sweet, and so closely he pressed, that I languished and pined till I granted the rest. Education is a social process. Education is growth. Education is, not a preparation for life education is life itself. -------------- next part -------------- An HTML attachment was scrubbed... URL: From joe at notcharles.ca Mon Apr 5 12:33:08 2004 From: joe at notcharles.ca (Joe Mason) Date: Mon, 05 Apr 2004 16:33:08 GMT Subject: Python is faster than C References: <36wn05qkeyk.fsf@hundertwasser.ti.uni-mannheim.de> Message-ID: In article <36wn05qkeyk.fsf at hundertwasser.ti.uni-mannheim.de>, Matthias wrote: > Isn't the whole idea of very high level languages to shift complexity > from the user code to the language implementation? Yes, but there's always a tradeoff to be made. Going through contortions in the VM to make user code only slightly simpler isn't worthwhile. Neither is going through contortions to optimize an extremely rare bit of user code. Also, a big part of keeping user code simple is making the language conceptually simple. If lots of optimizations are done behind the user's back, it can be confusing to remember which operations are already optimized. Take the example of storing large lists as a small pattern and a repetition counter. I'd argue that this is hard to get right at the VM level because you need to consider lots of cases - it's much easier for the user who knows exactly what patterns need to be optimized. I also doubt it will come up too often. Finally, a user might assume the optimization is more powerful than it is - for instance, noticing that huge lists of repeating numbers magically take little memory, they might fill a huge list in randomly and assume it will work. Joe From martin at v.loewis.de Mon Apr 19 16:09:05 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 19 Apr 2004 22:09:05 +0200 Subject: using a USB HID device In-Reply-To: <4083899d.1220139618@news.xs4all.nl> References: <40827ce3.1151345337@news.xs4all.nl> <4082e29d.1177387563@news.xs4all.nl> <4083899d.1220139618@news.xs4all.nl> Message-ID: <408431E1.8080201@v.loewis.de> Wouter van Ooijen (www.voti.nl) wrote: > > But I can live with something that appears to be pure python, like one > which only requires a win-specific addition. after all win32all is > windows-specific too, but I regard it as part of the windows-python > installation. One more dll is no problem, as long as I don't have to > write (and maintain!) it :) So libusb-win32 might be the solution for you (with other libusb incarnations for other systems). Notice, however, that your users need administrator privileges to install a kernel mode driver. Regards, Martin From roy at panix.com Thu Apr 15 18:52:43 2004 From: roy at panix.com (Roy Smith) Date: Thu, 15 Apr 2004 18:52:43 -0400 Subject: CamelCase versus wide_names (Prothon) References: Message-ID: Fran?ois Pinard wrote: > Given full power and choice, what I would prefer is that identifiers be > allowed to contain spaces -- would they have to be unbreakable spaces. > That would be the most legible avenue, especially given that my editors > and enscripters would then bold or colour Python/Prothon keywords, making > it clear the extent of each identifier. That's an interesting point. Most computer languages are written in ASCII. Typographic embelishments(*) like font, size, color, and so on are all ignored. It's only relatively recently that case has become significant. By contrast, the languages of math (maths to you silly Europeans), science, and engineering are full of wonderful typography. Different fonts, character sets, diacritical marks, character placement, and special symbols are all meaningful. For the most part, we struggle along with things like $ sum from x = 0 to inf [ pi sup x * j hat * omega dot ] $ when what we'd write with pen and paper looks nothing like that. Someday, when we finally break out of the 80-column, fixed width, monochrome, monofont, monosize, 7-bit world, our arguments about wide_name vs. bumpyCase will seem just as pre-historic as the $$ gibberish above. (*) Granted, what I call an "embellishement", many people would call "the ability to use all the letters in my native alphabet". From kirk at strauser.com Mon Apr 26 18:05:07 2004 From: kirk at strauser.com (Kirk Strauser) Date: Mon, 26 Apr 2004 22:05:07 GMT Subject: Is Perl *that* good? References: <108q51j4dscn7dc@corp.supernews.com> Message-ID: <87fzaqmm8t.fsf@strauser.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 At 2004-04-26T20:50:22Z, Paramjit Oberoi writes: > I have always felt that just like Jason Orendorff's path.py module makes > working with paths so incredibly convenient, a similarly well-designed > regex.py might make text processing as easy in python as it is in perl. I haven't noticed much of a different between Perl's regex and Python's re.py module, other than I'm now typing: pattern.match(string) instead of string ~= pattern - -- Kirk Strauser The Strauser Group Open. Solutions. Simple. http://www.strausergroup.com/ -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.4 (GNU/Linux) iD8DBQFAjYbp5sRg+Y0CpvERAge8AJ4s6qDPoCVB6BFrBjFOYfhPMTkFoACfcfdZ 6d2x9KAJGe+T67W6W4Y1zVI= =j8qP -----END PGP SIGNATURE----- From peter at engcorp.com Wed Apr 7 09:11:34 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 07 Apr 2004 09:11:34 -0400 Subject: Customizing the python search path depending on source directory In-Reply-To: <5cf809e9.0404070452.643b7053@posting.google.com> References: <5cf809e9.0404061853.41cd3c85@posting.google.com> <5cf809e9.0404070452.643b7053@posting.google.com> Message-ID: Peter Schwalm wrote: > Peter Hansen wrote in message news:> > > Thank you for your answer. But I'm afraid it's not the source > directory but the current working directory. You can see the > difference if you copy the passage > > "for ix1, p1 in enumerate(sys.path): print "%02.02d: %s" % (ix1, > p1)" > > to a "normal script". If you start that "normal script" from a > directory other than the source directory, you can see that both > directories are included in sys.path. If you run this code inside > sitecustomize.py this is not the case. On the contrary. When I start that from another directory which is *not* in the path, I do not see that directory in the sys.path at all, but merely the directory in which the script itself is stored. This is the defined behaviour of the Python sys.path stuff and you must be misinterpreting something. The current directory is *not* added to sys.path, unless it just happens that the main script is in the current directory. -Peter From pythonguy at Hotpop.com Wed Apr 14 05:06:59 2004 From: pythonguy at Hotpop.com (Anand Pillai) Date: 14 Apr 2004 02:06:59 -0700 Subject: Aspect Programming Module Message-ID: <84fc4588.0404140106.3fa0c55@posting.google.com> Is there any module/toolkit or framework for doing aspect oriented programming (AOP) in Python? For example AspectJ from Xerox park is a framework which can be used to do this for Java. Many TIA... -Anand From __peter__ at web.de Fri Apr 30 10:41:50 2004 From: __peter__ at web.de (Peter Otten) Date: Fri, 30 Apr 2004 16:41:50 +0200 Subject: Tkinter: focus/text selection problem with tkFileDialog References: <409259ed$0$574$e4fe514c@news.xs4all.nl> Message-ID: Irmen de Jong wrote: > Hi, > I'm having trouble with the code below. > It's just a regular Tk text widget in which you can type and > select text as expected, however the call to > tkFileDialog.askopenfilename() seems to screw things up. After the file > dialog, I can no longer use the Text widget (typing, selecting, it doesn't > work anymore!) What am I doing wrong? No sure, but opening the dialog before entering the main loop could be the problem. The following modification seems to work: import Tkinter, tkFileDialog window = Tkinter.Tk() txt = Tkinter.Text(window) txt.insert(Tkinter.END, "Choose a file, then try to select me") txt.pack() def openFile(event=None): name = tkFileDialog.askopenfilename() txt.insert(Tkinter.END, "\nFile chosen: " + name) txt.focus_set() window.after_idle(openFile) window.mainloop() Peter From katximan at gmx.net Tue Apr 6 19:51:29 2004 From: katximan at gmx.net (Asier) Date: 6 Apr 2004 16:51:29 -0700 Subject: Compact Python library for math statistics References: Message-ID: <4e1cc86c.0404061551.17caaa10@posting.google.com> > > I'm looking for a Python library for math statistics. This must be a cl > ear set of general statistics functions like 'average', 'variance', 'cova > riance' etc. Have you looked at PyGSL? http://pygsl.sf.net I've programmed with the GSL library in C and works very well and fast. It has code for a very long list of mathematical functions. Currently pygsl is a WIP but has some modules completed. -- Asier. From jeffbarish at starband.net Mon Apr 5 17:01:32 2004 From: jeffbarish at starband.net (Jeffrey Barish) Date: Mon, 05 Apr 2004 15:01:32 -0600 Subject: CSV ignores lineterminator References: <16497.47126.723619.586429@montanaro.dyndns.org> Message-ID: Skip Montanaro wrote: >>>>>> "Jeffrey" == Jeffrey Barish writes: > > Jeffrey> With > Jeffrey> input_data = ['word1\tword2;word3\tword4;', > Jeffrey> 'word5\tword6;word7\tword8;'] > > Jeffrey> and > > Jeffrey> delimiter = '\t' > Jeffrey> lineterminator = ';' > > Jeffrey> shouldn't csv.reader(input_data, dialect='mydialect') > return > > Jeffrey> ['word1', 'word2'] > > Jeffrey> as the first row? I find that it doesn't matter how I > set Jeffrey> lineterminator, csv always terminates at the end of > the line returned Jeffrey> by the iterable object passed as its > first argument (input_data, in > Jeffrey> this case). I must be missing something basic here. > > Jeffrey> I may be confused about the interaction between what > iterable Jeffrey> object defines as the next row and what > csv.reader defines as Jeffrey> the next row. > > Perhaps. Think of input_data as the conceptual result of > f.read().split(lineterminator) (though without loss of the line > terminator): > > >>> input_data = ['word1\tword2;', > >>> 'word3\tword4;','word5\tword6;', 'word7\tword8;'] import csv > >>> class d(csv.excel): > ... delimiter='\t' > ... lineterminator=';' > ... > >>> rdr = csv.reader(input_data, dialect=d) > >>> rdr.next() > ['word1', 'word2;'] > >>> rdr.next() > ['word3', 'word4;'] > >>> rdr.next() > ['word5', 'word6;'] > >>> rdr.next() > ['word7', 'word8;'] > > Skip > Thanks for your reply. Yes, I expect your example to work because each entry in the list defines a "line" regardless of csv: for line in input_data: print line word1 word2; word3 word4; word5 word6; word7 word8; In fact, if you leave out the semicolons, you get exactly the same list (sans semicolons, of course), so csv is terminating lines even though the lineterminator is not there. In my example, the first "line" of the list is 'word1\tword2;word3\tword4'. What I expect to happen is that the list passes the entire line to csv.reader(), which then splits off 'word1\tword2' as the first line by virtue of the presence of the lineterminator ';' and then continues to scan what remains. As there is no line terminator after 'word3\tword4', I expect csv.reader() to pull in the next "line" of the list in its search for another lineterminator, which it finds after word6, so the next line from cvs would be 'word3\tword4word5\tword6'. I don't see any evidence that cvs is terminating lines based on lineterminator rather than the termination used by the iterator object. -- Jeffrey Barish From no.email at please.com Fri Apr 9 19:03:07 2004 From: no.email at please.com (Stevie_mac) Date: Sat, 10 Apr 2004 00:03:07 +0100 Subject: Simple Class Question - need clarity please Message-ID: OK, 1st off, I'm brand new to python so all help is appreciated. Right... Lets say I want a class called Window. It will have some functions namely DoModal() Now this class is inherited in MyClass What is wrong with this?... import win32con, win32ui from pywin.mfc import dialog #, window class Window: def MakeDlgTemplate(self): style = win32con.DS_MODALFRAME | win32con.WS_POPUP | win32con.WS_VISIBLE | win32con.WS_CAPTION | win32con.WS_SYSMENU | win32con.DS_SETFONT dlg = [ ["My Dialog", (0, 0, 100, 100), style, None, (8, "MS Sans Serif")], ] s = win32con.BS_PUSHBUTTON | win32con.WS_CHILD | win32con.WS_VISIBLE dlg.append([128, "Cancel", win32con.IDCANCEL, (55, 80, 40, 16), s]) return dlg def DoModal(self): mw = win32ui.CreateDialogIndirect( self.MakeDlgTemplate() ) mw.DoModal() w = Window() w.DoModal() ^ ^ ^ This Works ^ ^ ^ but if I disable w = Window() & w.DoModal() and derive from this class . . . # file test.py # import mywindow class MyClass(mywindow.Window): def Show(self): self.DoModal() t = MyClass() t.Show() . . . I get NameError: global name 'MakeDlgTemplate' is not defined ??? another 1 I managed to clear up was . . . TypeError: Show() takes no arguments (1 given) . . . until I added 'self' to the Show function ??? I really am struggling with this - some real clarity is needed - can anyone explain the rules (I've read stuff & dissected samples, but I still struggle when it comes to this. If someone can clear this up for me, I should be flying as I am familiar with the concepts of OOP) I'm also struggling with other things like... Where do I save .py files? Will 'import' find my files where ever they are? (obviously not but...) What basic should be considerations when deriving classes? any help will be greatly appreciated - Ta Stevie_Mac From SDNS-SA at kv.ukrtel.net Thu Apr 8 07:57:04 2004 From: SDNS-SA at kv.ukrtel.net (SDNS-SA at kv.ukrtel.net) Date: Thu, 8 Apr 2004 14:57:04 +0300 Subject: [MailServer Notification] To Sender a virus was found and action taken. Message-ID: <812247F89B71D7118491003048244AF001D203E3@sdns.kv.ukrtel.net> ScanMail for Microsoft Exchange took action on the message. The message details were: Sender = python-list at python.org Recipient(s) = ems at kv.ukrtel.net; Subject = Mail Delivery (failure ems at kv.ukrtel.net) Scanning time = 04/08/2004 14:57:04 Engine/Pattern = 6.810-1005/853 Action taken on message: The attachment message.scr contained WORM_NETSKY.P virus. ScanMail took the action: Deleted. Warning to sender. ScanMail has detected a virus in an email you sent. From FBatista at uniFON.com.ar Thu Apr 15 16:30:30 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Thu, 15 Apr 2004 17:30:30 -0300 Subject: Breakpoint in IDLE's debugger Message-ID: I want to start my program under the IDLE's debugger, click "Go", and let the program run. But also want that if the program goes through a specific line of code, to stop and let me advance with "Step" or "Over" buttons. In Borland C++ 4.0 this was called "breakpoint": you mark a line with a breakpoint and get that behaviour. Exists something similar in IDLE? Thank you! . Facundo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA La informaci?n contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener informaci?n confidencial o propietaria, cuya divulgaci?n es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no est? autorizado a divulgar, copiar, distribuir o retener informaci?n (o parte de ella) contenida en este mensaje. Por favor notif?quenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magn?tico) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telef?nica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electr?nicos pueden ser alterados, motivo por el cual Telef?nica Comunicaciones Personales S.A. no aceptar? ninguna obligaci?n cualquiera sea el resultante de este mensaje. Muchas Gracias. -------------- next part -------------- An HTML attachment was scrubbed... URL: From sridharinfinity at yahoo.com Sat Apr 3 05:46:52 2004 From: sridharinfinity at yahoo.com (Sridhar R) Date: 3 Apr 2004 02:46:52 -0800 Subject: GUI Frameworks in Python? References: Message-ID: <930ba99a.0404030246.786455f5@posting.google.com> "Hugh Macdonald" wrote in message news:... > I've recently been trying out various different GUI frameworks in Python and > was wondering if I could get your input on the pros and cons of the > different ones... > > wxPython: I love the programming side of wxPython, but I find it's just so > slow to initialise in the first place. > > Tkinter: While it's fast to load up, the syntax has never really appealed to > me > > GTK: Unknown - I'm looking into it today > > Qt: I have yet to manage to install it on my system > > Anything else? > > > Hugh Macdonald Man, you better use PyGTK (http://pygtk.org). It's portable (See pygtk faq for windows port). It's neet (API). Try also `glade`, `libglade`. http://glade.gnome.org , I think? From http Sun Apr 11 21:11:42 2004 From: http (Paul Rubin) Date: 11 Apr 2004 18:11:42 -0700 Subject: Python OS References: <107j4eu6ffn2c68@corp.supernews.com> <107jq68ao58o7ff@corp.supernews.com> Message-ID: <7xy8p2m241.fsf@ruckus.brouhaha.com> "A Evans" writes: > Hey thanks everyone for the replies I guess it would be quite the task to > embark on I would like to do it and I think I will over the next couple of > years as my skills improve and I start saving some cash to get it off the > ground and to get other programmers and planners involved. Don't put any cash into it. Just start up a Python window and see how far you can go. You'll learn a lot whether you come up with anything useful or not. From fumanchu at amor.org Sat Apr 17 20:53:51 2004 From: fumanchu at amor.org (Robert Brewer) Date: Sat, 17 Apr 2004 17:53:51 -0700 Subject: Proposed PEP: Treating Builtins as Constants in the Standard Library Message-ID: Raymond Hettinger wrote a new PEP proposal: > For each module in the standard library, add a pair of lines near > the near of the code:: I think you meant, "near the end of the code". ;) > Q. Why not make this a public module so that users can > optimize builtins > or builtins and globals in their own code? > > A. The ASPN recipe [2]_ is provided for this purpose. It > takes a modicum > of skill to use correctly and not inadvertently tranform a > non-constant. HmmmmMmmmm..yeah... but then so does your garden-variety "while True:" loop. I for one would hate reusing the ASPN one when there's one not only already written but already loaded(!). And...as the builtin matures, I doubt the cookbook recipe will keep pace. Meh. I'm going to have to think more about that one. Robert Brewer MIS Amor Ministries fumanchu at amor.org From simon at struktur.de Mon Apr 5 03:59:56 2004 From: simon at struktur.de (Simon Eisenmann) Date: Mon, 05 Apr 2004 09:59:56 +0200 Subject: Python 2.3.3 SuSE Linux RPMs available Message-ID: Hi, during building Plone2 rpms for SuSE linux i was forced to create python 2.3.3 rpms for this linux distribution. As this may be useful for ppl outside the zope community as well i post this here. See http://longsleep.org/howto/suse9-python233 for a howto to get Python 2.3.3 installed by rpm on SuSE linux. cheers, Simon From mrroach at okmaybe.com Wed Apr 21 11:10:00 2004 From: mrroach at okmaybe.com (Mark Roach) Date: Wed, 21 Apr 2004 15:10:00 GMT Subject: Can't spawn, or popen from daemon In-Reply-To: References: <1082481539.1395.21.camel@localhost> Message-ID: <1082560180.1395.39.camel@localhost> Thanks to both of you guys for your responses, it turned out to be a simple programmer-error (no surprise). The original, non-daemon version of my program could take input from stdin or from argv[1] and I was trying to test using stdin, forgetting somehow that I had explicitly closed it already... I amaze myself sometimes... Thanks again, Mark From paul at prescod.net Fri Apr 9 20:15:03 2004 From: paul at prescod.net (Paul Prescod) Date: Fri, 09 Apr 2004 17:15:03 -0700 Subject: module not callable - why not? In-Reply-To: References: Message-ID: <40773C87.6030602@prescod.net> Terry Reedy wrote: > ... >>from quaternion import quaternion >>would solve that - but AFAIK thats considered bad for some reasons. > > > By who? and why would you let whoever override your preference ;-) > I have only read suggestions that one be careful with from x import *. If you use the "import from X from Y" form you need to understand the implications. It isn't just a shorter way of referring to Y. You're also removing a level of indirection that you have when you refer to it via X.Y. This means that if someone rebinds X.Y you won't see that. Typically you don't care but in some cases you might. Paul Prescod From garryknight at gmx.net Mon Apr 5 17:04:29 2004 From: garryknight at gmx.net (Garry Knight) Date: Mon, 05 Apr 2004 22:04:29 +0100 Subject: Up to 80 percent off on medication, Python. References: Message-ID: <1081199068.13889.0@eunomia.uk.clara.net> In message , Moon D. Rungs wrote: > Python, searching for a source to purchase medication? > A moment's insight is sometimes worth a life's experience. > The quality of decision is like the well-timed swoop of a falcon which > enables it to strike and destroy its victim. There is a tendency for > things to right themselves. You should be *taking* your medication, not trying to sell it on to others... -- Garry Knight garryknight at gmx.net ICQ 126351135 Linux registered user 182025 From greg at cosc.canterbury.ac.nz Sun Apr 25 22:43:51 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Mon, 26 Apr 2004 14:43:51 +1200 Subject: Why we will use obj$func() often In-Reply-To: References: <84Uhc.22278$dZ1.5087@fed1read04><8AWhc.23114$dZ1.11070@fed1read04> <40883BFE.B381518A@alcyone.com><27_hc.23801$dZ1.2716@fed1read04> <40887145.789A2FE8@alcyone.com> Message-ID: Mark Hahn wrote: > I just meant that people "pre-judge" Prothon based on it's looks. That argument might make sense if looks were irrelevant to the usability of a language, but they're not -- looks have a lot to do with readability. It's probably fair to say that readability is *all* about looks. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From max at alcyone.com Mon Apr 5 14:41:49 2004 From: max at alcyone.com (Erik Max Francis) Date: Mon, 05 Apr 2004 11:41:49 -0700 Subject: Intermittant slow startup References: <9badaf0.0404051033.9fec2db@posting.google.com> Message-ID: <4071A86D.97CA6CAE@alcyone.com> Michael Mossey wrote: > Runnng python 2.2 on HP-UX, I get intermittant slow startup. > Sometimes python starts up in a small fraction of a second, and > sometimes takes 3-5 seconds. This applies to any script I run, or > just typing 'python' at the prompt. > > I also observed something similar on Linux. > > Any ideas what would cause *intermittant* slow startup? Caching? Is it a long time between invocations that it takes a long time to start up? -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis \__/ A father is a thousand schoolmasters. -- Louis Nizer From pinard at iro.umontreal.ca Wed Apr 21 08:37:31 2004 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Wed, 21 Apr 2004 08:37:31 -0400 Subject: if (__name__ == '__main__'): main(sys.argv[1:]) In-Reply-To: <4085A445.1050303@heneryd.com> References: <01c601c4271b$7f7300a0$b401010a@sparta> <4085A445.1050303@heneryd.com> Message-ID: <20040421123731.GA6986@alcyon.progiciels-bpi.ca> [Erik Heneryd] > Eli Stevens (WG.c) wrote: > >I have a question about proper Python style when it comes to having a main > >function in a module. > http://www.artima.com/weblogs/viewpost.jsp?thread=4829 I asked myself the same question for a good while, and came up with the following skeleton from nearly all my Python programs. At times, I was removing lines below which appeared superfluous to me for smallish scripts, but found out in the long run that, sooner or later for any script which was surviving for some while, I have to add back the lines I removed, while adding new features as needed in such scripts, so I now stick to that skeleton. More comments follow below. ----------------------------------------------------------------------> #!/usr/bin/env python # -*- coding: Latin-1 # Copyright ? 2004 Progiciels Bourbeau-Pinard inc. # Fran?ois Pinard , 2004. """\ """ __metaclass__ = type class Main: def __init__(self): pass def main(self, *arguments): import getopt options, arguments = getopt.getopt(arguments, '') for option, valeur in options: pass run = Main() main = run.main if __name__ == '__main__': import sys main(*sys.argv[1:]) ----------------------------------------------------------------------< If that file is imported instead of executed as a main program, the `Main.main' method does not execute, but the `Main' object is still instantiated and available within the imported module under the name `run'. This can be used to call its methods, modify its options, etc. The role of `__init__' is to setup the `run' object, and in particular, to initialise default values for run options. The `main' method proper goes after the `pass' at its end, which gets replaced, of course, by option processing if any. The strange `*' which appears in two place is so that `main' may be called after the module being imported, with a variable number of explicit arguments. This has proven to be the most natural and convenient way to proceed: we think of the `main' method as accepting a list of arguments, not a bundle them in a list or tuple. This is useful, in particular, in an interactive Python session. The program name is not a useful first argument in the general case, this is why it is excluded in the last line of the above template, when the module is run as a script. Of course, the initial doc string is meant to be filled appropriately. A word about the `__metaclass__' line. My intent is to forget all about classic classes and go with the new type system as quickly as possible. I do not want to derive each and every of my classes from `object', and later edit all those `(object)' out when the classic classes will effectively get deprecated. Much easier and cleaner to remove that `__metaclass__' line then. Moreover, by using this `__metaclass__' line in all my things, I do not risk obscure bugs because I forgot one of these `object' derivation while I used more recent Python features. Finally, to criticise myself, I'm not satisfied with the copyright line, as it does not really state the copyright terms and conditions. I'm used to include that copyright in all my things, or almost, but I should either retract the line, or state conditions, for it to be meaningful. Currently, people sometimes write to me to clarify conditions -- which are GPL usually, yet my real intent in such things is to favour freedom for both programming and programmers, much more than spousing FSF politics which do not address both with equal attention! :-) -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From jzgoda at gazeta.usun.pl Sun Apr 18 03:54:19 2004 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Sun, 18 Apr 2004 09:54:19 +0200 Subject: Catching console output interactively References: Message-ID: Dnia Fri, 16 Apr 2004 13:56:24 +0100, Byrom, R (Rob) pisze: > I'd like to be able to trap console output as the user writes > interactively. For example if the user press the up or down keys I'd > like to be able to catch this and return the last executed command (a > bit like the bash_history idea). Can anyone point me in the right > direction? This is feature of GNU readline library, available on some Unix and Unix-like systems. If you want to build something, that resembles Unix shells, you can use class Cmd from cmd module. This class uses readline if it is available on host system. I don't know, how it behaves on Windows and if it uses capabilities of cmd.exe. -- Jarek Zgoda http://jpa.berlios.de/ From shalabh at cafepy.com Tue Apr 13 21:55:42 2004 From: shalabh at cafepy.com (Shalabh Chaturvedi) Date: Tue, 13 Apr 2004 18:55:42 -0700 Subject: Adding properties to objects In-Reply-To: <3a8e83d2.0404131327.33dfe92a@posting.google.com> References: <3a8e83d2.0404130906.2ea796e9@posting.google.com> <3a8e83d2.0404131327.33dfe92a@posting.google.com> Message-ID: Matthew Barnes wrote: > matthew at barnes.net (Matthew Barnes) wrote: > >>Is it possible to add properties to objects dynamically? You can add properties dynamically, but to the type (i.e. 'class') and not the instance (i.e. 'object'). For your example: >>> x = Foo() >>> def f(a,b=None): # a bogus getter, setter, deleter ... print a,b ... >>> Foo.property = property(f,f,f) >>> x.property <__main__.Foo object at 0x008F3CB0> None >>> x.property = 1 <__main__.Foo object at 0x008F3CB0> 1 >>> del x.property <__main__.Foo object at 0x008F3CB0> None >>> This property will work for *all* instances of Foo. > > So the impression I'm getting is that it's *possible* but not really > intended, otherwise there would be better support in the core > language. Fair statement? I don't see any reason why dynamically adding properties to the *type* is not intended. It's not complicated and works fine. > I'll take that as a clue that there's probably a cleaner approach to > the problem I'm trying to solve. What is the problem you are trying to solve? > The feedback was informative... thank you all! > > Matthew Barnes HTH, Shalabh From mark at prothon.org Fri Apr 23 19:36:15 2004 From: mark at prothon.org (Mark Hahn) Date: Fri, 23 Apr 2004 16:36:15 -0700 Subject: Why we will use obj$func() often References: <84Uhc.22278$dZ1.5087@fed1read04> <8AWhc.23114$dZ1.11070@fed1read04> <40883BFE.B381518A@alcyone.com> <27_hc.23801$dZ1.2716@fed1read04> <40887145.789A2FE8@alcyone.com> <7cki80hj976bia36lhf9er97v073o1pqvm@4ax.com> Message-ID: "Donn Cave" wrote ... > What you're doing there looks to me a bit like Objective > CAML's ref type. "a = ref 0" is a mutable container for an > immutable integer. It's just syntactic sugar for a mutable > record; the sugar is the assignment a := 1, and then there's > some special dereference notation -- a := !a + 1, something > like that, I forget. I'm not doing anything nearly that complex. &var just gives access to the outer closure scope and directly accesses var in that scope, just like accessing a global variable. It isn't just syntax sugar for var[0] because it has none of the list overhead associated with the var[0] kludge. & just tells the compiler where to find the variable, just like capitalized variables in Prothon say to find them in the global space and .var says to find var in self. The whole point is to make things simpler, more readable, and more efficient, but when people see the & symbol they somehow automatically think it's complex. Maybe my mind doesn't work like everyone else's. From psXdaXsilva at esotericaX.ptX Fri Apr 9 23:04:21 2004 From: psXdaXsilva at esotericaX.ptX (Paulo da Silva) Date: Sat, 10 Apr 2004 04:04:21 +0100 Subject: Parsing cmd line args problem In-Reply-To: <1081555827.877735@jubilee.esoterica.pt> References: <1081555827.877735@jubilee.esoterica.pt> Message-ID: <1081566459.617750@jubilee.esoterica.pt> Paulo da Silva wrote: I got it to work! Is there a better way? > Hi. > > I am writing my 1st. python program and I have the following problem: > > I need to build a list of lists (or tuples) for every -i option. > Example: > prog -i xxx -i yyy > and get a list like [[xxx,1],[yyy,1]] > > I have tried this (callback) without any success: > > .... Here is what I did! > def ixOpt(option,opt,value,parser): if parser.values.ix is None: parser.values.ix=[] parser.values.ix.append([value,1]) > > def parseArgs(): > .... > add_option("-i", "--include", > action="callback",callback=ixOpt, > type="string",dest="ix", > help="Include file PATTERN",metavar="PATTERN") > > Any help please? > Thanks From mail at markus-franz.de Mon Apr 19 14:14:32 2004 From: mail at markus-franz.de (Markus Franz) Date: Mon, 19 Apr 2004 20:14:32 +0200 Subject: Processes with timeout Message-ID: Hi. My little Python script creates some child-processes depending on how much command line options were given: for myvalue in sys.argv[1:]: pid = os.fork() if pid == 0: do_something() # placeholder for operations break Now I do some difficult things inside each child process (above: function do_something). These operations may take a long time. How can I make it sure that every child-process terminates after x senconds (wether it has finished or not)? I don't know how to force a child-process to kill itself after x seconds. I also don't know how to force a main process (parent) to kill a child-process after x seconds. I searched for something like: for myvalue in sys.argv[1:]: pid = os.fork() if pid == 0: os.exit(timeout) do_something() # placeholder for operations break But there was nothing like this... Do you have an answer to my question??? Thank you. Best regards Markus Franz From faassen at infrae.com Mon Apr 26 07:51:06 2004 From: faassen at infrae.com (Martijn Faassen) Date: Mon, 26 Apr 2004 13:51:06 +0200 Subject: EuroPython news april 26th Message-ID: Hi there, Back with your regular EuroPython reminder. EuroPython 2004 is to be held in G?teborg, Sweden on June 7-9. For more information, see here: http://www.europython.org The talk submission deadline is TODAY, monday the 26th. If you want to submit a talk and it's still today (the 26th of april :) when you're reading this, then go ahead and head here quickly: http://www.europython.org/conferences/epc2004/info/ Hope to see you there! Regards, Martijn From claird at lairds.com Tue Apr 6 20:22:33 2004 From: claird at lairds.com (Cameron Laird) Date: Wed, 07 Apr 2004 00:22:33 -0000 Subject: Capturing stdout incrementally References: Message-ID: <1076ie9gkemub5a@corp.supernews.com> In article , David Bolen wrote: >Josiah Carlson writes: > >> > I am on Windows by the way, so the utilities are printing to the windows >> > command shell. . . . >In general, the only way to fix this is through the program being >called, and not the program doing the calling. In some cases, the . [still more true stuff] . . >On Unix, a classic way around code for which you have no source is to >run it under expect or some other pty-simulating code rather than a >simple pipe with popen. I'm not sure if there's a good pty/expectish >module that works well under Windows (where simulating what a >"console" is can be tougher). . . . This press release just came today: VANCOUVER, BC - April 6, 2004 - ActiveState, a leading provider of professional tools for programmers, today announced Expect for Windows 1.0, releasing the real power of Expect to the Windows platform. ActiveState Expect for Windows is up-to-date, quality assured, and ... . It's not just a press release, by the way; it's a real product, and a good one, if limited by the difficulties of Windows. -- Cameron Laird Business: http://www.Phaseit.net From nhodgson at bigpond.net.au Thu Apr 29 07:10:10 2004 From: nhodgson at bigpond.net.au (Neil Hodgson) Date: Thu, 29 Apr 2004 11:10:10 GMT Subject: Scintilla/SciTE - Python folding References: Message-ID: Nuff Said: > I normally open a file either with 'fold.on.open=1' set in > the user's options file resp. I use 'toggle all folds' from > the menu to fold everything in an unfolded file. > But then, when I unfold e.g. a class, everything inside the > class gets unfolded, too. What I would need is something like > 'unfold one level only'. Thought, that maybe the keystroke > 'Ctrl-Keypad*' was meant for that, but it doesn't work that way. > > I am using Scintilla/SciTE 1.59 (Linux / compiled from the > sources). There is currently no support for this in SciTE. Scintilla doesn't implement the 'policy' layer of folding although most containers have copied SciTE's commands (fold click, fold ctrl click and fold ctrl shift click). The toggle all folds really only toggles the top level folds. If you want to fold a class completely, from the unfolded state: fold ctrl click. Then you can uncover one layer with fold click. There are lots of folding command variants that may be interesting, but many of the ones that sound useful seem both language and context sensitive: for example, a command for python that folds away function and method bodies, but leaves those bodies unfolded internally so they can be viewed with a single click. Neil From fredrik at pythonware.com Wed Apr 21 11:43:51 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 21 Apr 2004 17:43:51 +0200 Subject: Dollar sign ($) on foriegn keyboards? (prothon) References: Message-ID: Mark Hahn wrote: > Sorry if I annoy, but I've only posted a total of about 4 thread-starting > messages. The hundreds of messages have been replies. when I posted my message, 25 of 48 messages visible in my newsreader were Prothon-related. that's a lot of noise, for all those who read comp. lang.python because they're interested in Python. > We do have active Prothon mailing lists, but no international members yet, > which is why I asked this particular question here. if you're serious about doing user research among Python users, you can do a lot better than posting sporadic questions to a newsgroup. only a small number of all Python users reads comp.lang.python; only a small number of those that read the newsgroup posts to it, and only a small number of those that posts are contributing to your threads. you can get a lot better results and generate a lot less noise by doing a web-based questionaire, and post a single invitation here and in other forums where Pythoneers gather. > When I posted my first Prothon messages, I asked if I should stay away from > c.l.p. out of courtesy. I was specifically told to hang around here by > several of the top Pythoneers strangely enough, I don't see any top Pythoneers contributing to the Prothon threads. who are they? From rogerb at rogerbinns.com Sat Apr 3 15:22:05 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Sat, 3 Apr 2004 12:22:05 -0800 Subject: An attempt at guessing the encoding of a (non-unicode) string References: Message-ID: <80j3k1-ijc.ln1@home.rogerbinns.com> Christos TZOTZIOY Georgiou wrote: > This could be implemented as a function in codecs.py (let's call it > "wild_guess"), that is based on some pre-calculated data. Windows already has a related function: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/intl/unicode_81np.asp Read more about it here: http://weblogs.asp.net/oldnewthing/archive/2004/03/24/95235.aspx Roger From kdahlhaus at yahoo.com Thu Apr 8 08:55:53 2004 From: kdahlhaus at yahoo.com (Kevin Dahlhausen) Date: 8 Apr 2004 05:55:53 -0700 Subject: GUI Frameworks in Python? References: Message-ID: <283adf56.0404080455.bfa020a@posting.google.com> I'm a big fan of pyFltk (http://pyfltk.sourceforge.net/): from fltk import * def theCancelButtonCallback(ptr): import sys sys.exit(0) window = Fl_Window(100,100,200,90) window.label(sys.argv[0]) button = Fl_Button(9,20,180,50) button.label("Hello World") button.callback(theCancelButtonCallback) window.end() window.show(len(sys.argv), sys.argv) Fl.run() Does not look like a win-32 app under win-32 though. From jhouchin at texoma.net Mon Apr 19 12:31:53 2004 From: jhouchin at texoma.net (Jimmie Houchin) Date: Mon, 19 Apr 2004 16:31:53 GMT Subject: CamelCase versus wide_names (Prothon) References: <407ec022$0$54153$1b2cd167@news.wanadoo.nl> Message-ID: <4083efb6.87338343@news.texoma.net> On Fri, 16 Apr 2004 18:04:07 -0400, Jack Diederich wrote: >On Thu, Apr 15, 2004 at 11:05:29AM -0700, Mark Hahn wrote: [snip] >> Now I'll go through all the Python method and var names and convert them all >> to camelCase for Prothon. It shouldn't be a problem for users since the >> conversion is mechanical. >Noooooo! > >As others have pointed out down the thread, don't just go on the first >several replies. > >I'm a wide_case_fanboy, having done mixedCase and wide_names over the last >fifteen years. It all comes down to personal preference, of course. IMO >mixedCase people tend to be younger, and younger people tend to be more >zealous on newsgroups. Age has little to do with this. It probably has more to do with the environment in which the person learned programming or does their programming. mixedCase is minimally as old as Smalltalk 76. mixedCase it "the" way you define names in Smalltalk. So there is a minimum of 28+ years of mixedCase programming. Some of the oldest programmers I know of are Smalltalkers. I do not even claim that Smalltalk originated mixedCase >I'm also a native English speaker, so this_looks_like_words while >thisLooksAwkward. I can read/write both and do depending on who is paying >for the project, but I much prefer the underscores. I can also type 100+ >words per minute (much faster than I can think) so I'm limited by figuring >out what I want to do and not by hitting shift-minus. Smalltalk was developed by and for native English speakers. It was aimed at being syntactically suitable for children. Squeak is being used to teach elementary school children across the world. http://www.squeak.org Squeak is an open source Smalltalk 80 implementation which has progressed over the years. >Mixed case works fine on two word variables because twoWords are as easy >to read as two_words. But it gets painful forLongerVariableNames. >I'm a big fan of descriptive names and since mixed case seems to discourage them >when N > 2 that is enough reason to dislike it. Smalltalk also is a big fan of descriptive names. >My assertion that mixed case fanboys are young and therefore loud while >at the same time being too inexperienced to know the difference is harsh and >I'm sure a 65 year old programmer will post as a counter example. They >are called stereotypes because they work /most/ of the time, if they worked >/all/ of the time they would just call them truths. *wink* Most of your arguments show your preference which is fine. But I disagree that they demonstrate for your preference. Smalltalker's experience disagrees, which too is fine. Both are opinions. :) Both sides can argue for nativeEnglish, descriptive_names, etc. Plenty of experience on both sides regarding the above. Thus, it reduces it primarily to personal preferences and opinions. Smalltalk itself is a testimony it isn't just young programmers who prefer mixedCase. I am not a 65 year old programmer but I do post a significant and historical counter example. (Nor am I a kid.) As I am a Smalltalk (Squeak) fan I tend to prefer mixedCase. But I would not (do_not) have any problem with wide_names. So far outside of preference, the biggest argument I've seen in this discussion regarding wide_names is OS handling of file_names or modules. Smalltalk has the distinct advantage of living in its own world (image). As such its development of Classes and Objects live inside its own image and not on the file system. Python on the other hand is file based and does have to deal more with OS limitations and file_names. Whether or not that is truly much of an issue, I can not say. Nevertheless, I'll defer to the language designers and implementors. Jimmie Houchin From kfast at poczta.onet.pl Tue Apr 13 13:56:37 2004 From: kfast at poczta.onet.pl (Jakub Fast) Date: Tue, 13 Apr 2004 19:56:37 +0200 Subject: Does Python compete with Java? Message-ID: <407C29D5.4050200@poczta.onet.pl> Thanks for a quick reply! > "LISP is over there ==>" > > Saying, in effect, that it isn't Pythonic. Ok, maybe i'm asking for it :), but -- why? [i am willing to cease-and-desist asking any further if this is not a welcome topic (like: we've discussed it fifty times by now, get a grip)] Kuba From cjw at sympatico.ca Thu Apr 29 13:38:45 2004 From: cjw at sympatico.ca (Colin J. Williams) Date: Thu, 29 Apr 2004 13:38:45 -0400 Subject: MATLAB2Python In-Reply-To: References: Message-ID: Sarge wrote: > Hi, everybody! > I'm a moderately experienced programmer in Matlab, and looking for a > free computational language (Matlab is *REALLY* expensive for an > individual, like me). > I came across Python (actually Scipy) and immediately felt > comfortable with the interface and syntax. > I'm still a newbe, so, before attempting a serious work on it, I'd > like to hear any opinion about migration from Matlab to Python, and > also a rough comparison between these two languages. > > Thanx in advance, and excuse me for my very bad English (I'm not a > native English speaker), > > Sarge Sarge, You might like to take a look at PyMatrix. It is still very much a development project, but I would appreciate your thoughts on the areas where it is deficient, as compared with MatLab. http://www3.sympatico.ca/cjw/PyMatrix Colin W. From tdelaney at avaya.com Thu Apr 29 19:24:06 2004 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Fri, 30 Apr 2004 09:24:06 +1000 Subject: outline-style sorting algorithm Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE016BCCC1@au3010avexu1.global.avaya.com> Thorsten Kampe wrote: >> def sorted (seq, cmp=None, key=None): > > What is 'cmp=None' for? To have the same semantics as 2.4 `sorted`. In 2.4 `list.sort` and `sorted` can take either or both of `cmp` and `key`. If `key` is passed, the keys are generated. If `cmp` is passed then that comparison function is used to sort the *keys* (and only the keys). Of course, if `key` is not passed then the keys used are the objects themselves. >> if key is None: >> return seq >> else: >> return [i[-1] for i in seq] > > What is 'key=None' for? Is that for speeding up if someone wants to > pass the indentity function (f(x)=x; lambda x: x)? Nope - if no `key` function is passed, the objects themselves are used in the sort. >> Note that Python 2.4 will have DSU as a built-in idiom to `list.sort` >> i.e. `list.sort(key=func)` but will be somewhat more efficient than >> the above. Likewise there will be a new builtin `sorted` which has >> exactly the same semantics as the above - it is stable, and it does >> not ever compare the actual value if a key function is supplied - >> only the key value (the above also compares the position, but that's >> an implementation detail and has no visible effect). > > If it has no visible effects than it would be useless. In my opinion > it has the effect that two items that have the same func(x) stay in > the same position as before. Is that desirable? Was that your goal? Sorry - I didn't explain this well enough. In my implementation, I'm using the indices as a termination condition. Since all the indices are different integers, I'm guaranteed that the objects themselves will never be compared. I don't actually need them there to ensure that the sort is stable since the 2.3 sort method is itself stable. In the 2.4 sort, the indices themselves are never used or needed - since the sort is in C it's much easier to ensure that just the keys are sorted without falling back to the object, but still easily maintain where the object will end up. In Python code it's much simpler to just stick them into the same tuple, but then you do need to ensure that the object won't be used in the comparison. Tim Delaney From python at quixs.com Tue Apr 27 11:31:20 2004 From: python at quixs.com (Lars Heuer) Date: Tue, 27 Apr 2004 17:31:20 +0200 Subject: sending an object - twisted or what? In-Reply-To: References: Message-ID: <86099257.20040427173120@quixs.com> Hi Paul, > I wish to send an object (only one class, but many objects) > from python running on one computer to python on another. > It will be over the internet, so needs to be 'secure'. > Is twisted the only way to go, or is there something > simpler for my app? The code for twisted is fairly simple (I found I don't know if it's simpler, but there's PyRO: http://pyro.sourceforge.net/ Best regards, Lars From jcarlson at uci.edu Thu Apr 1 15:57:35 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Thu, 01 Apr 2004 12:57:35 -0800 Subject: Why '==' ?? In-Reply-To: <8089854e.0403312318.77d465f@posting.google.com> References: <8089854e.0403302319.1ab56af0@posting.google.com> <8089854e.0403312318.77d465f@posting.google.com> Message-ID: > Not at all...but there you go... you need to reread what I said :-) I've read what you said a few times. You say that using '=' instead of '==' in boolean tests is unambiguous. You also say that removing ':' is unambiguous. I attempted to show you an example where such modifications /are/ ambiguous. > Not at all. > No need for a special case. Leave '==' with the same meaning as it > currently has... but give '=' a dual meaning (as it has in reality) > with the meaning obvious from context. In 'multi statements' (or > whatever the correct phrase is to pre-empt any more otiose comments) > require '==' so the syntax is clear. > > Ie. If the meaning is obvious.... '=' can replace '=='... if it's > not.. it can't... The problem is that having multiple ways (syntactically) to do the exact same thing causes people to ask questions like "which one is better". There is an entire thread about this with regards to tabs vs. spaces in this newsgroup, and thousands of threads available as to where {} in C/C++ or Java should be located across the internet. By saying "use it this way when it is unambiguous" and "use it this way when it is ambiguous", you are attempting to complicate the syntax of Python. Why? To save a few keystrokes. "There should be one-- and preferably only one --obvious way to do it." - The Zen of Python, by Tim Peters > The reason some people stated it was necessary was to allow another > statement on the same line... which is what I said ';' was for. I'm pretty sure the choice of ';' to end statements was to mirror various languages that people trying Python would likely be familliar with. Considering these same languages have little to no use for the ':' character (except for C++), its use in Python would be unambiguous. Considering that in C, the following is a no-op, regardless of what a actually is... if (a); But in Python, different things /would/ actually happen based on the contents of a, so would introduce ambiguity for those people coming from a C/C++ background, needlessly. > Sorry if you enjoy flaming newbies....... but in this case you'r a bit > off beam Josian old bean............. It wasn't a flame, it was an unkind post saying that your proposed syntax options were crap. I'm fairly certain that Guido looked at quite a few options when trying to decide on proper syntaxes early on, so that he didn't make any major mistakes. I am also fairly certain that the reason that your proposed syntax isn't what is currently done, is due to its ambiguity from the point of view of a C/C++ programmer. - Josiah From theller at python.net Wed Apr 7 14:04:35 2004 From: theller at python.net (Thomas Heller) Date: Wed, 07 Apr 2004 20:04:35 +0200 Subject: painful debugging: techniques? References: Message-ID: David Bolen writes: > "Humpty Dumpty" writes: > >> I'm wondering if there are tricks people use to track down problems like >> this. > > Perhaps not so much a trick as much as experience, but after working > with Python a bit, you'll find that any time you see something like > 'NoneType not a callable' (or really any type) it pretty much says > that some object in your program should be a callable (function, > method, etc..) but is None (or the other type) instead. So in general > I'd immediately start looking for uses of None in my code (or ways in > which my code could generate None at runtime). It may be that the OP forgot an explicit 'return' statement in a function, so that the function returns None instead of a callable object. In this case, there is a chance that pychecked would have spit out a warning. Thomas From michele.simionato at poste.it Tue Apr 20 00:08:17 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 19 Apr 2004 21:08:17 -0700 Subject: Generic constructors and duplication of internal Python logic References: <87ekqq41ya.fsf@pobox.com> <95aa1afa.0404150033.79a53e1a@posting.google.com> <87k70bzlak.fsf@pobox.com> Message-ID: <95aa1afa.0404192008.3a9da567@posting.google.com> jjl at pobox.com (John J. Lee) wrote in message news:<87k70bzlak.fsf at pobox.com>... > michele.simionato at poste.it (Michele Simionato) writes: > > Have you thought of performing the checks in the __call__ method > > of a custom metaclass? > > No. How would that help? I had in mind something like that: class _WithConstructorChecked(type): # helper metaclass def __call__(cls, *args, **kw): assert len(args)<=2, "%s called with more than 2 args" % cls assert kw.has_key("kw"), "%s needs a 'kw=' argument" % cls return super(_WithConstructorChecked,cls).__call__(*args,**kw) class WithConstructorChecked(object): # mixin class __metaclass__ = _WithConstructorChecked class C(WithConstructorChecked): def __init__(self, *args, **kw): pass c=C(1,2,kw=3) # ok; try different signatures to get assertion errors In this example the mixin class WithConstructorChecked ensures that C is called with at least two positional arguments and a keyword argument named 'kw'. The code of class C is not touched at all, you just add WithConstructorChecked to the list of its bases. Is that what you are looking for? Michele Simionato From missive at frontiernet.net Sun Apr 4 22:57:52 2004 From: missive at frontiernet.net (Lee Harr) Date: Mon, 05 Apr 2004 02:57:52 GMT Subject: db paramstyle for arrays Message-ID: Is there a special DB API style for inserting array values in to a database? In postgres, the values needs to end up like ARRAY[1, 2, 3] so I am just putting the word ARRAY in to the query string like this: q = "INSERT INTO foo VALUES (ARRAY%(bar)s)" % {'bar': [1, 2, 3]} That works, but it seems to me there may be a better way. Thanks for your time. From cm at leetspeak.org Tue Apr 27 20:22:55 2004 From: cm at leetspeak.org (Michael Walter) Date: Wed, 28 Apr 2004 02:22:55 +0200 Subject: Ideas for Python 3 In-Reply-To: References: Message-ID: David MacQuigg wrote: > [...] > It took me a long time to realize that lamdas have only one advantage > over named functions - they can be crammed into a tight space. Here > is an example: > > L = [(lambda x: x**2), (lambda x:x**3), (lambda x:x**4), (lambda > x:x**5)] > > If the purpose is to save space, wouldn't this be better as: > > L = [:x:x**2, :x:x**3, :x:x**4 :x:x**5] L = map(lambda x: lambda y: x**y,range(2,6)) Almost. Or write mapc ("map currying") and have: L = mapc(pow,range(2,6)) Shorter than your example, less mistake-prone, no obvious lambda at all ;) Cheers, Michael From stephendotboulet at motorola_._com Fri Apr 16 14:46:19 2004 From: stephendotboulet at motorola_._com (Stephen Boulet) Date: Fri, 16 Apr 2004 13:46:19 -0500 Subject: Error copying a file In-Reply-To: References: Message-ID: Krzysztof Stachlewski wrote: > Stephen Boulet wrote: > >> I know that the name of this file is somewhat pathological, but this >> if weird: >> >> >>> print myfile >> E:\Fritz Reiner\Rimsky-Korsakov--Scheherazade.Debussy--La Mer\01 >> Symphonic Suite after "A Thousand and One Nights" - The Sea and >> Sinbad's Ship.ogg > > > It seems you are on Windows box. > What filesystem do you use? > I have just tried to create such a file, but the filesystem (NTFS) > refuses to use " as part of the name. I'm on win2000. The file is on a CD I burned, and I wanted to copy it to a file name that doesn't have any quotation marks in it. The problem is that I can't reference the file to begin with. The command: shutil.copy2(myfile,r'D:\foo.ogg') can't use the string held in myfile, although os.listdir('directory on CD') contains it as the first entry. It would be nice if I could referene the file in a way that would not cause the copy command to fail. Stephen From peter at engcorp.com Wed Apr 14 12:10:17 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 14 Apr 2004 12:10:17 -0400 Subject: Difficulty Finding Python Developers In-Reply-To: <65cbc3dd.0404140641.3501fde8@posting.google.com> References: <65cbc3dd.0404140641.3501fde8@posting.google.com> Message-ID: <407D6269.3090909@engcorp.com> Paul Morrow wrote: > We've worked hard to convince our company to migrate our core > applications to Python, and now we're looking for a Python developer > in Atlanta to handle a short-term (approx. 3 month) project. But our > initial searches have been fairly unsuccessful. We haven't actually > posted a job on Monster, but we have been talking with various > headhunters in our area and they don't have many resumes that show > Python experience. An so now, of course, mgt is wondering whether > selecting Python was a mistake. > > As anyone had a similar experience? Suggestions? Don't hire "Python programmers". I successfully staffed a team with over twenty five developers over the last five years, without once hiring anyone who was a "Python programmer". I did make an attempt to hire people who were good at programming, who had diverse backgrounds, strong communication skills, brains between their ears, and so on. Only one of the people hired, as I recall, had actually used Python (and then only briefly) prior to working for me. In only a couple of cases (where they turned out not to fit the above description too well) did anyone take more than about a week to become productive in Python, maybe two or three weeks max. I would actually suggest, however, that instead of hiring someone new for the position, take one of your talented existing programmers and have him or her learn Python while starting on this project. If the project goes well, you can more easily make the case for doing other projects with Python, and you might in the meantime have found some actual "Python programmers". I still wouldn't hire them, however, if they didn't fit the afore-mentioned criteria... -Peter From wl at flexis.de Thu Apr 8 08:20:29 2004 From: wl at flexis.de (Wolfgang Langner) Date: Thu, 08 Apr 2004 14:20:29 +0200 Subject: performance issue In-Reply-To: References: Message-ID: Hello, > Is there any obvious performance gain between 2.3 and 2.1 release? Is > this information available on the web site? Yes. From ba-admin at thekompany.com Fri Apr 23 23:19:01 2004 From: ba-admin at thekompany.com (ba-admin at thekompany.com) Date: Fri, 23 Apr 2004 20:19:01 -0700 (PDT) Subject: Your message to Ba awaits moderator approval Message-ID: <20040424031901.7F70D3FA8F@valentine.thekompany.com> Your mail to 'Ba' with the subject Re: Incoming Fax Is being held until the list moderator can review it for approval. The reason it is being held: Post by non-member to a members-only list Either the message will get posted to the list, or you will receive notification of the moderator's decision. From deetsNOSPAM at web.de Tue Apr 20 11:44:46 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Tue, 20 Apr 2004 17:44:46 +0200 Subject: Rekall configure probs References: Message-ID: Tony of Judicious wrote: > Not sure if this is right ng but i'm trying to install Rekall on Suse 9 > prof > > During ./configure i get the msg: > > checking for X... configure: error: Can't find X includes. Please check > your installation and add the correct paths! > > Any idea what it is looking for? the x window include files? Whatever it needs them for - nstall the X devel packages. -- Regards, Diez B. Roggisch From nemesis at nowhere.invalid Wed Apr 14 16:28:59 2004 From: nemesis at nowhere.invalid (Nemesis) Date: Wed, 14 Apr 2004 20:28:59 GMT Subject: Pygame References: Message-ID: Mentre io pensavo ad una intro simpatica "Jakub Fast" scriveva: > pygame (and sdl) are lgpl licensed and as such they are not > commercial-friendly. the lgpl license _is_ commercial-friendly. -- Being normal is driving me crazy. |\ | |HomePage : http://nem01.altervista.org | \|emesis |XPN (my nr): http://xpn.altervista.org From travis at enthought.com Wed Apr 21 17:40:24 2004 From: travis at enthought.com (Travis N. Vaught) Date: Wed, 21 Apr 2004 16:40:24 -0500 Subject: ANN: SciPy 0.3 Released Message-ID: <4086EA48.4080105@enthought.com> Greetings, SciPy 0.3 has been released and binaries are available from the scipy.org site. http://www.scipy.org Changes since the 0.1 version (0.1 enjoyed a wide release, there was a version 0.2 that had limited exposure) include the following: - general improvements: Added utility functions for constructing arrays by concatenation, intended mainly for command-line use. Added bmat constructor for easy creation of block matrices. Added mat constructor for constructing matrices (where * is matrix multiplication). Added many PIL utility functions so that if the PIL is installed, image loading, saving, and other operations are available. Added scipy.info, which handles dynamic docstrings and class help better than python's help command. - documentation: much improved - sparse: superLU upgraded to 3.0 - optimize: Added non-linear conjugate gradient algorithm. Improvements to BFGS algorithm and Wolfe-condition line-search. Added two CONSTRAINED optimization techniques. Added simulated annealing and brute-force optimization strategies and Powell's method. Added many very good 1-D root-finding routines. - stats: Added many statistical distributions. Many continuous and discrete random variables are available with a simple mechanism for adding new ones. Added several statistical tests. - special: Added MANY new special functions. |general_function| renamed to |vectorize| and moved to scipy_base. Improved the way domain errors are handled (user specified display of problems). More tests on special functions added. - fftpack: replaced with fftpack2--can optionally be configured to support djbfft - io: Reading of MATLAB .mat files (version 4 and 5) supported. Writing version 4 .mat files supported. Added very flexible and general_purpose text file reader. Added shelving save operation to save variables into an importable module. Routines for reading and writing fortran-records. - linalg: Linear algebra is greatly improved over SciPy 0.1. ATLAS is now optional (but encouraged). Most lapack functions have simplified interfaces (all lapack and blas available). Matrix exponentials and other matrix functions added. - signal: Added support for filter design and LTI system analysis. - xplt: Updated xplt to use newer pygist so that Windows platform is supported. Addition of several plotting types. - integrate: added another ODE integrator. Added romberg integration and several other integration approaches. The complete release notes can be found here: http://www.scipy.org/download/scipy_release_notes_0.3.html You'll also notice that scipy.org is now a spanking new Plone portal (http://www.plone.org -- keep up the good work, plone folks). This is the first binary release in a long time and we hope to increase the frequency to every 6 months or so. If you'd like to follow or join the community, you can subscribe to the mailing lists here: http://www.scipy.org/mailinglists/ Best Regards, Travis BTW SciPy is: ------------- SciPy is an open source library of scientific tools for Python. SciPy supplements the popular Numeric module, gathering a variety of high level science and engineering modules together as a single package. SciPy includes modules for graphics and plotting, optimization, integration, special functions, signal and image processing, genetic algorithms, ODE solvers, and others. From donn at u.washington.edu Fri Apr 30 15:24:12 2004 From: donn at u.washington.edu (Donn Cave) Date: Fri, 30 Apr 2004 12:24:12 -0700 Subject: Is classless worth consideration References: <69cbbef2.0404290259.fd8d71c@posting.google.com> <69cbbef2.0404291209.7a98a799@posting.google.com> <8ef9bea6.0404292307.66b78b83@posting.google.com> <84Kdnfu3OoN4oA_dRVn-vg@powergate.ca> <8ef9bea6.0404301017.575c91d7@posting.google.com> Message-ID: In a similar vein, I have noticed that clothing often comes with pockets, yet this essentially duplicates the functionality of shoes, which are also items of clothing that one puts things in. We can certainly reduce the Baroque complexity of our lifestyle if we can eliminate this gratuitous superfluity and rather than pockets, simply append shoes to our clothes where needed to store a few essentials. Why, you could store soup, all kinds of stuff in a shoe that you'd hesitate to put in a pocket. Think outside the box! Donn Cave, donn at u.washington.edu From corey.coughlin at attbi.com Sun Apr 4 21:18:31 2004 From: corey.coughlin at attbi.com (Corey Coughlin) Date: 4 Apr 2004 18:18:31 -0700 Subject: GUI Frameworks in Python? References: Message-ID: One I've always meant to look into more is PyUI, a gui framework built on the pygame library. Always looked kind of cool. Anyone have any experience with it? "Hugh Macdonald" wrote in message news:... > I've recently been trying out various different GUI frameworks in Python and > was wondering if I could get your input on the pros and cons of the > different ones... > > wxPython: I love the programming side of wxPython, but I find it's just so > slow to initialise in the first place. > > Tkinter: While it's fast to load up, the syntax has never really appealed to > me > > GTK: Unknown - I'm looking into it today > > Qt: I have yet to manage to install it on my system > > Anything else? > > > Hugh Macdonald From matthew at barnes.net Wed Apr 14 01:59:16 2004 From: matthew at barnes.net (Matthew Barnes) Date: 13 Apr 2004 22:59:16 -0700 Subject: Adding properties to objects References: <3a8e83d2.0404130906.2ea796e9@posting.google.com> <3a8e83d2.0404131327.33dfe92a@posting.google.com> Message-ID: <3a8e83d2.0404132159.12e23a55@posting.google.com> Shalabh Chaturvedi wrote... > You can add properties dynamically, but to the type (i.e. 'class') and > not the instance (i.e. 'object'). For your example: > > >>> x = Foo() > >>> def f(a,b=None): # a bogus getter, setter, deleter > ... print a,b > ... > >>> Foo.property = property(f,f,f) > >>> x.property > <__main__.Foo object at 0x008F3CB0> None > >>> x.property = 1 > <__main__.Foo object at 0x008F3CB0> 1 > >>> del x.property > <__main__.Foo object at 0x008F3CB0> None > >>> > > This property will work for *all* instances of Foo. Right. I may not have been clear, but I was trying to add different properties to different *instances* of Foo. > What is the problem you are trying to solve? Here's basically what I was trying to do: class Foo(object): def __init__(self, sourcedict): # sourcedict is a dictionary of objects having get() and set() # methods. Nevermind where sourcedict comes from. The point # is that different instances get different sourcedict's. for name, object in sourcedict.items(): # This doesn't do what I had hoped for. # My thinking was flawed on several levels. self.__dict__['name'] = property(object.get, object.set) So suppose "sourcedict" has some object named "bar". The idea was to create properties on-the-fly based on the contents of "sourcedict", such that: >>> x = Foo(sourcedict) # Given this... >>> x.bar # would invoke sourcedict['bar'].get() >>> x.bar = 1 # would invoke sourcedict['bar'].set(1) I've since realized that properties are not the right approach for something like this, and that I would be better off with a more straight-forward approach using custom Foo.__getattr__ and Foo.__setattr__ methods (seems obvious now that I've simplified the problem description :-). Matthew Barnes From herrn at gmx.net Sun Apr 4 12:38:54 2004 From: herrn at gmx.net (Marco Herrn) Date: 4 Apr 2004 16:38:54 GMT Subject: __import__() with packages References: <1070cph9hedq9ee@news.supernews.com> Message-ID: Sorry, accidently sent out the unfinished message. On 2004-04-04, John Roth wrote: > m = __import__("spam.eggs") > eggs = spam.eggs > > This will probably also work: > > eggs = __import__("spam.eggs").eggs Thanks, but in my application I read the names of the modules from a file, so I do not know them when writing (in this case I wouldn't know the name 'eggs'). Since the solution from Paul works for me, I will use that. Marco -- Marco Herrn herrn at gmx.net (GnuPG/PGP-signed and crypted mail preferred) Key ID: 0x94620736 From me at privacy.net Mon Apr 26 08:40:23 2004 From: me at privacy.net (Duncan Booth) Date: 26 Apr 2004 12:40:23 GMT Subject: Using descriptors to wrap methods References: <408cfa5a$0$28920$61fed72c@news.rcn.com> Message-ID: "Edward C. Jones" wrote in news:408cfa5a$0$28920$61fed72c at news.rcn.com: > Here is a stripped-down version of a Python Cookbook recipe. Is there a > simpler, more Pythonical, natural way of doing this? Here's a simpler way of doing the same thing: >>> def MethodWrapper(f): def wrapper(self, *args, **kw): print 'pre' result = f(self, *args, **kw) print 'post' return result return wrapper >>> class C(object): def f(self, arg): print 'in f' return arg+1 f = MethodWrapper(f) >>> c = C() >>> print c.f(1) pre in f post 2 >>> Or if you want pre and post code customisable you might try: >>> def MethodWrapper(f, pre=None, post=None): def wrapper(self, *args, **kw): if pre: pre(self, *args, **kw) result = f(self, *args, **kw) if post: post(self, result, *args, **kw) return result return wrapper >>> class C(object): def pre_f(self, arg): print 'pre',arg def post_f(self, res, arg): print 'post',res,arg def f(self, arg): print 'in f' return arg+1 f = MethodWrapper(f, pre_f, post_f) >>> c = C() >>> c.f(1) pre 1 in f post 2 1 2 >>> I don't know if you could call it Pythonic though. From __peter__ at web.de Wed Apr 21 18:34:06 2004 From: __peter__ at web.de (Peter Otten) Date: Thu, 22 Apr 2004 00:34:06 +0200 Subject: Optimizing a text statistics function References: <4086efbc$1@nntp0.pdx.net> Message-ID: Scott David Daniels wrote: > Peter Otten wrote: >> Nickolay Kolev wrote: > Playing along, simply because it's fun. > >> def main(filename): >> ... > > #> words = file(filename).read().translate(tr).split() > #> histogram = {} > #> wordCount = len(words) > #> for word in words: > #> histogram[word] = histogram.get(word, 0) + 1 > > Better not to do several huge string allocs above (I suspect). > This method lets you to work on files too large to read into memory: > > wordCount = 0 > histogram = {} > > for line in file(filename): > words = line.translate(tr).split() > wordCount += len(words) > for word in words: > histogram[word] = histogram.get(word, 0) + 1 > >> ... In theory you are right, in practice most text files are tiny compared to the amount of RAM available on a fairly recent machine. However, I readily admit that your variant plays nicely with *very* large files as long as they have newlines, and, contrary to my expectation, is even a bit faster with my adhoc testcase, a 670,000 byte 8,700 line HTML file. Peter From ecastro at dbbf.ulpgc.es Thu Apr 22 06:58:20 2004 From: ecastro at dbbf.ulpgc.es (Enrique Castro) Date: Thu, 22 Apr 2004 11:58:20 +0100 Subject: ANN: SciPy 0.3 Released In-Reply-To: References: Message-ID: Travis N. Vaught wrote: > SciPy 0.3 has been released and binaries are available from the > scipy.org site. > > http://www.scipy.org > Hi, What's the status of Chaco, the plotting package? Is it now included in SciPy download? I have tried to follow the chaco link in Enthought's site (http://www.enthought.com/) but it seems not working Tanks Enrique Castro From corey.coughlin at attbi.com Mon Apr 12 13:55:55 2004 From: corey.coughlin at attbi.com (Corey Coughlin) Date: 12 Apr 2004 10:55:55 -0700 Subject: A new OS References: <107k441hitt2ld9@corp.supernews.com> Message-ID: I think it sounds like a great idea. I'd ultimately like to go a direction like that at some point. One of the biggest problems with existing operating systems (like Windows or Linux) is that they are for the most part built on C, which then dictates what the low level calls look like, the memory architecture, and so on. Writing an OS in Python could give you a new perspective on mapping a high level architecture onto a machine. Imagine, for instance, an OS architecture with a genuine object hierarchy, where low level details get abstracted into a machine level that can be swapped out to conform to different processor architectures, where garbage collection is an OS service, and maybe the filesystem is actually an object persistance system, so every file is actually an object with type instead of a bag of bytes, and then imagine how easy it would be to add advanced indexing a la Chandler to it. Could we then distribute programs as only python bytecode, getting platform independence? Would it be easier adding security using higher levels of abstraction? How about creating a complete network OS? Would that be easier in python? In general, as you abstract complex os services into simpler python code, would it be easier to expand the capabilities of your os? I can't imagine that it would be harder. It could be quite an interesting project, if conducted with the aim of not just making yet another generic operating system, but with the aim of creating a truly pythonic OS. That would be great. "A Evans" wrote in message news:<107k441hitt2ld9 at corp.supernews.com>... > Hello Everyone I am working towards starting a project developing a new > Operating System using the Python language (or a derivative thereof). As > recommended on this forum I am asking if people are interested in something > like this and ask who would be willing to support a project this large. > > Any and all ideas are welcome this message is just to see what kind of > support this project would recieve > > Cheers > > Andrew From michele.simionato at poste.it Thu Apr 29 08:34:11 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 29 Apr 2004 05:34:11 -0700 Subject: Is classless worth consideration References: <1090r77d97k0tb1@news.supernews.com> Message-ID: <95aa1afa.0404290434.544a37d6@posting.google.com> Michael wrote in message news:... > Is there any way to to call a class method without making an instance of > that class? Yes, with classmethods and staticmethods and more in general with custom descriptors. > To me that would be useful because you could mimic modules > without having to create a sepperate file. Or is there already a way to > do that? You can dynamically generate a module: >>> from types import ModuleType # in Python 2.3 >>> mymodule=ModuleType("mymodule","This a dynamic module") >>> help(mymodule) Help on module mymodule: NAME mymodule - This a dynamic module FILE (built-in) You can populate the module with setattr or by hand: >>> mymodule.a=1 >>> mymodule.a 1 HTH, Michele Simionato From richie at entrian.com Thu Apr 1 07:02:10 2004 From: richie at entrian.com (Richie Hindle) Date: Thu, 01 Apr 2004 13:02:10 +0100 Subject: GUI Frameworks in Python? In-Reply-To: <6ee58e07.0403311125.52f0acf0@posting.google.com> References: <6ee58e07.0403311125.52f0acf0@posting.google.com> Message-ID: <2v0o60ts31jnciptpm9biujtvrkqfjvep3@4ax.com> [Lothar] > You and all others miss one important number: What a harddisk are you > using ? Good point. And, "how fragmented is it?" And (to a lesser extent) "how invasive is your virus scanner?" "Very" to both in my case, I think. Thanks for pointing out that there's more to performance than GHz. -- Richie Hindle richie at entrian.com From bh at intevation.de Mon Apr 5 11:19:03 2004 From: bh at intevation.de (Bernhard Herzog) Date: Mon, 05 Apr 2004 17:19:03 +0200 Subject: Working with bytes. References: <406EE606.4000604@yahoo.com> <406f33b6$0$30963$3a628fcd@reader1.nntp.hccnet.nl> <4071273d$0$132$3a628fcd@reader1.nntp.hccnet.nl> Message-ID: Piet van Oostrum writes: > Yes, you could in principle use 94 characters. There is a scheme called > btoa that encodes 4 bytes into 5 ASCII characters by using BASE85, but I > have never seen a Python implementation of it. It shouldn't be difficult, > however. Is that the same as PDF/PostScript Ascii85? If so, there's an implementation somewhere in reportlab, IIRC. Bernhard -- Intevation GmbH http://intevation.de/ Skencil http://sketch.sourceforge.net/ Thuban http://thuban.intevation.org/ From martin at v.loewis.de Tue Apr 27 16:29:59 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 27 Apr 2004 22:29:59 +0200 Subject: locale.CODESET / different in python shell and scripts In-Reply-To: References: Message-ID: Nuff Said wrote: > When I type the following code in the interactive python shell, > I get 'UTF-8'; but if I put the code into a Python script and > run the script - in the same terminal on my Linux box in which > I opened the python shell before -, I get 'ANSI_X3.4-1968'. > > How does that come? Because, for some reason, locale.setlocale() is called in your interactive startup, but not in the normal startup. It is uncertain why this happens - setlocale is not normally called automatically; not even in interactive mode. Perhaps you have created your own startup file? Regards, Martin From __peter__ at web.de Sat Apr 3 16:22:47 2004 From: __peter__ at web.de (Peter Otten) Date: Sat, 03 Apr 2004 23:22:47 +0200 Subject: gettext and the interpreter References: Message-ID: Hans-Joachim Widmaier wrote: > Recently I wanted to do some debugging using one module of my first > Python program using the gettext module. I just didn't find a way to > disable the interpreter binding the last result to _, which ought to > be (and stay) a function. > > Anybody got an idea how to do it? Try redefining sys.displayhook, e. g.: >>> import sys, __builtin__ >>> def myhook(value): ... if value is not None: ... __builtin__.__last__ = value ... sys.stdout.write("%r\n" % value) ... >>> sys.displayhook = myhook Now the last non-None value will be stored in __last__ instead of _: >>> 1 1 >>> _ Traceback (most recent call last): File "", line 1, in ? NameError: name '_' is not defined >>> __last__ 1 Peter From peter at engcorp.com Sat Apr 24 13:36:35 2004 From: peter at engcorp.com (Peter Hansen) Date: Sat, 24 Apr 2004 13:36:35 -0400 Subject: AOP use cases In-Reply-To: References: <84fc4588.0404140106.3fa0c55@posting.google.com> <0pydnSB4WYuieuLdRVn-hQ@powergate.ca> Message-ID: Tor Iver Wilhelmsen wrote: > Peter Hansen writes: > >>I would be very interested to hear some real-world and real useful >>use cases for AOP as well. So far, the logging example seems to >>be put forth so often that I'm starting to suspect that's the >>*only* "useful" thing people are doing with it. :-) > > A couple of other examples: > > - Implementing Singleton as an aspect which states that calling > set*(self, value) methods on a set of classes should raise an > AttributeError - or just do nothing > - Measure execution time of a method by wrapping an aspect-"advice" > around it Hmm.... maybe I need to clarify what I mean by "real-world". To mean, the term means something like "drawn from actual, working code in real projects implemented to achieve useful, practical results", as opposed to what, so far, pretty much everyone who proposes examples seems to think, which is more like "potentially interesting theoretical ideas which sound kinda cool"... Has anyone used AOP in a real project, which wasn't a project just to demonstrate AOP? For anything other than the logging example? If so, what was the specific value provided by AOP, and can you post a snippet or two of code which demonstrates the cleaner structure provided by the clear separation of concerns which you believe comes from AOP practices? And thank you. :-) (And I'll reject at this point examples which are no different than how any number of us use Python to wrap existing methods in useful ways, such as the synchronization scheme presented earlier in this thread. Why? Because if that's the best you can do, then I don't think AOP deserves to be recognized in the Python world as anything other than a fancy buzzword for something which we should all be doing already as we ensure our code is decoupled and has little duplication. That probably means your example will come from the Java world, or elsewhere, but I wouldn't reject it out of hand just because it's in Python.) -Peter From mhammond at keypoint.com.au Fri Apr 30 08:20:00 2004 From: mhammond at keypoint.com.au (Mark Hammond) Date: Fri, 30 Apr 2004 22:20:00 +1000 Subject: COM Interface Question In-Reply-To: <40923157$1_3@newspeer2.tds.net> References: <9e5ea2c4.0404291130.72e81c2e@posting.google.com> <40923157$1_3@newspeer2.tds.net> Message-ID: Olaf Meding wrote: > Mark > > The IDL shows a uuid for the IUser interface (bf79...). How would I use > IDispatch() to create an IUser as required by the put user call? > > Here are excerpts from the IDL file: There is nothing in that IDL that implies it can be created by an IDispatch call - it is just describing the interface. Generally a CoClass entry in the IDL indicates it can be publically created, but you haven't shown that - but in that case, the makepy code will include a comment telling you the progid, so I doubt it exists. Surely there is documentation or a sample (in any language) for this object? Mark. From jacek.generowicz at cern.ch Thu Apr 22 12:24:10 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 22 Apr 2004 18:24:10 +0200 Subject: AOP use cases References: <84fc4588.0404140106.3fa0c55@posting.google.com> <0pydnSB4WYuieuLdRVn-hQ@powergate.ca> Message-ID: hwlgw at hotmail.com (Will Stuyvesant) writes: > What they DO show is code in Java that solves Java problems, usually > to do with the limitations imposed by the static typing system. You might enjoy the first bullet in the conclusions of the following: http://www.cs.uni-bonn.de/~costanza/dynfun.pdf (Those of you not allergic to parentheses might find it interesting reading thoughout.) > I have come to the conclusion that AOP is nothing more than what I > expect from a decent programmer: a good, or at least reasonable, > design of software in the first place. I think there is _potentially_ more to it than that. I think that languages can provide direct assistance with this goal. The quality, weight, usefullnes and hype of this support varies greatly with the language in question, of course. From newsgroups at jhrothjr.com Sun Apr 4 12:07:31 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Sun, 4 Apr 2004 12:07:31 -0400 Subject: __import__() with packages References: Message-ID: <1070cph9hedq9ee@news.supernews.com> "Marco Herrn" wrote in message news:c4p3f2$2j1tnb$1 at ID-165840.news.uni-berlin.de... > Hi, > > I am using the builtin __import__() to import modules. That works for > simple modules like in this example: > > m= __import__("eggs") > > when there is the module "eggs.py" in the current directory > > But how do I do this with packages? A I understand the documentation for > __import__(), it must be something like: > > m= __import__("eggs", globals(), locals(), ["spam"]) > > when there is the package "spam" in the current directory, containing > the module "eggs". > But that doesn't work. I tried it in some different forms. The only one > that works in some way is: > > m= __import__("spam.eggs") > > But that is not what I want, since I get "spam" as a module: > > > So what am I doing wrong here? You're doing everything correctly, just not quite enough. What you've got is an almost empty module named "spam", which contains another module bound to the identifier "eggs". So what you need to do is: m = __import__("spam.eggs") eggs = spam.eggs This will probably also work: eggs = __import__("spam.eggs").eggs HTH John Roth > > Marco > > -- > Marco Herrn herrn at gmx.net > (GnuPG/PGP-signed and crypted mail preferred) > Key ID: 0x94620736 > From sholden at holdenweb.com Fri Apr 30 13:50:24 2004 From: sholden at holdenweb.com (Steve Holden) Date: Fri, 30 Apr 2004 13:50:24 -0400 Subject: How to read a file from another server? Newbie In-Reply-To: References: <%Oejc.16$ph.9@fed1read07> <9ugjc.3709$g31.1370@newsread2.news.atl.earthlink.net> Message-ID: <409291E0.1070906@holdenweb.com> Sean Berry wrote: > I have resolved the issue. I am just going to run the cgi script from the > server the file is on. If anyone out there is interested I am getting close > to finishing a script that does recursive digs for MX, A, and NS records for > a given domain, or list of domains. > > Sean > Without in any way wishing to rain on your parade, dnspython (http://www.dnspython.org/) is great for all DNS functionality. regards Steve From plastic"no-spam-pls" at xsintrk.net Thu Apr 15 16:55:11 2004 From: plastic"no-spam-pls" at xsintrk.net (jeff) Date: Thu, 15 Apr 2004 20:55:11 GMT Subject: newbie question Message-ID: ex: a = "text str" if a == "text str": print a why doesn't that work? i couldn't find much help about variable types in the manual, does it need a property like a.text? From jonas at jonasgalvez.com Wed Apr 21 00:12:12 2004 From: jonas at jonasgalvez.com (Jonas Galvez) Date: Wed, 21 Apr 2004 01:12:12 -0300 Subject: Regex'ing null bytes References: Message-ID: Nevermind, I decided to not use regexes at all. Jonas "Jonas Galvez" escreveu na mensagem news:c64nve$kut$1 at sea.gmane.org... > Hi, > > I'm trying to parse some binary data with regexes. It works well in > the latest Python build, but I need to run this on Python 1.5.2. The > binary data has a pattern like this: > > keyName1\002..(.*)\000.*keyName2\002..(.*)\000 > (I'm using regex syntax to illustrate) > > So I wrote the following script: > > def amfKey(str): > return "%s\002..([^\000]*)" % str > > keys = re.compile(amfKey("key"), re.DOTALL).findall(amfStr) > > Works on 2.3.3, but produces the following error on 1.5.2: > > Traceback (innermost last): > File "test.py", line 26, in ? > keys = re.compile(amfKey("key"), re.DOTALL).findall(amfStr) > File "C:\Python152\Lib\re.py", line 79, in compile > code=pcre_compile(pattern, flags, groupindex) > TypeError: argument 1: expected string without null bytes, string found > > Does anyone know a workaround? The type of binary data I'm trying to > parse is AMF (Action Message Format), Macromedia's proprietary format > for fast communication between the Flash Player and their "Flash > Remoting" servers (ColdFusion/.NET/Java implementations). But there > are opensource "Flash Remoting" implementations in PHP (amfphp.org), > Perl (simonf.com/flap/) and Java (openamf.org) already - I've > started to work on the Python port. > > And I wanted to keep this Python 1.5.2-compatible... > > > > Thanks in advance, > > > =- > Jonas Galvez > jonasgalvez.com/blog > macromedia.com/go/team From __peter__ at web.de Fri Apr 9 04:06:25 2004 From: __peter__ at web.de (Peter Otten) Date: Fri, 09 Apr 2004 10:06:25 +0200 Subject: Function args References: Message-ID: Jean-Michel Caricand wrote: > Imaginons que je veuille ?crire une fonction qui permute deux variables, > j'?cris : > > def permuter(a,b): > c = b > b = a > a = c > > Si tout est objet, donc pass? par r?f?rence a et b devraient ?tre > r?ellement modifier ? Pourtant ce n'est pas le cas. Assignments inside a function only affect local bindings, i. e what a and b "point" to in the local context. Rebinding in the calling context must be made explicit: >>> a = 1 >>> b = 2 >>> a, b = swap(a, b) >>> a 2 >>> b 1 Of course you wouldn't write a function for that particular example: >>> a = 1 >>> b = 2 >>> a, b = b, a >>> a 2 >>> b 1 >>> Does the above mean you can never change an object from inside a function? No, only bindings cannot be changed and because integers are "immutable", i. e. cannot be changed once they are created, what is viewed as changing them is in fact rebinding. Now a simple example with a mutable class: >>> class A: ... def __init__(self, name, value): ... self.name = name ... self.value = value ... def __repr__(self): ... return "A(name=%r, value=%r)" % (self.name, self.value) ... >>> def swapAttr(a, b): ... a.value, b.value = b.value, a.value ... >>> a = A("A", 1) >>> b = A("B", 2) >>> a, b (A(name='A', value=1), A(name='B', value=2)) >>> swapAttr(a, b) >>> a, b (A(name='A', value=2), A(name='B', value=1)) While objects stay the same, you can do anything with the attributes. As Michel Claveau already pointed out, the same is true for list and dict items. Peter From peter.maas at mplusr.de Wed Apr 7 12:08:01 2004 From: peter.maas at mplusr.de (Peter Maas) Date: Wed, 07 Apr 2004 18:08:01 +0200 Subject: Are line continuations needed? In-Reply-To: <407409ef.82801353@news.eircom.net> References: <407409ef.82801353@news.eircom.net> Message-ID: Russell Wallace wrote: > Python lets you continue a single logical line across more than one > physical line, either by putting a \ at the end or letting it happen > automatically with an incomplete infix operator. > > I'm wondering how often is this feature needed? Would there be any > problems if it weren't part of the language? Just had this example: d = { 'key1' : 'A very very long string of several hundred '\ 'characters. I could use a multi-line string but '\ 'then either left white space would be part of the '\ 'string or I would have to align it at column 0 '\ '(ugly). I could embed it into a pair of brackets '\ 'but I see no advantage over \\. Finally I could '\ 'put this string on a single line (also ugly and hard '\ 'to read).' ... } Mit freundlichen Gruessen, Peter Maas -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Hubert-Wienen-Str. 24 Tel +49-241-93878-0 Fax +49-241-93878-20 eMail peter.maas at mplusr.de ------------------------------------------------------------------- From robin at reportlab.com Wed Apr 28 13:58:09 2004 From: robin at reportlab.com (Robin Becker) Date: Wed, 28 Apr 2004 18:58:09 +0100 Subject: sys.modules strangeness Message-ID: <408FF0B1.5090505@chamonix.reportlab.co.uk> We had some legacy applications that used import to get parts of documents in. When run separately these worked fine, but failed when run as a single process because they both imported ch1 (after jumping to their home dirs and placing these on the path). Clearly the first to run used up ch1. I have a simple test script below. It seems I cannot just restore the original sys.modules and leave the modules to die, but actually need to del the relevant entries. Are modules somehow cached somewhere? What's the right way to unload a module (assuming I can remove non sys refs). #timport.py start####################### import sys, os def d_b(d): os.chdir(d) cwd = os.getcwd() sys.path.insert(0,os.getcwd()) import b print 'Expecting %s:'%os.path.join(d,'b.py'), b.run() sys.path.remove(cwd) os.chdir('..') for d in 'a','c': fn = os.path.join(d,'b.py') f = open(fn,'r') print 'The file %s is\n#######\n%s#######\n' % (fn,f.read()) f.close() #this works for d in 'a','c': OK = sys.modules.keys()[:] d_b(d) for k in sys.modules.keys(): if k not in OK: del sys.modules[k] #this doesn't for d in 'a','c': OM = sys.modules.copy() d_b(d) sys.modules = OM #a/b.py############################## def run(): print 'my file is', __file__, 'I am a\\b.py' #c/b.py############################## def run(): print 'my file is', __file__, 'I am c\\b.py' #outputput########################### The file a\b.py is ####### def run(): print 'my file is', __file__, 'I am a\\b.py' ####### The file c\b.py is ####### def run(): print 'my file is', __file__, 'I am c\\b.py' ####### Expecting a\b.py: my file is C:\Tmp\IIII\a\b.pyc I am a\b.py Expecting c\b.py: my file is C:\Tmp\IIII\c\b.pyc I am c\b.py Expecting a\b.py: my file is C:\Tmp\IIII\a\b.pyc I am a\b.py Expecting c\b.py: my file is C:\Tmp\IIII\a\b.pyc I am a\b.py -- Robin Becker From tzot at sil-tec.gr Tue Apr 6 05:43:32 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Tue, 06 Apr 2004 12:43:32 +0300 Subject: Prothon Prototypes vs Python Classes References: <569c605ld1cj8fc1emolk08ete0s1prls1@4ax.com> <106cc1f2rsnaoe2@news.supernews.com> <406635AB.9050803@mlug.missouri.edu> <106ceeeqc8ph126@news.supernews.com> <106di86neu1qh4d@news.supernews.com> <106eut1pe29uab8@news.supernews.com> <106g7r5nbg9ur16@news.supernews.com> Message-ID: On Mon, 29 Mar 2004 08:05:44 -0500, rumours say that "John Roth" might have written: [tabs vs spaces] >Reading the source for Idle is quite >enlightening: there is a comment about Tk doing something >rather absurd if you change the tab default. Which comment, I believe, is quite old, and possibly refers to an old glitch of Tk (ICBW of course). I like tabs, although out of courtesy to the general consensus in the python world, I filter any code I make available to the public, replacing tabs with 4 spaces (at least I try to remember that :). However, I have a little patch for EditorWindow.py which I apply in every python installation I am going to use, inserting a self.set_tabwidth(3) (which translates to a most pleasant width of 3 ens for the font I use, which is proportional) somewhere in the __init__ of the EditorWindow class. I don't have any bad consequences (or they went unnoticed). I don't preach to use tabs over spaces. I just believe in personal freedom, as long as I respect commonly accepted rules. -- TZOTZIOY, I speak England very best, Ils sont fous ces Redmontains! --Harddix From chris.lyon at spritenote.co.uk Thu Apr 22 08:15:36 2004 From: chris.lyon at spritenote.co.uk (Chris Lyon) Date: 22 Apr 2004 05:15:36 -0700 Subject: How to get the ip addresses of a nic References: <2e262238.0404211825.2f6231b@posting.google.com> Message-ID: jtdubs at eos.ncsu.edu (Justin Dubs) wrote in message news:<2e262238.0404211825.2f6231b at posting.google.com>... > "Bo Jacobsen" wrote in message news:... > > Is there a simple way to get all the ip addresses of a nic, beyound parsing > > /etc/sysconfig/..... > > Depending on your needs: > > >>> socket.gethostbyname(socket.gethostname()) > '192.168.0.18' > > Justin Dubs Tearing apart socket.gethostbyname_ex(socket.gethostname()) might help. From try_vanevery_at_mycompanyname at yahoo.com Mon Apr 26 15:14:26 2004 From: try_vanevery_at_mycompanyname at yahoo.com (Brandon J. Van Every) Date: Mon, 26 Apr 2004 12:14:26 -0700 Subject: How's ruby compare to it older brother python References: <108pvmgl0h7m3ea@news.supernews.com> <108qk9dft7h7o52@corp.supernews.com> Message-ID: Cameron Laird wrote: > . > It's not just that "You won't know until you try" ("is it better > to have children, or join the monastery?"); it's that you won't > know until you try, *and it's inexpensive to try*! It's eminently > feasible to gain experience in either language with a few hours (!) > of work, as opposed to the weeks that must precede enlightenment > about, say, J2EE servers. Of course, those of us who are more into the Complete Waste Of Time [TM] theory of selecting software components will simply give you the bottom line: - If you like Perl, you'll like Ruby. If you think Perl is a bletcherous hack, you'll like Python. - The Python community dwarfs the Ruby community. - Both languages are slow. - Python has lotsa libraries but not everything. Ask here regarding your specific needs. Even if Python were the most elegant language in the world, that's not useful if you must write everything from scratch and don't have time to do it. This is the kind of information you get by simply asking people and reading lotsa archives. Some people say "Try it yourself!" is the only way to learn. They are wrong, and they often don't value people's time. You really can rely on other people's reported experiences of the nuclear mushroom cloud exploding over the horizon. It is not strictly necessary to walk into Ground Zero yourself. Now, if you're going to argue "it's just a little Ruby code..." why don't you try multiplying that by all the languages in the comp.lang.* hierarchy that you could potentially be selecting from? Take a spin by the Language Shootouts if you want to spin your head some more. http://www.bagley.org/~doug/shootout/ http://dada.perl.it/shootout/ You need a filter of some kind for cutting down the options. I suggest asking people, and seeing what languages actually got used for jobs relevant to your software problem / industry. I'm waiting for someone to say that my participation in this thread constitutes trolling. I find it amusing that the boundary between "intelligent language discussion" and "trolling" is mainly a matter of who likes who, not the content. And, this is all I have to say on the subject, so have fun. -- Cheers, www.indiegamedesign.com Brandon Van Every Seattle, WA "Troll" - (n.) Anything you don't like. Usage: "He's just a troll." From sholden at holdenweb.com Sun Apr 25 11:02:10 2004 From: sholden at holdenweb.com (Steve Holden) Date: Sun, 25 Apr 2004 11:02:10 -0400 Subject: mx.DateTime.Error: cannot convert value to a time value In-Reply-To: References: Message-ID: <9oQic.12302$2e6.5340@lakeread01> Sorisio, Chris wrote: > Ladies and gentlemen, > > I've imported some data from a MySQL database into a Python dictionary. > I'm attempting to tidy up the date fields, but I'm receiving a > 'mx.DateTime.Error: cannot convert value to a time value' error. It's > related to glibc returning an error to a pre-1970 date, I think. > You don't say why you think this, though, which might help - when you say you are "attempting to tidy up" the date fields, do you mean convert them into time.time format, or what? > My question: /how/ do I go through the Python direction I've created to > remove the pre-1970 date objects? Ideally, I would be able to iterate > through the dict and remove any DateTime objects that cause int() to > fail. Unfortunately, the DateTime error causes my script to abort entirely. > Ah, I see. Well, this gives us a bit more of a clue: it's the int() of an mx.DateTime object that throws up this error? [pauses to install mx.DateTime ...] > Ex: > > >>> report["COMPANY X"][1][2] > > >>> import mx.DateTime as dt >>> d = dt.DateTimeFrom("1969-12-31 00:00:00.00") >>> d >>> int(d) -68400 Hmm, are we using different versions of Python? (This was on Cygwin 2.3.3 with mx.DateTime from mxBase-2.0.5). Anyway, now I seem to be more or less in the same position as you. Clearly your system has mx.DateTime loaded (at least indirectly) otherwise your dtabase couldn't have created those ms.DateTime objects. It's not much of a problem to install if you don't have it loaded. So, during initialization, have your program set the epoch: >>> epoch = dt.DateTimeFrom("1970-01-01 00:00:00") >>> epoch And then just compare the DateTimes to the epoch to decide whether they can be used or not. >>> if d < epoch: ... print "Throw this one away" ... Throw this one away >>> Perhaps you aren;t getting that error for the reason you suppose, however, in which case a little more information would be helpful. regards Steve From afigueiredo at elnetcorp.com.br Thu Apr 8 16:47:51 2004 From: afigueiredo at elnetcorp.com.br (Aloysio Figueiredo) Date: Thu, 8 Apr 2004 17:47:51 -0300 Subject: List vs tuples In-Reply-To: References: Message-ID: <20040408204751.GC6088@cerberus.elnet.grupomk> * Mitja [08-04-2004 17:42]: > A neewbie's question here, probably discussed before: > what's the purpose of having both lists AND tuples? It's a FAQ, Indeed :) http://www.python.org/doc/faq/general.html#why-are-there-separate-tuple-and-list-data-types Cheers, Aloysio -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From rpm1deleteme at direcway.com Mon Apr 12 06:58:45 2004 From: rpm1deleteme at direcway.com (RPM1) Date: Mon, 12 Apr 2004 06:58:45 -0400 Subject: Best IDE? References: <4ace7f9f.0404111147.3120288a@posting.google.com> Message-ID: "Timothy Wu" wrote ... > rakanishu wrote: > > I don't know if I'd call 'em IDEs but it's worth taking the time to > > learn either emacs or vim. Both are very powerful editors that run on > > multiple platforms. I tried emacs three times, but couldn't get into > > it. I'm now getting hooked on vim. YMMV. > > I love Vim. I really do. And it works wonderfully on both Linux and > Windows with Exuberant ctags (http://ctags.sourceforge.net/) on Python > code. However the only thing that's bugging me is once I'm used to using > Vi(that's practically the only editor I've ever use), I'm forever stuck > with using Vi. I wish all other real IDEs comes with Vi mode, or I can > somehow embed Vim in there (or someone else doing it for me as I'm not > that technical). I would love to be using an IDE if it doesn't slow me down. I used to use Vim all the time but then at work I started doing a lot of Visual Basic and C# programming and needed to use the stupid MS IDE and it was slowing me down switching back and forth between Vim's style and MS "style" so I converted to Scite which is closer to MS style. Once I figured out how to roll my own "jump to tag" stack for Scite I really started to like it. It even fits on a floppy and there is no installation. Also you just hit F5 when you're editing Python code and it runs it without having to download a Python ready version like with Vim. What's really amazing is that there are so many good editors and IDE's available for free! Just my $0.02, Patrick From moosebumps at moosebumps.com Fri Apr 9 18:16:39 2004 From: moosebumps at moosebumps.com (Moosebumps) Date: Fri, 09 Apr 2004 22:16:39 GMT Subject: automatically generating file dependency information from python tools Message-ID: Say you have a group of 20 programmers, and they're all writing python scripts that are simple data crunchers -- i.e. command line tools that read from one or more files and output one or more files. I want to set up some sort of system that would automatically generate makefile type information from the source code of these tools. Can anyone think of a good way of doing it? You could make everyone call a special function that wraps the file() and detects whether they are opening the file for read or write. If read, it's an input, if write, it's an output file (assume there is no r/w access). Then I guess your special function would output the info in some sort of repository, which collects such info from all the individual data crunchers. The other thing I could think of is statically analyzing the source code -- but what if the filenames are generated dynamically? I'd be interested in any ideas or links on this, I just started thinking about it today. For some reason it seems to be a sort of problem to solve with metaclasses -- but I haven't thought of exactly how. thanks, MB From maxm at mxm.dk Mon Apr 19 13:50:18 2004 From: maxm at mxm.dk (Max M) Date: Mon, 19 Apr 2004 19:50:18 +0200 Subject: outline-style sorting algorithm In-Reply-To: <71650A6F73F1D411BE8000805F65E3CB3B3A51@SRV-03> References: <71650A6F73F1D411BE8000805F65E3CB3B3A51@SRV-03> Message-ID: <4084115A.7000801@mxm.dk> jwsacksteder at ramprecision.com wrote: > Am I understanding correctly that python has an implict notion that position > in a list denotes order of magnitude? Batteries included- Big Win! Almost. But you can have multi digit numbers at each position. >>> l = [ ... [4242,42,42], ... [42,4242,42], ... ] >>> l.sort() >>> l [[42, 4242, 42], [4242, 42, 42]] It actually just sorts a list of lists, where the value of each item decides the sort order. regards Max M -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science From hawkeye.parker at autodesk.com Fri Apr 30 13:27:07 2004 From: hawkeye.parker at autodesk.com (haughki) Date: 30 Apr 2004 10:27:07 -0700 Subject: programmatic XML schema validation Message-ID: A year ago i used XSV. I'm having a little trouble with PyLtXML, and I'm wondering if any of the more "mainstream" XML packages (PyXML) has integrated schema validation into their toolset; or, if there are any other schema validating XML parsers for Python out there. thanks, hawkeye parker qa engineer autodesk, inc. From huggiepython at graffiti.idv.tw Thu Apr 8 06:31:04 2004 From: huggiepython at graffiti.idv.tw (Timothy Wu) Date: Thu, 08 Apr 2004 18:31:04 +0800 Subject: A beginner's question on thread In-Reply-To: <1081316259.664569@yasure> References: <1081316259.664569@yasure> Message-ID: <407529E8.3020900@graffiti.idv.tw> Donn Cave wrote: > Well, that's the deal. Use threads to solve a problem, and now > you have two problems. > > I'd probably do it the way Aurelio Martin proposed, with I/O to > the socket thread. It's much neater than whacking the thread, > which is the alternative. > > I wouldn't necessarily use threads in the first place, though. > I think it really depends on the user interface - usually that > has to be the dispatch core of the application, and if it's > built for threads, then there you go. Typically there will be > some provision for dispatch on an I/O channel like a socket. > If you're writing your own user interface, probably just reading > and writing to the tty, and the socket thread is going to be > the one and lonely extra thread - then don't do it, I'd say. > Use select.select, or a package like asyncore or twisted or > whatever (not very familiar with that territory, I just use select.) I think Roger Binns's setDaemon() suggestion works for me. =) Thanks for suggestion the other options. I'll take a look at asnycore or twisted when I have time or perhaps for other projects. Since from what I read somewhere else, it doesn't seem like Python thread's performance is exceptional. Timothy From greg at cosc.canterbury.ac.nz Sun Apr 25 23:32:59 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Mon, 26 Apr 2004 15:32:59 +1200 Subject: Why we will use obj$func() often In-Reply-To: References: <8AWhc.23114$dZ1.11070@fed1read04> <40883BFE.B381518A@alcyone.com> <27_hc.23801$dZ1.2716@fed1read04> <40887145.789A2FE8@alcyone.com> <7cki80hj976bia36lhf9er97v073o1pqvm@4ax.com> <1082783076.585831@yasure> Message-ID: David MacQuigg wrote: > Python added "read access" to external variables, so they must have > considered "write access" as well. I don't know the history, but I > would guess the reason they didn't allow this is the same as the > reason they don't allow GOTO. Yes it is powerful, but it might > encourage bad programming. Actually, it was more that there wasn't any single obvious way of providing write access that blends in with Python's "assignment is implicit declaration" flavour. Rather than pick one at random, it was decided to just provide read access to begin with and leave anything else to later. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From cookedm+news at physics.mcmaster.ca Mon Apr 26 16:51:26 2004 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Mon, 26 Apr 2004 16:51:26 -0400 Subject: How to debug CGI scripts with simulated variables from server? References: <670jc.100949$U83.74356@fed1read03> Message-ID: <8765bmsbsh.fsf@arbutus.physics.mcmaster.ca> At some point, "Sean Berry" wrote: > I want to debug a script that has a line like the following: > if len(os.environ["QUERY_STRING"]) > 0: > > How do I debug this from the command line. I tried > QUERY_STRING='sized=72&shaped=3' ./aqua_getShapes > > But that returns: > QUERY_STRING=sized=72&shaped=3: Command not found. > > Please help. Thanks Are you using tcsh as your shell? The syntax above works with Bourne shells (bash, etc.). With tcsh, try $ env QUERY_STRING='sized=72&shaped=3' ./aqua_getShapes ('env' being the same program that most Python scripts use to find the interpreter in the #! line: #! /usr/bin/env pytho) or, set the variable in the environment $ setenv QUERY_STRING='sized=72&shaped=3' $ ./aqua_getShapes -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From tzot at sil-tec.gr Wed Apr 7 05:05:36 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Wed, 07 Apr 2004 12:05:36 +0300 Subject: [OT] The Cracker's Guide To Python Message-ID: <04g770lqpbhdgr3n3b9mnu9o8f08fdkgk0@4ax.com> Dear all, yesterday afternoon I happened to be in the company of youngsters, and I overheard them talking about the whereabouts of the crack of the latest version of some famous video editing software... instead of preaching about legalities at first etc, I asked: "What exactly do you need this software for?" "I have two avi files and I want to join them..." "Why don't you download VirtualDub and do your job then? Google for it, it's open source and you can download it freely." "So I don't need a crack for it?" ... (!) I'm skipping the rest of the conversation, but the idea of lots of youngsters around the world, brilliant and talented perhaps, that waste their time in illegal activities instead of investing it into open source software struck me as very depressing. So jokingly, how do we advertise python in that "underground" world? Easy: let's provide a crack for every version of python for windows! :) It doesn't matter what it does, perhaps only change the copyright message into "H4x0r3d by Guid0 T34m" by changing directly the pythonxx.dll. The only problem would be that if the crack is written in Python, it won't be able to open the dll as read-write... It's a crazy world... -- TZOTZIOY, I speak England very best, Ils sont fous ces Redmontains! --Harddix From jepler at unpythonic.net Sun Apr 4 09:48:52 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Sun, 4 Apr 2004 08:48:52 -0500 Subject: Python is faster than C In-Reply-To: <5d83790c.0404032144.482787bd@posting.google.com> References: <406F0907.96F37EA1@tunes.org> <5d83790c.0404032144.482787bd@posting.google.com> Message-ID: <20040404134851.GB3455@unpythonic.net> from pprint import * def install_hook(): def displayhook(v): import __main__ if v is not None: if isiterator(v): print "<%s object at 0x%8x:" % ( type(v).__name__, id(v)), v, copy = itertools.tee(v) for elem in itertools.islice(copy, 3): print saferepr(elem), try: copy.next() except StopIteration: pass else: print '...', sys.stdout.softspace=0 print ">" else: pprint(v) __main__._ = v sys.displayhook = displayhook Jeff From mwilson at the-wire.com Tue Apr 6 08:20:44 2004 From: mwilson at the-wire.com (Mel Wilson) Date: Tue, 06 Apr 2004 08:20:44 -0400 Subject: int('2.1') does not work while int(float('2.1')) does References: <40722555.66C70D40@alcyone.com> Message-ID: In article , Joe Mason wrote: >In article <40722555.66C70D40 at alcyone.com>, Erik Max Francis wrote: >> There's a fundamental difference between an int and a float. If the >> string you're trying to convert looks like a float, that means it >> doesn't look like an int. >> >> With your first example of '2.1', what should it mean? Should it >> truncate, round to negative infinity round to positive infinity, round >> to zero, what? Python can't guess for you, so it shouldn't try. Thus >> it's an error. > >Why can it make this guess for "int(2.1)", then? It's got a rule for >converting floats to ints - why not use it here? I see it more as a programmer interface issue. There are kinds of operation that can suggest (especially in a dynamically-typed language) that your program has gotten away from you. Python creator(s?) could have drawn this particular line to this side or that, but in historical fact they drew it here. Perhaps on the principle of one conversion at a time, please. You could argue that unit testing, the universal solvent, would clean up this too. Regards. Mel. From nicolas.lehuen at thecrmcompany.com Thu Apr 22 06:39:50 2004 From: nicolas.lehuen at thecrmcompany.com (Nicolas Lehuen) Date: Thu, 22 Apr 2004 12:39:50 +0200 Subject: This is very simple question References: <108dbd1aftmkc48@corp.supernews.com> Message-ID: <4087a0f6$0$25552$afc38c87@news.easynet.fr> "Cameron Laird" a ?crit dans le message de news:108dbd1aftmkc48 at corp.supernews.com... > In article , > Brian Quinlan wrote: > > > >> I would want to obtain a list of factors (multiples of 2) given a > >> prime number in python. > >> > >> For example 13=[8,4,1], 5=[4,1], 7=[4,2,1], 15=[8,4,2,1] > >> > >> I would appreciate a fuction which would do this. > > > >If we told you it wouldn't be fair to the other students in your class :-) > . > . > . > I'm surprised only one of the responses I've seen so far has > objected to what sure seems like an inappropriate response to > classwork. I'm astonished that no one is reading this question > as I do. I leave as an exercise for readers this generalization > of what *I* think is going on: > > def positional_addends(positive_integer, base = 2): > result = [] > current = 1 > while positive_integer: > remainder = positive_integer % (base * current) > if remainder: > result.append(remainder) > positive_integer -= remainder > current *= base > result.reverse() > return result > > print positional_addends(13) > print positional_addends(5) > print positional_addends(7) > print positional_addends(15) > print positional_addends(78904, 10) > > The real exercise is to convert this to a readable one-liner, > at least for the binary case. > -- > > Cameron Laird > Business: http://www.Phaseit.net You can also use divmod : def decompose(i,base=2): result=[] factor=1 while i>0: i,r=divmod(i,base) if r: result.append(r*factor) # or result.extend([factor]*r), depending on style factor*=base return result.reverse() # if you really want it reversed Regards, Nicolas From hwlgw at hotmail.com Fri Apr 16 10:16:01 2004 From: hwlgw at hotmail.com (Will Stuyvesant) Date: 16 Apr 2004 07:16:01 -0700 Subject: Python Documentation Blows! References: <40699A31.8000708@yahoo.com> <20040330161531.GA17112@vulcan.cprogrammer.org> <86uu70phciv8arhieh3gv51dbf0i33f9ir@4ax.com> Message-ID: > [Terry Carroll] > The state of wxPython's documentation is the major factor that's kept > me from trying it. Short and elegant code examples. Preferably about what you want to do. That is always the kind of documentation I am looking for. But writing that kind of docs is *very* difficult, since you have to be a programmer who can give good examples in an elegant style. Best thing to do IMHO is to look at the effbot site with the online book, or search c.l.p. for examples, e.g. search for particular code strings. we-all-miss-effbot-ly y'rs - will From op73418 at mail.telepac.pt Thu Apr 1 08:17:29 2004 From: op73418 at mail.telepac.pt (Gonçalo Rodrigues) Date: Thu, 01 Apr 2004 14:17:29 +0100 Subject: ANNOUNCE: 'goto' for Python References: Message-ID: <1c5o609a7cnep1gv7d2s9t2j4b485p8dqq@4ax.com> On Thu, 01 Apr 2004 08:10:29 +0100, Richie Hindle wrote: > >Entrian Solutions is pleased to announce version 1.0 of the 'goto' module. > >This adds the 'goto' and 'comefrom' keywords to Python 2.3, adding >flexibility to Python's control flow mechanisms and allowing Python >programmers to use many common control flow idioms that were previously >denied to them. > >'goto' example: breaking out from a deeply nested loop: > > from goto import goto, label > for i in range(1, 10): > for j in range(1, 20): > for k in range(1, 30): > print i, j, k > if k == 3: > goto .end > label .end > print "Finished\n" > > >'comefrom' example: letting cleanup code take control after an error. > > from goto import comefrom, label > def bigFunction(): > setUp() > if not doFirstTask(): > label .failed > if not doSecondTask(): > label .failed > if not doThirdTask(): > label .failed > > comefrom .failed > cleanUp() > >Computed 'goto's are also supported - see the documentation for details. >Computed 'comefrom's are planned for a future release. > >Documentation and further examples: > http://entrian.com/goto/index.html > >Downloads: > http://entrian.com/goto/download.html > >The 'goto' module is released under the Python Software Foundation >license, and requires Python 2.3 or later. > >Please note that this version does not work at the interactive Python >prompt - code importing 'goto' must be in a .py file. This restriction >will hopefully be lifted in a future release. Thanks a lot!! Now I at least have a chance to shame my perlite friends in obfuscation contests with a suitably spaghetified Python code. I'm getting all warm and fuzzy with the possibilities this module opens. Once again, thanks a lot for your efforts to improve the Python language, with my best regards, G. Rodrigues From wweston at att.net Mon Apr 19 11:44:49 2004 From: wweston at att.net (wes weston) Date: Mon, 19 Apr 2004 15:44:49 GMT Subject: outline-style sorting algorithm In-Reply-To: References: Message-ID: jwsacksteder at ramprecision.com wrote: > I have a need to sort a list of elements that represent sections of a > document in dot-separated notation. The built in sort does the wrong thing. > This seems a rather complex problem and I was hoping someone smarter than me > had already worked out the best way to approach this. For example, consider > the following list- > > >>>>foo > > ['1.0', '1.0.1', '1.1.1', '1.2', '1.9', '1.10', '1.11', '1.20', '1.20.1', > '1.30'] > >>>>foo.sort() >>>>foo > > ['1.0', '1.0.1', '1.1.1', '1.10', '1.11', '1.2', '1.20', '1.20.1', '1.30', > '1.9'] > > Obviously 1.20.1 should be after 1.9 if we look at this as dot-delimited > integers, not as decimal numbers. > > Does anyone have pointers to existing code? > > > > > > > > list = ['1.0', '1.0.1', '1.1.1', '1.2', '1.9', '1.10', '1.11', '1.20', '1.20.1','1.30'] def parse(str): list = str.split('.') if len(list) > 0: x1 = int(list[0]) else: x1 = -1 if len(list) > 1: x2 = int(list[1]) else: x2 = -1 if len(list) > 2: x3 = int(list[2]) else: x3 = -1 return x1,x2,x3 def cmp(x1,x2): w1 = parse(x1) w2 = parse(x2) if w1[0] < w2[0]: return -1 if w1[0] > w2[0]: return 1 if w1[1] < w2[1]: return -1 if w1[1] > w2[1]: return 1 if w1[2] < w2[2]: return -1 if w1[2] > w2[2]: return 1 return 0 #--------------------------- if __name__ == "__main__": list.sort(cmp) for x in list: print x From asdf at asdf.com Thu Apr 22 20:12:22 2004 From: asdf at asdf.com (asdf sdf) Date: Fri, 23 Apr 2004 00:12:22 GMT Subject: python web programming / CMS In-Reply-To: References: <0kVhc.54316$eB7.29255@newssvr25.news.prodigy.com> <9YWhc.82882$%l7.5377160@phobos.telenet-ops.be> Message-ID: > Hehe :) Well i'm trying to figure out before i decide on what i'm > going to use. Are there other good CMS around based on Python? > > Anyway, i saw a page ( forgot the link ) that had benchmarks > between python, java, c++ and perl and it seemed that Python > was indeed a lot slower than the other languages. But if you have > a fast server, it might not be so much of a problem. > > flupke > > > Check out the earlier thread 'Simple pyhon-based CMS' (sic) started on 4-13 by Stewart Midwinter in this group. many threads in this group have clearly established that python is just as fast as java, c, c++, perl, assembler and light, and that speed doesn't matter anyways ;) From moosebumps at moosebumps.com Tue Apr 13 00:34:38 2004 From: moosebumps at moosebumps.com (Moosebumps) Date: Tue, 13 Apr 2004 04:34:38 GMT Subject: Random Numbers and a thought References: <107m6f0t4i0gnff@corp.supernews.com> <107m8qvphrjd303@corp.supernews.com> Message-ID: Yeah, this is not really a python question at all... go ask on sci.math or comp.programming and have people discourage and flame you there. : ) MB "A Evans" wrote in message news:107m8qvphrjd303 at corp.supernews.com... > > > What "pattern" are you talking about? > > Well from what I understand about my last post numbers computers generate > aren't truly random > > Quote from the link you gave me > > Computers are deterministic. They cannot create a truly random sequence in > which we cannot predict even if we know all preceding elements - it may be > a bit of work for us to actually sit down and do the figuring, but it is > always possible. > > I would like to take a random number generated by a computer application > then use my application to try and determine the pattern in that application > > Quote me if its impossible > > Basically I would like to create an application that takes a series of > random numbers generated by a computer and searches for the pattern inside > those numbers > > Sorry if I sound like I am repeating myself but I am just trying to explain > myself to the best of my ability > > I guess if the numbers were between say 1 and 1000 it would take 1000 inputs > to understand the pattern if not more I would like to solve it before that > > Cheers > > > From eadorio at yahoo.com Fri Apr 30 03:54:57 2004 From: eadorio at yahoo.com (Ernie) Date: 30 Apr 2004 00:54:57 -0700 Subject: Feedback on Sets, and Partitions References: Message-ID: <5b42ae4.0404292354.86c7026@posting.google.com> "Steve" wrote in message news:... > This post has two parts. First is my feedback on sets. (Hello? Last > summer called, they want their discussion thread back...) Second is some > questions about my implementation of a partition function for sets. > > Part 1. > --- .... snipped > Part 2 > --- .... snipped > For my current project, I need to generate partitions of sets up to size > 25. I am rather hopeless it will ever be feasible, and I have begun > looking for a different approach. Thanks for any replies! For Part 2, Google on restricted growth functions if you are interested in non-recursive generation of set partitions of n objects with k classes. I have an implementation done in python, not using sets but rather an array of integers which can be used for indexing, for processing equivalences and set partitions (See http://www.geocities.com/eadorio/equiv.pdf). Regards, Ernie From no.email at please.com Sat Apr 10 14:55:23 2004 From: no.email at please.com (Stevie_mac) Date: Sat, 10 Apr 2004 19:55:23 +0100 Subject: Static Data? References: <2FTdc.56817$Id.5813@news-binary.blueyonder.co.uk> Message-ID: "Stevie_mac" wrote in message news:2FTdc.56817$Id.5813 at news-binary.blueyonder.co.uk... > I need to have a static class data member like c. How can I achieve this? Thanks all for your assistance. This though raised some question for me... In Jeffs solution, Is self._ID the same variable as _ID (declared immediately after class Counted). Is there 3 _IDs? If you have the time, could you explain (nothing fancy, just brief) the meaning of declaring variables in different locations (like self, below class, as part of class, in a class def). This would be greatly appreciated. and Peters solution class Object: _ID = 1 def __init__(self): self.ID = Object._ID Object._ID += 1 Is Object._ID a class instance variable and self.ID a 'shared' class variable Cheers - Stevie_Mac (confused) From claird at lairds.com Wed Apr 28 08:05:56 2004 From: claird at lairds.com (Cameron Laird) Date: Wed, 28 Apr 2004 12:05:56 -0000 Subject: Is Perl *that* good? References: Message-ID: <108v7h488rohn0e@corp.supernews.com> In article , Leif B. Kristensen wrote: . . . >I actually did rewrite the routine once in PHP, but I usually find >regexps in any other language than Perl a PITA. . . . Right, and anything you can do to make that pain concretely evident interests me. I repeat: I have much experience of people deprecating REs outside Perl; I'm still collecting specific examples, to help me understand exactly what the pain is. -- Cameron Laird Business: http://www.Phaseit.net From peter at engcorp.com Wed Apr 14 12:00:12 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 14 Apr 2004 12:00:12 -0400 Subject: Pygame In-Reply-To: <107qkrbhnjpmh9b@news.supernews.com> References: <107qkrbhnjpmh9b@news.supernews.com> Message-ID: John Roth wrote: > "Alexander R?dseth" wrote in message > news:c5jdv2$s4$1 at orkan.itea.ntnu.no... > >>Why isn't Pygame a part of Python? > > Why should it be? > > In looking thorough the libarary, I find that > everything there is a developer tool of some > sort. The few executables are things like > unittest which are standard parts of the > developer's tool chain. Not that I agree with Alexander that Pygame should be part of the standard download, but isn't it true that it is just as much a developer tool as anything else? He gave examples such as XML and sound... Pygame is in the same vein as those, only more complex. (But I do think it would be crazy to include it, just not for the reason that "it's not a developer tool".) -Peter From dave at pythonapocrypha.com Tue Apr 27 13:20:52 2004 From: dave at pythonapocrypha.com (Dave Brueck) Date: Tue, 27 Apr 2004 11:20:52 -0600 Subject: Non-blocking connect BLOCKS References: Message-ID: <025f01c42c7b$fe337040$6600a8c0@YODA> > I'm using asyncore to download a large list of web pages, and I've > noticed dispatcher.connect blocks for some hosts. I was under the > impression that non-blocking sockets do not block on connects, in > addition to reads and writes. My connect code is essentially the same > as the asyncore example: > > http://docs.python.org/lib/asyncore-example.html > > It seems unlikely that I am the first to encounter this problem, can > someone explain what's wrong and suggest a remedy? Most likely the connect call is doing a DNS lookup, which means your execution pauses while some other (non-Python) code goes and talks to the DNS server. For many hosts the lookup will be fast (or even already cached locally, depending on how your OS is configured), but for others the lookup may require checking with an upstream DNS server (and in the worst case it'll involve several upstream queries for a lookup that ultimately fails). You can eliminate the delay by only passing in IP addresses to connect (it'll notice that they are IP addresses rather than hostnames, and skip the DNS lookup). The problem of course is that you need to then somehow get the DNS addresses yourself. Maintaining a cache of resolved hostnames is a quick hack to reduce the number of lookups, but it doesn't eliminate them. The only alternative is to talk to the DNS server yourself - using asyncore of course so that other connections don't block. IIRC there is some Python code for creating/unpacking DNS packets and at one time it was even included in the Python install (like in the Demo folder or something). If you can find a third-party asynchronous DNS lookup library then that might be the way to go - the above approach can get really messy (lots of details to manage), but it also works and completely solves the problem, so basically you have to decide how badly this problem hurts you. If you do go this route, here's a few hints: - on Windows you can semi-reliably detect the DNS servers by parsing the output of 'ipconfig /all' and on Linux you can usually parse /etc/resolve.conf. - you might also want to parse and honor the values in the /etc/hosts file (LMHOSTS on Windows) - you can of course skip the lookup of the hostname 'localhost' - it might be helpful to cache both the queries that succeed and the ones that fail, depending on your application, as failed lookups can be really slow. - I use a simple class to track cached entries: class AgingMap: def __init__(self): self.dict = {} def Get(self, key): try: expTime, val = self.dict[key] if expTime is not None and time.time() >= expTime: val = None except KeyError: # Not found val = None return val def Set(self, key, value, ttlSec): expires = ttlSec if ttlSec is not None: expires = ttlSec + time.time() self.dict[key] = (expires, value) This of course grows without bounds but most of the time I don't really care. You could add a cleanup() method or something that gets called every once in awhile from your main event loop. A ttlSec value of None indicates a non-expiring entry, e.g. due to an entry from the hosts file. - IIRC you actually get a time-to-live (TTL) value for each IP returned by the DNS, but to simplify things I usually store them all using the minimum TTL value from the whole set (makes the cache simpler). HTH, -Dave From eldiener at earthlink.net Sun Apr 4 20:20:46 2004 From: eldiener at earthlink.net (Edward Diener) Date: Mon, 05 Apr 2004 00:20:46 GMT Subject: Difference between default arguments and keyword arguments References: <10713rf4bjl1bab@news.supernews.com> Message-ID: Roy Smith wrote: > "John Roth" wrote: >> In going through the tutorial I also noticed that it explained >> the * notation, but not the ** notation. I think this also needs >> to be repaired - if one is in the tutorial, both should be. > > I suspect this will be an unpopular opinion, but I don't think either > belong in the tutorial. > > I think the function of a tutorial is to introduce somebody to the > main features of the language, not cover every nook and cranny of the > syntax. The * and ** syntaxes (synti?), while certainly useful, are > also somewhat advanced topics. I think their appearance in an > introductory document is misplaced. Along the same lines, I would like to add to that the explanation for classes in the tutorial is very poor since it assumes a much higher understanding of Python than a tutorial should about the language. A much simpler and more direct explanation regarding classes in Python would be much better. While I mostly got it because I have programmed extensively in other OOP languages, I would expect your average Python beginner to be completely lost by much of the high-level explanation in that chapter. Whoever wrote it was much more interested in explaining the theory of classes in Python, to beginners no less !, than they were toward explaining what classes are in Python and how to use them. And why iterators and generators are included in that chapter are beyond me. Also the tutorial mentions some usages of classes, in previous sections, before the explanation of classes occur, which I feel is definitely a mistake. From mark at prothon.org Fri Apr 23 13:25:38 2004 From: mark at prothon.org (Mark Hahn) Date: Fri, 23 Apr 2004 10:25:38 -0700 Subject: CamelCase versus wide_names (Prothon) References: <6e0680ac.0404211252.7f7b4358@posting.google.com> <4086DFA7.9736E7D3@alcyone.com> Message-ID: "Antoon Pardon" wrote in message news:slrnc8hluh.s60.apardon at trout.vub.ac.be... > copy(a)to(b) That's cool looking but I'm pretty sure impossible to parse the way you want :) Although, out angle brackets are free in Prothon right now. We could reserve them for that: copy
to. Interesting. That would drive newbies to the language crazy :) It sure is readable. It kind of lets you design you own syntax inside the symbols. I must hand it to you. That's one of the most creative crazy ideas I've seen lately. It is refreshing to see fun creative feedback instead of the "your language is just Perl" type of feedback. Maybe you could hang out on Prothon-user ? From marcel at vernix.org Fri Apr 16 10:43:19 2004 From: marcel at vernix.org (Marcel Molina Jr.) Date: Fri, 16 Apr 2004 10:43:19 -0400 Subject: (For gurus) Embed functions in webpages like in PHP? In-Reply-To: <5eq4l1-9vm.ln1@pilz.hasos.com> References: <5eq4l1-9vm.ln1@pilz.hasos.com> Message-ID: <20040416144319.GB7244@foxy> On Fri, Apr 16, 2004 at 12:38:16PM +0200, Robert Ferber wrote: > As far as I've seen, there is no way to embed Python-code in a webpage with > "" or anything equivalent and I don't see any other way to solve this > problem. > > But maybe somebody else does, I'd apreceate all ideas, there is also spyce, which is not a templating system but a way to embed python in html a la php or mason, etc. http://spyce.sf.net/ marcel -- Marcel Molina Jr. From news at contrado.com.au Tue Apr 20 07:54:27 2004 From: news at contrado.com.au (gsm) Date: Tue, 20 Apr 2004 21:54:27 +1000 Subject: python module for interactive web charts References: Message-ID: <40850f74$0$16577$5a62ac22@freenews.iinet.net.au> goto http://www.advsofteng.com/ you can do everythign with this library and it is HTTP server optimised ... i.e small footprint "Moosebumps" wrote in message news:hahgc.23618$zk1.8252 at newssvr27.news.prodigy.com... > Is there anything that is made to generate web pages which have charts > similar to the yahoo finance stock charts? Not looking to graph stocks > specifically, but anything. I like how you can zoom on each axis, and maybe > click to see numerical values and such. > > If there isn't anything in Python, what do people typically use for that > kind of stuff, or is it all hand-rolled? > > thanks, > MB > > From fredrik at pythonware.com Mon Apr 26 02:19:20 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 26 Apr 2004 08:19:20 +0200 Subject: Regexp optimization question References: <698f09f8.0404240819.1d3c6001@posting.google.com> Message-ID: Jeremy Fincher wrote: > It's important to note that many of these features turn the > expressions that represent their use into decidedly non-regular > expressions, regardless of what Pythoneers and Perlers call them :) the use of "regular" in this context refers to religion, not computer science. From tjreedy at udel.edu Mon Apr 26 22:34:44 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 26 Apr 2004 22:34:44 -0400 Subject: Compiler References: <408db4fb$1@news.unimelb.edu.au> Message-ID: "Maurice LING" wrote in message news:408db4fb$1 at news.unimelb.edu.au... > i was wondering just how different is the python bytecode from the java For Jython, 'python bytecode' is jave bytecode. > bytecode? is there a specification for python virtual machine or sort? For CPython, see the documentation for the CPython-specific dis (assembly) module. Note that the details are x.y version specific, subject to change, and not part of the language specification. For 'interesting projects' that have been posted, try googling for Python bytecode hacks. Terry J. Reedy From donald.welch at hp.com Tue Apr 27 20:04:32 2004 From: donald.welch at hp.com (donald.welch at hp.com) Date: Tue, 27 Apr 2004 17:04:32 -0700 Subject: Backticks: What up? References: Message-ID: Steven Brent wrote: > I was wondering why the backticks in the following fragment: > > return 'Here's the result: ' + `self.data` > > My guess is that in a return statement (as opposed to a print statement) > it's necessary to do this in order to get the self.data instance attribute > as a string, so it can be concatenated with the 'Here's the result: ' > string. > > What exactly do the backticks do, then? Just return the result of an > expression as a string? Does my guess make sense and / or is it correct? > Elucidations and gentle ridicule welcome. > > TIA. I think `self.data` is equivalent to repr(self.data). -Don From cedmunds at spamless.rochester.rr.com Wed Apr 14 17:56:45 2004 From: cedmunds at spamless.rochester.rr.com (Cy Edmunds) Date: Wed, 14 Apr 2004 21:56:45 GMT Subject: Missing Console in Pythonwin References: Message-ID: "Mike C. Fletcher" wrote in message news:mailman.561.1081818632.20120.python-list at python.org... > You've likely got the window showing up in a position within the MDI > window which is actually off-screen. Do a Window|Tile or Window|Cascade > and it *should* show up in the MDI area again. > > HTH, > Mike > > Cy Edmunds wrote: > > >Here's a weird one for you. Running Pythonwin on a Win2000 machine the > >console suddenly stopped showing. I can turn it on and off and the checkmark > >comes and goes but nothing is visible. I can do a print preview and see it > >but that's it. > > > >I uninstalled and reinstalled (upgrading from 3.2.2 to 3.2.3) but still no > >luck. Any ideas? > > > > > _______________________________________ > Mike C. Fletcher > Designer, VR Plumber, Coder > http://members.rogers.com/mcfletch/ > > > Mike- That did it! (Could have sworn I already tried that. hmm) Anyway thanks. -- Cy http://home.rochester.rr.com/cyhome/ From jcarlson at uci.edu Sun Apr 18 14:49:38 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Sun, 18 Apr 2004 11:49:38 -0700 Subject: How to kill a SocketServer? In-Reply-To: References: Message-ID: >>That is very interesting. >> >>After doing some research into heavily multi-threaded servers in Python >>a few years back, I discovered that for raw throughput, a properly >>written async server could do far better than a threaded one. >> >>If your request processing takes the most time, you may consider a >>communication thread and a processing thread. >> >>If your processing thread does a lot of waiting on a database or >>something else, it may make sense to have one communication thread, and >>a handful of database query threads. >> >>What part of a request takes up the most time? > > > I wonder if you're making it more complicated than necessary. > > The application uses a lot of CPU as it handles multiple > concurrent client connections. That makes a pretty clear > case for some kind of parallel thread architecture, not > only to dispatch inputs promptly but also to take advantage > of commonly available SMP hardware. As you acknowledge Just because it handles multiple concurrent client connections, doesn't mean it is CPU bound. Also, 'threading' in Python is not the same as 'threading' in C or other languages. I've got an SMP machine, and I've used threads in Python, and no matter what you do, it doesn't use the entirety of both processors (I've said as much in another discussion thread). I don't know the case in other operating systems, but I would imagine you get the same thing, likely the result of the Python GIL. One should also be aware that Python threads take up a nontrivial amount of processor to swap context, so now you're looking at a situation where many threads may not be as helpful as you (or even the original poster) expects. Now, stackless with microthreads pretty much solve the "threads are slow" problem, but thinking without threads will work on all Python installations. > above, the details of that architecture depend a lot on > what exactly they're doing - how many connections over > time, the nature of the request processing, etc. But at I agree, which is why I asked "what part of a request takes the most time". Since the original poster hasn't replied yet, I expect he's figured out what needs to be done in his situation. > any rate, now they have a thread waiting in accept, and they > need to shake it loose. My answer is `define a shutdown > request as part of the service protocol', but maybe you > would have a better idea. Yeah, I would go asynchronous with a timeout. while running: asyncore.poll(1) sys.exit(0) - Josiah From mgibson at tripwire.com Fri Apr 16 17:37:31 2004 From: mgibson at tripwire.com (uebertester) Date: 16 Apr 2004 14:37:31 -0700 Subject: md5.hexdigest() converting unicode string to ascii References: <77b925de.0404151450.5c1f720a@posting.google.com> Message-ID: <77b925de.0404161337.3917ef56@posting.google.com> "Krzysztof Stachlewski" wrote in message news:... > "Fredrik Lundh" wrote in message > news:mailman.687.1082117438.20120.python-list at python.org... > > > (unicode characters are characters too, you know...) > > You're right. :-) > > Stach None of the suggestions seem to address the issue. sValue = _winreg.QueryValueEx(y,"") returns a tuple containing the following (u'http://', 1). The string u'http://' is added to the md5 object via the update() and then hashed via hexdigest(). How do I keep the unicode string from being converted to ascii with the md5 functions? Or can I? Thanks again. From ae Mon Apr 12 15:48:20 2004 From: ae (A Evans) Date: Mon, 12 Apr 2004 12:48:20 -0700 Subject: A new OS References: <107k441hitt2ld9@corp.supernews.com> Message-ID: <107lskfjvqvc3e5@corp.supernews.com> Hello Everyone and thanks for the replies Yes It would be an entire OS made from Python. When I have something started I will come back to this forum and see then who would be interested. As asking for support is the wrong choice of words. What I should of said: Does anyone have any ideas to implement something this large and once I have a solid foundation to build from then who would be willing to help support the development of this project Thank You A. Evans From nw_moriarty at yahoo.com Thu Apr 29 19:46:40 2004 From: nw_moriarty at yahoo.com (Nigel Moriarty) Date: 29 Apr 2004 16:46:40 -0700 Subject: sockets and file locking Message-ID: Hi I've written a client/server using sockets but I get client sends intermixed at the server recieves. I was thinking that a locking file used as the connection might help. Any ideas anyone? It would be great if it worked on Unix and Windows. Nigel From greg at cosc.canterbury.ac.nz Fri Apr 16 01:53:31 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Fri, 16 Apr 2004 17:53:31 +1200 Subject: Python CPU? (Re: Python OS) In-Reply-To: References: <107j4eu6ffn2c68@corp.supernews.com> Message-ID: Peter Maas wrote: > The first step would probably be to define a Python OS. Surely no > CPU speaks Python :) Currently, no, but... *could* there be one? In one of my wilder daydreaming moments recently, I got to wondering what a machine designed from the ground up to run Python code might be like. I got a vision of a Python interpreter implemented in microcode, with a few extra bytecodes for low-level hardware access, with an OS written in Python running on top of it. Would it run Python code any faster than an interpreter running on an off-the-shelf CPU? Possibly not, but it's not clear that it couldn't, either. In any case, it would be a fun thing to design, and maybe even to build, perhaps using an FPGA. Anyone want to help? -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From andymac at bullseye.apana.org.au Tue Apr 13 10:38:04 2004 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Wed, 14 Apr 2004 00:38:04 +1000 (EST) Subject: How to kill a SocketServer? In-Reply-To: <6tadnU3-4_n7QubdRVn-tw@powergate.ca> References: <6tadnU3-4_n7QubdRVn-tw@powergate.ca> Message-ID: <20040413235818.V60495@bullseye.apana.org.au> On Tue, 13 Apr 2004, Peter Hansen wrote: > The OP indicated that "esp. the reaction time" was his concern, not > throughput. If he's right about that, then in principal he could well > be right that an async server would not be the most appropriate. > (I don't really believe that either, though...) If you consider OS architecture, I'm aware of 2 basic streams of think about process management: - clone the existing process; - start each new process from a clean slate. The first approach includes Unix and the second includes MS-DOS & derivatives (eg Windows & OS/2). OSes built around the first appoach have been highly optimised in ways that favour resource sharing by multiple processes, such as file handle & socket inheritance. This architecture tends to favour the async process model, as the resource overhead per process is modest. The second approach usually has a much higher cost when resource sharing (like file handle & socket inheritance) is taken into account, as the resource sharing has to be implemented after the new process has been instantiated rather than as part of the instantiation. As such, this architecture tends to favour the threaded approach, as the resources are much more easily shared. I don't know what Cygwin's fork() performance is like, or what limitations it might have, but I am familiar with the EMX fork() implementation on 32bit OS/2. EMX's fork() is quite resource intensive, due to having to synthesize a lot of machinery that is part of the infrastructure of Unix. Yes, you can spawn() (which is relatively cheap), but then the resources have to be explicitly managed at the application level with associated costs. By contrast, OS/2 is an environment highly developed for threads. Similarly with Win32 in my understanding. So it seems to me that the prevailing view that async is more effective needs to be tempered with a view of resource costing. IMHO, threaded models have been adopted by software such as Apache and Firebird (nee Interbase) for at least certain platforms and problem domains for pragmatic reasons at least as much as political reasons. -- 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 missive at frontiernet.net Thu Apr 15 11:15:11 2004 From: missive at frontiernet.net (Lee Harr) Date: Thu, 15 Apr 2004 15:15:11 GMT Subject: Python script to grep squid logs References: Message-ID: <3Gxfc.1767$dv3.959@news01.roc.ny> > I am a newby python user, I want to create a script which will go > through the squid log file and return me all the URL's accessed(i.e > www.bbc.com). Is RE the way to go? > Not sure if this is just a programming exercise, or if you want to get some work done... in any case you might want to look at these: http://www.squid-cache.org/Scripts/ http://www.mnot.net/squij/ From anand at easi.soft.net Thu Apr 1 06:11:17 2004 From: anand at easi.soft.net (Anand K Rayudu) Date: Thu, 01 Apr 2004 16:41:17 +0530 Subject: Python & COM References: <84257D042AA7D411B3F700D0B7DB9B7C0723BD50@PDC-DSPACE> Message-ID: <406BF8D5.4010604@easi.soft.net> Hi Stefan, Thanks a lot, It worked fine, Also i could extend the same for all data types. Thanks again. Anand From maurice.ulis at wanadoo.fr Sat Apr 17 09:00:20 2004 From: maurice.ulis at wanadoo.fr (ulis) Date: 17 Apr 2004 06:00:20 -0700 Subject: Goodbye TCL References: <0LudnSads6NmpuPdRVn-vw@centurytel.net> Message-ID: <29de415e.0404170500.544aa783@posting.google.com> Just to add one. ulis From usenet at microtonal.co.uk Mon Apr 12 13:41:28 2004 From: usenet at microtonal.co.uk (Graham Breed) Date: Mon, 12 Apr 2004 18:41:28 +0100 Subject: String + number split In-Reply-To: <2SAec.70005$Id.6002@news-binary.blueyonder.co.uk> References: <2SAec.70005$Id.6002@news-binary.blueyonder.co.uk> Message-ID: Stevie_mac wrote: > Hello again, I can do this, but I'm sure there is a much more elegant way... > > A string, with a number on the end, strip off the number & discard any underscores > > eg... > > font12 becomes ('font',12) > arial_14 becomes ('arial',14) Hmm, well, there's always >>> import re >>> def fsplit(s): matcher = re.compile('\d+$|_') return matcher.sub('', s), int(matcher.findall(s)[-1]) >>> fsplit('font12') ('font', 12) >>> fsplit('arial14') ('arial', 14) >>> fsplit('__arial__bold_1_14') ('arialbold1', 14) I'm scary enough that I probably would do it this way. Graham From michele.simionato at poste.it Thu Apr 1 22:33:49 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 1 Apr 2004 19:33:49 -0800 Subject: Prothon, metaclasses, Zope [Was: A 'Python like' language] References: <95aa1afa.0403272243.78d60724@posting.google.com> <95aa1afa.0404010017.2f1683b8@posting.google.com> Message-ID: <95aa1afa.0404011933.5cc5e959@posting.google.com> aahz at pythoncraft.com (Aahz) wrote in message news:... > In article <95aa1afa.0404010017.2f1683b8 at posting.google.com>, > Michele Simionato wrote: > > > > [...] > > Michele, I just got a mailbox full error when I tried sending you > e-mail. Please fix. It should work now. My address michele.simionato at poste.it is mostly a span recipient I don't check often. Rea addresses I check every day are michelesimionato at libero.it and michele.simionato at partecs.com M.S. From rawbobb at hotmail.com Sun Apr 18 23:15:33 2004 From: rawbobb at hotmail.com (bobb) Date: Mon, 19 Apr 2004 03:15:33 GMT Subject: Python/Win based report generator for MySQL databases References: <%zCgc.59345$oj6.9111@bignews6.bellsouth.net> Message-ID: I'm using (banging my head against the wall, actually) with report lab. very powerful... it my be what you're looking for, or maybe too much. I'm also doing reporting results to the web using zope... that may be an option also. hth bobb "Robert Oschler" wrote in message news:%zCgc.59345$oj6.9111 at bignews6.bellsouth.net... > Has anybody seen a nice Python 2.2+ compatible based module/package, running > on a Win2k box, that makes creating reports from a MySQL database easy? > > I am both a Python programmer and MySQL programmer so it doesn't have to be > too simple, just useful. > > Thanks > > Robert > > From skip at pobox.com Mon Apr 26 12:43:49 2004 From: skip at pobox.com (Skip Montanaro) Date: Mon, 26 Apr 2004 11:43:49 -0500 Subject: Is Perl *that* good? (was: How's ruby compare to it older bro In-Reply-To: References: Message-ID: <16525.15429.719288.687059@montanaro.dyndns.org> Peter> I guess it would be interesting to pose the question back to them Peter> "If you could not use regexes in Perl, would you still like to Peter> program in it?" or "If you couldn't use mysql in PHP would you Peter> still use it?" Peter> What similar question, if any, would be a difficult one for us Peter> Python types? "If Python didn't support indentation-based block structure would you still use it?" :-) Skip From lbates at swamisoft.com Tue Apr 27 15:03:14 2004 From: lbates at swamisoft.com (Larry Bates) Date: Tue, 27 Apr 2004 14:03:14 -0500 Subject: How to access outer class attribute from nested class References: Message-ID: I use something like: class SomeClass: SomeAttribute = 1 class SomeNestedClass: SomeOtherAttribute = 2 def __init__(self, parent): self.parent=parent return def SomeNestedClassMethod(self): print "%s-%s" % ( self.parent.SomeAttribute, self.SomeOtherAttribute) def __init__(self): self.SNC=self.SomeNestedClass(self) return if __name__=="__main__": a=SomeClass() a.SNC.SomeNestedClassMethod() I pretty much stole this idea from wxWindows. Larry Bates Syscon, Inc. "Heiko Henkelmann" wrote in message news:c6m9dg$die$1 at online.de... > Please see the following example. Is there any other way to access > SomeAttribute from the nested class, without having to use the actual > name of the outer class? > > > class SomeClass: > SomeAttribute = 1 > > class SomeNestedClass: > SomeOtherAttribute = 2 > > def SomeNestedClassMethod(cls): > print "%s%s" % ( > SomeClass.SomeAttribute > cls.SomeOtherAttribute, > ) > SomeNestedClassMethod = classmethod(SomeNestedClassMethod) > > Thanx From andrew-pythonlist at puzzling.org Tue Apr 13 07:18:23 2004 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Tue, 13 Apr 2004 21:18:23 +1000 Subject: twisted dns server look so easy to set up... am i missing something? does it work? In-Reply-To: References: Message-ID: <20040413111823.GC549@frobozz> On Mon, Apr 12, 2004 at 11:07:48PM -0700, Christian Seberino wrote: > http://twisted.sourceforge.net/TwistedDocs-1.2.0rc2/howto/names.html > > tells you how to create an authoritative dns server in a few lines!?? > > This is 10 times easier than bind and/or djbdns. > > Am I missing something? Does this really work that easily??? > > Anyone tried it?! I've used it a little bit, and it worked fine. -Andrew. From dave at pythonapocrypha.com Fri Apr 30 17:15:27 2004 From: dave at pythonapocrypha.com (Dave Brueck) Date: Fri, 30 Apr 2004 15:15:27 -0600 Subject: Is classless worth consideration References: <69cbbef2.0404290259.fd8d71c@posting.google.com><69cbbef2.0404291209.7a98a799@posting.google.com><8ef9bea6.0404292307.66b78b83@posting.google.com><84Kdnfu3OoN4oA_dRVn-vg@powergate.ca> <69cbbef2.0404301243.451c7b26@posting.google.com> Message-ID: <026501c42ef8$42cd89b0$6b1e140a@YODA> has wrote: > Peter Hansen wrote in message news:<84Kdnfu3OoN4oA_dRVn-vg at powergate.ca>... > > Hung Jung Lu wrote: > > > > > I have also pointed out previously that > > > Python uses 5 devices where prototype-based needs only one: (a) class, > > > (b) instance, (c) module, (d) metaclass, (e) scope. If this is not > > > hideously baroque, then, Houston, we've got a problem. If you can > > > really think outside the box, you'd pitch in also: (f) aspect. > > > > Well, (c) module is merely a packaging technique, not anything > > to do specifically with OOP, so it shouldn't appear in a list > > of "what do you think makes Python's OO model hideously baroque". > > Modules are an encapsulation mechanism, just like class instances, so > I'd say the large and obvious overlap counts as unnecessary > duplication of functionality that by rights ought to have been > factored out of the language design early on. No offsense, but this is faulty logic IMO. Just because two concepts can be unified under the umbrella of another doesn't necessarily mean that elimination of one or the other is the "right thing to do" if your goal is to make a good programming language. Personally I don't really care much about the discussions about purity or theoretical language simplicity - the fact of the matter is that having modules and classes is _useful_. If, under the covers, they are (nearly) identical - so what? In practice it just so happens that they are handy ways to think about things (one of the things that annoyed me about Java was that it _didn't_ have modules). One of the secrets of good language design is not heading too far down the path of simplicity for the sake of simplicity. Not only are modules a useful metaphor in big, real programs, they are useful in one-off scripts/apps where you don't really care about OO, and they're useful when you're teaching programming to newbies (they are a handy intermediate step in that they show the basics of separation of functionality, code reuse, etc. without overloading the student). > So I think it's reasonable to count them, especially seeing how proto-OO languages > have no problems eliminating them as a distinct type. It's certainly a matter of taste - for example, some of the Prothon examples I've seen so far leave me with the impression that they are work-arounds showing you how to get by without some language construct you really wish you had - the I-don't-have-a-chisel-so-this-screwdriver-will-do feeling. Perhaps proto-OO languages work really well in particular problem niches but are less well-suited for general purpose work. -Dave From tjreedy at udel.edu Sun Apr 4 00:29:10 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 4 Apr 2004 00:29:10 -0500 Subject: OT (was Re: But it still doesn't explain the joke) References: <106o7vn56fgmt85@corp.supernews.com><406F3C29.6030504@freedom.place> Message-ID: "Josiah Carlson" wrote in message news:c4nrgo$a98$1 at news.service.uci.edu... > Bush invades Iraq (killing thousands of innocents), lies about his > reasons for it, gets caught in his lie, and lies some more. Oh, and > he's currently up for reelection. Josiah, we could also discuss Clinton invading Serbia, killing thousands of innocents, some intentionally, (to distract attention from his rape of Juanita Broderick, in my opinion), or flip-flop Kerry consorting with hate-America Marxist radicals, and his current relation therewith, but I think it better that we, including you, maintain the political truce that currently prevails on this newsgroup, which is a unique forum for discussion Python, and leave such political discussions to more appropriate fora. Terry J. Reedy From peter at engcorp.com Sat Apr 3 22:10:38 2004 From: peter at engcorp.com (Peter Hansen) Date: Sat, 03 Apr 2004 22:10:38 -0500 Subject: Typing \n in strings In-Reply-To: References: Message-ID: Edward Diener wrote: > Python 2.3.3 on Win2K. In the Python tutorial it says that typing \n in > string literals is the new-line character. I open the interpreter and type a > string with a \n in it but instead of outputting a string with a new line, > it outputs the \n as literal characters of the string. Is the tutorial > wrong, is the interpreter broken, or what is happening ? Notice that there are also quotation marks around that string? What you are seeing is _not_ the string itself, but a printable representation of the string. Since it contains a newline, which is not "printable" (by this definition, anyway) it converts it to \n again. Trust that the string really does contain the ASCII LF character (byte value 10) however. To prove it, and see the real string, just print it: >>> 'test\nme' 'test\nme' >>> print 'test\nme' test me Does that help? Remember always that the interactive interpreter shows you the expression using the repr() call, which with strings will give you a representation that makes it clearer what non-printable characters are contained therein. Here's something that might clear up any remaining questions: >>> print repr('test\nme') 'test\nme' (Or, it might just raise more questions in your mind... experimenting a little more should answer most of them. :-) -Peter From martin at v.loewis.de Fri Apr 9 06:23:11 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 09 Apr 2004 12:23:11 +0200 Subject: print u"\u0432": why is this so hard? UnciodeEncodeError In-Reply-To: References: Message-ID: Hye-Shik Chang wrote: > The encoding of darwin terminal can be discovered by the routine > currently we have. > > perky$ LC_ALL=ko_KR.UTF-8 python But that requires the user to set LC_ALL correctly. I'd rather prefer if the standard installation of the system is supported, where LC_ALL is not set. In particular, Terminal.App supports changing its encoding through Settings, and I would like Python to detect the current settings at startup time. Regards, Martin From fpnews at fencepost.net Wed Apr 21 04:45:44 2004 From: fpnews at fencepost.net (Alan Miller) Date: Wed, 21 Apr 2004 08:45:44 GMT Subject: mcmillan installer (Gordon is OK) References: Message-ID: Got an email back from Gordon McMillan - he's had some other things he had to deal with lately, but he's still around. He didn't say when he might get back to dealing with his domain or installer, but hopefully things will clear up and it won't be too long. ajm From greg at cosc.canterbury.ac.nz Tue Apr 27 01:08:16 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Tue, 27 Apr 2004 17:08:16 +1200 Subject: Is Perl *that* good? (was: How's ruby compare to it older bro In-Reply-To: References: <108qcobc4m8g972@corp.supernews.com> Message-ID: Roy Smith wrote: > 5 years from now, they'll be comfortably mainstream. 10 years > from now, they'll be old-fashioned. And 20 years from now, they'll be > dinosaurs. Don't let yourself become a dinosaur. I suspect that, 20 years from now, there will still be a language called Python, and it will still be quietly and unobtrusively kicking all its competitors' backsides. Whether it will bear any resemblance to the Python of today is another matter... -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From pythongnome at hotmail.com Sun Apr 25 10:18:31 2004 From: pythongnome at hotmail.com (Lucas Raab) Date: Sun, 25 Apr 2004 14:18:31 GMT Subject: python for console game development, memory tracking References: <6soic.40551$c77.17448@newssvr29.news.prodigy.com> Message-ID: "Carl Banks" wrote in message news:IhBic.8575$Gp.6977 at fe1.columbus.rr.com... > Moosebumps wrote: > > > > > > When I have time, I am planning to evaluate Python for console game > > development (on Playstation 2, GameCube, and Xbox). Does anyone have any > > experience with this? > > > > Pretty much the only resource I have found, and the only thing that makes me > > think it might be possible is this: > > > > http://asbahr.com/python.html > > > > I would be interested to hear anybody's experience with Python on consoles. > > I can't speak for Game Cube or XBOX, but I have a Playstation running > Linux, so I know a little. I suspect Game Cube and XBOX have similar, > but less severe, concerns. Of course, since my Playstation has Linux > and a big ol' hard drive, I am not constrained with memory as much as > a native PS2 game would be. > > It seems that Python works just fine. I was able to control graphics > straight from Python using Numeric and a little C wrapper, and it > worked pretty well. It wasn't much of a demo, though, and of course > almost all of the graphics work would be done from C anyways. I don't > have much more experience than a few graphics demos, though. > > One thing that bothers me a little is that Python uses double > precision floats, but PS2 only supports single-precision natively. I > suspect most calculation-type code would be done in C, though. > > > > Before I even begin investigating though, there is a major question I have: > > How can you track the memory usage of Python? I would like to be able to > > track allocations by function / class, etc. I have googled and seen a bunch > > of threads with 1 guy asking the same exact question that I am, and no > > responses, which leads me to believe it's very easy or not possible. This > > would be dealbreaker unfortunately. But I am optimistic that Python is well > > designed so there must be some solution. > > You're right that memory is probably the biggest factor against Python > use, at least if you don't patch it. If you use it for production > work, I don't think there's any way you'd be able to use Python's > regular memory allocation. So, seeing that you'd have to use your own > memory allocation, you can keep track of the stuff yourself. Or you > can use a library that works on PS2 and also does what you need. > > > -- > CARL BANKS http://www.aerojockey.com/software > "If you believe in yourself, drink your school, stay on drugs, and > don't do milk, you can get work." > -- Parody of Mr. T from a Robert Smigel Cartoon There is a similar thing for Xbox. You can download Linux onto your Xbox, then hook up a mouse and keyboard to the memory ports on your controller. I can't personally attest to how well that works. Since I can't exactly recall where I saw it, you might try Googling "Xbox Linux". Lucas From weinhand at unileoben.ac.at Wed Apr 7 04:12:15 2004 From: weinhand at unileoben.ac.at (Weinhandl Herbert) Date: Wed, 07 Apr 2004 10:12:15 +0200 Subject: Python and postgres In-Reply-To: <40735c00$1@clarion.carno.net.au> References: <40735c00$1@clarion.carno.net.au> Message-ID: <4073b7db$0$30786$3b214f66@aconews.univie.ac.at> Steve wrote: > Hi, > > I have postgres 7.4.1 running on my server and I've been trying to find > a good python-postgres interface module. I installed Pygres on another > machine running Linux using a RPM release and it works. However, I need > to do the same for an alpha server and I can't find source files for you may want to try psycopg : http://www.initd.org/software/initd/psycopg i've compiled it successfully on my machines. it requires mxDateTime installed : http://www.egenix.com/files/python/egenix-mx-base-2.0.5.tar.gz from Python's db-sig : psycopg (PostgreSQL) A DB-API 2.0 compliant driver designed to support heavily multithreaded applications with many cursors. Cursors can be very short-lived since the driver has an intelligent system for reusing db connections at libpq level. Supports thread level 2. > PyGres that would compile with 7.4.1 anywhere. Can someone please help > me out? I need a good postgres python interface to work with. > > Cheers, > > Steve Herbert From peter at engcorp.com Mon Apr 19 08:09:56 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 19 Apr 2004 08:09:56 -0400 Subject: Proposed PEP: Treating Builtins as Constants in the Standard In-Reply-To: References: <5d83790c.0404171557.3db69f48@posting.google.com> Message-ID: Yermat wrote: > Raymond Hettinger wrote: >> PEP: 329 >> Title: Treating Builtins as Constants in the Standard Library >> Author: Raymond Hettinger >> >> Abstract >> ======== >> >> This proposal is to add a private function for treating builtin >> references as constants and to apply that function throughout >> the standard library. > > Is it really a good thing to do it manually? > Shouldn't be done automatically by a simple analyser? Not requiring that it be done manually, or at least not providing a simple means of disabling it, would prevent some kinds of automated testing. The most easily demonstrated one is where the builtin open/file calls are replaced with a simulated ("mock") file system which applies to *all* modules, not just a single module under test. This functionality is critical to some people using Python with the Test-Driven Development approach to software. -Peter From ville at spammers.com Thu Apr 1 14:28:08 2004 From: ville at spammers.com (Ville Vainio) Date: 01 Apr 2004 22:28:08 +0300 Subject: Python conference slogan References: <30260531.0404010833.1b834032@posting.google.com> Message-ID: >>>>> "Shane" == Shane Hathaway writes: >>> I surrender immediately and have to admit that I don't get it (One >>> Nation Under Under Python). Google was no help. I couldn't find the Shane> Ok, it's definitely not good. It's a cross between the Shane> U.S. Pledge of Allegience and Python's use of Shane> double-underscores. It was *not* intended to suggest that Shane> Python replaces deity. ;-) Actually, it seems to bring up mostly fascistic connotations, esp. if you are not American. Throw in the fact that we like to refer to Guido as BDFL, and you are conveying a very unfortunate image ;-). -- Ville Vainio http://tinyurl.com/2prnb From loic at fejoz.net Tue Apr 6 07:50:02 2004 From: loic at fejoz.net (Yermat) Date: Tue, 06 Apr 2004 13:50:02 +0200 Subject: design by contract versus doctest In-Reply-To: References: <407174ea$0$5066$4d4ebb8e@news.nl.uu.net> <40718ddb$0$5071$4d4ebb8e@news.nl.uu.net> <4071a6d4$0$5064$4d4ebb8e@news.nl.uu.net> Message-ID: Colin Blackburn wrote: > On Tue, 06 Apr 2004 06:51:16 -0400, Peter Hansen wrote: > >> Yermat wrote: >> >>> Peter Hansen wrote: >>> >>>> But I'm certainly no expert in (or proponent of) DBC... >>> >>> see http://www.python.org/doc/essays/metaclasses/Eiffel.py >>> to now how to do (at least one way to) design by contract in Python. >> >> >> This doesn't appear to do what the OP says it should do. >> I see preconditions which, while coded in separate methods >> from the code for which it is written, still executes >> every time the method is called. That is, in terms of the >> sequence of code, it's the same as just putting the check >> in at the top of the called method. > > > In this case yes because python does not support DbC within itself. > However, in a language that does support DbC (Eiffel) these checks can > be turned on during the implementation phase and turned off in the > delivered code. There are techniques in python, java and other > languages to implement DbC using comments and documentation, ie the > contract checks are only executed when a tool/module able to process > the structure comments is loaded. > > DbC though is about design rather than just a way testing of > parameters. It is a philosophy of program design. See Object Oriented > Software Construction, ed 2, by Bertrand Mayer. > > Colin > -- Hi, Not really each time ! As it uses "assert", it is turn off by using -O option of python or by removing the metaclass ! So it work exactly as DBC implemented in Eiffel. His author is Bertrand Meyer (with an 'e'). So please re-read it again ! Yermat From __peter__ at web.de Mon Apr 5 08:43:45 2004 From: __peter__ at web.de (Peter Otten) Date: Mon, 05 Apr 2004 14:43:45 +0200 Subject: How to assign a default constant value in a function declaration References: Message-ID: rzed wrote: > "Vineet Jain" wrote in > news:mailman.341.1081121191.20120.python-list at python.org: > >> The following does not work although it seems like something you >> should be able to do. >> >> def someFunction(option=Constants.DEFAULT_VALUE): >> > Do you mean in a context like this? > >>>> class Const: > ... someVal=255 > ... otherVal=0 > ... >>>> Const.someVal > 255 >>>> someVal=255 >>>> someVal > 255 >>>> def blip(Const.someVal): > File "", line 1 > def blip(Const.someVal): > ^ > SyntaxError: invalid syntax >>>> def blip(someVal): > ... (no syntax error) > > > I've wondered about that, too. Stop wondering then: >>> class Constants: ... DEFAULT_VALUE = 42 ... >>> def someFunction(option=Constants.DEFAULT_VALUE): ... print "option =", option ... >>> someFunction(1) option = 1 >>> someFunction() option = 42 >>> Constants.DEFAULT_VALUE = "another value" >>> someFunction() option = 42 >>> Constants = None >>> someFunction() option = 42 Here Constants might also be a module. The only constraint is that Constants.DEFAULT_VALUE is bound when the function is defined, not when it's called. Peter From fumanchu at amor.org Wed Apr 7 16:25:08 2004 From: fumanchu at amor.org (Robert Brewer) Date: Wed, 7 Apr 2004 13:25:08 -0700 Subject: Using function parameters to determine method kind Message-ID: Lenard Lindstrom wrote: > When I first posted my question on using a function's first parameter > to determine method kind I had a very specific idea on how to > implement it in Python. Type function becomes subtypable and several > builtin subtypes are made available. The root type has no __get__ > descriptor method so is a static method by nature. It has two subtypes > having __get__ methods: an instancefunction is what we now > call FunctionType, and a classfunction. >8 > My example module 'dparams.py' uses a metaclass to wrap functions in > staticmethod or classmethod descriptors at class creation, > but I consider this a less than ideal solution. And to implement > it in Python means that 'object' can no longer be of type 'type'. > I believe this is unacceptable. So I consider the issue of using > parameters to determine method kind closed. ...it would not be a "less than ideal" solution, IMO, if it were built into 'type' itself, rather than a metaclass. This is the foundation for my recent crack at the decorator problem: http://mail.python.org/pipermail/python-dev/2004-April/044151.html, which uses metaclasses as you indicate, but hopes for a day where the same functionality would be provided without using metaclass, being rather an integral part of the builtins "function", "classmethod", "staticmethod", etc. It currently uses the metaclass to lazily bind the actual function block to the function name, but a metaclass is not the only (future, possible) way to do so. > I made FunctionType subtypable just to prove a point... > But if there is enough interest and I have the time I > may try and do it again. I'd be interested...mostly because I like clean syntax and all of the proposed syntaxes for decorators are ugly IMO. :( Robert Brewer MIS Amor Ministries fumanchu at amor.org From dgray at coldstorage.com Sun Apr 25 23:28:02 2004 From: dgray at coldstorage.com (Doug Gray) Date: Sun, 25 Apr 2004 23:28:02 -0400 Subject: urllib2 timeout?? Message-ID: <200404260329.XAA21138@mail> Python2.3 on Redhat Linux 8.0 here is the code. import urllib2 import ClientCookie request = urllib2.Request("http://fantasygames.sportingnews.com/crs/home_check_reg.htm l",data='username=penngray1&password=testpwd') response = ClientCookie.urlopen(request) #return response.info() request2 =urllib2.Request("http://fantasygames.sportingnews.com/baseball/fullseason/u ltimate/game/frozen_roster.html?user_id=6208") resp2 = ClientCookie.urlopen(request2) return resp2.read() The ClientCookie is a 3rd party software that handles the Set-cookie stuff on the client for me. This allows me to login into a site then access other webpages from that site that need cookies set. The problem is that 50% of the time it works and 50% of the time it fails. I assume this problem is a time out problem Is there a time out problem here, why is the connection so slow in the first place. Is it my unix server? Here is the error when it fails. Traceback (most recent call last): File "/usr/lib/python2.3/site-packages/mod_python/apache.py", line 299, in HandlerDispatch result = object(req) File "/usr/lib/python2.3/site-packages/mod_python/publisher.py", line 136, in handler result = util.apply_fs_data(object, req.form, req=req) File "/usr/lib/python2.3/site-packages/mod_python/util.py", line 361, in apply_fs_data return object(**args) File "/usr/local/apach2/fantasy/TSN/htmlRead.py", line 31, in getwebpage response = ClientCookie.urlopen(request) File "/usr/lib/python2.3/site-packages/ClientCookie/_urllib2_support.py", line 829, in urlopen return _opener.open(url, data) File "/usr/lib/python2.3/site-packages/ClientCookie/_urllib2_support.py", line 520, in open response = urllib2.OpenerDirector.open(self, req, data) File "/var/tmp/python2.3-2.3.3-root/usr/lib/python2.3/urllib2.py", line 326, in open '_open', req) File "/var/tmp/python2.3-2.3.3-root/usr/lib/python2.3/urllib2.py", line 306, in _call_chain result = func(*args) File "/usr/lib/python2.3/site-packages/ClientCookie/_urllib2_support.py", line 754, in http_open return self.do_open(httplib.HTTP, req) File "/usr/lib/python2.3/site-packages/ClientCookie/_urllib2_support.py", line 612, in do_open raise URLError(err) URLError: Thanks in advance Doug -------------- next part -------------- An HTML attachment was scrubbed... URL: From dustin at myaddress.net Wed Apr 21 15:40:19 2004 From: dustin at myaddress.net (Dustin) Date: Wed, 21 Apr 2004 19:40:19 GMT Subject: Python editors for Windows question Message-ID: Hello, I just started programming in Python last night, and I've really enjoyed my experience so far. I would like to know if there is a Windows editor that recognizes Python and will support a module syntax/definition lists For instance, let's say that I set form = cgi and then when I hit the period (".") on the keyboard, a list of objects shows up, such as FieldStorage(), etc.. Any suggestions are appreciated. Thank you! Dustin From dkuhlman at rexx.com Sun Apr 18 15:54:38 2004 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Sun, 18 Apr 2004 12:54:38 -0700 Subject: AOP use cases References: <84fc4588.0404140106.3fa0c55@posting.google.com> <0pydnSB4WYuieuLdRVn-hQ@powergate.ca> <1082n594lndh27f@news.supernews.com> Message-ID: John Roth wrote: > "Peter Hansen" wrote in message > news:0pydnSB4WYuieuLdRVn-hQ at powergate.ca... >> Will Stuyvesant wrote: >> >> > What are good usage examples? >> [snip] > > I suspect you're not going to get any really compelling ones. Isn't AOP antithetical to the Pythonic admonition to make everything explicit? "Explicit is better than implicit." -- The Zen of Python (by Tim Peters) You can stare at a section of AOP code as intently as you like, and never discover the changes that are woven into it. A little more zen: "Mysterious is the worst of all." Dave [snip] > > John Roth -- http://www.rexx.com/~dkuhlman dkuhlman at rexx.com From nicksjacobson at yahoo.com Fri Apr 30 02:06:02 2004 From: nicksjacobson at yahoo.com (Nick Jacobson) Date: 29 Apr 2004 23:06:02 -0700 Subject: static keyword References: Message-ID: Peter Hansen wrote in message news:... > Nick Jacobson wrote: > > > Yes, that is excellent. Thank you very much. :) > > > > The good news: you can reset all your "static" data whenever you want, > > by calling foo(). Can't do that in C. > > > > The bad news: I just hope I don't forget and call foo() instead of > > g.next(). > > I would rather the command foo() by default call the next iteration, > > and, say, foo().reset() would recall the function from scratch. But > > that's neither here nor there.. > > Do this then (and this is, if not a hack, at least unusual style): > > >>>def foo_reset(): > # same as previous foo was, just renamed > > >>>foo = foo_reset().next > >>>foo() > First pass > 11 > >>>foo() > 12 > > Happy now? ;-) > > -Peter Yes, in fact that's very clever. Thanks! :) From __peter__ at web.de Tue Apr 6 09:08:37 2004 From: __peter__ at web.de (Peter Otten) Date: Tue, 06 Apr 2004 15:08:37 +0200 Subject: recursive file editing References: Message-ID: TaeKyon wrote: > Il Sun, 04 Apr 2004 12:11:25 +0200, Peter Otten ha scritto: > >> The following code comes with no warranties. Be sure to backup valuable >> data before trying it. You may need to edit the regular expressions. Call >> the script with the directory you want to process. > > Seems to work all right ! > I have a question: > >> class Path(object): > # multiple function definitions follow, amongst which: > >> def files(rootfolder): >> for folder, folders, files in os.walk(rootfolder): >> for name in files: >> yield Path(folder, name) > > So 'Path' is the name of a class and _contemporaneously_ the > result of one of the functions the class contains ? No, the functions up to __str__() are indented one level. This means they belong to the Path class, i. e. they are methods. In contrast, files() is a standalone function - or more precisely a generator. As a rule of thumb you can tell functions from methods by looking at the first parameter - if it's called "self" it's a method. As a side note, though it's not the case here it is possible for a class to have methods that return new instances of the same class (or even the same instance which is what a considerable fraction of python users wishes for list.sort()). For example: class Path(object): # ... as above def child(self, name): """ create a new Path instance denoting a child of the current path """ return Path(self.path, name) def __repr__(self): """ added for better commandline experience :-) """ return "Path(%r)" % self.path Now try it: >>> from processtree import Path >>> p = Path("/path/to", "folder") >>> p.child("file") Path('/path/to/folder/file') >>> p.child("sub").child("subsub") Path('/path/to/folder/sub/subsub') > Or are there really two separate 'Path' things which don't interfere > because each has its own namepace ? No, every Path(folder, name) creates a new Path instance as defined above. When you see Class(arg1, arg2, ..., argN), under the hood Python creates a new instance of Class and calls the special __init__(self, arg1, ..., argN) method with the instance as the first (called self by convention) and arg1,..., argN as the following arguments. > I'm sorry for the repeated questions, maybe I should take this discussion > over to the tutor mailing list ! I suggest that you stick with with the simpler approach in my later post until you have a firm grip of classes. For the task at hand the Path class seems overkill, now I'm reconsidering it. Peter From peter.maas at mplusr.de Tue Apr 20 04:04:35 2004 From: peter.maas at mplusr.de (Peter Maas) Date: Tue, 20 Apr 2004 10:04:35 +0200 Subject: Dollar sign ($) on foriegn keyboards? (prothon) In-Reply-To: References: Message-ID: LB wrote: > $ is a shift-key on italian standard keyboard. Also on german standard keyboard. Mit freundlichen Gruessen, Peter Maas -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Hubert-Wienen-Str. 24 Tel +49-241-93878-0 Fax +49-241-93878-20 eMail peter.maas at mplusr.de ------------------------------------------------------------------- From newsgroups at jhrothjr.com Mon Apr 26 10:09:09 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 26 Apr 2004 10:09:09 -0400 Subject: About generators References: Message-ID: <108q607fjni5ba5@news.supernews.com> "Peter Hansen" wrote in message news:L-6dnRq_ZvsmjBDdRVn_iw at powergate.ca... > Andrea Griffini wrote: > > > I'm new to python and I really like what I've seen so far > > with just one exception; the absence of a nice syntax > > for ranges of integers. I've read PEPs about allowing > > > > for i in 10: > > print i > > > > and I must say I don't like it very much, but I didn't > > find a discussion about what looks more natural > > > > for i in 0...9: > > print i > > > > or > > > > squares = [x*x for x in 1...100] > > > > that is having "expr1 ... expr2" returning an iterator > > from expr1 to expr2 (second limit included). > > > > Has this been considered ? If yes (as I suppose) where > > can I find and explanation about it ? > > Google Groups is always helpful for such questions: > > http://groups.google.com/groups?q=integer+range+syntax&meta=group%3Dcomp.lang.python.* > > This leads to various threads, such as the "Re: Thoughts on PEP284" > which had the same proposal as yours and what is, I believe, an > adequate reason for rejecting it. As far as I can tell, the appropriate PEP to reference is 204: range literals. That one proposed using slice notation, and it was firmly rejected. I frankly like the idea since .. or ... is an operator, so it naturally leads to a magic method or two, opening the door to other types of ranges, such as reals or dates, etc... John Roth > > -Peter From andy47 at halfcooked.com Tue Apr 6 17:27:53 2004 From: andy47 at halfcooked.com (Andy Todd) Date: Tue, 06 Apr 2004 22:27:53 +0100 Subject: IBM Developerworks: Learn how to write DB2 JDBC tools in Jython In-Reply-To: <66a61715.0404041039.2972d92b@posting.google.com> References: <3ea34487.0404031654.596cbd06@posting.google.com> <66a61715.0404041039.2972d92b@posting.google.com> Message-ID: Buck Nuggets wrote: > workingdudetor at yahoo.com (Neo) wrote in message news:<3ea34487.0404031654.596cbd06 at posting.google.com>... > >>Java Libraries + Python Syntax >> >> >>ttp://www-106.ibm.com/developerworks/db2/library/techarticle/dm-0404yang/index.html > > > It's always nice to see more support for agile languages with db2. I > know that there's a ton of support for java, but frankly I'm far more > interested in seeing db2 for fast-moving tiger-teams than for > slow-moving and massive projects. With that in mind great support for > python, ruby, php, perl, etc is essential. > > ks Sadly DB2 UDB isn't exactly the most developer friendly database out there. Whilst it's rock solid in a production environment it doesn't offer a lot of support during the development phase of a project. When your schema is changing more than once in a blue moon you can spend an awful lot of time adapting; http://www.halfcooked.com/mt/archives/000490.html http://www.halfcooked.com/mt/archives/000491.html http://www.halfcooked.com/mt/archives/000507.html Regards, Andy -- -------------------------------------------------------------------------------- From the desk of Andrew J Todd esq - http://www.halfcooked.com/ From RobMEmmons at cs.com Wed Apr 14 22:16:21 2004 From: RobMEmmons at cs.com (Robert M. Emmons) Date: Wed, 14 Apr 2004 21:16:21 -0500 Subject: Starting a Python COM server from vb? In-Reply-To: References: <407B3592.7010508@cs.com> Message-ID: <407DF075.4030900@cs.com> > How do I ensure that the service is registered? Does this need to > happen after every bootup? I recommend highly the book: Python Programming on Win32 by Mark Hammond and Andy Robinson ISBN: 1-56592-621-8. This should anwser many of your questions regarding Python and windows. They talk both about COM/ACTIVEX and about windows Servicies. The short answer to your question--I think it really depends on what you want. If you really want to run a "Service" in the windows sense, then yes you probably have to launch this at boot time. Generally Servicies or Daemons are just programs that run in the background. There is a way to run these at startup on windows. I can't remember exactly how -- I'm thinking there is a "Servicies" control panel(???) On the other hand if your talking about COM/ActiveX Servers that is a totally different thing. These are not Servicies. There is a standard way of writing these in Python using the win-32all package -- i.e. the python windows extnesions. It is to complicated for me to explain directly here...though it is not difficult. You need the book or another reference in front of you. Basically to setup a server you have to add some special attributes to the classes that you want to register, then some code that does the registration. The registration is peristant. You put your program in some fixed location and then register it once and it's good always. I've done this to write nice little utilities to call from VBA in Excel. Works nice. The book I referenced by the way covers both COM/ActiveX and Servicies to regarless of your interest it should have some information. Rob From dmq at gain.com Fri Apr 23 20:59:06 2004 From: dmq at gain.com (David MacQuigg) Date: Fri, 23 Apr 2004 17:59:06 -0700 Subject: Why we will use obj$func() often References: <84Uhc.22278$dZ1.5087@fed1read04> <8AWhc.23114$dZ1.11070@fed1read04> <40883BFE.B381518A@alcyone.com> <27_hc.23801$dZ1.2716@fed1read04> <40887145.789A2FE8@alcyone.com> <7cki80hj976bia36lhf9er97v073o1pqvm@4ax.com> Message-ID: <0kdj80hcdeo7igf1enbqf44gohhfhkff0u@4ax.com> On Fri, 23 Apr 2004 16:36:15 -0700, "Mark Hahn" wrote: > >"Donn Cave" wrote ... > >> What you're doing there looks to me a bit like Objective >> CAML's ref type. "a = ref 0" is a mutable container for an >> immutable integer. It's just syntactic sugar for a mutable >> record; the sugar is the assignment a := 1, and then there's >> some special dereference notation -- a := !a + 1, something >> like that, I forget. > >I'm not doing anything nearly that complex. &var just gives access to the >outer closure scope and directly accesses var in that scope, just like >accessing a global variable. It isn't just syntax sugar for var[0] because >it has none of the list overhead associated with the var[0] kludge. & just >tells the compiler where to find the variable, just like capitalized >variables in Prothon say to find them in the global space and .var says to >find var in self. > >The whole point is to make things simpler, more readable, and more >efficient, but when people see the & symbol they somehow automatically think >it's complex. Maybe my mind doesn't work like everyone else's. I think you are misunderstanding the objections to the proposed features. I see on this thread very little knee-jerk reaction to a new symbol. Its the accumulation of symbols and special syntax for little problems that will cause a big problem. In my first post on this thread I pointed out the problem: -- Perl-like syntax: Special symbols and capitalization to indicate variable scope, closures, dynamic variables, etc. local, Global, .x, ^x, X, &x, x, @x Yes, I did use the P word, but my criticism is *not* over the choice of symbols. What I worry about is the complexity which will result when all these little features become commonly used, and students are accessing variables all over the place instead of thinking about the structure of their programs, and figuring out how to solve a problem with simple syntax and structures. Once you add something like &x to a language, you can never take it out. Not only will you break existing code, but you will break the hearts of all those who now cannot write a program without that feature. I'm not trying to give you a hard time. I just don't see the value in providing elegant syntax for obscure problems like &x. I'm not saying the value isn't there. I just don't see it in what you have posted so far, and I'm a bit put off by your statement that you don't have time to put together a use-case. If I were you I would postpone all these embellishments, and the associated discussions, and focus on the one really good thing in Prothon, your simplification of classes. If you can do that in a way that doesn't make migration from Python difficult, you will have a winner. -- Dave From claird at lairds.com Sat Apr 3 19:32:21 2004 From: claird at lairds.com (Cameron Laird) Date: Sun, 04 Apr 2004 00:32:21 -0000 Subject: emergent/swarm/evolutionary systems etc References: Message-ID: <106ulsl62h4f8df@corp.supernews.com> In article , Peter MacKenzie wrote: >Hello, I'm Peter, and I'm very much a newbie. . [recapitulation of ancestral lore centering on von Neumann, Turing, ...] . . Do you know that there are Usenet newsgroups that focus on these specific domains, including comp.ai.alife comp.theory.self-org-sys sci.systems sci.anthropology sci.nonlinear alt.folklore.computers bionet.info-theory ? -- Cameron Laird Business: http://www.Phaseit.net From newsgroups at jhrothjr.com Wed Apr 14 20:23:40 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Wed, 14 Apr 2004 20:23:40 -0400 Subject: Pygame References: <107qkrbhnjpmh9b@news.supernews.com> Message-ID: <107rlp0in3r1k76@news.supernews.com> "Alexander R?dseth" wrote in message news:c5jpkb$6th$1 at orkan.itea.ntnu.no... > > Why should it be? > > Because it's inconsistent that Python includes many platform-specific and > hardware-specific modules, > and even gui-modules like Tkinter, but, afaik, no way at all to create > fullscreen and/or hw-accelerated graphics. > > > > In looking thorough the libarary, I find that > > everything there is a developer tool of some > > sort. The few executables are things like > > unittest which are standard parts of the > > developer's tool chain. > > I agree pretty much with Peter's reply. > How exactly did you "look through the library"? > Looking at http://docs.python.org/modindex.html, I find modules for sound, > xml, graphics, mail, a web-server and even the deprecated and insecure > "Enigma-like encryption and decryption". :-) Let's take a look at that. Sound support is on the same level as the SDL package that Pygame is based on. XML is a developer tool. Graphics support is pretty weak except for the TK toolkit, which supports the standard windows paradigm. While not everyone likes TK, the function is, at least, pretty pervasively needed. There's a pretty large selection of tools that support internet protocols, including the mail package you refer to. Etc. What I don't find is support for specialty application areas. Games are a specialty application area. > Python is supposed to be "batteries included", but still hasn't got native > support for fullscreen graphics. Pygame is layered on top of SDL, which in turn is layered on top of Open GL. If the issue is support for full screen 3d graphics, (which wasn't apparent from your initial post), I would suggest that either of those would be a better candidate. In fact, I certainly wouldn't object to including an interface to Open GL. > Granted, Pygame might not be the optimal solution, due to licensing issues > (or whatever other reason might appeal to you), but IMHO, there should be a > module included that allowed for similar functionality. > > - Alexander > > From gabriel.cooper at mediapulse.com Fri Apr 16 11:13:39 2004 From: gabriel.cooper at mediapulse.com (Gabriel Cooper) Date: Fri, 16 Apr 2004 11:13:39 -0400 Subject: Newbie question: matching In-Reply-To: References: Message-ID: <407FF823.8070207@mediapulse.com> josh R wrote: >Hi all, > >I am trying to write some python to parse html code. I find it easier >to do in perl, but would like to learn some basic python. My code >looks like this: > > You will be doing yourself a disservice if you do this by hand. Check out http://www.diveintopython.org/ .. it's a free online book (also available in print). Jump to the chapter on XML parsing. You'll save yourself loads of time and effort, and you'll take advantage of the python libraries. After all, python *is* supposed to be "batteries included." From roy at panix.com Tue Apr 27 08:35:16 2004 From: roy at panix.com (Roy Smith) Date: Tue, 27 Apr 2004 08:35:16 -0400 Subject: Is Perl *that* good? References: <108q51j4dscn7dc@corp.supernews.com> <87fzaqmm8t.fsf@strauser.com> <38ec68a6.0404262308.50029919@posting.google.com> Message-ID: Ville Vainio wrote: > >>>>> "Asun" == Asun Friere writes: > > Asun> Wouldn't you need to import the re module and compile the > Asun> pattern first? (And wouldn't you use 'search' rather than > Asun> 'match'?) And > > I rarely compile regexps, just pass the string to the re functions. For the occasional ad-hoc match, this is fine. The advantage of pre-compiling is that it's faster, since it doesn't have to recompile the regex each time. I don't see anything in the reference manual which says re.match() caches compilations, but I suspect it does. Even a trivial check for "thisRegEx is lastRegEx" would be sufficient to negate the speed advantage of pre-compiling in most cases. Anybody know if it does this? From peter at engcorp.com Sat Apr 17 02:31:17 2004 From: peter at engcorp.com (Peter Hansen) Date: Sat, 17 Apr 2004 02:31:17 -0400 Subject: AOP use cases In-Reply-To: References: <84fc4588.0404140106.3fa0c55@posting.google.com> <0pydnSB4WYuieuLdRVn-hQ@powergate.ca> <35qdnT4kNsX1kB3dRVn-gg@powergate.ca> Message-ID: Joe Mason wrote: > In article <35qdnT4kNsX1kB3dRVn-gg at powergate.ca>, Peter Hansen wrote: > >>The logging example is okay, yes, but another problem I have >>with it is that it's very development-oriented. It doesn't >>do anything directly for the user in terms of helping implement >>user functionality. Same goes for the contract aspect, which > > > It does if generating usage reports is a user requirement. Call logging > in a telephony app, for instance. Sorry, but that doesn't fly. That's a clearly separate function that should have a simple, single call somewhere in the application. The AOP logging example is talking about a "cross-cutting concern" (did I get that right?) where one wants to log *all method calls* in an object. It's a developer tool, not something that you would use for call logging. And even if it were, I'm still looking for real-world examples, not hypothetical ones. -Peter From rick.ratzel at magma-da.com Tue Apr 27 00:48:56 2004 From: rick.ratzel at magma-da.com (Rick L. Ratzel) Date: Tue, 27 Apr 2004 04:48:56 GMT Subject: Compiler References: Message-ID: <408DE6B3.3050104@magma-da.com> You can do this: python -c "import py_compile; py_compile.compile( \"foo.py\", \"foo.pyc\" )" ...which will create foo.pyc *only*, and will not compile any other .py files imported by foo.py. Steven wrote: > Hi folks, > > Just curious, is there a python compiler? > Or something that creates bytecode, like java? > > Regards, > > Steven From mcfletch at rogers.com Mon Apr 12 21:10:13 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Mon, 12 Apr 2004 21:10:13 -0400 Subject: Missing Console in Pythonwin In-Reply-To: References: Message-ID: <407B3DF5.1080204@rogers.com> You've likely got the window showing up in a position within the MDI window which is actually off-screen. Do a Window|Tile or Window|Cascade and it *should* show up in the MDI area again. HTH, Mike Cy Edmunds wrote: >Here's a weird one for you. Running Pythonwin on a Win2000 machine the >console suddenly stopped showing. I can turn it on and off and the checkmark >comes and goes but nothing is visible. I can do a print preview and see it >but that's it. > >I uninstalled and reinstalled (upgrading from 3.2.2 to 3.2.3) but still no >luck. Any ideas? > > _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From vincent at visualtrans.de Tue Apr 20 16:28:33 2004 From: vincent at visualtrans.de (vincent wehren) Date: Tue, 20 Apr 2004 22:28:33 +0200 Subject: python In-Reply-To: References: Message-ID: Limor Hevroni wrote: > Hi , > I consider using python as the programming language for an alpha testing > project. > I wonder whether any of you are using python in such a way, what is the best > development environment for python, is anyone used python for massive > project s with QA tendency ? is anyone used python with TestDirector ? At the company I work for we use Python among other things to drive automated QA test scenarios for the ERP software system (massive by nature) we develop. This involved quite some embedding/extending in C/C++ though. Our users can use Python for dialog/screen scripting, GUI customization. In addition it used as scripting language for our print and reporting engine. Vincent Wehren > > I would love to get answers on taht since I am running out if time, > development should start very soon. > The programming language I am considering is python and java, I would love > to get more info fro m people who use python in a working projects. > 10x. > limor hevrony > Spediant Systems Ltd. > > > > _____ > > > bst%3b&SG=&RAND=70373&partner=hotbar> Upgrade Your Email - Click here! > > > > > From fumanchu at amor.org Tue Apr 13 14:14:33 2004 From: fumanchu at amor.org (Robert Brewer) Date: Tue, 13 Apr 2004 11:14:33 -0700 Subject: Adding properties to objects Message-ID: John Roth wrote: > "Matthew Barnes" wrote in message > news:3a8e83d2.0404130906.2ea796e9 at posting.google.com... > > Is it possible to add properties to objects dynamically? > > > > I have an instance (x) of some new-style class (Foo), and I > would like > > to be able to do something like: > > > > >>> x = Foo() > > >>> x.myproperty = property(getsomething, setsomething, > delsomething); > > >>> x.myproperty # invokes getsomething > > >>> x.myproperty = 1 # invokes setsomething > > >>> del x.myproperty # invokes delsomething > > The property definition only lives in a class; you cannot add > a property to an instance by itself. Well, you can but it won't > be evaluated as a property by the default __getattribute__() > magic method. > > To make a property work on an instance basis you'd have > to have a specialty __getattribute__() magic method in the > class. That's left as an exercise for the reader. However, Matthew, you can dynamically add a property to the *class*, e.g.: class Property(object): def __get__(self, obj): pass def __set__(self, obj, value): pass Foo.setattr(propertyname, Property()) ...read Raymond Hettinger's How-To Guide for Descriptors to make your own property classes: http://users.rcn.com/python/download/Descriptor.htm Robert Brewer MIS Amor Ministries fumanchu at amor.org From __peter__ at web.de Wed Apr 28 03:01:20 2004 From: __peter__ at web.de (Peter Otten) Date: Wed, 28 Apr 2004 09:01:20 +0200 Subject: Is Perl *that* good? References: <108q51j4dscn7dc@corp.supernews.com> <87fzaqmm8t.fsf@strauser.com> <38ec68a6.0404262308.50029919@posting.google.com> Message-ID: Wallclimber wrote: > I have to agree with the original poster. My *only* complaint about > Python are not regex search, but regex search and replace operations. > Perl : s =~ s/(\w+)\s*=\s*(\d+)/$2 <= $1/g; > Python : regex.sub(s, "(\w+)\s*=\s*)\d+)", (lambda m: m.group(2)+" <= > "+m.group(1))) > > I didn't try this out so there might be some syntax problems in there, > but you get the idea. Is there a 'nicer' way to do this in python? Your example suggests that the Python equivalent for $1 is \1: >>> re.sub(r"(\w+)\s*=\s*(\d+)", r"\2 <= \1", "a=1 b = 3 c = d") '1 <= a 3 <= b c = d' Peter From peter at engcorp.com Tue Apr 20 11:33:56 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 20 Apr 2004 11:33:56 -0400 Subject: Editing/Writing Word-Files from Python In-Reply-To: References: Message-ID: Daniel Cloutier wrote: > is it possible to edit or write Word-files out of a Python-Program? Word uses a proprietary binary format, so you don't really have as an option the simple "open file, make some changes, write file" approach you might be picturing. On the other hand, this *is* Python, so you have alternatives: 1. Use ActiveX and control Word from Python. This is described well in Mark Hammond's book on Win32 programming with Python, web pages (use Google), and posts in the comp.lang.python archives. 2. Write HTML or RTF files, which are not proprietary binary formats. These can be edited in Python and then written back again. Not sure if there's an RTF library, but "it's just text". 3. Define in more detail what you are actually looking for ("edit" is ill-defined) including the context, and you'll probably get another three or four ways of doing it. -Peter From donn at u.washington.edu Wed Apr 14 20:04:12 2004 From: donn at u.washington.edu (Donn Cave) Date: Wed, 14 Apr 2004 17:04:12 -0700 Subject: Aspect Programming Module References: <84fc4588.0404140106.3fa0c55@posting.google.com> Message-ID: In article , Joe Mason wrote: > In article , Will Stuyvesant > wrote: > >> [Alexandre Fayolle, being a good employee] > >> You may want to try the logilab.aspects package, available at > >> http://www.logilab.org/projects/aspects/ > > > > I am afraid you are serious. > > > > AOP is *not needed* for Python programmers. Plain and simple. > > > > Don't understand? Try this: > > > > "AOP is a contrived way to get around the limitations of a statically > > typed language." > > Care to explain that? What I've seen of AOP seems like a very dynamic > design philosophy. Have you been through the materials referred to there? I didn't spend much time on it, but I didn't immediately recognize anything from the last time I heard about AOP, so I was led to wonder if it's a different notion going by the same name. The one I remember allows objects to inherit from containers, more or less. Your widget for example might inherit some drawing parameters from the window it belongs to. I'm probably getting it mostly wrong, but then I wasn't very excited about the idea. OOP is scary enough without compounding it this way. Donn Cave, donn at u.washington.edu From sdahlbacSPAMSUX at abo.fi Tue Apr 27 17:00:47 2004 From: sdahlbacSPAMSUX at abo.fi (Simon Dahlbacka) Date: Wed, 28 Apr 2004 00:00:47 +0300 Subject: wxpython + py2exe + innosetup Message-ID: <408eca0c$1@newsflash.abo.fi> I'm "exefying" an application that uses wxpython, some com to control excel and word and want to distribute this application. after creating the executable with py2exe, it still works fine (at least on my development machine), however, if I create an installer package with innosetup, install it and try to run it, I get a busy cursor for a split second and then.. nothing. no errors no traceback no nothing.. viewing dependencies does not reveal anything strange, and running the installed program in a debugger just tells that the application has exited with code 0. ..where do I go from here, I'm running out of ideas.. ? /Simon From tjreedy at udel.edu Mon Apr 12 10:37:11 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 12 Apr 2004 10:37:11 -0400 Subject: Documentation tool for python source code References: <930ba99a.0404120201.65203953@posting.google.com> Message-ID: "Sridhar R" wrote in message news:930ba99a.0404120201.65203953 at posting.google.com... > I am just wondering why epydoc isn't mentioned (or atleast in main > page) in the docsig section of www.python.org. Either a) it was considered and rejected or b) no one ever suggested or thought of it. You can eliminate the second possibility by making a suggestion at the email address on the side-bar. Suggesting a specific sentence to be added at a specific place would increase the probability to have an effect. tjr From pm_mon at yahoo.com Wed Apr 14 10:41:03 2004 From: pm_mon at yahoo.com (Paul Morrow) Date: 14 Apr 2004 07:41:03 -0700 Subject: Difficulty Finding Python Developers Message-ID: <65cbc3dd.0404140641.3501fde8@posting.google.com> We've worked hard to convince our company to migrate our core applications to Python, and now we're looking for a Python developer in Atlanta to handle a short-term (approx. 3 month) project. But our initial searches have been fairly unsuccessful. We haven't actually posted a job on Monster, but we have been talking with various headhunters in our area and they don't have many resumes that show Python experience. An so now, of course, mgt is wondering whether selecting Python was a mistake. As anyone had a similar experience? Suggestions? Thanks. From martin at v.loewis.de Sun Apr 4 15:11:06 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 04 Apr 2004 21:11:06 +0200 Subject: user authentication via /etc/passwd|/etc/shadow In-Reply-To: References: Message-ID: Marco Herrn wrote: > It seems that the pwd module can only access /etc/passwd. If the > passwords are stored in /etc/shadow, it doesn't work. Is there a way to > access shadow passwords, too? No, support for shadow modules is currently not available. You might want to check out http://python.org/sf/579435 to see whether it helps you. Comments in this SF patch submission on the usability of the specific patch are appreciated. Regards, Martin From till at score.is.tsukuba.ac.jp Wed Apr 21 11:39:23 2004 From: till at score.is.tsukuba.ac.jp (Till Plewe) Date: Thu, 22 Apr 2004 00:39:23 +0900 Subject: python shutting down sloooooooowly/tuning dictionaries Message-ID: <20040421153923.GA13234%till@score.is.tsukuba.ac.jp> Is there a way to speed up killing python from within a python program? Sometimes shutting down takes more than 10 times as much time as the actual running of the program. The programs are fairly simple (searching/organizing large boardgame databases) but use a lot of memory (1-6GB). The memory is mostly used for simple structures like trees or relations. Typically there will be a few large dictionaries and many small dictionaries/sets/arrays/lists. Since the entire database is too large I typically run the same program 10-100 times on smaller parts. The annoying bit is that the time for finishing one instance of a program before starting the next instance can take a lot of time. I have started using a shell script to check whether certain files have been written and then kill the program from the os to speed up everything. But this solution is way too ugly. There should be a better way, but I don't seem to be able to find one. A second question. Is it possible to control the resizing of dictionaries? It seems that resizing always doubles the size, but for dictionaries using more than half of the remaining memory than this is a problem. I would rather have a slightly too full dictionaries in main memory than have a sparse dictionary partially swapped out. I would like to be able to restrict the maximum growth of each resize operation to around 100MB or so. TIA. - Till From a at a.invalid Sun Apr 25 15:02:48 2004 From: a at a.invalid (Timo Virkkala) Date: Sun, 25 Apr 2004 19:02:48 GMT Subject: Python-list, Exotic sex is urgently necessary for you! In-Reply-To: References: Message-ID: Graham Fawcett wrote: > Timo Virkkala wrote in message news:... >>[disgusting content snipped] >> >>I've heard of sex with lots of kinds of animals, but Pythons? Wouldn't >>that be a) difficult b) VERY dangerous? > > It's no surprise you're not into snakes, Timo. Everyone knows that > Finns have fixations for flightless, fat waterfowl. LOL! Where does that come from? =) > BTW, I think that "Python-list, Exotic sex is urgently necessary for > you!" should be the slogan for the next PyCon conference. It would > definitely increase registrations. Hmm.. It might attract some people we would rather not have there. -- WT From hungjunglu at yahoo.com Sat Apr 10 11:20:25 2004 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 10 Apr 2004 08:20:25 -0700 Subject: Code blocks and top posting References: Message-ID: <8ef9bea6.0404100720.65ffd2c9@posting.google.com> Dave Benjamin wrote in message news:... > def answer(question): > return 'For pretty much the same reason top posting is.' > > if __name__ == '__main__': > question = 'Why is Python not having code blocks annoying?' > print answer(question) > > # HaHaOnlySerious def f(x): print x if __name__ == '__main__': f('Functions are annoying, by the same token?') Hung Jung From mark at prothon.org Mon Apr 26 15:20:59 2004 From: mark at prothon.org (Mark Hahn) Date: Mon, 26 Apr 2004 12:20:59 -0700 Subject: Why we will use obj$func() often References: <84Uhc.22278$dZ1.5087@fed1read04> <8AWhc.23114$dZ1.11070@fed1read04> <40883BFE.B381518A@alcyone.com> <27_hc.23801$dZ1.2716@fed1read04> <40887145.789A2FE8@alcyone.com> <7cki80hj976bia36lhf9er97v073o1pqvm@4ax.com> <1082783076.585831@yasure> <108qeg1lkm5hq8d@corp.supernews.com> Message-ID: "Michael Geary" wrote > It's not P*thonic, but JavaScript's solution for this keeps looking better > to me. When you want a local name, you create it with 'var'. When you refer > to a name, it always starts in the current scope and works its way up the > chain until it finds the name. Maybe there would be some way to make the "var" keyword totally optional. But then that still destroys the "no need to look around to to read the code" principle. From tjreedy at udel.edu Sun Apr 18 18:37:47 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 18 Apr 2004 18:37:47 -0400 Subject: imitating user input References: Message-ID: "Greg Grin" wrote in message news:ebd4b44c.0404181137.6ec29ba8 at posting.google.com... > I need to imitate keyboard strokes in an active window inside of > internet explorer, specifically I need my program to log on to a > chatroom without me actually sitting in front of my computer. Also, > once it has logged on to the program I need my program to "read" > (search for strings, etc.) the text that's entered by other users in > this "chatroom". The problem I have is actually logging in to the > chatroom since I have not found a way to duplicate keyboard strokes. For this problem, you do *not* need to imitate keystrokes (and mouseclicks) in the way that you would for interacting with a local interactive program. You *do* need to send and receive strings through internet sockets according to the Internet Relay Chat protocol (assuming that that is the protocol used by the site you are interested in. There are existing chat programs that can be scripted in Python. The Python-coded Twisted package also includes an IRC implementation. Some of the other internet packages may also. Look at http://twistedmatrix.com/users/jh/teud/Twisted/twisted.protocols.irc.html or google Python Internet Relay Chat protocol, as I did, for more. Terry J. Reedy From sean_berry at cox.net Mon Apr 5 15:56:46 2004 From: sean_berry at cox.net (Sean Berry) Date: Mon, 5 Apr 2004 14:56:46 -0500 Subject: FDF to PDF in Python? Message-ID: I am doing a project which will require me to take an FDF and convert it to a PDF after some information has been filled out. Is there anything in Python that can help me with this? I go the FDFToolkitforUnix from Adobe, but it is in Perl and I would much prefer Python. Has anyone out there done anything like this before? Any comments or suggestions are appreciated. From junkmail at solumslekt.org Sat Apr 3 04:22:47 2004 From: junkmail at solumslekt.org (Leif B. Kristensen) Date: Sat, 03 Apr 2004 11:22:47 +0200 Subject: String concatenation References: <7xisgi24fm.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > tmp = [x for x in res if x and x[0] != '-'] > return ', '.join(tmp) Substituting tmp with the real thing, it turns into a one-liner: return ', '.join([x for x in res if x and x[0] != '-']) Awesome :-) -- Leif Biberg Kristensen http://solumslekt.org/ Validare necesse est From greg at cosc.canterbury.ac.nz Fri Apr 2 02:32:35 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Fri, 02 Apr 2004 19:32:35 +1200 Subject: Prothon, metaclasses, Zope [Was: A 'Python like' language] References: <95aa1afa.0403272243.78d60724@posting.google.com> <95aa1afa.0403280258.41dc5cd9@posting.google.com> <8y8ac.68250$cx5.51296@fed1read04> Message-ID: <406D1713.60604@cosc.canterbury.ac.nz> Mark Hahn wrote: > You don't have to use the obj = proto() technique to create an object. The > following code is identical to saying subproto = topproto() except no > __init__() will be called: > > subproto = Object() > subproto.set_proto(topproto) # switch prototype on the fly > > Does this give you the missing piece you need Yes, it does, I think. Creating the prototype this way is very similar to what the Python class statement does. Greg From steve at ninereeds.fsnet.co.uk Thu Apr 8 18:38:46 2004 From: steve at ninereeds.fsnet.co.uk (Stephen Horne) Date: Thu, 08 Apr 2004 23:38:46 +0100 Subject: OFF-TOPIC:: Why Lisp is not my favorite programming language References: <165b3efa.0403030443.4d591f04@posting.google.com> <40460dd5$0$5916$7a628cd7@news.club-internet.fr> <6in670lrldbjkuujle68a526293j57a7mn@4ax.com> <95aa1afa.0404070205.94b32e4@posting.google.com> Message-ID: On 08 Apr 2004 10:28:19 +0200, Jacek Generowicz wrote: >Stephen Horne writes: > >> and given the kind of metaprogramming possible in Lisp (which for >> compilation to work, must imply just-in-time compilation at run >> time) > >Why ? I am led to believe that if you want to write any syntax in Lisp, you can - you just need a library that understands it. So if you feel like writing... (a := b + c) You just write the library that understands infix operators, precedence etc. But the Lisp compiler itself doesn't understand that code. For it to be handled, it must be translated (by the library) to Lisp code that the compiler does understand, and that code must then be compiled. Otherwise, the metaprogramming library is just an interpreter (barely any different than writing "(+ 1 2)" in quotes and having a Lisp interpreter written as a Python library, as really the only additional thing it handles is tokenising), and your code implemented using metaprogramming is not compiled. That would mean that what you can write using metaprogramming is second class compared with what is written using the standard Lisp facilities, which is a direct contradiction of what I have been told right here in this group. Or at least that is the impression I have - on the record of this thread so far, I am confident that I will be proven wrong. -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From dkuhlman at rexx.com Wed Apr 21 17:54:03 2004 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Wed, 21 Apr 2004 14:54:03 -0700 Subject: saving interpreter source? References: Message-ID: Peter Hansen wrote: > Garett wrote: > >> Hello, I would like to be able to save source typed into the >> interpreter to a file. Kind of like marshal, but I would like to >> have the file contain the source so I can edit it later. >> Something like inspect.getsource() but for source typed into the >> interpreter, not imported from a module. Is this possible? Any >> ideas are greatly appreciated. -Garett > > Last time I used it, Chris Gonnerman's readline replacement kept a > history by default: > > http://newcenturycomputers.net/projects/readline.html Also, take a look at the following. It tells you how to configure your interactive sessions so that both (1) interactive history will be saved to a file and (2) that history will be available in subsequent interactive sessions. Dave -- http://www.rexx.com/~dkuhlman From imbosol at aerojockey.invalid Tue Apr 27 20:09:08 2004 From: imbosol at aerojockey.invalid (Carl Banks) Date: Wed, 28 Apr 2004 00:09:08 GMT Subject: Is Perl *that* good? References: <108q51j4dscn7dc@corp.supernews.com> <87fzaqmm8t.fsf@strauser.com> <38ec68a6.0404262308.50029919@posting.google.com> Message-ID: Roy Smith wrote: > > > Carl Banks wrote: >> Hmm. The reason this hasn't been done is that it makes the match >> method non-reentrant. For example, suppose you call some functions in >> between the matching and use of the matched object, like this: >> >> if myregex.match(line): >> xyz = (subprocess(line[myregex.lastm.end():]) >> + myregex.lastm.group(1)) >> >> And suppose subprocess goes on to use the same regexp. By the time >> subprocess returns, myregex.lastm could have been overwritten. This >> is not a far-fetched example at all; one could easily encounter this >> problem when writing, say, a recursive descent parser. > > I don't see that this is any worse than any other stateful object. It's worse because, unlike most objects, regexp objects are usually global (at least they are when I use them). Moreover, the library encourages us to make regexp objects global by exposing the regexp compiler. So even if you personally use local regexps (and accept the resulting performance hit), many will declare them global. In other words, myregexp.match is essentially a global function, so it shouldn't have state. -- CARL BANKS http://www.aerojockey.com/software "If you believe in yourself, drink your school, stay on drugs, and don't do milk, you can get work." -- Parody of Mr. T from a Robert Smigel Cartoon From peter at engcorp.com Thu Apr 15 10:13:23 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 15 Apr 2004 10:13:23 -0400 Subject: Difficulty Finding Python Developers In-Reply-To: References: <65cbc3dd.0404140641.3501fde8@posting.google.com> <65cbc3dd.0404141018.36d9d4ce@posting.google.com> Message-ID: <4I2dnfDLZq4eBePdRVn-uw@powergate.ca> Ville Vainio wrote: > Offering some comebacks in advance... >>>>>>"Peter" == Peter Hansen writes: > Peter> And here I would ask, "Why do you say that? If there are > Peter> so few of them around, how could anyone know whether > Peter> they're better or worse? And wouldn't the best programmers > > I guess the braindeadness of perl can be argued as an indication of > the quality of programmers - if the Perl people are unable to see how > much the language stinks, they might be lacking in other areas of > programming also. > > Java OTOH is the lowest common denominator, pretty much everyone knows > it, which drags the average quality down. These are comments that Python developers understand. Try explaining them to a Perl or Java developer, or more importantly to the OP's management, and see how far it gets you. :-) (Also hope that the management type you're talking to wasn't/isn't a Java developer as well! :-) -Peter From mlh at furu.idi.ntnu.no Fri Apr 23 11:43:20 2004 From: mlh at furu.idi.ntnu.no (Magnus Lie Hetland) Date: Fri, 23 Apr 2004 15:43:20 +0000 (UTC) Subject: Regexp optimization question References: Message-ID: In article , Martin v. L?wis wrote: >Magnus Lie Hetland wrote: >> I've tried to speed this up by using the same trick as SPARK, putting >> all the regexps into a single or-group in a new regexp. That helped a >> *lot* -- but now I have to find out which one of them matched at a >> certain location. > >Are you using the .lastindex attribute of match objects yet? Dang! I thought I had read the docs ;) Seems very useful. I actually need to know all the matches, because which one gets selected depends on the current priorities (ordering) in the parser, and cannot be fixed for the scanner. (I could put the patterns in the or-group in reverse prioritized order, but that would have to be fixed...) Thanks for the tip, anyway. >Martin -- Magnus Lie Hetland "Wake up!" - Rage Against The Machine http://hetland.org "Shut up!" - Linkin Park From peter at engcorp.com Tue Apr 20 10:22:41 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 20 Apr 2004 10:22:41 -0400 Subject: CamelCase versus wide_names (Prothon) In-Reply-To: <6ee58e07.0404192141.2229efd6@posting.google.com> References: <6ee58e07.0404192141.2229efd6@posting.google.com> Message-ID: Lothar Scholz wrote: > After writing a few hundert thousands lines of code in Eiffel and a > few ten thousands lines in Java i must say that lowercase wide_names > are much much better to read. Someone else already mentioned this > problem: > > smtp_message <-> SMTPMessage <-> SmtpMessage What about SMTP_message? If you don't deal with that issue, you will doubtless get wide-namers who want to write it that way instead of smtp_message. If, on the other hand, you have a coding standard which insists that acronyms be lower-cased, then the supposed problem you mention above goes away, because whether you use wide_names or mixedCase, you are consistently (not) capitalizing acronyms. In other words, if it's a problem, it's a problem with wide_names as well.... -Peter From johnc_tan at hotmail.com Fri Apr 16 20:13:11 2004 From: johnc_tan at hotmail.com (JT) Date: 16 Apr 2004 17:13:11 -0700 Subject: Initializing Python in Optimized mode from C++ References: Message-ID: "Fredrik Lundh" wrote in message > here's one way to do it: > > putenv("PYTHONOPTIMIZE=yes"); > ... initialize interpreter as usual ... > > Thanks for response! I'll try this solution. Does anyone know of any way to do this directly through the Python C/C++ API, such as by modifying a variable representing the state, interpreter or compiler, or by calling a specific method? From cmg at dok.org Wed Apr 14 10:32:34 2004 From: cmg at dok.org (Chris Green) Date: Wed, 14 Apr 2004 10:32:34 -0400 Subject: mcmillan installer References: Message-ID: "Gianluca Trombetta" writes: > thank you Larry, > > but I need to compile for linux platform and py2exe only work on windows :-( > http://starship.python.net/crew/atuining/cx_Freeze/ I've had pretty good luck getting this to work under Linux though haven't gone into production with it. It's a pretty confusing to get started but it says it works on Linux & Windows. I've only tried Linux but after a lot of hair pulling I was able to get 4suite + wxPython + other modules all into a single app directory. The hardest part there was the encodings directory of the basic python where there are complicated things going on with __import__ and it doesn't figure them out. -- Chris Green Chicken's thinkin' From vineet at eswap.com Tue Apr 6 00:43:47 2004 From: vineet at eswap.com (Vineet Jain) Date: Tue, 6 Apr 2004 00:43:47 -0400 Subject: int('2.1') does not work while int(float('2.1')) does In-Reply-To: <40722E98.253B5FF2@alcyone.com> Message-ID: Just an interesting thing to note: >>> a = int(float(0.99999999999999999)) >>> a 1 >>> a = int(float(0.9999999999999999)) >>> a 0 I'm still not sure i follow why "int(aString) means make an int out of this string" cannot use the same rules and behave in the same way as it encouters a float when it encouters a float string. VJ -----Original Message----- From: python-list-bounces+vineet=eswap.com at python.org [mailto:python-list-bounces+vineet=eswap.com at python.org]On Behalf Of Erik Max Francis Sent: Monday, April 05, 2004 11:14 PM To: python-list at python.org Subject: Re: int('2.1') does not work while int(float('2.1')) does Joe Mason wrote: > Why can it make this guess for "int(2.1)", then? It's got a rule for > converting floats to ints - why not use it here? Because int(aFloat) means round toward zero. int(aString) means make an int out of this string. -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis \__/ Convictions are more dangerous enemies of truth than lies. -- Friedrich Nietzsche -- http://mail.python.org/mailman/listinfo/python-list From NAVMSE-PORSCHE at hjpfaff.com Wed Apr 14 19:15:55 2004 From: NAVMSE-PORSCHE at hjpfaff.com (NAVMSE-PORSCHE) Date: Wed, 14 Apr 2004 19:15:55 -0400 Subject: Norton AntiVirus detected and quarantined a virus in a message you sent. Message-ID: Recipient of the infected attachment: PORSCHE, First Storage Group\Mailbox Store (PORSCHE), Jamie Taylor/Inbox Subject of the message: Hi One or more attachments were quarantined. Attachment patch3425.zip was Quarantined for the following reasons: Virus W32.Netsky.P at mm was found. Virus W32.Netsky.P at mm was found in data.rtf .scr. From ryanlowe0 at msn.com Wed Apr 28 18:33:44 2004 From: ryanlowe0 at msn.com (Ryan Lowe) Date: Wed, 28 Apr 2004 22:33:44 GMT Subject: parallel for loops References: <0SAjc.12421$Gd3.3093654@news4.srv.hcvlny.cv.net> Message-ID: > >>>> a, b = [1,2,3], [4,5,6] # a = [1,2,3], b = [4,5,6] > >>>> for a, b in zip([1,2,3], [4,5,6]): print a, b > > > > instead of: > >>>> for a, b in [1,2,3], [4,5,6]: print a, b # illegal > > > > im sure there is a good reason why the former was chosen, and i know its way > > too late to switch, but i cant think of many examples of when you would use > > parallel iteration *without* zip. not even dictionaries since you have to > > dates = [(2004, 4, 27), (2004, 2, 9), (2003, 11, 14)] > for year, month, day in dates: > do_something_with(year) > and_with(month, date) i assume you meant day instead of date on the last line... > Also, it's more consistent: in each iteration, an element of the > list being iterated over is assigned to the loop variable; or if > it's multiple variables, automatic unpacking happens just like it > would if a value were assigned to multiple variables in an > assignment statement. i had thought of something like that, say points: for x, y, z in points: but when i really stopped to think about it, it is not more consistent since (x, y, z) is not a direct member of the points list; its a decomposition of a single point. likewise, (year, month, day) is a single date. therefore you should have to say: for point in points: x, y, z = point ... its one more line, but its more explicit. or just use a point class and access point.x, point.y, and point.z. i guess it comes down to whether breaking up a single list of tuples is the more common use of parallel iteration vars, or iterating over multiple iterators with a single var each. i think its the latter, but maybe thats just the type of problems ive encountered that dealt with parallel iteration... as another example, the old problem of including the counter var, only /satisfactorily/ solved by enumerate(). this is a case where i have to stop and remember which comes first the counter or the contents. of course, its still a lot better than the hideous old solution: for i, v in zip(range(len(list), list): removing the zip helps a bit (using my logic), and its clear which part goes to which which var: for i, v in range(len(list), list: then if you had a function that returned the indexes of a list, its very clear and only a couple of characters longer than enumerate, without the order problem: for i, v in indexes(list), list: anyway its just something to think about, or maybe waste time thinking about... ;) From no_spam at terastat.com Tue Apr 27 14:17:46 2004 From: no_spam at terastat.com (bap) Date: Tue, 27 Apr 2004 18:17:46 GMT Subject: Problem with PY2EXE and VPython References: <7mar8057sjdqh5h54ojb4et2bd3p10teug@4ax.com> Message-ID: Art Thanks for the pointer-- I did download and install your example. I did two tests. One is on a perfectly clean machine (a win2k system on Virtual_PC -- only operating system is on system, no Office or any Python distributions). The second machine is a Win2k system that has VB, Office, Python (but not Vpython) and much else. On the clean machine -- I get an error message about MSVCP60.DLL not being found. On the second machine it works. Both systems give me the WOW64Process error when TOH is compiled using the latest (0.5) PY2EXE, Python 2.3.2, and VPython 2003-10-05. BTW the new PY2EXE appears to be quite a bit simpler to use than the old. Bruce bapeters at terastat.com "Arthur" wrote in message news:7mar8057sjdqh5h54ojb4et2bd3p10teug at 4ax.com... > On Mon, 26 Apr 2004 23:29:28 GMT, "bap" wrote: > > >When I try to run a program on a clean machine using the VPython extensions > >after compiling with PY2EXE I get the following error message: "The > >procedure entry point IsWow64Process could not be located in the dynamic > >link library KERNEL32.dll" . The compiled version runs fine on the original > >machine (win NT OS) but gives this error message on a machine without > >VPython installed (Win 2K OS). Is this anything that can be fixed with > >appropriate parameters in PY2EXE or does it require that VPython be tweaked? > >Any help appriciated. > > At: > > http://www.dstoys.com/content/education/index_html/Visual%20Arts/Interactive > > I have the VPython Tower of Hanoi demo as a Windows executable. > > It is an older version of VPython and of Python. > > I would be curious to know if there are problems running this on your > machine without VPython installed. > > If it runs OK, we can see from there what I might have done > differently from you in building the executable. > > Art From tdelaney at avaya.com Thu Apr 29 21:24:45 2004 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Fri, 30 Apr 2004 11:24:45 +1000 Subject: outline-style sorting algorithm Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE016BCD44@au3010avexu1.global.avaya.com> Some more interesting results, which strongly demonstrate the performance differences between DSU and passing a comparison function when the comparison function becomes even a little bit complex. I've reduced the list size to make the time taken manageable. def identity (x): return x def double (x): return x * 2 def square (x): return x * x a = range(100000); a.reverse() b = randseq(1, 100000, 100000, 'repeat') timer(funcsort, a, identity, 'dsu') timer(funcsort, a, identity, 'pass') timer(funcsort, a, double, 'dsu') timer(funcsort, a, double, 'pass') timer(funcsort, a, square, 'dsu') timer(funcsort, a, square, 'pass') print timer(funcsort, b, identity, 'dsu') timer(funcsort, b, identity, 'pass') timer(funcsort, b, double, 'dsu') timer(funcsort, b, double, 'pass') timer(funcsort, b, square, 'dsu') timer(funcsort, b, square, 'pass') ---------- Run ---------- cpu: 0.242, total: 0.235 # timer(funcsort, a, identity, 'dsu') cpu: 0.137, total: 0.141 # timer(funcsort, a, identity, 'pass') cpu: 0.259, total: 0.266 # timer(funcsort, a, double, 'dsu') cpu: 0.162, total: 0.156 # timer(funcsort, a, double, 'pass') cpu: 1.299, total: 1.296 # timer(funcsort, a, square, 'dsu') cpu: 2.233, total: 2.235 # timer(funcsort, a, square, 'pass') cpu: 0.654, total: 0.657 # timer(funcsort, b, identity, 'dsu') cpu: 2.249, total: 2.250 # timer(funcsort, b, identity, 'pass') cpu: 0.761, total: 0.765 # timer(funcsort, b, double, 'dsu') cpu: 2.502, total: 2.500 # timer(funcsort, b, double, 'pass') cpu: 1.868, total: 1.875 # timer(funcsort, b, square, 'dsu') cpu: 33.227, total: 33.234 # timer(funcsort, b, square, 'pass') Output completed (46 sec consumed) - Normal Termination As you can clearly see, an apparently simple comparison function (squaring) suffers greatly when passing a comparison function to sort. In actual fact, this is *not* a simple comparison function, because with the size of the numbers involved it suffers overflow and starts using longs instead of ints. Since there are so many comparisons performed (due to randomness in the source list) those long multiplications need to be performed many times. identity: 2.250 - 0.141 = 2.109 double: 2.500 - 0.156 = 2.344 square: 33.235 - 2.235 = 31.000 The difference between partially-sorted source and random source OTOH is purely the sorting time (taking into account that it takes longer to compare longs than ints) - there's essentially a constant-factor overhead. identity: 0.657 - 0.235 = 0.422 double: 0.765 - 0.266 = 0.499 square: 1.875 - 1.296 = 0.579 This is why DSU is usually preferred to passing a comparison function. Tim Delaney From PPNTWIMBXFFC at spammotel.com Wed Apr 28 10:15:56 2004 From: PPNTWIMBXFFC at spammotel.com (Marco Aschwanden) Date: Wed, 28 Apr 2004 16:15:56 +0200 Subject: Path ... where is my application's home dir? References: Message-ID: On Wed, 28 Apr 2004 14:44:30 +0100, Tim Golden wrote: >> I want to store a file in the application directory. What is >> the easiest >> way to figure out, where my application is situated? >> >> sys.argv[0] does not work for my purposes... do you have any >> other ideas. > > a) Why doesn't argv[0] work? Because I am stupid and tested always the old/unchanged version where the sys.argv had no impact. 8o(((( Thanks, your a) hint - it was the kick that I needed! The look over my shoulder! But I still wonder: Suppose sys.argv[0] wouldn't work. What would be the easiest way to find out where an application lies? Ideas: 1. going through sys.path and checking whether the application file is in a dir 2. or is there a module method, that tells you where it is stored? Thanks for "help", Marco From fma at doe.carleton.ca Thu Apr 1 01:29:31 2004 From: fma at doe.carleton.ca (Fred Ma) Date: 1 Apr 2004 06:29:31 GMT Subject: Python from the command line (was: Choosing Perl/Python for my particular niche) References: <40652B0D.7C313F77@doe.carleton.ca> <406532F7.D56DC671@doe.carleton.ca> <406934a9$0$7564$afc38c87@news.easynet.co.uk> <4069F1FD.601C9079@doe.carleton.ca> <106n8kj2t5n7m11@corp.supernews.com> Message-ID: <406BB6C4.7F3ADD4@doe.carleton.ca> Cameron Laird wrote: > > In article <4069F1FD.601C9079 at doe.carleton.ca>, > Fred Ma wrote: > . > . > . > >Perl/sed. About invoking Perl as part of a simple command in a > >pipeline, I mean that one doesn't even have to write a script for it, > >similar to sed > > > > Command1 | sed -e Expression1 -e Expression2 ... | Command_N > > > >This might also be possible in Python, in which case so much the better. > >I'll find out (or someone might answer in a follow-up post). Thanks > . > . > . > # python -c "print 3 + 5" > 8 I was 99.99% sure that it was possible (heck, if tcsh and bash can do it, python surely can). It's a little easier to squish it into a simple command in a pipeline for a terse/compact "language" e.g. sed. On a side-note, I've abused sed before by embedded sed scripts into bash scripts without actually writing the sed script: Bash_Command | \ sed \ -e 'Expression1' \ -e 'Expression2' \ -e 'Conditional1 {' \ -e 'Body_of_Conditional1' \ -e 'More_of_Body' \ -e '}' \ | More_Bash_Commands Not that I want to do everything in sed, of course. And for perl/python, there is probably not much reason to mix commands with bash, since (unlike sed) they have the shell functionality. I've put in a request to my sysadmin to install python. The way to get hooked on it is to start small, with mundane tasks (same as with any new shell, I suppose). If it doesn't get installed due to lack of priority, I can always get it bundled with my next cygwin update. Cygwin is an absolute blessing. Everything comes prebuilt (lots of stuff) and you have superuser priveleges, as well as simultaneous access to Windows. Just as long as your HDD isn't FAT (that prevents chmod from working). But I digress..... Fred -- Fred Ma Dept. of Electronics, Carleton University 1125 Colonel By Drive, Ottawa, Ontario Canada, K1S 5B6 From hunnebal at yahoo.com Mon Apr 26 03:08:13 2004 From: hunnebal at yahoo.com (Hunn E. Balsiche) Date: Mon, 26 Apr 2004 03:08:13 -0400 Subject: How's ruby compare to it older brother python Message-ID: in term of its OO features, syntax consistencies, ease of use, and their development progress. I have not use python but heard about it quite often; and ruby, is it mature enough to be use for developing serious application, e.g web application as it has not many features in it yet. I've given up on Perl for its ugly syntax and it is not the easiest language to learn. How about PHP? Thanks From danb_83 at yahoo.com Sun Apr 25 20:12:21 2004 From: danb_83 at yahoo.com (Dan Bishop) Date: 25 Apr 2004 17:12:21 -0700 Subject: Andreas' practical language comparison References: Message-ID: Andreas Koch wrote in message news:... > Hi all, > > i started a little "practical language comparison" - practical > in the sense that i compare how actual distributions and versions > and their libraries (not abstract language specifications) solve small > test cases like the 8 queens problem. > > Currently there are contributions for 17 different languages, and > none for Phyton (and Lisp. And Forth. And many others ). > If someone is interested in contributing a few implementations, > please have a look at: > > http://www.kochandreas.com/home/language/lang.htm > > and mail me your code snippets (or critics) or post them here. # ************ Sort 2 ************ import sys lines = file(sys.argv[1]).readlines() lines.sort() file('sorted.txt', 'w').writelines(lines) # ************ Type "file" ************ import sys for line in file(sys.argv[1]): print line From Chris.Barker at noaa.gov Thu Apr 29 18:39:23 2004 From: Chris.Barker at noaa.gov (Christopher Barker) Date: Thu, 29 Apr 2004 15:39:23 -0700 Subject: Arachno Python IDE In-Reply-To: References: Message-ID: Bror Johansson wrote: > Follow up to myself. > I just noticed that the trial version was for Ruby only. My guess is that's a bug in their website...which clearly should be written in PYthon, rather than PHP. -Chris -- Christopher Barker, Ph.D. Oceanographer NOAA/OR&R/HAZMAT (206) 526-6959 voice 7600 Sand Point Way NE (206) 526-6329 fax Seattle, WA 98115 (206) 526-6317 main reception Chris.Barker at noaa.gov From gatti at dsdata.it Fri Apr 2 07:14:21 2004 From: gatti at dsdata.it (Lorenzo Gatti) Date: 2 Apr 2004 04:14:21 -0800 Subject: GTK2 Windows installation Was: Re: GUI Frameworks in Python? References: <8089854e.0403300518.3a180414@posting.google.com> <20040330143520.31dccb5e.HughMacdonald@brokenpipefilms.com> Message-ID: <5b3fd64f.0404020414.e036fe6@posting.google.com> J?rgen Cederberg wrote in message news:... > > Hi, > > i downloaded and installed the GTK runtime environment v. 2.2.4-2 and > PyGTK 2.2.0 for Python 2.3. The installation went fine and I added the > path to GTK/lib and bin. I run a helloworld program, but unfortunely I > get this error message which I quite puzzled about (translated from danish) > > (helloworld.py:3308): Gtk-WARNING **: Could not find the theme engine in > module_path: 'wimp' > > Does anyone have clue what to do? > > Regards > Jorgen Cederberg I had the same harmless warning and I moved libwimp.dll to somewhere\GTK\2.0\lib\gtk-2.0\2.2.0\engines (a new directory, sister of "loaders" and "immodules"). Lorenzo Gatti From ville at spammers.com Tue Apr 27 04:31:37 2004 From: ville at spammers.com (Ville Vainio) Date: 27 Apr 2004 11:31:37 +0300 Subject: Is Perl *that* good? References: <108q51j4dscn7dc@corp.supernews.com> <87fzaqmm8t.fsf@strauser.com> <38ec68a6.0404262308.50029919@posting.google.com> Message-ID: >>>>> "Asun" == Asun Friere writes: Asun> Wouldn't you need to import the re module and compile the Asun> pattern first? (And wouldn't you use 'search' rather than Asun> 'match'?) And I rarely compile regexps, just pass the string to the re functions. Asun> Regex is much more 'immediate' in Perl. Probably the only I mostly use re.findall and re.sub, which are every bit as immediate as the perl counterparts. Match objects provide flexibility - if you want immediacy, just define a utility function that removes the flexibility and provides the convenience. Asun> time I would reach for Perl rather than for python is when I Asun> knew a task involved a lot of regex (and no object Asun> orientation). If the task involves a lot of anything it can often be factored out to some functions, and Python wins again. Perl5 is one of those languages with no reason to exist anymore. -- Ville Vainio http://tinyurl.com/2prnb From peter at engcorp.com Wed Apr 14 14:47:32 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 14 Apr 2004 14:47:32 -0400 Subject: Pygame In-Reply-To: References: Message-ID: Alexander R?dseth wrote: > Well, if it's not due to the licensing, and not because it's unusual to > include anything similar, > when speaking in terms of "batteries included"; It most definitely is unusual to include *anything* (my emphasis) similar, or you would find Python already at 150MB and growing rapidly as I suggested before. I ask again what you think should be the criteria for including something in the standard distribution. Clearly, whatever you think it should be, it's at odds with what the current maintainers consider appropriate. Perhaps if you can come up with some guidelines which would include Pygame but not 130MB of other useful and interesting packages, we'll have a better way of deciding what to put in in future releases. -Peter From j.dot.willeke at verizon.dot.net Fri Apr 2 10:05:42 2004 From: j.dot.willeke at verizon.dot.net (Jon Willeke) Date: Fri, 02 Apr 2004 15:05:42 GMT Subject: An attempt at guessing the encoding of a (non-unicode) string In-Reply-To: References: Message-ID: Christos TZOTZIOY Georgiou wrote: > This is a subject that comes up fairly often. Last night, I had the > following idea, for which I would like feedback from you. > > This could be implemented as a function in codecs.py (let's call it > "wild_guess"), that is based on some pre-calculated data. These > pre-calculated data would be produced as follows: ... > What do you think? I can't test whether that would work unless I have > 'representative' texts for various encodings. Please feel free to help > or bash :) The representative text would, in some circles, be called a training corpus. See the Natural Language Toolkit for some modules that may help you prototype this approach: In particular, check out the probability tutorial. From enrique.palomo at xgs-spain.com Fri Apr 23 03:49:44 2004 From: enrique.palomo at xgs-spain.com (=?utf-8?Q?Enrique_Palomo_Jim=C3=A9nez?=) Date: Fri, 23 Apr 2004 09:49:44 +0200 Subject: Help: Fatal Python error: deletion of interned string failed Message-ID: Hello all I'm running python in as400 and using the db2 module i find the subject's error. commenting one "append" the error desapears ... At least, is friday... Enrique From peter at engcorp.com Fri Apr 16 18:31:50 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 16 Apr 2004 18:31:50 -0400 Subject: Difficulty Finding Python Developers In-Reply-To: References: <65cbc3dd.0404140641.3501fde8@posting.google.com><5d83790c.0404150701.605782a7@posting.google.com><7xpta8hqe7.fsf@ruckus.brouhaha.com><7xsmf4kbac.fsf@ruckus.brouhaha.com><7x7jwg7ipn.fsf@ruckus.brouhaha.com> Message-ID: Paul Morrow wrote: >> And in case my point was unclear: the OP asked about something >> which seemed like a very simple experimental project to get their >> feet wet with Python. > > It is somewhat of an experiment, but the application is to be used in an > actual production system. The experiment is to see how viable Python > outsourcing is in our area, in the event the inhouse developers get > swamped and we need help fast... Heh heh! :-) That pretty much eliminates the approach some of us suggested to have an in-house developer pick up Python quickly to do the job. (It doesn't, I think, change the fact that you shouldn't necessarily be insisting on hiring a "Python programmer", but clearly you will need to mention that the work will involve programming in Python...) -Peter From claird at lairds.com Mon Apr 5 07:27:08 2004 From: claird at lairds.com (Cameron Laird) Date: Mon, 05 Apr 2004 11:27:08 -0000 Subject: Newbie need help References: Message-ID: <1072gkc3e3oif19@corp.supernews.com> In article , Tony Ha wrote: >Question from a newbie. > >In the interactive Python shell. > >1. How do I find out where I am in the file system under WindowXP? > > I try os.curdir, which only give '.' back, I would like a full path >like the Unix 'pwd' give. . . . print os.getcwd() -- Cameron Laird Business: http://www.Phaseit.net From jepler at unpythonic.net Thu Apr 22 21:33:26 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Thu, 22 Apr 2004 20:33:26 -0500 Subject: equivalent to Tcl 'after' command? In-Reply-To: References: Message-ID: <20040423013326.GB2311@unpythonic.net> > On Thu, 22 Apr 2004 17:42:37 GMT, Mark Harrison > wrote: > > I'm writing some event-driven programs, and I would like > > to do the equivalent of the Tcl 'after' command, e.g.: > > > > after 1000 {puts "one second has elapsed"} > > > > 1. What's the most canonical way of doing this? > On Thu, Apr 22, 2004 at 11:52:57PM +0100, Alan Gauld wrote: > I suspect its to start a thread that in turn starts with > a sleep command. Not very pretty but approximately the same. But "doing something in about X ms in a thread" and "doing something in about X ms from the event loop" are different: the latter basically frees you from worrying about locking, race conditions, and the rest, because you know it can't run concurrently with arbitrary other code. Jeff From oest at soetu.eu Wed Apr 7 22:08:53 2004 From: oest at soetu.eu (Carlo v. Dango) Date: Thu, 08 Apr 2004 04:08:53 +0200 Subject: why is python better than eg. smalltalk?? no one has any solid arguments! you should all go to church with all that religious talk! References: <20031028061245.12451.00000133@mb-m01.aol.com> Message-ID: On Thu, 30 Oct 2003 13:08:02 +0100, Andy Jewell wrote: OK, I'm on the python wagon as well, but I do not really se much improvement over JAVA... especially when it comes to maintaining and reusing code (e.g. API's)... here the types are really helpful. So just saying typing is bad, is to me, plain wrong. I guess its like choosing a language for the problem... if your code is simple and script-like, you probably do not get nothing but trouble from the types, but maintaining a 1 billion line of code program, you probably feel less agony by the restrictions (and promises!) set up by the types. In a sense types are like contracts (DBC) and we do agree on those as being a good thing, right??! Also, I see all this advocacy of python which to me seems more like religion.. there is no concretenes in it, and I completely fail to see how python beats any of the other dynamically typed languages such as smalltalk or self... what is it with you guys? :) however, when playing and trying to bend a language a dynamically typed language is way more fun to play with than a typed one! But the integrated lexer and parser in smalltalk, makes one wonder why python should be a choice here? Maybe what people like is all the extra software which has been and is being written for python, which you do not have in smalltalk? or what is it? -carlo > Kef, > > Funny, a lot of people make testemonials about Python, just like you > have... > > (I'm sure people also make testimonials about any given language, too). > > I think the difference is the way people tend to come to Python: search > the > archives and you'll see hundreds of instances of 'seekers' having 'come > home'. > > Python seems to engender an almost 'born again programmer' style > response from > most who bother to try to master it. Most say that when they eventually > /do/ > take the step, the transition is surprisingly easy - Guido's claim in the > tutorial that you can learn most of what you need to know to become > productive in an afternoon is not too far from the truth. > > When it comes to the finer, weirder, and (dare I say) darker secrets of > Python, c.l.py is the place to learn about them. You can learn > everything > from 'just for fun' tricks that you'd never dream of incorporating into a > real program to powerful magic that makes your program run n-times > faster, > without losing readability. > > Still, the guys here are generally quite firmly grounded on reality; > there are > certain scenarios where you just *wouldn't* employ Python, and the peeps > here > in c.l.py will freely admit that. For some, the obvious answer is to > write > the appropriate parts in, say, C and use Python as a 'wrapper' around > that, > saving the bits that Python is good at for Python and the bits that C is > good > at for C. Others would advocate simply using the *right* language in the > first place. I think a realistic motto would be "one size *does not* fit > all". > > Still, given the 'performance limitations' of python, I've not really > found it > to be too deficient at the things I want it to do. In fact, often, due > to > its exceptionally well optimised high-level data types, I'm often > surprised > at exactly *how* fast it is ;-) > > For my part, I came in from a firmly Wirthian perspective: Pascal; > Modula-2 > and Oberon. Aside from the Pascal family of languages, I also know > LOADS of > dialects of BASIC; 4GL's like dBase; Assembly (6502, 8080, Z80, 8086, > 68000); > DOS/Windows batch language; and a little FORTH. > > With Oberon, I though I had found the Grail, but was frustrated by > poor/incomplete implementations of it, or with the licensing terms of the > better implementations. It was at the point that I ditched POW Oberon, > that > I made the transition to Python. I, too, was amazed, and I continue to > be, > too. That was about 3 years ago... > > Python does generate certain problems of its own, though: I recently had > to > learn RPG III and IV for work, and going 'back to the dark ages' was > incredibly frustrating and just felt 'bad'. I guess you get spoiled by > the > beauty of Python... and by the facilities, libraries and support > infrastructure (i.e. c.l.py). > > Python does seem to magnify the flaws in other languages: everything else > seems (to me at least) to be second-best now. > > Slither On! > > -andyj > > > > > > -- Using M2, Opera's revolutionary e-mail client: http://www.opera.com/m2/ From python at rcn.com Fri Apr 2 03:42:37 2004 From: python at rcn.com (Raymond Hettinger) Date: 2 Apr 2004 00:42:37 -0800 Subject: splitting one dictionary into two Message-ID: <5d83790c.0404020042.41f4a576@posting.google.com> [jsaul] > I have to split a dict into two dicts. Depending on their values, > the items shall remain in the original dict or be moved to another > one and at the same time be removed from the original dict. > > OK, this is how I do it right now: > > dict1 = { "a":1, "b":3, "c":5, "d":4, "e":2 } > dict2 = {} > klist = [] > > for key in dict1: > if dict1[key] > 3: # some criterion > dict2[key] = dict1[key] > klist.append(key) > > for key in klist: > del dict1[key] > > print dict1 > print dict2 > > That means that I store the keys of the items to be removed from > the original dict in a list (klist) and subsequently remove the > items using these keys. > > Is there an "even more pythonic" way? Your way seems clean enough to me. One other approach is to use items() so you can modify dict1 as you go: for key, value in dict1.items(): if value > 3: dict2[key] = value del dict1[key] Raymond Hettinger From cookedm+news at physics.mcmaster.ca Wed Apr 7 16:45:25 2004 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Wed, 07 Apr 2004 16:45:25 -0400 Subject: Idiom for error checking within a C extension References: Message-ID: At some point, Jon Perez wrote: > I want to retrieve a value from a tuple and convert it to a C > type. Is the following idiom okay? > > if (!( > ( tmp_pyobj=PyTuple_GetItem(tuple,1) ) && You've got 1 here, but mention the first member below (that's number 0). > ( c_int=PyInt_AsLong(tmp_pyobj) ) > )) > { > if (PyErr_ExceptionMatches(PyExc_TypeError)) > PyErr_SetString(PyExc_TypeError,"tuple's 1st member was not an integer"); > return NULL; > } > > > The PyErr_ExceptionMatches/PyErr_SetString combination in the if-block is > where I'm a bit unsure. I want to check if the tuple element is of the > correct type (a PyInt in this case) and if it isn't, I want to return my > own customized error message instead of the default TypeError message. > I'm kind of uncomfortable with the idea that I am checking for the kind > of exception raised and then afterwards calling a function which can > change it (even if I don't really end up doing that). That's no different than the python code try: p = tple[0] c = int(p) except TypeError: raise TypeError("tuple's 1st member was not an integer") You could use PyInt_Check(), and throw your own error, but if you want to handle longs or things that can be coerced to ints, you end up rewriting PyInt_AsLong(). -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From project5 at redrival.net Sat Apr 10 09:44:18 2004 From: project5 at redrival.net (Andrei) Date: Sat, 10 Apr 2004 15:44:18 +0200 Subject: Is boa-constructor dead? References: Message-ID: <4077fa35$0$93590$cd19a363@news.wanadoo.nl> Mark Carter wrote on Saturday 10 April 2004 14:42: > I noticed that boa-constructor has been stuck at 0.2.3 for a long time > now. Is it dead? Nope, it just doesn't release very often on the front page, where one would normally expect releases to appear :). There is activity on CVS. There is also a - not very well publicized - 0.2.8 zip/tarball somewhere in the forums if I'm not mistaken. I just can't find it right now. -- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5 at jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From joe at notcharles.ca Fri Apr 2 10:55:52 2004 From: joe at notcharles.ca (Joe Mason) Date: Fri, 02 Apr 2004 15:55:52 GMT Subject: Making the Zen of Python more useful References: <106qp0uivlefo40@corp.supernews.com> <-5ydnTEmxfuZHvDdRVn-iQ@powergate.ca> Message-ID: In article , Andrew Henshaw wrote: > In article <-5ydnTEmxfuZHvDdRVn-iQ at powergate.ca>, peter at engcorp.com says... >> >>Andrew Henshaw wrote: >> >>> In article , peter at engcorp.com says... >>>>I'm not sure why you had to do quite all that. The following is >>>>sufficient, and you don't need a custom ROT-13 thingie: >>>> >>>>>>>import StringIO, sys >>>>>>>s = StringIO.StringIO() >>>>>>>sys.stdout = s >>>>>>>import this >>>>>>>sys.stdout = sys.__stdout__ >>>>>>>s.getvalue() >>>> >>>>"The Zen of Python, by Tim Peters\n\nBeautiful is ... >>> >>> Much better. Still pretty awkward for the purpose I described. Perhaps, > the >>> best solution, overall. >> >>Okay then, how about this one? :-) >> >> >>> import this >>The Zen of Python, by Tim Peters\n\nBeautiful is ... >> >>> this.s.decode('rot-13') >>u"The Zen of Python, by Tim Peters\n\nBeautiful is ... >> >>-Peter > > Hey, that's very slick! But ... (starting to feel like a whiner), my main > problem was with the automatic printing of the text upon import. Obviously, > that functionality needs to remain. It would just be nice if there was > some clean way of (sometimes) using the module without it. Personally, I'd just make a "zen" module which imports "this" after redirecting stdout as described above, and give that to your students. Joe From donn at u.washington.edu Fri Apr 30 14:00:44 2004 From: donn at u.washington.edu (Donn Cave) Date: Fri, 30 Apr 2004 11:00:44 -0700 Subject: Is classless worth consideration References: <69cbbef2.0404290259.fd8d71c@posting.google.com> <69cbbef2.0404291209.7a98a799@posting.google.com> <8ef9bea6.0404292307.66b78b83@posting.google.com> Message-ID: In article <8ef9bea6.0404292307.66b78b83 at posting.google.com>, hungjunglu at yahoo.com (Hung Jung Lu) wrote: > Peter Hansen wrote in message > news:... > > has wrote: > > > Compared to C++, I expect it's a real breath of fresh air. But > > > compared to how something like Self does OO, it is indeed hideously > > > baroque. > > > > Oh, now you're qualifying the statement. In comparison to > > something less baroque, it's baroque. Fair enough... > > Good that things cleared up. I have also pointed out previously that > Python uses 5 devices where prototype-based needs only one: (a) class, > (b) instance, (c) module, (d) metaclass, (e) scope. If this is not > hideously baroque, then, Houston, we've got a problem. If you can > really think outside the box, you'd pitch in also: (f) aspect. As much as I love simplicity, it seems to me you may be stretching it here. I would have to agree with Peter Hansen that it isn't clear that scope and module would benefit from collapse into a single concept along with the rest. For that matter it isn't clear that instance and class would benefit, but when we get to metaclasses it's harder to disagree with you. I think I recall that you have been arguing that class and instance naturally give rise to metaclass, and that would be a strong argument. If it's true - if you really can't write effective, maintainable programs in Python without metaclass. To me that seems like an absurd proposition, though, if only because I'd have no idea how to use metaclass nor why I would want to do so. When the idea showed up a few years back, everyone chuckled about the `then my head exploded' experience of wrestling with metaclasses, and I have been assuming that it was a sort of sport accessory for people who need a little of that kind of thing now and then. You don't think so, it's a basic necessity, programs written with just class and instance are liable to be ineffective or unmaintainable or something? Donn Cave, donn at u.washington.edu From no.email at please.com Mon Apr 12 19:09:58 2004 From: no.email at please.com (Stevie_mac) Date: Tue, 13 Apr 2004 00:09:58 +0100 Subject: String + number split References: <2SAec.70005$Id.6002@news-binary.blueyonder.co.uk> Message-ID: Thank you all very much. "Stevie_mac" wrote in message news:2SAec.70005$Id.6002 at news-binary.blueyonder.co.uk... > Hello again, I can do this, but I'm sure there is a much more elegant way... > > A string, with a number on the end, strip off the number & discard any underscores > > eg... > > font12 becomes ('font',12) > arial_14 becomes ('arial',14) > > Cheers > > From peter at engcorp.com Wed Apr 7 11:23:41 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 07 Apr 2004 11:23:41 -0400 Subject: Non-math-geek needs help with CRCs (binascii.crc32) In-Reply-To: References: <4073c865$0$27642$61ce578d@news.syd.swiftdsl.com.au> Message-ID: Nick Craig-Wood wrote: > nobody wrote: > >> 1) Does anyone know if the CRC32 algorithm in binascii has a name? There >> seem to be a TON of different CRC32 methods; different polynomials, > If you have a sample of data, its usually pretty easy to work out > which CRC it does actually use by trial and error. You can use the > code Ross provides to help. Probably _much_ easier just to check the source. (It's not in Python, though, it's in the C source this time...) From mark at prothon.org Fri Apr 30 20:07:58 2004 From: mark at prothon.org (Mark Hahn) Date: Fri, 30 Apr 2004 17:07:58 -0700 Subject: What is good about Prothon? References: <108t2tlo06j8vb9@corp.supernews.com> <69cbbef2.0404281446.4e0ab52e@posting.google.com> <69cbbef2.0404291609.72d391db@posting.google.com> <69cbbef2.0404300855.4dce5e5@posting.google.com> Message-ID: Donn Cave wrote: > He's saying `language that tries to please everybody [by adding > features like copy instead of doing it right in the first place] == > C++' He could have a point. (Is there going to be an optional > __copy__ method?) Yes, there already is a copy method. It solves the problem he posted of AS versus Prothon. Adding copy is apparently turning Prothon into C++. I've never thought of something as simple as copy as being an evil thing. (The funny thing is I added copy as part of porting Python's methods. It has nothing to do with Self or AS, but it happens to match his needs). > He probably thought they were pearls of wisdom. He and I have been going in circles for weeks. I keep trying to get him to identify what would really make him happy in Prothon and apparently having anything that resembles the two-tiers of object creation of Python is an anathema to him and has to be removed. If it stays and there is anything else in there that he'd like then it would be C++. > Guess you don't want any more, anyway. Depends on what you mean by pearls of wisdom. I've been getting a lot of great ideas from both Prothon and Python mailing lists. I've been spending a lot of time arguing with Has (we started on the Prothon lists) because he has knowledge of AS and Self and would love to have him contribute. So far he will only tell me that Prothon sucks because of the two tiers and his only recommendation is to treat my code like clay and tear it down and start over. From colarte at telesat.com.co Fri Apr 2 09:18:47 2004 From: colarte at telesat.com.co (Camilo Olarte) Date: Fri, 2 Apr 2004 09:18:47 -0500 Subject: Making the Zen of Python more useful Message-ID: <1080915527.406d76472e1c5@ilpostino3.telesat.com.co> What about this: import os zen_command = os.popen("python -c 'import this'") zen_string = "" for line in zen_command.readlines(): zen_string += line zen_command.close() print zen_string Camilo Olarte Telesat, m?s f?cil...m?s Internet. http://www.telesat.com.co/ From stach at fr.USUN.pl Fri Apr 16 18:47:26 2004 From: stach at fr.USUN.pl (Krzysztof Stachlewski) Date: Sat, 17 Apr 2004 00:47:26 +0200 Subject: md5.hexdigest() converting unicode string to ascii In-Reply-To: <77b925de.0404161337.3917ef56@posting.google.com> References: <77b925de.0404151450.5c1f720a@posting.google.com> <77b925de.0404161337.3917ef56@posting.google.com> Message-ID: uebertester wrote: > None of the suggestions seem to address the issue. sValue = > _winreg.QueryValueEx(y,"") returns a tuple containing the following > (u'http://', 1). The string u'http://' is added to the md5 object via > the update() and then hashed via hexdigest(). How do I keep the > unicode string from being converted to ascii with the md5 functions? You *have to* convert the unicode string to byte character string (I'm trying not to call it 'character string' :-) ) md5 needs bytes to work, not unicode characters. As I have already said, you have some ready-to-use conversions to choose from. utf8? maybe utf16? I don't know which one you want. If you don't specify the codec yourself then the ascii codec is used by default. Unicode characters are implemented in Python either as 2 or 4 byte integers. You can't rely on memory representation of those integers (although you can play with ord() function). You need a codec. -- Stach Tlen: stachobywatelpl, GG: 1811474 Jabber: stach at jabber atman pl From deetsNOSPAM at web.de Thu Apr 22 10:19:23 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Thu, 22 Apr 2004 16:19:23 +0200 Subject: Simple question about mutable container iterator References: Message-ID: Neal D. Becker wrote: > x = [1,2,3] > > for i in x: > i = 2 > > This doesn't change x. 2 questions: > > 1) Why not? Why doesn't assign to an iterator of a mutable type change > the underlying object? because i doesn't point to an iterator, but instead to the value. The line i = 2 rebinds i to the value 2 - which doesn't affect the list x. In python, an iterator has only a next()-method. So its immutable and only capable of delivering the values in the order they appear in the underlying collection. > 2) What is the preferred way to do this? For lists, you could do for index, v in enumerate(x): x[index] = 2 -- Regards, Diez B. Roggisch From newsuser at itgoesclick.com Tue Apr 20 02:03:38 2004 From: newsuser at itgoesclick.com (Noah from IT Goes Click) Date: Tue, 20 Apr 2004 06:03:38 GMT Subject: I'm looking for a good overview of Tk concepts. Message-ID: <_23hc.186323$oR5.125527@pd7tw3no> I'm comming from the background of being primarily a data processing programmer (Python) and I'd like to do some GUI stuff for a comercial project but I have quite a bit of time, nothing too complex but it has to work on Windows98+ OSX and Solaris so I was thinking Tkinter. I was wondering if there were some sites with a good overview of the whole Python +Tk shpeal, I've got some code examples and "Programming Python 2nd Edition" but that's more of a learn by example, rather than an overview of concepts. Anyone have a good recommendation? From roy at panix.com Mon Apr 26 13:12:11 2004 From: roy at panix.com (Roy Smith) Date: Mon, 26 Apr 2004 13:12:11 -0400 Subject: Is Perl *that* good? (was: How's ruby compare to it older bro References: <108qcobc4m8g972@corp.supernews.com> Message-ID: claird at lairds.com (Cameron Laird) wrote: > Over in Perlmark, Randal "often" (his adverb) claims > no one'd use Tcl now if Expect and Tk hadn't kept it > alive. I don't know about that. What Tcl lacks in power and expressiveness, it makes up for in simplicity of use, quick learning curve, and ease of embedding/extending. I've written a lot of Tcl code, and never used either Expect or Tk. I think Tcl fills a valid niche, especially for small embedded applications. I'll go further than that; I think everybody who considers themselves a professional programmer should learn Tcl. Even if you never use it in anger, it's interesting and useful to explore different corners of the "language design concept" space. For the same reason, I think people should learn postscript, and try writing some real programs in it (no, it's not just a printer language). It's important to keep learning new stuff, and to recognize that however great your favorite tool d'jour is, there's going to be something better coming along in the future. Perl was invented because the mammoth shell/awk/sed/grep scripts of the day were getting unmanageable, and gained such popularity because it was better than the alternatives. Inertia, and lack of real competition has kept it alive for 20 years, but it's clear that better things have come along. By the same token, while Python is in its ascendancy, it's foolish to think nothing better will come along. It might be one of the Python outgrowths like the brand-new Prothon, or a current competitor like Ruby, or something even more afield like D, or something not yet invented. But it'll happen. My advice is to celebrate the joy that Python gives us today (just like Unix sysadmins celebrated Perl's introduction 20 years ago), but keep trying new things too. 5 years ago, Pythonistas (was the term even invented then?) were crazy rebels. Today, they're the fashionable avant garde. 5 years from now, they'll be comfortably mainstream. 10 years from now, they'll be old-fashioned. And 20 years from now, they'll be dinosaurs. Don't let yourself become a dinosaur. From heikowu at ceosg.de Thu Apr 22 04:06:58 2004 From: heikowu at ceosg.de (Heiko Wundram) Date: Thu, 22 Apr 2004 10:06:58 +0200 Subject: Python use large scale projects In-Reply-To: <47fc6058.0404212327.24163290@posting.google.com> References: <47fc6058.0404212327.24163290@posting.google.com> Message-ID: <200404221006.58682.heikowu@ceosg.de> Am Donnerstag 22 April 2004 09:27 schrieb limor: > I'd really like to talk with someone who is using this language in his > work for large scale projects. btw. you'd like to look at some large-scale projects written in Python which are out there, twisted (www.twistedmatrix.com) being one, Zope (www.zope.org) being the other, which seem to be both well-maintainable and -maintained by the group of programmers working on it. And I've yet to hear the devs complain about the code not being maintainable on their mailing-lists (okay, maybe Zope isn't such a fine example... ;)) Heiko. From aahz at pythoncraft.com Thu Apr 1 15:19:40 2004 From: aahz at pythoncraft.com (Aahz) Date: 1 Apr 2004 15:19:40 -0500 Subject: Python 3.0 (was Re: Prothon Prototypes vs Python Classes) References: <569c605ld1cj8fc1emolk08ete0s1prls1@4ax.com> <106di86neu1qh4d@news.supernews.com> <40675F08.9070402@mlug.missouri.edu> <258fd9b8.0403301237.60528600@posting.google.com> Message-ID: In article <258fd9b8.0403301237.60528600 at posting.google.com>, Magnus Lyck? wrote: >Michael wrote in message news:<40675F08.9070402 at mlug.missouri.edu>... >> >> They're planning to remove tab indention support in 3.0? I for one would >> be pissed off at such a change. > >I don't think you need to worry. AFAIK Python 3 is the mythological >if-I-could-turn-back-the-clock-and-undo-all-my-mistakes version >of Python, which Guido probably won't have time to work with >until his son is big enough to help him. (He'll be 3 in November.) >It will have little regard for backward compatibility, and if it >does appear sooner than expected, you can expect Python 2.x to be >maintaned in parallel for a long time. Not quite. Python 3000 is the mythical version; Python 3.0 is expected to appear some day. While there will be many changes that are not backward compatible, your "little regard" is unlikely to be true: Guido *likes* Python. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "usenet imitates usenet" --Darkhawk From tim.golden at viacom-outdoor.co.uk Fri Apr 2 03:06:32 2004 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Fri, 2 Apr 2004 09:06:32 +0100 Subject: Apologies Message-ID: Apologies to all on the last for my rampant out-of-office messages. I'm using Exchange (over which I have no control), and I thought it did the right thing by list replies. I'll make sure next time. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star Internet. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From jcm at FreeBSD-uk.eu.org Mon Apr 26 11:05:35 2004 From: jcm at FreeBSD-uk.eu.org (Jonathon McKitrick) Date: Mon, 26 Apr 2004 16:05:35 +0100 Subject: Best way to add attributes to shelved objects? In-Reply-To: <16521.29527.356495.151656@montanaro.dyndns.org> References: <20040423193951.GC27351@dogma.freebsd-uk.eu.org> <16521.29527.356495.151656@montanaro.dyndns.org> Message-ID: <20040426150535.GA63648@dogma.freebsd-uk.eu.org> On Fri, Apr 23, 2004 at 02:49:43PM -0500, Skip Montanaro wrote: : : jm> I'm working on an app that persists a few classes with shelve. But : jm> if I load older saved classes, I get an exception in code that uses : jm> the new attributes, of course. : : jm> What is the best way to load these older classes, check for the new : jm> attributes, and add them so they will work with the new code? : : Why not check for those attributes in your __getstate__ method and add : default (or computed) values for any missing attributes? I tried experimenting with these, and could not get them to work. I had main() create a class, then shelve it. Then I added a new attribute to the class source code, and a statement to print it. When I tried hooking in __setstate__ and/or __getstate__ to load __dict__, it still did not find the new attribute when loading. Are there any examples on how to do this? jm -- My other computer is your Windows box. From anton at vredegoor.doge.nl Fri Apr 30 14:33:32 2004 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Fri, 30 Apr 2004 20:33:32 +0200 Subject: Feedback on Sets, and Partitions References: <5b42ae4.0404292354.86c7026@posting.google.com> Message-ID: <40929c3e$0$125$3a628fcd@reader3.nntp.hccnet.nl> eadorio at yahoo.com (Ernie) wrote: >I have an implementation done in python, not using sets but rather an >array of integers which can be used for indexing, for processing >equivalences and set partitions (See >http://www.geocities.com/eadorio/equiv.pdf). Thanks. Here's something I wrote in 2000. I just did some very superficial inspection of the code and adapted a few names that would not be ok anymore, now that we have sets, but very likely I would do things very differently now. It might start off other implementations though so I'm providing it below here. # SetPart.py : return a set divided into subsets. The possible ways # this can be done are indexed. Algorithms are adapted from the book # "Combinatorial Algorithms..." (1999) by Donald Kreher and # Douglas Stinson. # See also: http://www.math.mtu.edu/~kreher/cages.html # Translated and adapted for Python by Anton Vredegoor: # anton at vredegoor.doge.nl 19 jun 2000 # last update: april 2004 class SetPart: def __init__(self, aset): self.aset = aset self.m = len(self.aset) self.d = self.GeneralizedRGF(self.m) self.count = self.d[self.m][0] def __getitem__(self, index): # Partition number index if index > self.count - 1: raise IndexError rgf = self.UnrankRGF(self.m, index) result = self.RGFToSetPart(self.m, rgf, self.aset) return result[1:] ## ** Algorithm 3.12 def RGFToSetPart(self, m, b, aset): # Transform a restricted growth function list into a partition A = [] n = 1 for i in range(1,m+1): if b[i] > n: n = b[i] for i in range(n+1): A.append([]) for i in range(1,m+1): A[b[i]].append(aset[i-1]) return A ## ** Algorithm 3.14 def GeneralizedRGF(self, m): # Compute the values d[i.j] d = [[1L] * (m+1) for i in range(m+1)] for i in range(1,m+1): for j in range(0,m-i+1): d[i][j] = j * d[i-1][j] + d[i-1][j+1] return d ##** Algorithm 3.16 def UnrankRGF(self, m, r): # Unrank a restricted grow function f = [1] * (m+1) j = 1 d = self.d for i in range(2,m+1): v = d[m-i][j] cr = j*v if cr <= r: f[i] = j + 1 r -= cr j += 1 else: f[i] = r / v + 1 r %= v return f def test(): aset = range(5) P = SetPart(aset) print P.count for x in P: print x if __name__ == '__main__': test() Anton From steve at ninereeds.fsnet.co.uk Wed Apr 7 17:26:56 2004 From: steve at ninereeds.fsnet.co.uk (Stephen Horne) Date: Wed, 07 Apr 2004 22:26:56 +0100 Subject: OFF-TOPIC:: Why Lisp is not my favorite programming language References: <165b3efa.0403030443.4d591f04@posting.google.com> <40460dd5$0$5916$7a628cd7@news.club-internet.fr> <6in670lrldbjkuujle68a526293j57a7mn@4ax.com> Message-ID: On 07 Apr 2004 13:32:49 +0200, Jacek Generowicz wrote: >Now just what do you mean when you say "LISP is normally interpreted" ? That would be "I'm at least twenty years out of date, and stupid as well for not checking my facts before posting". Sorry. -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From loic at fejoz.net Mon Apr 19 03:48:01 2004 From: loic at fejoz.net (Yermat) Date: Mon, 19 Apr 2004 09:48:01 +0200 Subject: Proposed PEP: Treating Builtins as Constants in the Standard Library In-Reply-To: <5d83790c.0404171557.3db69f48@posting.google.com> References: <5d83790c.0404171557.3db69f48@posting.google.com> Message-ID: Raymond Hettinger wrote: > Comments are invited on the following proposed PEP. > > > Raymond Hettinger > > ------------------------------------------------------- > > > > PEP: 329 > Title: Treating Builtins as Constants in the Standard Library > Author: Raymond Hettinger > Status: Pre-PEP > > > Abstract > ======== > > This proposal is to add a private function for treating builtin > references as constants and to apply that function throughout > the standard library. Is it really a good thing to do it manually? Shouldn't be done automatically by a simple analyser? -- Yermat From pinard at iro.umontreal.ca Wed Apr 21 20:32:52 2004 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Wed, 21 Apr 2004 20:32:52 -0400 Subject: __metaclass__ = type (was: Re: if (__name__ == '__main__'): main(sys.argv[1:])) In-Reply-To: <11Bhc.2149$hM2.1561@news02.roc.ny> References: <01c601c4271b$7f7300a0$b401010a@sparta> <4085A445.1050303@heneryd.com> <11Bhc.2149$hM2.1561@news02.roc.ny> Message-ID: <20040422003252.GA16351@alcyon.progiciels-bpi.ca> [Lee Harr] > On 2004-04-21, Fran?ois Pinard wrote: > > __metaclass__ = type > Is there any reason to stick with old-style classes? For your new programs, there is probably no good reason to worry about old-style classes. For your old programs, it is likely that you will not meet problems on the average by the mere action of switching to types. However, there are areas of incompatibilities indeed, that one may stumble upon, if one were pushing a bit deep in the internals. > I mostly just create classes the old way and never even think about > sub-classing object. There are some new features, and corrections to previously debatable features, which are not available in the old-style classes. If you do very simple uses of classes, always, you might choose to ignore the difference. -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From python at rcn.com Thu Apr 22 17:15:23 2004 From: python at rcn.com (Raymond Hettinger) Date: 22 Apr 2004 14:15:23 -0700 Subject: mutable list iterators - a proposal References: <5d83790c.0403170242.759ac8d9@posting.google.com> <5d83790c.0403211210.703991c2@posting.google.com> Message-ID: <5d83790c.0404221315.4ad5fc00@posting.google.com> [Raymond] > > All the contortions in the code still suggest to me that the use case > > needs a different algorithm. Try rewriting it with separate input and > > output lists. My bet is that the code is clearer and more > > maintainable. [Jess Austin] > My original use case was 3 classes in 30 lines, not including the > subclassing of list. Depending on your application, there may be a good alternative to mutating in-place while iterating. Consider using a Queue object or something similar (collections.deque in Py2.4, deque objects on ASPN, or lists with append() and pop(0)): while inputlist: datum = inputlist.pop(0) [processing with the element] if somecondition: inputlist.append(datum) else: continue # effectively removing the element The idea is to get around the issues of mutating in-place by removing the element in question, processing it, and if needed again, adding to the end of the queue. The ASPN recipes on queues show show to do this a bit more efficiently than with the list object but the idea is the same. > I love to use it. Iterators and list comprehensions were good, but > coupled with itertools they are great. > > Thanks, Raymond, for all you've done for Python. Thanks for the accolades. Raymond From dmq at gain.com Tue Apr 27 19:53:13 2004 From: dmq at gain.com (David MacQuigg) Date: Tue, 27 Apr 2004 16:53:13 -0700 Subject: What is good about Prothon? References: Message-ID: <31st80lj1utns91pmm34ki7dsoqv34h4bb@4ax.com> On Tue, 27 Apr 2004 09:12:11 -0700, "Mark Hahn" wrote: >You have argued this in the Prothon mailing lists for almost a month with >Greg and me. Please don't just start it up again here (about Prothon I >mean). Mark, Stop making false statements about me. If you have personal criticism, send me an email. You now have 5 out of 9 postings on this thread. I don't have time to keep up with this, so anyone following this thread please don't take my lack of further response as lack of interest in your feedback. My filter is set to ignore "Prothon" in the subject line. Please join me on the new thread "Ideas for Python 3". -- Dave From michele.simionato at poste.it Fri Apr 30 00:07:48 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 29 Apr 2004 21:07:48 -0700 Subject: Closures References: Message-ID: <95aa1afa.0404292007.6a28a806@posting.google.com> Gustavo Niemeyer wrote in message news:... > import sys > > class Closure: > def __init__(self): > self.__dict__ = sys._getframe().f_back.f_locals > > def getFunc(): > counter = 0 > c = Closure() > def count(): > c.counter += 1 > print c.counter > return count > > c = getFunc() > c() > c() > c() This is a nice hack! Why not to make it available as a Cookbook recipe? Michele Simionato From tkpmep at hotmail.com Thu Apr 22 22:55:07 2004 From: tkpmep at hotmail.com (Thomas Philips) Date: 22 Apr 2004 19:55:07 -0700 Subject: Subclasses in Python Message-ID: I'm teaching myself programming using Python, and have a question about subclasses. My game has two classes, Player and Alien, with identical functions, and I want to make Player a base class and Alien a derived class. The two classes are described below class Player(object): #Class attributes for class Player threshold = 50 n=0 #n is the number of players #Private methods for class Player def __init__(self,name): self.name = name self.strength = 100 Player.n +=1 def __del__(self): Player.n -=1 print "You got me, Alien" #Public methods for class Player def blast(self,enemy,energy): enemy.hit(energy) def hit(self,energy): self.strength -= energy if(self.strength <= Player.threshold): self.__del__() class Alien(Player): #Class attributes for class Alien threshold = 100 n=0 #n is the number of players #Private methods for class Alien def __init__(self,name): self.name = name self.strength = 100 Alien.n +=1 def __del__(self): Alien.n -=1 print "You got me, earthling" #Public methods for class Alien def hit(self,energy): self.strength -= energy if(self.strength <= Alien.threshold): self.__del__() The two classes are almost identical, except that: 1. When a new player is instantiated or destroyed, Player.n is incremented/decremented, while when a new alien is instantiated, Alien.n is incremented/decremented. 2. When hit by an energy blast, the player and the alien have different thresholds below which they die. How can I base the Alien's __init__(), __del__() and hit() methods on the Player's methods, while ensuring that the appropriate class variables are incremented/decremented when a new object is instantiated and that the appropriate threshold is used when the player/alien is hit by an energy bolt? Thomas Philips From no.email at please.com Sun Apr 11 07:15:11 2004 From: no.email at please.com (Stevie_mac) Date: Sun, 11 Apr 2004 12:15:11 +0100 Subject: Static Data? References: <2FTdc.56817$Id.5813@news-binary.blueyonder.co.uk> Message-ID: Thanks Peter, I really appreciate this - I'm gonna trim this down to a short tutorial - I personally think (even having read up on classes & scope) that this was the toughest thing to get my head around. "Peter Otten" <__peter__ at web.de> wrote in message news:c5ausj$qfb$01$1 at news.t-online.com... > Stevie_mac wrote: > > > In Jeffs solution, Is self._ID the same variable as _ID (declared > > immediately after class Counted). Is there 3 _IDs? If you have the time, > > Jeff Epler's code with annotations: > > class Counted: > _ID = 0 # set the class attribute; same as Counted._ID = 0 > > def __init__(self): > Counted._ID += 1 # increment the class attribute > self._ID = Counted._ID # set the instance attribute to the > # current value of the class attribute > > > could you explain (nothing fancy, just brief) the meaning of declaring > > variables in different > > locations (like self, below class, as part of class, in a class def). > > This would be greatly appreciated. > > > > and Peters solution > > class Object: > > _ID = 1 > > def __init__(self): > > self.ID = Object._ID > > Object._ID += 1 > > Is Object._ID a class instance variable and self.ID a 'shared' class > > variable > > This is basically the same as Jeff's. I just chose different names for the > class attribute (_ID) and instance attribute (ID). > > If you set an attribute in the class, > > class Object: > clsattr = 1 > > that is the same as > > class Object: > pass > Object.clsattr = 1 > > If you set an instance attribute you always need the instance: > > inst = Object() > inst.attr = 2 > > Inside a method it's the same, only the instance will most likely be named > self. > > class Object: > def method(self, newvalue): > self.attr = newvalue > > Now for attribute lookup: > > inst.attr > > will first look up attr in the instance, and if it's not there, it will fall > back to the class: > > >>> class Object: > ... pass > ... > >>> Object.attr = "in class" > >>> inst = Object() > >>> inst.attr > 'in class' > >>> inst.attr = "in instance" > >>> inst.attr > 'in instance' > > The class attribute is still there, only "shaded" bye the instance > attribute: > > >>> Object.attr > 'in class' > > Now let's delete the instance attribute: > > >>> del inst.attr > >>> inst.attr > 'in class' > > The class attribute becomes visible again. > > Once you have understood the above, classmethods are just a another way to > access the class instead of the instance. The advantage over an explicit > use of the class identifier is that with inheritance they always provide > the actual class: > > >>> class Object(object): > ... def method(cls): > ... print cls.__name__ > ... method = classmethod(method) > ... > >>> class Sub(Object): > ... pass > ... > >>> Object().method() > Object > >>> Sub().method() > Sub > > Peter > From loic at fejoz.net Mon Apr 5 11:40:23 2004 From: loic at fejoz.net (Yermat) Date: Mon, 05 Apr 2004 17:40:23 +0200 Subject: design by contract versus doctest In-Reply-To: <407174ea$0$5066$4d4ebb8e@news.nl.uu.net> References: <407174ea$0$5066$4d4ebb8e@news.nl.uu.net> Message-ID: aku wrote: > There seems to be a contradictive approach in > these two things. Example: In the doctest documentation > (http://www.python.org/doc/current/lib/module-doctest.html) > a required precondition (i.e. n is an integer and >= 0) > is verified in the function itself: > > if not n >= 0: > raise ValueError("n must be >= 0") > > But in "design by contract" this responsibility is squarely > on the shoulders of the caller, and is *not* checked in > the function. > > I'm confused as to what the "best" approach is. > > Isn't it so, that by applying DBC, a lot of unittests can be > made redundant? > > shan. I disagree with you ! Both are needed and not contradictory... In design by contract, you assume that caller do not call you with stupid argument. So you can see this precondition as something sure or as something to check. In the language that use the most Design by Contract, ie Eiffel, by default it check those condition on all call and give you something like and assert Error. (see http://www.python.org/doc/essays/metaclasses/Eiffel.py for something similar in python). But when you have finish to write your application you can compile it without those check because you are sure nobody will do false check ! Like in python if you optimize byte code (option -O), it delete all assertions. Hence there is no contradiction. And to improve your code, you can (must?) do unittest with, for example, doctest. Yermat From max at alcyone.com Wed Apr 21 16:55:03 2004 From: max at alcyone.com (Erik Max Francis) Date: Wed, 21 Apr 2004 13:55:03 -0700 Subject: CamelCase versus wide_names (Prothon) References: <6e0680ac.0404211252.7f7b4358@posting.google.com> Message-ID: <4086DFA7.9736E7D3@alcyone.com> Mike wrote: > Since Python has removed the need for the ';' character, how about > using that as a word separator? It's very easy to type, as it is right > next to the 'L' key on a qwerty keyboard. > > Here;is;a;test;paragraph.;What;do;you;think?;Is;it;the;greatest;programming;language;invention;since;the > ;curly;brace? This is a really stellar example of why designing a language by committee doesn't work very well ... -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis \__/ Who shall stand guard to the guards themselves? -- Juvenal From asdf at asdf.com Fri Apr 9 17:58:52 2004 From: asdf at asdf.com (asdf sdf) Date: Fri, 09 Apr 2004 21:58:52 GMT Subject: Why Activestate Python ? In-Reply-To: <8089854e.0404090025.141f090c@posting.google.com> References: <8089854e.0404090025.141f090c@posting.google.com> Message-ID: Fuzzyman wrote: > Again... a silly newbie question which might have an obvious > answer.... but *why* is their an alternative distribution of python by > activestate ? > > Apart fromt he fact that they bundle Mark Hammond's Windows Extensions > with it (in the windows version) - what is to be gained from using > their distributio instead of the 'normal' one ? > > Regards, > > > Fuzzy > > http://www.voidspace.org.uk/atlantibots/pythonutils.html i think there is an impression generally that Win32 is a harder build platform for OSS projects than Linux-Unix. Very unscientifically, I think my reading of message boards supports that, at least for Apache, Python, and their related modules. I've never tried to build it myself. The activestate distribution includes Help files in compiled html format. Which I do not prefer. I just download the doc of interest from the python site. From max at alcyone.com Fri Apr 2 05:21:30 2004 From: max at alcyone.com (Erik Max Francis) Date: Fri, 02 Apr 2004 02:21:30 -0800 Subject: Simple text markup (-> HTML) References: Message-ID: <406D3EAA.16466030@alcyone.com> Jacek Generowicz wrote: > I'm looking for something to help developers wirte documentation for > bits of software they are writing. reStructredText. Bigtime. -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis \__/ Everybody's playing the game / But nobody's rules are the same -- Florence, _Chess_ From greg at invalid.invalid Wed Apr 28 15:14:38 2004 From: greg at invalid.invalid (Greg Krohn) Date: Wed, 28 Apr 2004 19:14:38 GMT Subject: Don't understand wxPython ids In-Reply-To: <408fb665$0$17264$a1866201@newsreader.visi.com> References: <408ed938$0$17263$a1866201@newsreader.visi.com> <408f3061$0$17258$a1866201@newsreader.visi.com> <408fb665$0$17264$a1866201@newsreader.visi.com> Message-ID: Grant Edwards wrote: > I guess it's simple enough to subclass the widgets I use and > add one, but it feels like going to buy a new car and having to > bring your own steering wheel. Well, no I meant importing something like this each time (it doesn't actually work, BTW): import wx #Subclass wx.PyEventBinder to catch all EVT_* args class MyPyEventBinder(wx.PyEventBinder): def __init__(self, *args, **kwargs): # Look for EVT_* args, bind them and del them for kw in kwargs: if kw.startswith('EVT_'): self.Bind(getattr(wx, kw), kwargs[kw]) del kwargs[kw] wx.PyEventBinder.__init__(self, *args, **kwargs) #A little behind-the-scenes switcheroo wx.PyEventBinder = MyPyEventBinder if __name__ == '__main__': class MyFrame(wx.Frame): def __init__(self, *args, **kwargs): wx.Frame.__init__(self, *args, **kwargs) self.button = wx.Button(self, -1, "What's my id?", EVT_BUTTON=self.OnButtonPress) def OnButtonPress(self, event): self.button.SetLabel("My id is: %d" % self.button.GetId()) app = wx.App() frame = MyFrame(None, -1, "Events and ids") frame.Show(True) app.MainLoop() If I can't figure this out, I'll try subclassing individule widgets and throwing it in a module. greg From peter at engcorp.com Sat Apr 24 08:55:56 2004 From: peter at engcorp.com (Peter Hansen) Date: Sat, 24 Apr 2004 08:55:56 -0400 Subject: command-line args In-Reply-To: References: Message-ID: Michael wrote: > What's the perfered method of passing command-line args throughout a > Python program given that globals don't seem to really exist? I thought > of writing them out to a python file and then importing them when > needed.. but that seems like it'd only work for a single process.. not > in instances where more than one user is running the program. There > isn't anything like a virtual file space that could be used for this? > Anyway to set a global variable? Create an empty module called "globals" and import that wherever needed. Populate it with settings from the command-line parsing stage. Get fancier and put defaults in there to begin with, and override them only if specified in the command-line parsing area. Flavour as needed... (That's just one option, but in many ways the simplest. Some of us also use a simple "bag" type of object which we pass around as required, but that's more awkward with really large applications.) -Peter From mayal at tiscali.be Sat Apr 24 10:35:01 2004 From: mayal at tiscali.be (Paul Mayal) Date: Sat, 24 Apr 2004 16:35:01 +0200 Subject: help: py2exe and com server Message-ID: <408a78f5$0$41761$5fc3050@dreader2.news.tiscali.nl> Hi, I have written a com server in python 2.3 (ActiveState distribution). I have build the dll with py2exe. First of all, py2exe complain he can't find pythoncom module. I can register the dll with regsvr32 on my development workstation. But when I try to register the com dll on an another workstation, the registration fail. what am I missing ? Georges From fumanchu at amor.org Tue Apr 20 15:35:21 2004 From: fumanchu at amor.org (Robert Brewer) Date: Tue, 20 Apr 2004 12:35:21 -0700 Subject: co_freevars question Message-ID: Jeff Epler wrote: > co_freevars names variables that come from an enclosing scope that is > not module scope. > > def g(): > return y > print g.func_code.co_freevars # () > > def f(): > y = 3 > def g(): > return y > print g.func_code.co_freevars # ('y',) > f() Ah...got it. Thanks! Robert Brewer MIS Amor Ministries fumanchu at amor.org From woodsplitter at rocketmail.com Wed Apr 28 00:25:08 2004 From: woodsplitter at rocketmail.com (David Rushby) Date: 27 Apr 2004 21:25:08 -0700 Subject: Newbie question: Where is python23 bcpp.lib? References: Message-ID: <7876a8ea.0404272025.49c0634c@posting.google.com> De La Maza Michael A GS-11 AFSPC/XPYS wrote in message news:... > Under Windows, I'm trying to make a program (Gambit Python APIs) using > Borland (i.e., "make -f borland"). > > The Borland make file, shown below, wants python23_bcpp.lib in > $(PYTHONDIR)\libs\. > > Unfortunately, there is no such file (error shown below). There is a > python23.lib file but simply substituting python23 bcpp.lib with > python23.lib does not work. Because the official distributions of Python 2.3.x are compiled with MSVC 6, python23.lib is in the Microsoft lib format (coff). BCPP requires the Borland format (omf). BCPP includes a conversion utility called coff2omf.exe. The commands cd $(PYTHONDIR)\libs coff2omf.exe python23.lib python23_bcpp.lib should create the required file. From jcarlson at uci.edu Thu Apr 1 02:34:08 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Wed, 31 Mar 2004 23:34:08 -0800 Subject: From python-dev, space vs. tab controversy finally settled In-Reply-To: References: Message-ID: Carl Banks wrote: > Here's a summary of the final decision Guido made concerning how > Python will indent code in the future, from python-dev: > > Guido had been planning to deprecate tabs in favor of spaces for > awhile, although there have been good arguments for both tabs and > spaces. But he was never really comfortable pulling the rug out from > half the user base. However, today he finally decided on a compromise > that has all the benefits of both spaces and tabs. > > His decision was predicated by the recent decision of the Unicode > Consortium to allocate some new codes for special use in programming > languages. The Consortium allocated codes for (among other things): > several sets of left and right braces, several sets of quote > characters, a couple universal comment markers, and several > metacharacters for use in regular expressions. > > However, the code that influenced Guido was a special indent code. > Here's how it works: at the beginning of the line, you put in one > "indent character" for each level of indentation. Because Python will > support Unicode fully by 3.0, Guido decided that this new Unicode > character will be the one and only way to indent Python code. > > Now, I'm sure everyone's aware that Unicode is getting kind of full, > and so, rather than allocating precious ununsed slots to the new > programming characters, the Consortium decided reallocate some codes > that had been rarely used. These codes fall in the range 0001 through > 001F, excepting 000A and 001A (all codes in hexadecimal). The new > indent character has code 0009. > > So, you should start using Unicode character 0009 to indent right > away. Python 2.4 will deprecate all indentation not using the new > indent character, and Python 3.0 will not support any other > indentation. Great april fools joke, but no such conversation has gone on in Python-Dev in the last 3 months. Better luck next time. - Josiah From peter.schwalm at epost.de Thu Apr 8 17:06:53 2004 From: peter.schwalm at epost.de (Peter Schwalm) Date: 8 Apr 2004 14:06:53 -0700 Subject: Customizing the python search path depending on source directory References: <5cf809e9.0404061853.41cd3c85@posting.google.com> <5cf809e9.0404070452.643b7053@posting.google.com> <5cf809e9.0404071734.26f1078a@posting.google.com> <4dudnVzbRvwbyOjdRVn-sw@powergate.ca> Message-ID: <5cf809e9.0404081306.5d8a81cb@posting.google.com> Peter Hansen wrote in message news:<4dudnVzbRvwbyOjdRVn-sw at powergate.ca>... > Peter Schwalm wrote: > > ... can you confirm that you get identical results if in each > place where you typed "test1.py" you instead typed the > equivalent with, for example, "python test1.py"? > I have run the programs with "python .py" now. For my purposes the results look identical - the source directory is still not accessible during the processing of sitecustomize.py. Here are the outputs of the explicit invocations: Invocation from source directory: E:\temp>python test1.py ---> C:\Python23\lib\sitecustomize.pyc ... ---------------------------------------------------------------- python-version= 2.3.2 (#49, Oct 24 2003, 13:37:57) [MSC v.1200 32 bit (Intel)] argv= sys.argv does still not exist! sys.modules["__main__"]= sys.modules["__main__"].__file__ does still not exist sys.path= 00: C:\WINNT\System32\python23.zip 01: C:\Python23\Lib\site-packages\Pythonwin 02: C:\Python23\Lib\site-packages\win32 03: C:\Python23\Lib\site-packages\win32\lib 04: C:\Python23\Lib\site-packages 05: C:\Python23\DLLs 06: C:\Python23\lib 07: C:\Python23\lib\plat-win 08: C:\Python23\lib\lib-tk 09: C:\Python23 10: C:\Python23\lib\site-packages\PIL ---------------------------------------------------------------- <--- C:\Python23\lib\sitecustomize.pyc ... ---> test1.py ... ---------------------------------------------------------------- python-version= 2.3.2 (#49, Oct 24 2003, 13:37:57) [MSC v.1200 32 bit (Intel)] argv= ['test1.py'] sys.modules["__main__"]= test1.py sys.path= 00: E:\temp 01: C:\WINNT\System32\python23.zip 02: C:\Python23\Lib\site-packages\Pythonwin 03: C:\Python23\Lib\site-packages\win32 04: C:\Python23\Lib\site-packages\win32\lib 05: C:\Python23\Lib\site-packages 06: C:\Python23\DLLs 07: C:\Python23\lib 08: C:\Python23\lib\plat-win 09: C:\Python23\lib\lib-tk 10: C:\Python23 11: C:\Python23\lib\site-packages\PIL ---------------------------------------------------------------- <--- test1.py ... E:\temp> Invocation from different directory: E:\temp\sub1>python ..\test1.py ---> C:\Python23\lib\sitecustomize.pyc ... ---------------------------------------------------------------- python-version= 2.3.2 (#49, Oct 24 2003, 13:37:57) [MSC v.1200 32 bit (Intel)] argv= sys.argv does still not exist! sys.modules["__main__"]= sys.modules["__main__"].__file__ does still not exist sys.path= 00: C:\WINNT\System32\python23.zip 01: C:\Python23\Lib\site-packages\Pythonwin 02: C:\Python23\Lib\site-packages\win32 03: C:\Python23\Lib\site-packages\win32\lib 04: C:\Python23\Lib\site-packages 05: C:\Python23\DLLs 06: C:\Python23\lib 07: C:\Python23\lib\plat-win 08: C:\Python23\lib\lib-tk 09: C:\Python23 10: C:\Python23\lib\site-packages\PIL ---------------------------------------------------------------- <--- C:\Python23\lib\sitecustomize.pyc ... ---> ..\test1.py ... ---------------------------------------------------------------- python-version= 2.3.2 (#49, Oct 24 2003, 13:37:57) [MSC v.1200 32 bit (Intel)] argv= ['..\\test1.py'] sys.modules["__main__"]= ..\test1.py sys.path= 00: E:\temp 01: C:\WINNT\System32\python23.zip 02: C:\Python23\Lib\site-packages\Pythonwin 03: C:\Python23\Lib\site-packages\win32 04: C:\Python23\Lib\site-packages\win32\lib 05: C:\Python23\Lib\site-packages 06: C:\Python23\DLLs 07: C:\Python23\lib 08: C:\Python23\lib\plat-win 09: C:\Python23\lib\lib-tk 10: C:\Python23 11: C:\Python23\lib\site-packages\PIL ---------------------------------------------------------------- <--- ..\test1.py ... E:\temp\sub1> By the way, *if I remember that correctly*: to be able to invoke python scripts simply by name ("test1" instead of "python test1.py") you have to do two things: 1) set the environment variable PATHEXT such that it contains ".py"(see sample output from set command) E:\temp>set pathext PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.PY;.py;.pyw; .pyc;.pys;.pyo E:\temp> 2) associate the file extension ".py" with c:\python23\python.exe right click a .py-file in explorer, select "open with" (my translation of the german "oeffnen mit") select python.exe as application and check "open always with". Thank you in advance Peter Schwalm From k.robert at gmx.de Mon Apr 12 08:11:09 2004 From: k.robert at gmx.de (Robert) Date: 12 Apr 2004 05:11:09 -0700 Subject: How to read & write standard password encrypted ZIP files? Message-ID: <19804fd8.0404120411.3497925d@posting.google.com> Is it possible to write & read standard password encrypted ZIP files easily (using zipfile.ZipFile?) Robert From op73418 at mail.telepac.pt Tue Apr 6 06:12:49 2004 From: op73418 at mail.telepac.pt (Gonçalo Rodrigues) Date: Tue, 06 Apr 2004 11:12:49 +0100 Subject: slightly OT: BUT NEEDs to be said References: <8b42d1998c978c8c1cddf15c52a1c57b@dizum.com> Message-ID: <8c057057tktogrhl3vsgskji165oj24t8d@4ax.com> On Mon, 5 Apr 2004 21:50:07 +0200 (CEST), Nomen Nescio wrote: [some text snipped] >Sorry if I was ranting but here is some more rant: > >People have very real reason to fear MPFC: Highly educated/wealthy family background/private >school/Oxford/Cambridge people jumping about and acting 'zany' and coming up >with all sorts of useless sketches designed to appeal strictly to the liberal-elite >is a fairly repulsive artistic concept especially if you do not find the style >of MPFC even remotely amusing. > >Unfortunately this formula (hiring these sorts of people) was to become the >bed rock of BBC alternative comedy for years to come (Ben Elton, Steven Fry >etc etc) and remember people in the UK did not have the choice about this crap >as it came out of their licence fee (that is another subject) > >So anyway I don't see quite those sorts of concepts woven into PHP, Perl,C,C++, >Java or anything else....although there may well be similar things but *well* >hidden as they should be > >If someone came up with a KKK language it might be attractive for members of >the KKK but would generally be consideredly highly unacceptable and would attract >much criticism. If someone came up with a language/interpreter based on their >favourite TV show like I dunno 'Friends' or whatever it would be seen as ridiculous. >If I came up with a scripting language called 'Ben Elton' then that would have >extreme political overtones and just invoke all Ben Eltons extreme left wing >radicalism. > >At the least MPFC is divisive (you either find it funny or you don't) > >Surely the uptake and use of a particular language (to solve a particular niche >or set of problems) is at least in part due to the perceived politcal and artist >*neutrality* of that language. > >If the author and contributors to Python wish to only encourage Python use >on the basis that the end user has great admiration of MPFC (as amusingly hinted >at by one of the other authors in this thread) you should perhaps restrict >access to python.org and related sites and authenticate on that basis and call >it a private members club.... > >Cuddly cartoon characters like the Snake, or various BSD creatures = highly >acceptable and good. > >MPFC = too aristically/politically/socially 'loaded' to be acceptable. > Unbelievable... "socially loaded"... unbelievable... <\amazed> >Please drag the Python and python.org image out of the stuffy past and in line >with similar projects And you sir, are a Troll. With my best regards, G. Rodrigues From joshway_without_spam at myway.com Thu Apr 15 20:18:26 2004 From: joshway_without_spam at myway.com (JCM) Date: Fri, 16 Apr 2004 00:18:26 +0000 (UTC) Subject: CamelCase versus wide_names (Prothon) References: <407ec022$0$54153$1b2cd167@news.wanadoo.nl> Message-ID: Mark Hahn wrote: ... > (Unless there is some correlation with camelCase-loving and > quick-responding :) Yes, and in addition to being overzealous, those who prefer camelCase are stubborn, sloppy coders, and have poor personal hygiene. From beliavsky at aol.com Wed Apr 28 10:58:39 2004 From: beliavsky at aol.com (beliavsky at aol.com) Date: 28 Apr 2004 07:58:39 -0700 Subject: debugging code References: <3064b51d.0404271139.6ec7057@posting.google.com> <408ee541$0$46510$39cecf19@news.twtelecom.net> Message-ID: <3064b51d.0404280658.ccf1894@posting.google.com> Rick Ratzel wrote in message news:<408ee541$0$46510$39cecf19 at news.twtelecom.net>... > Python defines __debug__ to True by default, and False when > optimizations are enabled...meaning you can enable/disable code without > having to define/undefine vars ahead of time and without having to > change it prior to deployment. This is how the "assert" statement > works. You can only set __debug__ through the use of -O or -OO. Thanks -- I will take your suggestion. Where are the Python command line options like -O and -OO documented? Typing 'python -h' just gives me -O : optimize generated bytecode (a tad; also PYTHONOPTIMIZE=x) -OO : remove doc-strings in addition to the -O optimizations From jepler at unpythonic.net Tue Apr 13 21:13:09 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Tue, 13 Apr 2004 20:13:09 -0500 Subject: Looking for Python Definition In-Reply-To: References: Message-ID: <20040414011309.GB8795@unpythonic.net> You may want to read: http://www.python.org/doc/faq/installed.html From deetsNOSPAM at web.de Tue Apr 27 14:50:44 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Tue, 27 Apr 2004 20:50:44 +0200 Subject: Trying to write comments after escaping newline References: Message-ID: p brian wrote: > mystring = "hello " + someVariable + \ > "multiple lines 4 clarity" + \ > someothervariable > > The above works , but if I add comments > > mystring = "hello " + someVariable + \ #comment > "multiple lines 4 clarity" + \ #comment > someothervariable #comment > > it stops working because instead of escaping a newline I am now just > escaping a space or tab. > Is there some clever thing i have missed? To make line continuation work, the newline at the end of an line has to be escaped using an \ - and putting your comment there makes this exactly what you already observed: a space or tab escape instead of the newline. -- Regards, Diez B. Roggisch From vdazyvtm at tcaxwtrl.com Wed Apr 7 11:14:04 2004 From: vdazyvtm at tcaxwtrl.com (Datatec) Date: Wed, 7 Apr 2004 23:14:04 +0800 Subject: Take Online Surveys $10 to $125 per hr! Message-ID: <40741b4f$0$4543$afc38c87@news.optusnet.com.au> Our companies will pay you $5 to $75 for each suervey you fill out from the comfort of your own home. Get paid $50 to $150 for participating in focus group panels for 30 to 60 minutes. THAT'S IT! No catch, no gimmick. Check it out at http://hop.clickbank.net/?datatec/surveys2 From graham__fawcett at hotmail.com Sun Apr 25 23:17:30 2004 From: graham__fawcett at hotmail.com (Graham Fawcett) Date: 25 Apr 2004 20:17:30 -0700 Subject: Python-list, Exotic sex is urgently necessary for you! References: Message-ID: Timo Virkkala wrote in message news:... > Graham Fawcett wrote: > > Timo Virkkala wrote in message news:... > >>[disgusting content snipped] > >> > >>I've heard of sex with lots of kinds of animals, but Pythons? Wouldn't > >>that be a) difficult b) VERY dangerous? > > > > It's no surprise you're not into snakes, Timo. Everyone knows that > > Finns have fixations for flightless, fat waterfowl. > > LOL! Where does that come from? =) It's an obscure Linus Torvalds reference, about "Tux" the Linux mascot. From the Wikipedia: http://en.wikipedia.org/wiki/Tux According to Jeff Ayers, Linus Torvalds had a "fixation for flightless, fat waterfowl" and Torvalds claims to have contracted "penguinitis" after being gently nibbled by a penguin: "Penguinitis makes you stay awake at nights just thinking about penguins and feeling great love towards them." I hope this condition doesn't sound *too* familiar, Timo! ;-) Cheers, -- Graham From vineet at eswap.com Mon Apr 5 21:05:34 2004 From: vineet at eswap.com (Vineet Jain) Date: Mon, 5 Apr 2004 21:05:34 -0400 Subject: How to do [1]*4 for a tuple Message-ID: I'm not sure I understand why [1]*4 and (1)*4 work differently? [1]*4 results in [1, 1, 1, 1] while (1)*4 results in 4. There are times when I have to do the following: '%s some value %s and some other text %s' % (a)*3 as apposed to '%s some value %s and some other text %s' % (a, a, a) In this case I always end up doing '%s some value %s and some other text %s' % [a]*3 VJ From roccomoretti at hotpop.com Wed Apr 7 09:53:50 2004 From: roccomoretti at hotpop.com (Rocco Moretti) Date: Wed, 07 Apr 2004 08:53:50 -0500 Subject: [OT] The Cracker's Guide To Python In-Reply-To: <04g770lqpbhdgr3n3b9mnu9o8f08fdkgk0@4ax.com> References: <04g770lqpbhdgr3n3b9mnu9o8f08fdkgk0@4ax.com> Message-ID: Christos TZOTZIOY Georgiou wrote: > So jokingly, how do we advertise python in that "underground" world? > Easy: let's provide a crack for every version of python for windows! :) > It doesn't matter what it does, perhaps only change the copyright > message into "H4x0r3d by Guid0 T34m" by changing directly the > pythonxx.dll. The only problem would be that if the crack is written in > Python, it won't be able to open the dll as read-write... Like most things in Python, the solution is simple. Add the following to "site.py" in the standard library directly after the import: === sys.copyright = "H4x0r3d by Guid0 T34m" === Viola! ==== Python 2.3 (#46, Jul 29 2003, 18:54:32) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> copyright H4x0r3d by Guid0 T34m >>> ==== From danbmil at cmu.edu Tue Apr 6 18:29:00 2004 From: danbmil at cmu.edu (dan miller (moderator, s.p.d)) Date: Tue, 06 Apr 2004 15:29:00 -0700 Subject: what is happening here? Message-ID: trying to figure out scoping of 'globals' in modules. So I have test.py: glob = 1 def setglob(v): global glob glob = v def getglob(): return glob and I do this: >>> from test import * >>> glob 1 >>> getglob() 1 >>> glob=2 >>> glob 2 >>> getglob() 1 >>> setglob(3) >>> getglob() 3 >>> glob 2 Seems to me like the first time I invoke glob, it creates a new global in my namespace, and initializes it to the value of the glob in test.py. Seems counterintuitive! From eric at zomething.com Fri Apr 2 22:39:29 2004 From: eric at zomething.com (Eric @ Zomething) Date: Fri, 2 Apr 2004 19:39:29 -0800 Subject: first python program.. lyrics search Message-ID: <20040402193929.1818612568.eric@zomething.com> Gustavo wrote: > I am trying to parse the html code and get the information that i need. [snip] > > The problem is once I have the M.htm page I don't now how to get from > the html code the "http://www.musicsonglyrics.com/M/Metallica/Metallica > lyrics.htm" link to proceed with the search. I tried to read about > Regular Expressions [snip] There are several challenges to this. First, you will find lyric website webpages that have, for example, "Metallica" on them, but do not have any Metallica lyrics on them. Second, the organizational (file/database) method for finding lyrics will vary by website. Third, the presentation of lyrics will vary by website. This makes it hard to generalize an approach, I think, without perhaps using a fairly robust spider. As for lyric sites, there may also be some access impediments, depending on the site, and cagey sys admin's have been known to pollute the data sent in response to welcome requests. I do think regular expressions are your friend, and can be used successfully to parse the lyrics, or other information, out of a specific website's pages, even if those pages are not, for example, valid (x)html. One nice way to work into a workable understanding of RE is to use a program such as redemo.py which may have been included with your Python distribution under "/Scripts" or the equivalent. It might be an interesting problem to identify song and poem lyrics by analyzing the strings (line length, word content, etc.), but I am not sure how favorable a success rate could be achieved. I suppose its all about characterizing the data... that could be fun. good luck! Eric From lbates at swamisoft.com Mon Apr 26 15:48:30 2004 From: lbates at swamisoft.com (Larry Bates) Date: Mon, 26 Apr 2004 14:48:30 -0500 Subject: iterating over collection, deleting entries References: Message-ID: I would do: collection=[i for i in collection if not isBad(i)] Larry Bates Syscon, Inc. "Patrick von Harsdorf" wrote in message news:c6gop3$5p7$03$1 at news.t-online.com... > I want to iterate over a collection and delete all unwanted entries. > > for item in collection: > del item > > of course doesn?t do anything useful. Two things come to mind: > a) iterating backwards over the collection using indexing, something like: > > for i in range(len(collection)-1, -1, -1): > item = collection[i] > if isBad(item) del collection[i] > > b) duplicating the collection, iterating over one and deleting from the > other. > > Both solutions seem both ugly and expensive to me, solution a) > probably isn?t even O(x) anymore. > > Please tell me, what?s the best way to do this? > > > -- > Patrick von Harsdorf > patrick at harsdorf.de > > > > From michele.simionato at poste.it Sun Apr 4 10:30:40 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 4 Apr 2004 07:30:40 -0700 Subject: __nonzero__ of iterators References: Message-ID: <95aa1afa.0404040630.5008ebc7@posting.google.com> Christian Eder wrote in message news:... > > I would like to read some comments on this topic as I'm sure that I'm > not the first one wondering whether the current behaviour should be that > way. Indeed. You may want to read this thread of last summer: http://groups.google.it/groups?hl=it&lr=&ie=UTF-8&threadm=2259b0e2.0307220744.156c95bf%40posting.google.com&rnum=1&prev=/groups%3Fhl%3Dit%26lr%3D%26ie%3DISO-8859-1%26q%3Dsimionato%2Bempty%2Biterator%26meta%3Dgroup%253Dcomp.lang.python.* Michele Simionato From jacek.generowicz at cern.ch Wed Apr 7 11:45:47 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 07 Apr 2004 17:45:47 +0200 Subject: Dynamic creation of an object instance of a class by name References: <10f99b0f.0404070656.5960e2c8@posting.google.com> Message-ID: meyer at acm.org (Andre Meyer) writes: > Hi all > > I have been searching everywhere for this, but have not found a > solution, yet. > > What I need is to create an object that is an instance of a class (NOT a > class instance!) I'm sorry, I can't for the life of me figure out what the (semantic) difference is between "intsance of a class" and "class instance". > of which I only know the name as a string. This what I > tried: > > class A: > def __init__(self, id): > self.id = id > def getID(self): > print self.id > > ca = new.classobj('A', (), {}) This creates a new class which will be called "A", displacing your original class by the same name. > oa1 = ca() > oa2 = new.instance(ca) > > oa1 > <__main__.A instance at 0x007E8AF8> > > oa1.getID() > Traceback (most recent call last): > File "", line 1, in ? > AttributeError: A instance has no attribute 'getID' > > oa2 > <__main__.A instance at 0x007E8AF8> > > oa2.getID() > Traceback (most recent call last): > File "", line 1, in ? > AttributeError: A instance has no attribute 'getID' > > > Thus, both ways only produce a class instance, but NOT an object of that > class!!! Yes, they produce an instance of your newly created class. > How can I get a new object instance??? I think you mean to ask "How can I get a new instance of the class whose name I have in a string?". In other words, you should be asking yourself, "How can I get my hands on an object whose name[*] I have in a string?" (One possible approach is shown below.) > What else needs to be filled in for base_classes and __dict__ in > new.classobj? You can't do it that way ... that way you create a _new_ separate class called "A". Here's how you might achieve what you want: >>> class A: ... def __init__(self, id): ... self.id = id ... def getID(self): ... print self.id ... >>> oa1 = globals()['A'](12345) >>> oa1 <__main__.A instance at 0x8190844> >>> oa1.getID() 12345 >>> [*] I'm a bit wary about using "name" here, because I don't really mean the name of the class, but the name of a variable that happens to refer to the class. For example, consider (in the context established above) >>> B = A >>> del A >>> B.__name__ 'A' >>> A.__name__ Traceback (most recent call last): File "", line 1, in ? NameError: name 'A' is not defined So, while the name of the class is still "A", it is no longer known by an identifier of that name. From listsub at wickedgrey.com Tue Apr 20 17:07:00 2004 From: listsub at wickedgrey.com (Eli Stevens (WG.c)) Date: Tue, 20 Apr 2004 14:07:00 -0700 Subject: if (__name__ == '__main__'): main(sys.argv[1:]) Message-ID: <01c601c4271b$7f7300a0$b401010a@sparta> I have a question about proper Python style when it comes to having a main function in a module. I'm fairly new to Python - a few months of very-part-time tinkering (lots'o'Java at work, shrug); my apologies if this has been hashed out before. Random Googling didn't enlighten me, so instead I'll ask here. :) Take the following strmod.py (it's silly, I know): ---- import sys import getopt def main(sys_argv): try: opts, args = getopt.getopt(sys_argv, "clstu") for str_toPrint in args: for opt, arg in opts: if opt == '-c': str_toPrint = str_toPrint.capitalize() elif opt == '-l': str_toPrint = str_toPrint.lower() elif opt == '-s': str_toPrint = str_toPrint.swapcase() elif opt == '-t': str_toPrint = str_toPrint.title() elif opt == '-u': str_toPrint = str_toPrint.upper() print str_toPrint except getopt.GetoptError: pass if (__name__ == '__main__'): main(sys.argv[1:]) ---- Now, from what I have seen in terms of examples etc. would do something like (note the lack of sys_argv, and how sys.argv[1:] is imbedded in the getop.getopt call): ---- import sys import getopt def main(): try: opts, args = getopt.getopt(sys.argv[1:], "clstu") # ... print str_toPrint except getopt.GetoptError: pass if (__name__ == '__main__'): main() ---- This essentially makes strmod.main() uncallable by anything else that needs command line args, right? The first pattern allows calls like strmod.main("-t -s pRINT mE tHE sAME uNTESTED".split()) from elsewhere. It seems to me that this would be very helpful when writing low-level utilities that could be driven by other higher-level utilities without needing to fall back to OS calls, etc. So... Is this a good idea? Bad idea? Is there a better way? I'm just trying to not fall into any newbie pit traps ("Hey, what's at the bottom of this nifty hole?" ;). TIA, Eli -- Give a man some mud, and he plays for a day. Teach a man to mud, and he plays for a lifetime. WickedGrey.com uses SpamBayes on incoming email: http://spambayes.sourceforge.net/ -- From jamesl at appliedminds.com Thu Apr 8 19:52:47 2004 From: jamesl at appliedminds.com (James Lamanna) Date: Thu, 08 Apr 2004 16:52:47 -0700 Subject: Bug in struct.calcsize() ? Message-ID: <4075E5CF.7080203@appliedminds.com> Noticed this under 2.3.3: struct.calcsize('H') => 2 struct.calcsize('BBB') => 3 struct.calcsize('BBBH') => 6 Umm, shouldn't 'BBBH' return 5? Please CC me for I am not subscribed. -- James Lamanna From ed-no at spam-eepatents.com Thu Apr 8 12:46:22 2004 From: ed-no at spam-eepatents.com (Ed Suominen) Date: Thu, 08 Apr 2004 09:46:22 -0700 Subject: Distributing a Python based application on Linux References: <98013c51.0404080807.6f08f1a3@posting.google.com> Message-ID: One of the beauties of Linux is that you are neither required nor encouraged to put together the big, monolithic installation packages that Windows typically requires. Most (all?) distributions will include Python and most of the modules you'll be needing. -Ed Suominen Ramki wrote: > Hi !! > > I have written an install script to deploy some of my product rpms. > The install script does OS Version Check, OS Memory check, logging the > status of install into a log file amongst other things. > > Now the size of my product rpms is around 3 MB. If I am to distribute > Python along with the install, it is taking around 12 MB totally (the > python gz tar is around 9 MB), which is not ideal. > > Is there way I can avoid this by distributing only the bare minimum > Python related binary along with my rpms ? > > Any help would be appreciated. > > thanks, > Ram. From a-steinhoff at web.de Fri Apr 2 04:34:28 2004 From: a-steinhoff at web.de (root) Date: Fri, 02 Apr 2004 11:34:28 +0200 Subject: Just magic ... In-Reply-To: References: Message-ID: Jeff Epler wrote: > I don't know, and since the code you posted doesn't run I can't find > out. #it's only a subset of the code ... class SlaveParSet(QDialog): def __init__(self,parent = None, name=None, modal = 0, fl = 0, Conf='PROFIBUS', saddr= 0): if name == None: self.setName('SlaveParSet') self.config_name=conf self.slave_addr = saddr self.gsd_connect = sqlite.connect("gsd_db") self.gsd_curs = self.gsd_connect.cursor() # open project data base self.prj_connect = sqlite.connect("proj_db") self.prj_curs = self.prj_connect.cursor() self.ID = '' self.IMpos = 0 # insert selected module into installed modules def ModuleSelectionval(self, nr): module = str(self.ModuleSelection.text(nr)) #rebuild pos/module relationship Sel = str("""select mod_pos, mod_name, proj, saddr, mod_config_data, mod_prm_data from INSTMODULE where proj= %s and saddr = %s""") Key = (self.config_name, self.slave_addr) self.prj_curs.execute(Sel, Key) ins_list = self.prj_curs.fetchall() #ins_list is a list and contains now one tuple if len(ins_list): self.IMpos +=1 InsPos = self.IMpos Ins = str("""insert into INSTMODULE(mod_pos, mod_name, proj, saddr, mod_config_data, mod_prm_data) values (%s, %s, %s, %s, %s, %s)""") self.IMpos =0 for set in ins_list: setdata = (self.IMpos,) + set[1:] # set should reference a tuple but it refers to class instance .. WHY?? self.prj_curs.execute(Ins, setdata) self.InstModules.insertItem(set[1], self.IMpos) self.IMpos +=1 if InsPos == self.IMpos: self.InstModules.insertItem(new_item[1], self.IMpos) self.prj_curs.execute(self.Ins, new_item) self.IMpos +=1 if self.IMpos > 0: self.IMpos -= 1 self.InstModules.setCurrentItem(self.IMpos) self.prj_connect.commit() else: self.IMpos = 0 self.InstModules.clear() self.InstModules.insertItem(module, self.IMpos) self.InstModules.setCurrentItem(self.IMpos) > > >>>>self.IMpos =0 > > Traceback (most recent call last): > File "", line 1, in ? > NameError: name 'self' is not defined > > Jeff > From donn at u.washington.edu Wed Apr 28 14:11:43 2004 From: donn at u.washington.edu (Donn Cave) Date: Wed, 28 Apr 2004 11:11:43 -0700 Subject: Problem with socket References: <408f7917$0$27016$626a14ce@news.free.fr> Message-ID: In article <408f7917$0$27016$626a14ce at news.free.fr>, Thomas Herve wrote: ... > Ok I hope it's clear. My problem is that "select" only tests if there's > data on the socket, and not the state of the socket. I want to be able > to know if socket is "alive" or something like that. But I don't want > to make "send" in the client (stay passive). Then, if I know that my > socket is closed or my link down, I can try to reconnect periodically. Try a SO_KEEPALIVE option on the socket (setsockopt). That should (I would sort of expect anyway) raise an exception when the keepalive negotiation fails. The reaction won't be immediate, it may take hours to notice a dead connection. Donn Cave, donn at u.washington.edu From peter at engcorp.com Fri Apr 16 18:35:16 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 16 Apr 2004 18:35:16 -0400 Subject: md5.hexdigest() converting unicode string to ascii In-Reply-To: <77b925de.0404161337.3917ef56@posting.google.com> References: <77b925de.0404151450.5c1f720a@posting.google.com> <77b925de.0404161337.3917ef56@posting.google.com> Message-ID: uebertester wrote: > None of the suggestions seem to address the issue. sValue = > _winreg.QueryValueEx(y,"") returns a tuple containing the following > (u'http://', 1). The string u'http://' is added to the md5 object via > the update() and then hashed via hexdigest(). How do I keep the > unicode string from being converted to ascii with the md5 functions? > Or can I? You cannot. You missed the key fact, which is that Unicode strings are sequences of "characters" (roughly, 16-bit values), not sequences of bytes. MD5 is defined on byte sequences. *You* must specify the encoding scheme you want to use, by converting the string before passing it to the hash function. If you are trying to match the MD5 values calculated by some other tool, you must find out what encoding scheme that other tool was using (maybe by trial and error, starting with utf-8 probably). If this is just for your own purposes, simply pick a convenient scheme and encode consistently. md5.update(yourUnicode.encode('utf-8')) for example... -Peter From fnord at u.washington.edu Mon Apr 19 12:38:25 2004 From: fnord at u.washington.edu (Lonnie Princehouse) Date: 19 Apr 2004 09:38:25 -0700 Subject: Static Modules... References: Message-ID: Grzegorz Dostatni wrote in message news:... > I had an idea yesterday. (Yes, I know. Sorry). > > -------- BEGIN HERE ------ > import sys, inspect > > def autoload_exc(type, value, traceback): > modulename = value.args[0].split()[1][1:-1] > f_locals = traceback.tb_frame.f_locals > f_globals = traceback.tb_frame.f_globals > > exec "import " + modulename in f_locals, f_globals > exec traceback.tb_frame.f_code in f_locals, f_globals > > sys.excepthook = autoload_exc > > ------- END HERE ------- Nice hack! The earlier pundits have a point that explicit imports are a Good Thing for most code, but for the interactive session this will be really handy. (...considers putting it in .pythonrc) From fumanchu at amor.org Tue Apr 27 02:30:21 2004 From: fumanchu at amor.org (Robert Brewer) Date: Mon, 26 Apr 2004 23:30:21 -0700 Subject: Uploading files from a server Message-ID: drs wrote: > "Edward Diener" wrote in message > news:m1gjc.3688$g31.2919 at newsread2.news.atl.earthlink.net... > > What is the easiest way in Python in a web server to upload > a client file, > > once the file name on the client's machine has been entered, to a > directory > > on the server ? > > I think this is what you want ... this is for mod_python with > the publisher > handler. It will allow a user to upload a file and save it on > a server. It > provides no protection or checking, however. other server > configurations > will be slightly different. > > first, use a form tag and input tag like > >
ENCTYPE="multipart/form-data"> > > >
> > The above will get the file to your server. then use an > upload function > like: > > def upload_function(req, uploaded_file=None): > if uploaded_file: > fn1 = str(uploaded_file.filename).split('\\')[-1] > fn = fn1.split('/')[-1] > # the weird file splitting is because os.path on > Freebsd, where this > ran, > # didn't deal with win32 and unix file paths for > uploaded files > d = uploaded_file.read() > f = open('/save/path/%s' % fn, 'w') > f.write(d) > f.close() > return 'uploaded' > else: return 'no file' ...and if you don't know beforehand if you have an uploaded file, try something like: from mod_python import apache, util def read(self, request): # Retrieve the submitted CGI parameters from Apache/mod_python. # ONLY CALL ONCE per request. newData = util.FieldStorage(request, 1).list self.requestParams.clear() if newData is not None: for eachParam in newData: name = self.unicode(eachParam.name) if eachParam.filename: fileData = eachParam.file.read() filename = self.unicode(eachParam.filename) self.requestParams[name] = (filename, fileData) else: value = self.unicode(eachParam.value) self.requestParams[name] = value Robert Brewer MIS Amor Ministries fumanchu at amor.org From mogmios at mlug.missouri.edu Wed Apr 28 00:37:06 2004 From: mogmios at mlug.missouri.edu (Michael) Date: Tue, 27 Apr 2004 21:37:06 -0700 Subject: Is Perl *that* good? In-Reply-To: References: <108q51j4dscn7dc@corp.supernews.com> <87fzaqmm8t.fsf@strauser.com> <38ec68a6.0404262308.50029919@posting.google.com> Message-ID: <408F34F2.8060205@mlug.missouri.edu> >Regular expressions are like duct tape. They may not be the best tool >for everything, but they usually get the job done. > > Until you are in the middle of a vital project with a limited time to get the job done and suddenly all your duct tape starts to twist together incorrectly. :) From jbore at tjtech.com Tue Apr 13 13:31:21 2004 From: jbore at tjtech.com (Joseph T. Bore) Date: Tue, 13 Apr 2004 17:31:21 GMT Subject: interpreter limits References: <407c23bf$0$570$e4fe514c@news.xs4all.nl> Message-ID: Irmen de Jong writes: > Interesting. I know it's not of any help but 'back then', > most MUD engines did exactly this (at least, LP and MudOS did). > When a user-written module ran too long, it was aborted, to > avoid hanging the mud :) Indeed. In my case MOO is where I got the idea from. moop is also a side interest of mine where this becomes very important. Any idea if it's possible? should I write a PEP? jb From ville at spammers.com Thu Apr 15 10:00:47 2004 From: ville at spammers.com (Ville Vainio) Date: 15 Apr 2004 17:00:47 +0300 Subject: Difficulty Finding Python Developers References: <65cbc3dd.0404140641.3501fde8@posting.google.com> <65cbc3dd.0404141018.36d9d4ce@posting.google.com> Message-ID: Offering some comebacks in advance... >>>>> "Peter" == Peter Hansen writes: >> Mention that when you do find a >> Python programmer he'll probably be better than your average perl or >> Java programmer. Peter> And here I would ask, "Why do you say that? If there are Peter> so few of them around, how could anyone know whether Peter> they're better or worse? And wouldn't the best programmers I guess the braindeadness of perl can be argued as an indication of the quality of programmers - if the Perl people are unable to see how much the language stinks, they might be lacking in other areas of programming also. Java OTOH is the lowest common denominator, pretty much everyone knows it, which drags the average quality down. Peter> be using the most popular languages, because they would Peter> make more money that way?" Of course the best programmers are often mostly using the more popular languages because they are paid to do it (the r341 31337 use C++ ;-), but they *know* Python and would rather use it. -- Ville Vainio http://tinyurl.com/2prnb From wweston at att.net Thu Apr 1 11:42:57 2004 From: wweston at att.net (wes weston) Date: Thu, 01 Apr 2004 16:42:57 GMT Subject: splitting one dictionary into two In-Reply-To: <20040401153103.GC4577@jsaul.de> References: <20040401153103.GC4577@jsaul.de> Message-ID: jsaul wrote: > Hello all, > > I have to split a dict into two dicts. Depending on their values, > the items shall remain in the original dict or be moved to another > one and at the same time be removed from the original dict. > > OK, this is how I do it right now: > > dict1 = { "a":1, "b":3, "c":5, "d":4, "e":2 } > dict2 = {} > klist = [] > > for key in dict1: > if dict1[key] > 3: # some criterion > dict2[key] = dict1[key] > klist.append(key) > > for key in klist: > del dict1[key] > > print dict1 > print dict2 > > That means that I store the keys of the items to be removed from > the original dict in a list (klist) and subsequently remove the > items using these keys. > > Is there an "even more pythonic" way? > > Cheers, jsaul jsaul, I'll have a hack with small code. Nice that you can iterate while removing. wes dict1 = { "a":1, "b":3, "c":5, "d":4, "e":2 } dict2 = {} print dict1 for key,val in dict1.items(): if val > 3: # some criterion dict2[key] = val del dict1[key] print dict1 print dict2 From ae Mon Apr 12 19:16:39 2004 From: ae (A Evans) Date: Mon, 12 Apr 2004 16:16:39 -0700 Subject: Random Numbers and a thought References: <107m6f0t4i0gnff@corp.supernews.com> Message-ID: <107m8qvphrjd303@corp.supernews.com> > What "pattern" are you talking about? Well from what I understand about my last post numbers computers generate aren't truly random Quote from the link you gave me Computers are deterministic. They cannot create a truly random sequence in which we cannot predict even if we know all preceding elements - it may be a bit of work for us to actually sit down and do the figuring, but it is always possible. I would like to take a random number generated by a computer application then use my application to try and determine the pattern in that application Quote me if its impossible Basically I would like to create an application that takes a series of random numbers generated by a computer and searches for the pattern inside those numbers Sorry if I sound like I am repeating myself but I am just trying to explain myself to the best of my ability I guess if the numbers were between say 1 and 1000 it would take 1000 inputs to understand the pattern if not more I would like to solve it before that Cheers begin 666 img8.gif M1TE&.#EA$@`.`( ``````+^_OR'Y! $```$`+ `````2``X```(C#& 7R\VJ ?G$-(VG=O?*?WM7$)"%9-A9I2A!H:E6;R3-?V;14`.P`` ` end From thorsten at thorstenkampe.de Thu Apr 29 08:30:14 2004 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Thu, 29 Apr 2004 14:30:14 +0200 Subject: suggestions for using tuples instead of list (or vice versa) Message-ID: I found out that I am rarely using tuples and almost always lists because of the more flexible usability of lists (methods, etc.) To my knowledge, the only fundamental difference between tuples and lists is that tuples are immutable, so if this is correct, than list are a superset of tuples, meaning lists can do everything tuples can do and more. Is there any advantage for using tuples? Are they "faster"? Consume less memory? When is it better to use tuples instead of lists and when better to use lists instead of tuples? Thorsten From peter at engcorp.com Mon Apr 5 21:57:57 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 05 Apr 2004 21:57:57 -0400 Subject: Does Python compete with Java? In-Reply-To: References: <8b336527.0404051337.51bb4a1b@posting.google.com> <1073su4etm95p35@news.supernews.com> Message-ID: Roy Smith wrote: > They don't have one for Python, but I expect it would be something like > this: > > You create a Foot object and call its shoot() method. The bullet makes > a hole in your foot, but by that time you've gotten dragged into a huge > flamewar about the relative merits of spaces vs. tabs for indentation > and barely notice the pain. See Laura's excellent http://groups.google.com/groups?selm=slrna0f23p.511.QnickQm%40h00104b6bfa23.ne.mediaone.net and also a whole thread from late 2001 http://groups.google.ca/groups?threadm=fPBN7.961%24zX1.1625310%40typhoon.ne.mediaone.net -Peter From op73418 at mail.telepac.pt Fri Apr 2 08:13:16 2004 From: op73418 at mail.telepac.pt (Gonçalo Rodrigues) Date: Fri, 02 Apr 2004 14:13:16 +0100 Subject: Stackless Website down, Project gone, I'm dead. References: Message-ID: <4bpq609588953o4b1rno8339djt3u0fqpi@4ax.com> On Fri, 02 Apr 2004 04:30:08 +0200, in comp.lang.python you wrote: >Dear Former Stackless Users, > [rest of text snipped] I think this deserves a proper eulogy. Here is Wallace Stevens in "Cort?ge for Rosenbloom" with Rosenbloom replaced by Tismer (rhyme and metric is messed up but hey, what the heck, the guy deserves it even though by his own admission he sucks as a sys admin): Now, the wry Tismer is dead And his finical carriers tread, On a hundred legs, the tread Of the dead. Tismer is dead. They carry the wizened one Of the color of horn To the sullen hill, Treading a tread In unison for the dead. Tismer is dead. The tread of the carriers does not halt On the hill, but turns Up the sky. They are bearing his body into the sky. It is the infants of misanthropes And the infants of nothingness That tread The wooden ascents Of the ascending of the dead. It is turbans they wear And boots of fur As they tread the boards In a region of frost, Viewing the frost. To a chirr of gongs And a chitter of cries And the heavy thrum Of the endless tread That they tread. To a jangle of doom And a jumble of words Of the intense poem Of the strictest prose Of Tismer. And they bury him there, Body and soul, In a place in the sky. The lamentable tread! Tismer is dead. My dear Tismer, I only wish that your little grave in the sky that is going to be your eternal home is cozy and comfy. Adieu, G. Rodrigues From tdelaney at avaya.com Thu Apr 29 20:21:45 2004 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Fri, 30 Apr 2004 10:21:45 +1000 Subject: What is good about Prothon? Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE016BCCF8@au3010avexu1.global.avaya.com> has wrote: > Whereas Prothon does this: > > # Create object 'a' > a = Object() > a.x = 1 > > # Create objects 'b' and 'c' > b = a() > c = a() > > print a.x, b.x, c.x # --> 1 1 1 > > b.x = 4 > print a.x, b.x, c.x # --> 1 4 1 > > a.x = 9 > print a.x, b.x, c.x # --> 9 4 9 Urgh. I haven't been following closely, but this is exactly counter to what I would expect of a prototype-based language. The whole point of ptototypes IMO is to provide a *snapshot* as the base configuration of an object. So every attibute and method should be copied to the new object, and there is then no further connection between the prototype and the new object. Tim Delaney From sdahlbacSPAMSUX at abo.fi Tue Apr 27 17:08:04 2004 From: sdahlbacSPAMSUX at abo.fi (Simon Dahlbacka) Date: Wed, 28 Apr 2004 00:08:04 +0300 Subject: Passing through keywork arguments References: Message-ID: <408ecbc4$1@newsflash.abo.fi> wrote in message news:mailman.62.1083098978.25742.python-list at python.org... > If I have a class method that accepts keywork arguments, how may I pass > those arguments into a method call of some other class? This is some > namespace thing I'm not understanding and I can't seem to find any examples. def function_accepting_kwargs(**kw): # optionally check/mangle kw here (it is a dictionary) otherfunction(**kw) /Simon From sdementen at hotmail.com Wed Apr 28 06:17:48 2004 From: sdementen at hotmail.com (Sebastien de Menten) Date: 28 Apr 2004 03:17:48 -0700 Subject: Generic constructors and duplication of internal Python logic References: <87ekqq41ya.fsf@pobox.com> Message-ID: <8dad5312.0404280217.21c2cfd1@posting.google.com> Here is a metaclass for uber-lazy user :-) Concretely, at the creation of the class it takes the source of the __init__ function and add, at the first line of __init__, the line that sets the attributes : > self.foo, self.bar, self.baz, self.optional1, self.optional2 = > foo, bar, baz, optional1, optional2 Nothing is done for *args or **kwargs but they could also be assigned to some attributes of the class (like self.args and self.kwargs ?). Moreover, for really lazy users, the line for calling the __init__ of the father of the class (if necessary) > super(Father, self).__init__() could also be dynamically added #---------------------------------------------------- import inspect,re class autoArgInit(type): """ Replace any occurence of xxx in the class by a col version and a row version and yyy by its complementary row/col """ def __new__(cls,classname,bases,classdict): # get the __init__ function function_object = classdict["__init__"] # get the source of the function function_source = inspect.getsource(function_object) # detect indentation of the function definition and remove it such that def __init__ is at beginning of line indentation_level = re.match("( *)def (.*)\(",function_source).groups()[0] function_source = re.sub("^"+indentation_level,"",function_source) function_source = re.sub("\n"+indentation_level,"\n",function_source) # split the lines to add new lines easely function_lines = function_source.split("\n") # detect indentation inside the function indentation = re.match("(\s*)\S*",function_lines[1]).groups()[0] # take argument list without self args = inspect.getargspec(function_object)[0][1:] # create the line for assignment assign_code = indentation + ", ".join(map(lambda s: "self.%s"%(s),args)) + " = " + ", ".join(args) # insert it in the code function_lines.insert(1,assign_code) # join the code again new_function_source = "\n".join(function_lines) # evaluate it and replace the __init__ definition in classdict exec new_function_source in function_object.func_globals, classdict return type.__new__(cls,classname,bases,classdict) class test(object): __metaclass__ = autoArgInit def __init__(self, baz, top, foo=3, r = 5, *args, **kwargs): assert self.baz == baz assert self.top == top assert self.foo == foo assert self.r == r test(3,4,6) #---------------------------------------------------- Seb jjl at pobox.com (John J. Lee) wrote in message news:<87ekqq41ya.fsf at pobox.com>... > This is one of those things that I can't quite believe I've never > needed to do before. > > I've got a set classes, each of which has a set of attributes that all > behave very similarly. So, I have a class attribute (Blah.attr_spec > below), which is used by a mixin class to implement various methods > that would otherwise be highly repetitious across these classes. I'd > like to do the same for the constructor, to avoid this kind of > nonsense: > > class Blah(NamesMixin): > attr_spec = ["foo", "bar", "baz", > ("optional1", None), ("optional2", None)] > def __init__(self, foo, bar, baz, > optional1=None, optional2=None): > self.foo, self.bar, self.baz = \ > foo, bar, baz > self.optional1, self.optional2 = \ > optional1, optional2 > > So, I wrote a mixin class whose __init__ looks at the attr_spec > attribute, and uses args and kwds (below) to assign attributes in the > same sort of way as the special-case code above: > > class ArgsMixin: > def __init__(self, *args, **kwds): > # set attributes based on arguments passed in, as done > # manually in Blah.__init__, above > ... lots of logic already present in Python goes here... > > That immediately leads to duplication of Python's internal logic: I > have to check things like: > > -are there too many positional arguments? > -any unexpected keyword arguments? > -multiple keyword arguments? > -any duplication between positional and keyword arguments? > > etc. > > Surely there's some easy way of making use of Python's internal logic > here? For some reason, I can't see how. Can anybody see a way? > > > John From No.Spam.mc at No.Spam.mclaveau.No.Spam.com Thu Apr 29 14:29:35 2004 From: No.Spam.mc at No.Spam.mclaveau.No.Spam.com (Michel Claveau/Hamster) Date: Thu, 29 Apr 2004 20:29:35 +0200 Subject: PyLinda 0.1 References: Message-ID: Bonjour ! Pour des besoins propres, j'ai fait un logiciel qui ressemble ? PyLinda. Je l'ai appel? TPS (T?l?-Persistance-Server). Le principe de focntionnement est assez ressemblant. Par contre j'ai mis d'autres "connecteurs" : e-mail ; COM (Ole, sous windows) ; t?ches_planifi?es. J'ai ?galement ajout? la possibilit? "d'ex?cuter un message" (en fait le message est alors un script). Je me sers beaucoup de TPS, que j'installe syst?matiquement chez tous mes clients. C'est tr?s pratique pour ?changer des informations entre applications/postes/r?seaux. L'id?e est bonne, alors... continuez ! @-salutations -- Michel Claveau m?l : http://cerbermail.com/?6J1TthIa8B site : http://mclaveau.com From davidjtaylor at optushome.com.au Tue Apr 6 23:48:55 2004 From: davidjtaylor at optushome.com.au (sydneyguru) Date: Wed, 7 Apr 2004 13:48:55 +1000 Subject: Cookies Message-ID: <40737a05$0$20085$afc38c87@news.optusnet.com.au> Trying to write a python script that does the same thing my browser does when posting a form.(cgi) All works except for this. My browser has a cookie which it also sends, and the server insists on getting. So how can I replicate this under python? I've looked at cookie module but can't see how to use it to achieve this. Please help. From deetsNOSPAM at web.de Mon Apr 12 11:39:18 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Mon, 12 Apr 2004 17:39:18 +0200 Subject: How to kill a SocketServer? References: Message-ID: > The problem is, that I found no way to interrupt the blocking call to > self.rfile.readline(). Is there a way to do that? >From the SocketServerDocs: --------------- serve_forever() Handle an infinite number of requests. This simply calls handle_request() inside an infinite loop. --------------- So simply call handle_request yourself, like this: while self.run_me: s.server_forever() run_me is a variable that can be set to false in stop_server -- Regards, Diez B. Roggisch From mwilson at the-wire.com Sun Apr 4 23:24:16 2004 From: mwilson at the-wire.com (Mel Wilson) Date: Sun, 04 Apr 2004 23:24:16 -0400 Subject: How to assign a default constant value in a function declaration References: Message-ID: In article , "Vineet Jain" wrote: >The following does not work although it seems like something you should be >able to do. > >def someFunction(option=Constants.DEFAULT_VALUE): Certainly seems like it. What's it doing to make you say it's not working? Regards. Mel. From smallbee at rediffmail.com Thu Apr 1 06:35:56 2004 From: smallbee at rediffmail.com (Somesh Bartakkay) Date: 1 Apr 2004 03:35:56 -0800 Subject: Reliability of venster+ctypes on win32 Message-ID: <8f198e47.0404010335.6045400e@posting.google.com> I downloaded and tried a small dialog-dll's application with venster+ctypes+python 2.3 its working very well, but is it reliable to use in big projects ? or part of big projects ? wot are limitations in use ? wot are advantages/disadvantages of this combination over win32all package of Mark Hammond ? plz guide me before i starting using it ../ thanX in +vance ! somesh From FBatista at uniFON.com.ar Tue Apr 13 12:19:04 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Tue, 13 Apr 2004 13:19:04 -0300 Subject: Decimal data type issues Message-ID: People: Tim Peters reviewed the PEP 327, and asked some questions. Trying to answer those questions, I found that some items needs to be addressed with a comunity consensus. So, the next items are to be included in the PEP when the discussion finishes: Exponent Maximum ---------------- The Decimal number composes of three elements: A sign that can be 0 or 1, a tuple of digits where each can be 0..9, and an exponent. The exponent is an integer, and in the actual implementation exists a maximum value:: DEFAULT_MAX_EXPONENT = 999999999 DEFAULT_MIN_EXPONENT = -999999999 ABSOLUTE_MAX_EXP = 999999999 ABSOLUTE_MIN_EXP = -999999999 The issue is that this limit is artificial: As long it's a long, you should be able to make it as big as your memory let you. In the General Decimal Arithmetic Specification says: In the abstract, there is no upper limit on the absolute value of the exponent. In practice there may be some upper limit, E_limit , on the absolute value of the exponent. So, should we impose an artificial limit to the exponent? This is important, as there're several cases where this maximums are checked and exceptions raised and/or the numbers get changed. New operations -------------- Tim Peters found I missed three operations required by the standard. Those are: a. ``to-scientific-string``: This operation converts a number to a string, using scientific notation if an exponent is needed. The operation is not affected by the context. b. ``to-engineering-string``: This operation converts a number to a string, using engineering notation if an exponent is needed. c. ``to-number``: This operation converts a string to a number, as defined by its abstract representation. First we should agree the names of the methods, I propose: a. to_sci_string b. to_eng_string c. from_string The (a) and (b) methods are different from str, as this method just doesn't adjust the exponent at all. Regarding the method (c), the only difference with creating the decimal with Decimal(string) is that method (c) honors the context (if the literal contains more digits that the current precision the numbers get rounded, and gets rounded according to the round method specified in context, etc). For example, with a precision of 9 and with the name I proposed:: >>> Decimal('112233445566') Decimal( (0, (1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6), 0) ) >>> Decimal.from_string('112233445566') Decimal( (0, (1, 1, 2, 2, 3, 3, 4, 4, 6), 3L) ) Hash behaviour -------------- This item actually wasn't raised by Tim, but I found it when implementing the module. In the PEP I wrote that Decimal must be hashable. But what hash should it give? Should the following be true?:: hash(Decimal(25) == hash(25) hash(Decimal.from_float(25.35) == hash(25.35) hash(Decimal('-33.8')) == hash(-33.8) I don't think so. I think that hash(Decimal(...)) just should return a different value in each case, but no the same value that other data types. Thank you all for your feedback. . Facundo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA La informaci?n contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener informaci?n confidencial o propietaria, cuya divulgaci?n es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no est? autorizado a divulgar, copiar, distribuir o retener informaci?n (o parte de ella) contenida en este mensaje. Por favor notif?quenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magn?tico) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telef?nica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electr?nicos pueden ser alterados, motivo por el cual Telef?nica Comunicaciones Personales S.A. no aceptar? ninguna obligaci?n cualquiera sea el resultante de este mensaje. Muchas Gracias. -------------- next part -------------- An HTML attachment was scrubbed... URL: From balaji at email.arizona.edu Sat Apr 24 17:22:14 2004 From: balaji at email.arizona.edu (Balaji) Date: 24 Apr 2004 14:22:14 -0700 Subject: Please Help with references Message-ID: <494182a9.0404241322.8f3ec0a@posting.google.com> import __main__ tempbuffer= None permbuffer={} class E: def __init__(self): # print id(self) self.hasVar = False def doOperation(self,op,rightOperand): e = E() if self.__class__ == E: e.hasVar = self.hasVar elif self.__class__ == V or rightOperand.__class__ == V or \ (rightOperand.__class__ == E and rightOperand.hasVar == True): e.hasVar = True e.operator = op e.left = self e.right = rightOperand global tempbuffer global permbuffer print "bll" f = copy.copy(e) print f r =findNonTempBufferRef(tempbuffer) print r if r != 'tempbuffer': print "hello" permbuffer[r] =tempbuffer tempbuffer = f return e def relationalOperators(self,op,rightOperand): print self,rightOperand e=E() e.operator =op e.left=self e.right=rightOperand return e def __neg__(self): return self def __radd__(self,e2): return self.doOperation('+',e2) def __add__(self,e2): return self.doOperation('+',e2) class V(E): """ This is a variable for MPY""" def __init__(self): print "V", E.__init__(self) self.hasVar = True self.val = None def __str__(self): if self.val: # print "self.val *****" return str(self.val) else: return findRefTo(self) or "MPY Error! Printing unnamed variable." def findRefTo(obj): import expression # Needed to get access to main. vnames = vars(__main__) for name in vnames.keys(): if vnames[name] == obj: return name return None def findNonTempBufferRef(obj): import expression # Needed to get access to main. vnames = vars(__main__) print vnames for name in vnames.keys(): if vnames[name] == obj: return name return None ************************************************** This my code... On interpretor if i create x=V() and y=V() creates two instances of class variable which inherits from expression class E. now if i say x+y and then c=x+y and ce=x+y i think i loose the original one... i want to store in a permbuffer all asignments made.. after assigning c and ce i want a copy of both in a permbuffer.. Iam at my witends .. Please help... Balaji From noemail at noemail4u.com Tue Apr 20 08:04:30 2004 From: noemail at noemail4u.com (Daniel 'Dang' Griffith) Date: Tue, 20 Apr 2004 12:04:30 GMT Subject: Proposed PEP: Treating Builtins as Constants in the Standard References: <5d83790c.0404171557.3db69f48@posting.google.com> Message-ID: <097808fe24c7cc9771e446d5bddfe91d@news.teranews.com> On Mon, 19 Apr 2004 08:09:56 -0400, Peter Hansen wrote: [snip] ... >automated testing. The most easily demonstrated one is where >the builtin open/file calls are replaced with a simulated ("mock") >file system which applies to *all* modules, not just a single >module under test. This functionality is critical to some people >using Python with the Test-Driven Development approach to software. Isn't this the use case for AOP you were looking for? --dang From theller at python.net Thu Apr 15 16:10:18 2004 From: theller at python.net (Thomas Heller) Date: Thu, 15 Apr 2004 22:10:18 +0200 Subject: Wrapper round x86 Assembler References: <8089854e.0404082353.7bf163a2@posting.google.com> Message-ID: michael at foord.net (Fuzzyman) writes: > There might be a really good reason why this hasn't been done *or* > someone might have done it and I just can't find it..... *but* > > what about a wrapper to an assembler (presumably for x86 assembly !) > !! > I just wrote some code doing binary operations which would have been > about a zillion times faster in a few lines of assembly code. > > I also have fond memories of programming in BBC Basic which had an > inline assembler - so you could wrap your assembly program in Basic. > It meant some commercial games started with Basic ! > > Anyway - it would be easy to reserve some memory with a string like > object to pass to an 'assembly object' and allow some really nifty > (and fast) stuff ?? For simple algorithms it would be very neat. > Avoiding memory overflow etc would be up to the assembly code 'chunk' > of course. The following has been reposted by Bradley Schatz to the ctypes mailing list, it may indeed contain what you want, and it *is* very interesting. The original post was to the bugtraq mailing list (or so): from oliver.lavery at sympatico.ca Today marks another solar cycle I've spent on this planet. To celebrate I'd like to share one of my toys with all of you. Adder is a tool I wrote for myself, so that I could experiment with runtime modification of binary applications. I've found it really useful for prototyping run-time patches, understanding the effects and possibilities of call-hooking and other run-time program tweaks; that sort of thing. I hope you might find it useful too... Binary: http://www.rootkit.com/vault/x3nophi1e/adder-0.3.3-win32.zip ( NT 4 / 2000 / XP / 2003 ) Source: http://www.rootkit.com/vault/x3nophi1e/adder-0.3.3-src.zip Documentation: http://www.rootkit.com/vault/x3nophi1e/adder-manual.zip ( please read the installation instructions in here. ) The way it works is fairly simple. Adder allows you to inject a python interpreter into any win32 process. That interpreter then runs a script within the context of your target process which is able to instrument and modify the target in any way it sees fit. Included are a extensions to the python language that provide: - safe pointer support - execution path hooking in python and C++. Hooks can be installed at something close to instruction granularity. - x86 instruction manipulation. (based on z0mbie's ADE32 engine) - programmable x86 instruction disassembler. (a win32 port of libdisasm from The Bastard) - x86 assembler. (Dave Aitel's Mosdef 1.1) These features make it easy to play with the deep majik of really low-level code hacking in an efficient, sophisticated, high-level language. So adder is a sort of meta-tool which you might use to script things like: - dynamic analysis. Hook every function in jscript.dll and graph which ones execute when a HTML page's script runs. - API interception. Should IE really be allowed to open an .exe straight of the web? - run-time patching. Get rid of those pesky bugs. - binary forensics. Packers aren't so hard to crack when they run. Performance and stability are pretty good at this point. Since it's a tool I wrote for my own use, there are lots of rough edges that need to be cleaned up. I've been waiting to find the time to fix these for ages and never seem to. So you'll excuse the occasional glitch. Please tell me if you find something really horrid. Hope you all find this interesting, and maybe even useful. ~x ---------- From vincent at visualtrans.de Thu Apr 15 04:21:57 2004 From: vincent at visualtrans.de (vincent wehren) Date: Thu, 15 Apr 2004 10:21:57 +0200 Subject: charset conversion routine? In-Reply-To: References: Message-ID: Joe Wong wrote: > Hi, I am trying to use python to convert UTF8->BIG5 and GB->BIG5 charset. Is it possible and how to do it? From the manual I read something about unicode and locale, but I couldn't get a clear direction on how to make it work. > > Thanks in advance, > > -- Wong > You'll need the cjk-codecs package. You can find it via http://cjkpython.i18n.org/ Regards, -- Vincent Wehren From newsgroups at jhrothjr.com Sat Apr 3 09:10:29 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 3 Apr 2004 09:10:29 -0500 Subject: Parrot for Python References: <930ba99a.0404030251.c2d2107@posting.google.com> Message-ID: <106theugbjm8l30@news.supernews.com> "Sridhar R" wrote in message news:930ba99a.0404030251.c2d2107 at posting.google.com... > Hi, > > I come across the Parrot project. Seems like it is a better > compromising alternative for .NET and Java. That is, we can develop > applications in Python (for productivity) and still can interact with > components written in other languages, as they were compiled to the > parrot byte code. > > But my concern is, how will Python interoperate with Parrot. Since, > Python has strong interospection, won't it be difficult to generate > parrot code from python source file. I believe there were some people working on a Python port to Parrot a while ago, but they lost interest when the then current Parrot implementation was insufficient to handle what they wanted to do. It's all a volunteer effort; it'll get done if enough people want to get together to get it done. John Roth From CousinStanley at hotmail.com Thu Apr 8 00:53:29 2004 From: CousinStanley at hotmail.com (Cousin Stanley) Date: Wed, 7 Apr 2004 21:53:29 -0700 Subject: pyAlbum.py - Python Album Generator References: Message-ID: Premshree .... Thanks for making your pyAlbum.py program available .... A glimpse of what the Arizona desert east of Phoenix toward Globe on highway US 60 looked like last Sunday April 04, 2004 .... http://fastq.com/~sckitching/Album_01 Photography by .... John C. Schluterbusch The slide show was generated using a locally edited version of your Python program pyAlbum .... http://premshree.resource-locator.com/python/pyAlbum.py It took about 100 Seconds on this machine to generate the SlideShow for 31 images, which includes .... Generating ThumbNails Re-Sizing Images Writing a CSS Style Sheet Writing the Index HTML Page Generating the Individual HTML Pages This machine .... Compaq ...... 250 MHz Memory ...... 192 MB System ...... Win98_SE Python ...... 2.3 Enthought Edition PIL ......... 1.1.4 So, for a S L O W machine, 100 Seconds ain't too bad .... The edited version that I used .... http://fastq.com/~sckitching/Python/pyAlbum.py o Re-coded some of the l o n g string concatenations and ''' Triple Quoted String ''' % ( w , x , y , z ... ) substitutions into join( list_xxx ) function calls which seemed a bit more readble/editable o Added a prompt and code for Including/Excluding links to Full-Size images o All other changes are basically coding style cosmetics .... Thanks again for a useful Python program .... -- Cousin Stanley Human Being Phoenix, Arizona From elainejackson7355 at home.com Thu Apr 8 01:05:43 2004 From: elainejackson7355 at home.com (Elaine Jackson) Date: Thu, 08 Apr 2004 05:05:43 GMT Subject: list comprehensions References: Message-ID: I still need to digest it, but yes, I think it will help. Thanks. "Paul McGuire" wrote in message news:ku0dc.74742$o_.33729 at fe1.texas.rr.com... | "Elaine Jackson" wrote in message | news:yjZcc.42823$Pk3.9547 at pd7tw1no... | > | > List comprehensions don't work the way you intuitively expect them to | work. I | > realize many people have no intuitions about how list comprehensions | 'should' | > work, so if you recognize yourself in this description, feel free to go | back to | > whatever you were doing before. If you're still here, though, I invite you | to | > consider the following definition: | > | > partitions = lambda n: [[n]]+[[k]+x for x in partitions(n-k) for k in | > range(1,n)] | > | > As defined above, the function raises an exception when you call it ('k' | > referenced before assignment). For the sake of clarity, here is workable | code | > expressing the same intention: | > | > def partitions(n): | > reVal=[[n]] | > for k in range(1,n): | > for x in partitions(n-k): | > reVal.append([k]+x) | > return reVal | > | > So I guess what I want to ask is: Can somebody explain the semantics of | list | > comprehensions to me? Or even better: Can somebody tell me where to look | in the | > documentation to find out about list comprehensions? All donations | gratefully | > received. | > | > Peace | > | > | Elaine - | | I suspect you wrote your listcomp by thinking this is an inversion of the | nested for loops. That is, if you think of some arbitrary nesting of loops | as: | | for i in firstRange: | for j in secondRange: | for k in thirdRange: | ...... | | | then you looked at the list comp as working its way inside out, since it | starts with the part. | | But as the other posters have already stated, even though the listcomp | starts with the most deeply nested body, the remaining 'for... for ... | for... ' clauses match the nested loops, as if you had just removed the | colons and copied them all onto one line. So the listcomp ends up looking | like: | | [ for i in firstRange for j in | secondRange for k in thirdRange...] | | If you want some kind of model for how to conceptualize this, then I'd say | that a listcomp starts with its most important part being the actual list | element assembly/definition, followed by the iteration specifiers in | successive outer-to-inner order, that will get the loop variables to the | necessary values to satisfy the list assembly code. | | You also asked for doc references. The Python Tutorial includes an obscure | example (you have do a bit of in-your-head multiplication to get it), but | try these other articles describing listcomps when they were a new feature: | http://www-106.ibm.com/developerworks/linux/library/l-py20.html | http://python.org/2.0/new-python.html#SECTION000600000000000000000 | Perhaps the tutorial could lift some of the examples from these other pages, | as I'm sure people don't necessarily go back to the "What's New" pages for | version x-2, x-3, etc. | | HTH, | -- Paul | | | | From python at holdenweb.com Tue Apr 13 10:11:04 2004 From: python at holdenweb.com (Steve Holden) Date: Tue, 13 Apr 2004 10:11:04 -0400 Subject: Random Numbers and a thought In-Reply-To: <407BDF9C.1050908@engcorp.com> References: <107m6f0t4i0gnff@corp.supernews.com> <107m8qvphrjd303@corp.supernews.com> <407BDF9C.1050908@engcorp.com> Message-ID: Peter Hansen wrote: > Moosebumps wrote: > >> Yeah, this is not really a python question at all... go ask on >> sci.math or >> comp.programming and have people discourage and flame you there. : ) > > > Was anyone flaming anyone here? Of course not, you idiot :-) couldn't-resist-ly y'rs - steve From cliechti at gmx.net Fri Apr 16 19:43:46 2004 From: cliechti at gmx.net (Chris Liechti) Date: Fri, 16 Apr 2004 23:43:46 +0000 (UTC) Subject: Wrapper round x86 Assembler References: <8089854e.0404082353.7bf163a2@posting.google.com> <4dKdnQlIXMIXIevdRVn-gg@powergate.ca> <8089854e.0404100204.504186a0@posting.google.com> <8089854e.0404122329.5dfe5ce1@posting.google.com> <8089854e.0404132323.3283390@posting.google.com> <8089854e.0404141105.37d09320@posting.google.com> <8089854e.0404160530.5b7c23aa@posting.google.com> Message-ID: michael at foord.net (Fuzzyman) wrote in news:8089854e.0404160530.5b7c23aa at posting.google.com: > Greg Ewing wrote in message > news:... >> Fuzzyman wrote: >> > The only compielr I have is gcc under mingw - and I'm not at all >> > sure it's set up right. Does pyrex still need a C-compiler or *is* >> > pyrex a compiler ? >> >> It needs a C compiler. MinGW should be fine >> (once you get it set up properly, anyway:-). > > Yeah - I'm having great fun getting it set up. > MinGW seems easy enough to install - I've even compiled example C > programs with gcc - but getting disutils to use it is another > matter... add the bin dir of mingw to the PATH variable, do the pexports stuff to create an import lib and then use e.g. python setup.py build --compiler=mingw32 see here for the pexports part: http://docs.python.org/inst/tweak-flags.html#SECTION000620000000000000000 chris -- Chris From tim.one at comcast.net Wed Apr 7 01:07:56 2004 From: tim.one at comcast.net (Tim Peters) Date: Wed, 7 Apr 2004 01:07:56 -0400 Subject: Type checking inside a C extension... doesn't throw exception on failure In-Reply-To: Message-ID: [Andrew MacIntyre] >> First rule of using the Python C API: _always_ check the return >> value of API functions. [Jon Perez] > This only applies to API functions which return PyObject*, right? No, it applies to all API functions that return a value (not all do). > ...because it is not hard to find instances in the source code for > the modules that come with Python where, for example, > PyTuple_SetItem()'s return value is not checked for. Strictly speaking, those are bugs in the core, and are mostly in very old modules. When new code is written in the core that wants to skip the error checks done by PyTuple_SetItem, because it "knows" nothing can go wrong, it uses the macro PyTuple_SET_ITEM instead. All non-checking uses of PyTuple_SetItem() should be reviewed for correctness, and replaced with PyTuple_SET_ITEM() invocations instead whenever they are in fact provably correct (or changed to check the return value when they're not provably correct). Even API functions that return ints or doubles need to be checked! In those cases, there may not be an unambiguous "this is an error return" value, and then fancier code is needed; e.g., long_float's static PyObject * long_float(PyObject *v) { double result; result = PyLong_AsDouble(v); if (result == -1.0 && PyErr_Occurred()) return NULL; return PyFloat_FromDouble(result); } There are at least 3 ways in which PyLong_AsDouble() can fail, but -1.0 is also a legitimate return value, so PyErr_Occurred() is needed to distinguish "-1.0 is a normal return" from "-1.0 is an error return". From urnerk at qwest.net Thu Apr 15 00:09:57 2004 From: urnerk at qwest.net (urnerk at qwest.net) Date: Thu, 15 Apr 2004 00:09:57 -0400 Subject: Kuhlman's tutorials pretty good References: <407E1E20.D0216E92@doe.carleton.ca> Message-ID: I like Dave Kuhlman's tutorials as well. They seem to be in the right place at the website now: http://www.python.org/topics/learn/prog.html However, in looking over 201, I see some scrambling of source code examples, vs. surrounding text, e.g. when he's getting into regular expressions, some of the examples have nothing to do with the explanations that follow. Notably sections 2.2, 2.3, 2.4, 2.5. 2.6 is mostly OK except: """ Put together a new string with string concatenation from pieces of the original string and replacement values. You can use string slices to get the sub-strings of the original string. In our case, the following gets the start of the string, adds the first replacement, adds the middle of the original string, adds the second replacement, and finally, adds the last part of the original string: lineDef = delimitedList(fieldDef) """ Kirby Fred Ma wrote: > I find Dave Kuhlman's tutorials very good, and very complementary > to the stock tutorial that is part of the python download. Even > when they cover the same thing, if it's not that clear in one > tutorial, reading the other makes it quite clear. But one can > swim around the Python website for ages before rummaging into > Kulhman's tutorials (Python 101 and 201). I thought it was easy > to run into a few days ago. Has the website changed? Aren't > Kuhlman's tutorials good enough to sit shoulder-to-shoulder with > the other links in "Python for Programmers"? I thought that's > where it was before. Granted, it's got a few sections (like > Using Regular Expressions and Match Objects, 2.3 & 2.4 of 201) > that need editting, but invaluable nevertheless. From the point > of view of someone still waiting for Learning Python to come. > > Fred From davidb at mcs.st-and.ac.uk Thu Apr 15 08:05:00 2004 From: davidb at mcs.st-and.ac.uk (David Boddie) Date: 15 Apr 2004 05:05:00 -0700 Subject: pyKDE won't build References: Message-ID: <4de76ee2.0404150405.6ac2f50d@posting.google.com> Steven wrote in message news:... > Hi folks, > I'm trying to install pyKDE. > python, pyQT and sip are installed and working. > > I run python build.py and get the error shown at the end. > sip -V gives 3.10.1 (3.10.1-192) > PyQt version is 3.11 Unfortunately, PyKDE 3.8 isn't guaranteed to work with versions of SIP or PyQt later than SIP 3.8 and PyQt 3.8. A later version of PyKDE which works with both KDE 3.2 and more recent versions of PyQt and SIP is scheduled for release in the near future. Meanwhile, you might want to try getting hold of compatible versions of PyQt and SIP. > From the traceback it detects the wrong sip version, but I don't know how to > make it detect the correct version. There is only one version of sip on my > system. (slackware linux 9.1) This all sounds familiar. You may want to take a look at the PyKDE mailing list archives at http://mats.imk.fraunhofer.de/pipermail/pykde/ or even subscribe and repost details of your problem there. > I don't understand python, but need pyKDE to make something else work. Hopefully, you won't need to understand Python to get it all working, although you may wish to look at it more closely once you see what can be achieved with Python, PyQt and PyKDE. David From deetsNOSPAM at web.de Thu Apr 15 10:10:42 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Thu, 15 Apr 2004 16:10:42 +0200 Subject: Python style of accessing bools? References: Message-ID: > In other words, do you use accessors or just access the variable directly? As a lot of things in programming, its a matter of taste. Now I personally think that using accessors that simply return the value without any computation are useless, as python has no real concept of private/protected members. Now if someone needs to protect her members from unwanted access, IMHO properties are the way to go. And I don't like the overhead of defining additional accessors - they're sort of clumsy and they don't allow for nice assignments like this: foo.bar = -- Regards, Diez B. Roggisch From anton at vredegoor.doge.nl Fri Apr 30 06:56:03 2004 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Fri, 30 Apr 2004 12:56:03 +0200 Subject: Feedback on Sets, and Partitions References: Message-ID: <4092315d$0$133$3a628fcd@reader1.nntp.hccnet.nl> David Eppstein wrote: >BTW, here is some code for generating these numbers. I think it's a >little interesting that one can write the obvious one-line definition >for factorials, forgetting the base case, and then make it work anyway >via the magic of memoization. Something to think about in connection >with PEP 318... [snip some interesting code] Here's a more tedious way to do the same, but this code is more "graphic" in that it shows how one can build up a triangle of numbers line by line according to some mutation prescription. Depending on the kind of prescription one ends up with pascals triangle or the triangle for bell numbers. def pascal_mutate(L): R = [L[i] + L[i+1] for i in xrange(len(L)-1)] return [1] + R + [1] def stirling_mutate(L): R = [L[i] + (i+2)*L[i+1] for i in xrange(len(L)-1)] return [1] + R + [1] def triangle(mutator): L = [1] while 1: yield L L = mutator(L) def listify(gen): cache = [] def func(n): while len(cache) <= n: cache.append(gen.next()) return cache[n] return func def triangle_function_generator(mutator): T = listify(triangle(mutator)) def func(n,k): return T(n)[k] return func pascal = triangle_function_generator(pascal_mutate) stirling_raw = triangle_function_generator(stirling_mutate) def noverk(n,k): return reduce(lambda a,b: a*(n-b)/(b+1),range(k),1) def stirling(n,k): return stirling_raw(n-1,k-1) def bell(n): return sum([stirling(n,i) for i in range(1,n+1)]) def test(): n,k = 10,4 assert pascal(n,k) == noverk(n,k) print bell(25) if __name__=='__main__': test() #prints 4638590332229999353 Anton From martin at v.loewis.de Mon Apr 5 19:38:32 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 06 Apr 2004 01:38:32 +0200 Subject: Does Python compete with Java? In-Reply-To: <8b336527.0404051337.51bb4a1b@posting.google.com> References: <8b336527.0404051337.51bb4a1b@posting.google.com> Message-ID: kk wrote: > I'd like to know if you guys think Python really has a chance to > compete with Java, .NET, and any other commercially backed language. Python, by nature, does not compete: it is a product, and only producers of a product can compete with producers of other products; products never ever compete with one another (a product has no soul, and no goal). Whether the makers of Python compete with the makers of Java or .NET is an interesting question, and one that is difficult to answer. The makers of Python a free software developers, many of them volunteers. The maker of Java is Sun Microsystems, the maker of .NET is Microsoft. The Python makers have very different motivations, and for some of them, competing with Sun may be a motivation - others could not care less. The same holds for the users: Some users of Python compete with some users of Java, whereas others don't. This continues into education: authors of Python books typically compete with authors of Java books, except for authors of the Python tutorial, which likely don't compete with anybody (except perhaps that authors of Python books have to compete with the authors of the Python tutorial and other free online documentation). The mission of the Python Software Foundation is (among others), to publicize, promote the adoption of, and facilitate the ongoing development of Python-related technology and educational resources. Whether or not that makes the PSF a competitor of Sun Microsystems, I don't know. > The reason I ask is I think it is important to have a "popular" > well-supported Open Source language to compete with the big players. Why is that important? > PHP seems to have some momentum in popularity, but I much prefer > Python as a language. Python has much to offer over Java, VB, etc... > Maybe the best chance it has is to ride on the coat-tails of .NET > (Python.NET) and the JVM (Jython). If Python works for you, just go ahead and use it. Consider all advantages and risks, and weigh for yourself. Regards, Martin From alexanro at stud.ntnu.no Sun Apr 18 20:23:13 2004 From: alexanro at stud.ntnu.no (=?iso-8859-1?q?Alexander_R=F8dseth?=) Date: Mon, 19 Apr 2004 02:23:13 +0200 Subject: Pygame References: Message-ID: Hm, I guess you're right about that. :) - Alexander From davidf at sjsoft.com Thu Apr 22 03:55:04 2004 From: davidf at sjsoft.com (David Fraser) Date: Thu, 22 Apr 2004 09:55:04 +0200 Subject: Python use large scale projects In-Reply-To: <47fc6058.0404212327.24163290@posting.google.com> References: <47fc6058.0404212327.24163290@posting.google.com> Message-ID: limor wrote: > Hi, > I am considering using Python in a new testing tool application we > intend to build for out product. > I must get references before starting develope in this language , > since although lots of good things are said about this language , I > still have my doubts how can it compete with languages like C++ and > Java. > I have found te sytax and some features if the language not as > problematic in maintenance prospective (although I keep reading the > contrary everywhere I read somthing about python) . For people who are > used to write in C and C++ I think the python being typless makes the > code hard to maintain. On the contrary, I found coming from a C/C++ background that the dynamic typing was an advantage. > But still, In many prespective the language seems to really suit my > needs and I would really like to talk with people who are using Python > in their company to medium-large scale project. > > I'd really like to talk with someone who is using this language in his > work for large scale projects. > 10x allot for whoe ever reply me on that. > With Regards, > limor. We use Python for a few projects that are about 10000 lines of code. Note however that this would probably be 40000 lines in C++. The compact simplicity of Python has made this code much easier to manage... David From michele.simionato at poste.it Sun Apr 25 02:22:17 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 24 Apr 2004 23:22:17 -0700 Subject: Richards bench benchmark References: <6748553f.0403291446.27fb7b93@posting.google.com> <6748553f.0403300836.744e3e22@posting.google.com> <6748553f.0403302317.4595844@posting.google.com> <6748553f.0404060802.6e0d708c@posting.google.com> <6748553f.0404211342.7591cd8e@posting.google.com> <40899240.7020508@engcorp.com> Message-ID: <95aa1afa.0404242222.15101178@posting.google.com> Peter Hansen wrote in message news:<40899240.7020508 at engcorp.com>... > http://www.engcorp.com/main/projects/PyBench . > The above page is a wiki ... I see that you use ZWiki; I started using it few days ago and I like it. My question: did you succeed in getting the testing framework (http://www.zwiki.org/FitTests) to work? It seems it is very new and it does not work out of the box, at least for me. Alternatively, which Web-based test framework (Fitnless-like) would you suggest for Python? The question is of course open to everybody having expertise in the area. Michele Simionato From __peter__ at web.de Thu Apr 15 04:02:14 2004 From: __peter__ at web.de (Peter Otten) Date: Thu, 15 Apr 2004 10:02:14 +0200 Subject: Generic constructors and duplication of internal Python logic References: <87ekqq41ya.fsf@pobox.com> Message-ID: John J. Lee wrote: > This is one of those things that I can't quite believe I've never > needed to do before. > > I've got a set classes, each of which has a set of attributes that all > behave very similarly. So, I have a class attribute (Blah.attr_spec > below), which is used by a mixin class to implement various methods > that would otherwise be highly repetitious across these classes. I'd > like to do the same for the constructor, to avoid this kind of > nonsense: > > class Blah(NamesMixin): > attr_spec = ["foo", "bar", "baz", > ("optional1", None), ("optional2", None)] > def __init__(self, foo, bar, baz, > optional1=None, optional2=None): > self.foo, self.bar, self.baz = \ > foo, bar, baz > self.optional1, self.optional2 = \ > optional1, optional2 > > So, I wrote a mixin class whose __init__ looks at the attr_spec > attribute, and uses args and kwds (below) to assign attributes in the > same sort of way as the special-case code above: > > class ArgsMixin: > def __init__(self, *args, **kwds): > # set attributes based on arguments passed in, as done > # manually in Blah.__init__, above > ... lots of logic already present in Python goes here... > > That immediately leads to duplication of Python's internal logic: I > have to check things like: > > -are there too many positional arguments? > -any unexpected keyword arguments? > -multiple keyword arguments? > -any duplication between positional and keyword arguments? > > etc. > > Surely there's some easy way of making use of Python's internal logic > here? For some reason, I can't see how. Can anybody see a way? You could use a noop method check_attrs() to define the argspec. check_attrs() is then called from the mixin's __init__() just to check that the parameters comply. import inspect def make_attrspec(f): a = inspect.getargspec(f) names = a[0] if names[0] in ["self", "cls"]: # XXX for now relies on naming convention del names[0] defaults = a[3] for i in range(-1, -len(defaults)-1, -1): names[i] = names[i], defaults[i] return names class ArgsMixin: def __init__(self, *args, **kwds): self.check_attrs(*args, **kwds) class Blah(ArgsMixin): def check_attrs(self, foo, bar, baz, optional1="first", optional2="second"): pass attr_spec = make_attrspec(check_attrs) print Blah.attr_spec Blah(1, 2, 3) Blah(1, 2, optional1="o1", baz=99) Blah(1, 2) I'm not sure whether check_attrs() should be a class or static method, so I made it a standard method for now. Todo: automagically "normalize" the argument list, e. g. convert Blah(1, 2, optional1="o1", baz=99) to Blah(1, 2, 99, optional1="o1"). A workaround would be to make them all keyword arguments kwds.update(dict(zip(Blah.attr_spec, args))) after the self.check_attrs() call. Peter From dd55 at cornell.edu Wed Apr 28 10:43:38 2004 From: dd55 at cornell.edu (Darren Dale) Date: Wed, 28 Apr 2004 10:43:38 -0400 Subject: dynamically naming fields? Message-ID: I am transitioning from Matlab and am not very literate in Python terminology.... I want to load data from a file, and I want to use the header to name my fields... for example, I have a file containing "time counter" in the header, how do I create Sample.time and Sample.counter? In Matlab it would be Sample.(string) thanks, Darren From jobs at signpostnetworks.com Mon Apr 12 09:48:06 2004 From: jobs at signpostnetworks.com (Frank Steele) Date: Mon, 12 Apr 2004 13:48:06 GMT Subject: US-Atlanta Python developer Message-ID:
SignPost Networks Atlanta, Georgia (Midtown) Job Description: Python developers - We're seeking Python developers to help us build and manage a network of electronic signs deployed in U.S. transit stations. Contract work, 3-6 months duration. Job Requirements: - A candidate will have experience developing python web applications that interface with relational databases. - An ideal candidate will additionally possess experience designing graphical user interfaces. - Must be comfortable working solo, or on a small team with minimal supervision. - Strong preference for metro Atlanta residents, because of the need to develop against specialized hardware. Contract position on a project basis. We will consider proposals from software development groups. We will begin interviewing as we receive resumes. Candidates with UI experience are asked to provide links or a portfolio of past work. Contact: Mark McClain E-mail contact: jobs at signpostnetworks.com Please send resume, link(s) to previous project(s), hourly salary requirements. Web: http://www.signpostnetworks.com/ From trasno-bounces at ceu.fi.udc.es Tue Apr 27 19:32:24 2004 From: trasno-bounces at ceu.fi.udc.es (trasno-bounces at ceu.fi.udc.es) Date: Wed, 28 Apr 2004 01:32:24 +0200 Subject: Your message to Trasno awaits moderator approval Message-ID: Your mail to 'Trasno' with the subject Status Is being held until the list moderator can review it for approval. The reason it is being held: SpamAssassin identified this message as possible spam Either the message will get posted to the list, or you will receive notification of the moderator's decision. If you would like to cancel this posting, please visit the following URL: http://ceu.fi.udc.es/cgi-bin/mailman/confirm/trasno/ddf67f492e5080c88721d9aeff9e5d7f85e41085 From use_reply-to at empty.invalid Thu Apr 1 12:15:02 2004 From: use_reply-to at empty.invalid (jsaul) Date: Thu, 1 Apr 2004 19:15:02 +0200 Subject: splitting one dictionary into two In-Reply-To: References: <20040401153103.GC4577@jsaul.de> Message-ID: <20040401171502.GD4577@jsaul.de> * Peter Otten [2004-04-01 18:46]: > jsaul wrote: > > > dict1 = { "a":1, "b":3, "c":5, "d":4, "e":2 } > > dict2 = {} > > klist = [] > > > > for key in dict1: > > if dict1[key] > 3: # some criterion > > dict2[key] = dict1[key] > > klist.append(key) > > > > for key in klist: > > del dict1[key] > > > > print dict1 > > print dict2 > > Only a minor change to do away with the temporary list: > > for key in dict1: > if dict1[key] > 3: # some criterion > dict2[key] = dict1[key] > > for key in dict2: > del dict1[key] Hi Peter and others who responded so quickly, I notice now that I forgot to mention an important condition, namely that in real life dict2 is already existing and may have become huge. That's the reason why I need to somewhere save only those items which I most recently removed from the 1st dict, as I want to avoid iterating over the while dict2. In real life, dict1 contains pending jobs which, after they are done, are moved to a second dict for post processing. Sorry for the confusion. I think the most "pythonic" candidate is actually the version suggested by Larry, namely dict1 = { "a":1, "b":3, "c":5, "d":4, "e":2 } dict2 = {} # in real life, dict2 already exists for key in dict1.keys(): if dict1[key] > 3: dict2[key] = dict1.pop(key) print dict1 print dict2 Cheers, jsaul From peter at engcorp.com Mon Apr 5 11:32:52 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 05 Apr 2004 11:32:52 -0400 Subject: slightly OT: BUT NEEDs to be said In-Reply-To: <4078daf265c69e9353e8af72542da703@dizum.com> References: <4078daf265c69e9353e8af72542da703@dizum.com> Message-ID: Nomen Nescio wrote: > Hi I downloaded this document about Python recently: > > I loved the cute little Snake graphic. Some people despise snakes, and are terrified of them. > I think it would be great for Python.org/people behind Python to adopt this > as an official mascot and DROP the god awful references to Monty Pythons's > Flying Circus. It is the later which is causing a slow take up and reluctance > of many individuals using Python. MPFC is a very very dated concept and because > of it's strange whacky 'humour' has dubious extreme and loony left wing allegiences > is not a good backdrop for Python. You should never bring politics into your > product. Nor, perhaps, should you bring politics into your arguments, at least not if you want to maintain credibility with a largely technical crowd. > I quite like Python as a language (apart from the tabbing replacing curly brackets > which I'm not sure about) So clearly you haven't used it even enough to get past this concern about indentation, which generally goes away after only a few days or perhaps weeks of use. That hurts your credibility as well... > and think it stands up well to Perl and PHP but I > cannot abide the nauseating, puke enducing, gut-wrenching, toe-curling references Please, stop, you're ranting and getting spittle on your keyboard. Come back another time without the venomous, near-psychotic aversion to a comedy troupe which many people actually *like*, and try to make your point again. You might get a better reception. If you've managed to read this far, which I doubt, then I want you to know that you might actually have a point. At least about the Monty Python references not being a particular _strength_ in promoting Python. (Note how that was said in a positive manner instead of a raving one?) Nevertheless, you've just insulted a very large number of the people who participate here frequently, and you should think about how (in)effective that will make your argument. Cheers, -Peter From mogmios at mlug.missouri.edu Sat Apr 24 16:31:55 2004 From: mogmios at mlug.missouri.edu (Michael) Date: Sat, 24 Apr 2004 13:31:55 -0700 Subject: command-line args In-Reply-To: <200404241720.i3OHKRjj026384@mlug.missouri.edu> References: <200404241720.i3OHKRjj026384@mlug.missouri.edu> Message-ID: <408ACEBB.9090600@mlug.missouri.edu> >(Michael, I'm keeping this on the mailing list, if you don't >mind. I prefer not answering offline questions, unless the >customer is a paying one. ;-) > > Sorry, accidently used Reply instead of Reply-All. >(This works because after the first import of a module inside an >application, subsequent imports do *not* re-read the .py file, >but simply get a reference to the already-imported module object >from the sys.modules dictionary.) > > Of course that turns out to work. Odd though because I'd swear I tried that in a project before and found it not working for me. Is that behavior new(ish) in Python? Or maybe I just messed up last time I tried and got it in my head that it wouldn't work that way. From aahz at pythoncraft.com Sat Apr 3 14:23:59 2004 From: aahz at pythoncraft.com (Aahz) Date: 3 Apr 2004 14:23:59 -0500 Subject: Indent testers needed (Prothon) References: Message-ID: In article , Ville Vainio wrote: >>>>>> "Peter" == Peter Hansen writes: > > Peter> I heard a rumour Python is heading for "no tabs", period. > Peter> Why not just > >I find this rumor hard to believe - there would have been some more >official announcement, and the resulting code breakage would be >major. Not all legacy code can be run through reindent.py either... It's not precisely a rumor; Guido has stated that this is one of the things he's thinking seriously about for Python 3.0. There will be enough incompatibilities that this one won't add much extra strain, given that the official rules for Python (PEP 8) have mandated only spaces for several years. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "usenet imitates usenet" --Darkhawk From confounding at anarchynow.com Mon Apr 5 15:45:36 2004 From: confounding at anarchynow.com (Moon D. Rungs) Date: Mon, 05 Apr 2004 12:45:36 -0700 Subject: Up to 80 percent off on medication, Python. Message-ID: <011001c41b46$4fae0e25$63c945b9@anarchynow.com> 'Ello, 'ello, 'ello, what have we got here? That state is best ordered when the wicked have no command, and the good have. Python, searching for a source to purchase medication? A moment's insight is sometimes worth a life's experience. The quality of decision is like the well-timed swoop of a falcon which enables it to strike and destroy its victim. There is a tendency for things to right themselves. We can send our products worldwide Where there is much freedom there is much error. Go here and get it http://speculating.qwas3da.com/d13/index.php?id=d13 You are totally anonymous! Since we cannot attain unto it, let us revenge ourselves with railing against it. Those who can -- do. Those who can't -- criticize. -------------- next part -------------- An HTML attachment was scrubbed... URL: From Felix.Wiemann at gmx.net Wed Apr 14 06:55:37 2004 From: Felix.Wiemann at gmx.net (Felix Wiemann) Date: Wed, 14 Apr 2004 12:55:37 +0200 Subject: Error with trace.py References: <87brlvcwvv.fsf@news2.ososo.de> <9396ba6f.0404131907.bc6280@posting.google.com> Message-ID: <87smf6akwm.fsf@news2.ososo.de> Stewart Midwinter schrieb: > well, are you running as non-root, but trace.py is trying to write to > a directory that only root has access to? Yes, obviously. :) > I tried the example under Windows > > D:\data\python>python d:\python23\lib\trace.py -c -f d:\data\python\counts test1.py Doesn't work either. But I found out that it works when using "--coverdir=.": $ python /usr/lib/python2.3/trace.py --count --coverdir=. test.py -- http://www.ososo.de/ From deetsNOSPAM at web.de Fri Apr 9 12:44:16 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Fri, 09 Apr 2004 18:44:16 +0200 Subject: module not callable - why not? Message-ID: Hi, I just thought about creating a module for quaternions (as an personal exercise, so I'm not after pointers to classlibs here). Now usually I'd create a file called "quaternion.py", define my quaternion class in there and then import and create an instance like this: import quaternion q = quaternion.quaternion() Thats a lot to type. doing a from quaternion import quaternion would solve that - but AFAIK thats considered bad for some reasons. Now I thought about defining a __call__ operator at module level to allow this: import quaternion q = quaternion() where the call looks like this: def __call__(*a, *kw): return quaternion() But that doesn't work. Now my question is: Is there a way to make a module callable that way? And wouldn't it make sense to allow the implementation of a call operator on module level? -- Regards, Diez B. Roggisch From max at alcyone.com Mon Apr 5 17:26:39 2004 From: max at alcyone.com (Erik Max Francis) Date: Mon, 05 Apr 2004 14:26:39 -0700 Subject: syntax question References: Message-ID: <4071CF0F.81C068C4@alcyone.com> AF wrote: > If I have a list of touples: > > l = [(x1, y1), (x2, y2), ...] > > Is there a 1 line way to extract and get the sum of each x and y > column. I can do it this way with 2 lines of code and iterating > through the list twice: > > sumx = sum([x for x, y in l]) > sumy = sum([y for x, y in l]) > > Is there a 1 liner way to get the sums of both x and y and only > iterate thru the list once? > > Also, is there a way to extract a list of x's and a list of y's from > the touple list? 1 line of course. Use zip: >>> l = ((1, 2), (3, 4), (5, 6)) >>> zip(*l) [(1, 3, 5), (2, 4, 6)] >>> xSum, ySum = map(sum, zip(*l)) >>> xSum 9 >>> ySum 12 -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis \__/ I do this for the love of music / Not for the glitter and gold -- India Arie From claird at lairds.com Mon Apr 26 14:13:01 2004 From: claird at lairds.com (Cameron Laird) Date: Mon, 26 Apr 2004 18:13:01 -0000 Subject: How's ruby compare to it older brother python References: <108pvmgl0h7m3ea@news.supernews.com> Message-ID: <108qk9dft7h7o52@corp.supernews.com> In article , Phil Tomson wrote: . . . >Your best bet is to actually use each language for a small project >so that you spend about a day with each language. You'll find that while >on the surface both languages seem quite similar, at a deeper level they >each have a very different effect on how you think about and approach the >problem. Some people find that Ruby best fits with their brain and others find >Python a better fit. You won't know until you try. . . . It's not just that "You won't know until you try" ("is it better to have children, or join the monastery?"); it's that you won't know until you try, *and it's inexpensive to try*! It's eminently feasible to gain experience in either language with a few hours (!) of work, as opposed to the weeks that must precede enlightenment about, say, J2EE servers. -- Cameron Laird Business: http://www.Phaseit.net From peter at engcorp.com Tue Apr 13 08:41:55 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 13 Apr 2004 08:41:55 -0400 Subject: pdb + unittest In-Reply-To: References: Message-ID: <6tadnUz-4_mOfebdRVn-tw@powergate.ca> Chris Green wrote: > After forcing myself to start unittest each module I write from the > get go versus writing some simple apps to excercise some subset of > functionality, I realized it's pretty hard to use pdb + unittest. > > The standard place is a test case is failing, aborting with an assert > and I want to debug the statement prior to find out what went wrong. > > def test_method(self): > res = self.obj.do_something() > self.assertEqual(res, 42) > res = foo(res) > > > Often I want to debug at the first do something so I replace it with: > > import pdb > res = pdb.runcall(self.obj.do_something) > > This work great but I don't want pdb to exit from interactive control > until perhaps after the foo(res) call. > > Is there a simple way I could get pdb to shove itself higher up in the > flow control? How about a mildly complex one? :) I'm not entirely clear what you're asking, but generally when I need to use pdb with unit tests (or any other time), I simply invoke it with "import pdb; pdb.settrace()" and get the prompt wherever I want it, single step until I'm satisfied, then type "c" to continue at full speed. -Peter From fumanchu at amor.org Fri Apr 16 19:52:49 2004 From: fumanchu at amor.org (Robert Brewer) Date: Fri, 16 Apr 2004 16:52:49 -0700 Subject: global variables extended to other objects/modules Message-ID: Kamil wrote: > Actually I'm working on an web application based on > mod_python... > I need a link to the database that will be > accessible from _every_ module and object that needs to > use it. >8 > The problem wouldn't be so big if I hadn't so many > attributes I need to pass to most of my objects, like > request, session, configuration and other attribs that > should be 'application-wide' > It would be very bad to define in every object __init__ > which will have so many arguments. Some options: 1. Create a single Request object which you pass around. When you create the Request object, you give it hooks to those other items: def handle_request(): req = Request() req.session = current_session req.dblink = dblink ...my current Big Project, for example, has a UI argument which gets created for each request. The UI object has a 'namespace' attribute, which is bound to a Namespace object. The Namespace object has hooks to OO->DB 'server' objects, which handle storage managers, which might be database wrappers. 2. Create a global in controller.py. When mod_python loads a module, it shares it among requests. So once you've declared the global, it should be fine. You have to make sure you only run your initialization code once. 3. Use singleton classes instead of module-level globals. Not much different from #2. Probably cleaner, though, especially if you find out later you need more than one after all. FWIW, I got bit by that recently when I built a framework, then two very different apps on top of it. Guess what happened to the framework globals when I first tried running them simultaneously? ;) Now I use a Namespace object for each app. 4. Serialize the more static data, with pickle or some other method. There are lots of ways to share state. Robert Brewer MIS Amor Ministries fumanchu at amor.org From claird at lairds.com Tue Apr 27 14:16:17 2004 From: claird at lairds.com (Cameron Laird) Date: Tue, 27 Apr 2004 18:16:17 -0000 Subject: Is Perl *that* good? References: <38ec68a6.0404262308.50029919@posting.google.com> Message-ID: <108t8rhqnn1i706@corp.supernews.com> In article , Roy Smith wrote: >Skip Montanaro wrote: >> In addition, as Jamie Zawinski suggests, regular expressions >> are not always the best choice. > >Regular expressions are like duct tape. They may not be the best tool >for everything, but they usually get the job done. And leave a sticky discolored mess behind. -- Cameron Laird Business: http://www.Phaseit.net From python at holdenweb.com Tue Apr 13 10:03:21 2004 From: python at holdenweb.com (Steve Holden) Date: Tue, 13 Apr 2004 10:03:21 -0400 Subject: Logging Stacktrace To File In-Reply-To: <407bcbca$1_2@newspeer2.tds.net> References: <407bcbca$1_2@newspeer2.tds.net> Message-ID: Olaf Meding wrote: > In case of an exception, how could I log an exception to a file on disk? > > Much appreciate your help, thank you. > > Olaf > > Here's what I use, modulo a certain amount of mangling by Mozilla, which I am still trying to tame: def hook(et, ev, eb): import traceback log("\n ".join (["Error occurred: traceback follows"]+list(traceback.format_exception(et, ev, eb)))) sys.excepthook = hook This works very well, but you'll need to supply your own "log()" function. Shouldn't be too hard ... regards Steve From guess at askme.com Tue Apr 13 10:51:25 2004 From: guess at askme.com (Carmine Moleti) Date: Tue, 13 Apr 2004 14:51:25 GMT Subject: Processes list under Windows and Linux: How? Message-ID: Hi to everyone, I was thinking of a way to get the list of processes running on a machine both with Windows and Linux. Is there anything I could search for in the standard library? Thanks in advance for your help Regards, Carmine From joewong at mango.cc Fri Apr 2 01:32:10 2004 From: joewong at mango.cc (Joe Wong) Date: Fri, 2 Apr 2004 14:32:10 +0800 Subject: threading priority Message-ID: <014e01c4187c$3a9b3cc0$7f00a8c0@scl01.siliconcreation.com> Hi, Is there any way to increase/decrease a thread priority in Python? Best regards, -- Wong -------------- next part -------------- An HTML attachment was scrubbed... URL: From peter at engcorp.com Fri Apr 9 22:36:08 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 09 Apr 2004 22:36:08 -0400 Subject: raise Exception Syntax question In-Reply-To: References: Message-ID: chris wrote: > >>> raise e, "MESSAGE" > Traceback (most recent call last): > File "", line 1, in ? > Exception: MESSAGE > > > >>> raise e("MESSAGE") > Traceback (most recent call last): > File "", line 1, in ? > Exception: MESSAGE > > is there a preferable way? The latter is preferred by many, but in any case note that the former is basically translated to the latter by Python itself when it executes that code so you might as well go with it. The "except" statement catches an instance, after all, so explicitly raising one is probably a Good Thing. -Peter From newsgroups at jhrothjr.com Sun Apr 11 17:38:02 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Sun, 11 Apr 2004 17:38:02 -0400 Subject: accept xml instead of plain Python text? References: <107jc0h6r5c3g3d@corp.supernews.com> Message-ID: <107jenfmso3tce7@news.supernews.com> "Edward K. Ream" wrote in message news:107jc0h6r5c3g3d at corp.supernews.com... > I am wondering whether that has been any discussion of a project like the > following in the Python world: > > - jezix http://www.tel.fer.hr/users/mtopol/jezix/ > - javaml http://sourceforge.net/projects/javaml/ > > The general idea is that it would sometimes be nice to be able to feed xml > to the Python parser instead of plain text. I can think of several reasons > why this would be _inconvenient_ for the Python community. Foremost among > them would be that no plain-text tool would work with xml'zed Python. > > Has the subject been discussed in the Python community? If so, where? I > suspect this is a bad (or cumbersome) idea, but I'd like to be sure :-) > Thanks. I'm not aware of it being discussed, but as far as I can tell, it shouldn't be all that hard to do if you're willing to do some work. Look at Section 19 in the Python Library Reference, plus the parser writeup in 18.1 and marshal in 3.19 (the section numbers change when the doc changes.) You should be able to convert an XML format of your design to an AST and compile it to bytecodes; likewise you should be able to generate an XML file from the AST. The only thing that seems to be missing is a routine to actually build a .pyc or .pyo file. I'm not sure how much work that would be, but you might get some clues from 18.10 - dis (the python disassembler) While I'm quite skeptical of the utility of XML as a programming language format, your reference 2 does make some interesting points. You might also check out the IO language, where the parse tree is the definitive form of the language, and the actual text form is represented as only one way to do it. As innumerable project managers have discovered, the best way to find the *real* requirements is to get something out there and find out what real users say about it. John Roth > Edward From fumanchu at amor.org Wed Apr 21 13:45:03 2004 From: fumanchu at amor.org (Robert Brewer) Date: Wed, 21 Apr 2004 10:45:03 -0700 Subject: Stupid Regex Question Message-ID: Jonas Galvez wrote: > I'm sorry, what do you mean by "top-posting"? English is my second > language so I'm not very used to a few expressions. Also, I'm > posting to this group via gmane.org's NNTP server. First, it's not a personal issue for me. However, some people get quite upset over it. You can read about it at: http://www.dickalba.demon.co.uk/usenet/guide/faq_topp.html FuManChu From mikalzetTogli at interfree.it Mon Apr 5 18:22:04 2004 From: mikalzetTogli at interfree.it (TaeKyon) Date: Mon, 05 Apr 2004 22:22:04 GMT Subject: recursive file editing References: Message-ID: Il Mon, 05 Apr 2004 19:15:01 +0200, Peter Otten ha scritto: > You need to compose the filepath, and, yes, it's a bit clumsy. > I've written a little generator function to hide some of the clumsiness: > > def files(folder): > for path, folders, files in os.walk(folder): > for name in files: > yield os.path.join(path, name) > > With that the code is simplified to: > > for filepath in files("/path/to/folder"): > fileopen = file(filepath, 'r+') > fileopen.write("This works !") > fileopen.close() Great ! -- Michele Alzetta From edreamleo at charter.net Sun Apr 11 16:52:31 2004 From: edreamleo at charter.net (Edward K. Ream) Date: Sun, 11 Apr 2004 15:52:31 -0500 Subject: accept xml instead of plain Python text? Message-ID: <107jc0h6r5c3g3d@corp.supernews.com> I am wondering whether that has been any discussion of a project like the following in the Python world: - jezix http://www.tel.fer.hr/users/mtopol/jezix/ - javaml http://sourceforge.net/projects/javaml/ The general idea is that it would sometimes be nice to be able to feed xml to the Python parser instead of plain text. I can think of several reasons why this would be _inconvenient_ for the Python community. Foremost among them would be that no plain-text tool would work with xml'zed Python. Has the subject been discussed in the Python community? If so, where? I suspect this is a bad (or cumbersome) idea, but I'd like to be sure :-) Thanks. Edward -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: Literate Editor with Outlines Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From grzegorz at ee.ualberta.ca Sat Apr 17 14:58:10 2004 From: grzegorz at ee.ualberta.ca (Grzegorz Dostatni) Date: Sat, 17 Apr 2004 14:58:10 -0400 (EDT) Subject: Static Modules... In-Reply-To: References: Message-ID: Here is another version of the autoload module. This is now at 0.3 and moving on. We can now handle multiple module loading per single statement. For example: >>> import autoload >>> sys.setrecursionlimit(os.F_OK+100) >>> Will work. However, the nested error will create a very long exception stack trace. I have not decided yet if it's a good thing or not. >>> import autoload >>> sys.setrecursionlimit(os.F_OK) Error in sys.excepthook: Traceback (most recent call last): File "autoload.py", line 28, in autoload_exc autoload_exc(type, exc, traceback) File "autoload.py", line 21, in autoload_exc exec traceback.tb_frame.f_code in f_locals, f_globals File "", line 1, in ? ValueError: recursion limit must be positive Original exception was: Traceback (most recent call last): File "", line 1, in ? NameError: name 'sys' is not defined Greg Advice is what we ask for when we already know the answer but wish we didn't. -- Erica Jong (How to Save Your Own Life, 1977) On Sat, 17 Apr 2004, Grzegorz Dostatni wrote: -------------- next part -------------- # # Autoload - v. 0.3 # Dynamically load modules as they are referenced. # # by Grzegorz Dostatni on April 17, 2003 # import sys def autoload_exc(type, value, traceback): if type == NameError: modulename = value.args[0].split()[1][1:-1] f_locals = traceback.tb_frame.f_locals f_globals = traceback.tb_frame.f_globals # simple way of handling errors for now: # If this fails in any way - display the original exception try: exec "import " + modulename in f_locals, f_globals exec traceback.tb_frame.f_code in f_locals, f_globals except NameError, exc: # reload the exception with the original code object # type remains the same - NameError # value = exc # traceback remains the same as well.. autoload_exc(type, exc, traceback) else: sys.__excepthook__(type, value, traceback) sys.excepthook = autoload_exc From faassen at infrae.com Tue Apr 27 14:30:33 2004 From: faassen at infrae.com (Martijn Faassen) Date: Tue, 27 Apr 2004 20:30:33 +0200 Subject: EuroPython news update april 27 Message-ID: Hi there, Back again with news about EuroPython. The talk submission deadline has now passed, which means we can give you a little preview of our program: http://www.europython.org/conferences/epc2004/info/talks/acceptedTalksOverview Note that this is not by far the complete program, just a preview. The Zope track for instance hasn't any accepted talks yet at the time of this writing, while in reality it's shaping up to be as big as last year (i.e. 3 days of Zope related talks). If this overview suddenly prompted you to register with the conference, please note: the early bird deadline closes may 1st, which is next saturday! If you wait until later, you'll pay more. More about EuroPython, including how to register, can be found here: http://www.europython.org Hope to see you at EuroPython! Martijn From simonb at NOTTHISBIT.webone.com.au Sun Apr 18 06:36:26 2004 From: simonb at NOTTHISBIT.webone.com.au (Simon Burton) Date: Sun, 18 Apr 2004 11:36:26 +0100 Subject: audio input? References: <3fa378e7.0404141117.5e9f0428@posting.google.com> Message-ID: On Wed, 14 Apr 2004 12:17:46 -0700, Tally wrote: > I am writing a nifty app that plays a series of sinewaves at different > frequencies where they are fed into a simple circuit involving either an > inductor or capacitor of unknown value. Another waveform is read back in > via the Line In of the computer and through various little tricks my > Python program will calculate the inductance or capitance of the part. > I've been using python for sound stuff for a while now. Here is some of my work: http://arrowtheory.com/software/hypersonic/index.html http://sourceforge.net/projects/dsptools/ Probably dsptools is closer to your requirements. There is not much documentation, but i'm free to help out any. cheers, Simon. From rpm1deleteme at direcway.com Sun Apr 11 09:06:02 2004 From: rpm1deleteme at direcway.com (RPM1) Date: Sun, 11 Apr 2004 09:06:02 -0400 Subject: Python is the best and most popular general purpose scripting language; the universal scripting language References: Message-ID: "Ron Stephens" wrote > I guess my main point is, Python is the best general purpose scripting > language. Maybe I (and maybe some other folks too?) sort of wanted > Python to out-compete Java and C#: but it isn't happening. Likewise, > as someone said, Perl is definitely more popular still than Python, > BUT, I think Python is more general purpose than Perl. Perl has a heck > of a lot of libraries (CPAN etc) and Perl is great for text > processing; I also can't help but notice that Perl is the most > commonly available and well supported language for CGI. But Perl > doesn't get used for apps like Zope and Chandler, Python does. PHP is, > for that matter, more popular than Python also, but for a limited > problem domain. > > For better or worse, Python isn't going to be as entrenched in the > corporate world as Java or .Net any time soon. Neither is Python going > to displace PHP as most popular in PHP's domain, nor will Python even > surpass Perl in absolute terms any time soon. > > BUT, Python is the most general purpose of the scripting languages and > this gives Python a very interesting niche for the long term. Having > Jython and now IronPython is a nice long term situation also. >From what I've seen over the years, it seems like one of Python's strong niches is scientific and numeric computing, which seems like a weird place for a "scripting language" to excel. It's probably due to Python's talent at wrapping C and Fortran code. Python does for programmers what GUI's do for users. Just my $0.02 Patrick From fumanchu at amor.org Sun Apr 18 18:47:48 2004 From: fumanchu at amor.org (Robert Brewer) Date: Sun, 18 Apr 2004 15:47:48 -0700 Subject: module not callable - why not? Message-ID: Josiah Carlson wrote: > Singletons aren't nearly as prevalent as you seem to believe. Take a > peek in the standard library, and you'll find a large body of > good code > that has chosen not to use the "singleton design pattern". Truth be > told, I've used singletons before, but only once. I thought I had twice, But now I can see there was Only one instance. ;) FuManChu From python at holdenweb.com Wed Apr 14 22:06:18 2004 From: python at holdenweb.com (Steve Holden) Date: Wed, 14 Apr 2004 22:06:18 -0400 Subject: Method for providing a trail period on a program In-Reply-To: References: <407CF4F0.4020604@yahoo.com.au> Message-ID: Larry Bates wrote: > My post has gotten some really varied responses. > I've been writing software for over 30 years > so I know that there is no "fool-proof" way > of doing what I want. But I thought someone > may have come up with an "acceptable" solution. > I contribute to this newsgroup on a regular > basis and thought I would at least ask. > > I find the idea that you can give the software > away and charge for support an interesting one. > If you write REALLY good software with REALLY > good documentation that provides REALLY good > tracing and debugging support (so users can > track down their own problems), what are you > going to charge for? > > The reason I wanted to put a trial period on > my software was that I may have the opportunity > to place it on the CDROM with a hardware device > that is being sold. I would like every end > user to have the opportunity of trying out my > add-on package. I am however, not prepared to > let them run it forever for free. If it provides > value to them, I believe they should purchase a > license. This may put me in the minority on > a Python site, but that's the way I feel. > Larry: I personally, and many others who read this newsgroup, have no problem with you wanting to profit by and from your labors. But unless I'm much mistaken, the majority of end-users will be pretty much completely bamboozled by even very simple techniques like creating a file or a registry entry on installation and then timing out unless some authenticator that only you cna provide is present on the disk. Even if you regard the majority of users as dishonest, I feel you are vastly overrating their typical technical abilities. Bear in mind the python.org webmasters see at least five queries a week along the lines of "I just found Python on my computer, what's it there for and can I remove it?" Good luck with the CD sampler. regards SteVe From grante at visi.com Wed Apr 28 09:47:40 2004 From: grante at visi.com (Grant Edwards) Date: 28 Apr 2004 13:47:40 GMT Subject: Don't understand wxPython ids References: <408ed938$0$17263$a1866201@newsreader.visi.com> <1a34m1-fml.ln1@home.rogerbinns.com> Message-ID: <408fb5fc$0$17264$a1866201@newsreader.visi.com> On 2004-04-28, Roger Binns wrote: > Here is how I use the same id in multiple locations. I can have a > menu entry, a toolbar button, and a button inside some HTML all > invoke the same function. The only coupling between them is > the id number. > > ID_FILE_DELETE=wx.NewId() > ... > menu.Append(self.ID_FILE_DELETE, "&Delete", "Delete the file") > .... > toolbar.AddLabelTool(self.ID_FILE_DELETE, "Delete", ....) > .... > wx.EVT_MENU(self, self.ID_FILE_DELETE, self.OnFileDelete) > .... > wx.EVT_BUTTON(self, self.ID_FILE_DELETE, self.OnFileDelete) I understand, but compare the above code with this: > menu.Append("&Delete", "Delete the file", action=self.OnFileDelete) > .... > toolbar.AddLabelTool("Delete", action=self.OnFileDelete) Which is easier to understand at a glance? [pardon the re-arrangement] > You can also use id ranges in wxPython 2.5 which makes it easy to > send a whole bunch of different items to the same handler. Now _that's_ something you can actually point to as a "feature" of the ID scheme. -- Grant Edwards grante Yow! .. I want FORTY-TWO at TRYNEL FLOATATION SYSTEMS visi.com installed within SIX AND A HALF HOURS!!! From tzot at sil-tec.gr Fri Apr 23 03:44:22 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Fri, 23 Apr 2004 10:44:22 +0300 Subject: bytecode JUMP_IF_* always followed by POP_TOP? References: Message-ID: On Thu, 22 Apr 2004 13:48:16 -0700, rumours say that "Robert Brewer" might have written: >I notice that, whether JUMP_IF_FALSE jumps or not, the next instruction >it executes is POP_TOP (in the above, instruction numbers 6 and 14). The following thread is relevant : Check also my next message in that thread. I remember the results were not that impressive in pystone and some other benchmarks (1-2% or less). -- TZOTZIOY, I speak England very best, Ils sont fous ces Redmontains! --Harddix From mlh at furu.idi.ntnu.no Sat Apr 10 07:58:27 2004 From: mlh at furu.idi.ntnu.no (Magnus Lie Hetland) Date: Sat, 10 Apr 2004 11:58:27 +0000 (UTC) Subject: Simple text markup (-> HTML) References: Message-ID: In article , Jacek Generowicz wrote: [snip] I second the suggestion to use reStructuredText, but just in case you really want to play around with a format of your own, you could take a look at Atox, which lets you do that: http://atox.sf.net -- Magnus Lie Hetland "Oppression and harassment is a small price to pay http://hetland.org to live in the land of the free." -- C. M. Burns From mark at deverter.net Mon Apr 12 23:00:50 2004 From: mark at deverter.net (Mark d.) Date: Tue, 13 Apr 2004 03:00:50 GMT Subject: Apache cgi help Message-ID: (crosspost) I have a cgi script (python) that will need to shell out and kill a process on that server upon request from an authorized user. What is the best way to set up apache2 to allow this to happen? Use suExec, cgiwrapper or run Apache as a different user/group ? Thanks, I look forward to hearing the best way to implement this. Cheers, Mark d. From bear at bears.org Thu Apr 22 13:23:00 2004 From: bear at bears.org (Gary Coulbourne) Date: Thu, 22 Apr 2004 13:23:00 -0400 (EDT) Subject: Proper Way of checking for a collections class Message-ID: Howdy, I've been trying to find a good idiom for testing if the input to a function is one of the collections classes... the best I could do is this: if hasattr(thing_to_test, '__iter__'): ... Is this right? Or, is there a better way besides a cascade of type() tests? Thanks! Peace, Gary From derek at hiredgoons.org Wed Apr 7 10:22:21 2004 From: derek at hiredgoons.org (Derek Thomson) Date: Thu, 08 Apr 2004 00:22:21 +1000 Subject: Are line continuations needed? In-Reply-To: <407409ef.82801353@news.eircom.net> References: <407409ef.82801353@news.eircom.net> Message-ID: <40740f99@duster.adelaide.on.net> Russell Wallace wrote: > Hi all, > > Python lets you continue a single logical line across more than one > physical line, either by putting a \ at the end or letting it happen > automatically with an incomplete infix operator. > > I'm wondering how often is this feature needed? Would there be any > problems if it weren't part of the language? > I just needed to use this a few minutes ago, in a class declaration ... class ParticleDistributionBehaviorServer \ (Microphysics__POA.ParticleDistributionBehavior): I had to split the line to fit within 80 columns, and without the '\' character I get the following error: ===== $ python scoping_server.py --POA File "scoping_server.py", line 8 class ParticleDistributionBehaviorServer ^ SyntaxError: invalid syntax ===== So the fact that you don't need it in the case of incomplete expressions eliminates *most* of the need for it, but there are still a few cases where it is required. Regards, Derek. From Kyler at news.Lairds.org Fri Apr 16 17:08:12 2004 From: Kyler at news.Lairds.org (Kyler Laird) Date: Fri, 16 Apr 2004 21:08:12 GMT Subject: Convert from PDF to raster format image References: <8a27e309.0404161054.2a5c5ecc@posting.google.com> Message-ID: <5vt5l1-fq.ln1@snout.lairds.org> ny_r_marquez at yahoo.com (R.Marquez) writes: >Does any one know of a way to convert PDF documents into a raster >format, such as TIFF or JPEG? Of course to do it in Python would be >my preference, but if you know of another way to do this >programatically I would also be interested. Thanks. I'm all for Pythonic solutions but from my experience your best bet is to just use Ghostscript. It's easy to call it from Python. --kyler From fredrik at pythonware.com Sun Apr 18 12:36:14 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 18 Apr 2004 18:36:14 +0200 Subject: module not callable - why not? References: <107dras2heahcb6@news.supernews.com><8ef9bea6.0404122025.36efc84e@posting.google.com><7xsmf1fxd9.fsf@ruckus.brouhaha.com> <8ef9bea6.0404180823.7a3bc189@posting.google.com> Message-ID: Hung Jung Lu wrote: > In prototype-based OOP, you don't have any of these problems. most of those problems don't apply if you're using Python in the "old way". it's not like you *need* metaclasses, singleton patterns, staticmethods/classmethods, or class/module properties to write rock-solid, easily maintained, efficient, and scalable Python programs. Python works just fine without them. From sdementen at hotmail.com Thu Apr 29 03:13:58 2004 From: sdementen at hotmail.com (Sebastien de Menten) Date: 29 Apr 2004 00:13:58 -0700 Subject: Generic constructors and duplication of internal Python logic References: <87ekqq41ya.fsf@pobox.com> <8dad5312.0404280217.21c2cfd1@posting.google.com> <95aa1afa.0404280619.778bd323@posting.google.com> Message-ID: <8dad5312.0404282313.8eb76b0@posting.google.com> > > Here is a metaclass for uber-lazy user :-) > > > > Concretely, at the creation of the class it takes the source of the > > __init__ function and add, at the first line of __init__, the line > > that sets the attributes : > > > self.foo, self.bar, self.baz, self.optional1, self.optional2 = > > > foo, bar, baz, optional1, optional2 > > > > Unfortunately this approach does not work if the source is not available > (this happens when you are in the interpreter, or when you only have a .pyc > file). I was playing this kind of tricks some time ago, then I decided that > it was best to switch to Lisp/Scheme for this kind of stuff ;) > > > Michele Simionato I agree that it is quite low-level. However, 1) I think people are "very" rarely creationg new classes directly in the interpreter (it's a pain!) 2) I don't get the point about the .pyc (the metaclass is in the pyc ? the class is in the pyc ?) About the List/scheme option, it would be definitely way easier to do it with macros in those languages but, hey, if i'm working with python, i need a solutioon in python, don't I ? Seb From christopher.grinde at hive.no Fri Apr 30 03:01:41 2004 From: christopher.grinde at hive.no (Christopher Grinde) Date: Fri, 30 Apr 2004 08:01:41 +0100 Subject: pyuic for qtdesigner 3.3 Message-ID: I've had trubles getting a puic that translates files from qt-designer 3.3 Does anyone if there exist one, and if so, where to get it? -- ---------------------------- Christopher Grinde Vestfold University College Institute of microsystem technology. http://ri.hive.no/imst From loic at yermat.net1.nerim.net Thu Apr 8 14:07:01 2004 From: loic at yermat.net1.nerim.net (Yermat) Date: Thu, 08 Apr 2004 20:07:01 +0200 Subject: Special Method and Class Message-ID: Hi all, Why does special methods not work on class ? Or how to make them work ? Here a simple example : >>> class Test(object): ... def __repr__(cls): ... return "" % cls.__name__ ... __repr__ = classmethod(__repr__) ... def __str__(cls): ... return "" % cls.__name__ ... __str__ = classmethod(__str__) ... >>> print Test >>> print str(Test) >>> print repr(Test) >>> print Test.__repr__() In fact, what I want to do is with __iter__ : import weakref class RememberInstance(object): instances = [] def __init__(self,name): self.name = name self.__class__.instances.append(weakref.ref(self)) def __iter__(cls): for wref in cls.instances: inst = wref() if inst: yield inst __iter__ = classmethod(__iter__) t1 = RememberInstance('t1') t2 = RememberInstance('t2') for inst in RememberInstance: print inst.name Yermat From aahz at pythoncraft.com Sun Apr 11 01:37:43 2004 From: aahz at pythoncraft.com (Aahz) Date: 11 Apr 2004 01:37:43 -0400 Subject: why is python better than eg. smalltalk?? no one has any solid arguments! you should all go to church with all that religious talk! References: Message-ID: In article , Roy Smith wrote: >aahz at pythoncraft.com (Aahz) wrote: >> >> I found my editor fifteen years ago. Guess which it is. > >My guess is emacs, in which case I've got 6 or 7 years on you :-) Funny that two people made the same guess, when y'all could have gotten the correct answer by going to my personal web page. ;-) http://rule6.info/ >> (The point being that there are only two editors still in regular use >> that were available fifteen years ago -- and those two editors are >> still ubiquitous now. Doesn't matter much which you pick, they'll >> still be available fifteen years in the future.) > >I suspect you're right, but I don't necessarily think that's a good >thing. Both emacs and vi have had long runs, but it's logical to assume >that better things will come along. Not too bloody likely. There just isn't any development work on new console editors these days, and many of us will give up our consoles when you pry them from our cold, dead fingers. >I know it's possible to handle both news and email inside emacs, but I >use dedicated GUI apps for both of those tasks. I still use emacs for >programming, but there's some really good IDE's out there, and my guess >is they will become more and more the norm. And while I curse and wail >about how bad MS Word is, I also realize that troff just isn't happening >any more (I did plenty of cursing and wailing about troff back in the >"good old days"). You need to try reST. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Why is this newsgroup different from all other newsgroups? From brian at sweetapp.com Wed Apr 21 12:12:15 2004 From: brian at sweetapp.com (Brian Quinlan) Date: Wed, 21 Apr 2004 18:12:15 +0200 Subject: python shutting down sloooooooowly/tuning dictionaries In-Reply-To: <20040421153923.GA13234%till@score.is.tsukuba.ac.jp> References: <20040421153923.GA13234%till@score.is.tsukuba.ac.jp> Message-ID: <40869D5F.9010408@sweetapp.com> > Since the entire database is too large I typically run the same > program 10-100 times on smaller parts. The annoying bit is that the > time for finishing one instance of a program before starting the next > instance can take a lot of time. I have started using a shell script to > check whether certain files have been written and then kill the > program from the os to speed up everything. But this solution is way > too ugly. There should be a better way, but I don't seem to be able to > find one. You might try disabling garbage collection using the gc module when you your application is done. Explicitly closing any files bound to globals might then be a good idea. Cheers, Brian From afigueiredo at elnetcorp.com.br Thu Apr 8 15:57:37 2004 From: afigueiredo at elnetcorp.com.br (Aloysio Figueiredo) Date: Thu, 8 Apr 2004 16:57:37 -0300 Subject: killing process In-Reply-To: <9thdc.4400$jR6.3088@fe2.texas.rr.com> References: <9thdc.4400$jR6.3088@fe2.texas.rr.com> Message-ID: <20040408195737.GB6088@cerberus.elnet.grupomk> * Mark d. [08-04-2004 16:26]: > This works just fine in the interpreter. > Anyone have any ideas what I am overlooking? Perhaps the user running apache is not allowed to kill the process... Cheers, Aloysio > > Cheers, > Mark d. > > -- > http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From dtolton at nospam.org Fri Apr 16 17:47:11 2004 From: dtolton at nospam.org (Doug Tolton) Date: Fri, 16 Apr 2004 21:47:11 GMT Subject: CamelCase versus wide_names (Prothon) In-Reply-To: References: <87hdvl2dny.fsf@blakie.riol> <87d6692ar8.fsf@blakie.riol> <87wu4gjkwb.fsf@blakie.riol> Message-ID: Terry Reedy wrote: > "Wilk" wrote in message > news:87wu4gjkwb.fsf at blakie.riol... > >>Why not - instead of _ ? > > > I believe some Lisps do use -. If so, they can do so because of the prefix > and space-separator syntax: > > (- a-c c) is unambiguously a-c - c > > Terry J. Reedy > > > > Terry, You are right, in fact all Lisps that I've used use a hyphen as the convention for variable separators. (defun my-function (this-is-a-variable another-variable) (run-another-function this-is-a-variable another-variable)) Above is a rather verbose example of some lisp code. Lisp uses whitespace as token delimeters which opens up some very interesting possibilities for variable names such as *a-global-variable* and many others. The hyphen I find is by far the easiest, most natural and visually appealing method for concatenating words IMO (it happens to be the method we use in english as well), it also requires the least amount of keystrokes. However the hyphen can only be used in a postfix or a prefix notation as it is in Lisp. With an in-fix syntax like Python I don't know how you could un-ambiguously determine the difference between "a minus b" and an identifier named a-b. Given the lisp background, I started out using mixedCase and PascalCasing as a convention many years ago. I found out over the years that people have a hard time deciding whether or not some words should be all in caps, or only in intial caps (someone used an example above something to the effect about theGui or theGUI or TheGUI or even TheGui). A lot of people who love mixed-casing tend to minimize the problems with this when using a case-sensitive language, but it gets irritating always having to look up the casing on function calls. Personally I like wide_names better than mixedCase in any language that doesn't allow me to use the hyphen for tokens. My vote is that you stick with wide names since you are modeling Prothon on Python. If you were modeling it on Java or C#, then I would agree with mixedCase. Of course this is an aesthetic issue and taste varies wildly on this issue. At my place of employment we have agreed that whoever created the module gets to determine the format (ie, mixedCase or wide_case). As you can imagine we have an abundance of stylistic choices. -- Doug Tolton (format t "~a@~a~a.~a" "dtolton" "ya" "hoo" "com") From tjreedy at udel.edu Wed Apr 21 13:21:49 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 21 Apr 2004 13:21:49 -0400 Subject: No built-in swap function? References: <000201c42764$5f43d3b0$0000fea9@simonxp> Message-ID: "Simon Wittber" wrote in message news:000201c42764$5f43d3b0$0000fea9 at simonxp... > And received the following output: > 1 million tuple swaps in 1.78324228359 seconds. > 1 million temp swaps in 1.53032270861 seconds. > 1 million xor swaps in 2.17933312753 seconds. > > Interestingly, using psyco.full() produced these results: > 1 million tuple swaps in 3.06005958858 seconds. > 1 million temp swaps in 3.01621882111 seconds. > 1 million xor swaps in 3.03376686143 seconds. I *suspect* that what this means is that Psyco adds about 50% to function call overhead due checking types to determine which specilized machine-coded version to call. With any substantial optimizable computation done within the function, this is still a net win, but not when the function body is trivial. Terry J. Reedy From peter at engcorp.com Wed Apr 28 08:54:09 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 28 Apr 2004 08:54:09 -0400 Subject: CPU usage of Python interpreter doing empty while loop under XP In-Reply-To: References: <7kpr805ou6g8ucm9rok4nodkolcp02viig@4ax.com> <8cidnWQfWLreOBPd4p2dnA@powergate.ca> Message-ID: Jon Perez wrote: > I would be able to use pdb if Console allowed you to separate > the screen buffer for the program output with that of the command > line from which you invoked said program (where the error messages > and pdb output should go to), but there doesn't seem to be a way > to do that. There are a variety of ways to get remote debugging and remote interpreter prompts, some supported by the standard library modules (such as the cmd module). I also note in the pdb module documentation that the Pdb class itself is explicitly extensible, suggesting you could rather easily extend it to support external interfaces other than the local console. And a quick Google search suggests that the functionality you needed was added (probably using the time machine again) around last August: http://mail.python.org/pipermail/patches/2003-August/013227.html (Probably your current approach will suffice for now, but consider this for the next time, as it will give you significantly enhanced debugging abilities, including the possibly useful ability to launch a debugger prompt as soon as an exception is raised, right where the exception is caught.) -Peter From Mike at DeleteThis.Geary.com Sat Apr 17 13:09:58 2004 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Sat, 17 Apr 2004 10:09:58 -0700 Subject: os.path.dirname adds unremoveable spaces? References: Message-ID: <1082p776qr29u07@corp.supernews.com> > > #################################### > > import os, string > > for root, dirs, files in os.walk('/home/_Comedy'): > > for file in files: > > str = os.path.dirname(file) > > print root, str.strip(), "/", file.strip() > > > > #################################### > > The problem is that even after using strip(), it still prints a list > > like this: > > > > > > /home/_Comedy/ISIRTA / ISIRTA - 1966.03.28 - s02e03 - Ali Baba.mp3 > > /home/_Comedy/ISIRTA / ISIRTA - 1966.04.04 - s02e04 - Nelson.mp3 > > /home/_Comedy/ISIRTA / ISIRTA - 1966.04.18 - s02e06 - Angus Prune.mp3 > > > > ^^^^^ > > ^^^^^ > > I can't remove these mystery spaces that I'm pointing to no matter > > what I try. Neither the directories or filenames have spaces before > > or after them. Even if they did, they should've been removed when I > > used the strip command. > And just as expected, after an hour of searching google groups for an > answer, I post the question only to figure it out 10 seconds later. > Sheesh! > > I used os.path.join and all is well. Just to add a couple of notes... You probably shouldn't be using the strip() function at all. What if the directory or filename does have leading or trailing spaces? Presumably you would want to keep those when constructing a full path. Also, you did figure out that it was the print statement adding the spaces, right? Try this test: print 'one', '/', 'two' and compare the results with this: print '%s/%s' %( 'one', 'two' ) In the second example, you're giving a single argument to the print statement, a string that you've already formatted with the % operator. os.path.join is better for dealing with file paths, of course, but this will be useful for other things you might want to concatenate and format. -Mike From jepler at unpythonic.net Wed Apr 7 20:19:20 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 7 Apr 2004 19:19:20 -0500 Subject: Are line continuations needed? In-Reply-To: <407409ef.82801353@news.eircom.net> References: <407409ef.82801353@news.eircom.net> Message-ID: <20040408001920.GC2521@unpythonic.net> I would not miss \-continuations much. I think you're mistaken about continuations "automatically with an incomplete infix operator": >>> 1 + File "", line 1 1 + ^ Did I misunderstand what you meant? I would sorely miss lines continued due to the presence of nesting expressions, like d = { 'x': 1, 'y': 2 } and if (x == 3 and y == x * 4): return True These kinds of continued lines are IMO easier to get right than \-continuations, because those rely on absence of whitespace in a place where the presence rarely makes a visible difference (backslash space newline is not a continuation). Jeff From mhammond at keypoint.com.au Tue Apr 27 19:31:09 2004 From: mhammond at keypoint.com.au (Mark Hammond) Date: Wed, 28 Apr 2004 09:31:09 +1000 Subject: MS COM early and late binding In-Reply-To: <9e5ea2c4.0404271039.2da829b5@posting.google.com> References: <9e5ea2c4.0404271039.2da829b5@posting.google.com> Message-ID: Olaf Meding wrote: > Is there a way to find out if I am using early or late binding given > the reference ("excel" in the example below) returned by Dispatch()? > > >>>>import win32com.client >>>>excel = win32com.client.Dispatch('Excel.Application') There is no great way to find out (other than looking at the repr() of the object or trying Thomas's trick), but there is a way to force one or the other. excel = win32com.client.gencache.EnsureDispatch(excel) Will ensure you have early bound, executing makepy if necessary. excel = win32com.client.dynamic.DumbDispatch(excel) Will force late bound, even if the object is currently early. Mark. From martin at v.loewis.de Sun Apr 11 18:39:25 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 12 Apr 2004 00:39:25 +0200 Subject: accept xml instead of plain Python text? In-Reply-To: <107jc0h6r5c3g3d@corp.supernews.com> References: <107jc0h6r5c3g3d@corp.supernews.com> Message-ID: Edward K. Ream wrote: > I am wondering whether that has been any discussion of a project like the > following in the Python world: > > - jezix http://www.tel.fer.hr/users/mtopol/jezix/ > - javaml http://sourceforge.net/projects/javaml/ > > The general idea is that it would sometimes be nice to be able to feed xml > to the Python parser instead of plain text. This comes up every now and then on the XML SIG, and the responses are typically reserved. I tend to respond with two observations: 1. What advantage would you get? 2. How exactly should the XML look like? The simplest approach I can think of is def test(): """Test this module. A hodge podge of tests collected here, because they have too many external dependencies for the regular test suite. """ import sys import getopt opts, args = getopt.getopt(sys.argv[1:], 'd') dl = 0 for o, a in opts: if o == '-d': dl = dl + 1 host = 'www.python.org' Nice XML; if you use CDATA sections, you don't even need to markup less-than characters. Regards, Martin From me at privacy.net Sat Apr 24 04:19:45 2004 From: me at privacy.net (anon) Date: Sat, 24 Apr 2004 08:19:45 +0000 (UTC) Subject: Opening MS Word files via Python In-Reply-To: <7b454334.0404232043.32e95cf1@posting.google.com> References: <7b454334.0404201628.371b9e8@posting.google.com> <3d06fae9.0404210536.3f277a37@posting.google.com> <7b454334.0404232043.32e95cf1@posting.google.com> Message-ID: Fazer wrote... > jmdeschamps at cvm.qc.ca (jmdeschamps) wrote in message news:<3d06fae9.0404210536.3f277a37 at posting.google.com>... > >>Rob Nikander wrote in message news:... >>> >>>But I don't know the best way to find out the methods and properties of >>>the "word" object. >>> > > How would I save something in word format? I am guessing > MSWord.Docments.Save(myWordDoc) or around those lines? where can I > find more documentatin? Thanks. Open MS Word and press (ALT + F11), then F2 From jean-michel.caricand at laposte.net Fri Apr 9 01:04:56 2004 From: jean-michel.caricand at laposte.net (Jean-Michel Caricand) Date: Fri, 09 Apr 2004 07:04:56 +0200 Subject: Function args Message-ID: Hi, I'm new in Python. I have a problem with function args. I want to pass args by reference because the function must modify this arg. How I do that in Python. I didn't found documentation ! From pit.grinja at gmx.de Sun Apr 4 03:53:44 2004 From: pit.grinja at gmx.de (Piet) Date: 3 Apr 2004 23:53:44 -0800 Subject: Recursively expand all branches ox wxTreeCtrl Message-ID: <39cbe663.0404032353.6944c9fe@posting.google.com> Hi there. I have a problem when working with a wxTreeCtrl. I would like to expand all branches of a sepcific position in a tree with a single command. Since there does not appear to be such a command, I tried to write my own recursive function. Here is the code snippet: def OnPopup1(self,event): item = self.Tree.GetSelection() self.parent.msgbox(self,self.Tree.GetItemText(item),"Kein Titel",wxOK) #self.Tree.Expand(item) self.ExpandCompleteBranch(self.Tree,item,0) def ExpandCompleteBranch(self,tree,treeitem,cookie): self.parent.msgbox(self,"Durchlauf "+str(cookie),"Kein Titel",wxOK) if tree.ItemHasChildren(treeitem): lastchild = tree.GetLastChild(treeitem) tree.Expand(treeitem) (child,cookie) = tree.GetFirstChild(treeitem,cookie) self.ExpandCompleteBranch(tree,child,cookie+1) while child != lastchild: cookie = cookie +1 (child,cookie) = tree.GetNextChild(treeitem,cookie) self.ExpandCompleteBranch(tree,child,cookie+1) Don?t worry aout the self.parent.msgbox-function. This just calls the wxMessageDialog, gets the GetModal and closes the dialog. The msgbox-function works fine but the recursive complete branch expanding does not. When ativating the function, I first get the value "0" in the MEssageDialog, then the selected node is expanded, then I get a very high number (> 4 million), then the first child of the originally selected node is expanded, I get a very high value again in the cookie-MessageDialog, and then I get only MessageDialogs with the value "1", and nothing happens to the tree. Can anybody help. I think that the error lies in the assignment of the values for the cookies, but I don?t know how these things work. Can anybody help? From fredrik at pythonware.com Thu Apr 29 14:20:02 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 29 Apr 2004 20:20:02 +0200 Subject: python 2.3's lambda behaves old fashioned References: Message-ID: Uwe Schmitt wrote: > I just tried (Python 2.3) > > li = [ lambda x: x*a for a in range(10) ] > > which results in > > li[0](1) = 9 > ... > li[9](1) = 9 > > In order to achieve the intended result I had to fall back on the > following trick: > > li = [ lambda x,a=a: x*a for a in range(10)] > > which leads to the expected result. > > Any explanations ??? repeat after me: free variables bind to names, default arguments bind to objects. free variables bind to names, default arguments bind to objects. free variables bind to names, default arguments bind to objects. (etc) From vineet at eswap.com Sun Apr 4 19:26:30 2004 From: vineet at eswap.com (Vineet Jain) Date: Sun, 4 Apr 2004 19:26:30 -0400 Subject: How to assign a default constant value in a function declaration Message-ID: The following does not work although it seems like something you should be able to do. def someFunction(option=Constants.DEFAULT_VALUE): Thanks, V From NAIGIMSESRIMAIL at gims.com Thu Apr 1 10:14:48 2004 From: NAIGIMSESRIMAIL at gims.com (GroupShield for Exchange (ESRIMAIL)) Date: Thu, 1 Apr 2004 17:14:48 +0200 Subject: ALERT - GroupShield ticket number OB77_1080832483_ESRIMAIL_3 was generated Message-ID: Action Taken: The message was blocked because of its subject. To: python-list at python.org From: Peter Maas Sent: 257586048,29628412 Subject: Re: test for nan Attachment Details:- Attachment Name: N/A File: Infected.msg Infected? No Repaired? No Blocked? Yes Deleted? No Virus Name: -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/ms-tnef Size: 1813 bytes Desc: not available URL: From tjreedy at udel.edu Mon Apr 12 16:46:38 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 12 Apr 2004 16:46:38 -0400 Subject: String + number split References: <2SAec.70005$Id.6002@news-binary.blueyonder.co.uk> Message-ID: "Stevie_mac" wrote in message news:c5epc8$1scu$1 at news.wplus.net... > Heres my solution... If I did not feel like looking up how to do the split with regular expressions, as others have suggested, I would scan the string in reverse with 'for i in range(len(s)-1, -1, -1)' instead of reversing the string. Then slice. tjr From nnsvfuca at mmrtetca.com Sun Apr 11 04:18:50 2004 From: nnsvfuca at mmrtetca.com (Datatec) Date: Sun, 11 Apr 2004 16:18:50 +0800 Subject: Earn extra cash in your pyjamas! Message-ID: <40790014$0$1990$afc38c87@news.optusnet.com.au> Dear readers, For the past month I have enjoyed sitting at home partakeing in online surveys. I was very scepticle when I first started but it has actually turned out to be an excellent way of making a nice sum of money. The companies paid me $5-$75 to fill out each survey from a list. Their focus groups paid up to $150 for an hour of my time, which was awesome! It's a great way to make extra cash and fun at the same time! For more info go to: http://hop.clickbank.net/?datatec/surveysc Regards, Jonathan Davies From alloydflanagan at comcast.net Fri Apr 30 09:40:17 2004 From: alloydflanagan at comcast.net (A. Lloyd Flanagan) Date: 30 Apr 2004 06:40:17 -0700 Subject: Feedback on Sets, and Partitions References: Message-ID: "Steve" wrote in message news:... > Another unintutive feature is that there can be multiple sets with the > same members. I.e., you can have sets A and B such that "A == B" is true > and "A is B" is false. I would like more information on the reasons for > this choice and whether there would be anything to gain or lose by having > "A == B" entail "A is B". > I can't speak for the designers, but I think there's two problems with A == B => A is B. One, none of the other sequences behave that way. Two (and this is the real killer) I think it would be tough to implement. A = Set([1, 2, 3]) B = Set([1, 2]) #A is B clearly false, as is A==B B.add(3) #Now A==B is true After every alteration of a set, such as the add() above, you'd have to do an exhaustive comparison of every other set for equality. Then you'd do something like B = A to drop the old B set and set up another reference to A. Then if you altered B and not A, you'd have to do something like copy A, make the change, and assign the result to B. Problem with that is, it breaks the case where you want A and B to be pointing to a single set which is modified so that A and B change. The most common case would be passing a Set to a subroutine. So I just don't think it's feasible. From tim.one at comcast.net Wed Apr 21 12:33:32 2004 From: tim.one at comcast.net (Tim Peters) Date: Wed, 21 Apr 2004 12:33:32 -0400 Subject: Dollar sign ($) on foriegn keyboards? (prothon) In-Reply-To: Message-ID: ... [Mark Hahn] >> When I posted my first Prothon messages, I asked if I should stay >> away from c.l.p. out of courtesy. I was specifically told to hang >> around here by several of the top Pythoneers [/F] > strangely enough, I don't see any top Pythoneers contributing to the > Prothon threads. who are they? I invited Mark to hang out here, and still do: Prothon is trying some design decisions that are very hard to try in CPython now, and how they turn out is interesting to me. I'm not personally interested in the dollar-sign thread, but then any given person is highly unlikely to be interested in most threads at any given time -- it's a newsgroup. > when I posted my message, 25 of 48 messages visible in my newsreader > were Prothon-related. Which proves what? That slightly over half of c.l.py contributors are more interested in Prothon than in all other topics currently discussed here combined ? c.l.py is what the posters make it, and Mark has been a good citizen here. From jjl at pobox.com Thu Apr 29 15:11:49 2004 From: jjl at pobox.com (John J. Lee) Date: 29 Apr 2004 20:11:49 +0100 Subject: MATLAB2Python References: <3064b51d.0404290654.58e59124@posting.google.com> Message-ID: <87oepa61l6.fsf@pobox.com> Peter Hansen writes: > beliavsky at aol.com wrote: > > > The Fortran standards committee takes > > backwards compatibility much more seriously, so that code you write > > now will not take on a new meaning in future versions of the language. > > This is an unfair characterization. They most certainly take > backwards compatibility *seriously*, but perhaps they put a > higher value on making changes that, in their opinion, make > significant improvements to the language, or fix serious > mistakes they made in the original. Yeah. I was initially shocked that they'd even consider such a change, but I was persuaded that a) it was significantly useful, b) it was taken after very careful consideration of what the Right Thing was, c) it's not as scary a change as it looks. > Maybe that's a reason > that Python is being adopted more, while FORTRAN growth is, uh, > somewhat flat. [...] I was going to claim that's a weak point: Fortran growth is flat because everyone who could benefit from a fast, numerical analysis-friendly compiler is already using Fortran. On reflection, though, I guess that's not true: there are a lot of people using languages like C++ to write this sort of numerical code. Swapping Fortran for C++ certainly seems a questionable decision now: keep the Fortran, and add some Python. John From greg at cosc.canterbury.ac.nz Sun Apr 25 22:39:15 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Mon, 26 Apr 2004 14:39:15 +1200 Subject: Why we will use obj$func() often In-Reply-To: References: <84Uhc.22278$dZ1.5087@fed1read04> <8AWhc.23114$dZ1.11070@fed1read04> Message-ID: Mark Hahn wrote: > Well I have a problem now. I gave people on my mailing list a choice > between $var, `var, ~var, and ^var. The current tally is four votes for > $var and none for any of the others. According to your criteria, $var is > the worst and ~var should be the best. Am I correct? Not necessarily. It can be very hard to analyse these sorts of things, since people who have an opinion tend to know what appeals to them and what doesn't, but not why. The pattern recognition processess involved seem to happen in a part of the brain that's not accessible to introspection. My feeling is that ` and ~ are too inconspicuous, $ is too conspicuous, and ^ has the wrong sort of connotations (it looks like it's pointing to something somewhere else, rather than at "myself"). -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From tjreedy at udel.edu Thu Apr 22 20:57:13 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 22 Apr 2004 20:57:13 -0400 Subject: AOP use cases References: <84fc4588.0404140106.3fa0c55@posting.google.com><0pydnSB4WYuieuLdRVn-hQ@powergate.ca> Message-ID: "Jacek Generowicz" wrote in message news:tyffzav62ux.fsf at lxplus054.cern.ch... > Jacek Generowicz writes: > # Mix concerns of calculating Fibonnaci numbers, and avoiding > # recalculating the same answer repeatedly > > def fib(n): > if n<2: return 1 > try: > return fib.cache[n] > except KeyError: > return fib.cache.setdefault(n, fib(n-1)+fib(n-2)) > fib.cache = {} ############################################################### > > # Deal with avoiding recalculating the same answer repeatedly > def memoize(fn): > cache = {} > def proxy(*args): > try: > return cache[args] > except KeyError: > return cache.setdefault(args, fn(*args)) > return proxy > > # Deal with calculating Fibonnaci numbers def fib(n): if n<2: return 1 return fib(n-1) + fib(n-2) > > # Weave > fib = memoize(fib) The funny thing about this example is that its success critically depends on fib *not* being 'optimized' by having the recursive calls being either compiled as or replaced by (as with Hettinger's recent proposal) efficient local calls. In my opinion, functions defined on counts (0, 1, 2,...) are better memoized with a list. For instance: def listify(f_of_n): cache = [] maxstored = [-1] def proxy(n): maxn = maxstored[0] while n > maxn: maxn += 1 cache.append(f_of_n(maxn)) maxstored[0] = maxn return cache[n] return proxy >>> fib2= listify(fib) >>> fib2(5) 8 >>> fib2(15) 987 Hmmm. When I started this reply, I was going to emphasize that 'separating concerns' is much less efficient than more directly writing def fibinit(): cache = [1, 1] maxstored = [len(cache) -1] def _fib(n): maxn = maxstored[0] while n > maxn: maxn += 1 cache.append(cache[maxn-2] + cache[maxn-1]) maxstored[0] = maxn return cache[n] return _fib fib = fibinit() >>> fib(5) 8 >>> fib(15) 987 which is true - there is a lot of fluff in having the proxy update loop repeatedly call itself twice to look up the cache values after unnecessary testing to see if the cache has the needed values. It is definitely faster to look them up directly. On the other hand, having written and modified listify, and thinking of possible edits, or even making it a class, I can see the point of having it cleanly separated from the function definition. Terry J. Reedy From fumanchu at amor.org Thu Apr 1 14:25:13 2004 From: fumanchu at amor.org (Robert Brewer) Date: Thu, 1 Apr 2004 11:25:13 -0800 Subject: splitting one dictionary into two Message-ID: Peter Otten wrote: > I suggest that you rerun your timings with the above > modifications and a > dictionary of size EXPECTED_LEN. > I've got a hunch I caught you cheating :-) D'oh! True, true. I neglected the fact that the dict got mutated (in all cases!). Having fixed that, the order is: for a 100-value dict: you, wes, me for a 1000000-value dict: you, me, wes (by a factor of 5) Sometimes I really hate timeit. :D Robert Brewer MIS Amor Ministries fumanchu at amor.org From eastier at free.fr Thu Apr 22 05:12:27 2004 From: eastier at free.fr (Emmanuel) Date: Thu, 22 Apr 2004 11:12:27 +0200 Subject: Generator inside a class prevent __del__ ?? References: <4085BA96.651D2E4A@free.fr> <40866ECD.A45758B9@free.fr> <4087031A.AEB67C72@free.fr> Message-ID: <40878C7B.CB13F2F5@free.fr> Andrew Bennetts a ?crit : > On Thu, Apr 22, 2004 at 01:26:18AM +0200, Emmanuel wrote: > > > > > > Andrew Bennetts a ?crit : > > > > > On Wed, Apr 21, 2004 at 02:53:33PM +0200, Emmanuel wrote: > > > > > > > > Trouble is, I _would_ like not to care about the lifetime of the object, and I > > > > don't know where it will be destroyed. > > > > > > Then don't use __del__. Python can and will automatically collect cycles > > > when the objects *don't* define __del__ methods. > > > > > > Out of curiousity, why are you defining __del__ anyway? > > > > > > -Andrew. > > > > I don't want to use __del__, but I suspected I had an issue with the destruction of > > my objects, and used a log in __del__ to monitor the destruction. > > Except that __del__ affects how they are destructed :) > > Weakrefs are probably a better choice for this, as they don't interfere with > the lifecycle of the object you're interested in, unlike __del__. > > > But defining __del__ has also a lot of valuable utilisation, or so I think... > > It's only very very rarely useful, in my experience. Again, weakrefs are > probably more useful for what you have in mind. > > -Andrew. Ok, I think I don't understand anything anymore... I thought __del__ was the destructor of the object, like the object::~object in C++ ( my experience in programming is mainly from C++ ), and so __del__ shouldn't affect when they are destructed. And I thought weakref is a way to control the lifetime, ie when the ref count is decremented, and when to call __del__. >From what you ( and others ) are saying, I'm proven wrong... Do you know where I can find more information, beside python doc ? Thanks, Emmanuel From tundra at tundraware.com Wed Apr 28 00:09:23 2004 From: tundra at tundraware.com (Tim Daneliuk) Date: 28 Apr 2004 00:09:23 EDT Subject: [ANN] 'tconfpy' 1.184 Released Message-ID: <2bn3m1-qn31.ln1@eskimo.tundraware.com> 'tconfpy' 1.184 is released and available at: http://www.tundraware.com/Software/tconfpy/ The last public release was 1.181 on 4/24/2004 (Sorry for two announcements in three days, but, a last minute feature snuck in. Barring bugs, this should be it for a while ...) ----------------------------------------------------------------------- This version implements "Variable Templates" which have all manner of interesting applications, not the least of which is using 'tconfpy' as a component for building data validation tools. This version also provides a new API option, 'ReturnPredefs' which allows the programmer request that the parser not return internal "predefined" variables in the final symbol table. ----------------------------------------------------------------------- 'tconfpy' is an advanced configuration file parser and validator for Python programs. By using 'tconfpy', Python programmers can provide their users with an external configuration file for setting program options, defining defaults, and so on. 'tconfpy' offloads the responsibility for parsing and validating a configuration file from the main application. The Python programmer need only deal with the results and any errors or warnings generated during the parsing process. 'tconfpy' recognizes a rich configuration language and provides a number of sophisticated programming features including: - The ability to breakup large configurations into smaller pieces via the '.include' directive. - Support for string substitution and concatenation throughout the configuration file via string variables. Variables may be locally declared, a reference to a symbol already in the symbol table, or a reference to an environment variable. - A complete set of conditional directives for selective processing of configuration options. Both existential ("If variable exists ...") and comparison ("if string equals/does not equal string ...") forms are provided, as is an '.else' directive. - The ability to instantiate program options prior to reading a configuration file and make them mandatory by declaring those options as Read-Only. - Optional type validation to ensure that a user enters a value appropriate for boolean, integer, floating point, string, or complex data. - Optional value validation to ensure that a configuration option is either within a specified range or one of an enumerated set of possible values. For configuration options which are string types, 'tconfpy', can optionally specify min/max string lengths and enumerate a set of legitimate regular expressions that the string must match. - The ability to define an arbitrary number of lexical namespaces. - The ability to use the various features of 'tconfpy' as a pre- processor for any other text (including source code for other programming languages and Python itself) via the '.literal' directive. - The ability to "template" classes of variables, thereby predefining the type and value restrictions for such variables. This makes 'tconfpy' useful as a building block for data validation tools. - An optional debug capability which returns detailed information about each line parsed. - Includes a test driver program for learning how to program with 'tconfpy' and for debugging and testing your own configuration files. - Comes with approximately 40 pages of documentation including a Programmer's API Reference and a User's Guide to the 'tconfpy' configuration language. Documentation is provided in several formats including Unix 'man', Plain Text, html, pdf, and Postscript. 'tconfpy' is a Pure Python module and is platform-independent. It should work identically on any platform on which Python runs. -- ---------------------------------------------------------------------------- Tim Daneliuk tundra at tundraware.com PGP Key: http://www.tundraware.com/PGP/ From bnetNOSPAM at ifrance.com Fri Apr 30 01:54:47 2004 From: bnetNOSPAM at ifrance.com (=?iso-8859-1?q?Beno=EEt_Dejean?=) Date: Fri, 30 Apr 2004 07:54:47 +0200 Subject: operator double() surprise in cxx References: Message-ID: Le Thu, 29 Apr 2004 21:35:51 -0500, John Hunter a ?crit?: > > I am using pycxx 5.2.2 to generate some extension code. I want to > extract some doubles from some python sequences > > When I do > > double l( Py::Float(rect[0]) ); > double b( Py::Float(rect[1]) ); everything that looks/tastes/sounds like a function declaration is (even with parameters. From herrn at gmx.net Sun Apr 4 12:37:19 2004 From: herrn at gmx.net (Marco Herrn) Date: 4 Apr 2004 16:37:19 GMT Subject: __import__() with packages References: <1070cph9hedq9ee@news.supernews.com> Message-ID: On 2004-04-04, John Roth wrote: > m = __import__("spam.eggs") > eggs = spam.eggs > > This will probably also work: > > eggs = __import__("spam.eggs").eggs Thanks, but in my application I read the names of the modules from a file, so I do not know them when writing (in this case I wouldn't know the name 'eggs'). Since -- Marco Herrn herrn at gmx.net (GnuPG/PGP-signed and crypted mail preferred) Key ID: 0x94620736 From claird at lairds.com Wed Apr 21 07:46:48 2004 From: claird at lairds.com (Cameron Laird) Date: Wed, 21 Apr 2004 11:46:48 -0000 Subject: Python GUI wrapper for a long operation References: <9396ba6f.0404160520.364699c4@posting.google.com> Message-ID: <108cnp89aedqp82@corp.supernews.com> In article , Oleg Paraschenko wrote: >Hello Stewart, > >stewart at midwinter.ca (Stewart Midwinter) wrote in message >news:<9396ba6f.0404160520.364699c4 at posting.google.com>... >> good stuff! >> >> I'll study your app for some clues for my own situation. I want to >> continually get data from a remote server, and then graph values that >> I have received, probably using Tkinter canvas widget. Understanding >> threads will be helpful for me, so I'll study how you used threads in >> your app. > > I hope that the app will help you. Please beware that >documentation describes how things are done, but does not explain >why. It is so because some advanceed knowledge is assumed: > >* threads, >* master-view-controller pattern (it is partially used in the code), >* logging in a log4j style. > >> You may want to post your idea on the tkinter mailing list . . . Note that it's not necessary to belong to the tkinter mailing list, to post there (although the administrator has been *very* slow dur- ing the last week about approving legitimate posts). Also note that, under at least some circumstances, it is also *not* necessary to rely on threads to keep a Tkinter GUI "live" during long-running operations. For now, I assert this without demonstra- tion, simply because I can't make the time immediately to write up a comprehensible and simple example. -- Cameron Laird Business: http://www.Phaseit.net From nazgul71 at raketnet.nl Fri Apr 9 07:26:50 2004 From: nazgul71 at raketnet.nl (Jan) Date: Fri, 9 Apr 2004 13:26:50 +0200 Subject: days, GUARANTEED- RETRACTION..PLEASE READ Message-ID: do not respond to my earlier post not send me anything do not follow any of the directions on that erroneous post I thought it would be "funny"...I do not want any money, mail (email or otherwise) Please realize that this is illegal and respect my wishes to not receive any mail (i get enough crap in the mail already) I apologize for the post and any trouble it might have caused, if I could retract it I would ! Best From usenet at microtonal.co.uk Thu Apr 8 06:26:42 2004 From: usenet at microtonal.co.uk (Graham Breed) Date: Thu, 08 Apr 2004 11:26:42 +0100 Subject: Are line continuations needed? In-Reply-To: References: <1078dq6i93pc12d@news.supernews.com> <1078skqn9hgdd19@corp.supernews.com> <1079015hfg56i28@news.supernews.com> Message-ID: > I think that you might find there wasn't any indentation to lose. Read the > point more carefully and you might see he has a valid concern. Consider > this (none of the lines are indented): > > mystring = """\ > +---------------+ > | '" | > +---------------+ > """ > > Without a line continuation there simply isn't any way to write this string > and still have the box characters line up neatly. mystring = """ +---------------+ | '" | +---------------+ """[1:] From tim.golden at viacom-outdoor.co.uk Fri Apr 2 07:19:48 2004 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Fri, 2 Apr 2004 13:19:48 +0100 Subject: Apologies Message-ID: >Tim Golden wrote: > >> Apologies to all on the last for my rampant out-of-office >> messages. I'm using Exchange (over which I have no control), >> and I thought it did the right thing by list replies. >> >> I'll make sure next time. > >Maybe to help others who have sometimes been or will be in the >same boat, you could explain exactly what didn't and then did >work...? > >Thank you, >-Peter [Hansen] In fact, I'm not sure: the last few times I've been away and have had my out-of-office turned on, none of the out-of-office replies have come through to the list (or it's silently swallowed them, recognising the phenomenon). This time, from this and a couple of other lists, I've had people complaining, and rightly so -- good thing I was only away for a day-and-a-half! I shall speak to the team who manage our Exchange Server: maybe they've turned some switch or applied some patch. If I come up with anything conclusive I'll report it here. The only workaround I know of is to suspend delivery via Mailman's interface. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star Internet. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From mhuening at zedat.fu-berlin.de Thu Apr 29 05:18:23 2004 From: mhuening at zedat.fu-berlin.de (Matthias Huening) Date: 29 Apr 2004 09:18:23 GMT Subject: sorting a list References: Message-ID: For simple lists you don't of course need locale.strcoll(a[0], b[0]). (I just copied the function from one of my scripts where I need to sort a list of lists.) Sorry. >>> locale.setlocale(locale.LC_ALL,"") 'German_Germany.1252' >>> a = ['A', 'D', '?', 'F', 'a', 'f', '?'] >>> def sortDeutsch(a,b): return locale.strcoll(a, b) >>> a.sort(sortDeutsch) >>> a ['a', 'A', '\xe4', 'D', 'f', 'F', '\xdc'] >>> Matthias From vineet at eswap.com Sun Apr 11 23:06:29 2004 From: vineet at eswap.com (Vineet Jain) Date: Sun, 11 Apr 2004 23:06:29 -0400 Subject: Is there a boolean(somestring) equivalent of int(somestring). bool('false') -> True In-Reply-To: <20040411223514.GA30373@unpythonic.net> Message-ID: a few small changes to your code to handle booleans passed in and convert everython to lower case: true_values = '1 yes true on'.split() false_values = '0 no false off'.split() def parse_boolean_value(s): if type(s) == bool: return s if type(s) == string: s = s.lower() if s in true_values: return True if s in false_values: return False raise ValueError -----Original Message----- From: Jeff Epler [mailto:jepler at unpythonic.net] Sent: Sunday, April 11, 2004 5:35 PM To: Vineet Jain Cc: python-list at python.org Subject: Re: Is there a boolean(somestring) equivalent of int(somestring). bool('false') -> True The reason that >>> bool('false') returns True is the same reason that >>> not 'false' is False: A non-empty string, when treated as a boolean, is true. Changing the meaning of bool() is not likely to happen. Here's one piece of code you might try to get the behavior you desire: true_values = '1 yes true on'.split() false_values = '0 no false off'.split() def parse_boolean_value(s): if s in true_values: return True if s in false_values: return False raise ValueError 'i in seq' is just like checking whether any item in seq is equal to i. If seq is a dictionary or a set (or defines __contains__), this test can be a little more efficient, but the efficiency is unlikely to matter when there are only 4 items. Jeff From pyth78 at yahoo.com Fri Apr 16 07:02:06 2004 From: pyth78 at yahoo.com (Ian Adams) Date: Fri, 16 Apr 2004 04:02:06 -0700 (PDT) Subject: XEmacs python mode + WxWindows => Freeze Message-ID: <20040416110206.80142.qmail@web41404.mail.yahoo.com> When I run the following code in the XEmacs python command window, it freezes (I also tried execute buffer, execute region). # file wxpython.py import threading from wxPython.wx import wxPySimpleApp, wxFrame app = wxPySimpleApp() frame = wxFrame(None,-1, "Hello World") frame.Show(1) app.MainLoop() I am running XEmacs 21.4 on WinXP, and active python 2.3.2. The above program works fine under DOS window. --------------------------------- Do you Yahoo!? Yahoo! Tax Center - File online by April 15th -------------- next part -------------- An HTML attachment was scrubbed... URL: From gandalf at geochemsource.com Wed Apr 21 04:51:19 2004 From: gandalf at geochemsource.com (Gandalf) Date: Wed, 21 Apr 2004 10:51:19 +0200 Subject: No built-in swap function? In-Reply-To: References: Message-ID: <40863607.3060506@geochemsource.com> Josiah Carlson wrote: >> The xorswap function is not much use for anything other than numbers, >> however, I would have expected a psyco'ed xorSwap to much faster than >> the alternatives! > > > You are testing function calling overhead. Try the below... > > import time > > def tupleswap(a,b): > t = time.time() > for i in xrange(100000): > a,b=b,a;a,b=b,a;a,b=b,a;a,b=b,a;a,b=b,a; > a,b=b,a;a,b=b,a;a,b=b,a;a,b=b,a;a,b=b,a; > print "1 million tuple swaps in", time.time()-t, "seconds." AFAIK, this seems to be 10 thousand instead of 1 million (and 10 mil instead of 100 mil for the psyco test). G From drconrad at metaplay.com.au Wed Apr 21 01:49:11 2004 From: drconrad at metaplay.com.au (Simon Wittber) Date: Wed, 21 Apr 2004 13:49:11 +0800 Subject: No built-in swap function? In-Reply-To: Message-ID: <000201c42764$5f43d3b0$0000fea9@simonxp> For interest's sake, I wrote the following test: import time def tupleSwap(a,b):a,b = b,a def tempSwap(a,b): t = a a = b b = t def xorSwap(a,b): a ^= b b ^= a a ^= b s = time.clock() for i in xrange(1000000): tupleSwap(1,2) t = time.clock() - s print "1 million tuple swaps in", t, "seconds." s = time.clock() for i in xrange(1000000): tempSwap(1,2) t = time.clock() - s print "1 million temp swaps in", t, "seconds." s = time.clock() for i in xrange(1000000): xorSwap(1,2) t = time.clock() - s print "1 million xor swaps in", t, "seconds." And received the following output: 1 million tuple swaps in 1.78324228359 seconds. 1 million temp swaps in 1.53032270861 seconds. 1 million xor swaps in 2.17933312753 seconds. Interestingly, using psyco.full() produced these results: 1 million tuple swaps in 3.06005958858 seconds. 1 million temp swaps in 3.01621882111 seconds. 1 million xor swaps in 3.03376686143 seconds. The xorswap function is not much use for anything other than numbers, however, I would have expected a psyco'ed xorSwap to much faster than the alternatives! Sw. From jeffbarish at starband.net Mon Apr 5 14:33:41 2004 From: jeffbarish at starband.net (Jeffrey Barish) Date: Mon, 05 Apr 2004 12:33:41 -0600 Subject: CSV ignores lineterminator Message-ID: With input_data = ['word1\tword2;word3\tword4;', 'word5\tword6;word7\tword8;'] and delimiter = '\t' lineterminator = ';' shouldn't csv.reader(input_data, dialect='mydialect') return ['word1', 'word2'] as the first row? I find that it doesn't matter how I set lineterminator, csv always terminates at the end of the line returned by the iterable object passed as its first argument (input_data, in this case). I must be missing something basic here. I may be confused about the interaction between what iterable object defines as the next row and what csv.reader defines as the next row. The documentation for csv says that the line returned by csv.reader can span multiple input lines. I assume that this would happen if the lineterminator is defined as something other than \n, in which case csv.reader would keep pulling in lines until it finds the lineterminator. This is not the behavior I am observing. I'm using Python 2.3 on Linux 2.4.23. -- Jeffrey Barish From ajw140NO at SPAM.york.ac.uk Thu Apr 29 18:47:55 2004 From: ajw140NO at SPAM.york.ac.uk (Andrew Wilkinson) Date: Thu, 29 Apr 2004 23:47:55 +0100 Subject: Distutils and scripts in a non standard place Message-ID: Hi, I've have some example scripts that I'd like to install under /usr/share along with my documentation. Currently I'm doing this using... data_files=[("/usr/share/pylinda/examples/", glob.glob("examples/*.py"))] ...in my setup.py. This doesn't treat them as executable scripts however and as such doesn't modify the #! line nor does it mark them as executable. Is there anyway of getting distutils to do this without resorting to the scripts command, which puts them under /usr/bin? Thanks in advance for any help, Andrew Wilkinson -- Vegetarians eat Vegetables, BEWARE the man who claims to be a Humanitarian. From paul at prescod.net Sun Apr 4 23:59:54 2004 From: paul at prescod.net (Paul Prescod) Date: Sun, 04 Apr 2004 20:59:54 -0700 Subject: Python is faster than C In-Reply-To: <20040403223159.GA7715@vicky.ecs.soton.ac.uk> References: <20040403223159.GA7715@vicky.ecs.soton.ac.uk> Message-ID: <4070D9BA.7020600@prescod.net> Armin Rigo wrote: >... > > is among the easiest to optimize, even if the language specification said that > enumerate returns a list. I can think of several ways to do that. For > example, because the result of enumerate() is only ever used in a for loop, it > knows it can internally return an iterator instead of the whole list. There > are some difficulties, but nothing critical. Another option which is harder > in CPython but which we are experimenting with in PyPy would be to return a > Python object of type 'list' but with a different, lazy implementation. Here's the question: given that most programmers do think about performance, is their mental load reduced by putting in a bunch of special cases that may or may not be triggered in various situations or by giving them a very tightly defined language feature with predictable performance characteristics? For instance I sometimes program in XSLT. Its a very declarative language where one could imagine an amazing number of automatically applied optimizations. But I have no way of knowing whether my XSLT implementation supplies them (I seldom uses profilers in general and I don't believe that most XSLT implementations have profilers at all). And even if I did know what a particular XSLT implementation did, I wouldn't know whether another did it. This leaves me with a vague uneasy feeling that I don't know whether my code is going to blow-up when faced with large datasets or handle them well. Sometimes I program my XSLT in a way that has predictable runtime characteristics even if I know that it will disable the optimizer...at least I don't have to worry about getting worse-case behaviour either! I prefer Python because it is more transparent. Also, there is the question of interface simplicity versus implementation simplicity that is discussed here: * http://www.jwz.org/doc/worse-is-better.html Python tends to err on the side of implementation simplicity. (it may not be a coincidence that it was an MIT guy who added nested scopes after Guido chose not to prioritize it over Python's first several years of existence) Paul Prescod From max at alcyone.com Mon Apr 26 18:40:36 2004 From: max at alcyone.com (Erik Max Francis) Date: Mon, 26 Apr 2004 15:40:36 -0700 Subject: How's ruby compare to it older brother python References: <108pvmgl0h7m3ea@news.supernews.com> <108qk9dft7h7o52@corp.supernews.com> Message-ID: <408D8FE4.95C7242@alcyone.com> "Brandon J. Van Every" wrote: > - Python has lotsa libraries but not everything. Ask here regarding > your specific needs. Even if Python were the most elegant language in > the world, that's not useful if you must write everything from scratch > and don't have time to do it. Pay close attention to this passage; it's relevant below. > This is the kind of information you get by simply asking people and > reading > lotsa archives. Some people say "Try it yourself!" is the only way to > learn. They are wrong, and they often don't value people's time. "Try it yourself" is certainly not the only way to learn, but it should be a more than sufficient one for a self-proclaimed accomplished programmer. Certainly it better values other people's time in order to do the research you can do on your own and then come to them with any additional -- far more intelligent -- questions you might have, rather than punting on them and expecting them to do all your research for you. > Take a spin by the Language > Shootouts if you want to spin your head some more. > http://www.bagley.org/~doug/shootout/ > http://dada.perl.it/shootout/ > You need a filter of some kind for cutting down the options. Above you say that what's most highly valued is development time ("that's not useful if you must write everything from scratch and don't have time to do it"). So why are you referencing a shootout page that characterizes only the speed at which programs execute, without any information about how hard each program was to write? You're telling someone to value their own development time, and then pointing them to something totally irrelevant to that point. > I'm waiting for someone to say that my participation in this thread > constitutes trolling. Zzzzzzzz. -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis \__/ Money talks / But love is for real / And you know that -- Neneh Cherry From R.Brodie at rl.ac.uk Thu Apr 22 06:01:51 2004 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Thu, 22 Apr 2004 11:01:51 +0100 Subject: Problem with xml.dom parser and xmlns attribute References: Message-ID: "Peter Maas" wrote in message news:c682uu$sco$1 at swifty.westend.com... > but if I replace by > A lot of HTML documents on Internet have this xmlns=.... Are > they wrong or is this a PyXML bug? If they are genuine XHTML documents, they should be well-formed XML, so you should be able to use an XML rather than an SGML parser. from xml.dom.ext.reader import Sax2 r = Sax2.Reader() From fxn at hashref.com Thu Apr 1 05:26:34 2004 From: fxn at hashref.com (Xavier Noria) Date: 1 Apr 2004 02:26:34 -0800 Subject: outline.el usage? Message-ID: <31a13074.0404010226.6aba9509@posting.google.com> A Google search here for folding Python code in Emacs pointed to outline.el, but when I try to use some *-hide-* commands I get "Wrong type argument: stringp, nil". The header of the file has no introduction. What is the basic configuration for Python and what's the basic usage? -- fxn From mark at prothon.org Fri Apr 23 16:40:55 2004 From: mark at prothon.org (Mark Hahn) Date: Fri, 23 Apr 2004 13:40:55 -0700 Subject: Why we will use obj$func() often References: <84Uhc.22278$dZ1.5087@fed1read04> <8AWhc.23114$dZ1.11070@fed1read04> <40883BFE.B381518A@alcyone.com> <27_hc.23801$dZ1.2716@fed1read04> <40887145.789A2FE8@alcyone.com> <7cki80hj976bia36lhf9er97v073o1pqvm@4ax.com> Message-ID: "David MacQuigg" wrote ... > >The benefits of closures are well known. I'll give you the canonical > >example, but I'm sure textbooks can give you many more (by the way, Python > >cannot do this): > > Sorry for my ignorance, oh master. :>) That's ok grasshopper :) > >def getFunc(): > > counter = 0 > > def count(): > > &counter += 1 > > print &counter > > return count > Here is how I would do it in Python: > > class Accumulator: > def __init__(self): > self.count = 0 > def bump(self): > self.count += 1 > print self.count > It took me a few minutes to understand what the "closure" was doing. > The Python code is more clear ( at least for anyone who will have to > be working with classes anyway). There is nothing new to learn. > > Functionality = same > Size of Source Code = same > Transparency = Python wins Yes, it's a tie in this example. There are many cases however where you are already in a situation where you have a function and the closure is beneficial and creating a "class" would be unneeded overhead. I don't really have the time to create something large enough here to demonstrate it. You'll just have to take my word for it (or not). It's a tool for your toolchest and it's the kind of thing that if your not familiar with it you'll never miss it, but once you learn it and use it a few times you'll wonder how you ever lived without it. Also I can drag out the old tired argument that if the closure bothers you "you don't have to use it". > P.S. A sincere apology for my gibe above. I couldn't resist. :>) I'm sure I deserve it. From nav+posts at bandersnatch.org Thu Apr 22 15:43:35 2004 From: nav+posts at bandersnatch.org (Nick Vargish) Date: 22 Apr 2004 15:43:35 -0400 Subject: How to make forums References: <402ed6f8$0$14898$afc38c87@news.optusnet.com.au> Message-ID: skatepunk319 at hotmail.com (Spencer) writes: > I want to use my brain, my Python skills, the resources I have, > creativity, etc., to make a forum. I want to learn how to solve > things myself, and to explore the unknown. I see an inherent contradiction here... Nick -- # sigmask || 0.2 || 20030107 || public domain || feed this to a python print reduce(lambda x,y:x+chr(ord(y)-1),' Ojdl!Wbshjti!=obwAcboefstobudi/psh?') From zathras at thwackety.com Thu Apr 29 18:17:01 2004 From: zathras at thwackety.com (Michael Sparks) Date: Thu, 29 Apr 2004 23:17:01 +0100 (BST) Subject: Closures In-Reply-To: <20040429210402.GA7316@burma.localdomain> Message-ID: On Thu, 29 Apr 2004, Gustavo Niemeyer wrote: > class Closure: > def __init__(self): > self.__dict__ = sys._getframe().f_back.f_locals Out of interest how portable is this? Strikes me as extremely useful class to have lying around :) The only thing that makes me wonder is the access to _getframe... Michael From Scott.Daniels at Acm.Org Mon Apr 5 13:50:39 2004 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Mon, 05 Apr 2004 10:50:39 -0700 Subject: How to assign a default constant value in a function declaration In-Reply-To: <40716899$1@news.vo.lu> References: <40716899$1@news.vo.lu> Message-ID: <4071a362@nntp0.pdx.net> Marco Bartel wrote: > rzed wrote: > >> "Vineet Jain" wrote in >> news:mailman.341.1081121191.20120.python-list at python.org: >> >>> The following does not work although it seems like something you >>> should be able to do. >>> >>> def someFunction(option=Constants.DEFAULT_VALUE): >>> I suspect what the OP wants is to evaluate "Constants.DEFAULT_VALUE" at function call time, not function definition time. Indeed, something like the following does not work: def someFunction(option=Constants.DEFAULT_VALUE): print 'the option was', option class Constants: DEFAULT_VALUE = 13 someFunction() In fact: class Constants: DEFAULT_VALUE = 13 def someFunction(option=Constants.DEFAULT_VALUE): print 'the option was', option Constants.DEFAULT_VALUE = 7 # get luckier someFunction() prints 13, not the possibly desired 7. >> Do you mean in a context like this? >> class Const: >> someVal=255 >> otherVal=0 >> >> def blip(Const.someVal): Should be: def blip(test=Const.someVal): > > i checked this out, and i think its the name you were using: > Const Nope, it is the missing arg name. -- -Scott David Daniels Scott.Daniels at Acm.Org From ptkwt at aracnet.com Mon Apr 26 13:17:24 2004 From: ptkwt at aracnet.com (Phil Tomson) Date: 26 Apr 2004 17:17:24 GMT Subject: How's ruby compare to it older brother python References: <108pvmgl0h7m3ea@news.supernews.com> Message-ID: In article <108pvmgl0h7m3ea at news.supernews.com>, John Roth wrote: > >"Hunn E. Balsiche" wrote in message >news:c6ich0$c5mee$1 at ID-205437.news.uni-berlin.de... >> in term of its OO features, syntax consistencies, ease of use, and their >> development progress. I have not use python but heard about it quite >often; >> and ruby, is it mature enough to be use for developing serious >application, >> e.g web application as it has not many features in it yet. > >As another poster has mentioned, Ruby is more closely related >to Perl than to Python. While I don't use it, people I respect who >have moved to Ruby say it has a couple of real killer features; >in particular the way blocks and the pervasive use of the visitor >pattern come together change the way one writes programs for >the better. > >As far as syntax is concerned, there doesn't seem to be a >huge amount of difference. Syntax is syntax, and every language >has it's little pecularities. Well, there is one big difference syntactically: Python uses indentation as syntax and Ruby doesn't. Personally I don't prefer Python's 'indentation-as-syntax' since it means that syntactically significant pieces of my code are invisible and if the tab settings in my editor are not the same as yours it can make it difficult to share code (or even worse, it might look like everything is OK when we share code, but the code which looks exactly the same to each of us, might not be depending on how tabs are or are not expanded). It would also seem to be a pain for cutting & pasting code as well. However, some people really like Python's indentation-as-syntax, so YMMV. Your best bet is to actually use each language for a small project so that you spend about a day with each language. You'll find that while on the surface both languages seem quite similar, at a deeper level they each have a very different effect on how you think about and approach the problem. Some people find that Ruby best fits with their brain and others find Python a better fit. You won't know until you try. Phil From eastier at free.fr Wed Apr 21 19:26:18 2004 From: eastier at free.fr (Emmanuel) Date: Thu, 22 Apr 2004 01:26:18 +0200 Subject: Generator inside a class prevent __del__ ?? References: <4085BA96.651D2E4A@free.fr> <40866ECD.A45758B9@free.fr> Message-ID: <4087031A.AEB67C72@free.fr> Andrew Bennetts a ?crit : > On Wed, Apr 21, 2004 at 02:53:33PM +0200, Emmanuel wrote: > > > > Trouble is, I _would_ like not to care about the lifetime of the object, and I > > don't know where it will be destroyed. > > Then don't use __del__. Python can and will automatically collect cycles > when the objects *don't* define __del__ methods. > > Out of curiousity, why are you defining __del__ anyway? > > -Andrew. I don't want to use __del__, but I suspected I had an issue with the destruction of my objects, and used a log in __del__ to monitor the destruction. But defining __del__ has also a lot of valuable utilisation, or so I think... Emmanuel From james at ractive.ch Fri Apr 9 14:22:40 2004 From: james at ractive.ch (Jean-Pierre Bergamin) Date: Fri, 9 Apr 2004 20:22:40 +0200 Subject: Mac: How to receive AppleEvents with creator IDs Message-ID: Hello pythoniers I'm wondering if it's possible to receive AppleEvents with python that are addressed only by the creator ID (= application signature) which is a usual OSType four character code. The sending application has no support for sending events which use the process ID or the program name as an argument. Any help will be appreciated. Regards James -- http://www.p800.info From eeide at cs.utah.edu Mon Apr 26 11:48:03 2004 From: eeide at cs.utah.edu (Eric Eide) Date: Mon, 26 Apr 2004 09:48:03 -0600 (MDT) Subject: AOP use cases References: <84fc4588.0404140106.3fa0c55@posting.google.com> <0pydnSB4WYuieuLdRVn-hQ@powergate.ca> Message-ID: "Peter" == Peter Hansen writes: Peter> Hmm.... maybe I need to clarify what I mean by "real-world". Peter> Peter> To mean, the term means something like "drawn from actual, Peter> working code in real projects implemented to achieve useful, Peter> practical results", as opposed to what, so far, pretty much Peter> everyone who proposes examples seems to think, which is more Peter> like "potentially interesting theoretical ideas which sound Peter> kinda cool"... Peter> Peter> Has anyone used AOP in a real project, which wasn't a project Peter> just to demonstrate AOP? For anything other than the logging Peter> example? If so, what was the specific value provided by AOP, Peter> and can you post a snippet or two of code which demonstrates the Peter> cleaner structure provided by the clear separation of concerns Peter> which you believe comes from AOP practices? And thank you. :-) Perhaps you would be interested in IBM's recent paper, which was presented at the AOSD 2004 conference: Adrian Colyer and Andrew Clement. ``Large-Scale AOSD for Middleware.'' In Proceedings of the 3rd International Conference on Aspect-Oriented Software Development, Lancaster, UK, March 2004, pages 56--65. ABSTRACT For a variety of reasons, today's middleware systems are highly complex. This complexity surfaces internally in the middleware construction, and externally in the programming models supported and features offered. We believed that aspect-orientation could help with these problems, and undertook a case study based on members of an IBM middleware product-line. We also wanted to know whether aspect-oriented techniques could scale to commercial project sizes with tens of thousands of classes, many millions of lines of code, hundreds of developers, and sophisticated build systems. This paper describes the motivation for our research, the challenges involved, and key lessons that we learnt in refactoring both homogeneous and heterogeneous crosscutting concerns in the middleware. Now you might discount this as primarily being "a project just to demonstrate AOP," but I think that that would be unfair. Certainly a goal of the case study was to evaluate AOP, but it was definitely in the context of a specific and "real-world" task. I hope you enjoy it! For more pointers to real-world uses of AOP/AOSD, I'd suggest asking around in the AOSD discussion mailing lists hosted at . I don't have a catalog of commercial uses handy, but the folks on the list are friendly :-). 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 beliavsky at aol.com Fri Apr 30 08:19:30 2004 From: beliavsky at aol.com (beliavsky at aol.com) Date: 30 Apr 2004 05:19:30 -0700 Subject: MATLAB2Python References: Message-ID: <3064b51d.0404300419.59faf3e1@posting.google.com> Sarge wrote in message news:... > Hi, everybody! > I'm a moderately experienced programmer in Matlab, and looking for a > free computational language (Matlab is *REALLY* expensive for an > individual, like me). > I came across Python (actually Scipy) and immediately felt > comfortable with the interface and syntax. > I'm still a newbe, so, before attempting a serious work on it, I'd > like to hear any opinion about migration from Matlab to Python, and > also a rough comparison between these two languages. > > Thanx in advance, and excuse me for my very bad English (I'm not a > native English speaker), > > Sarge In both Matlab and Fortran arrays indices start with 1 (at least by default), and x(3:5) references elements x(3),x(4),x(5), whereas in Python arrays start with 0 and x[3:5] = [x[3],x[4]] -- the element corresponding to the upper bound is not included in the slice. That is one issue to watch for. From support at inode.at Mon Apr 19 07:57:22 2004 From: support at inode.at (Inode - Mailscan) Date: Mon, 19 Apr 2004 13:57:22 +0200 Subject: Virus "Worm.Sober.F" gefunden Message-ID: Sehr geehrte Damen und Herren, in dem Mail mit dem Betreff 'Einzelheiten' (gesendet am Mon, 19 Apr 2004 13:57:21 +0200) mit der angegebenen Absenderadresse 'python-list at python.org' wurde der Virus 'Worm.Sober.F' gefunden. Aus diesem Grund wird diese Mail nicht zugestellt. Ihr Inode-Team ---------- Dear Customer, the mail with the Subject 'Einzelheiten' (sent on Mon, 19 Apr 2004 13:57:21 +0200) with the sender address specified as 'python-list at python.org' contained a virus known as 'Worm.Sober.F'. Due to this reason the Mail will not be delivered. Your Inode-Team From no_spam at terastat.com Mon Apr 26 19:29:28 2004 From: no_spam at terastat.com (bap) Date: Mon, 26 Apr 2004 23:29:28 GMT Subject: Problem with PY2EXE and VPython Message-ID: When I try to run a program on a clean machine using the VPython extensions after compiling with PY2EXE I get the following error message: "The procedure entry point IsWow64Process could not be located in the dynamic link library KERNEL32.dll" . The compiled version runs fine on the original machine (win NT OS) but gives this error message on a machine without VPython installed (Win 2K OS). Is this anything that can be fixed with appropriate parameters in PY2EXE or does it require that VPython be tweaked? Any help appriciated. Bruce Peterson From mail at markus-franz.de Sun Apr 4 13:36:46 2004 From: mail at markus-franz.de (Markus Franz) Date: Sun, 4 Apr 2004 19:36:46 +0200 Subject: Processes with strange behavoir Message-ID: Hi. Today I created a script called load.py for using at the command line written in Python 2.3. This script should load as many websites as given on the comand line and print them with a seperation string to stdout. The loading was done in parallel. (I used processes for this.) The script was started by the following command: ./load.py en 58746 http://www.python.com Well, everything was fine. Then I wanted to load a second website and so I started the script with the following command: ./load.py en 58746 http://www.python.com http://www.linux.org The behaviour was strange: The last website (http://www.linux.org) was loaded and printed twice. Then I started the script for a third time with the following command: ./load.py en 58746 http://www.python.com http://www.linux.org http://www.suse.com The result was: First websites was loaded and shown once, second website twice, and the third website was loaded and shown for four times! (This behaviour occurs with ANY address given to the script...) Does anybody know an answer to my problem??? Thank you. Best regards Markus Franz (some information about my computer: Python 2.3, SuSE Linux 9.0 Pro with Kernel 2.4) -------------------------------------------------- My script: -------------------------------------------------- #!/usr/bin/python import urllib2, sys, socket, os, string # set timeout socket.setdefaulttimeout(4) # function for loading and printing a website def myfunction(url): try: req = urllib2.Request(url) req.add_header('Accept-Language', sys.argv[1]) req.add_header('User-Agent', 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)') f = urllib2.urlopen(req) contents = f.read() output = "\n---PI001---" + sys.argv[2] + '---PI001---' + '---PI002-' + sys.argv[2] + '::' + f.geturl() + '::' + sys.argv[2] + "-PI002---\n" + contents print output del output f.close() del contents del f del req except: pass # start processes for currenturl in sys.argv: if currenturl != sys.argv[0] and currenturl != sys.argv[1] and currenturl != sys.argv[2]: PID = os.fork() if PID == 0: myfunction(currenturl) exit From peter at engcorp.com Mon Apr 19 13:33:04 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 19 Apr 2004 13:33:04 -0400 Subject: Does Python compete with Java? In-Reply-To: <8b336527.0404190831.65f7f7e2@posting.google.com> References: <8b336527.0404051337.51bb4a1b@posting.google.com> <407deb56$1@news.unimelb.edu.au> <8b336527.0404151019.14b93502@posting.google.com> <5KydnYqkwP1ES-PdRVn-vA@powergate.ca> <8b336527.0404190831.65f7f7e2@posting.google.com> Message-ID: kk wrote: > > Peter Hansen wrote: >>kk wrote: >>>That is exactly my point! >> >>Uh, sorry, but what point? The email address and initials you >>are using here (kkennedy65 at yahoo.com and kk) have not posted >>before in this thread, as far as I can see. So who are you? :-) > I was responding to your point made earlier. > > I was the one that started the thread, look again. Ah, thanks. Mozilla had dropped the earlier messages, but Google Groups helped me out. And yes, I see that that was exactly your point. :-) -Peter From peter at semantico.com Tue Apr 6 07:41:45 2004 From: peter at semantico.com (Peter Hickman) Date: Tue, 06 Apr 2004 12:41:45 +0100 Subject: design by contract versus doctest In-Reply-To: <407174ea$0$5066$4d4ebb8e@news.nl.uu.net> References: <407174ea$0$5066$4d4ebb8e@news.nl.uu.net> Message-ID: <4072977b$0$1699$afc38c87@news.easynet.co.uk> aku wrote: > But in "design by contract" this responsibility is squarely > on the shoulders of the caller, and is *not* checked in > the function. Are you sure about this. If the called function did the checking then it will always be checked and the checks would be in one place and easy to update. If it the checks were done by the caller then the tests need to be placed everywhere the function is called. That alone would be a maintenance mightmare. Looking at the Eiffel site the contract is enforced within the called function. put (x: ELEMENT; key: STRING) is -- Insert x so that it will be retrievable through key. require count <= capacity not key.empty do ... Some insertion algorithm ... ensure has (x) item (key) = x count = old count + 1 end But then this is the python news group so I expect the father of DbC, Bertrand Meyer, is wrong. No Smilley From psXdaXsilva at esotericaX.ptX Fri Apr 16 20:32:42 2004 From: psXdaXsilva at esotericaX.ptX (Paulo da Silva) Date: Sat, 17 Apr 2004 01:32:42 +0100 Subject: idle: Watch self.vars Message-ID: <1082163007.243512@jubilee.esoterica.pt> How can I see the value of a self.var in a class object when in a breapoint using "idle"? From fumanchu at amor.org Fri Apr 23 11:22:57 2004 From: fumanchu at amor.org (Robert Brewer) Date: Fri, 23 Apr 2004 08:22:57 -0700 Subject: Setting variable values from dictionary Message-ID: Sean Berry wrote: > If I have a dictionary like the following: > > {'category' : 2, 'shape', 4} > > How can I use this to make > category = 2 and > shape = 4. > > I want to be able to do this regardless of the dict values type. So: > > {'cateogry' : 2, 'shape' : 'circle'} > > will work as well. Others will probably show you how to do this, but in most cases, I've been better off making attributes of a new object instead of module-level globals. >>> attrs = {'category' : 2, 'shape' : 'circle'} >>> class Namespace(object): pass ... >>> ns = Namespace() >>> ns.__dict__.update(attrs) >>> ns.shape 'circle' ...that way, you "cordon off" all of your shiny new dynamic 'variables' into their own namespace. Robert Brewer MIS Amor Ministries fumanchu at amor.org From davidb at mcs.st-and.ac.uk Fri Apr 30 08:07:01 2004 From: davidb at mcs.st-and.ac.uk (David Boddie) Date: 30 Apr 2004 05:07:01 -0700 Subject: pyuic for qtdesigner 3.3 References: Message-ID: <4de76ee2.0404300407.2e6dfa4@posting.google.com> Christopher Grinde wrote in message news:... > I've had trubles getting a puic that translates files from qt-designer 3.3 > Does anyone if there exist one, and if so, where to get it? This thread on the PyQt/PyKDE mailing list might be relevant: http://mats.imk.fraunhofer.de/pipermail/pykde/2004-April/007687.html Good luck! David From llothar at web.de Wed Apr 14 18:45:17 2004 From: llothar at web.de (Lothar Scholz) Date: 14 Apr 2004 15:45:17 -0700 Subject: Difficulty Finding Python Developers References: <65cbc3dd.0404140641.3501fde8@posting.google.com> <65cbc3dd.0404141018.36d9d4ce@posting.google.com> Message-ID: <6ee58e07.0404141445.5c0136b8@posting.google.com> pm_mon at yahoo.com (Paul Morrow) wrote in message news:<65cbc3dd.0404141018.36d9d4ce at posting.google.com>... > For those who've asked... > > This particular project is essentially a web-based registration > application. We'll probably want to use mod_python to serve the > pages, and Oracle for the database backend. It will have things like > a white-paper area that requires registration to access, an opt-in/out > email component, and the like. > > But we do want the developer to be physically here (in Atlanta). Hmm, do you have any information if it is possible to get a working permit for europeans for such a short time ? This could increase your chances a lot. But from what i know the three month will pass until i get all the bureaucracy overhead done. From moosebumps at moosebumps.com Thu Apr 22 02:56:15 2004 From: moosebumps at moosebumps.com (Moosebumps) Date: Thu, 22 Apr 2004 06:56:15 GMT Subject: String/source code analysis tools Message-ID: I have a whole bunch of script files in a custom scripting "language" that were basically copied and pasted all over the place -- a huge mess, basically. I want to clean this up using Python -- and I'm wondering if there is any sort of algorithm for detecting copied and pasted code with slight modifications. i.e. a simple example: If I have two pieces of code like this: func1( a, b, c, 13, d, e, f ) func2( x, y, z, z ) and func1( a, b, c, 55, d, e, f ) func2( x, y, z, x ) I would like to be able to detect the redundancies. This is obviously a simple example, the real code is worlds messier -- say a 3 line script, each line has 800 characters, copied 10 times over with slight modifications among the 800 characters. I'm not exaggerating. So I'm wondering if there is any code out there that will assist me in refactoring this code. My feeling that a general solution this is very intractable, but I thought I'd ask. I'd probably have to roll my own based on the specifics of the situation. It is actually sort of like a diff algorithm maybe, but it wouldn't go line by line. How would I do a diff, token by token? I don't know anything about what algorithms diffs use. thanks, MB From ml at dynkin.com Sun Apr 18 00:39:02 2004 From: ml at dynkin.com (George Yoshida) Date: Sun, 18 Apr 2004 13:39:02 +0900 Subject: Creating function object from text In-Reply-To: <40815ab3$0$16479$61fed72c@news.rcn.com> References: <40815ab3$0$16479$61fed72c@news.rcn.com> Message-ID: Edward C. Jones wrote: > Suppose I have a piece of text that defines a function: > > text ="""\ > def fun(i): > return i + 2 > """ > > How do I turn this into a function object, f, which can be called or > passed around? Aside from Peter's advice, I'd recommend you to look into timeit.py and doctest.py. These two library is a good example of how to use exec and compile in a real application. -- George From paul at boddie.net Tue Apr 6 09:38:00 2004 From: paul at boddie.net (Paul Boddie) Date: 6 Apr 2004 06:38:00 -0700 Subject: slightly OT: BUT NEEDs to be said References: <4078daf265c69e9353e8af72542da703@dizum.com> Message-ID: <23891c90.0404060538.24238953@posting.google.com> Nomen Nescio wrote in message news:<4078daf265c69e9353e8af72542da703 at dizum.com>... > > I think it would be great for Python.org/people behind Python > to adopt this as an official mascot and DROP the god awful > references to Monty Pythons's Flying Circus. It is the later > which is causing a slow take up and reluctance of many > individuals using Python. PHB #1: "Python was proposed as an implementation technology for the project." PHB #2: "I didn't find Quest for the Holy Grail funny at all. Just didn't get it." PHB #1: "Scratch Python, then - do it in Java instead!" > MPFC is a very very dated concept and because of it's strange > whacky 'humour' has dubious extreme and loony left wing > allegiences is not a good backdrop for Python. You should never > bring politics into your product. I think *you* did that, actually. > Understand that in the UK a lot of people don't find MPFC > amusing, In my experience, people who make such overt generalisations about British culture don't tend to be British, but instead turn out to be people trying to flaunt some kind of British "credentials". > and many of the 'comedians' have become extremely > dispised (like Michael Palin who is universally recognised as > a figure of great nauseum) and have become objects of ridicule. Universally ridiculed in your clique? Is this what you spend your time doing these days, Mr Campbell [1]? ;-) Paul [1] http://news.bbc.co.uk/1/hi/uk_politics/3028250.stm From martin at v.loewis.de Sun Apr 11 18:28:25 2004 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Mon, 12 Apr 2004 00:28:25 +0200 Subject: print u"\u0432": why is this so hard? UnciodeEncodeError In-Reply-To: References: Message-ID: Michael Hudson wrote: > The user can set it per-terminal, at runtime, with no notification to > the running process that it has done so! I would find it acceptable to say "don't do that, then", here. However, changing the encoding should be visible to new programs running in the terminal. I wonder how much would break if Python would assume the terminal encoding is UTF-8 on Darwin. Do people use different terminal encodings? Regards, Martin From peter at engcorp.com Tue Apr 20 10:41:08 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 20 Apr 2004 10:41:08 -0400 Subject: How to check if a path *could* be a legal path? In-Reply-To: References: Message-ID: Maciej Sobczak wrote: > I have a string. > This string is to be used as a path for a new file. > I would like to check if this string *could be* a valid file name, > *before* I try to create the file itself. > In other words, I would like to know whether some string violates the > underlying OS's policies (or maybe some more restriced policies, but > portable) considering file paths. > > Does the Python library contain a functionality that allows to achieve > this goal? I don't think it does, and certainly not in a cross-platform manner. Furthermore, even on a given platform I suspect you will not find such a thing, because there are things like remote file systems which might change the rules. One file system might recognize more or fewer valid characters than another, even on the same OS. The best is probably just to define a restrictive subset of possible characters and do a simple regular expression which handles the basic path separator stuff, maybe with a little os.path.sep substituted on the fly to keep it relatively non-platform-specific. Presumably this isn't a case where you can just catch an exception at the time file creation is attempted? After all, even with a valid file name, you could still have several types of error at the moment of creation. -Peter From eeide at cs.utah.edu Fri Apr 23 13:04:29 2004 From: eeide at cs.utah.edu (Eric Eide) Date: Fri, 23 Apr 2004 11:04:29 -0600 (MDT) Subject: AOP use cases References: <84fc4588.0404140106.3fa0c55@posting.google.com> <0pydnSB4WYuieuLdRVn-hQ@powergate.ca> Message-ID: "Will" == Will Stuyvesant writes: Will> Forget about *real* real-world examples, these people just want Will> to get papers published. Perhaps that explains IBM's excitement about aspect-oriented technologies, as reported here: Will> Usability is considered of minor impportance. Perhaps that explains why AspectJ 1.1 received a Jolt Productivity Award in the "Languages and Development Environments" category, as reported here: Will> I have come to the conclusion that AOP is nothing more than what Will> I expect from a decent programmer: a good, or at least Will> reasonable, design of software in the first place. I would say that the *goal* of AOP is "nothing more" that what you would expect from a good programmer: good implementation of good software designs. AOP is a an approach that augments existing approaches, such as OOP, for obtaining that goal. Eric. PS --- ObPython: I think it would be great to see more Python involvement in the AOP/AOSD community! -- ------------------------------------------------------------------------------- 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 mab at iee Mon Apr 5 09:41:22 2004 From: mab at iee (Marco Bartel) Date: Mon, 05 Apr 2004 15:41:22 +0200 Subject: Python and USB Message-ID: <407162b0$1@news.vo.lu> Hi Folks, i just started to adapt some i2c routines from Flagship to Python. I allready succeded in porting the low-level-routines accessing the parallel port. But now i also changed the electronics, so that my i2c-bus is connected to the usb-port of my machine. What i'am looking for now, is a way to access the usb-subsystem from python. i know there is a library called libusb for c , wich deals with the usb-kernel-modules, but unfortunatly i didn't found a wrapper around this library, wich allows me to do the same from within python. I just was thinking about to do the wrapper myself using SWIG, but i also still hope, that there is someone outside, who played allready with usb and python arround. great thanks in advance for some tips and hints Marco From donn at drizzle.com Sat Apr 3 23:52:45 2004 From: donn at drizzle.com (Donn Cave) Date: Sun, 04 Apr 2004 04:52:45 -0000 Subject: Simulate socket with files or stdin/stdout References: <106t7bin3d7vf93@corp.supernews.com> Message-ID: <1081054362.25117@yasure> Quoth claird at lairds.com (Cameron Laird): [... re invoking application with connected socket for unit 0 & 1 ...] | I wonder how close the effect will be to recreation of inetd | . Pretty close, given the root privilege to configure inetd and no intent to add any authorization checks, logging or other embellishments. Donn Cave, donn at drizzle.com From jdhunter at ace.bsd.uchicago.edu Fri Apr 16 16:25:01 2004 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Fri, 16 Apr 2004 15:25:01 -0500 Subject: datetimes, tzinfo and gmtime epoch In-Reply-To: (John Hunter's message of "Fri, 16 Apr 2004 14:40:02 -0500") References: Message-ID: >>>>> "John" == John Hunter writes: John> I *think* this is correct, where x is a datetime instance John> and tz is a tzinfo instance. No goddawgy, I'm still off by an hour. Basically, I need to go from datetime -> gm epoch time -> and back while properly accounting for dst. My converter class is below. The assertion fails, and the print reveals I'm off by an hour. Where is the timbot when you need him? from your_tz_module import Eastern import time from datetime import datetime SEC_PER_DAY = 24*3600 class PyDatetimeConverter: """ Convert python2.3 datetime instances to/from epoch gmtime """ def __init__(self, tz=Eastern): self.tz = tz def epoch(self, x): 'convert userland datetime instance x to epoch' offset = self.tz.utcoffset(x).days*SEC_PER_DAY + \ self.tz.utcoffset(x).seconds return time.mktime( x.timetuple() ) + offset def from_epoch(self, e): 'return a datetime from the epoch' y,month,d,h,m,s,wd,jd,ds = time.gmtime(e) return datetime(y,month,d,h,m,s, tzinfo=self.tz) tz = Eastern dt1 = datetime(2004, 03, 01, tzinfo=tz) # before dst dt2 = datetime(2004, 04, 15, tzinfo=tz) # after dst dtc = PyDatetimeConverter(Eastern) #assert( dtc.from_epoch( dtc.epoch(dt1) ) == dt1 ) print dt1, dt2 print dtc.from_epoch( dtc.epoch(dt1) ), dtc.from_epoch( dtc.epoch(dt2) ) From ramen at lackingtalent.com Thu Apr 29 20:43:56 2004 From: ramen at lackingtalent.com (Dave Benjamin) Date: Fri, 30 Apr 2004 00:43:56 -0000 Subject: Simple prototyping in Python Message-ID: The recent conversation on prototype-based OOP and the Prothon project has been interesting. I've been playing around with the idea for awhile now, actually, since I do a lot of programming in JavaScript/ActionScript. I feel like people are focusing too much on the "prototype chain", which to me is mainly an attempt at reintroducing inheritance. I almost never use inheritance anymore, preferring delegation instead in most cases. What I think is much more interesting about the prototype-based style is the ability to create and pass around anonymous objects. JavaScript has a syntax for this: var o = {a: 5, b: 6} which is roughly equivalent to Python's: class Whatever: pass o = Whatever() o.a = 5 o.b = 6 If you can tolerate some Lispism, you can actually create anonymous objects in straight Python. This is liable to get some adverse reactions, but I just want to demonstrate that it *can* be done. Here's an example: class obj: def __init__(self, **kwds): self.__dict__.update(kwds) def set(self, name, value): setattr(self, name, value) def do(*args): return args[-1] def counter(start): ref = obj(value=start) return obj( current = lambda: ref.value, next = lambda: do( ref.set('value', ref.value + 1), ref.value)) c = counter(0) print c.current() print c.next() print c.next() print c.current() This outputs: 0 1 2 2 -- .:[ dave benjamin: ramen/[sp00] -:- spoomusic.com -:- ramenfest.com ]:. : please talk to your son or daughter about parametric polymorphism. : From mikael at isy.liu.se Thu Apr 8 06:05:02 2004 From: mikael at isy.liu.se (Mikael Olofsson) Date: Thu, 8 Apr 2004 12:05:02 +0200 Subject: list comprehensions In-Reply-To: References: Message-ID: <20040408120502.00a23387.mikael@isy.liu.se> "Elaine Jackson" wrote: > [snip] I've discovered that you get an error from > > x = [(i,j) for i in range(7-j) for j in range(3)] > > while > > y = [[(i,j) for i in range(7-j)] for j in range(3)] > > works fine. [snip] I will not argue about intuitiveness, but FYI: z = [(i,j) for j in range(3) for i in range(7-j)] works fine. Others can explain why it is one way and not the other. /Mikael Olofsson Universitetslektor (Associate professor) Link?pings universitet ----------------------------------------------------------------------- E-Mail: mikael at isy.liu.se WWW: http://www.dtr.isy.liu.se/en/staff/mikael Phone: +46 - (0)13 - 28 1343 Telefax: +46 - (0)13 - 28 1339 ----------------------------------------------------------------------- Link?pings kammark?r: www.kammarkoren.com Vi s?ker tenorer och basar! From nish20 at netzero.net Tue Apr 6 16:58:45 2004 From: nish20 at netzero.net (Mike Nishizawa) Date: 6 Apr 2004 13:58:45 -0700 Subject: OFF-TOPIC:: Why Lisp is not my favorite programming language References: <165b3efa.0403030443.4d591f04@posting.google.com> <40460dd5$0$5916$7a628cd7@news.club-internet.fr> Message-ID: mintiSPAMBLOCK at yahoo.com (Minti) wrote in message news:... > nish20 at netzero.net (Mike Nishizawa) wrote in message news:... > > These posts are like big huge neon signs that say, "I'm IGNORANT." If > > you hold that 1 language is better than all other languages, then you > > ARE ignorant. LISP is a parsing language. It's obviously not made to > > do the same things that C is. LISP is extremely fast for processing > > data files. > > > > C in not an end-all be-all of programming languages, even though it is > > quite robust. For instance, C is great if you are going to develop > > software for 1 platform. However, if you are developing software for > > multiple platforms, Java is a better choice. > > > > Really these discussions boil down to the programmer him/herself, who > > is usually the one at fault for poor performance. I'm not quite sure > > when this happened, but at some point programmers started relying on > > hardware for fast, efficient software and from that point on, the > > quality and emphasis placed on writing efficient programs has > > diminished. If you want your code to run faster, make it more > > efficient... make it use less resources... and use the right language > > for the job. Don't try to fit all things under one umbrella because > > that language has not been developed yet. > > > > > Quite valid arguments. However I have one question to ask, I am quite > naive with LISP { just couple of weekends ) but I think the OP did > raise some doubts in my mind. I mean to me LISP looks right now to be > just OK. Some people said that with all the () it is difficult to code > in but I think that with proper indentation that is absolutely > ludicurous. However when some one says that the code might be 31.? > times slower as compared to C, kinda of scares me. Could assert such > figures. I know speed is not the one and only goal but just wondering > if these figures are correct. > > > Thanks I would ask what the C program is doing. If it beats LISP at it's own game which is, list processing, then that would be different. I don't think I would choose to write an enterprise application in it, but I think it's as good a choice as anything for any type of parsing applications. And to the smart guy who feels like he can take a stab at me for calling lisp a parsing language... consider: a parser is, by definition, something that analyzes or separates (input, for example) into more easily processed components. Let's take a document, for instance. If I wanted to parse the document and separate it into words, I would write a parser to do so. What is a document but a list of words separated by spaces... an especially good application for a LISt Processing language. From peter at engcorp.com Thu Apr 15 10:09:09 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 15 Apr 2004 10:09:09 -0400 Subject: 7bit to 8bit In-Reply-To: References: <2CF1A5CA-8E8F-11D8-BBCE-000A95D05654@gmx.net> Message-ID: <4I2dnfbLZq4YCuPdRVn-uw@powergate.ca> Daniel Roth wrote: > When I try your 'line' I get: > # python > Python 2.3.3 (#2, Apr 15 2004, 04:41:13) > [GCC 3.3.3 20040110 (prerelease) (Debian)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> print "=F6=E4".decode('quopri').decode('latin-1') > Traceback (most recent call last): > File "", line 1, in ? > UnicodeEncodeError: 'ascii' codec can't encode characters in position > 0-1: ordinal not in range(128) > >>> Note that the error is coming from the attempt to print, not from the conversion. Do this instead to prove that what Mark gave you works: >>> s = "=F6=E4".decode('quopri').decode('latin-1') >>> print s (here you'll get the same error as before) >>> s u'\xf6\xe4' You can see that the string was converted properly (to a unicode string) but when you try to print it, because your terminal's encoding is ascii, it cannot be displayed properly. -Peter From simoninusa2001 at yahoo.co.uk Thu Apr 15 20:01:01 2004 From: simoninusa2001 at yahoo.co.uk (simo) Date: 15 Apr 2004 17:01:01 -0700 Subject: Python 2.3 on RedHat 9 References: Message-ID: <30260531.0404151601.bc92f2b@posting.google.com> Bill Scherer wrote: > > Did you install on top of Python 2.2 or did you install in a separate > > directory (eg the default)? > 2.3 prefix is /usr/local, RedHat's installed python prefix is /usr Yes, and that seems to be the root of all evil for me - everything I install wants to go into the /usr//python2.2 directories instead of /usr/local//python2.3! Forget the RPMs, compile everything from source is my advice (I installed 2.3.3, VPython, Installer, wxPython, PyQt, SIPs, wxGlade....) What annoyed me was when I was evaluating LindowsOS and "apt-get install libwxgtk24" installed everything for me (including Python 2.3.3!) in about 3 minutes as apposed to about 8 hours of compilation time and hunting around for source tarballs! It was even easier that Windows I think! From bdesth.quelquechose at free.quelquepart.fr Mon Apr 26 08:52:58 2004 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 26 Apr 2004 14:52:58 +0200 Subject: How's ruby compare to it older brother python In-Reply-To: References: Message-ID: <408cffbb$0$22877$626a14ce@news.free.fr> Hunn E. Balsiche wrote: > in term of its OO features, syntax consistencies, ease of use, and their > development progress. I have not use python but heard about it quite often; > and ruby, is it mature enough to be use for developing serious application, > e.g web application as it has not many features in it yet. Syntax : both Ruby and Python are pretty clean, Ruby being IMHO more consistent and Python easier to grasp OO : Ruby is OO all the way, and pretty close to Smalltalk. Python is more a mix of procedural and OO with some functional stuff too. Web : Python may have a bit more existing solutions, and a real killer app (Zope). Now, AFAIK, Ruby has also some interesting stuff for web developpement. IMHO, both are really great languages. I really like the elegance of Ruby and the ease of use of Python. So try both and pick the one that fits you're brain !-) > I've given up on Perl for its ugly syntax and it is not the easiest language > to learn. No comment... > How about PHP? One of the dumbest 'scripting' language I've ever worked with, but still a good solution for web developpement when you have no better (read : Python or Ruby) choice. Bruno From cjw at sympatico.ca Fri Apr 16 14:22:05 2004 From: cjw at sympatico.ca (Colin J. Williams) Date: Fri, 16 Apr 2004 14:22:05 -0400 Subject: CamelCase versus wide_names (Prothon) In-Reply-To: References: Message-ID: <6vVfc.33671$vF3.1961904@news20.bellglobal.com> Hans Nowak wrote: > Mark Hahn wrote: > >> We have agreed in Prothon that unlike Python we are going to be 100% >> consistant in our var and method naming. We will not have run-together >> words like iteritems, we are going to always have seperated words like >> has_key. >> >> Now we are in the midst of a discussion of camelCase versus >> wide_names. So >> far our arguments are: >> >> 1) CamelCase is more elegant, modern, more readable, and more >> efficient in >> character usage. >> >> 2) Wide_names is cleaner, more readable, compatible with C, which is the >> standard module language for Python and Prothon. Wide_names is also the >> Python standard. >> >> Of course in the Python world you alread have wide_names as your >> standard, >> but could you for the moment pretend you were picking your standard from >> scratch (as we are doing in the Prothon world) and give your vote for >> which >> you'd prefer? > > > That would be wide_names. CamelCase would be tolerable. In my own > code, I use a mixture: CamelCase for class names, wide_names for > everything else (inspired by older Python code). Not mixedCase, mind > you; IMHO, that's an atrocity. If you're going to use caps in names, > then at least the first letter should be capitalized. Putting the > capitals somewhere in the middle but not in the front seems very > unnatural to me. > My preferences are: module names: lower case. to cope with case insensitive file systems class names: PascalCase. this is comonly used other names: camelCase. one has to choose something and this avoids underscores indent depth: 2 two is enough to give a visual break and this reduces line wrape with multiple indents On the other hand as another contributor said, when amending existing code, it make sense to try to stick with whatever was done before. Colin W. From eddie at holyrood.ed.ac.uk Thu Apr 22 06:11:23 2004 From: eddie at holyrood.ed.ac.uk (Eddie Corns) Date: Thu, 22 Apr 2004 10:11:23 +0000 (UTC) Subject: A python telnet entry level question References: Message-ID: "Jinming Xu" writes: >Hello Everyone, >I am trying to write a python script to telnet to a server and then do >something there. As the first step, I practiced the python example in Lib >Reference 11.13.2. But I am finding the script stops after I supplied the >password. Does anyone know why? >Thanks in advance! >Jinming Xu >PS: Here is the script: >import getpass >import sys >import telnetlib >HOST = "localhost" >user = raw_input("Enter your remote account: ") >password = getpass.getpass() >tn = telnetlib.Telnet(HOST) >tn.read_until("login: ") >tn.write(user + "\n") >if password: > tn.read_until("Password: ") > tn.write(password + "\n") >tn.write("ls\n") >tn.write("exit\n") >print tn.read_all() You are maybe being too specific in what you match for. At least one of my machines prompts: Pasword for : rather than just "Password: ". I tend to match things like "ogin" (in case of Login vs login) "assword" (will this get filtered out by censoring s/w?) Eddie From jbore at tjtech.com Wed Apr 14 16:02:53 2004 From: jbore at tjtech.com (Joseph T. Bore) Date: Wed, 14 Apr 2004 20:02:53 GMT Subject: interpreter limits References: <407c23bf$0$570$e4fe514c@news.xs4all.nl> <407c2ecc$0$574$e4fe514c@news.xs4all.nl> <7xisg3vfat.fsf@ruckus.brouhaha.com> Message-ID: There is probably a better solution but this worked for me, thanks Irmen! jb ---------------------------------------- import signal def alarmHandler(signum, frame): raise TimeExceededError, "Your command ran too long" def infinite(): while 1: pass # # code to wrap a function call which may take too long... # signal.signal(signal.SIGALRM, alarmHandler) signal.alarm(1) try: # call a function that never returns infinite() except TimeExceededError: print "code must have gone crazy..." signal.alarm(0) ---------------------------------------- From surrender_it at remove.yahoo.it Sun Apr 4 10:11:02 2004 From: surrender_it at remove.yahoo.it (gabriele renzi) Date: Sun, 04 Apr 2004 14:11:02 GMT Subject: =?iso-8859-1?q?Re=3A_Working_with_a_list_in_a_more_=84pythonic?= =?iso-8859-1?q?=93_way?= References: <20040404124833458+0200@news.rhrz.uni-bonn.de> Message-ID: il 4 Apr 2004 10:48:28 GMT, Nickolay Kolev ha scritto:: >I have come up with the following solution, but I hope some of you might >suggest a more _functional_ (reduce and map) way of diong it. > >n = 0 # the final score of the string > >for i in range(len(phrase)): > try: > n += soundScoreMatrix[ord(x[i]) - 65][ord(x[i + 1]) - 65] > except IndexError: > pass > >I was thinking about using "reduce", but that would not work as the >input and output of the function I would use are different (string input, >integer output). why not? you just need to say to reduce to use a 0 as the first parameter: say: def get_val(x): # gets the value from SSMatrix, now dumb return ord(x) reduce(lambda a,b: a+get_val(b),list('blablabla'),0) #909 From michele.simionato at poste.it Tue Apr 6 07:09:19 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 6 Apr 2004 04:09:19 -0700 Subject: Using function parameters to determine method kind References: <4qrzym6e.fsf@telus.net> <95aa1afa.0404050417.2d11b369@posting.google.com> <8yh9r7p2.fsf@telus.net> Message-ID: <95aa1afa.0404060309.32629338@posting.google.com> Lenard Lindstrom wrote in message news:<8yh9r7p2.fsf at telus.net>... > Michele Simionato wrote: > >Lenard Lindstrom wrote in message > > news:<4qrzym6e.fsf at telus.net>... > >> I was wondering if anyone has suggested having Python determine > >> a method's kind from its first parameter. > ... > >I find relaying on tbe parameter name to specify the kind of method > >to be rather fragile. It works most times but not always. What about > >inner classes for instance? > Do you mean: > from dparams import Object > class A(Object): > class B(Object): > def __init__(self, x): self.x = x > b=A.B(x) > ? No, I had in mind this (contrived) example: class Outer(object): def outermeth(self1): class Inner(object): def innermeth(self2): ... It is nice to have the ability to give any name to "self". > Class A.B is not affected. Parameter checking only happens for > instances of type function. Other callables have to be or > use descriptors to be anything other than static. As for B's > methods, parameter checking works just fine. My module is > more of a demonstration than a practical solution anyway. > I would suggest a different approach for implementing > parameter checking in the python interpreter. > > > Also, there are situations where you want > >a method to work both with instances and classes, so do you want to > >use self or cls? > I can only imagine one way to do this now, wrap the function in a > descriptor. > > >>> from dparams import Object > >>> from types import MethodType > >>> class bimethod(Object): > ... def __init__(self, f): self.f=f > ... def __get__(self, o, t): > ... if o is None: return MethodType(self.f, t, type(t)) > ... return MethodType(self.f, o, t) > ... > >>> class A(Object): > ... def bi(x): return x > ... bi=bimethod(bi) > ... > >>> A.bi() > > >>> A().bi() > <__main__.A object at 0x0119C1B0> > > Descriptors are unaffected by the function's parameters, so the first > parameter can be anything you want. If I am not mistaken, the only > methods other that __new__ that currently work without descriptors > are instance methods. ?? All methods works with descriptors, what do you mean? > Is it not good form for instance methods to > start with 'self' anyways? (except maybe for a metaclass's __init__, > but this is a special case) It is not a special case (no special case is special enough or something like that). From usenet_spam at janc.invalid Fri Apr 30 22:30:36 2004 From: usenet_spam at janc.invalid (JanC) Date: Sat, 01 May 2004 02:30:36 GMT Subject: Using C libraries References: Message-ID: "Laughlin, Joseph V" schreef: > I was thinking more along the lines of unix C libraries, not windows > DLL. >From the ctypes documentation: """ ctypes is a Python package to create and manipulate C data types in Python, and to call functions in dynamic link libraries/shared dlls. It allows wrapping these libraries in pure Python. It works on Windows, Linux and MacOS X (the latter two require that your machine is supported by libffi). """ -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From teiffel at attglobal.net Mon Apr 19 21:38:42 2004 From: teiffel at attglobal.net (Marcello Pietrobon) Date: Mon, 19 Apr 2004 21:38:42 -0400 Subject: raw_input Message-ID: <40847F22.8040707@attglobal.net> Hello, even if I learned something about Python, still I don't know how to do ask the input from a user on the command line This is my ( not working ) code: if ( not os.path.exists( dirname) ): msg = 'The directory \'%s\' does not exist. Create it [y/n] ?' % dirname c = raw_input( msg ).lower if ( c == 'y' or c == 'yes' ): os.makedirs( dirname) else: raise Exception( 'directory \'%s\' not created, impossible to continue !' % dirname ) Thank you for any answers, Marcello From matthew at barnes.net Tue Apr 13 13:06:45 2004 From: matthew at barnes.net (Matthew Barnes) Date: 13 Apr 2004 10:06:45 -0700 Subject: Adding properties to objects Message-ID: <3a8e83d2.0404130906.2ea796e9@posting.google.com> Is it possible to add properties to objects dynamically? I have an instance (x) of some new-style class (Foo), and I would like to be able to do something like: >>> x = Foo() >>> x.myproperty = property(getsomething, setsomething, delsomething); >>> x.myproperty # invokes getsomething >>> x.myproperty = 1 # invokes setsomething >>> del x.myproperty # invokes delsomething However, when I evaluate x.myproperty I get back a property object (which makes sense). I get the feeling I'm missing a step to "bind" the property object to the class instance. Is this possible (it's Python... of course it's possible, right?), and if so, how? Matthew Barnes From kkennedy65 at yahoo.com Thu Apr 15 14:19:52 2004 From: kkennedy65 at yahoo.com (kk) Date: 15 Apr 2004 11:19:52 -0700 Subject: Does Python compete with Java? References: <8b336527.0404051337.51bb4a1b@posting.google.com> <407deb56$1@news.unimelb.edu.au> Message-ID: <8b336527.0404151019.14b93502@posting.google.com> That is exactly my point! If I were starting a company that needed a staff to write custom software or software for sale, I could choose to use Python as the predominate tool. Assuming this was a rational decision, and not an emotional one, this could lower my costs by making programmers more productive, and making maintenance cheaper. However, if there are no programmers in my area that know Python, how could I justify that decision? I would have the expense of training programmers on the job, as well as having a hard time getting applicants for the job. Python doesn't have big company dollars behind it like Java and C#, and some say it never will. It could be argued that the same thing was said about Linux a few years ago. Now, you can't pick up an IT rag without reading something about Linux and Open Source. compete -> as in developer mind-share. I would hope that someday Python would be a "tool" that "most" developers would want to have in their "tool box". Peter Hansen wrote in message news:... > Maurice LING wrote: > > A. Lloyd Flanagan wrote: > >> Dave Benjamin wrote: > >>> Over the long term, I think Python's biggest key to success will be > >>> that we will still be able to read the programs that we are writing now. > >> > >> No argument here :) > > > > I don't quite understand, does Python have to compete with Java? In many > > cases, the programming language used to write an application almost has > > no relevance to the acceptance of the application. > > That's not the whole picture though. One would also like to be able > to easily find programmers capable of working very effectively with > the language, so that maintenance can be performed, and enhancements, > and new projects using the same language. > > This "competition" he's talking about is not really going on in the > users' minds, but in the developers' minds. Imagine how difficult it > would be to get anywhere with projects if there were so many popular > languages that the odds of a given developer knowing your language > were, say, less than 2%... > > > What I see is that Python and Java can be synergistically linked, for > > example, through Jython, can be more constructive than competition... > > That is yet another of Python's strengths. ;-) > > -Peter From marklists at mceahern.com Thu Apr 29 20:30:16 2004 From: marklists at mceahern.com (Mark McEahern) Date: Thu, 29 Apr 2004 19:30:16 -0500 Subject: Closures In-Reply-To: References: Message-ID: <1083285016.2411.59.camel@dev.internal> On Thu, 2004-04-29 at 17:17, Michael Sparks wrote: > On Thu, 29 Apr 2004, Gustavo Niemeyer wrote: > > > class Closure: > > def __init__(self): > > self.__dict__ = sys._getframe().f_back.f_locals > > Out of interest how portable is this? Strikes me as extremely useful > class to have lying around :) The only thing that makes me wonder is the > access to _getframe... There are more straightforward ways to get at locals--here's a modified version that uses doctest to demonstrate/prove what the code does. Is the value of Closure--beyond just plain old nested scopes--that you don't have to pass counter into getFunc()? #!/usr/bin/env python import doctest import unittest class Closure: def __init__(self, **kwargs): self.__dict__.update(kwargs) def getFunc(): """ >>> c = getFunc() >>> c() 1 >>> c() 2 >>> c() 3 """ counter = 0 c = Closure(**locals()) def count(): c.counter += 1 print c.counter return count def test_suite(): return doctest.DocTestSuite() if __name__ == '__main__': unittest.main(defaultTest='test_suite') From tjreedy at udel.edu Thu Apr 29 16:43:48 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 29 Apr 2004 16:43:48 -0400 Subject: Create object for item in list References: <39885b3c.0404291110.7bd152ba@posting.google.com> Message-ID: "Helge" wrote in message news:39885b3c.0404291110.7bd152ba at posting.google.com... > I wonder how this can be accomplished: > > I've got a list, containing several strings. The strings look like > this: > > [ "Name1/N1/N2/N3" , "Name2/N1/N2/N3" , "..." ] > > I would like to create one object for each item in the list, and the > name of the object should be "str(item.split("/")[0])". Binding and using dynamic names in the global (or function local) namespace is generally a nuisance. The standard idiom is to use a separate dictionary as a namespace for just those items. Something like myobs = {} for datastring in namedata: data = datastring.split('/') myobs[data[0]] = myclass(*data[1:]) Terry J. Reedy From trushe at tut.by Sat Apr 10 03:10:48 2004 From: trushe at tut.by (tru) Date: Sat, 10 Apr 2004 11:10:48 +0400 Subject: a little problem Message-ID: <40779DF8.9000207@tut.by> Hello, I'm not a specialist in Python and it occured so that my tutor gave me the task to write server part of a site in Python using CGI scripts, which should have next functions: connecting to database and putting there messages ot users, also it will be the possibility for tester to check this base and I should write a simple interfase.Would you advise me what should I start with, because I got known about Python only from his words two weeks ago. Please, do not advice me to read a lot of books before bothering you , he gave me too little time to learn it and to do it . One more thing-- I'm a student. ) best wishes , Tru. From rtw at freenet.co.uk Mon Apr 12 22:00:47 2004 From: rtw at freenet.co.uk (Rob Williscroft) Date: 13 Apr 2004 02:00:47 GMT Subject: Escaping characters in MySQLdb query References: Message-ID: Sean Berry wrote in news:AkEec.271$U83.155 at fed1read03 in comp.lang.python: > I wrote a little script that is inserting thousands of records into a > mysql database. > > How do I escape characters like ' in my insert statements? > > I have something like the following (much shorter) example: > > c.execute("INSERT INTO records (var1, var2) values ('%s', '%s')" > %(value1, value2)) > > My problem is when value1 is something like "Tom's auto supply". The > ' in Tom's needs to be escaped. How can I do this? > IIUC this is (mostly) a SQL question. c.execute( "INSERT INTO records (var1, var2) values ('%s', '%s')" % (value1.replace( "'", "''" ), value2.replace( "'", "''" )) ) I believe the standard way of puting a ' in an SQL ' delemited string is to double it i.e. '''' is a single char string "'", but check the mysql docs. http://dev.mysql.com/doc/mysql/en/String_syntax.html Apparently with mysql you can also use '\'' so: c.execute( "INSERT INTO records (var1, var2) values ('%s', '%s')" % (value1.replace( "'", "\\'" ), value2.replace( "'", "\\'" )) ) Should also work. Rob. -- http://www.victim-prime.dsl.pipex.com/ From lambajan at yahoo.com Sun Apr 4 03:49:42 2004 From: lambajan at yahoo.com (Nakamura) Date: 3 Apr 2004 23:49:42 -0800 Subject: splitting a long token across lines Message-ID: Hi all, Say, I have a very long integer constant , how can I split across lines ? I tried something like MODULUS = 7567567567567567567567567567567\ 7567507546546986094860986094860\ 2345646986598695869548498698989\ ... but it doesn't compile. Is there another way to write a long numeric constant besides writing it as a string and then converting to long? I also wouldn't like to put it all on one very long line. Thanks! From tdelaney at avaya.com Wed Apr 28 19:43:52 2004 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Thu, 29 Apr 2004 09:43:52 +1000 Subject: Backticks: What up? Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE016BCA3B@au3010avexu1.global.avaya.com> Steven Brent wrote: > Thanks! I didn't know you could use printf type syntax with return.... String formatting can be used anywhere that an expression can. There is nothing special about `return` in Python - it just returns the result of an expression. In the Python library reference ... 2.3.6.2 String Formatting Operations will tell you everything you need to know about them. Tim Delaney From mark at prothon.org Fri Apr 2 23:29:57 2004 From: mark at prothon.org (Mark Hahn) Date: Fri, 2 Apr 2004 20:29:57 -0800 Subject: Indent testers needed (Prothon) References: Message-ID: This was a bit premature. Some of our test cases give indentation errors. I'll post another file when it is really ready for testing. Meanwhile comments on our intended solution would be greatly appreciated. From peter at engcorp.com Thu Apr 22 16:10:56 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 22 Apr 2004 16:10:56 -0400 Subject: equivalent to Tcl 'after' command? In-Reply-To: References: Message-ID: <846dnYvX2qlNuxXdRVn-ig@powergate.ca> Jeff Epler wrote: > Python doesn't define any event loop of its own. asyncore has one, but > I don't think it has the concept of scheduling events at a future time, > but only of reacting to the readability / writability of sockets. > > I'm sure that more advanced systems, like Twisted, can do the kind of > thing you're asking for. It does, using reactor callLater(), but I'd go for the sched approach if it's just a one-off. From tim.one at comcast.net Sat Apr 3 11:50:17 2004 From: tim.one at comcast.net (Tim Peters) Date: Sat, 3 Apr 2004 11:50:17 -0500 Subject: ANNOUNCE: 'goto' for Python In-Reply-To: Message-ID: [Roger] >> http://www.fortran.com/come_from.html >> http://c2.com/cgi/wiki?ComeFrom >> http://aspn.activestate.com/ASPN/CodeDoc/Acme-ComeFrom/ComeFrom.html [Richie Hindle] > Thanks for the references! It's a bit of an embarrassment for the > Python community that it's taken us so long to catch up. Guido has already accepted your module for inclusion in Python 2.4, and I expect he'll use his time machine then to ensure that it's always been part of Python. > And it's a bit of an embarrassment for me that I didn't implement > "goto " or "comefrom " - I'll implement those > in the next release. That would be confusingly low-level. If you haven't used Fortran, you may not have realized that Clark's examples never used line numbers. In Fortran, you have the option of putting a non-negative integer in columns 1 through 5 of a statement. There are no restrictions on the integers you can put there (e.g., they needn't bear any relation to line number, and don't even have to be increasing top-to-bottom), except that no two statements can have the same integer attached. So Clark *was* using labels, not line numbers -- they're simply integer labels. Your introduction of alphanumeric labels to Python is already far advanced. I must say, though, that the restriction to 5 digits in Fortran had the nice Pythonic effect of discouraging a subroutine from containing more than a hundred thousand branch targets (if you wanted more than that, you had to play obscure tricks to worm around the no-more-than-1E5-labels restriction, and that had a healthy moderating effect -- sad to say, most programmers start to lose track after just a few tens of thousands of branch targets!). BTW, because Fortran ignored whitespace, these labels were all the same: 123 123 123 01 23 1 2 3 00123 > (Computed and conditional comefroms are already on the list, as are > computed labels, which I'm surprised to see missing from Clark's paper. > His "assigned COME FROM" is almost the same thing, but I found it > confusing - computed labels seem like a much clearer way of achieving > the same thing.) As above, the conflict is an illusion: Clark is also using labels, they're just integer labels. Full speed ahead! From nikolai.kirsebom.NOJUNK at siemens.no Fri Apr 30 03:04:11 2004 From: nikolai.kirsebom.NOJUNK at siemens.no (Nikolai Kirsebom) Date: Fri, 30 Apr 2004 09:04:11 +0200 Subject: Automated installation framework Message-ID: Does anyone know of an 'automated installation framework' written in Python / accessible from Python ? Could it be an idea to use the unittest module as a framework for making such a system, using the 'setup-action' to make precondition testing, 'run' to do the actual installation and the 'teardown-action' to do verification. Opinions are appreciated. In our case, the target system is (multi-machine) Windows. Nikolai From adam_gautier at yahoo.com Sat Apr 3 11:27:50 2004 From: adam_gautier at yahoo.com (Adam T. Gautier) Date: Sat, 03 Apr 2004 11:27:50 -0500 Subject: Working with bytes. Message-ID: <406EE606.4000604@yahoo.com> I have been unable to solve a problem. I am working with MD5 signatures trying to put these in a database. The MD5 signatures are not generated using the python md5 module but an external application that is producing the valid 16 byte signature formats. Anyway, these 16 byte signatures are not nescarrally valid strings. How do I manipulate the bytes? I need to concatenate the bytes with a SQL statement which is a string. This works fine for most of the md5 signatures but some blow up with a TypeError. Because there is a NULL byte or something else. So I guess my ultimate question is how do I get a prepared SQL statement to accept a series of bytes? How do I convert the bytes to a valid string like: 'x%L9d\340\316\262\363\037\311\345<\262\357\215' that can be concatenated? Thanks From pm_mon at yahoo.com Fri Apr 16 13:46:39 2004 From: pm_mon at yahoo.com (Paul Morrow) Date: Fri, 16 Apr 2004 13:46:39 -0400 Subject: Difficulty Finding Python Developers In-Reply-To: References: <65cbc3dd.0404140641.3501fde8@posting.google.com><5d83790c.0404150701.605782a7@posting.google.com><7xpta8hqe7.fsf@ruckus.brouhaha.com><7xsmf4kbac.fsf@ruckus.brouhaha.com><7x7jwg7ipn.fsf@ruckus.brouhaha.com> Message-ID: > And in case my point was unclear: the OP asked about something > which seemed like a very simple experimental project to get their > feet wet with Python. It is somewhat of an experiment, but the application is to be used in an actual production system. The experiment is to see how viable Python outsourcing is in our area, in the event the inhouse developers get swamped and we need help fast... We're now in the process of creating a posting for (at least) monster.com, so those interested in the position can apply. From marco.terzuoli at libero.it Tue Apr 27 18:27:51 2004 From: marco.terzuoli at libero.it (Marco Terzuoli) Date: Tue, 27 Apr 2004 22:27:51 GMT Subject: insert-at-cursor doesn't work Message-ID: Hi, I have created a window and placed a gtk.Entry inside it. I would like to perform some tasks when the text of the entry is changed, so I have created a connection such as this: self.name_text=gtk.Entry() self.name_text.connect("insert-at-cursor",self.name_text_changed,None) Also, I have defined the function name_text_changed as follows: def testo_cambiato(self,entry,string,data=None): I don't receive any error while the program is run, but actually nothing works.... I have tried to deal with other signals concerning the entry such as activate and delete-from-cursor and they worked perfecly, so I just don't understand what's wrong with my code. Can anybody help? Thanks Marco From theller at python.net Fri Apr 2 12:51:36 2004 From: theller at python.net (Thomas Heller) Date: Fri, 02 Apr 2004 19:51:36 +0200 Subject: py2exe and the path module Message-ID: Several users have been bitten by the incompatibility of py2exe and Jason Jorendorff's path module at http://www.jorendorff.com/articles/python/path/. I think I have found the bug in modulefinder that leads to the unbounded recursion when the path module is installed, and posted a patch to the wiki: http://starship.python.net/crew/theller/moin.cgi/PathModul It would be nice if some people at least could try out the patch (even some that don't have the path module), and report whether it works or not. Thanks, Thomas From steve at ninereeds.fsnet.co.uk Tue Apr 6 11:15:14 2004 From: steve at ninereeds.fsnet.co.uk (Stephen Horne) Date: Tue, 06 Apr 2004 16:15:14 +0100 Subject: int('2.1') does not work while int(float('2.1')) does References: <40722555.66C70D40@alcyone.com> <40722E98.253B5FF2@alcyone.com> Message-ID: On 6 Apr 2004 11:52:32 GMT, Duncan Booth wrote: >If int(string) was changed to have this behaviour as well, then those of >who don't want any rounding wouldn't have any way to get the current >behaviour. Users may be surprised when they enter 2.1 and find the program >accepted it but didn't use the value they entered; I don't like suprising >users. Even this is debatable, as it is possible to spot the error. >>> '.' in '2.1' True Or, to be sure about it... >>> numstr = '2.1' >>> ('.' in numstr) or ('E' in numstr.upper ()) True You claim it's a case of "Explicit is better than implicit" but I don't know any typecast that is explicit about what it is casting from in any language, Python included. One way or the other, some users get a slight extra hassle. In this case I think Python got it right for two reasons... 1. Wanting to implicitly accept a float in a string as an integer is relatively unusual, so better to have the small extra hassle in this case. 2. Accidentally accepting a float in a string as an integer when you shouldn't is a bad thing - it is usually better to get a highly visible exception early in development rather than releasing a program which gives bad results without warning. But it wouldn't matter than much either way. I've used at least one language that did the conversion in one step and that never created a serious problem. As Mel Wilson said... : You could argue that unit testing, the universal solvent, : would clean up this too. -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From peter at engcorp.com Tue Apr 20 10:18:26 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 20 Apr 2004 10:18:26 -0400 Subject: Goodbye TCL In-Reply-To: <4084A419.3020004@activestate.com> References: <0LudnSads6NmpuPdRVn-vw@centurytel.net> <107u6ef5a2ise19@news.supernews.com> <4084A419.3020004@activestate.com> Message-ID: <3IGdncIrwrqvrBjdRVn-uw@powergate.ca> Jeff Hobbs wrote: > Roy Smith wrote: >> In article , >> blacksqr at usa.net (Stephen Huntley) wrote: >> >>> I would be curious to know what is the biggest-capacity Python network >>> application in use? How does it scale in comparison with AOLServer? >>> Any ideas? >> >> How about the one you're using to post your articles -- Google. > > This is no longer true - google did use Python at one point, but > now it is reserved for internal company stuff only, as google > really required hard-core C/C++ for the speed and scale at which > it performs. Doubtless you have real evidence to back up this claim? Proof that shows that you aren't just mistaken about where Python was ever used in that company? (Hint: it was never used to run the web servers themselves, of course, but was and still is used for the "gathering" side of things.) -Peter From me at privacy.net Sat Apr 24 09:59:12 2004 From: me at privacy.net (Heather Coppersmith) Date: 24 Apr 2004 09:59:12 -0400 Subject: How to check if a path *could* be a legal path? References: Message-ID: On Sat, 24 Apr 2004 08:52:31 -0400, Peter Hansen wrote: > Jorgen Grahn wrote: >> By the way, for Unix the test is pretty easy. It's more or less >> def isValid(path): return path and not '\0' in path > Aren't there also length limits, and limits which differ > depending on the specific *nix variant one has? And "/" is still reserved for the directory separator. Regards, Heather -- Heather Coppersmith That's not right; that's not even wrong. -- Wolfgang Pauli From See_my at Signature.com.invalid Sun Apr 18 07:15:41 2004 From: See_my at Signature.com.invalid (Tuxtrax) Date: Sun, 18 Apr 2004 11:15:41 GMT Subject: help with str() Message-ID: Hi all. I have need of assistance on something that should be very simple, and is driving me absolutely batty. This is a code snippet from a short program that downloads news headers via nntplib. getinput() is simply a function I have defined for using raw_input in a friendly fashion. message_request = getinput("\nHow many posts should I be interested in? [max 10,000]") if int(message_request) > int(number_of_messages): print "\nRequest exceeds current available message count. Adjusting to %s posts" % number_of_messages message_request = number_of_messages elif int(message_request) > 10000: print "\nRequest exceeds program capacity. Assuming max of 10,000 posts, and continuing ...." message_request = "10000" The trouble comes in when I try to convert last_message into a string: last_message = str(int(first_available_message) + int(message_request)) I also tried variations on a theme like: last_message = int(first_available_message) + int(message_request) string_result = str(last message) No dice. In every case, I get the following error: Traceback (most recent call last): File "headhunter.py", line 317, in ? response, poster = n.xhdr("from", first_available_message+"-"+str(last_message)) TypeError: 'str' object is not callable I have tried everything I could think of and there is only one possibility still left that I can think of. My theory is this: by using the int() function, I am typing the numbers in the last_message assignment to type integer, and str() is expecting type float, or something. I am stuck. Thanks for any help you all can provide. I appreciate it. best regards, Mathew -- ROT 13 this address to mail me: bar jbeq abg guerr; uvtu qrfreg zna, gura nqq - ng lnubb qbg pbz. From PPNTWIMBXFFC at spammotel.com Wed Apr 28 11:27:58 2004 From: PPNTWIMBXFFC at spammotel.com (Marco Aschwanden) Date: Wed, 28 Apr 2004 17:27:58 +0200 Subject: Path ... where is my application's home dir? References: Message-ID: Your answer is very much appreciated! Thanks a lot, Marco From theller at python.net Fri Apr 30 09:46:33 2004 From: theller at python.net (Thomas Heller) Date: Fri, 30 Apr 2004 15:46:33 +0200 Subject: Automated installation framework References: Message-ID: Nikolai Kirsebom writes: > On Fri, 30 Apr 2004 13:36:02 +0200, Thomas Heller > wrote: > >> >>Is it this that you have in mind? >> >>Martin von L?wis, packing Python with Microsoft Installer: >>http://www.python.org/pycon/dc2004/papers/44/ >> > Not really. I'm looking for a system which can be used to install an > application in an environment. As an example: Have you read the paper? The title talks about packaging the Python distribution, but what Martin does is creating the msi installer using Python. In other words, a Python framework to create msi packages, which could contain anything... Sorry if I misunderstood again. Thomas From smallbee at rediffmail.com Thu Apr 8 00:50:05 2004 From: smallbee at rediffmail.com (Somesh Bartakkay) Date: 7 Apr 2004 21:50:05 -0700 Subject: Py2exe installation problem Message-ID: <8f198e47.0404072050.2f69ea90@posting.google.com> hello friends i am trying to install py2exe with win32 installation binary file, its giving me 'freopen std error' plz help somesh From chrish at cryptocard.com Tue Apr 20 13:01:32 2004 From: chrish at cryptocard.com (Chris Herborth) Date: Tue, 20 Apr 2004 13:01:32 -0400 Subject: Pygame book In-Reply-To: References: Message-ID: Lucas Raab wrote: > I was at the bookstore the other day and I noticed a book that dealt with > making games with Pygame. As I recall the book title was "Game Programming > with Python." I have an interest in making games, so I was wondering if any > of you have this book and if you do, could you please give me a nice > overview and whether I should buy the book or not. Assuming it's this one: http://www.amazon.ca/exec/obidos/ASIN/1584502584/ ("Game Programing with Python" by Sean Riley) it certainly looks good; I'd love to pick up a copy. I'll definitely keep my eye out for it the next time I'm in Chapters. 3 reviewers all gave it 5/5 stars. There's another one: http://www.amazon.ca/exec/obidos/ASIN/1592000770/ ("Game Programming with Python, Lua and Ruby" by Tom Gutschmidt) Neither of the two reviewers liked it (1.5/5 stars). -- Chris Herborth chrish at cryptocard.com Documentation Overlord, CRYPTOCard Corp. http://www.cryptocard.com/ Never send a monster to do the work of an evil scientist. Postatem obscuri lateris nescitis. From irmen at -nospam-remove-this-xs4all.nl Tue Apr 13 18:43:33 2004 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Wed, 14 Apr 2004 00:43:33 +0200 Subject: ANN: Snakelets 1.24 (simple-to-use web app server with dynamic pages) Message-ID: <407c6d15$0$562$e4fe514c@news.xs4all.nl> I'm happy to say that Snakelets 1.24 is available. Snakelets is a Python web application server, mainly for educational purposes (but it works fine, mind you). This project provides a threaded web server, Ypages (HTML+Python language, similar to Java's JSPs) and Snakelets: code-centric page request handlers (similar to Java's Servlets). It is possible to run Snakelets off a CD (read-only mode). You can download from http://snakelets.sourceforge.net More info on that site. Enjoy, --Irmen de Jong. From skip at pobox.com Tue Apr 6 12:55:13 2004 From: skip at pobox.com (Skip Montanaro) Date: Tue, 6 Apr 2004 11:55:13 -0500 Subject: CSV ignores lineterminator In-Reply-To: References: <16497.47126.723619.586429@montanaro.dyndns.org> <16497.52305.246261.519498@montanaro.dyndns.org> Message-ID: <16498.57585.149851.596214@montanaro.dyndns.org> >> I haven't the time to think deep thoughts about this problem at the >> moment. You might want to post to the csv mailing list >> (csv at mail.mojam.com) and see if one of the other csv folks can >> provide a more coherent/accurate answer. Jeffrey> For the record, the answer that I got back from one of the Jeffrey> developers is that lineterminator is used only for output. FWIW, I'm one of the module's developers but don't currently use it daily and have forgotten many of those sorts of subtleties. When I was actively working on it I tended to focus on the somewhat higher level DictReader and DictWriter classes. Skip From dkuhlman at rexx.com Wed Apr 21 19:35:21 2004 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Wed, 21 Apr 2004 16:35:21 -0700 Subject: saving interpreter source? References: Message-ID: Dave Kuhlman wrote: > Peter Hansen wrote: > >> Garett wrote: >> >>> Hello, I would like to be able to save source typed into the >>> interpreter to a file. Kind of like marshal, but I would like to >>> have the file contain the source so I can edit it later. >>> Something like inspect.getsource() but for source typed into the >>> interpreter, not imported from a module. Is this possible? Any >>> ideas are greatly appreciated. -Garett >> >> Last time I used it, Chris Gonnerman's readline replacement kept >> a history by default: >> >> http://newcenturycomputers.net/projects/readline.html > > Also, take a look at the following. It tells you how to configure > your interactive sessions so that both (1) interactive history > will be saved to a file and (2) that history will be available in > subsequent interactive sessions. Oops. Forgot the link. Here it is: http://docs.python.org/lib/readline-example.html Dave -- http://www.rexx.com/~dkuhlman From pln at cosmic.stanford.edu Tue Apr 6 21:38:56 2004 From: pln at cosmic.stanford.edu (Patrick L. Nolan) Date: Wed, 7 Apr 2004 01:38:56 +0000 (UTC) Subject: Tkinter: cut'n'paste from DISABLED window? Message-ID: Our Tkinter application has a big ScrolledText widget which is a log of everything that happens. In order to prevent people from making changes, we have it in DISABLED mode except when the program wants to write a new entry. This works OK, except that sometimes we want to copy out of piece of the contents and paste it in another window. When it's DISABLED, it appears that we can't even select a portion of the text. Is this an either-or situation? Or is there some clever way to get around it? If it matters, we want this to work on both Linux and Windows. -- * Patrick L. Nolan * * W. W. Hansen Experimental Physics Laboratory (HEPL) * * Stanford University * From hyperbob at walla.com Tue Apr 20 09:49:56 2004 From: hyperbob at walla.com (hyperbob at walla.com) Date: Tue, 20 Apr 2004 16:49:56 +0300 Subject: Networking! Message-ID: <200404201349.i3KDnuf23940@omail4.walla.co.il> And, of course, thank in advance! Bob. ----------------------------------------------------------------------- Walla! Mail, Get Your Private, Free E-mail from Walla! at: http://mail.walla.co.il -------------- next part -------------- An HTML attachment was scrubbed... URL: From max at alcyone.com Wed Apr 28 21:40:07 2004 From: max at alcyone.com (Erik Max Francis) Date: Wed, 28 Apr 2004 18:40:07 -0700 Subject: Is classless worth consideration References: Message-ID: <40905CF7.4A2625A4@alcyone.com> David MacQuigg wrote: > The problem we Python programmers are having is understanding the > fundamental advantage of eliminating classes and working only with > instances. The theoretical discussions put me to sleep. I can't see > the point of the examples above. What we need is a simple use case. I certainly don't see the point in having a prototype-based system if the declaration for defining a prototype (`proto' in your examples) looks very much like the way you build a class. All that seems to accomplish is a semantic change of "class" to "proto," which doesn't gain anything. Compare that to, say, Io -- a prototype-based system -- where there is no syntax at all for defining a "class" or "prototype." You simply clone and attach messages as you go. -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis \__/ Convictions are more dangerous enemies of truth than lies. -- Friedrich Nietzsche From peter at engcorp.com Fri Apr 16 07:23:48 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 16 Apr 2004 07:23:48 -0400 Subject: Difficulty Finding Python Developers In-Reply-To: <7xwu4gzff2.fsf@ruckus.brouhaha.com> References: <65cbc3dd.0404140641.3501fde8@posting.google.com> <5d83790c.0404150701.605782a7@posting.google.com> <7xpta8hqe7.fsf@ruckus.brouhaha.com> <7xsmf4kbac.fsf@ruckus.brouhaha.com> <7x7jwg7ipn.fsf@ruckus.brouhaha.com> <7xwu4gzff2.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Peter Hansen writes: > >>I thought the discussion was a 3-month project. To me, that's >>definitely not something I would classify as a "serious production >>project". I know, I know, the length alone shouldn't be enough to >>call it serious or production or not. It's just not the term I >>would apply to something that short. "Experiment", maybe, or >>"quickie", or "co-op student project" or something... > > It often means "we have a huge deadline in three months and are forced > to bring in contractors because the in-house staff is and > overstretched and not sufficiently up to speed on this stuff". In > which case the contractor better need zero ramp-up time. Sure, it often means that, but here's the OP's wording to keep us focused on what the discussion was really about: We've worked hard to convince our company to migrate our core applications to Python, and now we're looking for a Python developer in Atlanta to handle a short-term (approx. 3 month) project. That's not a good way to describe either of your scenarios, I believe. I think it's more of an initial foray without the company's future on the line type of thing... -Peter From deetsNOSPAM at web.de Wed Apr 7 11:51:35 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Wed, 07 Apr 2004 17:51:35 +0200 Subject: Dynamic creation of an object instance of a class by name References: <10f99b0f.0404070656.5960e2c8@posting.google.com> Message-ID: > Don't listen to the voices whispering "Use eval()" or "globals() are the > way to go", make it clean and explicit with a dictionary containing all > classes you want to expose: Out of curiosity - why not to use eval? having a dict like yours makes things look like your average java factory pattern - some explicit structure, to which access has to be guaranteed and that requires a registration. Of course, if you know that you will always only select the class from a fixed num of classes, your approach ensures that no non-compliant classes can be selected - but hey, we're dynamic here ;) You never can be totally sure what you get.... -- Regards, Diez B. Roggisch From jack at performancedrivers.com Fri Apr 16 18:48:49 2004 From: jack at performancedrivers.com (Jack Diederich) Date: Fri, 16 Apr 2004 18:48:49 -0400 Subject: Getters and setters in python, common practise In-Reply-To: <407e4703$0$255$edfadb0f@dread12.news.tele.dk> References: <407e402c$1@newsflash.abo.fi> <407e4703$0$255$edfadb0f@dread12.news.tele.dk> Message-ID: <20040416224849.GC794@performancedrivers.com> On Thu, Apr 15, 2004 at 10:25:07AM +0200, Max M wrote: > Petter Holmstr?m wrote: > > >Hello, > > > >Having a Delphi/Object Pascal-background, I'm very used to using getters > >and setters when designing my classes. What is the common practise in > >the Python world? Should one use them or not? > > Start with simple object attributes, then convert to attribute functions > using get/set-ers when needed. > Agreed, do a search on some keywords plus "considered (evil|harmful)" I consider get/set harmful 99% of the time, so read the rest of this post as opinion. Getter/Setters seem object oriented, but they usually aren't. You are hiding nothing, you aren't abstacting anything either. Someone is still depending on accessing a very particular attribute of your class. If the same amount of code has to be changed when you alter a getset method as when you alter a member your getset methods are just adding obscurity and call overhead with no reward. The object you are calling should get its state explicitly passed in during __init__, and if it needs something else it should be passed in on a method call. get/set methods are typically an indication that an instance is 'peeking' at something else to figure out what to do. Make "grep counts" your mantra. Passing things only at the time they are actually needed makes things obvious. import amodule def myfunc(self): # obvious, only gets what it needs. amodule.launch_debugger(use_globals=self.vars) import amodule def myfunc(self): # has to get 'vars' from self, might silently grow to do evil later. amodule.launch_debugger(self) If you limit what methods can use to what they are explicitly given it also makes writing unit tests much, much easier. -jackdied From newsgroups at jhrothjr.com Thu Apr 22 06:58:17 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Thu, 22 Apr 2004 06:58:17 -0400 Subject: AOP use cases References: <84fc4588.0404140106.3fa0c55@posting.google.com> <0pydnSB4WYuieuLdRVn-hQ@powergate.ca> Message-ID: <108f99vgg6ub501@news.supernews.com> "Peter Hansen" wrote in message news:XYmdnVLB9rjbARrdRVn-vg at powergate.ca... > Jacek Generowicz wrote: > (a lengthy reply, and thank you for taking the time!) > > Peter Hansen writes: > >>I would be very interested to hear some real-world and real useful > >>use cases for AOP as well. > > > > AOP is about separation of concerns. Let me repeat that: AOP is about > > SEPARATION OF CONCERNS. > [snip] > > As for real world examples ... if you think of AOP as separation of > > concerns which you want to be weaved together, then I am sure that you > > will be able to come up with plenty of excellent real world examples > > yourself. > > Unfortunately, that's just my point. So far I haven't been able > to do that, it seems. The example posted previously with the > "synchronization wrapper" approach is, however, quite understandable > and comes from real-world experience that many of us share. Is > that AOP? Is it not AOP? If it's an application of AOP principles, > then is AOP anything other than a good practice which some of us > have been doing for years, prettied up with a nice name. In other > words, Just Another Pattern? > > Jacek, I appreciate the attempt to clarify, but so far it seems to > me that *everyone* who talks about AOP just talks in abstract terms > and isn't willing (or able?) to pin it down with *real* real-world > examples, just "imagine this" or "wouldn't it be nice if". You > seem to be someone who understands AOP well: do you use it? Could > you please provide an example from your own uses which demonstrates > the effectiveness of AOP versus "not AOP" in the same way that the > synchronization example posted earlier is clearly better when done > as a wrapper than with the code duplicated everywhere (i.e. with > the "concerns" not separated)? Oh, absolutely. "Separation of concerns" is all very nice, but it's simply another way of looking at program composability. And composability has turned out to be a very hard problem: there are no, and I mean no, examples of composable programs where there was no planning on making it happen. The other thing to note is that "separation of concerns" imposes significant overhead, and I'm not just talking about performance. It cuts down on communication, code sharing and any possibility of finding structural congruence that might lead to deeper understanding. John Roth > > -Peter From asldfkjasldfj at asldfkjasldkfjasdf.com Sat Apr 17 14:11:36 2004 From: asldfkjasldfj at asldfkjasldkfjasdf.com (Jason) Date: Sat, 17 Apr 2004 18:11:36 GMT Subject: os.path.dirname adds unremoveable spaces? References: <1082p776qr29u07@corp.supernews.com> Message-ID: That's some great info, thanks. I never actually figured out what was adding the spaces, so I appreciate your explanation. This is only my third day of Python. > > Just to add a couple of notes... You probably shouldn't be using the > strip() function at all. What if the directory or filename does have > leading or trailing spaces? Presumably you would want to keep those > when constructing a full path. > > Also, you did figure out that it was the print statement adding the > spaces, right? Try this test: > > print 'one', '/', 'two' > > and compare the results with this: > > print '%s/%s' %( 'one', 'two' ) > > In the second example, you're giving a single argument to the print > statement, a string that you've already formatted with the % operator. > > os.path.join is better for dealing with file paths, of course, but > this will be useful for other things you might want to concatenate and > format. > > -Mike > > > From list-python at ccraig.org Thu Apr 22 10:51:12 2004 From: list-python at ccraig.org (Christopher A. Craig) Date: 22 Apr 2004 10:51:12 -0400 Subject: Deleting objects References: Message-ID: tkpmep at hotmail.com (Thomas Philips) writes: > Villain dies and executes its destructor (__del__). The game then > ends. However, when I execute the program in IDLE, IT FINISHES BY > EXECUTING THE DESTRUCTOR FOR BOTH HERO AND VILLAIN. > > How can this be? As one of the two objects was destroyed prior to the > end of the game, how can it be re-destroyed when the program ends? What's happening is that you're calling self.__del__() (which prints a string, but does not actually delete the object) and at the end of the program the object is deleted, which calls self.__del__(). I think you have the causality backwards, object destruction causes self.__del__() to be run, self.__del__ does not cause object destruction. You are, in fact, guaranteed that the object still exists immediately after a call to self.__del__() because self must still exist for it to have been there to be called. It's also impossible for an object to commit suicide like that, when you call method(obj) a new reference is created to "obj", so destroying that refrence cannot destroy the last reference (since there must still be one in the calling namespace). This is why delete in python is del obj instead of del(obj) -- Christopher A. Craig "May the source be with you." -- Open Source Software mantra From newsgroups at jhrothjr.com Sat Apr 3 09:14:30 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 3 Apr 2004 09:14:30 -0500 Subject: An attempt at guessing the encoding of a (non-unicode) string References: Message-ID: <106thmedmq162ce@news.supernews.com> "David Eppstein" wrote in message news:eppstein-8C467F.14490702042004 at news.service.uci.edu... > I've been getting decent results by a much simpler approach: > count the number of characters for which the encoding produces a symbol > c for which c.isalpha() or c.isspace(), subtract a large penalty if > using the encoding leads to UnicodeDecodeError, and take the encoding > with the largest count. Shouldn't that be isalphanum()? Or does your data not have very many numbers? John Roth > > -- > David Eppstein http://www.ics.uci.edu/~eppstein/ > Univ. of California, Irvine, School of Information & Computer Science From fumanchu at amor.org Mon Apr 19 22:17:04 2004 From: fumanchu at amor.org (Robert Brewer) Date: Mon, 19 Apr 2004 19:17:04 -0700 Subject: raw_input Message-ID: Marcello Pietrobon wrote: > if ( not os.path.exists( dirname) ): > msg = 'The directory \'%s\' does not exist. > Create it [y/n] > ?' % dirname > c = raw_input( msg ).lower > if ( c == 'y' or c == 'yes' ): > os.makedirs( dirname) > else: > raise Exception( 'directory \'%s\' not created, > impossible to continue !' % dirname ) try lower() instead of lower. FuManChu From mutah at NOSPAM-libertysurf.fr Tue Apr 27 09:20:51 2004 From: mutah at NOSPAM-libertysurf.fr (Mutah) Date: Tue, 27 Apr 2004 15:20:51 +0200 Subject: sending an object - twisted or what? References: Message-ID: <20040427152051.50234c65.mutah@NOSPAM-libertysurf.fr> On Tue, 27 Apr 2004 13:00:17 +0000 (UTC) Paul Sweeney wrote: > Is twisted the only way to go, or is there something > simpler for my app? The code for twisted is fairly simple (I found > http://twistedmatrix.com/documents/current/howto/pb-copyable) > but the library is a bit heavy and I don't want to go through the > hassle of dependencies/compiling etc if there's a simpler way. > Using only modules shipped with python, a simpler way (in term of dependencies only) would be to pickle the objects and then send the result throught a socket. On the other side, you may need to write more code to do that. -- mutah From newsgroups at jhrothjr.com Mon Apr 12 07:57:38 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 12 Apr 2004 07:57:38 -0400 Subject: new-style class instance check References: Message-ID: <107l13c5tti8876@news.supernews.com> "Richard Gruet" wrote in message news:c59uvd$fgh$1 at apollon.grec.isp.9tel.net... > Hi all, > > How to determine that an object o is for sure an instance of a new-style > class, without knowing of which specific class ? > That is, if I define a function: > > def isNewStyleClassInstance(o): > pass ## to be completed > > .. I want to pass the following test: > > def C: pass > def CNew(object): pass > > assert not isNewStyleClassInstance(C()) # InstanceType > assert isNewStyleClassInstance(CNew()) > assert not isNewStyleClassInstance(1) # instance of type int > # and naturally for all other types of o the function should return False. The following untested code should work: import types def isNewStyleClass(obj): if type(obj) is types.InstanceType: if hasattr(obj.__class__, "__mro__"): return True return False John Roth > > Richard > > From has.temp2 at virgin.net Fri Apr 30 12:55:40 2004 From: has.temp2 at virgin.net (has) Date: 30 Apr 2004 09:55:40 -0700 Subject: Simple prototyping in Python References: Message-ID: <69cbbef2.0404300855.20dd436b@posting.google.com> Dave Benjamin wrote in message news:... > The recent conversation on prototype-based OOP and the Prothon project has > been interesting. I've been playing around with the idea for awhile now, > actually, since I do a lot of programming in JavaScript/ActionScript. I feel > like people are focusing too much on the "prototype chain", which to me is > mainly an attempt at reintroducing inheritance. It doesn't even do that; at least not in the sense that class-based OO defines it, where inheritance merely describes the initial state for every object created from a class. To me, the way Prothon and Io do "prototypes" feels more like a leaky abstraction, where a common internal optimisation for proto-OO systems has somehow leaked out into user-space. See if I ever find that Lieberman fellow, think I'll be having a word or two with 'im. ;) > I almost never use > inheritance anymore, preferring delegation instead in most cases. What I > think is much more interesting about the prototype-based style is the > ability to create and pass around anonymous objects. In a proto-OO system all objects are _completely_ anonymous*, having no 'class' and all being of the same type, 'object'. In this respect, they're just like strings, lists, dicts, or any other 'anonymous' type; a list is a list is a list, for example, regardless of how it is used. (* To the user, anyway. Of course, they still have internal ids so the runtime can track 'em, but that's not something the user ever needs to know about.) > JavaScript has a syntax > for this: > > var o = {a: 5, b: 6} Looks on the surface like AppleScript's record type, which is roughly analogous to C structs... and useless for anything more than struct-style usage. While I did read about JS programming in the dim-n-distant past - it was one of a number of languages I looked at when learning proto-OO on AS, which lacked any decent learning material on the topic - I've pretty much forgotten everything since. So can I ask: is the JS structure more flexible; e.g. can one add functions to it to operate like methods on the other data in the structure? Or does it have to provide a second structure for proto-OO use, as AS does? From mickel at csc.fi Thu Apr 8 05:51:34 2004 From: mickel at csc.fi (=?ISO-8859-1?Q?Mickel_Gr=F6nroos?=) Date: Thu, 8 Apr 2004 12:51:34 +0300 (EEST) Subject: RealPlayer and Python Message-ID: "RealNetworks has developed a Python binding for their RealMedia client." (http://www.python.org/community/users.html) Does anybody now more about this? Is the Python binding freeware and downloadable? I want to access RealPlayer on Windows from Python without having to use COM. What I need to be able to do is open a video clip (mpeg-1, mpeg-2 or mpeg-4 will do) and seek to different positions in the clip, play and stop. Cheers, Mickel Gr?nroos -- 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 Scott.Daniels at Acm.Org Sat Apr 3 12:15:13 2004 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sat, 03 Apr 2004 09:15:13 -0800 Subject: Working with bytes. In-Reply-To: References: Message-ID: <406ef82a@nntp0.pdx.net> Adam T. Gautier wrote: > I have been unable to solve a problem. I am working with MD5 signatures > trying to put these in a database. The MD5 signatures are not generated > using the python md5 module but an external application that is > producing the valid 16 byte signature formats. Anyway, these 16 byte > signatures are not nescarrally valid strings. How do I manipulate the > bytes? I need to concatenate the bytes with a SQL statement which is a > string. This works fine for most of the md5 signatures but some blow up > with a TypeError. Because there is a NULL byte or something else. So I > guess my ultimate question is how do I get a prepared SQL statement to > accept a series of bytes? How do I convert the bytes to a valid string > like: > > 'x%L9d\340\316\262\363\037\311\345<\262\357\215' > > that can be concatenated? > > Thanks > This should probably do: cursor.execute('SELECT author from stored where md5 = ?', md5) But you might consider changing your approach to store hex strings: cursor.execute('SELECT author from stored where md5 = ?', ''.join(['%02x' % byte for byte in md5])) -- -Scott David Daniels Scott.Daniels at Acm.Org From anton at vredegoor.doge.nl Sun Apr 25 06:23:22 2004 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Sun, 25 Apr 2004 12:23:22 +0200 Subject: AOP use cases References: <0pydnSB4WYuieuLdRVn-hQ@powergate.ca> <40888443$0$126$3a628fcd@reader3.nntp.hccnet.nl> Message-ID: <408b928f$0$1011$3a628fcd@reader1.nntp.hccnet.nl> "Terry Reedy" wrote: >I agree that separating and wrapping the function as generator or iterator >is even better that as regular function. I have use for this. Thanks. Your idea of making the wrapping independent of the generator is very interesting. I have been playing with it and produced a vector class. It's not meant for serious production code (who knows however what such wrapped generators might be used for :-) but it might be interesting to those who want to invade the dictionary noosphere. It's at: http://home.hccnet.nl/a.vredegoor/vector/ Anton From t-meyer at ihug.co.nz Wed Apr 14 19:28:08 2004 From: t-meyer at ihug.co.nz (Tony Meyer) Date: Thu, 15 Apr 2004 11:28:08 +1200 Subject: lauching Spambayes on Mac OS 9 In-Reply-To: <1ED4ECF91CDED24C8D012BCF2B034F1305E92350@its-xchg4.massey.ac.nz> Message-ID: <1ED4ECF91CDED24C8D012BCF2B034F13026F2B96@its-xchg4.massey.ac.nz> [FWIW, you'd be better off asking SpamBayes questions in the SpamBayes list - spambayes at python.org] > I've installed the latest version of python for mac os 9. > But now the spambayes indicates that i have to run python > setup.py and then run python scripts/sb_server.py...and > that's the problem! i can't figure out how to run these commands! I believe that when you installed Python you ended up with an application called "PythonLauncher", yes? If you option-drag the setup.py script to this you should be offered ways that you can launch the script. You want to pass it a command line argument "install". Once that's done, I believe you can simply double-click sb_server.py to run it (it doesn't need any command-line arguments). Then go to and you should see the main web interface page. =Tony Meyer From haim at babysnakes.org Sat Apr 17 20:42:04 2004 From: haim at babysnakes.org (Haim Ashkenazi) Date: Sun, 18 Apr 2004 03:42:04 +0300 Subject: creating panel icons Message-ID: Hi I want to write an application that has the option of having an icon on the panel (to hide and show the main window + menu), something like gaim or rhythmbox. my first choice was pykde (since I use kde) but although I'm a python newbie, I got the impression from their mailing list that you have to wait every time a new kde version is out, for the release of the new bindings (like now, I have kde 3.2 for almost a month, but I can't use pykde 3.8...). then I've looked at some python-gnome examples and the only way I was able to launch the applet was through the gnome-panel menu (which means that I have to run gnome-panel in kde, I don't like this solution). does anyone has an idea how can I create something like that? thanx -- Haim From pwatson at redlinepy.com Fri Apr 16 23:24:38 2004 From: pwatson at redlinepy.com (Paul Watson) Date: Sat, 17 Apr 2004 03:24:38 GMT Subject: Python OS References: Message-ID: "Michael Chermside" wrote in message news:mailman.702.1082138150.20120.python-list at python.org... > A Evans writes: > > I am by no means a programmer at this stage. > > But as I learn more and more I see Python as the > > Holy Grail of programming languages > > Then you have much to learn. Different languages have different > strengths, and a skilled programmer will realize that. Python > is an excellent language for expressing algorithms, doing rapid > prototyping, and a GREAT many other tasks. But it is poorly > suited to performing low-level register and bit manipulation. > If I wanted an inference engine, I might use prolog rather than > Python. > > In the world of OSes, I think a core done in something like C > with the higher level kernel functionality in Python would make > an interesting system for experimenting with OS design. But > performance is likely to be unreasonable for a "production" OS. > Remember too, that much of what is nice about Python is that it > provides you with easy access to OS facilities (everything from > sockets (as a library) to memory management (in the language). > If you were developing an OS then that wouldn't be available > until you had built it. > > -- Michael Chermside What if we had a machine whose native instruction set was Parrot bytecode? From FBatista at uniFON.com.ar Wed Apr 7 08:39:55 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Wed, 7 Apr 2004 09:39:55 -0300 Subject: String comparison problem Message-ID: [Senthoorkumaran Punniamoorthy] #- I am printing these information. #- #- print string.lower(info_res[2]) #- print string.lower(md5sum(f_md5)) #- print len(string.lower(info_res[2])) #- print len(string.lower(md5sum(f_md5))) #- print str(string.lower(md5sum(f_md5)) == #- string.lower(info_res[2])) #- #- and the output are #- #- 01b7ebfc27437a90cc421c50df8f9ac5 #- 01b7ebfc27437a90cc421c50df8f9ac5 #- 32 #- 32 #- False Can not reproduce it. Please, do the following: str1 = info_res[2] str2 = md5sum(f_md5) print str1 print str2 And send them back to us. . Facundo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA La informaci?n contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener informaci?n confidencial o propietaria, cuya divulgaci?n es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no est? autorizado a divulgar, copiar, distribuir o retener informaci?n (o parte de ella) contenida en este mensaje. Por favor notif?quenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magn?tico) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telef?nica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electr?nicos pueden ser alterados, motivo por el cual Telef?nica Comunicaciones Personales S.A. no aceptar? ninguna obligaci?n cualquiera sea el resultante de este mensaje. Muchas Gracias. -------------- next part -------------- An HTML attachment was scrubbed... URL: From rogerb at rogerbinns.com Mon Apr 26 21:54:08 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Mon, 26 Apr 2004 18:54:08 -0700 Subject: Compiler References: <408db4fb$1@news.unimelb.edu.au> Message-ID: Maurice LING wrote: > i was wondering just how different is the python bytecode from the java > bytecode? is there a specification for python virtual machine or sort? i > can foresee a lot of interesting projects and uses that can stem from > this specification. I recommend reading all the posts in this earlier thread: http://groups.google.com/groups?th=f20ad34ef1157bcb It largely overlaps with what you are thinking and what your next questions would be :-) Roger From jacek.generowicz at cern.ch Thu Apr 8 04:28:19 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 08 Apr 2004 10:28:19 +0200 Subject: OFF-TOPIC:: Why Lisp is not my favorite programming language References: <165b3efa.0403030443.4d591f04@posting.google.com> <40460dd5$0$5916$7a628cd7@news.club-internet.fr> <6in670lrldbjkuujle68a526293j57a7mn@4ax.com> <95aa1afa.0404070205.94b32e4@posting.google.com> Message-ID: Stephen Horne writes: > and given the kind of metaprogramming possible in Lisp (which for > compilation to work, must imply just-in-time compilation at run > time) Why ? From simoninusa2001 at yahoo.co.uk Mon Apr 5 12:27:19 2004 From: simoninusa2001 at yahoo.co.uk (simo) Date: 5 Apr 2004 09:27:19 -0700 Subject: Module import problems References: <30260531.0404041725.746befa0@posting.google.com> Message-ID: <30260531.0404050827.320e3c14@posting.google.com> login.login or login.login() don't work. I tried adding... def simon(): print "hello" ...to the top of login.py (before the login class) and then calling login.simon() and that works - but then that's a def, not a class.... So I think the login class is failing to initialise as it can't find the wx class imported in main.py, because if I run login.py then I get "...wx not defined" surely I don't have to import wx in every file (that doesn't work actually)?! This namespace crap is becomming an inconvenience - jees, do we have to make everything global?! Also, does IDLE cache the compiled Python or something, as sometimes when I change a file and save/run it in the shell, it doesn't change (I do delete the .pyc files) until I quit and reload IDLE? This is with Python 2.3.2/Solaris (ActiveState) and 2.3.3/Windows (python.org) and wxPython 2.4.2.4/2.5.1.5 From gyromagnetic at excite.com Wed Apr 21 12:42:38 2004 From: gyromagnetic at excite.com (Gyro Funch) Date: Wed, 21 Apr 2004 10:42:38 -0600 Subject: This is very simple question In-Reply-To: References: Message-ID: <4086a46c@news.ColoState.EDU> Eric wrote: > I would want to obtain a list of factors (multiples of 2) given a > prime number in python. > > For example 13=[8,4,1], 5=[4,1], 7=[4,2,1], 15=[8,4,2,1] > > I would appreciate a fuction which would do this. > > Eric Below is an ugly and inefficient implementation. -g def i2b(i): s = '' while i: s = (i & 1 and '1' or '0') + s i >>= 1 return s or '0' def find_factors(val): bstr = i2b(val) facs = [int(j)*2**i for (i,j) in enumerate(bstr[::-1]) if int(j) != 0] facs.reverse() return facs if __name__ == '__main__': print find_factors(13) == [8,4,1] print find_factors(5) == [4,1] print find_factors(7) == [4,2,1] print find_factors(15) == [8,4,2,1] From lbates at swamisoft.com Fri Apr 30 15:06:26 2004 From: lbates at swamisoft.com (Larry Bates) Date: Fri, 30 Apr 2004 14:06:26 -0500 Subject: Dictionnary vs Class for configuration References: <40929016$0$8635$626a14ce@news.free.fr> Message-ID: <5p6dnTePS_YtPg_dRVn-hw@comcast.com> Ultimately you must answer to your professor, but... I firmly believe that configuration parameters belong in a configuration file. ConfigParser module handles these very well. Essentially it builds the dictionary for you in the form of a ConfigParser class instance. Then when you wish to change a parameter, edit the config file and the next time the program runs it reads the new parameters. You didn't mention your platform, but I do a lot on Windows and "freeze" my programs using py2exe, so configuration files come in really handy to make those "run-time" variables available to the program. I also find that people are quite comfortable editing these files. Config file would look something like: [database] name=nanana userdb=bob password=******** [other] timetosleep=100 path=/home/script program to read this: import sys def ini_error(section, option): # # Insert code here to handle missing parameters # print "Unable to locate section=%s, option=%s in .INI file" % (section, option) sys.exit(2) import ConfigParser ini_filename="/directory/where/config/stored/program.ini" INI=ConfigParser.ConfigParser() INI.read(ini_filename) section="database" option="name" try: database=INI.get(section, option) except: ini_error(section, option) option="userdb" try: userdb=INI.get(section, option) except: ini_error(section, option) option="password" try: password=INI.get(section, option) except: ini_error(section, option) section="other" option="name" try: timetosleep=INI.getint(section, option) except: timetosleep=100 option="path" try: path=INI.get(section, option) except: ini_error(section, option) You get the idea. Regards, Larry Bates Syscon, Inc. "Famille Delorme" wrote in message news:40929016$0$8635$626a14ce at news.free.fr... > Sorry if this discussion are already submited, but I don't find anything > really interresting for me. > And sorry for my bad english, it is not my native language. > > I wrote a program in Python for a school project and I am in trouble. > I have make a Python script called conf.py. This file contains dictionnarys > for configuration like this: > config_sql = { > "DATABASE" : "nanana", > "USERDB" : "bob", > "PASSWORD" : "********" > } > config_script = { > "TIMETOSLEEP" : 100 > "PATH" : "/home/script" > } > The config_section variable is included in each modules (script python) used > in my program > (with from config.py import config_section) > And the use is like this > from conf.py import config_sql > print config["DATABASE"] > > But my master say it's better to do a class like this > class config : > def __init__(self, part=="") : > if (part=="SQL") : > self.database="nanana" > self.userdb="bob" > self.password="*******" > elif (part=="SCRIPT") : > self.timetosleep=10 > self.path="/home/script" > .... > > and the use like this > from conf.py import config > cfg=config("SQL") > print cfg.database > > We have do only a file for configuration because the administrator is no > searching for configuration. > I want know : > - what is more faster, dictionnary method or class method? > - what use more ram memory ? > - if you are administrator, what method you like for configure program ? > > Note: > * the class will not have methods, it is not necessary. > * the program is composed of several modules which import > config_section. > > > Thank you for futures answers, > 3Zen > > > > > > From peter at engcorp.com Tue Apr 27 14:34:22 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 27 Apr 2004 14:34:22 -0400 Subject: And *this* is why you need Perl!? In-Reply-To: <108t8pvam9q139c@corp.supernews.com> References: <87fzaqmm8t.fsf@strauser.com> <38ec68a6.0404262308.50029919@posting.google.com> <108t8pvam9q139c@corp.supernews.com> Message-ID: Cameron Laird wrote: > In article , > Skip Montanaro wrote: > >>differences. In addition, as Jamie Zawinski suggests, regular expressions >>are not always the best choice. > > "suggests"? I thought he was "chanting", or "intoning", or > "inveighing" or "denouncing" or ... Well, I'll say it on my > own behalf: friends, REs are not always the best choice http://www.unixreview.com/documents/s=2472/uni1037388368795/ >. "Denouncing" it definitely was. I wanted to find the original source for myself, and Google conveniently provided it. Still fun reading, and quite relevant to the thread: http://slashdot.org/comments.pl?sid=19607&cid=1871619 -Peter From jgentil at sebistar.net Thu Apr 1 18:56:43 2004 From: jgentil at sebistar.net (Jon-Pierre Gentil) Date: Thu, 01 Apr 2004 17:56:43 -0600 Subject: Microsoft making Python.NET In-Reply-To: References: Message-ID: <106pb1re9uknt43@corp.supernews.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Greg wrote: > The following article from microsoft describes a workaroind for a bug > in hte beta version of VISUAL PYTHON DOT NET > > http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnaskdr/html/askgui04032001.asp > > When did microsoft put python into the visual studio beta? How did > this not make big news in developmnt circles? Erm, ActiveState makes Visual Python.NET. http://www.activestate.com/Products/Visual_Python/?_x=1 Microsoft often places data about how its software interacts with 3rd party software in their MSDN knowledgebase. If you search for Python alone on MSDN you get lots of information on using Python in ASP using ActivePython. - -- :: Jon-Pierre Gentil :: PGP Key ID 0xA21BC30E :: Jabber: jgentil at jabber.org -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.4 (GNU/Linux) Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org iEYEARECAAYFAkBsrDsACgkQOrVFmaIbww4q9QCeLAJlVn8EVsCvltjCz1+QbEjg xuAAnRx2PYY3gWNoEqinptQoHRcPrMlR =PwgS -----END PGP SIGNATURE----- From nospam at kochandreas.com Mon Apr 26 15:49:01 2004 From: nospam at kochandreas.com (Andreas Koch) Date: Mon, 26 Apr 2004 21:49:01 +0200 Subject: Andreas' practical language comparison In-Reply-To: <5ago80thlgfrsrapol1lldi2cq0uulto4n@4ax.com> References: <408c23b8$0$41746$5fc3050@dreader2.news.tiscali.nl> <5ago80thlgfrsrapol1lldi2cq0uulto4n@4ax.com> Message-ID: Andrea Griffini wrote: Hi Andrea! >>I really would like to see the linecount. I do belive that it is one of the >>indicators of the power of the language and its batteries. > > Then at least you should be talking of the same problem and > of the same solution to the problem. For example the Delphi > solution for the 8 queens problem is completely different > from the ALGOL one (and I must say IMO the Delphi solution > is quite terrible from an algorithm point of view) I didn't really get the ALGOL one. My first Delphi version was using bitmaps and marking endangered fields, but the code was pretty horrible because i found no elegant way to fill the diagonals but using 2 loops (~ 20 lines of not very intuitive additional code) I find the current version to be quite nicely readable, while the bitmap solution would probably be faster. > comparing > a linecount for that that with a linecount for a totally > different solution is just nonsense. Depends. The solution often reflects how certain problems are handled in a language. > However this create problems for very different approaches; > implementing a certain algorithm in prolog and comparing it > with the same algorithm in C has any meaning ? If say one > solution uses generators (may be heavily and with backtracking, > for example in Icon) how can you implement the same solution > on a language that has no generator concept at all ? > Even if you manage to do that, what's the point in finding > that you needed a lot of lines of code to do it ? I have some tests that require to solve an problem, and some that require to use an certain algorith. I think you can encounter both situations in real life. Of course, saying "A needs 20 lines so its better than B which needs 22 lines" is idiotic. > I'm very new to python, but anyway this is my solution to 8 > queen's problem: Thanks, i allready had lots of submissions by mail this night. Lots more feedback than expected :-D > Does this mean that Python is less expressive ? that > C is less clear ? Or just means one program has been > written trying to be expressive and the other trying > to be compact ? > > If I run that Delphi solution for the 8 queens problem > should I conclude that Python is faster than Delphi ? Good questions. Any ideas for solutions? -- Andreas He screamed: THIS IS SIG! From srumbalski at copper.net Sat Apr 24 22:09:28 2004 From: srumbalski at copper.net (Steven Rumbalski) Date: Sat, 24 Apr 2004 22:09:28 -0400 Subject: deleting items within a for loop - mutable indices References: <4089cb21$1_2@mk-nntp-2.news.uk.tiscali.com> <16752bcc.0404240006.491ec7e3@posting.google.com> Message-ID: <408b1c04_2@newsfeed.slurp.net> James Moughan wrote: > you could speed either up for largish lists with hashing; > > dict = {} > for d in deletion_list: > dict[d] = 1 > tmp = [x[i] for i in range(len(x)) if not dict.has_key(i)] > x = tmp If order doesn't matter and the items are unique you may wish to use sets.Set from python 2.3 instead of a dict: >>> from sets import Set >>> set = Set(['a', 'b', 2, 42]) >>> for item in deletion_list: ... set.discard(item) ... >>> print set Set(['b', 42]) -- Steven Rumbalski news AT rumbalski DOT com From eric at zomething.com Tue Apr 6 02:33:53 2004 From: eric at zomething.com (Eric @ Zomething) Date: Mon, 5 Apr 2004 22:33:53 -0800 Subject: slightly OT: BUT NEEDs to be said Message-ID: <20040405223353.1541376021.eric@zomething.com> Greg Ewing wrote: > Aha! I've been trying to decide what to name the next language > I invent, and now I know. It will be called: > > Buffy Python goes good with databases, how about renaming it: QuerI I feel so neked without braces! Eric PSU indeed, another myth, there is no conspiracy, no filter, nothing but a desire to be the next PHP (but what would I know, no one ever lets me in on the conspiracies) From kmmcdonald at wisc.edu Sun Apr 4 17:35:32 2004 From: kmmcdonald at wisc.edu (Kenneth McDonald) Date: Sun, 04 Apr 2004 21:35:32 GMT Subject: GUI Frameworks in Python? References: Message-ID: In article , Hugh Macdonald wrote: > I've recently been trying out various different GUI frameworks in Python and > was wondering if I could get your input on the pros and cons of the > different ones... > I would take a strong, close look at Tkinter again. In my opinion, people have dismissed Tk as 'old technology', but I have seen nothing else that remotely approaches the power of Tk. First, a few points: 1) Tk at the moment looks ugly. There is a major effort undergoing (tile--look on sourceforge) to develop a themable Tk, and they already have some very good-looking Windows-looking screenshots. This won't be available in the immediate future, but I think it won't be too too far off either. The Tk community understands that the ugly, nonstandard look is hurting Tk use. 2) Tkinter is a (relatively) thin layer over Tk calls. The best way to use it is to build some functions over it to do what you want to do, and then reuse those functions. 3) Tkinter does make Tk into an object oriented paradigm. So as you mention, you can subclass a Tk widget and then pass in appropriate methods of that class as functions. However, you often don't even need to do this. A complex widget is almost certainly going to be declared as a class so just do: class MyWidget(Frame): def __init__(self) button1=Button(command=self.foo1) button2=Button(command=self.foo2) def foo1(event):... def foo2(event):... I can't remember if 'command' is the right option to Button, but you get the idea. 3) People often complain about the Tk widget set not being powerful enough. This is nonsense. First, read through all of the man pages for the Text and Canvas widgets--nothing else even comes close. (If something does, please let me know). I've looked at QScintilla, and it is far less flexible than Text. Then, download the BLT addon package for Tcl/Tk and read through its graph widget documentation. As for basic widget sets, There may be a few widget types missing, but it is very few, and what is missing can usually be found in an Python extension (MegaWidgets) or somewhere else, or coded fairly quickly using Tkinter. 4) The event-handling mechanism in Tk is awesome It is very easy to specify not just single events, but also "event sequences"; so, for example, you can specify that ^X^S (the emacs save command) saves your files. 5) As I mentioned above, it is often best to put a nicer wrapper around some of the Tkinter stuff. For example, here is the way I put things into a gridded layout: button = Button(...) label = Label(...) subframe = Frame(...) mywidget = MyWidget(...) grid([ [button, '-', label], [subframe, 'x', '^'], ['^', mywidget, '-'] ]) Which, using the captalized first letter of each widget's variable, result in a layout like this: BBL S L SMM with the middle cell empty. The ^ and - characters simply indicate that the cell in the previous row/column should be carred into this cell. This grid function (not method) took me about 8 lines to write, and I've put it up on the Tkinter mailing list hosted on the Python web site. Likewise, I'm in the process of writing something to make event binding easier, and will put that up when it's done. It will look something like: bindevents(widget, ca_x_space_b1=fun1, m_backspace=fun2, Y=fun3, ) Which indicates that fun1 should be invoked on the event sequence ctrl-alt-x ctrl-alt-space ctrl-mousebutton1; fun2 on meta-backspace; and fun3 on the single key 'Y'. There are a few problems with Tk. To use much of the Tkinter stuff, you need to have the Tk man pages handy, which is why writing more pythonic wrappers is a good idea. There is a third-party table widget available which is useful for relatively simple applications, but which lacks the flexibility and power of the Text and Canvas widgets. (Still, it's better than a lot of other table implementations I've seen.) However, once you've gotten over the initial learning curve (which mostly has to do with learning the Tk side, and isn't really that bad--Brent Welch and a co-author have a brand new book out which is just great), you can throw a powerful UI together in an amzingly short time. Cheers, Ken From cliechti at gmx.net Sat Apr 17 14:01:02 2004 From: cliechti at gmx.net (Chris Liechti) Date: Sat, 17 Apr 2004 18:01:02 +0000 (UTC) Subject: Static Modules... References: Message-ID: Grzegorz Dostatni wrote in news:Pine.LNX.4.44.0404171006210.27811-100000 at e5-05.ee.ualberta.ca: > > I had an idea yesterday. (Yes, I know. Sorry). > > If we don't need to declare variables as having a certain type, why do > we need to import modules into the program? Isn't the "import sys" > redundant if all I want is to call "sys.setrecursionlimit(5000)" ? Why > couldn't we just try loading the module of a name "sys" to see if it > exists and re-try the command? > > I tried just that. This is meant as a proof of concept (I called it > autoload.py) > > -------- BEGIN HERE ------ > import sys, inspect > > def autoload_exc(type, value, traceback): > modulename = value.args[0].split()[1][1:-1] > f_locals = traceback.tb_frame.f_locals > f_globals = traceback.tb_frame.f_globals > > exec "import " + modulename in f_locals, f_globals > exec traceback.tb_frame.f_code in f_locals, f_globals > > sys.excepthook = autoload_exc > > ------- END HERE ------- > > I know there are problems here. Checking if we have a NameError > exception is the most glaring one. Still this works for simple things > as a proof of concept. > > Here is an example of a simple session: > >>>> import autoload >>>> sys.setrecursionlimit(5000) >>>> dir(time) > ['__doc__', '__name__', 'accept2dyear', 'altzone', 'asctime', 'clock', > 'ctime', > 'daylight', 'gmtime', 'localtime', 'mktime', 'sleep', 'strftime', > 'strptime', 's > truct_time', 'time', 'timezone', 'tzname'] >>>> os.path.join("usr","local","bin") > 'usr\\local\\bin' > > Any comments? "import this" -> "Explicit is better than implicit." you dont easily see what exetrnal modules a program uses. that makes it more difficult to debug, and it makes neat things like py2exe/installer impossible. a slight missconception is also there, as variables dont exist out of nothing, they start apearing when you assign something to them. (appart from that i dont like to say "variable" in python, more like binding names to objects.) so something similar to using "variables" would be: sys = __import__("sys") which is already possible without any hack ;-) however, it could be a nice little hack for interactive sessions when playing around in the interpreter. but i'd like to see a message when it imports something, so that later when copy&pasting something to a file, i dont forget the imports. chris -- Chris From NoSpamPlease_rubytuzdaiz at yahoo.com Mon Apr 26 16:55:02 2004 From: NoSpamPlease_rubytuzdaiz at yahoo.com (Ruby Tuesdays) Date: Mon, 26 Apr 2004 16:55:02 -0400 Subject: Is Perl *that* good? (was: How's ruby compare to it older brother python) References: <108q51j4dscn7dc@corp.supernews.com> Message-ID: Would this super perl program of yours can convert the massive amount of perl script to ruby or python? If it could, it would be great so ruby/python programmers does not have to learn those cryptic perl-ish syntax and the non-OOish scripting language. From asldfkjasldfj at asldfkjasldkfjasdf.com Sat Apr 17 12:56:03 2004 From: asldfkjasldfj at asldfkjasldkfjasdf.com (Jason) Date: Sat, 17 Apr 2004 16:56:03 GMT Subject: os.path.dirname adds unremoveable spaces? References: Message-ID: And just as expected, after an hour of searching google groups for an answer, I post the question only to figure it out 10 seconds later. Sheesh! I used os.path.join and all is well. Jason wrote in news:Xns94CE7B19D78E7nonenonecom at 24.93.43.119: > Here's the code I'm using: > > #################################### > import os, string > for root, dirs, files in os.walk('/home/_Comedy'): > for file in files: > str = os.path.dirname(file) > print root, str.strip(), "/", file.strip() > > #################################### > The problem is that even after using strip(), it still prints a list > like this: > > > /home/_Comedy/ISIRTA / ISIRTA - 1966.03.28 - s02e03 - Ali Baba.mp3 > /home/_Comedy/ISIRTA / ISIRTA - 1966.04.04 - s02e04 - Nelson.mp3 > /home/_Comedy/ISIRTA / ISIRTA - 1966.04.18 - s02e06 - Angus Prune.mp3 > > ^^^^^ > ^^^^^ > I can't remove these mystery spaces that I'm pointing to no matter > what I try. Neither the directories or filenames have spaces before > or after them. Even if they did, they should've been removed when I > used the strip command. > > Any ideas? > From peter at engcorp.com Tue Apr 13 08:44:33 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 13 Apr 2004 08:44:33 -0400 Subject: Logging Stacktrace To File In-Reply-To: <407bdce5$1_1@newspeer2.tds.net> References: <407bcbca$1_2@newspeer2.tds.net> <407bdce5$1_1@newspeer2.tds.net> Message-ID: <6tadnU_-4_ksfebdRVn-tw@powergate.ca> Olaf Meding wrote: >>... have to catch the exception and then log it to the file. > > > Right. I do also know how to open a file and write to it. > > But how do I get at the stack trace? I would like to have it look the same > in the file as what gets printed to the screen. You're looking for the standard module "traceback", plus possibly a call to sys.exc_info()... The Cookbook has some helpful examples, probably more complex than what you need: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52215 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65332 -Peter From eastier at free.fr Thu Apr 22 05:17:20 2004 From: eastier at free.fr (Emmanuel) Date: Thu, 22 Apr 2004 11:17:20 +0200 Subject: Reload All References: <40867308.26DD15BD@free.fr> Message-ID: <40878DA0.403A0619@free.fr> Emmanuel a ?crit : > Hi, > > I use a 'reload all' feature in my app, that allow to reload every > module. > > I first try this version : > > import sys > def Reload(): > for a in sys.modules.values(): > if ( type(a) == type(sys) ): # I can't remember why > if ( '__file__' in dir ( a ) ): # to avoid reload of > extending C module > try: > ## print a.__name__ > reload ( a ) > except ImportError: > Log ("Reload", "error importing module" + > a.__name__) > > but there are some cases where the order of the reload is important. > I came into this one : > > CODE : > =============== > Base.py > ---------- > class Base: > def __init__(self): > print "Base Init" > > Derived.py > ------------ > import Base > class Derived( Base.Base): > def __init__(self): > Base.Base.__init__(self) > print "Derived additional init" > > In order to reload all to work, Base _MUST_ be reloaded before Derived. > > So I continue with this code, modified from something I get on the forum > : > ---------------------------------------------------- > import inspect > > def reload_from_root(root): > if(not inspect.ismodule(root)): > print 'root is not a module!! Failing.' > print type(root) > > #Keeping lists of pairs where pairs are (parent, child) > #to establish module relationships and prevent > #circular reloads > reload_me = [(None, root)] > reloaded = [] > > while(len(reload_me) > 0): > tmp = reload_me.pop() > > for x in inspect.getmembers(tmp[1]): > if(inspect.ismodule(x[1])): > if ( '__file__' in dir ( x[1] ) ): > if((tmp[1], getattr(tmp[1], x[0])) not in reloaded): > reload_me.append((tmp[1], getattr(tmp[1], x[0]))) > > ## reload(tmp[1]) # If I use reload here, the child is > always reloaded before the parent > reloaded.append((tmp[0], tmp[1])) > > reloaded.reverse() > TheReloaded = [] > for pair in reloaded: > if (pair[1] not in TheReloaded ): # Don't reload twice > the Base, else it can reload in this order : > # Base - > Derived1 - Base- Derived2 > # and > Derived1 init will fails > reload (pair[1]) > TheReloaded.append( pair[1]) > ---------------------------------------------------- > > This code solves my current problems, but I can imagine some possible > issue with two levels hierarchies. euh... Can I ??? From peter at engcorp.com Wed Apr 21 15:22:04 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 21 Apr 2004 15:22:04 -0400 Subject: CamelCase versus wide_names (Prothon) In-Reply-To: References: <407F3F20.DB8FA765@alcyone.com> Message-ID: A. Lloyd Flanagan wrote: > "Mark Hahn" wrote in message news:... > >>"Erik Max Francis" wrote ... >> >> >>>I'm surprised you're creating your own language and don't have enough >>>internal stylistic sense to make this choice yourself. >> > FWIW, Mark, I'm with you on this one. Standardizing variable names > isn't exactly what I'd call a "deep" design decision. > What's wrong with asking experienced programmers what works best? Well, threads like this, for one... From xml-bindings-admin at gnome.org Sun Apr 25 21:50:02 2004 From: xml-bindings-admin at gnome.org (xml-bindings-admin at gnome.org) Date: Sun, 25 Apr 2004 21:50:02 -0400 Subject: Your message to xml-bindings awaits moderator approval Message-ID: <20040426015002.26794.89149.Mailman@moniker.gnome.org> Your mail to 'xml-bindings' with the subject important Is being held until the list moderator can review it for approval. The reason it is being held: Post by non-member to a members-only list Either the message will get posted to the list, or you will receive notification of the moderator's decision. From sarge at arena.invalid Thu Apr 29 16:13:33 2004 From: sarge at arena.invalid (Sarge) Date: Thu, 29 Apr 2004 20:13:33 GMT Subject: MATLAB2Python References: <1090ivtaa0b2e26@corp.supernews.com> <40904EDE.9060407@erols.com> <715kc.3$i6.251@psinet-eu-nl> Message-ID: Il 29 apr 2004, John Hunter ha scritto: > I find python + numeric/numarray + MLAb + scipy + matplotlib to > be a very workable replacement for matlab, [cut] I'm impressed. Especially I liked the scipts, awesome! Please help me a little more, would you? Now, I work on WindosXP and on MDK Linux, I have found on the Internet and downloaded all the packages you were talking about: python, numeric, MLAb, scipy, matplotlib, but I can't figure out in which order (and where) I have to install them. I don't want to mess things up, because the Windoze box is at work and I have to ask for administrator priviledges in order to install/uninstall. Thanx, Sarge From peter at semantico.com Tue Apr 6 08:51:29 2004 From: peter at semantico.com (Peter Hickman) Date: Tue, 06 Apr 2004 13:51:29 +0100 Subject: design by contract versus doctest In-Reply-To: References: <407174ea$0$5066$4d4ebb8e@news.nl.uu.net> <4072977b$0$1699$afc38c87@news.easynet.co.uk> Message-ID: <4072a7d3$0$23314$afc38c87@news.easynet.co.uk> Colin Blackburn wrote: > On Tue, 06 Apr 2004 12:41:45 +0100, Peter Hickman > wrote: > >> Looking at the Eiffel site the contract is enforced within the called >> function. > > Only while checking is turned on. It is a design philosophy. You > specify the pre and post-conditions before code is even thought of, it > is part of the design. Sure but the checks are still made by the function that is called not by the caller of the function. Which was my point and contrary to what aku said. aku wrote: > But in "design by contract" this responsibility is squarely > on the shoulders of the caller, and is *not* checked in > the function. >> put (x: ELEMENT; key: STRING) is >> -- Insert x so that it will be retrievable through key. >> require >> count <= capacity >> not key.empty >> do >> ... Some insertion algorithm ... >> ensure >> has (x) >> item (key) = x >> count = old count + 1 >> end > > > This says that *if* the pre-conditions are met (by the caller) *then* > the post-conditions will be guaranteed to be met (by the called > method.) No this is not entirely true, the require and ensure and both parts of the contract. The function will not be called if the require section is found to be false (such as count being greater than capacity). Then after the function is executed (the do portion) then second half of the contract is checked, the ensure section. If these conditions fail then the contract is broken and the call fail just as if the require had failed. The require is a contract between the caller and the called. The ensure is, in effect, a contract between the called and itself. You might get the require section correct, this would mean that valid parameters have been passed to the called by the caller. But this is no guarantee that the do section doesnt screw things up. Which is why we have the ensure section, this checks that the do section has not done anything stupid. Take this as an example (hacked at the keyboard, probably wont work) double (x: ELEMENT) is require x > 0 do x = x * -2 ensure x > 0 end If you call it with double(-12) then the require section fails. If you call it with double(12) then the require section passes but the do section is creating a negative number and so the ensure section fails. Getting the require section to pass is no guarantee that the post-conditions (ensure section) will be met, the do section is code like anything else and may get things wrong. From anton at vredegoor.doge.nl Fri Apr 9 05:26:27 2004 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Fri, 09 Apr 2004 11:26:27 +0200 Subject: OT: Esperanto again (was Re: why is python better than eg. smalltalk?? ) References: <20031028061245.12451.00000133@mb-m01.aol.com> <4074f954$0$5802$79c14f64@nan-newsreader-02.noos.net> <407524df$0$5066$4d4ebb8e@news.nl.uu.net> <2dydnWcBufhsy-jdRVn-hA@powergate.ca> Message-ID: <40766c57$0$131$3a628fcd@reader1.nntp.hccnet.nl> Peter Hansen wrote: >As the author of that, I have to object slightly. Yes, it was >humor, but there are most definitely more people in the >Netherlands who speak Esperanto than there are people walking >on the moon, unless my lack of television has led to me missing >a few key events in the world of space exploration in the last >few years... Only if one is using statically typed concepts. There's a common feeling here that the government operates at a very large distance from the citizens of this country, and certainly doesn't speak esperanto. Anton From mark at prothon.org Mon Apr 26 15:23:03 2004 From: mark at prothon.org (Mark Hahn) Date: Mon, 26 Apr 2004 12:23:03 -0700 Subject: CamelCase versus wide_names (Prothon) References: <6e0680ac.0404211252.7f7b4358@posting.google.com> <4086DFA7.9736E7D3@alcyone.com> Message-ID: "Antoon Pardon" wrote ... > Where do I subscribe? The http://prothon.org page will point you to http://lists.prothon.org/mailman/listinfo From mrroach at okmaybe.com Tue Apr 20 13:19:13 2004 From: mrroach at okmaybe.com (Mark Roach) Date: Tue, 20 Apr 2004 17:19:13 GMT Subject: Can't spawn, or popen from daemon Message-ID: <1082481539.1395.21.camel@localhost> I am using the daemonize (double-fork) code from the cookbook, and have bumped into a strange issue. This is what my program is doing: def main(): ... useful things ... os.popen('/usr/bin/lp -d printer1 %s' % (filename)) def daemonize(func): """cookbook recipe from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66012""" ... cut 'n paste code ... #Additional closing of stdio sys.stdin.close() sys.stdout.close() sys.stderr.close() # this is pretty obscure! os.close(0) os.close(1) os.close(2) if __name__ == '__main__': daemonize(main) The thing that's strange is that the call to lp never happens... if I replace daemonize(main) with just main() it works as expected. Is there some secret requirement on stdin/out for popen/spawn/system calls? I have tried all three, and they all work when I don't double-fork, but don't when I do. I can't figure this out at all, and it doesn't help matters that the problem only occurs in a situation where it is very hard to debug... Thanks, Mark From peter at engcorp.com Thu Apr 29 14:13:35 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 29 Apr 2004 14:13:35 -0400 Subject: reading and removing first x bytes of a file In-Reply-To: References: <40911B85.5080107@hotmail.com> Message-ID: Terry Reedy wrote: > IF the remainder of the file fits in memory, then it can 'moved up' by > rewriting same file after seeking to beginning of file. Don't know how > safe on MAC OSes (ie, degree to which write is atomic). Of course, if data > are important, one should have at least a few minutes of battery backup. I think it's a fair assumption that when the OP asked for a "safe" way, he meant at least safer than that. If power failed in the middle of the update, or a system crash occurred, the file could well be unrecoverable... -Peter From len-1 at telus.net Tue Apr 6 17:34:22 2004 From: len-1 at telus.net (Lenard Lindstrom) Date: Tue, 06 Apr 2004 21:34:22 GMT Subject: Using function parameters to determine method kind References: <4qrzym6e.fsf@telus.net> <95aa1afa.0404050417.2d11b369@posting.google.com> <8yh9r7p2.fsf@telus.net> <95aa1afa.0404060309.32629338@posting.google.com> Message-ID: michele.simionato at poste.it (Michele Simionato) writes: > Lenard Lindstrom wrote in message > news:<8yh9r7p2.fsf at telus.net>... > > Michele Simionato wrote: > > >Lenard Lindstrom wrote in message > > > news:<4qrzym6e.fsf at telus.net>... > > >> I was wondering if anyone has suggested having Python determine > > >> a method's kind from its first parameter. > > ... > > >I find relaying on tbe parameter name to specify the kind of method > > >to be rather fragile. It works most times but not always. What about > > >inner classes for instance? ... > No, I had in mind this (contrived) example: > > class Outer(object): > def outermeth(self1): > class Inner(object): > def innermeth(self2): > > ... > > It is nice to have the ability to give any name to "self". Yes, I see what you mean. The best I can suggest is: class Outer(object): def outermethod(self1): class Inner(object): def innermeth(self2): ... innermeth = instancemethod(innermeth) outermeth = instancemethod(outermethod) or def outermethod(self): self1 = self ... def innermethod(self): self2 = self I believe there is a use for a builtin instancemethod descriptor anyways. It can wrap callables not of type python function. > ... > > Descriptors are unaffected by the function's parameters, so the first > > parameter can be anything you want. If I am not mistaken, the only > > methods other that __new__ that currently work without descriptors > > are instance methods. > > ?? All methods works with descriptors, what do you mean? > By descriptor I mean wrapper classes like staticmethod. A naked function can only be an instance method descriptor, which by convention has a first parameter of 'self'. __new__ is exceptional in that it is an instance method that is always called as an unbound method. I see though that __new__ would break if accidentally made a class method. > > Is it not good form for instance methods to > > start with 'self' anyways? (except maybe for a metaclass's __init__, > > but this is a special case) > > It is not a special case (no special case is special enough or something > like that). I thought a metaclass's __init__ was a special case because it was called from the meta meta-class, usually by method type.__call__. So maybe it could be called as an unbound method to avoid problems if it was not an instance method. But isn't type.__call__ the factory function for all new-style objects, not just classes? I also overlooked cooperative __init__ calls for multiple metaclass inheritance. So yes, there is nothing special about a metaclass's __init__ other than it is usually declared with 'cls' rather than 'self' as a first parameter. This is enough to convince me that a method's first argument is not a reliable indicator of method kind. All this talk about python functions just being another kind of descriptor makes me wonder if it is not time to revive the idea of having type function subclassable: class C(object): def f(c): __factory__ = classfunction # No confusion here ... issubclass(classfunction, type(lambda: None)) # True isinstance(C.f.im_func, classfunction) # True :-) Thanks for answering my questions. Lenard Lindstrom From godoy at ieee.org Tue Apr 13 07:33:54 2004 From: godoy at ieee.org (Jorge Godoy) Date: Tue, 13 Apr 2004 08:33:54 -0300 Subject: Logging Stacktrace To File References: <407bcbca$1_2@newspeer2.tds.net> Message-ID: On Ter 13 Abr 2004 08:15, Olaf Meding wrote: > In case of an exception, how could I log an exception to a file on disk? I think you'll have to catch the exception and then log it to the file. After that, you should raise the exception again. But I think that if any other part of the program deals with such an exception before you do, then you might miss it. -- Godoy. From greg at cosc.canterbury.ac.nz Tue Apr 6 00:58:25 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Tue, 06 Apr 2004 16:58:25 +1200 Subject: GUI Frameworks in Python? In-Reply-To: <8ef9bea6.0404041009.26ae2683@posting.google.com> References: <930ba99a.0404030246.786455f5@posting.google.com> <8ef9bea6.0404041009.26ae2683@posting.google.com> Message-ID: Hung Jung Lu wrote: > Can someone outline some differences/advantages of PyGTK vs. wxPython? Having had an intensive experience with both recently, I can give you some of my impressions. I started a project using wxPython, having heard good things about it. At first it seemed all right, but as things progressed I found myself becoming more and more frustrated with it. Everything seemed to be just a little more complicated than it needed to be, and I kept on running into bugs, limitations and strange behaviours that I had to work around. As an experiment, I tried re-writing it to use PyGtk, to find out what it would be like. It turned out to be a much more pleasant experience. The wrapping is very straightforward and Pythonic, and everything Just Works the way I expect. I've yet to encounter a single bug or unreasonable limitation. > A first look at PyGTK shows me a more Unix-like look-and-feel. On the > other hand, wxPython on Windows does look very much like any other > Windows applications. It doesn't look quite the same as native apps on Windows, but for my purposes it's close enough. If precise Windows authenticity is important to you, you might have to use wxPython or something else that uses native Windows widgets. > Is the event handling in PyGTK cleaner/better than wxPython? The basic idea is fairly similar in both, but event handlers ("signal handlers" in Gtk terminology) seem more straightforward to set up in PyGtk. In wxPython, for example, you have to get the ID number of the widget and pass that to an event-binding function; in PyGtk, you just pass the widget itself. That's just one example of how the PyGtk API is simpler. It might not sound like much, but lots of little things like that add up to make me like PyGtk much better. > Does PyGTK have more widgets? They seem to be more or less equal in this area, although the PyGtk text and table/tree widgets may provide more functionality than their counterparts in wxPython. I'm not sure, since I haven't had to use much more than the basic functionality of these widgets. It did seem to be easier to get the PyGtk table widget to do exactly what I wanted in some cases. > Given the lack of comparison, I > would guess that GTK is unix-friendly, since Unix people usually would > mention little or nothing about Windows. :) I would say that PyGtk is more Python-programmer-friendly, regardless of what platform you're using. The only disadvantage I can see for Windows is possibly slightly less authentic appearance. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From akhar at gmx.net Sun Apr 18 19:32:04 2004 From: akhar at gmx.net (StŽphane) Date: Sun, 18 Apr 2004 19:32:04 -0400 Subject: python and apple events ... Message-ID: <2004041819320416807%akhar@gmxnet> Hello, I am wondering if any one knows how I could bind my python app to answer to a hotkey combination under mac os x. I know it is possible to do so in obj-c but it seems to call a pure C function, and this makes me a bit confused on how I would use it under pyobjc here is an example: #import const UInt32 kLockUIElementHotKeyIdentifier = 'lUIk'; const UInt32 kLockUIElementHotKey ? ? ? ?= 109; //F10 will be the key to hit, in combo with Cmd AppShell * ? ? ? ? ? ?gAppShell = NULL; EventHotKeyRef gMyHotKeyRef; EventHotKeyID ? ?gMyHotKeyID; EventHandlerUPP ? ?gAppHotKeyFunction; pascal OSStatus LockUIElementHotKeyHandler(EventHandlerCallRef nextHandler,EventRef theEvent, void *userData); - (void)awakeFromNib { ?? ?EventTypeSpec eventType; ?? ?gAppHotKeyFunction = NewEventHandlerUPP(LockUIElementHotKeyHandler); ?? ?eventType.eventClass = kEventClassKeyboard; ?? ?eventType.eventKind = kEventHotKeyPressed; InstallApplicationEventHandler(gAppHotKeyFunction,1,&eventType,NULL,NULL); ?? ?gMyHotKeyID.signature = kLockUIElementHotKeyIdentifier; ?? ?gMyHotKeyID.id = 1; ?? ?RegisterEventHotKey(kLockUIElementHotKey, cmdKey, gMyHotKeyID, GetApplicationEventTarget(), 0, &gMyHotKeyRef); } pascal OSStatus LockUIElementHotKeyHandler(EventHandlerCallRef nextHandler,EventRef theEvent, void *userData) { ?? ?// We only register for one hotkey, so if we get here we know the hotkey combo was pressed; we can do whatever we want here ?? ?NSLog(@"Hello, World! HotKey was pressed!"); ?? ?return noErr; } --- taken from a post on cocoa.mamasam.com Thanks in advance for any help. Stephane From piet at cs.uu.nl Wed Apr 21 12:19:10 2004 From: piet at cs.uu.nl (Piet van Oostrum) Date: 21 Apr 2004 18:19:10 +0200 Subject: emacs for OS X Message-ID: >>>>> Tuxtrax (T) wrote: T> Hi all T> My editor of choice on linux for python, bar none, is xemacs. I love the T> python mode that detects a python file and handles indentation and T> coloration for me automagically. T> I have been using a powerbook for a while now, and I finally found emacs T> for aqua in OS X Jaguar (10.2.8). I downloaded it from porkrind.com. Really?? -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP] Private email: P.van.Oostrum at hccnet.nl From peter at engcorp.com Wed Apr 28 15:14:57 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 28 Apr 2004 15:14:57 -0400 Subject: Polling eth0? In-Reply-To: <3cdce0bb529198fa30efae192faeea7a@news.teranews.com> References: <3cdce0bb529198fa30efae192faeea7a@news.teranews.com> Message-ID: Dennis Craven wrote: > I intend on writing a small application that monitors incoming/outgoing > traffic on eth0, and recording the bandwidth usage with monthly > totals etc.. > > Where would be a good place to start in regards to connecting to > eth0 and reading such data? I would most definitely do this with appropriate calls to "iptables", specifically using the -Z option with -L, which is designed specifically for this kind of thing. (If you aren't familiar with it, it's a Linux firewall command, not anything to do with Python. You could use os.popen() to call it from Python though, and capture the output.) -Peter From devnull at example.com Tue Apr 27 00:08:01 2004 From: devnull at example.com (Derek Fountain) Date: Tue, 27 Apr 2004 12:08:01 +0800 Subject: urllib2 request blocks Message-ID: <408ddbdd$0$16600$5a62ac22@freenews.iinet.net.au> I just tried this: >>> import urllib2 >>> urllib2.urlopen( "https://passenger.ssc.com/~dmarti/contrib-faq/" ) It sits forever. Loading that URL in a normal browser gets me a popup asking about server certificate authenticity, which presumably is what urllib2 is blocking at. How can I prepare my code for this eventuality and ensure it doesn't block? From michal65 at hotmail.com Tue Apr 20 11:21:48 2004 From: michal65 at hotmail.com (Michal Mikolajczyk) Date: Tue, 20 Apr 2004 15:21:48 +0000 Subject: Easily convert unicode tuple to python string tuple??? Message-ID: Is there a quick way to convert a unicode tuple to a tuple containing python strings? (u'USER', u'NODE', u'HASH', u'IDNBR') to this: ('USER', 'NODE', 'HASH', 'IDNBR') I need to be able to do this for a lot of tuples, not just one. Thanks, Michael _________________________________________________________________ Watch LIVE baseball games on your computer with MLB.TV, included with MSN Premium! http://join.msn.com/?page=features/mlb&pgmarket=en-us/go/onm00200439ave/direct/01/ From grzegorz at ee.ualberta.ca Sat Apr 17 20:16:53 2004 From: grzegorz at ee.ualberta.ca (Grzegorz Dostatni) Date: Sat, 17 Apr 2004 20:16:53 -0400 Subject: os.system help In-Reply-To: <78lgc.3445$AL1.7744@news1.mts.net> References: <78lgc.3445$AL1.7744@news1.mts.net> Message-ID: Cheers. In short ghostscript is not installed by default on windows. You can install it yourself (http://www.cs.wisc.edu/~ghost/doc/AFPL/get814.htm) and install. You could also try to package it in your program somehow (for example including the binary in your program directory). I'm not sure if it will work properly though. I don't think there is anything installed by default on windows that can read .ps files. You could also try another approach. I am not entirely sure, but I think that Python Imaging Library supports writing/reading .ps files. Greg Advice is what we ask for when we already know the answer but wish we didn't. -- Erica Jong (How to Save Your Own Life, 1977) On Sat, 17 Apr 2004, Reid Nichol wrote: > Hello, > I have made a program that works wonderfully on OpenBSD but it uses > os.system to get ghostscript to convert ps to jpeg. But, I wish this > program to run on Windows as well. Is there any way I can snag where > the gs executable is on Windows? What it is named? And so forth. > > From hungjunglu at yahoo.com Wed Apr 7 10:21:09 2004 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 7 Apr 2004 07:21:09 -0700 Subject: painful debugging: techniques? References: Message-ID: <8ef9bea6.0404070621.342c3b5d@posting.google.com> "Roger Binns" wrote in message news:... > > I do two things. One is that I catch exceptions and print out the > variables for each frame, in addition to the traceback. The recipe > is at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52215 I think this will not work for the original poster's case. His exception happens at the moment of garbage collection, out of his control. That is, the exception is not coming from one of his statements, so he can't wrap a try...except block around it. Example: import weakref class A: pass def f(): a = A() w = weakref.ref(a, None) try: f() except: print 'This will never be printed' -------------------------- The original poster spent 9 hours to find the source of this bug. So it is a tough problem, and it may well happen to other people. The question now is: how can we stop this from happening to other people? This bug does not seem to be catchable by sys.excepthook, which makes it even tougher. So far, I think Peter Otten's approach (search through the source code) may be the most practical way. The fact that this bug cannot be caught with sys.excepthook should probably be considered a bug in Python? I guess the only consolation is that this kind of system bugs don't seem to happen too often. :) regards, Hung Jung From pm_mon at yahoo.com Wed Apr 14 14:18:57 2004 From: pm_mon at yahoo.com (Paul Morrow) Date: 14 Apr 2004 11:18:57 -0700 Subject: Difficulty Finding Python Developers References: <65cbc3dd.0404140641.3501fde8@posting.google.com> Message-ID: <65cbc3dd.0404141018.36d9d4ce@posting.google.com> For those who've asked... This particular project is essentially a web-based registration application. We'll probably want to use mod_python to serve the pages, and Oracle for the database backend. It will have things like a white-paper area that requires registration to access, an opt-in/out email component, and the like. But we do want the developer to be physically here (in Atlanta). From jcarlson at uci.edu Sun Apr 11 04:28:29 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Sun, 11 Apr 2004 01:28:29 -0700 Subject: maximum length of a list & tuple In-Reply-To: References: Message-ID: >>Run the following and the last thing it prints out is your limit... >> >> c = 1 >> while c < 2**32: >> try: >> d = [1]*c >> print c >> c *= 2 >> except: >> break > > > Interesting experiment. I get 64M on my 384MB machine, which suggests 4 > bytes per list entry. Of course, now my swap file is packed full, and all > my apps are running slowly while they page themselves back in... Far more than 4 bytes per list entry. 4 bytes to store the integers themselves, but since integers are Python objects, and lists are arrays of pointers to list objects, there is quite a bit of other extra stuff attached. I can't remember exactly how much extra stuff, but it can be found by looking through the sources. You could check the amount of memory used before, and the memory used at peak, and divide it by your 64M to find out how much is used. I just did, but I'll also leave it as an exercise to the reader. - Josiah From claird at lairds.com Wed Apr 21 13:34:53 2004 From: claird at lairds.com (Cameron Laird) Date: Wed, 21 Apr 2004 17:34:53 -0000 Subject: tkinter widget collection project References: Message-ID: <108dc5tc7q6bnbd@corp.supernews.com> In article , wrote: >-=-=-=-=-=- > >I, like a lot of developers, have collected a homegrown set of widgets for >Tkinter. > >Any thoughts on a central repository for Tkinter widgets or widget >extensions? Stuff that's not in Tkinter or standard extensions like Pmw. > >It would be nice if you could go to sourceforge and download a package >instead of hunting the Vaults, the Activestate cookbook, googling, etc. > >If there's enough interest I'd be willing to set the project up on >sourceforge and provide some (limited) manpower towards packaging submitted >widgets. . . . Be certain to leave at least a pointer in the Tkinter Wiki . -- Cameron Laird Business: http://www.Phaseit.net From JimJJewett at yahoo.com Mon Apr 19 23:22:20 2004 From: JimJJewett at yahoo.com (Jim Jewett) Date: 19 Apr 2004 20:22:20 -0700 Subject: module parameters Message-ID: I have often wanted to pass arguments to a module. Tyically, these are globals, such as DEBUG or VERBOSE that are set at the top of the module -- and I want to use a different value. For modules that provide a service (such as logging), I would like to make my changes before the defaults are set up. Assuming that the loaded module is cooperative, what is the least ugly way to pass these parameters? (1) Alter/Check __builtins__ (2) Alter/Check a "well-known" module, such as settings, for an attribute named after the loading module.* (3) Alter/check a modsettings module specific to module mod. (4) Use an import hook (5) Accept that there will be some inefficiencies and reset after the initial load. * I'm not aware of any such well-known module yet, but if others agree that it sounds like a good idea, I will write one. -jJ From ramen at lackingtalent.com Mon Apr 19 13:08:41 2004 From: ramen at lackingtalent.com (Dave Benjamin) Date: Mon, 19 Apr 2004 17:08:41 -0000 Subject: module not callable - why not? References: Message-ID: In article , Diez B. Roggisch wrote: > Now usually I'd create a file called "quaternion.py", define my quaternion > class in there and then import and create an instance like this: > > import quaternion > > q = quaternion.quaternion() > > Thats a lot to type. doing a > > from quaternion import quaternion > > would solve that - but AFAIK thats considered bad for some reasons. Lately, I've become particularly fond of creating "factory" functions and using those instead. For instance: import Quaternion q = Quaternion.create() Aside from the less redundant naming style, factories are nice because they allow you to return different classes of objects depending on their parameters. For instance, Quaternion.create() might give you a Quaternion.SimpleQuaternion, where Quaternion.create(foo='bar') might give you a FooQuaternion instead. (I don't know much about quaternions, so I can't give you a better example in that context.) -- .:[ dave benjamin: ramen/[sp00] -:- spoomusic.com -:- ramenfest.com ]:. : please talk to your son or daughter about parametric polymorphism. : From jcarlson at uci.edu Fri Apr 2 15:49:00 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Fri, 02 Apr 2004 12:49:00 -0800 Subject: PLEASE STOP!!! In-Reply-To: References: <95aa1afa.0404010352.80de14e@posting.google.com> <406C40E8.10209@prescod.net> Message-ID: >>Of course, I suppose the prank is that people think it is a prank, when >>in fact, is actually truth. > > > Aren't double bluffs great?-) I don't know about 'great', but nifty, yes. - Josiah From peter at engcorp.com Mon Apr 5 12:46:54 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 05 Apr 2004 12:46:54 -0400 Subject: Module import problems In-Reply-To: <30260531.0404050827.320e3c14@posting.google.com> References: <30260531.0404041725.746befa0@posting.google.com> <30260531.0404050827.320e3c14@posting.google.com> Message-ID: simo wrote: > So I think the login class is failing to initialise as it can't find > the wx class imported in main.py, because if I run login.py then I get > "...wx not defined" surely I don't have to import wx in every file > (that doesn't work actually)?! Yes, of course you do. > This namespace crap is becomming an inconvenience - jees, do we have > to make everything global?! Really, it's not at all that difficult. Anyway, the namespaces are there to protect you and simplify the code. Although you could think of it as a small inconvenience to have to put imports for various things wherever you need them, the alternative is vastly more of a problem. > Also, does IDLE cache the compiled Python or something, as sometimes > when I change a file and save/run it in the shell, it doesn't change > (I do delete the .pyc files) until I quit and reload IDLE? I never use IDLE, so I can't say. My preferred approach is simply running things from the command line (but you get that way when you start focusing on unit testing rather than code-and-fix...). -Peter From richie at entrian.com Thu Apr 15 12:07:49 2004 From: richie at entrian.com (Richie Hindle) Date: Thu, 15 Apr 2004 17:07:49 +0100 Subject: CamelCase versus wide_names (Prothon) In-Reply-To: References: Message-ID: [Mark] > could you for the moment pretend you were picking your standard from > scratch (as we are doing in the Prothon world) and give your vote for which > you'd prefer? My preference is for camel case, with initial caps only for class names: -------------------------------------------- moduleVariable = 3 def myFunction(formalParameter): localVariable = None class MyClass: def methodName(self, formalParameter): localVariable = None self.myAttribute = None -------------------------------------------- I don't have any scientific backing for that - just "it looks right to me". That said, 99% of the standard library disagrees with me and uses wide_names (at least for method names) which is a pretty powerful argument for adopting that as your standard: $ egrep "( |\t)+def " *.py | wc 3353 14222 154294 $ egrep "( |\t)+def [a-z0-9]*[A-Z][a-z0-9]*\(" *.py | wc 39 148 1645 ...OK, 98.837% 8-) Class names are mostly standardised on CamelCase - hardly any have underscores: $ egrep "^class +[^(_]+_[^(]*\(" *.py | wc 11 45 583 -- Richie Hindle richie at entrian.com From peter at engcorp.com Thu Apr 29 08:57:21 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 29 Apr 2004 08:57:21 -0400 Subject: Is classless worth consideration In-Reply-To: <69cbbef2.0404290259.fd8d71c@posting.google.com> References: <69cbbef2.0404290259.fd8d71c@posting.google.com> Message-ID: has wrote: > Well, as far as Python itself is concerned, it'd go a long way in > eliminating the hideously baroque and increasingly brittle OO model it I find it especially hard to find the enthusiasm to read past the highly inflammatory phrase "hideously baroque". I had to do a double-take just to confirm that the poster is indeed talking about Python. If you think it's baroque**, say so. Adding "hideous" just tells us you are already highly biased against Python and poisons anything else you were about to say... -Peter ** Please double-check the definition of "baroque" that you are using as well. Very little of the meaning that I find at dict.org, for example, has ever come to mind while using OO with Python. Terms more like "elegant" and "simple" have come to mind, however, which is quite at odds with your perception. Strange, that. From godoy at ieee.org Fri Apr 30 14:09:25 2004 From: godoy at ieee.org (Jorge Godoy) Date: Fri, 30 Apr 2004 15:09:25 -0300 Subject: Dictionnary vs Class for configuration References: <40929016$0$8635$626a14ce@news.free.fr> Message-ID: On Sex 30 Abr 2004 14:38, Famille Delorme wrote: > We have do only a file for configuration because the administrator is no > searching for configuration. > I want know : > - what is more faster, dictionnary method or class method? > - what use more ram memory ? > - if you are administrator, what method you like for configure program ? Not answering directly --- because if it is for your professor and he said he would like to have it one way you should do what he says... --- but have you looked at ConfigParser module? -- Godoy. From __peter__ at web.de Wed Apr 7 05:35:16 2004 From: __peter__ at web.de (Peter Otten) Date: Wed, 07 Apr 2004 11:35:16 +0200 Subject: painful debugging: techniques? References: Message-ID: Humpty Dumpty wrote: > Hello, I've been using python for about 3 months now. Prior to that I did > C++ for over 5 years. I'm wondering if my debugging techniques are too C++ > oriented. > > E.g., it took me about 9 hrs of debugging to figure out that the second > parameter to weakref.ref() was being passed as None. This is odd because > the second parameter is optional, yet its default value is not documented, > so I assumed that passing None would be fine, and then I forgot that I was > doing that. It took that long mostly because the exception message was > "Exception TypeError: 'NoneType not a callable' in None being ignored", ie > it was being ignored and function from which it was being raised was > unknown to Python (somehow), *and* it was only being raised upon exit of > the test (cleanup). So I had no way of knowing where this was being > raised. It was nasty. > > I'm wondering if there are tricks people use to track down problems like > this. The best strategy would have been to avoid the error altogether :-) Python makes that easy; just test a chunk of code on the command line: >>> import weakref >>> class X: ... pass ... >>> def cb(a): print "callback" ... >>> x = X() >>> w = weakref.ref(x, cb) >>> del x callback >>> x = X() >>> w = weakref.ref(x, None) >>> del x Exception exceptions.TypeError: "'NoneType' object is not callable" in None ignored The next best thing is to have a proper test suite and making only small changes to your program, so that you can easily attribute an error to a newly added chunk of code. IMHO this is the most promising aproach for anything comprising more than one module. I admit that I don't know how to devise test to discover your problem. So what if all else fails? Let's stick to your example. I would see not getting a traceback as a strong hint that something unusual is going on. In this case you can leverage the fact that python is open source and search for the place where the error message is generated. Looking for "%r ignored" and "%s ignored" in *.py of Python's source distribution yields no result. At this point I would extend the search to "ignored" in the C source: 48 hits, but most of them in comments. The one in error.c seems promising. Unfortunately the comment in PyErr_WriteUnraisable() gives the "wrong" __del__() example, so you need one more iteration to hunt for PyErr_WriteUnraisable. As the variable names are well chosen, the match in weakrefobject.c (PyErr_WriteUnraisable(callback);) gives you a strong clue. I admit this is tedious and that I had a headstart as you already provided the connection to weakref, but I reckon that this approach would still take less than one hour. As a hidden benefit, you learn something about Python's architecture. Also, in my experience your problem is a particularly hard one to track down (as far as pure Python is concerned). At last, what I would call the Columbus approach: do you really need weakrefs in your application, or is the error an indication that you are introducing unnecessary complexity in your app? Few eggs actually need to stand on their tip :-) Peter From grzegorz at ee.ualberta.ca Fri Apr 30 14:32:48 2004 From: grzegorz at ee.ualberta.ca (Grzegorz Dostatni) Date: Fri, 30 Apr 2004 14:32:48 -0400 Subject: Embedding python into PyQt Message-ID: Cheers. What I am trying to do is to embed the python interactive interpreter inside a qt TextEdit. I could write an event loop myself, but I was wandering if there exists a solution somewhere, or the best way to do it myself. Greg Advice is what we ask for when we already know the answer but wish we didn't. -- Erica Jong (How to Save Your Own Life, 1977) From peter at engcorp.com Mon Apr 12 12:31:26 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 12 Apr 2004 12:31:26 -0400 Subject: Problem with dates and daylight savings... In-Reply-To: References: Message-ID: John Taylor wrote: > I was wondering if some one could explain this anomaly. I wrote a program to add/subtract > dates. For example, > > ./ComputeDay.py 2004/04/12 -7 %Y/%m/%d > 2004/04/05 > > Here is the anomaly.... > ./ComputeDay.py 2004/04/12 -8 %Y/%m/%d > 2004/04/03 > > I would have thought this would have returned the 4th. I have a feeling that daylight savings > has something to do with this, as the time changed on the 3rd. > Can someone explain this? How can I correct this problem? Doing date math using seconds is highly error-prone and frustrating. The way to correct this is to use the datetime module: c:\>python Python 2.3.3 (#51, Dec 18 2003, 20:22:39) [MSC v.1200 32 bit (Intel)] on win32 >>> from datetime import datetime, timedelta >>> d = datetime(2004,4,12) >>> d datetime.datetime(2004, 4, 12, 0, 0) >>> d - timedelta(days=8) datetime.datetime(2004, 4, 4, 0, 0) You might be right about the daylight savings time thing, but who cares? ;-) The datetime module is the right tool for the job here and it gets the correct result. -Peter From simoninusa2001 at yahoo.co.uk Thu Apr 8 14:03:20 2004 From: simoninusa2001 at yahoo.co.uk (simo) Date: 8 Apr 2004 11:03:20 -0700 Subject: wx.SystemSettings - GTK/Win32/Python variances Message-ID: <30260531.0404081003.136f8759@posting.google.com> I'm trying to find the vertical scrollbar width across platforms in my wxPython app, but am having troubles. It seems that on Linux/wx2.4.2.4 these work: wx.SystemSettings_GetSystemMetric(wx.SYS_VSCROLL_X) wx.SystemSettings.GetSystemMetric(wx.SYS_VSCROLL_X) The first is supposed to be wxPython-specific according to the docs. Neither of these work on Windows/wx2.5.1.5, but this does: wx.SystemSettings.GetMetric(wx.SYS_VSCROLL_X) Note the lack of the second "System". Also, according to something I've read, "on GTK, the scrollbar is included in the client size, but on Windows it is not included", which seems to be crap, from my results, it seems it's not included on either platform. Maybe this is outdated info and it's changed in 2.4+ I seem to recall that wx.Platform was being deprecated, so how do we do platform checks to fix the things that vary between implementations - I don't know what wxMAC does with scrollbars/GetClientSize() ! From jmiller at stsci.edu Mon Apr 19 15:41:14 2004 From: jmiller at stsci.edu (Todd Miller) Date: Mon, 19 Apr 2004 15:41:14 -0400 Subject: matplotlib error with tkagg In-Reply-To: References: Message-ID: <40842B5A.7090103@stsci.edu> Federico wrote: > Hi, I'm using python 2.2 under windows...when I use the 'Agg ' backend it > works fine but when I try to use the 'TkAgg' one I've an error message that > says : > .... > .... > "import tkagg # Paint image to Tk photo blitter extension > File "D:\PYTHON~1.3\Lib\site-packages\matplotlib\backends\tkagg.py", line > 1, in ? > import _tkagg > ImportError: DLL load failed: " impossible to find the specified procedure It's not just you... I develop the TkAgg backend with Python 2.3 (on Linux and Solaris and win32) and didn't test the 2.2 installer for windows. TkAgg is apparently broken for Python-2.2 on windows. > > What do I need? > Nothing. I think there's a bug in the way the tkagg backend is currently built for Windows. The _tkagg.pyd file appears to be dependent on Tcl/Tk 8.4 and I think for Python-2.2 it needs 8.3. If you're willing to upgrade to Python-2.3, you can have matplotlib with TkAgg today. Regards, Todd Miller From simoninusa2001 at yahoo.co.uk Thu Apr 8 19:29:18 2004 From: simoninusa2001 at yahoo.co.uk (simo) Date: 8 Apr 2004 16:29:18 -0700 Subject: wx.SystemSettings - GTK/Win32/Python variances References: <30260531.0404081003.136f8759@posting.google.com> Message-ID: <30260531.0404081529.195b033e@posting.google.com> Peter Hansen wrote: > http://www.wxpython.org/MigrationGuide.html says that you should > probably begin using wx.PlatformInfo instead. This is a tuple. > On my machine (WinXP) it contains: > > >>> wx.PlatformInfo > ('__WXMSW__', 'wxMSW', 'ascii') > > The doc mentioned says to do things like this now: > > if "__WXGTK__" in wx.PlatformInfo: Yup, found that just now - I had only looked at the wxWidgets migration guide, didn't know there was a wxPython version too! Anyway, I don't need the platform check now as also in the wxPy25 guide they say that we're now to use wx.SystemSettings_GetMetric(wx.SYS_VSCROLL_X) across all platforms as they're deprecating the other forms - which seem to be aliases for backwards compatibility. Thanks for the help :-) From iv at an.voras.fer Fri Apr 2 10:41:38 2004 From: iv at an.voras.fer (Ivan Voras) Date: Fri, 02 Apr 2004 17:41:38 +0200 Subject: Creating a matrix? In-Reply-To: References: Message-ID: Peter Maas wrote: > Ivan Voras wrote: > >> Is there a nice(r) way of creating a list of uniform values? I'm >> currently using: list('0'*N), which makes a string and then chops it >> up into a list. I need it to create a NxN matrix: >> > > matrix = [list('0'*N) for i in range(N)] > > matrix = [['0']*N]*N I can't believe I didn't try that one :) (hmm, actually, I think I tried it but the results were bad for some reason... oh well, thank you :) ) From Kyler at news.Lairds.org Thu Apr 1 00:08:04 2004 From: Kyler at news.Lairds.org (Kyler Laird) Date: Thu, 01 Apr 2004 05:08:04 GMT Subject: Python conference slogan References: Message-ID: Shane Hathaway writes: >I don't know if international folks will >get it, though. :-) If they don't, we just send in troops to explain it to them, right? --kyler From alan.gauld at btinternet.com Tue Apr 27 16:24:28 2004 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 27 Apr 2004 21:24:28 +0100 Subject: Tkinter vs. wxPython? References: Message-ID: <05gt801pbp6jmprrcbr78npbp2j2q0i94p@4ax.com> On Tue, 27 Apr 2004 15:03:19 -0300, "Batista, Facundo" wrote: > But, I read somewhere that Tkinter is simpler, but difficult so make big > complicated stuff. wxPython is more difficult at start, but more scalable. > I've played with both but my GUI needs are simple - usually putting a nice front end on a CLI script. (Fancy GUI stuff I tend to do in Delphi - oh the shame of it...) But my experience suggests similar findings, Tkinter is dead easy to build small GUIs but it has a limited widget set (even including PMW) and has no currently maintained graphical GUI builder so far as I know (SpecPython is long discontnued!) And there is no doubt that wxPython looks more natural, on windows at least, although the differences aren't enough to make me switch. BUt my needs are, as I said, very simple. Alan G. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld From mwilson at the-wire.com Sat Apr 3 08:07:45 2004 From: mwilson at the-wire.com (Mel Wilson) Date: Sat, 03 Apr 2004 08:07:45 -0500 Subject: first python program.. lyrics search References: Message-ID: In article , Gustavo Rahal wrote: >Hi > >I'm trying to learn python by doing something that I think it would be >nice; Search lyrics using some websites like www.musicsonglyrics.com, >http://www.sing365.com [ ... ] >The problem is once I have the M.htm page I don't now how to get from >the html code the "http://www.musicsonglyrics.com/M/Metallica/Metallica >lyrics.htm" link to proceed with the search. I tried to read about >Regular Expressions but I think I'm to dumb for it. > >Any ideas? Maybe my approach is completely wrong.... Look up htmllib in Python libraries. It's not a small job, but you'll have learned a lot by the time you've finished. Good Luck. Mel. From trevp_spam at trevp.net Mon Apr 19 22:41:58 2004 From: trevp_spam at trevp.net (Trevor Perrin) Date: Tue, 20 Apr 2004 02:41:58 GMT Subject: block ciphers In-Reply-To: <7x3c6zqvdy.fsf@ruckus.brouhaha.com> References: <7L_gc.53134$Gn6.49963@newssvr25.news.prodigy.com> <7x3c6zqvdy.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > [...] > PEP 272 has an API for both block and stream ciphers, and the block > cipher API is kind of cumbersome. In what way? It seems to me quite simple: >>> from Crypto.Cipher import AES >>> >>> context = AES.new(key, AES.MODE_CBC, iv) >>> ciphertext = context.encrypt(plaintext) >> >>> context = AES.new(key, AES.MODE_CBC, iv) >>> plaintext = context.decrypt(ciphertext) A couple of the keyword arguments could be changed ('rounds', and 'counter'), and the IV should probably be writeable as well as readable (which is how PyCrypto, which implements this PEP, actually works). Other than that, I've been using this API (and wrapping a few other cipher libraries with it), and I find it about as close to transparent and painless as you can get! > I did some work a while back on > defining a new block cipher API and posted some about it back then. > I've been meaning to get that code out of mothballs and propose a new > PEP. A sample implementation is at > > http://www.nightsong.com/phr/crypto/blockcipher.tgz I'd be happy with that too, but it seems a smidgen less simple, at least for the user: >>> from blockcipher import CBC >>> import AES >>> >>> context = CBC(AES.ecb(key), 'e', iv) >>> ciphertext = context.update(plaintext) More importantly though, PEP 272 is already implemented (in PyCrypto), and it's been in use awhile so people (like me) have code built around it, and experience with it. Again, I'd be happy with either, but PEP 272 / PyCrypto seems the leading horse in this race. [Trevor] >>So is this totally out of the question? Or would it be worth >>pursuing, through a PEP, or patch, or discussion on python-dev? > > > I'm not sure exactly what you're asking. Me neither, exactly... ;-) I'm just trying to gauge the interest or resistance to this, and see if there's any way I could help. Trevor From newsgroups at jhrothjr.com Sat Apr 10 10:20:51 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 10 Apr 2004 10:20:51 -0400 Subject: Wrapper round x86 Assembler References: <8089854e.0404082353.7bf163a2@posting.google.com> Message-ID: <107g0m9sg8h85b3@news.supernews.com> "Fuzzyman" wrote in message news:8089854e.0404082353.7bf163a2 at posting.google.com... > There might be a really good reason why this hasn't been done *or* > someone might have done it and I just can't find it..... *but* > > what about a wrapper to an assembler (presumably for x86 assembly !) > !! > I just wrote some code doing binary operations which would have been > about a zillion times faster in a few lines of assembly code. > > I also have fond memories of programming in BBC Basic which had an > inline assembler - so you could wrap your assembly program in Basic. > It meant some commercial games started with Basic ! > > Anyway - it would be easy to reserve some memory with a string like > object to pass to an 'assembly object' and allow some really nifty > (and fast) stuff ?? For simple algorithms it would be very neat. > Avoiding memory overflow etc would be up to the assembly code 'chunk' > of course. > > Regards, > > > Fuzzy You should be able to write a relatively simple C language extension that would let you do this. The interface to extensions isn't all that hard to work with. It would probably be pretty useful for some kinds of intensive crunching. There's one thing to watch out for: Intel CPU's are going to a model where dynamically generated code won't work unless you provide the correct incantation. This is to eliminate a large class of viri. John Roth From michele.simionato at poste.it Sat Apr 3 04:43:02 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 3 Apr 2004 01:43:02 -0800 Subject: [maybe OT] Making posters Message-ID: <95aa1afa.0404030143.58c32975@posting.google.com> Perhaps this is a bit off topic, but I haven't had look browsing on the net, so I thought I will try my chance here. I am looking for a tool taking a postscript file and enlarging it to make a poster. For instance I want to convert a picture taking a sheet in a poster made by four sheet that I can compose. Any suggestion? A Python suggestion would help me to stay on topic ;) Michele Simionato From jepler at unpythonic.net Sun Apr 18 10:03:52 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Sun, 18 Apr 2004 09:03:52 -0500 Subject: module not callable - why not? In-Reply-To: References: <107dras2heahcb6@news.supernews.com> <8ef9bea6.0404122025.36efc84e@posting.google.com> <7xsmf1fxd9.fsf@ruckus.brouhaha.com> Message-ID: <20040418140351.GA30226@unpythonic.net> On Sun, Apr 18, 2004 at 09:08:37AM -0400, Heather Coppersmith wrote: > Note that modules are neither functions nor objects. Of course modules are objects. Everything is an object, and most things are even instances of "object". >>> import sys >>> type(sys) >>> isinstance(sys, object) 1 Jeff From mark at prothon.org Thu Apr 1 18:57:06 2004 From: mark at prothon.org (Mark Hahn) Date: Thu, 1 Apr 2004 15:57:06 -0800 Subject: Prothon, metaclasses, Zope [Was: A 'Python like' language] References: <95aa1afa.0403272243.78d60724@posting.google.com> <95aa1afa.0404010017.2f1683b8@posting.google.com> Message-ID: > it is difficult to give credit to people liking tabs and > top posting. Even though I admit to the heinous crime being a "tab-lover", we have changed Prothon to accept either tabs or spaces in indents, just not both in the same file. As far as top-posting, I am trying to improve, it's just hard to change my reply style after using it for 30 years without getting any complaints before. I feel like I'm in a twilight-zone episode. "Michele Simionato" wrote in message news:95aa1afa.0404010017.2f1683b8 at posting.google.com... > "Mark Hahn" wrote in message news:... > > Original top posting maintained on purpose: > > > Does anyone get anything done around here with all the bitching? I've been > > communicating via email for 30 years and never have I seen such complaining > > about something so silly. If you have anything to contribute to Prothon > > I'll be over in the Prothon lists. We are too busy creating to have > > conversations like this over there. > > > > You may not be able to tell it, but I'm a nice guy who would really like > > feedback from intelligent knowledgable people like yourself. I just can't > > take this anymore. > > > > Aahz wrote: > > > In article , > > > Mark Hahn wrote: > > >> > > >> Self defines having the same attribute in two different prototypes > > >> illegal. That seemed extremely constraining to me so I went with the > > >> Python 2.2 mro solution in Prothon. > > > > > > Bad idea. But I won't tell you why until you stop top-posting and > > > over-quoting. > > Aahz is probably referring to the fact that Python 2.3 has changed the > MRO since the 2.2 one was a bad idea. See > http://www.python.org/2.3/mro.html > for more. A part for this, Aahz is right in pointing out that you > cannot get > the attention of a lot of intelligent knowledgable people on c.l.py > because > of your postings habits. Actually this is the reason why I have > downloaded Prothon yet. It is kinda of a pity, since maybe the idea is > worth, but it is difficult to give credit to people liking tabs and > top posting. Those are not > stupid things IMNSHO. > > Michele Simionato From pf_moore at yahoo.co.uk Sun Apr 4 11:23:38 2004 From: pf_moore at yahoo.co.uk (Paul Moore) Date: Sun, 04 Apr 2004 16:23:38 +0100 Subject: __import__() with packages References: Message-ID: Marco Herrn writes: > I am using the builtin __import__() to import modules. That works for > simple modules like in this example: [...] > But how do I do this with packages? A I understand the documentation > for __import__(), it must be something like: Look again at the documentation for __import__. In particular, you want a function like the following, given in the dicumentation: def my_import(name): mod = __import__(name) components = name.split('.') for comp in components[1:]: mod = getattr(mod, comp) return mod Then, you do eggs = my_import("spam.eggs") I have to admit, I find this annoyingly subtle - 99.99% of the time, it's my_import() that you want, but you have to define it yourself... Ah, well. I hope this helps. Paul -- This signature intentionally left blank From alloydflanagan at comcast.net Wed Apr 21 18:06:23 2004 From: alloydflanagan at comcast.net (A. Lloyd Flanagan) Date: 21 Apr 2004 15:06:23 -0700 Subject: This is very simple question References: Message-ID: ekoome at yahoo.com (Eric) wrote in message news:... > I would want to obtain a list of factors (multiples of 2) given a > prime number in python. > > For example 13=[8,4,1], 5=[4,1], 7=[4,2,1], 15=[8,4,2,1] > > I would appreciate a fuction which would do this. > > Eric Minor quibble: you don't mean factors. The only factors of a prime number are the number itself and one; that's the definition of a prime number. Now, do you want a list of all powers of 2 less than a prime number, OR do you want a list of powers of 2 such that the sum of the numbers is the given prime number? For Mersienne primes, which are of the form (2**n-1) the answer is the same either way. All your examples are Mersienne primes. But look at 11: 11 = 8 + 2 + 1, not 8 + 4 + 2 + 1 Of course, any odd number can be expressed as 2 + 2 + ... + 1, so what you would really want is the shortest list of powers of 2 that add up to the prime. From skip at pobox.com Mon Apr 5 15:48:38 2004 From: skip at pobox.com (Skip Montanaro) Date: Mon, 5 Apr 2004 14:48:38 -0500 Subject: CSV ignores lineterminator In-Reply-To: References: Message-ID: <16497.47126.723619.586429@montanaro.dyndns.org> >>>>> "Jeffrey" == Jeffrey Barish writes: Jeffrey> With Jeffrey> input_data = ['word1\tword2;word3\tword4;', Jeffrey> 'word5\tword6;word7\tword8;'] Jeffrey> and Jeffrey> delimiter = '\t' Jeffrey> lineterminator = ';' Jeffrey> shouldn't csv.reader(input_data, dialect='mydialect') return Jeffrey> ['word1', 'word2'] Jeffrey> as the first row? I find that it doesn't matter how I set Jeffrey> lineterminator, csv always terminates at the end of the line returned Jeffrey> by the iterable object passed as its first argument (input_data, in Jeffrey> this case). I must be missing something basic here. Jeffrey> I may be confused about the interaction between what iterable Jeffrey> object defines as the next row and what csv.reader defines as Jeffrey> the next row. Perhaps. Think of input_data as the conceptual result of f.read().split(lineterminator) (though without loss of the line terminator): >>> input_data = ['word1\tword2;', 'word3\tword4;','word5\tword6;', 'word7\tword8;'] >>> import csv >>> class d(csv.excel): ... delimiter='\t' ... lineterminator=';' ... >>> rdr = csv.reader(input_data, dialect=d) >>> rdr.next() ['word1', 'word2;'] >>> rdr.next() ['word3', 'word4;'] >>> rdr.next() ['word5', 'word6;'] >>> rdr.next() ['word7', 'word8;'] Skip From no_spam at terastat.com Tue Apr 27 14:16:00 2004 From: no_spam at terastat.com (bap) Date: Tue, 27 Apr 2004 18:16:00 GMT Subject: Problem with PY2EXE and VPython References: Message-ID: Thanks The following files are in the distribution directory created by PY2EXE cvisual.dll datetime.pyd DDRAW.dll dirlist.txt GLU32.dll hanoi.exe library.zip multiarray.pyd OPENGL32.dll python23.dll umath.pyd w9xpopen.exe _numpy.pyd _sre.pyd None appear to be extraneous system files. Bruce "Thomas Heller" wrote in message news:mailman.37.1083048526.25742.python-list at python.org... > "bap" writes: > > > When I try to run a program on a clean machine using the VPython extensions > > after compiling with PY2EXE I get the following error message: "The > > procedure entry point IsWow64Process could not be located in the dynamic > > link library KERNEL32.dll" . The compiled version runs fine on the original > > machine (win NT OS) but gives this error message on a machine without > > VPython installed (Win 2K OS). Is this anything that can be fixed with > > appropriate parameters in PY2EXE or does it require that VPython be tweaked? > > This error looks like that py2exe is picking up some 'system dlls' into > the dist directory, which are (sometimes) system specific. > > If you post the list of files that are in the dist directory, it might > be possible to name them. > > Earlier versions of py2exe had a builtin list of dlls which should be > ignored, this list will again be in the next version. > > Thomas > > From rjgruet at yahoo.com Sun Apr 11 06:42:23 2004 From: rjgruet at yahoo.com (Richard Gruet) Date: Sun, 11 Apr 2004 12:42:23 +0200 Subject: new-style class instance check References: Message-ID: "Mike C. Fletcher" wrote in message news:mailman.518.1081644036.20120.python-list at python.org... > I'm guessing what you're looking for is "everything that would have had > a type InstanceType in Python 2.1 and before", but I don't have time to > track down all the little corner cases for how to implement that, and > I'd guess you'll find that there's better ways to accomplish what you > want than using it anyway. Type-class unification has forever blurred > the line between class and type, and coding as if it hadn't is just > going to cause pain IMO. Right, you are perfectly right. As Robert (Brewer) guessed, I was actually naively trying to detect whether an object was an instance of a *user-defined* new-style class in an attempt to find and equivalent to type(o) is InstanceType for new-style classes - so my function could be more appropriately named e;G. isUserDefinedNewStyleClassInstance(o). Yes, Type-class unification has blurred the line between class and type (and moreover old style classes still exist and contribute to the mess, so that's now type-old class-new class unification that is needed ;-). That's just that although I thought I understood the general concept of class/type unification, I have not contemplated all its practical consequences. In *practice* (I mean my every day programmer's life) I am confused by things like considering a function as a (new-style) class, even if it makes perfect sense conceptually. I should stop trying to speak in terms of instances, classes, methods, functions like a die-hard and be more Zen, simply accept the new (Python) reality as it is. But the fact is, *I* am now more often puzzled with the new system than I was in the past, I spend more time wondering what things may mean. Even if my Python code doesn't seem to break most of the time (meaning that metaphysical questions don't concern most of coding), my brain has backwards compatibility problems with these subtle changes. I guess I'm like dinosaurs and doomed to disappear soon... A depressed Richard. From peter at engcorp.com Sat Apr 24 22:12:52 2004 From: peter at engcorp.com (Peter Hansen) Date: Sat, 24 Apr 2004 22:12:52 -0400 Subject: Richards bench benchmark In-Reply-To: <6748553f.0404241759.1f98a441@posting.google.com> References: <6748553f.0403291446.27fb7b93@posting.google.com> <6748553f.0403300836.744e3e22@posting.google.com> <6748553f.0403302317.4595844@posting.google.com> <6748553f.0404060802.6e0d708c@posting.google.com> <6748553f.0404211342.7591cd8e@posting.google.com> <40899240.7020508@engcorp.com> <6748553f.0404241759.1f98a441@posting.google.com> Message-ID: Duncan Lissett wrote: > Peter Hansen wrote in message news:<40899240.7020508 at engcorp.com>... > >>Okay, first working version is available by going to >>http://www.engcorp.com/main/projects/PyBench . >> >>That's about all the time I can spare on this for now. >>Feel free to download, hack, improve, or ignore. > > Excellent! > > I've added the Python implementation timings: > http://www.lissett.com/ben/bench1.htm > > I've no prior experience of Python to judge from, but for some reason > I expected it to be faster than the interpreted implementation of > Smalltalk designed for mobile devices. One key item would be to examine the function calls to append(). I'm guessing they are a substantial portion of the execution time. A little profiling is in order if anyone is interested in optimizing it. I made no effort to convert it to a Pythonic style. It's basically C code translated, with one small exception being the task list which is a simple Python list object instead of being a linked list. That means task lookups by id using findtcb() are quite fast, but the "work queues" used to hold the packets are actual singly-linked lists, implemented in Python, with a subroutine called append() used to scan the list and stick stuff on the end. This is absolutely, without question, not the way anyone would write this in Python if they were not just trying to maintain the original BCPL/C flavour intact. I'll make a prediction: with an hour or two of work, any good Python programmer can get a 10x speedup out of the program. I don't know how meaningful it will be as a benchmark at that point, but it is probably fair to compare with the object-oriented versions which already violate the original specification (e.g. the Java version, and the Smalltalk ones Duncan mentioned). If anyone wants to improve it, feel free. There are full unit tests and an acceptance test in bench_test.py, even covering the format of the output, so this could be a good chance for someone new to unit testing to get a feel for it by trying to modify them to drive the code in a new direction... -Peter From gnosticray at aol.com Thu Apr 15 08:26:20 2004 From: gnosticray at aol.com (A B Carter) Date: 15 Apr 2004 05:26:20 -0700 Subject: Difficulty Finding Python Developers References: <65cbc3dd.0404140641.3501fde8@posting.google.com> <65cbc3dd.0404141018.36d9d4ce@posting.google.com> Message-ID: pm_mon at yahoo.com (Paul Morrow) wrote in message news:<65cbc3dd.0404141018.36d9d4ce at posting.google.com>... > For those who've asked... > > This particular project is essentially a web-based registration > application. We'll probably want to use mod_python to serve the > pages, and Oracle for the database backend. It will have things like > a white-paper area that requires registration to access, an opt-in/out > email component, and the like. > > But we do want the developer to be physically here (in Atlanta). The fact is that if you go to a job site and key in Java, Perl and Python you are going to get something like a 50 to 10 to 1 ratio of responses. So you just may have a problem here :) First, here's what not to do. 1 - Don't blame mgt for being concerned, that's there job. 2 - Don't blame recruiters if they say they're having problems finding people with Python experience, it's probably because (just guessing here) that they're having problems finding people with Python experience. In general, don't pretend there isn't a problem and blame others for saying there is. Once you accept that, you are half-way home: 1 - Recognize that an extra effort will be required to find an experience Python programmer. So put a posting on monsters and other job sites (don't forget dice.com an excellent site for IT consultants). Also, educate the recruiters about Python, for instance make sure they understand the connection between Python and Zope. 2 - Start setting expectations with management. For example, explain that if there are not a lot of Python programmers it's because it's a new language that it builds on the strengths of langauges such as C++, Java and perl while avoiding their weaknesses. Mention that when you do find a Python programmer he'll probably be better than your average perl or Java programmer. Make the argument that you get what you pay for, and the extra expense of Python is worth it. 3 - With 2 out of the way consider rethinking how this three month project should be done. If Python talent is scarce then it might make more sense to develop in-house talent. This may no longer be a three month project but down the road your in a more solid position, which ,if you think about it, is a basic part of what Python is all about. 4 - If 3 above is accepted in some form then consider training someone in Python who has strong web skills. There are plenty of people who know Apache, perl and Oracle and who have done web development. From everything that I've seen and heard about Python, they could begin to become productive in a few weeks. From steveb428pleaseremovethis at hotmail.com Tue Apr 6 22:30:29 2004 From: steveb428pleaseremovethis at hotmail.com (DilbertFan) Date: Wed, 07 Apr 2004 02:30:29 GMT Subject: logging Message-ID: <9JJcc.47277$Bp7.10602@newssvr25.news.prodigy.com> I just discovered Python 2.3's logging and how it uses handlers. Absolutely fucking brilliant. From __peter__ at web.de Tue Apr 20 07:30:28 2004 From: __peter__ at web.de (Peter Otten) Date: Tue, 20 Apr 2004 13:30:28 +0200 Subject: Dollar sign ($) on foriegn keyboards? (prothon) References: Message-ID: Joe Mason wrote: > In article , Peter Otten wrote: >> Mark Hahn wrote: >> >>> We are considering switching to the dollar sign ($) for self, instead of >>> the >>> period ( . ) we are using now in Prothon. Ruby uses the at-sign (@) for > > > >> Apart from that obj$func() hurts my eye more than obj->func() and >> obj!func(). As always, Python shines here with its obj.func() :-) > > I believe the suggestion is "$.func()" instead of "self.func()" (the > Python way) or just ".func()" (the earlier Prothon way). Or possibly > the suggestion is for "$func()", although I like $.func() much better. I skimmed too lightly over the first paragraph and missed that - but still there is the obj$func() example in Mark's post, and with my Python mindset (I didn't follow the Prothon discussion closely) I cannot figure out what that is supposed to mean. > (I like this better than the ., though I still have no problem with > writing self all the time, so I prefer sticking to the Python way. It > solves my main problem with ., which is when you do have to pass self > explicitly. "function_call(param1, ., parm2)" is much more confusing > than "function_call(param1, $, param2)".) [OT] Seems to happen all the time with Python - try to simplify at some point and you pay twice elsewhere. Prothon will have a hard time occupying a local optimum in beauty/simplicity/usefulness that is both near and better than Python. This starts with the name, by the way - it evokes the association of prothotype, which looks quite, er, ungreek :-) Peter From secchi at sssup.it Wed Apr 14 12:50:15 2004 From: secchi at sssup.it (Angelo Secchi) Date: Wed, 14 Apr 2004 18:50:15 +0200 Subject: Help with dates Message-ID: <20040414185015.0d77bb6c.secchi@sssup.it> Hi, I have a dictionary, data, with the following structure: >>>data['III'] [['18-07-1994', '283.000000', '292.500000', '27712168.000000'] ['19-07-1994', '292.000000', '294.500000', '2492106.000000'] ['20-07-1994', '294.000000', '294.500000', '4881451.000000'] ['21-07-1994', '292.000000', '291.000000', '2183402.000000'] ['22-07-1994', '293.000000', '291.000000', '889050.000000'] ['25-07-1994', '293.000000', '292.000000', '657931.000000']] and I would like to create a "sort" of daily increments of, for example, the second column (ex. 292-283). I say "sort" since I do not need to consider week ends (i.e. I can consider them as one day) but I would also like to check if, in my database, there are big time jumps and possibly discard corresponding increments. Where should I look for hints in how to solve this task? Thanks a lot, angelo -- ======================================================== Angelo Secchi PGP Key ID:EA280337 ======================================================== Current Position: Graduate Fellow Scuola Superiore S.Anna Piazza Martiri della Liberta' 33, Pisa, 56127 Italy ph.: +39 050 883365 email: secchi at sssup.it www.sssup.it/~secchi/ ======================================================== From gianluca.trombetta at tin.it Thu Apr 1 15:37:37 2004 From: gianluca.trombetta at tin.it (Gianluca Trombetta) Date: Thu, 1 Apr 2004 22:37:37 +0200 Subject: ftpmirror.py in reverse? References: Message-ID: i don't understand if u would use a python program... However rsync is very nice and useful for site-mirroring... Hi "Harry George" ha scritto nel messaggio news:xqxwu4zk599.fsf at cola2.ca.boeing.com... > I maintain a website on a local machine, and want to maintain a clone > of it on a www-visible remote machine via ftp. I.e., local to remote. > > Going remote to local, ftpmirror.py would (I understand) do the job. > > Is there some tool available (or even a parameter for ftpmirror.py) > which can do local-->remote? > > > > -- > harry.g.george at boeing.com > 6-6M21 BCA CompArch Design Engineering > Phone: (425) 342-0007 > -- > http://mail.python.org/mailman/listinfo/python-list > From fumanchu at amor.org Fri Apr 9 14:30:26 2004 From: fumanchu at amor.org (Robert Brewer) Date: Fri, 9 Apr 2004 11:30:26 -0700 Subject: How to give a descriptor method access? Message-ID: Tom Loredo wrote: > I'd like to have objects with members that return values when accessed > by name, but the members must also have methods that can > manipulate the > values and store additional state. [Sorry, Tom, about getting cut off before--dang Outlook.] If the additional state applies to all instances of the class, a common approach is to return or modify the descriptor itself at the class level: def __get__(self, inst, owner): if inst is None: return self else: return getattr(inst, self.name) ...you can then add attributes to the descriptor. 'inst' will be None when the descriptor is called on the class instead of on an instance. > PS: In case being more concrete helps, an example would be that > Parameter stores the value of a float parameter in a model, so a.x > should return a float value (as quickly as possible---this will be > accessed a lot). But I'd like to set allowed ranges to such values, > define grids they'll be stepped on, store whether they can be > maximized > or integrated over in a calculation, etc.. So I want to be able to > call a.x.range(1,10) and have it store 1 and 10 as the range > for future > values of a.x, have a.x.vary() set a variable saying it can be varied > in a fit, etc., and do this having multiple Parameter instances > in a class, and multiple instances of that class. Descriptors IMO aren't really designed for that--they're more of a class-level concept. You can of course, store per-instance data within the descriptor: class Parameter(object): """Insert named descriptor into calling instance.""" def __init__(self, name): self.name = name + 'val' self.ranges = {} def __set__(self, inst, val): # print 'setting val' setattr(inst, self.name, val) self.ranges[inst] = (1, 10) ...but 1) that gets ugly quickly, and 2) the easiest way to beautify it is to put that "ranges" dictionary back into the owner class, and 3)..then why bother passing it through the descriptor? ;) I think the clean solution to your particular example would be to make x and y more robust classes, probably subclassed from the appropriate type: class Parameter(int): def __init__(self, value, range=(1,10)): int.__init__(self, value) self.range = range class test(object): x = Parameter(3) y = Parameter(6, (0, 25)) ...in which case (untested): >>> test.x 3 >>> test.x.range (1, 10) >>> test.y 6 >>> test.y.range (0, 25) ...something like that. :) Robert Brewer MIS Amor Ministries fumanchu at amor.org From drlinux at columbus.rr.com Sat Apr 17 12:14:33 2004 From: drlinux at columbus.rr.com (Dave Reed) Date: Sat, 17 Apr 2004 12:14:33 -0400 Subject: Kuhlman's tutorials pretty good In-Reply-To: References: <407E1E20.D0216E92@doe.carleton.ca> Message-ID: <200404171214.33753.drlinux@columbus.rr.com> On Friday 16 April 2004 14:55, Dave Kuhlman wrote: > gabor wrote: > > [snip] > > > > hmmm..could you also put on the web the latex sources? (or a > > ps/pdf version?)... > > > > or if it is already there, i can't find it :( > > The TeX/LaTeX sources for these tutorials and postscript (.ps) > and PDF files are in: > > http://www.rexx.com/~dkuhlman/python_x01_training.zip > > A few comments: > > I was able, just now, to generate ps and pdf files. Thanks for > asking this question. You motivated me to try to generate them. I > did not know that I could do that. > > The fonts in the ps files are not so good, and the fonts in the pdf > files are terrible. Maybe they will appear better on your system. > If you look at them, please let me know. I've always had luck with: dvips -Ppdf file.dvi -o ps2pdf file.ps I believe the -Ppdf embeds the fonts in the PostScript file and then ps2pdf uses those giving better results. Dave From gaz at effective-it.co.uk Wed Apr 28 13:26:47 2004 From: gaz at effective-it.co.uk (Gaz Oakley) Date: Wed, 28 Apr 2004 18:26:47 +0100 Subject: MySQL Connectivity Message-ID: Hi, I've looked through the mailing list archives trying to find the best ways of connecting to a MySQL database using Python. From what I've seen, people seem to be using http://sourceforge.net/projects/mysql-python/. First of all, is this the recommended method of connectivity? (I'm assuming it is). If it is, I've experienced a problem here. I'd ideally like to have Python 2.3 installed with MySQLdb. Following the instructions on http://sourceforge.net/forum/forum.php?thread_id=948054&forum_id=70461 I tried to build an RPM that would work with Python 2.3. It appears to be using rpm -ba to build. I can fix that, but it would indicate that the build script is somewhat out of date (rpmbuild has been around for a long time now). Are there any newer RPM's for this anywhere or any newer build scripts? Is the testing version relatively stable? (although I havent checked this is fixing the build problem yet) Thanks, Gareth Oakley From len-1 at telus.net Tue Apr 6 20:05:04 2004 From: len-1 at telus.net (Lenard Lindstrom) Date: Wed, 07 Apr 2004 00:05:04 GMT Subject: run-time construction of methods References: Message-ID: "Carlo v. Dango" writes: > Hello all. > > I am in the need of wrapping certain objects at run-time. My initial > approach was: > > import inspect, new > def make_wrapper(obj, methodName): > cls = obj.__class__ > wrapmth = getattr(obj, methodName) > print "************ ", methodName > def wrapper(self, *args, **kwargs): > print "**before ", methodName > return wrapmth(*args, **kwargs) > return wrapper > > class Person(object): > def __init__(self, age): > super(Person, self).__init__() > self.age = age > > def getAge(self): > return self.age > > def setAge(self, newage): > """sets the age of the person""" > self.age = newage > > p = Person(33) > setattr(p, "setAge", new.instancemethod(make_wrapper(p,"setAge"), p, > p.__class__)) > p.setAge(22) > print "age is ", p.getAge() > I like the approach of using a bound method to p to create a new instance specific method for p. >... > def make_wrapper(obj, methodName): > cls = obj.__class__ > wrapmth = getattr(obj, methodName) > print "************ ", methodName > wrapperstr = """def wrapper(self, *args, **kwargs): > print "**before ", methodName > return wrapmth(*args, **kwargs)""" > exec(wrapperstr, globals(), locals()) > return wrapper > > but I get the error > > NameError: global name 'methodName' is not defined > exec does not create a closure within the function calling it. That is its downside. So everything is either local to wrapmth, eg. parameters and variables created within the function, or global. Fortunately you can still create a closure with exec by declaring a function within a function. Here's my rewrite. I hope it works for you. def make_wrapper(obj, methodName): cls = obj.__class__ wrapmth = getattr(obj, methodName) print "********** ", methodName wrapperstr = """\ def _closure(_wrapmth): def wrapper(self, *args, **kwds): "I wrap method %(methodName)s" print "**before %(methodName)s" return _wrapmth(*args, **kwds) return wrapper _wrapper = _closure(wrapmth) """ % {'methodName': methodName} # Insert strings directly into code locs = {'wrapmth': wrapmth} # Keep namespace clean to avoid conflicts exec(wrapperstr, {}, locs) return locs['_wrapper'] # and here is the result See how the argument to _closure is the 'local' you want to keep around. Also I don't use globals() or locals() directly since they are cluttered. When you start trying to make the parameters of wrapper meaningful you will want to minimize the chance the parameter names conflict with other names within the scope of the exec. That is also why _closure and _wrapmth begin with underscores. You might want to choose even more cryptic names. Also, inlining strings such as methodName instead of passing them as variables into the exec scope reduces the chance of conflict. Lenard Lindstrom From hungjunglu at yahoo.com Fri Apr 30 04:01:32 2004 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 30 Apr 2004 01:01:32 -0700 Subject: Is classless worth consideration References: <69cbbef2.0404290259.fd8d71c@posting.google.com> <69cbbef2.0404291209.7a98a799@posting.google.com> Message-ID: <8ef9bea6.0404292307.66b78b83@posting.google.com> Peter Hansen wrote in message news:... > has wrote: > > Compared to C++, I expect it's a real breath of fresh air. But > > compared to how something like Self does OO, it is indeed hideously > > baroque. > > Oh, now you're qualifying the statement. In comparison to > something less baroque, it's baroque. Fair enough... Good that things cleared up. I have also pointed out previously that Python uses 5 devices where prototype-based needs only one: (a) class, (b) instance, (c) module, (d) metaclass, (e) scope. If this is not hideously baroque, then, Houston, we've got a problem. If you can really think outside the box, you'd pitch in also: (f) aspect. regards, Hung Jung From theller at python.net Tue Apr 27 15:06:05 2004 From: theller at python.net (Thomas Heller) Date: Tue, 27 Apr 2004 21:06:05 +0200 Subject: MS COM early and late binding References: <9e5ea2c4.0404271039.2da829b5@posting.google.com> Message-ID: <4qr5p7fm.fsf@python.net> OlafMeding at compuserve.com (Olaf Meding) writes: > Is there a way to find out if I am using early or late binding given > the reference ("excel" in the example below) returned by Dispatch()? > >>>> import win32com.client >>>> excel = win32com.client.Dispatch('Excel.Application') > try: excel.visible except AttributeError: print "late bound" else: print "early bound" Hint: Attributes are case sensitive when early bound ;-) Thomas From rick.ratzel at magma-da.com Tue Apr 27 00:41:27 2004 From: rick.ratzel at magma-da.com (Rick L. Ratzel) Date: Tue, 27 Apr 2004 04:41:27 GMT Subject: Embedding Python in C++ References: <71djc.147368$Kc3.4878757@twister2.libero.it> Message-ID: <408DE4F3.7080804@magma-da.com> Ciao, I have some examples from my PyCon presentation here: http://elmer.sourceforge.net/PyCon04/elmer_pycon04.html ...and here is the complete example code: http://elmer.sourceforge.net/PyCon04/Elmer_PyCon04.tgz I think the example code from example 1 may be most relevant. You can also use Elmer (http://elmer.sourceforge.net) to generate a C interface to your Python code (as shown in examples 2 & 3). Buona fortuna! Rick. Tonio wrote: > Hi > i'm a italian student. > I must create a virtual machine which call python script from Visual C++ > program. > My teacher tell me use swig fror make this work. > I use Swig for import in Python class, object, variables of C++, but my > problem are when in C++ i must call script Python. > I find many article, but i don't find a working example. > Can you advise me how i call python script from C++? > Have you example which can you send me (in my email)? > (my script use only int, float, string and object, class). > Thanks. > > From jacek.generowicz at cern.ch Mon Apr 26 11:00:13 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 26 Apr 2004 17:00:13 +0200 Subject: Magic methods in extension types References: Message-ID: Michael Hudson writes: > Jacek Generowicz writes: > > > Michael Hudson writes: > > > > > Not finding the tp_as_number->nb_inplace_add field? > > > > ( ... or tp_as_sequence ... ) > > > > I was afraid you (someone) was going to say that. > > Why? Because I'm too lazy to pollute my tiny extension type with a whole thingy_as_number sturucture for the sake of just one maginc method :-) > Well, the type of old-style classes has something in it's > tp_as_number->nb_inplace_add slot that looks in the class dictionary > for an __iadd__ method. > > If you'd made that a new-style class, you would be surprised! Don't follow ... you mean if I had done this: >>> class foo(object): ... def __iadd__(self,other): ... print "__iadd__ running" ... return self ... >>> f = foo() >>> f += 2 __iadd__ running ? > > Python manages to map "+=" to the method called "__iadd__" in > > user-defined classes, but not for extension types. What is the > > essential difference that makes that mapping work in one case but > > not in the other? > > Well, for old-style classes a whole bunch of code like: > > BINARY_INPLACE(instance_ior, "or", PyNumber_InPlaceOr) > BINARY_INPLACE(instance_ixor, "xor", PyNumber_InPlaceXor) > BINARY_INPLACE(instance_iand, "and", PyNumber_InPlaceAnd) > BINARY_INPLACE(instance_ilshift, "lshift", PyNumber_InPlaceLshift) > BINARY_INPLACE(instance_irshift, "rshift", PyNumber_InPlaceRshift) > BINARY_INPLACE(instance_iadd, "add", PyNumber_InPlaceAdd) > BINARY_INPLACE(instance_isub, "sub", PyNumber_InPlaceSubtract) > BINARY_INPLACE(instance_imul, "mul", PyNumber_InPlaceMultiply) > BINARY_INPLACE(instance_idiv, "div", PyNumber_InPlaceDivide) > BINARY_INPLACE(instance_imod, "mod", PyNumber_InPlaceRemainder) > BINARY_INPLACE(instance_ifloordiv, "floordiv", PyNumber_InPlaceFloorDivide) > BINARY_INPLACE(instance_itruediv, "truediv", PyNumber_InPlaceTrueDivide) > > and for new-style classes much hair in typeobject.c:type_new and > therein called functions. Extension types don't go through type_new > and are expected to go the other way round, in a sense: define > something in tp_as_number->nb_inplace_add and a wrapper called > __iadd__ will be created for you. Yuk. You are, in summary, saying that by _far_ the simplest way of adding __iadd__ to an extenion type is via tp_as_number->nb_inplace_add, aren't you. So be it. Thanks. From ramen at lackingtalent.com Sat Apr 17 22:03:07 2004 From: ramen at lackingtalent.com (Dave Benjamin) Date: Sun, 18 Apr 2004 02:03:07 -0000 Subject: Difficulty finding Python employer References: <407e9164$0$122$3a628fcd@reader3.nntp.hccnet.nl> Message-ID: In article <407e9164$0$122$3a628fcd at reader3.nntp.hccnet.nl>, Anton Vredegoor wrote: > Will send no resume. Can't stand hype. Must telecommute. That could explain your difficulty... From python at rcn.com Thu Apr 15 11:21:05 2004 From: python at rcn.com (Raymond Hettinger) Date: 15 Apr 2004 08:21:05 -0700 Subject: Automatic, portable optimization of global access Message-ID: <5d83790c.0404150721.46a3b5d0@posting.google.com> FWIW, I've posted a brief, but powerful recipe for a bytecode optimization that saves known globals as constants: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/277940 It's not psyco, but it does run everywhere and is easy to use. A key benefit is being able to localize variable access without adding clutter to your code like: _random=random; _len=len. One caveat is to run it in the builtin_only mode whenever some of the module globals are going to be updated at runtime. Raymond Hettinger From llothar at web.de Tue Apr 20 01:41:48 2004 From: llothar at web.de (Lothar Scholz) Date: 19 Apr 2004 22:41:48 -0700 Subject: CamelCase versus wide_names (Prothon) References: Message-ID: <6ee58e07.0404192141.2229efd6@posting.google.com> "Mark Hahn" wrote in message news:... > We have agreed in Prothon that unlike Python we are going to be 100% > consistant in our var and method naming. We will not have run-together > words like iteritems, we are going to always have seperated words like > has_key. > > Now we are in the midst of a discussion of camelCase versus wide_names. So > far our arguments are: > > 1) CamelCase is more elegant, modern, more readable, and more efficient in > character usage. > > 2) Wide_names is cleaner, more readable, compatible with C, which is the > standard module language for Python and Prothon. Wide_names is also the > Python standard. > > Of course in the Python world you alread have wide_names as your standard, > but could you for the moment pretend you were picking your standard from > scratch (as we are doing in the Prothon world) and give your vote for which > you'd prefer? After writing a few hundert thousands lines of code in Eiffel and a few ten thousands lines in Java i must say that lowercase wide_names are much much better to read. Someone else already mentioned this problem: smtp_message <-> SMTPMessage <-> SmtpMessage From mwh at python.net Thu Apr 22 06:17:20 2004 From: mwh at python.net (Michael Hudson) Date: Thu, 22 Apr 2004 10:17:20 GMT Subject: if (__name__ == '__main__'): main(sys.argv[1:]) References: <01c601c4271b$7f7300a0$b401010a@sparta> <4085A445.1050303@heneryd.com> Message-ID: Fran?ois Pinard writes: > A word about the `__metaclass__' line. My intent is to forget all about > classic classes and go with the new type system as quickly as possible. > I do not want to derive each and every of my classes from `object', > and later edit all those `(object)' out when the classic classes will > effectively get deprecated. Why would you do that? Even if you don't inherit from object explicitly (eg. what you do) object is still a base class. I don't like using a __metaclass__ global because it's a non-local effect. Cheers, mwh -- I never disputed the Perl hacking skill of the Slashdot creators. My objections are to the editors' taste, the site's ugly visual design, and the Slashdot community's raging stupidity. -- http://www.cs.washington.edu/homes/klee/misc/slashdot.html#faq From try_vanevery_at_mycompanyname at yahoo.com Mon Apr 26 00:35:43 2004 From: try_vanevery_at_mycompanyname at yahoo.com (Brandon J. Van Every) Date: Sun, 25 Apr 2004 21:35:43 -0700 Subject: Maya API with Python? Message-ID: Anybody tried that? Progress or horror stories to tell? -- Cheers, www.indiegamedesign.com Brandon Van Every Seattle, WA "Troll" - (n.) Anything you don't like. Usage: "He's just a troll." From newsgroups at jhrothjr.com Wed Apr 14 20:06:27 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Wed, 14 Apr 2004 20:06:27 -0400 Subject: Difficulty Finding Python Developers References: <65cbc3dd.0404140641.3501fde8@posting.google.com> Message-ID: <107rkii2un8o1b0@news.supernews.com> "Paul Morrow" wrote in message news:65cbc3dd.0404140641.3501fde8 at posting.google.com... > We've worked hard to convince our company to migrate our core > applications to Python, and now we're looking for a Python developer > in Atlanta to handle a short-term (approx. 3 month) project. But our > initial searches have been fairly unsuccessful. We haven't actually > posted a job on Monster, but we have been talking with various > headhunters in our area and they don't have many resumes that show > Python experience. An so now, of course, mgt is wondering whether > selecting Python was a mistake. > > As anyone had a similar experience? Suggestions? Besides Monster, different areas have other job boards that are pretty good. This one seems to be better in this area: at least it has the number of jobs I'd expect, and more than in some other areas: http://www.atlanta.computerjobs.com/ John Roth > > Thanks. From jcarlson at uci.edu Thu Apr 1 14:39:53 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Thu, 01 Apr 2004 11:39:53 -0800 Subject: From python-dev, space vs. tab controversy finally settled In-Reply-To: References: Message-ID: > Yeah, thanks Josiah. Well all know how bright you are already though, > and it's customary (though an unspoken custom, perhaps, until now) to > chuckle quietly at such things and wait a while before posting, just to > give an opportunity for the unwary ones to get sucked in for a while. Yeah, I suppose I should try not to ruin the joke quite so soon next time. > Anyway, you forgot to point out that the *real* conclusion from the > python-dev discussions was that Guido has finally decided that the > space vs. tab wars will _never_ be won, and chooses explicit over > implicit yet again. The indentation style for Python 3.0 (not 2.4) > will be leading periods, since they make the indentation more obvious > and thus avoid mistakes. Now that is funny. If you want to see another good Python joke, I like this one: Python for Commodore 64. http://zephyrfalcon.org/weblog/arch_d7_2004_03_27.html#e536 Not terribly believable, but still good. - Josiah From remi at cherrypy.org Tue Apr 27 13:23:43 2004 From: remi at cherrypy.org (Remi Delon) Date: 27 Apr 2004 10:23:43 -0700 Subject: [ANN] CherryPy-0.10 released Message-ID: <585c0de9.0404270923.165cbc67@posting.google.com> Hello everyone, I am pleased to announce the release of CherryPy-10. It's been a while since I last announced a CherryPy release on this newsgroup but a lot has happened since then: - The cherrypy.org site now has a nice forum and a wiki - Sessions are now fully thread-safe and they work great in production environments with the thread-pool HTTP-server - Jython compatibility has been restored - Lots of new HowTos have been added to the documentation, including one HowTo about best practices for deploying a demanding production website. - Plus many bugfixes and improvements ... ------------------------------------------ About CherryPy: CherryPy is a Python based web development toolkit. It provides all the features of an enterprise-class application server while remaining light, fast and easy to learn. CherryPy allows developers to build web applications in much the same way they would build any other object-oriented Python program. This usually results in smaller source code developed in less time. Remi. http://www.cherrypy.org From aahz at pythoncraft.com Mon Apr 5 00:43:50 2004 From: aahz at pythoncraft.com (Aahz) Date: 5 Apr 2004 00:43:50 -0400 Subject: Difference between default arguments and keyword arguments References: <10713rf4bjl1bab@news.supernews.com> Message-ID: In article , Edward Diener wrote: > >Along the same lines, I would like to add to that the explanation for >classes in the tutorial is very poor since it assumes a much higher >understanding of Python than a tutorial should about the language. A >much simpler and more direct explanation regarding classes in Python >would be much better. While I mostly got it because I have programmed >extensively in other OOP languages, I would expect your average Python >beginner to be completely lost by much of the high-level explanation in >that chapter. Whoever wrote it was much more interested in explaining >the theory of classes in Python, to beginners no less !, than they were >toward explaining what classes are in Python and how to use them. And >why iterators and generators are included in that chapter are beyond >me. Also the tutorial mentions some usages of classes, in previous >sections, before the explanation of classes occur, which I feel is >definitely a mistake. While I agree that the tutorial could stand improvement, it *is* targetted more at experienced programmers. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "usenet imitates usenet" --Darkhawk From nick at no.spam.org Tue Apr 20 06:37:23 2004 From: nick at no.spam.org (Nick Efford) Date: Tue, 20 Apr 2004 11:37:23 +0100 Subject: block ciphers References: <7L_gc.53134$Gn6.49963@newssvr25.news.prodigy.com> <7x3c6zqvdy.fsf@ruckus.brouhaha.com> Message-ID: On Tue, 20 Apr 2004 02:41:58 +0000, Trevor Perrin wrote: > Me neither, exactly... ;-) I'm just trying to gauge the interest or > resistance to this, and see if there's any way I could help. I would definitely like to see better crypto in the standard library. N. From imbosol at aerojockey.invalid Fri Apr 16 00:04:13 2004 From: imbosol at aerojockey.invalid (Carl Banks) Date: Fri, 16 Apr 2004 04:04:13 GMT Subject: CamelCase versus wide_names (Prothon) References: Message-ID: <1XIfc.246$GN6.122@fe2.columbus.rr.com> Mark Hahn wrote: > > > We have agreed in Prothon that unlike Python we are going to be 100% > consistant in our var and method naming. We will not have run-together > words like iteritems, we are going to always have seperated words like > has_key. > > Now we are in the midst of a discussion of camelCase versus wide_names. So > far our arguments are: > > 1) CamelCase is more elegant, modern, more readable, and more efficient in > character usage. > > 2) Wide_names is cleaner, more readable, compatible with C, which is the > standard module language for Python and Prothon. Wide_names is also the > Python standard. > > Of course in the Python world you alread have wide_names as your standard, > but could you for the moment pretend you were picking your standard from > scratch (as we are doing in the Prothon world) and give your vote for which > you'd prefer? Ok, get ready for this one. When I'm naming classes, instances, functions, methods, and other complex (not complex number) objects, I tend to use wide names. When I'm naming numbers, strings, or collections thereof, I choose camel case before wide naming. Why? Well, I use wide for most objects because I think it's a bit more readable in general, being closer to what we're used to reading. (I guess that might not be the case for Arabic people.) But, when you are doing all kinds of math calculations with numbers, or operating on strings, or whatnot, the underscores make it harder to read, because it takes effort to sort out whether something's an operator or an underscore. In other words, I typically use wide names because they're very readable and nice looking in ordinary code like this: func_status = blast_furnace.ignite_furnace() but avoid the wide names when they're uber-ugly and unreadable in operator-laden code like this: pitch_rate_coefficient = pitch_rate*mean_aerodynamic_chord/total_airspeed It would not surprise me if the people who prefer wide names tend to be applications-type programmers, whereas those who prefer camel case naming tend to be numerical-type programmers. -- CARL BANKS http://www.aerojockey.com/software "If you believe in yourself, drink your school, stay on drugs, and don't do milk, you can get work." -- Parody of Mr. T from a Robert Smigel Cartoon From danb_83 at yahoo.com Sat Apr 17 23:27:19 2004 From: danb_83 at yahoo.com (Dan Bishop) Date: 17 Apr 2004 20:27:19 -0700 Subject: CamelCase versus wide_names (Prothon) References: Message-ID: Dave Benjamin wrote in message news:... > In article , Paramjit Oberoi wrote: > > * the real problem is the absence of a character for > > indicating non-breaking spaces---that's why we have > > to use all these damn_WorkArounds. > > That's so funny; I was just thinking the same thing myself. After all these > years, they couldn't just make it easier to press? That's the only problem > here, IMHO; I *much* prefer reading lowercase_with_underscores. I never > noticed how much until I read this thread, because I have a slight hangover > and all these capWordsAreLiterallyGivingMeAHeadache. ;) ButKeepInMindThatManyIdentifierNamesHaveOnlyOneWord (InWhichCaseTheWordSeparationStyleDoesntMatter), AndMostOrOnlyTwoOrThreeWords, SoCodeWontBeAsHardToReadAsThis. > Out of curiosity, do most of us prefer CamelCaps for class names, regardless > of our opinions on variables, functions, methods, etc.? I do. > I almost never see > class names defined in lowercase unless they're built-in or user-defined > types meant to look like they're built-in. I'd prefer it if built-in types were uppercase too, so I wouldn't have to remember not to use "list" and "file" as variable names. Unforunately, that would break a lot of code. From michaelmossey at yahoo.com Thu Apr 8 18:15:05 2004 From: michaelmossey at yahoo.com (Michael Mossey) Date: 8 Apr 2004 15:15:05 -0700 Subject: Intermittant slow startup References: <9badaf0.0404051033.9fec2db@posting.google.com> <4071A86D.97CA6CAE@alcyone.com> <9badaf0.0404051445.5b26b945@posting.google.com> <9badaf0.0404071113.6cdcee6b@posting.google.com> Message-ID: <9badaf0.0404081415.4d59d088@posting.google.com> Andrew MacIntyre wrote in message news:... > On Thu, 7 Apr 2004, Michael Mossey wrote: > > > I double-checked that and asked the sysadmin to check if the python > > build was using any network source. I do have AFS and NFS drives > > mounted on this machine, but I'm not reading any python code from them > > as nearly as I can tell. PYTHONPATH points only to local disk. > > All I can think of is to try using "python -v" and see where in the > startup process the delay appears to be occurring. If the same module is > involved in every stumble, then at least you have a module to investigate. python -v reveals that the hang is coming before it prints anything. So what is python doing then? Or is the OS having a problem in loading the python executable and getting it going? This doesn't seem to happen with other utilities installed in /usr/local/bin. -Mike From balaji at email.arizona.edu Fri Apr 9 01:15:59 2004 From: balaji at email.arizona.edu (Balaji) Date: 8 Apr 2004 22:15:59 -0700 Subject: Problem!! Message-ID: <494182a9.0404082115.3c828371@posting.google.com> Hello everybody.. I have a problem!!! suppose i want to define c1=x(i)+y(i)<=b for i in s1 ------------ suppose it is the first constraint.. c2=x(i)+y(i)<=b for i in s2------------- suppose it is the second constraint.. now as i is indexed over s1 so is c1.. but what it does is it overites the first constraint.. I guess there should be some problem with the iterators... any help in this regard is apreciated.. Thanx Balaji From loic at fejoz.net Fri Apr 30 10:11:47 2004 From: loic at fejoz.net (Yermat) Date: Fri, 30 Apr 2004 16:11:47 +0200 Subject: [Classless] Just to be sure... Message-ID: Hi all, I just want to be sure that I have really understand what classless means... Can you look at the following "test" function and tell me if this is what you would have called classless programmation ? thanks ! -- Yermat import types PropertyType = type(property()) class Prototype(object): parent = None def __init__(self, parent=None): self.parent = parent def clone(self): return Prototype(self) def __hasattr__(self, name): if name in self.__dict__: return True elif self.parent!= None: return self.parent.__hasattr__(self, name) else: return False def __getattribute__(self, name): if name in ['__dict__', 'parent']: return object.__getattribute__(self, name) if name in self.__dict__: val = self.__dict__[name] elif self.parent != None: val = getattr(self.parent, name) else: val = object.__getattribute__(self, name) if type(val) in [types.FunctionType, types.GeneratorType, types.UnboundMethodType, types.BuiltinFunctionType]: return val.__get__(self, self.__class__) if type(val) == PropertyType: return val.fget(self) return val def __setattr__(self, name, value): if type(value) == types.MethodType: value = value.im_func self.__dict__[name] = value def __add__(self, other): return self.__add__(other) def test(): import random def show(self): print '(%s, %s)' % (self.x, self.y) def addPoint(self, other): r = self.clone() r.x = self.x + other.x r.y = self.y + other.y return r point = Prototype() point.show = show point.__add__ = addPoint a1 = point.clone() a1.x = 3 a1.y = 5 a2 = point.clone() a2.x = 7 a2.y = 9 print 'a1: ', a1.show() print 'a2: ', a2.show() def getX(self): return random.randint(0, 10) print 'a3:' a3 = a2.clone() a3.x = property(getX) print a3.x a3.show() a3.show() a3.show() a2.y = 10 print 'a3: ', a3.show() p = a3.__add__(a2) print 'p = a3 + a2: ', p.show() print 'a3 + a2: ', (a3 + a2).show() def squareDistance(self): return (self.x ** 2) + (self.y ** 2) point.squareDistance = squareDistance a4 = a1.clone() print 'a4: ', a4.show() print a4.squareDistance() def pointTuple(self): return (self.x, self.y) a5 = a3.clone() a5.tuple = pointTuple print 'a5: ', a5.tuple() a5.x = 10 print 'a5: ', a5.tuple() print 'a3: ', a3.show() if __name__=='__main__': test() From colarte at telesat.com.co Thu Apr 1 10:33:04 2004 From: colarte at telesat.com.co (Camilo Olarte) Date: Thu, 1 Apr 2004 10:33:04 -0500 Subject: ANNOUNCE: 'goto' for Python Message-ID: <1080833584.406c3630a523d@ilpostino3.telesat.com.co> >> Entrian Solutions is pleased to announce version 1.0 of the 'goto' >> module. >> >> This adds the 'goto' and 'comefrom' keywords to Python 2.3, adding >> flexibility to Python's control flow mechanisms and allowing Python >> programmers to use many common control flow idioms that were previously >> denied to them. >>>>>> What is the day today ? Oh yes the first of April ! <<<<<< OOUCH ! I Almost believe it! :) Camilo Olarte Telesat, m?s f?cil...m?s Internet. http://www.telesat.com.co/ From pythongnome at hotmail.com Tue Apr 20 17:15:13 2004 From: pythongnome at hotmail.com (Lucas Raab) Date: Tue, 20 Apr 2004 21:15:13 GMT Subject: Thanks, and a URL correction References: Message-ID: "Noah from IT Goes Click" wrote in message news:PKahc.189360$oR5.3955 at pd7tw3no... > Thanks Lucas > > the correct URL is (you got a . instead of a / after com) > http://www.pythonware.com/library/tkinter/introduction/ > > and the PDF link so those who care don't have to dig > http://www.pythonware.com/library/tkinter/an-introduction-to-tkinter.pdf Thanks for catching that, otherwise I wouldn't have noticed. From mab at iee Tue Apr 6 05:29:05 2004 From: mab at iee (Marco Bartel) Date: Tue, 06 Apr 2004 11:29:05 +0200 Subject: Python and USB In-Reply-To: <5ns8k1-3q4.ln1@home.rogerbinns.com> References: <407162b0$1@news.vo.lu> <5ns8k1-3q4.ln1@home.rogerbinns.com> Message-ID: <40727912$1@news.vo.lu> Roger Binns wrote: >>I just >>was thinking about to do the wrapper myself using SWIG, but i also still >>hope, that there is someone outside, who played allready with usb and >>python arround. > > > Here is one I made earlier: > > http://cvs.sf.net/viewcvs.py/bitpim/bitpim/native/usb/ > > It is shipping as part of BitPim and works with libusb on Linux and Mac > and libusb-win32 on Windows. > > If someone wants to make this into a proper distutils style package > etc, I'd be more than happy to contribute the code etc. > > Roger > > Thanks a lot roger, it was exactly the thing i'am was looking for. Now i only have to get my device running. Under C i was allready using the libusb, and so this code should be easily to be adapted. THX Marco From edreamleo at charter.net Mon Apr 12 20:59:25 2004 From: edreamleo at charter.net (Edward K. Ream) Date: Mon, 12 Apr 2004 19:59:25 -0500 Subject: accept xml instead of plain Python text? References: <107jc0h6r5c3g3d@corp.supernews.com> <107jenfmso3tce7@news.supernews.com> Message-ID: <107merg7rqhrm71@corp.supernews.com> > You should be able to convert an XML format of your > design to an AST and compile it to bytecodes; likewise > you should be able to generate an XML file from the AST. Thanks, John. This is a valuable suggestion because it points in a direction that doesn't require the assent (or participation) of the wider Python community. As I just said in my reply to Martin, I am pretty dubious about the whole idea. I suspect though, that if the idea ever goes anywhere something like what you suggest will be the way to go. I'll keep this suggestion in the back of my mind... Thanks again. Edward -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: Literate Editor with Outlines Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From mcfletch at rogers.com Wed Apr 21 16:23:44 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Wed, 21 Apr 2004 16:23:44 -0400 Subject: Python editors for Windows question In-Reply-To: References: Message-ID: <4086D850.5040004@rogers.com> PythonWin (part of the pywin32/win32all package) has limited autocomplete. Basically it will auto-complete for modules which are loaded, so if you import cgi in the interactive session then you will have autocompletion for cgi. If the module is not loaded, then PythonWin uses a simpler algorithm that searches through the current file looking for x.y notations where x matches your currently-begun x. PythonWin also has very nice ctrl+space identifier completion which searches back/forward from where you're typing, so you can type longer identifiers with just a few keystrokes. Would be nice to have that same set of mechanisms in all Python editors. I believe Boa has auto-completion in much the same way. Not sure about the other win32 editors. I think the Activestate IDEs may have auto-completion, but again, not sure. Good luck and welcome, Mike Dustin wrote: >Hello, > >I just started programming in Python last night, and I've really enjoyed my >experience so far. I would like to know if there is a Windows editor that >recognizes Python and will support a module syntax/definition lists For >instance, let's say that I set form = cgi and then when I hit the period >(".") on the keyboard, a list of objects shows up, such as FieldStorage(), >etc.. Any suggestions are appreciated. Thank you! > >Dustin > > _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From heikowu at ceosg.de Thu Apr 22 03:59:15 2004 From: heikowu at ceosg.de (Heiko Wundram) Date: Thu, 22 Apr 2004 09:59:15 +0200 Subject: Python use large scale projects In-Reply-To: <47fc6058.0404212327.24163290@posting.google.com> References: <47fc6058.0404212327.24163290@posting.google.com> Message-ID: <200404220959.15702.heikowu@ceosg.de> Am Donnerstag 22 April 2004 09:27 schrieb limor: > I think the python being typless makes the > code hard to maintain. Python isn't typeless. Little example: >>> a = "3" >>> b = "5" >>> a*b Traceback (most recent call last): File "", line 1, in ? TypeError: can't multiply sequence to non-int It's not typeless (as e.g. you'd consider Perl to be), but variables aren't declared by type (they are all just references to objects, in the above example references to two string objects, and not declared at all...). Heiko. From jcarlson at uci.edu Mon Apr 12 15:12:33 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Mon, 12 Apr 2004 12:12:33 -0700 Subject: Parsing string array for differences In-Reply-To: <7598e160.0404120856.217bc8d5@posting.google.com> References: <7598e160.0404120856.217bc8d5@posting.google.com> Message-ID: > My below code doesn't do what I need it to do. What I want is to > capture the differences between two arrays of data into a new list. > So if list A has {Fred, Bob, Jim} and List B has {Jim, George, Fred} I > want to capture in list C just {Fred, Jim} According to your example just given, you don't want the difference, you want the similarity. a = {} a.fromkeys(listA) listC_similarity = [i for i in listB if i in a] Using a dictionary for the lookup makes it faster than searching another list. - Josiah From stevenbee at removethis.att.net Tue Apr 27 19:39:32 2004 From: stevenbee at removethis.att.net (Steven Brent) Date: Tue, 27 Apr 2004 19:39:32 -0400 Subject: Backticks: What up? Message-ID: I was wondering why the backticks in the following fragment: return 'Here's the result: ' + `self.data` My guess is that in a return statement (as opposed to a print statement) it's necessary to do this in order to get the self.data instance attribute as a string, so it can be concatenated with the 'Here's the result: ' string. What exactly do the backticks do, then? Just return the result of an expression as a string? Does my guess make sense and / or is it correct? Elucidations and gentle ridicule welcome. TIA. From dwb2 at speakeasy.net Mon Apr 5 13:13:54 2004 From: dwb2 at speakeasy.net (Derek Chen-Becker) Date: Mon, 05 Apr 2004 11:13:54 -0600 Subject: Profiling iterators? Message-ID: <19idnQuS8dNODuzdRVn-hw@speakeasy.net> Hi, I'm using Python 2.2 and a library that makes heavy use of iterators. I'm in the process of cleaning up/optimizing some of the code and I tried profiling it, but the profiler seems to completely ignore iterator calls, and even routines called by the iterator calls. Have I done something wrong, or is this a limitation of the profiler? Thanks, Derek From P at draigBrady.com Mon Apr 26 13:18:56 2004 From: P at draigBrady.com (P at draigBrady.com) Date: Mon, 26 Apr 2004 18:18:56 +0100 Subject: how to add new print %b format to python? In-Reply-To: References: Message-ID: <408D4480.8090104@draigBrady.com> Rusty Shackleford wrote: > I have a Summer in front of me without any school, and I'd like to add a > new format for python print strings that will show any number in a > binary representation. For example: > > >>>>'%b' % 3 > > 11 > >>>>'%b' % 5 > > 101 > > You get the idea. I've written functions that return strings, so that > part is done, but where do I go to tinker with the python interpreter to > add this new format? > > Please don't argue with me about whether this is an advisable goal in > itself -- I'm using it as a method to learn about the internals of the > python language. I don't think this will be accepted as the format args are really a lowest common denominator across all systems. For e.g. on linux you can use the ' modifier to print numbers in locale format (and example for mine is 1,234). Also %b is already used by userspace utils in linux, from the docs: In addition to the standard printf(1) formats, %b causes printf to expand backslash escape sequences in the corresponding argument, and %q causes printf to output the corresponding argument in a format that can be reused as shell input. Anyway it's easy to get a binary representation and I can't remember the last time I needed one? Something like this should work: binary = lambda n: n>0 and binary(n>>1)+[str(n&1)] or [] ''.join(map(binary(4096)) P?draig. From mgibson at tripwire.com Wed Apr 21 13:19:25 2004 From: mgibson at tripwire.com (uebertester) Date: 21 Apr 2004 10:19:25 -0700 Subject: md5.hexdigest() converting unicode string to ascii References: <77b925de.0404161337.3917ef56@posting.google.com> <77b925de.0404201516.7941cd83@posting.google.com> Message-ID: <77b925de.0404210919.76fc0aa3@posting.google.com> Heather Coppersmith wrote in message news:... > On 20 Apr 2004 16:16:33 -0700, > mgibson at tripwire.com (uebertester) wrote: > > > I've attempted the suggested solution specifying different > > encodings, however, the hash value that is returned does not > > match what I expect based upon another utility I'm checking > > against. Hash value returned by python specifying utf16 > > encoding: 731f46dd88cb3a67a4ee1392aa84c6f4 . Hash value > > returned by other utility: 0b0ebc769e2b89cf61a10a72d5a11dda . > > Note: I've tried other encoding also. As the utility I'm > > verifying against is extensively used, I'm assuming it is > > returning the correct value. I appreciate any help in resolving > > this as I'm trying to enhance an automated test suite written in > > python. > > Other things that may bite or may have bitten you: > > o the byte order marker or lack thereof > o different newline conventions > o trailing newlines or lack thereof > o don't forget that there are two utf16 encodings, big endian > and little endian > > Adding to what Peter indicated, the source (code and/or persons) > of your extensively used utility may also contain specific test > vectors. > > Regards, > Heather Your first bullet is the problem. _winreg.QueryValueEx(y,"") returns a unicode string with the BOM "fffe". The utility I'm comparing against removes this prior to hashing the registry value. Thanks for all the input I received from everyone. Mark From FBatista at uniFON.com.ar Tue Apr 27 16:44:09 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Tue, 27 Apr 2004 17:44:09 -0300 Subject: Tkinter vs. wxPython? Message-ID: [Alan Gauld] #- And there is no doubt that wxPython looks more natural, on #- windows at least, although the differences aren't enough to make #- me switch. BUt my needs are, as I said, very simple. Well, I love the way GTK looks. But for windows, PyGTK is pretty difficult to install and make it work. So, wxPython has the appeal that can run native over Windows and over GTK in linux. . Facundo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA La informaci?n contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener informaci?n confidencial o propietaria, cuya divulgaci?n es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no est? autorizado a divulgar, copiar, distribuir o retener informaci?n (o parte de ella) contenida en este mensaje. Por favor notif?quenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magn?tico) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telef?nica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electr?nicos pueden ser alterados, motivo por el cual Telef?nica Comunicaciones Personales S.A. no aceptar? ninguna obligaci?n cualquiera sea el resultante de este mensaje. Muchas Gracias. -------------- next part -------------- An HTML attachment was scrubbed... URL: From claird at lairds.com Tue Apr 27 14:15:27 2004 From: claird at lairds.com (Cameron Laird) Date: Tue, 27 Apr 2004 18:15:27 -0000 Subject: And *this* is why you need Perl!? (was: Is Perl *that* good?) References: <87fzaqmm8t.fsf@strauser.com> <38ec68a6.0404262308.50029919@posting.google.com> Message-ID: <108t8pvam9q139c@corp.supernews.com> In article , Skip Montanaro wrote: . . . >differences. In addition, as Jamie Zawinski suggests, regular expressions >are not always the best choice. > >Skip > "suggests"? I thought he was "chanting", or "intoning", or "inveighing" or "denouncing" or ... Well, I'll say it on my own behalf: friends, REs are not always the best choice . -- Cameron Laird Business: http://www.Phaseit.net From fumanchu at amor.org Tue Apr 13 02:20:37 2004 From: fumanchu at amor.org (Robert Brewer) Date: Mon, 12 Apr 2004 23:20:37 -0700 Subject: FutureWarning question Message-ID: Mike wrote: > I ran across the message below in 2.3.2 today. These are the > lines of code: > > 402: if m1_hi >> 15 & 0x0001 == 1: > 403: m1_hi = m1_hi | 0xFFFF0000 > 404: if m1_lo >> 15 & 0x0001 == 1: > 405: m1_lo = m1_lo | 0xFFFF0000 > > This is the warning message: > > pwg.py:403: FutureWarning: hex/oct constants > sys.maxint > will return > positive values in Python 2.4 and up > m1_hi = m1_hi | 0xFFFF0000 > pwg.py:405: FutureWarning: hex/oct constants > sys.maxint > will return > positive values in Python 2.4 and up > m1_lo = m1_lo | 0xFFFF0000 > > m1_hi and m1_lo are 32 bit values read from a file. It's not > clear to me > what the warning message means. The only constant is > 0xffff0000; does the > message mean that the result of the OR operation won't be > what I think it > is? Can anyone elucidate? Try typing at an interactive prompt: >>> 0xffff0000 :1: FutureWarning: hex/oct constants > sys.maxint will return positive values in Python 2.4 and up :1: FutureWarning: hex/oct constants > sys.maxint will return positive values in Python 2.4 and up :1: FutureWarning: hex/oct constants > sys.maxint will return positive values in Python 2.4 and up -65536 ...as you can see, Python 2.3.2 interprets 0xffff0000 as a negative int. The warning is saying that in Python 2.4 and following, such a hex value will be positive (e.g. 4294901760L), rather than negative (-65536). Robert Brewer MIS Amor Ministries fumanchu at amor.org From jepler at unpythonic.net Thu Apr 22 13:51:23 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Thu, 22 Apr 2004 12:51:23 -0500 Subject: Main-process doesn't wait for child-processes In-Reply-To: References: Message-ID: <20040422175123.GC17776@unpythonic.net> Keep track of the processes you create, then wait for them each to exit. Untested code: def do(task): pass processes = [] try: for task in tasks: pid = os.fork() if pid == 0: do(task) os._exit(0) else: processes.append(pid) finally: while processes: pid = waitpid(0,0) # Wait for any child, block # print "reaped", pid processes.remove(pid) Instead of looping until 'processes' is empty, you could wait until waitpid raises os.error with errno==ECHILD ("No child processes"). Jeff From cookedm+news at physics.mcmaster.ca Fri Apr 23 17:10:59 2004 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Fri, 23 Apr 2004 17:10:59 -0400 Subject: Easiest way to *add a column* to a 2d matrix/array in numarray??? References: Message-ID: <87oepifli4.fsf@arbutus.physics.mcmaster.ca> At some point, seberino at spawar.navy.mil (Christian Seberino) wrote: > Thanks for the reply. I appreciate all the help I can get. Your suggestion > of using resize is excellent for adding *rows* but does not seem > right for *columns*. If rows works, you could do transpose/resize/transpose. -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From joe at notcharles.ca Wed Apr 21 20:15:26 2004 From: joe at notcharles.ca (Joe Mason) Date: Thu, 22 Apr 2004 00:15:26 GMT Subject: Generator inside a class prevent __del__ ?? References: <4085BA96.651D2E4A@free.fr> <40866ECD.A45758B9@free.fr> Message-ID: In article <40866ECD.A45758B9 at free.fr>, Emmanuel wrote: > Thank you very much for your answer, but I'm still not sure I understand it. > If I understand your words right, creating self.Coroutine as an iterator on > the generator function will create a reference on self, so if I want to use a > generator in a class ( and I really want to ), I must delete explicitly the > iterator before I destroy the object. > > Trouble is, I _would_ like not to care about the lifetime of the object, and I > don't know where it will be destroyed. Try looking up "weakref". (I've never used them myself, so I don't know the exact syntax.) Joe From peter at engcorp.com Thu Apr 1 09:32:56 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 01 Apr 2004 09:32:56 -0500 Subject: From python-dev, space vs. tab controversy finally settled In-Reply-To: References: Message-ID: Josiah Carlson wrote: > Carl Banks wrote: > [snip] > Great april fools joke, but no such conversation has gone on in > Python-Dev in the last 3 months. > > Better luck next time. > > - Josiah Yeah, thanks Josiah. Well all know how bright you are already though, and it's customary (though an unspoken custom, perhaps, until now) to chuckle quietly at such things and wait a while before posting, just to give an opportunity for the unwary ones to get sucked in for a while. Anyway, you forgot to point out that the *real* conclusion from the python-dev discussions was that Guido has finally decided that the space vs. tab wars will _never_ be won, and chooses explicit over implicit yet again. The indentation style for Python 3.0 (not 2.4) will be leading periods, since they make the indentation more obvious and thus avoid mistakes. -Peter From peholmst at abo.fi Wed Apr 21 05:34:35 2004 From: peholmst at abo.fi (=?ISO-8859-1?Q?Petter_Holmstr=F6m?=) Date: Wed, 21 Apr 2004 12:34:35 +0300 Subject: File access and threads In-Reply-To: References: <4084b3eb@newsflash.abo.fi> Message-ID: <40864030$1@newsflash.abo.fi> Aahz wrote: > > Could you at least post a full traceback? Is this enough? === TRACEBACK BEGINS === Mod_python error: "PythonHandler mod_python.psp" Traceback (most recent call last): File "/usr/local/lib/python2.3/site-packages/mod_python/apache.py", line 287, in HandlerDispatch log=debug) File "/usr/local/lib/python2.3/site-packages/mod_python/apache.py", line 457, in import_module module = imp.load_module(mname, f, p, d) File "/usr/local/lib/python2.3/site-packages/mod_python/psp.py", line 34, in ? tempdir = tempfile.gettempdir() File "/usr/local/lib/python2.3/tempfile.py", line 242, in gettempdir tempdir = _get_default_tempdir() File "/usr/local/lib/python2.3/tempfile.py", line 188, in _get_default_tempdir raise IOError, (_errno.ENOENT, IOError: [Errno 2] No usable temporary directory found in ['/tmp', '/var/tmp', '/usr/tmp', '/'] === TRACEBACK ENDS === -Petter- From peter at engcorp.com Fri Apr 2 16:40:21 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 02 Apr 2004 16:40:21 -0500 Subject: GUI Frameworks in Python? In-Reply-To: <45228044.0404021040.3860a027@posting.google.com> References: <45228044.0404021040.3860a027@posting.google.com> Message-ID: <406DDDC5.1060102@engcorp.com> Chris Perkins wrote: > Peter Hansen wrote in message news:... > > >>Running that repeatedly (sorry, can't reboot conveniently >>right now, so can't get the first time) it takes 0.125 s >>on my machine. > > Nobody seems to have mentioned wxPython version numbers in this > discussion. > > I just upgraded from 2.4.2.4 to 2.5.1.5, and the start-up time for the > demo app went from about 5 seconds to less than a second. I've been running 2.4.1.2 on Python 2.3.3... If I had the same absolute speedup going to 2.5.1.5 it would be running before I managed to click on its icon! ;-) -Peter From eeide at cs.utah.edu Mon Apr 26 11:32:45 2004 From: eeide at cs.utah.edu (Eric Eide) Date: Mon, 26 Apr 2004 09:32:45 -0600 (MDT) Subject: AOP use cases References: <84fc4588.0404140106.3fa0c55@posting.google.com> <0pydnSB4WYuieuLdRVn-hQ@powergate.ca> Message-ID: "Will" == Will Stuyvesant writes: Will> One of my original points was that Java needs "AOP" to solve Will> problems imposed by the static typing system. The links you Will> provide are Java-centric. A better designed programming Will> language, like the dynamicall typed language Python, does not Will> need "AOP". It is up to the software designer to make good Will> designs, orthogonal where needed, with separation of concerns, Will> etc. I think that we disagree about the nature of AOP. Perhaps I should review your previous posts to see why you think AOP is primarily about working around "problems imposed by the static typing system." I don't agree with this claim. To me --- and I think the AOSD literature and community supports this view --- AOP is about structure and problem decomposition, just like OOP is about these things. AOP is not primarily about working around technical problems in a base language, Java or otherwise. Not all AOP research is done in Java, or even in statically typed languages. See, for instance, a recent paper about implementing an AOP system in Scheme: http://www.cs.brown.edu/~sk/Publications/Papers/Published/tk-ptcts-adv-ho-lang/ You claim that Python doesn't need AOP because it is "a better designed programming language." If you believe that, what about OOP? Do you think that Python needs OOP? If so, why? I don't mean to start a holy war, but consider that Scheme does quite well without inherent OOP. Should we consider Python's support for OOP evidence that Python is defective in some way with respect to Scheme, and that Scheme is therefore "a better designed programming language" because it "needs" neither AOP nor OOP? Thank you for explaining your point of view! 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 junkmail at solumslekt.org Fri Apr 2 11:43:52 2004 From: junkmail at solumslekt.org (Leif B. Kristensen) Date: Fri, 02 Apr 2004 18:43:52 +0200 Subject: emergent/swarm/evolutionary systems etc References: Message-ID: <4Jgbc.4588$zf6.61662@news4.e.nsc.no> Peter MacKenzie wrote: > Oh the joy! It makes life worth living when things click into place > and make sense. I know the feeling. For me too, the best way to learn a new language is to wallow in working examples. I still remember the thrill of hacking my way through Tom Swan's "Mastering Turbo Pascal" in the late eighties, where he presented every wrinkle of the language, and every single library function with both a working example program and a lucid discussion. I've never learnt any other computer language so thoroughly. regards, -- Leif Biberg Kristensen http://solumslekt.org/ Validare necesse est From j.dot.willeke at verizon.dot.net Wed Apr 7 22:21:06 2004 From: j.dot.willeke at verizon.dot.net (Jon Willeke) Date: Thu, 08 Apr 2004 02:21:06 GMT Subject: print u"\u0432": why is this so hard? UnciodeEncodeError In-Reply-To: References: Message-ID: Nelson Minar wrote: > I have a simple goal. I want the following Python program to work: > print u"\u0432" > > This program fails on my US Debian machine: > UnicodeEncodeError: 'ascii' codec can't encode character u'\u0432' in position 0: ordinal not in range(128) Try playing with sys.setdefaultencoding(). You'll need to reload( sys ) to call it. If it solves your problem, you can make it permanent by modifying site.py. From hjwidmaier at web.de Thu Apr 8 06:50:56 2004 From: hjwidmaier at web.de (Hans-Joachim Widmaier) Date: Thu, 08 Apr 2004 12:50:56 +0200 Subject: gettext and the interpreter References: Message-ID: Am Sat, 03 Apr 2004 23:22:47 +0200 schrieb Peter Otten: > Try redefining sys.displayhook, e. g.: Thanks a lot! This is the stuff I keep having problems with finding in the docs. [Sorry for answering late, but Google gave me only empty pages, and I'm just now able to do it properly.] Hans-Joachim From fredrik at pythonware.com Fri Apr 16 07:36:48 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 16 Apr 2004 13:36:48 +0200 Subject: Difficulty Finding Python Developers References: <65cbc3dd.0404140641.3501fde8@posting.google.com><5d83790c.0404150701.605782a7@posting.google.com><7xpta8hqe7.fsf@ruckus.brouhaha.com><7xsmf4kbac.fsf@ruckus.brouhaha.com><7x7jwg7ipn.fsf@ruckus.brouhaha.com> Message-ID: Peter Hanse wrote. > > They're not, but the discussion was serious production projects. > > I thought the discussion was a 3-month project. To me, that's > definitely not something I would classify as a "serious production > project". I know, I know, the length alone shouldn't be enough > to call it serious or production or not. It's just not the term > I would apply to something that short. "Experiment", maybe, or > "quickie", or "co-op student project" or something... hmm. have I been posting to the wrong newsgroup? From lbates at swamisoft.com Tue Apr 13 10:00:18 2004 From: lbates at swamisoft.com (Larry Bates) Date: Tue, 13 Apr 2004 09:00:18 -0500 Subject: mcmillan installer References: Message-ID: You might also want to take a look at py2exe. It seems to be under active development and Thomas Heller (author) monitors this list frequently. http://starship.python.net/crew/theller/py2exe/ Larry Bates Syscon, Inc. "Gianluca Trombetta" wrote in message news:mailman.575.1081855698.20120.python-list at python.org... > Hi all, > > I'm searching a tool that compile python script to an executable binary. > I found the mcmillan installer but i can't find a valid url to download it. > > Do someone know a valid url to download it or know another similar tool? > > Thanks. > Gianluca > > > > From wallacethinmintr at eircom.net Wed Apr 7 10:05:29 2004 From: wallacethinmintr at eircom.net (Russell Wallace) Date: Wed, 07 Apr 2004 14:05:29 GMT Subject: Are line continuations needed? Message-ID: <407409ef.82801353@news.eircom.net> Hi all, Python lets you continue a single logical line across more than one physical line, either by putting a \ at the end or letting it happen automatically with an incomplete infix operator. I'm wondering how often is this feature needed? Would there be any problems if it weren't part of the language? -- "Sore wa himitsu desu." To reply by email, remove the small snack from address. http://www.esatclear.ie/~rwallace From mwh at python.net Thu Apr 8 08:08:46 2004 From: mwh at python.net (Michael Hudson) Date: Thu, 8 Apr 2004 12:08:46 GMT Subject: Intermittant slow startup References: <9badaf0.0404051033.9fec2db@posting.google.com> <4071A86D.97CA6CAE@alcyone.com> <9badaf0.0404051445.5b26b945@posting.google.com> Message-ID: michaelmossey at yahoo.com (Michael Mossey) writes: > Erik Max Francis wrote in message news:<4071A86D.97CA6CAE at alcyone.com>... > > Michael Mossey wrote: > > > > > Runnng python 2.2 on HP-UX, I get intermittant slow startup. > > > Sometimes python starts up in a small fraction of a second, and > > > sometimes takes 3-5 seconds. This applies to any script I run, or > > > just typing 'python' at the prompt. > > > > > > I also observed something similar on Linux. > > > > > > Any ideas what would cause *intermittant* slow startup? > > > > Caching? Is it a long time between invocations that it takes a long > > time to start up? > > It is quite intermittant without much of a pattern I can see. One > thing that is definitely true is that if I start up python several > times in a row one right after the other, some can be slow and some > fast. I just observed it start fast twice, then start slow. I don't > remember if it ever does the other way around but I think it does. Does HP-UX have a version of strace/truss/ktrace? Cheers, mwh -- In general, I'd recommend injecting LSD directly into your temples, Syd-Barret-style, before mucking with Motif's resource framework. The former has far lower odds of leading directly to terminal insanity. -- Dan Martinez From boudot-kim at wanadoo.fr Mon Apr 26 11:07:41 2004 From: boudot-kim at wanadoo.fr (Seo-Kyeong KIM-BOUDOT) Date: Mon, 26 Apr 2004 17:07:41 +0200 Subject: Paris python user group? References: <408795ee$0$25893$79c14f64@nan-newsreader-02.noos.net> Message-ID: moi je serais tres heureux qu'on fasse ca a la campagne :) on peut organiser un week end python au soleil eheh fb "Michel Claveau/Hamster" a ?crit dans le message news: c6d4pt$pca$1 at news-reader2.wanadoo.fr... > Bonsoir ! > > L'id?e est int?ressante. Je serait assez tent?, s'il n'y avait pas cette > s?gr?gation pro-parisienne. > C'est vrai, quoi ! Pourquoi vous limiter ? Paris ? Il y a des coins > nettement moins pollu?s que Paris, et donc plus productif (pythoniquement > parlant). > > Vive l'Ard?che ! > > > @+ > -- > Michel Claveau > > > > > From fgeiger at datec.at Wed Apr 28 01:24:15 2004 From: fgeiger at datec.at (F. GEIGER) Date: Wed, 28 Apr 2004 07:24:15 +0200 Subject: Debugging a python module as a form's action handler References: Message-ID: Wing IDE can do that (did it many times when I dev'ed a Webware app of mine). Cheers Franz "Edward Diener" schrieb im Newsbeitrag news:IWCjc.5098$g31.2262 at newsread2.news.atl.earthlink.net... > I am using Python in a CGI web application and need to be able to debug a > Python module as a form handler. Is there a way to do this so that I can > step through my module while it is handling the form's data ? > > I couldn't find much information at all in either IDLE or PythonWin about > using the IDE's for debugging, so I thought I would ask here. > > From gabor at z10n.net Fri Apr 16 04:33:54 2004 From: gabor at z10n.net (gabor) Date: Fri, 16 Apr 2004 10:33:54 +0200 Subject: Kuhlman's tutorials pretty good In-Reply-To: References: <407E1E20.D0216E92@doe.carleton.ca> <200404150710.i3F7A0Hw010978@locutus.doe.carleton.ca> <407E40CC.C06FA9E3@doe.carleton.ca> Message-ID: <1082104434.13313.17.camel@dubb> On Thu, 2004-04-15 at 21:12, Dave Kuhlman wrote: > Fred Ma wrote: > > [snip] > > >> However, in looking over 201, I see some scrambling of source > >> code examples, vs. surrounding text, e.g. when he's getting into > >> regular expressions, some of the examples have nothing to do with > >> the explanations that follow. > >> Notably sections 2.2, 2.3, 2.4, 2.5. 2.6 is mostly OK except: > >> > >> """ > >> Put together a new string with string concatenation from pieces > >> of the original string and replacement values. You can use string > >> slices to get the sub-strings of the original string. In our > >> case, the following gets the start of the string, adds the first > >> replacement, adds the middle of the original string, adds the > >> second replacement, and finally, adds the last part of the > >> original string: > >> > >> lineDef = delimitedList(fieldDef) > >> """ > > > > Yes, they seem rearranged. I'm not sure what Dr. Kuhlman's time > > is like, but his tutorials are very good, and thus of great value > > to > > Python newbies everywhere. ;) > > Whoa! How did all that happen? I believe I tried one too many > fancy things in TeX/LaTeX, which is definitely not my native > language. hmmm..could you also put on the web the latex sources? (or a ps/pdf version?)... or if it is already there, i can't find it :( gabor From peter at engcorp.com Wed Apr 28 09:07:20 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 28 Apr 2004 09:07:20 -0400 Subject: Backticks: What up? In-Reply-To: References: Message-ID: Steven Brent wrote: > I was wondering why the backticks in the following fragment: > > return 'Here's the result: ' + `self.data` > > My guess is that in a return statement (as opposed to a print statement) > it's necessary to do this in order to get the self.data instance attribute > as a string, so it can be concatenated with the 'Here's the result: ' > string. > > What exactly do the backticks do, then? Just return the result of an > expression as a string? Does my guess make sense and / or is it correct? > Elucidations and gentle ridicule welcome. I was looking for the proper language ref but sometimes they can be hard to track down: http://docs.python.org/ref/string-conversions.html -Peter From nuffsaid at phreaker.net Thu Apr 29 18:01:52 2004 From: nuffsaid at phreaker.net (Nuff Said) Date: Fri, 30 Apr 2004 00:01:52 +0200 Subject: Newbe-books References: Message-ID: Since you have some programming background, I would recommend David M. Beazley's "Python - Essential Reference (2nd edition)". It gives a concise overview of the language and is a great reference book, too. (Not like many other books which are - at most - good for one reading only.) The 'Essential Reference (2nd edition)" covers Python 2.1. So you should read A. M. Kuchling's "What's new in Python 2.x" for Python 2.2 and 2.3 (which one should always do when a new Python version is released). The articles can be found on the Python Homepage: http://www.python.org/doc/2.2.3/whatsnew/whatsnew22.html http://www.python.org/doc/2.3.3/whatsnew/whatsnew23.html The above mentioned book, the "What's new ...' articles and the Python 'Library Reference' http://www.python.org/doc/2.3.3/lib/lib.html are all you really need for a long time. (If you are interested in GUI programming - e.g. Tkinter - you will need additional sources of information. The same holds for other 'special' stuff.) HTH, Nuff. From michael at foord.net Sat Apr 10 06:04:16 2004 From: michael at foord.net (Fuzzyman) Date: 10 Apr 2004 03:04:16 -0700 Subject: Wrapper round x86 Assembler References: <8089854e.0404082353.7bf163a2@posting.google.com> <4dKdnQlIXMIXIevdRVn-gg@powergate.ca> Message-ID: <8089854e.0404100204.504186a0@posting.google.com> Peter Hansen wrote in message news:<4dKdnQlIXMIXIevdRVn-gg at powergate.ca>... > Fuzzyman wrote: > > > There might be a really good reason why this hasn't been done *or* > > someone might have done it and I just can't find it..... *but* > > > > what about a wrapper to an assembler (presumably for x86 assembly !) > > !! > > I just wrote some code doing binary operations which would have been > > about a zillion times faster in a few lines of assembly code. > > I refer you to "Pyrex"... > > -Peter If I understand correctly (which is probably not likely) - Pyrex is a compiled language with some C syntax and some Python syntax. Because the result is compiled, and a step in the compile chain is assembly, you could include inline assembly in the same way that you could with C ?? Never having done any C programming that stretches the limit of my knowledge. *However* it's not quite what I had in mind. What I'd like to be able to do is to access machine code subroutines from within normal python. Not that exploring pyrex is a bad idea - I probably should. I don't think my 'idea' would be hard to achieve, since effectively all that would be needed is a wrapper to an existing freeware assembler *and* an interface to the assembled 'objects'. Ho hum - a bit beyond me at the moment and until I have a real burning need for it will have to remain an idea...... Regards, Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html From NAICTN_DOMAIN_1CTN-OFFICESRV at ctn.co.uk Tue Apr 20 09:58:17 2004 From: NAICTN_DOMAIN_1CTN-OFFICESRV at ctn.co.uk (GroupShield for Exchange (CTN-OFFICESRV)) Date: Tue, 20 Apr 2004 14:58:17 +0100 Subject: ALERT - GroupShield ticket number OA3207_1082469496_CTN-OFFICESR V_1 was generated Message-ID: Action Taken: The attachment was deleted from the message and replaced with a text file informing the recipient of the action taken. To: triciaf at ctn.co.uk From: python-list at python.org Sent: -2027746304,29632223 Subject: approved document_all Attachment Details:- Attachment Name: document.zip File: document.zip Infected? Yes Repaired? No Blocked? No Deleted? Yes Virus Name: W32/Netsky.p at MM!zip -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/ms-tnef Size: 1992 bytes Desc: not available URL: From arch at spyre.net Thu Apr 22 18:15:54 2004 From: arch at spyre.net (A. Y. Chen) Date: 22 Apr 2004 15:15:54 -0700 Subject: from vh3 import virthost / AddVirtDomain / Ensim / Apache References: Message-ID: <2a9bf4b4.0404221415.4313d267@posting.google.com> Hi, I'm trying to do the same thing and getting the exact same problem as you. Have you had any luck? Part of the difficulty is that the files virthost.py and virtutil.py are probably compiles (in .pyc form), and not located in those directories shown in the trace. However, I still get the same error after I chmod those files. "Dan Messenger" wrote in message news:... > Hi, > > I'm new to python, and am trying to use some premade scripts on RedHat 7, > but its giving me errors. > > The scripts are part of the Ensim hosting software, and when I run the > command "AddVirtDomain" from a root shell, it works fine. > > However when I call it from my php page, and thus running under the apache > user, I get the following error: > > Traceback (most recent call last): > File "/usr/local/bin/AddVirtDomain", line 26, in ? > from vh3 import virthost > File "virtualhosting/virthost.py", line 46, in ? > File > "/home/build/qa/webppliance/3.1.11/2/lwp/vaishali2/WebGui/base/services/vh3/ > virtualhosting/virtutil.py", line 14, in ? > ImportError: No module named logging > > The first file mentioned is the one I am running, and 2nd two dont even > exist - tho the script runs fine under a root shell. > > To me this indicates a permissions problem - but permissions to what? The > files mentioned dont exist ! > > Anybody got any ideas ? > Thanks in advance > -Dan From eastier at free.fr Thu Apr 22 05:26:11 2004 From: eastier at free.fr (Emmanuel) Date: Thu, 22 Apr 2004 11:26:11 +0200 Subject: Generator inside a class prevent __del__ ?? References: <4085BA96.651D2E4A@free.fr> <40866ECD.A45758B9@free.fr> Message-ID: <40878FB3.FE0507D2@free.fr> Terry Reedy a ?crit : > "Emmanuel" wrote in message > news:40866ECD.A45758B9 at free.fr... > > > > > > Terry Reedy a ?crit : > > > > >>> class toto: > > > > def __init__(self): > > > > print "init" > > > > self.Coroutine = self.Gen() > > > > > > This creates a reference loop. Delete this (and correct typo below) > and > > > 'problem' will disappear. > > To amplify: the usual idiom for an instance-associated generator is to name > the generator function (method) __iter__ (with one param, self) and to > create and get a reference to the generator via iter() or let the for loop > mechanism do so for you. > > c = C(*args) > cgen =iter(c) > > Then there is no reference loop. And you can pass around the cgen object > just like any other. If you only need the instance after initialization to > get the generator and you only need one generator for the instance, then > combine the two lines into > > cgen = iter(C(*args)) > > and the *only* reference to the instance is the one in the generator, which > will disappear at the end of a for loop or with an explicit 'del cgen'. But I obviously need other references to my object in my code, my object isn't modified by the generator only. I want to resume my generator from time to time during the execution of my app, and to modify the members of the objects somewhere else ( interaction between my objects ). Doing this result in my nicer programmation style than without generators. > > > There is also the question whether you actually *need* to get rid of the > object while the program is still running instead of just letting the > program finish and clean up. > I have a _lot_ of objects created whenever they want, and I don't know where they will finish their job. Additionnaly, I'm not developping only on PC, but also on platforms where there is not so much memory avalaible. By the way, it seems I still have a lot to understand on this subject. Do you know any link, example, or whatever, that I could have a look at ? Thank you very much for your answers, Emmanuel From danb_83 at yahoo.com Wed Apr 7 10:16:35 2004 From: danb_83 at yahoo.com (Dan Bishop) Date: 7 Apr 2004 07:16:35 -0700 Subject: min() with custom compare. References: <20040407114407.0a07d143@pistache.sara.nl> Message-ID: Heather Coppersmith wrote in message news:... > On Wed, 7 Apr 2004 11:44:07 +0200, > Bram Stolk wrote: > > [ example of sort with custom compare function snipped ] > > > What if I need only a max, or min value, and not a complete > > sort, but I do want to have a custom compare func. What could I > > do? ... > > def absolulte_minimum_function( x, y ): > x, y = abs( x ), abs( y ) > if x < y: > return x > else: > return y > > minimum = reduce( absolute_minimum_function, l ) > > There's probably some (awfully horrible) lambda-embeddable > equivalent to absolute_minimum_function, but I'm not about to try > to figure it out right now, and even if I did, I'd probably end up > not using it anyway. minimum = reduce(lambda x, y: min(abs(x), abs(y)), l) From pinard at iro.umontreal.ca Fri Apr 23 15:22:01 2004 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Fri, 23 Apr 2004 15:22:01 -0400 Subject: if (__name__ == '__main__'): main(sys.argv[1:]) In-Reply-To: References: <01c601c4271b$7f7300a0$b401010a@sparta> <4085A445.1050303@heneryd.com> <20040423155026.GB5587@alcyon.progiciels-bpi.ca> Message-ID: <20040423192201.GA7974@alcyon.progiciels-bpi.ca> (Note: this is about having a line `__metaclass__ = type' near the beginning of a Python program.) [Michael Hudson] > I like my code to do things similar to what it looks like it's doing. > To me, > class MyClass: > ... > says "classic class". I understand your concern. But since I do not want classic classes anymore in my code, I prefer to read all classes as new style, as blindly as possible. If I ever wanted to specify a class as old-style (but I never had the need so far), I would write: from types import ClassType class MyOldClass: __metaclass__ = ClassType ... Why would you want to specifically use classic classes in these days? -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From noemail at noemail4u.com Thu Apr 8 07:47:33 2004 From: noemail at noemail4u.com (Dang Griffith) Date: Thu, 08 Apr 2004 11:47:33 GMT Subject: CGI Problems With Xitami References: <8089854e.0404072356.7f33f440@posting.google.com> Message-ID: On 8 Apr 2004 00:56:59 -0700, michael at foord.net (Fuzzyman) wrote: >All of a sudden the 'POST' method has stopped working - when I specify >'POST' as the method in forms... the CGI gets no data... and I really >don't want to use 'GET' as it makes the password visible in the URL... > >I've looked in the CGI options of the Xitami config and I can't find >anything amiss, or even especially relevant. The Xitami docs say >'POST' should work fine (of course they don't mention python). > >Anyone any suggestions or experience. >(Yes I've checked the form construction in the hTML templates - it's >fine. The values don't even make it to Fieldstorage...) Try capturing the generated HTML source and run it through TidyHTML. http://tidy.sourceforge.net/ http://www.w3.org/People/Raggett/tidy/ It could be something in that page is causing the browser not to post the data. --dang From therve at neocles.com Thu Apr 29 09:58:38 2004 From: therve at neocles.com (=?ISO-8859-1?Q?Thomas_Herv=E9?=) Date: Thu, 29 Apr 2004 15:58:38 +0200 Subject: Problem with socket In-Reply-To: <408ffd56$0$17252$a1866201@newsreader.visi.com> References: <408f7917$0$27016$626a14ce@news.free.fr> <408ffd56$0$17252$a1866201@newsreader.visi.com> Message-ID: <40910985$0$22886$626a14ce@news.free.fr> Grant Edwards wrote: > On 2004-04-28, Thomas Herv? wrote: > > >>Ok I hope it's clear. My problem is that "select" only tests >>if there's data on the socket, and not the state of the >>socket. > > That's not true. If the socket is closed, it will return from > select as readable. Exact. >>I want to be able to know if socket is "alive" or something >>like that. But I don't want to make "send" in the client (stay >>passive). Then, if I know that my socket is closed or my link >>down, I can try to reconnect periodically. > > You'll know if the socket is closed because select will mark it > as readable, and you'll get 0 bytes when you read it. It seems that it's not true : when I read it I have a "Connection reset by peer" error. > If you want to know if the network or the other host has "gone > away", set the SO_KEEPALIVE option on the socket. That will > generate an error if the link is down. IIRC, it takes 75 > minutes (or is it 150?) to time out after the other end goes > away. Yes, I've seen this option, but the delay is a bit too large (2 hours ? depending on OS it seems) and not configurable. So I made it by send some hearbeat regulary, even if I didn't want to I haven't found another way. And it's better for server side, from which I can make some recv that make the break found earlier. -- Thomas Herve From imbosol at aerojockey.com Fri Apr 16 16:02:57 2004 From: imbosol at aerojockey.com (Carl Banks) Date: 16 Apr 2004 13:02:57 -0700 Subject: CamelCase versus wide_names (Prothon) References: <1XIfc.246$GN6.122@fe2.columbus.rr.com> Message-ID: <60dfb6f6.0404161202.14748d0a@posting.google.com> Joe Mason wrote in message news:... > In article <1XIfc.246$GN6.122 at fe2.columbus.rr.com>, Carl Banks wrote: > > but avoid the wide names when they're uber-ugly and unreadable in > > operator-laden code like this: > > > > pitch_rate_coefficient = pitch_rate*mean_aerodynamic_chord/total_airspeed > > Spaces are a much better way to fix this than camelCase. > > pitch_rate_coefficient = pitch_rate * mean_aerodynamic_chord / > total_airspeed Well, when you get into more complicated examples, with lots of operators and parentheses, the spaces don't help much either. Also, I like to use spaces to give a visual clue about nesting level, so I don't used them in the most nested operations. But if it makes you feel better, I don't actually use camel case there, either. I just string the words together with no underscores and all lower case. The OP had ruled that one out, though. > > It would not surprise me if the people who prefer wide names tend to > > be applications-type programmers, whereas those who prefer camel case > > naming tend to be numerical-type programmers. > > I'm somewhat surprised numerical-type programmers don't just use > ubershort variable names. Using _ for subscript: > > P_r_c = P_r * ADC_m / A_t > > (I'm not advocating this style, but seems like direct translations from > math or engineering algorithms would encourage it.) I do advocate retaining the nomenclature of the domain you're programming in, as long as the names are of local variables or structure attributes. However, the OP's question was about neither local variables nor domain-specific naming, so I didn't bother with this possibility. -- CARL BANKS From jonas at jonasgalvez.com Wed Apr 21 14:26:11 2004 From: jonas at jonasgalvez.com (Jonas Galvez) Date: Wed, 21 Apr 2004 15:26:11 -0300 Subject: Stupid Regex Question References: Message-ID: > [Robert Brewer] > I do it by hand, too. But cf. > http://article.gmane.org/gmane.comp.python.general/339488, the post > to which I originally replied. ;) Actually, I do that *only* to my own posts, and here's the reason: > [Me] > I wrote this And I'm writing this too. Me A little weird, don't you think? Hehe :-D Cheers, =- Jonas Galvez jonasgalvez.com/blog macromedia.com/go/team From mogmios at mlug.missouri.edu Wed Apr 28 00:34:02 2004 From: mogmios at mlug.missouri.edu (Michael) Date: Tue, 27 Apr 2004 21:34:02 -0700 Subject: Is Perl *that* good? In-Reply-To: References: Message-ID: <408F343A.1060609@mlug.missouri.edu> >I wish Python had won, as well. But time is linear (in my mind). I now >wish only that we could leverage the similarity of JS and Python >(execution and binding models) into more Python users. Marketing needs >to run with the line, "So you know Javascript? Then you know Python!" > I wish Python could be ran inside a browser as a client-side scripting language. I've seen it done but it'd be awesome to seen done properly and intergrated into something like Mozilla. From tzot at sil-tec.gr Mon Apr 5 06:11:38 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Mon, 05 Apr 2004 13:11:38 +0300 Subject: Using ST_ATIME to watch for files being read References: <939f49f8.0404020739.70a7750a@posting.google.com> Message-ID: On 2 Apr 2004 07:39:38 -0800, rumours say that iamlevis3 at hotmail.com (Chris) might have written: Hi Chris, >I need to monitor a bunch of files to see what is being opened, read, >and closed, with no modifications being made. This is being done >first on Windows machines, and later on Solaris. ># from the i.shell. st_atime date is inside >>><<< >>>> os.stat("c:\\devtemp\\python\\1.txt") >(33206, 0L, 2, 1, 0, 0, 3L, >>>1080919329<<<, 1080919329, 1080918583) ># now i open c:\devtemp\python\1.txt, close it, and rerun How exactly do you open the file? Through python or through an external program (eg notepad)? If only through python, do you read any data? I believe you have to read data for the access time to be updated. >>>> os.stat("c:\\devtemp\\python\\1.txt") >(33206, 0L, 2, 1, 0, 0, 3L, >>>1080919329<<<, 1080919329, 1080918583) > >The Win32 books states that stat.ST_ATIME is "the time the file was >last accessed or zero if the filesystem doesn't support this >information". Obviously I'm missing something, or maybe atime isn't >the best thing for me to use in this situation. Hoping someone can >provide guidance. Windows has a weird behaviour even with st_mtime... I have a directory structure in a USB disk, which, taking advantage of NTFS capability for hard links, I present under two different views for the users of my network. To avoid re-reading the contents of all files, I keep a cache of (relative-filename, size, modification time); by comparing the cache to the actual directory structure, every time I change a couple of files, I read only the changed ones to decide where in the linked structures I will present them. I have found (through trial and error) that the modification time does not show up immediately, esp. if the file is modified in the linked directory structures... I tried even using a sync.exe from sysinternals, but that doesn't change a lot. So, after a change, I wait a couple of minutes and then I run the python script that relinks the files. Everything works this way. -- TZOTZIOY, I speak England very best, Ils sont fous ces Redmontains! --Harddix From carl at l5web.net Fri Apr 2 21:02:54 2004 From: carl at l5web.net (Carl L) Date: 2 Apr 2004 18:02:54 -0800 Subject: Installing Python 2.3.3 on RH 7.3 References: <106e6nge2aiiqa9@corp.supernews.com> Message-ID: <5fb57772.0404021802.a3e0e75@posting.google.com> "Rien Kok" wrote in message news:<106e6nge2aiiqa9 at corp.supernews.com>... > Hi, > > I have a strange problem. I want to install Plone > (Plone2-2.0.0rh-2.i386.rpm) Because Plone 2.0 needs Python 2.3.3, I > installed Python 2.3.3 from source (Python-2.3.3.tar). > > Everything went well. After installing Python I did a reboot of the server > and checked if Python works. > > Quote: > [root at homeserver root]# python > Python 2.3.3 (#1, Mar 28 2004, 11:29:35) > [GCC 2.96 20000731 (Red Hat Linux 7.3 2.96-113)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> > > > So I suppose I installed the right version of Python. But when I tried to > install Plone2-2.0.0rh-2.i386.rpm it gives the following error: > > Quote: > [root at homeserver Zope-Plone]# rpm -Uvh Plone2-2.0.0rh-2.i386.rpm > error: failed dependencies: > /usr/bin/python2.3 is needed by Plone2-2.0.0rh-2 > expat >= 1.95.5 is needed by Plone2-2.0.0rh-2 > libc.so.6(GLIBC_2.3) is needed by Plone2-2.0.0rh-2 > python2.3 >= 2.3.3 is needed by Plone2-2.0.0rh-2 > > > When I installed Python from source, Python was installed in > "/usr/local/bin/" in stead of "/usr/bin/" so I copied "Python2.3" from > "/usr/local/bin/" to "/usr/bin/" but that doesn't help. > > What can I do to change (or extend) the path so Plone can find the right > version of Python. > > Thanks, > > Rien Rien, I have the same problem with install Plone 2 on Redhat 9.0. Did you find an answer to the problem? Carl From daniel at dreamflavor.com Sun Apr 25 13:48:36 2004 From: daniel at dreamflavor.com (Daniel) Date: 25 Apr 2004 10:48:36 -0700 Subject: my first program- List Box help? Message-ID: I am new to python and am trying to make a front end for an emulator. I am using python, livewires and pygame. I am able to do everything I want except createa list box. I have a background image with 5 other images on top of it. I have an xml file with a list of 10,000 games. I want to import that list into a scrollable text box. I want to use the arrow keys to scroll it. As the names scroll in the text box I want the images to change also. So if you are on PAC-MAN in the text box you will see 5 images named folder1/PAC-MAN.png folder2/PAC-MAN.png and so on. If you hit down it would go to the next game in the list and images the images would update to show the new game. If you hit enter it would start emulator.bat PAC-MAN.zip. Also it needs to be full screen. So I think all I need to learn how to do is draw a text box that imports a xml file and with every click of an arrow key it updates a variable. I also do not know how to start the bat file. But I think I might be able to figure out on my own. From jdhunter at ace.bsd.uchicago.edu Fri Apr 30 07:43:57 2004 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Fri, 30 Apr 2004 06:43:57 -0500 Subject: operator double() surprise in cxx In-Reply-To: =?iso-8859-1?q?(Beno=EEt?= Dejean's message of "Fri, 30 Apr 2004 07:54:47 +0200") References: Message-ID: >>>>> "Beno?t" == Beno?t Dejean writes: >> double l( Py::Float(rect[0]) ); double b( Py::Float(rect[1]) ); Beno?t> everything that looks/tastes/sounds like a function Beno?t> declaration is (even with parameters. Interesting. So you are saying I can do double l(1); because this could not be a function declaration so the double constructor is called with an integer argument, but in double l( Py::Float(rect[0]) ); the compiler thinks I am declaring a function l that takes Py::Float* as an argument and returns a double? Hmm. This line was inside a class method -- I didn't think you could declare functions in a class method.... Still confused, but perhaps on the road to enlightenment. JDH From peter at engcorp.com Fri Apr 16 10:01:35 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 16 Apr 2004 10:01:35 -0400 Subject: AOP use cases In-Reply-To: References: <84fc4588.0404140106.3fa0c55@posting.google.com> Message-ID: <0pydnSB4WYuieuLdRVn-hQ@powergate.ca> Will Stuyvesant wrote: > What are good usage examples? I would be very interested to hear some real-world and real useful use cases for AOP as well. So far, the logging example seems to be put forth so often that I'm starting to suspect that's the *only* "useful" thing people are doing with it. :-) From direct personal experience, could some AOP folks please point out some compelling use cases so that the doubting Thomases (and Wills, and Peters) can better understand and accept the idea of AOP as being more than just a few fringe cases? (The logging one actually annoys me: the only time I've ever wanted such logging was when debugging very complicated problems, and since switching to TDD I have never encountered anything that even remotely made me consider writing such logging wrappers again.) -Peter From no.email at please.com Mon Apr 12 05:55:05 2004 From: no.email at please.com (Stevie_Mac) Date: Mon, 12 Apr 2004 10:55:05 +0100 Subject: pythonwin crash (used to work) - please help quick. References: <5Reec.62668$Id.61067@news-binary.blueyonder.co.uk> Message-ID: I think seen somthing like this on net somewhere when i was searching. So if I understand this, a python GUI can't debug a script that uses code from any other GUI implementation (like wx for example)? If so, dang! Whats my options - different IDE - or - no debug! wait, im sure when I tried to run the script direct (through python and pythonw) it still bombed - but in pyShell it didn't - hows that? Stevie_Mac :confused: "Paul Prescod" wrote in message news:mailman.537.1081743469.20120.python-list at python.org... > Stevie_mac wrote: > > > OS=XP, Python 2.3, wx2.5.1.5u > > Not sure what's to blame here - or to be more precise, how to fix it!... > > > > If I do this in PythonWin... > > import wx > > d = wx.Dialog(None, -1, 'title') > > BANG - IDE crashes > > It typically doesn't work to have two GUIs in one process. PythonWin > uses MFC. Wx is a totally different GUI. > > Paul Prescod > > > From asdf at asdf.com Thu Apr 22 15:48:12 2004 From: asdf at asdf.com (asdf sdf) Date: Thu, 22 Apr 2004 19:48:12 GMT Subject: python web programming / CMS In-Reply-To: References: Message-ID: <0kVhc.54316$eB7.29255@newssvr25.news.prodigy.com> > 1. Am i correct in thinking i would have to add for instance FastCGI to > the Spyce install in order to get it working? > > 2. In jsp, i often used my own java objects in the code. Can you also do > this with Spyce? For instance, if i would have to get data from a db, i > would > make an object that implements code to do this and then create an instance > of that object in a PSP. Is this doable? > > 3. What databases can be accessed from Python? i've only played a bit with Spyce. you can use it as plain CGI, or you can use FastCGI or modpython. your choice. you can invoke python scripts which can make database connections. database support isn't built into Spyce. you get the python-wrapper for whatever database you want. a bunch are available. certainly all the major databases. modpython has recently greatly expanded its scope. now it includes PSP style functionality. also session support. seems to overlap pretty heavily/maybe subsume what Spyce does. i tried asking on the modpython group for a comparison of modpython PSP v. Spyce PSP, especially in terms on completeness, stability, scope, etc. i triggered an interesting discussion of PSP-style templates, but no one directly answered my question. Be advised also there are other python PSP-style projects out there, including one named PSP. Also I hope you realize none of these projects are a CMS framework of any sort. They are tools with which you could write your own. I assume your CMS requirements are very minimal or you would avoid trying to reinvent the wheel. From claird at lairds.com Mon Apr 26 16:33:44 2004 From: claird at lairds.com (Cameron Laird) Date: Mon, 26 Apr 2004 20:33:44 -0000 Subject: alternative python compilers/vms? (like java) References: Message-ID: <108qsh8bo27vp3e@corp.supernews.com> In article , Yermat wrote: >Diez B. Roggisch a ?crit : >> project2501 wrote: >> >> >>>are there alternative compilers for python? or different VMs to run the >>>bytecode? >>> >>>similar to IBM java jvm and sun jvm, and other jvms? jikes, gcj? >> >> >> there is jython, a very popular python 2.1 implementation on top of the java >> vm. >> >> Apart from that, AFAIX python is not specified in terms of a vm, as java is. >> The bytecode might actually change between versions. >> > >There is also IronPython for .NET. > >By now, the python byte code is considered as "an implementation detail" >that is why it is not specified... >It might disappear in the future... or not. ;-) > >So it seems that we cannot rely on it for whatever purpose ! > >-- >Yermat > might interest the original questioner. -- Cameron Laird Business: http://www.Phaseit.net From peter.maas at mplusr.de Thu Apr 8 08:47:30 2004 From: peter.maas at mplusr.de (Peter Maas) Date: Thu, 08 Apr 2004 14:47:30 +0200 Subject: Are line continuations needed? In-Reply-To: References: <407409ef.82801353@news.eircom.net> Message-ID: Peter Otten wrote: >>d = { 'key1' : 'A very very long string of several hundred '\ >> 'characters. I could use a multi-line string but '\ [...] >>>>d = {1: "Hi Peter, " > > ... "what do you " > ... "think of this?"} You got me :) I know implicit line continuation but thought that it applies only to cases where the strings are direct elements of the bracket like in ["s1", "s2"]. OK, then my example should read s = 'A very very long string of several hundred '\ 'characters. I could use a multi-line string but '\ [...] If there are more than three lines you will type less with a pair of brackets. Mit freundlichen Gruessen, Peter Maas -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Hubert-Wienen-Str. 24 Tel +49-241-93878-0 Fax +49-241-93878-20 eMail peter.maas at mplusr.de ------------------------------------------------------------------- From project5 at redrival.net Fri Apr 2 16:22:11 2004 From: project5 at redrival.net (Andrei) Date: Fri, 2 Apr 2004 23:22:11 +0200 Subject: Making the Zen of Python more useful References: <106qp0uivlefo40@corp.supernews.com> <-5ydnTEmxfuZHvDdRVn-iQ@powergate.ca> Message-ID: <135x6c17eiagn.10nki10lpeg9p$.dlg@40tude.net> Peter Hansen wrote on Fri, 02 Apr 2004 13:09:42 -0500: > One could expand on that idea as well, such as to satisfy those who > are overly obsessed with performance issues: > > import wxPython rapidly Hey, that's a pretty neat idea :). A dummy 'rapidly' keyword would be worth it even if just for the psychological effects it would have. But I'd suggest to make it more versatile, not tie it to import: you should be allowed to optimize bottlenecks by adding 'rapidly' to them! -- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5 at jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From jcarlson at uci.edu Sat Apr 10 18:47:09 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Sat, 10 Apr 2004 15:47:09 -0700 Subject: Changing the default string object used by the interpreter In-Reply-To: <1081577328.739901@bats.mcs.vuw.ac.nz> References: <1081577328.739901@bats.mcs.vuw.ac.nz> Message-ID: > I'm wondering if anyone can suggest a way, short of directly hacking the > python interpreter, to change the default str class to a different one. > ie. So that every time a str instance is created, it uses *my* class > instead of the built-in python string. Is there anything hidden away > that can be overloaded that might make this possible to do? Mike, I don't believe so. There would need to be quite a few changes to the C internals of Python in order to make /every/ string created or generated be of your string class. I would suggest you just wrap the Python strings with your own class whenever you need it... def myfunct(arg, ...): if isinstance(arg, str): arg = MyClass(arg) #rest of the function body. With the upcoming decorator syntax for 2.4, you could decorate all of your functions to do this, or if you are careful, you could use the below now (as long as MyClass was a subclass of object)... def auto_wrap(*arg_types): def funct(function): def funct_with_arguments(*args): a = [] for typ, arg in zip(arg_types, args): if isinstance(typ, type): a.append(typ(arg)) else: a.append(arg) return function(*a) return funct_with_arguments return funct #using current syntax.. def myfunct(arg): #rest of function body myfunct = auto_wrap(MyClass)(myfunct) #using Guido and other's preferred decorator syntax... [auto_wrap(MyClass)] def myfunct(arg): #rest of function body #using another group's preferred decorator syntax... def myfunct(arg) [auto_wrap(MyClass)]: #rest of function body - Josiah From meyer at acm.org Wed Apr 7 10:22:42 2004 From: meyer at acm.org (Andre Meyer) Date: Wed, 7 Apr 2004 14:22:42 +0000 (UTC) Subject: Dynamic creation of an object instance of a class by name Message-ID: Hi all I have been searching everywhere for this, but have not found a solution, yet. What I need is to create is an object that is an instance of a class (NOT a class instance!) of which I only know the name as a string. This what I tried: class A: def __init__(self, id): self.id = id def getID(self): print self.id ca = new.classobj('A', (), {}) oa1 = ca() oa2 = new.instance(ca) oa1 <__main__.A instance at 0x007E8AF8> oa1.getID() Traceback (most recent call last): File "", line 1, in ? AttributeError: A instance has no attribute 'getID' oa2 <__main__.A instance at 0x007E8AF8> oa2.getID() Traceback (most recent call last): File "", line 1, in ? AttributeError: A instance has no attribute 'getID' Thus, both ways only produce a class instance, but NOT an object of that class!!! How can I get a new object instance??? What else needs to be filled in for base_classes and __dict__ in new.classobj? Any help is appreciated, this is driving me nuts! kind regards Andre From fredrik at pythonware.com Fri Apr 16 15:19:00 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 16 Apr 2004 21:19:00 +0200 Subject: empty window when using askopenfile References: Message-ID: Sorin Gherman wrote: > Is there any way to minimize/hide the annoying default, empty Tk > window that shows behind the native file opening dialog , when using > askopenfile, etc, in tkCommonDialog? explicitly create the root window, and withdraw it from the screen before you call askopenfile: import Tkinter root = Tkinter.Tk() root.withdraw() file = tkFileDialog.askopenfile(...) Got Tkinter questions? http://mail.python.org/mailman/listinfo/tkinter-discuss has the answers. From dmq at gain.com Tue Apr 27 19:39:16 2004 From: dmq at gain.com (David MacQuigg) Date: Tue, 27 Apr 2004 16:39:16 -0700 Subject: Ideas for Python 3 References: Message-ID: Mike, thanks for a very thorough and thoughtful review of this proposal. On Mon, 26 Apr 2004 22:00:50 -0400, "Mike C. Fletcher" wrote: >David MacQuigg wrote: >... > >>All methods look like functions (which students already understand). >> >> >I think it might be more proper to say that you've made all functions >methods with an implicitly defined target, but I suppose the statement >is still technically true. A function with no instance variables is identical to a function defined outside a class. In that case, the only way to tell if it is a method or a function is to look at the surrounding code. "Method" is one of those mystery words that tend to put off non-CIS students. I use it when it is necessary to distinguish a method from a function, but otherwise I prefer the term function. It emphasizes the similarity to what the students already know. >>Benefits of Proposed Syntax >>=========================== >>-- Unification of all function forms ( bound, unbound, static, class, >>lambda ). All will have the same form as a normal function >>definition. This will make it easier to teach OOP. Students will >>already understand functions and modules. OOP is a small step up. A >>prototype will look just like a module ( except for the instance >>variables ). See Parallels between Prototypes and Modules below. >> >> >This is nice. Not "I'm going to rush out to adopt a language because of >it" nice, but nice enough. I'm curious about one thing: > > proto x( object ): > flog :( x, y ): > .x = x > a = x() > b = x() > a.flog = b.flog > a.flog() > print b.x > >In other words, how do I hold a reference to a bound method/function if >there are no such things and only the "last access" determines what the >implicit target is? Just to be clear, I'm assuming you're going to have >storage *somewhere* so that: > > a = module.do > a() > >works. Bound and unbound functions work just like in Python. This is where I differ with Prothon, on the need for special binding syntax. >>-- Using an explicit __self__ variable avoids the magic first >>argument, and makes it easier to explain instance variables. See the >>sections below comparing a brief explanation of instance variables in >>Python vs the simplified form. A full presentation of OOP, like pages >>295-390 in Learning Python, 2nd ed. will likely be 1/2 the number of >>pages. Not only is the basic presentation simpler, but we can >>eliminate a lot of discussion of lambda functions, static methods, >>etc. >> >> >This is a wash IMO, with the explicit "self" having a slight edge on >"Explicit is better than Implicit" grounds. You now have to explain >where the magic __self__ comes from instead of how self is bound when >you access the instance's method. They're both magic, the Python stuff >is just explicitly visible. Still, since you're coding it deep into >this new language, it'll be first nature to the Whateverthon programmer. > >On a personal note, the moment where I "got" the concept of methods >(Python was my first OO language) was seeing "self" in the argument list >of a function and realising that it's just a parameter curried into the >function by doing x.method lookup. That is, it just looked like any >other function, the parameter was just a parameter, nothing special, >nothing requiring any extra knowledge save how it got bound (and that's >pretty darn simple). Coming from a structures+functions background it >made complete sense. I assume no background other than what the students will know from studying Python up to the point of introducing OOP. At this point, they have a good understanding of functions and global variables. I've seen a lot of discussion on the "explicitness" of self in Python, and I have to conclude that most of it is missing the real problem, which is complexity from the fact that some functions have a special first argument and others don't. It is hard to compare alternatives by focusing our microscope on something as small as setting a global variable vs inserting a special first argument. What I would do in comparing complexity is look at the length of basic but complete "textbook explanations" of the alternatives. I've copied at the end of this post the explanation of instance variables from my OOP chapter at http://ece.arizona.edu/~edatools/Python/ I've also made my best effort to write an equivalent explanation of Python's instance variables. Comments are welcome. Also, if anyone can write a better explanation for Python's syntax, please post it. >>-- All attributes of a prototype ( both data and functions ) will be >>in a neat column, making it easier to find a particular attribute when >>visually scanning a program. Understanding the structure of a program >>will be almost as quick as seeing a UML diagram. >> >> >Can't say I find it particularly compelling as an argument, not if >introducing punctuation-itis is the cost, anyway. Most people I know >use syntax colouring editors, after all. Do we want to assume syntax coloring is the norm? This will make a difference in the readability of :( ): I use IDLE for my Python editor, and I love it, so maybe I'm just taking syntax coloring for granted. For the function def syntax, we should consider alternative forms, depending on how much clarity or compactness we want. Any of these would be acceptable: func1 = function( x, y ): func1 = func( x, y ): func1 = def( x, y ): func1 = :( x, y ): func1 = : x, y : :x,y: The last form would be used where we now have lambda x,y: It seems like the choice of symbols and keywords here is a matter of personal preference. The only objective criteria I have is that the short form should be as short as possible and reasonably close to the normal form. Verbosity is one of the reasons I don't use lambda. >>-- Lambda keyword will be gone. An anonymous function using normal >>function syntax can be extremely compact. ( :x,y:x+y ) >> >> >That particular example almost screams "don't do this", doesn't it? >:(x,y): x+y I can see as an improvement, but yawn, really. Making >function definitions expressions rather than statements would have the >same effect. By the way, how do you know when your lambda is finished? >I gather the ()s are required if using as an expression? It took me a long time to realize that lamdas have only one advantage over named functions - they can be crammed into a tight space. Here is an example: L = [(lambda x: x**2), (lambda x:x**3), (lambda x:x**4), (lambda x:x**5)] If the purpose is to save space, wouldn't this be better as: L = [:x:x**2, :x:x**3, :x:x**4 :x:x**5] I'm assuming the parens are optional. Is there a parsing problem I'm not seeing? I would add parens simply because I like the appearance of func1 = :( x, y ): I would also be happy with just deprecating lambdas entirely. >>-- Method definitions will be less cluttered and less typing with >>__self__ as a hidden variable. >> >> >I personally prefer explicit to implicit, but I know there's lots of >people who are big into saving a few keystrokes. See discussion above on explicitness. I'm not seeing any advantage in the explicitness of self.something over .something -- *provided* that the leading dot is not used for any other purpose than an abbreviation for __self__. Keystrokes are not a big issue for me either, but in this case, where we have such frequent use of the syntax, I can see where it would be significant. >>-- Changing numerous attributes of an instance will be more >>convenient. ( need use case ) >> >> >That's nice, but honestly, if you're doing a lot of this in cases >trivial enough to warrant the addition you should likely be refactoring >with a domain-modelling system anyway. Still, if you modify the with to >work something like this: > > with x: > .this = 32 > .that = 43 > temp = 'this'*repeat > .something = temp[:55] > >i.e. to just alter the implicit target of the block, not force all >variables to be assigned to the object, it seems a nice enough feature. I'm not sure I understand your use of the leading dots above. Do I assume that .something gets attached to x, and temp is discarded when the with block is finished? This will conflict with the use of leading dots as an abbreviation for __self__. Why do we care about temp variables here? If it really matters, wouldn't it be easier to just del x.temp when we are done? >>Pro2: Replace lambdas with standard function syntax. >> >>Con2: ??? >> >> >Fine, but no need to redefine the spelling for that save to make the >definition itself an expression that returns the function as a value and >allows one to drop the name. i.e. a = def ( y,z ): y+z would work just >as well if you could assign the result to a variable and figured out how >you wanted to handle the indentation-continuation thing to know when the >function ended. The tradeoff is compactness vs preference for a keyword over a symbol. I don't see any objective criteria, except that the lambda syntax should be similar to the normal sytnax. >>Explicit __self__ >> >>Pro1: Allows the unification of methods and functions. >> >>Con1: ??? >> >> >Is hidden (implicit) magic that requires the user to learn rules as to >what the target is when treating functions/methods as first-class >objects. Not a big deal, really. > >>Pro2: Explanation of instance variables is simpler. >> >>Con2: Using __self__ instead of a special first argument is less >>explicit. >> >Um, can't say I see this as a huge pedagogical win. A function either >takes an argument self and can set attributes of the object, or a >function has access to a magical "global" __self__ on which it can set >attributes. I'll agree that it's nice having the same concept for >module and class variables, but seeing that as a huge win assumes, I >think, that those being taught are coming from a "globals and functions" >background rather than a structures and functions background. One type >is accustomed to altering their execution environment, the other to >altering solely those things which are passed into the function as >parameters. I am assuming no background at all other than Python up to the point where we introduce OOP. At that point, students will understand both global variables and functions. I measure simplicity by how much text it takes to provide a basic explanation. See the samples at the end of this post. >>Pro3: Less typing and less clutter in method definitions. >> >>Con3: Can use "s" or "_" instead of "self" to minimize typing and >>clutter. >> >> >That's a counter, not a con. Similarly "Explicit is better than >Implicit" is only a counter, not a con. A con would be: "presence of >variable of implicit origin" or "too much punctuation". Don't think >either is a huge concern. > >>"Assignment" Syntax for Function Definitions >> >>Pro1: See all the variables at a glance in one column. >> >>Con1: ??? >> >> >Doesn't seem a particularly strong pro. IOW seems pretty minimal in >benefit. As for a con, the eye, particularly in a syntax-colouring >editor picks out keywords very well, while punctuation tends to blur >into other punctuation. > >>Pro2: Emphasize the similarity between data and functions as >>attributes of an object. >> >>Con2: ??? >> >> >I see the pro, seems approx. the same to me. > >>With Block >> >>Pro: Saves typing the object name on each line. >> >>Con: Making it too easy to modify prototypes after they have been >>created will lead to more undisciplined programming. >> >> >As specified, makes it only useful for trivial assignments. If you're >going to all the trouble of introducing .x notation to save keystrokes, >why not simply have with alter __self__ for the block so you can still >distinguish between temporary and instance variables? I'm using __self__ exclusively for the bind object in a method call. My biggest concern is not wanting to make leading dots the norm on every variable assignment in a prototype definition. If we are going to highlight the instance variables, and say to students "This is the key difference between what you already know (modules) and what you are going to learn next (prototypes), then I don't want every other variable in the prototype definition to look just like the instance variables. I've included the with blocks in my proposal to please the Prothon folks, but unless someone can come up with a use case, they are not worth the confusion they are causing. >In the final analysis, this really seems like about 3 separate proposals: > > * I like the .x notation's universal applicability, it does seem > simple and elegant from a certain point of view > o I don't like the implicit __self__, but that's an integral > part of the proposal, so a wash If we can come up with an alternative that doesn't require multiple function forms, I would like to consider it. > o I'd want clarification of how to store a reference to > another object's (bound) method (which is *extremely* common > in Python code for storing, e.g. callbacks) bf = cat1.func # where cat1 is an instance not a prototype. > * I really dislike the :( ): function definition notation, > "Readability Counts". Why clutter the proposal with that? It looks good to me, but I'm probably not the best judge of aesthetics. I'll collect some other opinions on this. If enough people prefer def ( ): ( or def : for the lambda form), I'll change the proposal. Does it make a difference in your preference that the parens are optional? I would use them to enhnace readability on normal functions, but leave them out on lambdas. > * I'm neutral on the with: stuff, I'd much prefer a real block > mechanism similar to Ruby with (if we're using implicit targets), > the ability to specify the .x target for the block I've never understood the advantage of Ruby code blocks over Python functions, but that is a separate discussion. >So, the .x notation seems like it would be nice enough, but nothing else >really makes me jump up and down for it... > >That said, I'd probably be willing to use a language that was running on >the PythonVM with a parser/compiler that supported the syntax. I'd be >totally uninterested in automated translation of Python code to the new >form. That's the kind of thing that can be handled by running on the >same VM just as easily as anything else and you then avoid lots of >migration headaches. I don't understand. If you need to use modules written in Python 2, you would need at least some kind of wrapper to make the calls look like Python 3. It seems like any changes that are not "backward compatible" with Python 2 will need to be at least "migratable" from earlier versions, using some automatic translator. That is the major constraint I have assumed in thinking about new syntax. Is this not a vital requirement? >So, just as a marketing data-point; I'm not convinced that this is >markedly superior, but I'd be willing to try a language that differed >from Python in just the .x aspects to see whether it was worthwhile. Thanks again for your time and effort. -- Dave Explanation of Instance Variables in Python =========================================== """ Some of the variables inside the functions in a class have a self. prefix. This is to distinguish local variables in the function from "instance variables". These instance variables will be found when the function is called, by searching the instance which called the function. The way this works is that calling the function from an instance causes that instance to be passed as the first argument to the function call. So if you call cat1.talk(), that is equivalent to Cat.talk(cat1) If you call cat1.set_vars( "Garfield", "Meow"), that is equivalent to Cat.set_vars(cat1, "Garfield", "Meow") The "current instance" argument is auto-magically inserted as the first argument, ahead of any other arguments that you may provide in calling a method that is "bound" to an instance. Note: The distinction between instances and classes is important here. If you call a function from a class, that function is not bound to any instance, and you have to supply the instance explicitly in the first argument ( Cat.talk(cat1) ) The variable name self is just a convention. As long as you put the same name in the first argument as in the body of the definition, it can be self or s or even _ The single underscore is handy if you want to maximally suppress clutter. """ Explanation of Simplified Instance Variables ============================================ """ Some of the variables inside the functions in a prototype have a leading dot. This is to distinguish local variables in the function from "instance variables". When a function is called from an instance ( cat1.talk() ) a special global variable __self__ is automatically assigned to that instance ( __self__ = cat1 ) Then when the function needs an instance variable ( .sound ) it uses __self__ just as if you had typed it in front of the dot ( __self__.sound ) The leading dot is just an abbreviation to avoid typing __self__ everywhere. """ From richie at entrian.com Fri Apr 23 04:49:57 2004 From: richie at entrian.com (Richie Hindle) Date: Fri, 23 Apr 2004 09:49:57 +0100 Subject: AOP use cases In-Reply-To: References: <84fc4588.0404140106.3fa0c55@posting.google.com> <0pydnSB4WYuieuLdRVn-hQ@powergate.ca> Message-ID: [Will] > It's all abstract chitchat [...] Forget about *real* real-world > examples, these people just want to get papers published. [...] > AOP is nothing more than what I expect from a decent programmer: > a good, or at least reasonable, design of software in the first > place. This whole AOP discussion reminds me of this from the ever-relevant Hitch-Hiker's Guide: Slowly, however, the implications of the idea began to be understood. To begin with it had been too stark, too crazy, too much what the man in the street would have said, 'Oh yes, I could have told you that,' about. Then some phrases like 'Interactive Subjectivity Frameworks' were invented, and everybody was able to relax and get on with it. I'm happy to be a man in the street on this one. Let the Java crowd invent shiny new TLAs. -- Richie Hindle richie at entrian.com From joe at notcharles.ca Sat Apr 17 10:09:06 2004 From: joe at notcharles.ca (Joe Mason) Date: Sat, 17 Apr 2004 14:09:06 GMT Subject: AOP use cases References: <84fc4588.0404140106.3fa0c55@posting.google.com> <0pydnSB4WYuieuLdRVn-hQ@powergate.ca> <35qdnT4kNsX1kB3dRVn-gg@powergate.ca> Message-ID: In article , Peter Hansen wrote: > Joe Mason wrote: >> In article <35qdnT4kNsX1kB3dRVn-gg at powergate.ca>, Peter Hansen wrote: >> >>>The logging example is okay, yes, but another problem I have >>>with it is that it's very development-oriented. It doesn't >>>do anything directly for the user in terms of helping implement >>>user functionality. Same goes for the contract aspect, which >> >> >> It does if generating usage reports is a user requirement. Call logging >> in a telephony app, for instance. > > Sorry, but that doesn't fly. That's a clearly separate function > that should have a simple, single call somewhere in the application. Not at all. You'll want to log when calls start and end, when features are turned on and off, when specific services (voice mail, call forwarding) are accessed. If your app is for a call center, you want to log when people go on and off hold and when they enter specific service queues. Two years down the road a major customer will want to buy your system, except they have incredibly specific requirements for report generation which requires you to add even more entry points... > The AOP logging example is talking about a "cross-cutting concern" > (did I get that right?) where one wants to log *all method calls* > in an object. It's a developer tool, not something that you would > use for call logging. No, where one can dynamically decide which method calls to log. The point of "cross-cutting" is that you have the voice mail modules, and the call forwarding module, and the service queue module, and they *all* have to do logging. The examples just add to all methods of an object because it's an easy demonstration. Joe From peter at engcorp.com Mon Apr 26 09:42:18 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 26 Apr 2004 09:42:18 -0400 Subject: About generators In-Reply-To: References: Message-ID: Andrea Griffini wrote: > I'm new to python and I really like what I've seen so far > with just one exception; the absence of a nice syntax > for ranges of integers. I've read PEPs about allowing > > for i in 10: > print i > > and I must say I don't like it very much, but I didn't > find a discussion about what looks more natural > > for i in 0...9: > print i > > or > > squares = [x*x for x in 1...100] > > that is having "expr1 ... expr2" returning an iterator > from expr1 to expr2 (second limit included). > > Has this been considered ? If yes (as I suppose) where > can I find and explanation about it ? Google Groups is always helpful for such questions: http://groups.google.com/groups?q=integer+range+syntax&meta=group%3Dcomp.lang.python.* This leads to various threads, such as the "Re: Thoughts on PEP284" which had the same proposal as yours and what is, I believe, an adequate reason for rejecting it. -Peter From sp at sunguru.com Tue Apr 13 09:25:14 2004 From: sp at sunguru.com (Stefan) Date: Tue, 13 Apr 2004 13:25:14 GMT Subject: [SOLVED] Re: compiling Python 2.3.3 Solaris 9 x86 question In-Reply-To: References: Message-ID: <_SRec.13840$g4.270682@news2.nokia.com> More details: I found that using Sun's cc compiler will do the work without any problem. Make sure two things: 1. Make sure you are not using any libncurses library ... For instance: SFWncur from companion CD 2. Install the 60day trial version of Sun's compiler or if you have already the Sun's compiler installed just use CC=cc instead of GCC. Using this config it will do the trick. For some reasons gcc and configure are not picking up the correct config ! regards, stefan > I had some python 2.3.3 build problems a while ago on a > solaris 8 system. I ended up modifying setup.py to know about > the "non-standard" paths where our stuff is installed, e.g. the > detect_modules method: > > 241 def detect_modules(self): > 242 ### Ensure that /usr/local is always used > 243 ##add_dir_to_list(self.compiler.library_dirs, > '/usr/local/lib') > 244 ##add_dir_to_list(self.compiler.include_dirs, > '/usr/local/include') > 245 > 246 # add_dir inserts as first list element, so /apps/prod > should come last > 247 add_dir_to_list(self.compiler.library_dirs, > '/apps/local/lib') > 248 add_dir_to_list(self.compiler.include_dirs, > '/apps/local/include') > 249 add_dir_to_list(self.compiler.library_dirs, > '/apps/prod/lib') > 250 add_dir_to_list(self.compiler.include_dirs, > '/apps/prod/include') > 251 > 252 # fink installs lots of goodies in /sw/... - make sure we > 253 # check there > 254 if sys.platform == "darwin": > 255 add_dir_to_list(self.compiler.library_dirs, '/sw/lib') > 256 add_dir_to_list(self.compiler.include_dirs, > '/sw/include') > 257 > 258 ##??? Why would I want to set -I and -L paths for the > destination dir? > 259 ## (sys.prefix == --prefix= to configure> > 260 ##if os.path.normpath(sys.prefix) != '/usr': > 261 ## add_dir_to_list(self.compiler.library_dirs, > 262 ## sysconfig.get_config_var("LIBDIR")) > 263 ## add_dir_to_list(self.compiler.include_dirs, > 264 ## > sysconfig.get_config_var("INCLUDEDIR")) > 265 > > and also some runtime lib paths: > > 667 # Curses support, requring the System V version of curses, > often > 668 # provided by the ncurses library. > 669 if platform == 'sunos4': > 670 inc_dirs += ['/usr/5include'] > 671 lib_dirs += ['/usr/5lib'] > 672 > 673 if (self.compiler.find_library_file(lib_dirs, 'ncurses')): > 674 curses_libs = ['ncurses'] > 675 exts.append( Extension('_curses', ['_cursesmodule.c'], > 676 > define_macros=[('HAVE_NCURSES_H', 1)], > 677 > runtime_library_dirs=['/apps/prod/lib'], > 678 libraries = curses_libs) ) > > Without the modifications, some of the extension modules (gdbm, curses, > readline) would > not build. Not exactly nice and portable, but I do not have the time right > now. > > >>Regarding this problem looks like 'configure' does not pickup >>Solaris's curses library. >>I had to manually pass to configure command libncurses library >> >> >>LDFLAGS="-L/opt/sfw/lib -R/opt/sfw/lib -lncurses" >>CPPFLAGS="-I/optsfw/include" ./configure --prefix=/usr/local >>--with-threads --enable-shared >> > > > Does this work for you when you finally run setup.py? > > >>Does this mean that python needs libncurses and can not work with >>Solaris curses library !? > > > I?m afraid I have no clues. Where does the Solaris curses reside? > > Bye, From sadplanet at MAPS.chello.be Fri Apr 23 14:11:21 2004 From: sadplanet at MAPS.chello.be (mr.happy) Date: Fri, 23 Apr 2004 18:11:21 GMT Subject: walking a list Message-ID: Hi all, I have this little question, basicly i solved it already by writing a little bit of code for it (using recursion), but still i am wondering if there is a shorter ways to do things (like 1 or 2 commands). the problem is this, imagine i have a list: list = [1, 2, [3, 2], 5, [6, 5, 4]] if i print out this list using 'for element in list: print element,' it will show me the following: 1 2 [3, 2] 5 [6, 5, 4] but what i really want to show is: 1 2 3 2 5 6 5 4 What i want to do is run through the list and when i get back a list run through that list as well (and if that list contains a list run through it again etc.). all suggestions are welcome, i'm ready to learn from the pro's ;) -- One monk said to the other, "The fish has flopped out of the net! How will it live?" The other said, "When you have gotten out of the net, I'll tell you." From daniel.dittmar at sap.com Thu Apr 15 09:09:36 2004 From: daniel.dittmar at sap.com (Daniel Dittmar) Date: Thu, 15 Apr 2004 15:09:36 +0200 Subject: Why Activestate Python ? References: <8089854e.0404090025.141f090c@posting.google.com> <1afv95dy6164y.1a9l3etptcw8w.dlg@40tude.net> <107sqv5o109su9f@corp.supernews.com> Message-ID: Cameron Laird wrote: > after. It's a fact, though, that some organizations (still!) > only understand "commercial" products. Developers and admini- I suspect it's rather - ActiveState wants to sell support for Python - they only want to support specific releases and packages: those they built and tested themselves Daniel From benjamin at araisoft.com Mon Apr 26 11:57:51 2004 From: benjamin at araisoft.com (Benjamin Arai) Date: Mon, 26 Apr 2004 08:57:51 -0700 Subject: Regular Expressions In-Reply-To: References: Message-ID: <1082995071.2101.17.camel@localhost.localdomain> I would just use the re library because regular expressions will allow you to get right down to the data on the first try anyways without further parsing. If you use the htmlparser library first it may cause some unneeded processing time. On Mon, 2004-04-26 at 06:38, Diez B. Roggisch wrote: > > A - TYPE1: any_text
> > B - TYPE2: any_text_2
> > C - TYPE2: any_text_3
> > w - any_text_15
> >
> > html code > > > > > > I need to have only following data: > > (B, any_text_2) > > (C, any_text_3) > > that is, these data TYPE2 in which. > > you should utilize the htmlparser class to extract the text first. Then this > regular expression might help: > > r"(.) TYPE. : (.*)" > > > -- > Regards, > > Diez B. Roggisch Benjamin Arai Araisoft Email: benjamin at araisoft.com Website: http://www.araisoft.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From mcarm at ssol.us Sat Apr 10 13:21:16 2004 From: mcarm at ssol.us (Mike Carmichael) Date: Sat, 10 Apr 2004 10:21:16 -0700 Subject: Configuring OpenOffice 680 for Tkinter Message-ID: <40782D0C.3020301@ssol.us> Hello, I'm trying to port some simple tkinter python windows to open office's python (just downloaded the latest 680 release). It appears that the required files are there, but I get an error -- 'import _tkinter # If this fails your Python may not be configured for Tk'. How does one configure OO for tkinter? Appreciate any help! Thanks, Mike -------------- next part -------------- An HTML attachment was scrubbed... URL: From daniel.dittmar at sap.com Thu Apr 22 08:59:17 2004 From: daniel.dittmar at sap.com (Daniel Dittmar) Date: Thu, 22 Apr 2004 14:59:17 +0200 Subject: AOP use cases References: <84fc4588.0404140106.3fa0c55@posting.google.com> <0pydnSB4WYuieuLdRVn-hQ@powergate.ca> Message-ID: Jacek Generowicz wrote: >>> SEPARATION OF CONCERNS. [snip] C moved the I/O from the language to a library. This is separation of concerns, but I wouldn't call it AOP. My idea of AOP vs. OOP is about hooks or variation points: ways to customize existing code. OOP added two kinds of variation points: interfaces and calls of virtual methods (yes, the two are closely related). When I have a method a, I can - self.b (): add a call to a virtual method b of self: the behaviour of method a can be changed by implementing a subclass and overriding b - x.c (): add a call to a virtual method c of variable x: the behaviour of method a can be changed by passing a different kind of x into the method Both of these hooks must be provided be the implementor of a, he/she must add calls self.b () and x.c (). AOP tries to add hooks that are provided by the structure of the program so that the programmer doesn't have to add them by hand: - method entry and exit - creation of objects - calls to methods - module import - ... Those of you using XML might want to visualize the program as a DOM tree and AOP as applying a XSLT stylesheet. (Now visualize applying several different stylesheets in arbitrary order) This works probably best if each short rule matches many individual hooks. This is why the logging example is so compelling. If many rules match only one individual hook, then you have 'mincemeat of concerns'. Daniel From R.Byrom at rl.ac.uk Fri Apr 16 08:56:24 2004 From: R.Byrom at rl.ac.uk (Byrom, R (Rob) ) Date: Fri, 16 Apr 2004 13:56:24 +0100 Subject: Catching console output interactively Message-ID: hi, I'd like to be able to trap console output as the user writes interactively. For example if the user press the up or down keys I'd like to be able to catch this and return the last executed command (a bit like the bash_history idea). Can anyone point me in the right direction? thanks for any help, Rob From skip at pobox.com Tue Apr 20 14:54:40 2004 From: skip at pobox.com (Skip Montanaro) Date: Tue, 20 Apr 2004 13:54:40 -0500 Subject: emacs for OS X In-Reply-To: <1gcjrc7.1s60i39g5q0kiN%fabio.trezziCANCELLAMI@email.it> References: <1gcjrc7.1s60i39g5q0kiN%fabio.trezziCANCELLAMI@email.it> Message-ID: <16517.29168.404126.276470@montanaro.dyndns.org> Wezzy> Download python-mode from python.org: Wezzy> http://www.python.org/emacs/python-mode/python-mode.el Ancient, ancient, ancient! Pop up a level to http://www.python.org/emacs/python-mode/ and you'll read: The current release of python-mode.el is no longer maintained on this website. Check the python-mode project on Sourceforge instead. The version you referred to (which I don't think is any longer linked to from the website) is 4.6. The current version is 4.54. Skip From peter at engcorp.com Thu Apr 22 11:42:38 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 22 Apr 2004 11:42:38 -0400 Subject: Convert hexadecimal string to binary In-Reply-To: References: Message-ID: Eric wrote: > I have the following hexadecimal string - '\xff\xff\xff' which i need > to convert to binary. > > How would i go about doing this? You'll need to explain more clearly, and possibly change how you view such things, before anyone can help you with certainty. What you show above is a *binary* sequence of bytes containing three bytes, each with the value 255. The representation of it which you copied (?) from the console contains printable characters and extra stuff to make it easier to read, but that's what you get from repr() on a binary string. Do you actually want a string containing the six printable characters 'FFFFFF'? If that's the case, it's not what you would usually call "binary". Anyway, use binascii.hexlify() for that... Can you give an example of the output you really want? How many bytes does it contain? How does it differ from the string above? -Peter From peter at engcorp.com Wed Apr 28 09:15:02 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 28 Apr 2004 09:15:02 -0400 Subject: String formatting (%) In-Reply-To: References: Message-ID: Pascal wrote: > Hello, > I've a float number 123456789.01 and, I'de like to format it like this > "123 456 789.01". > Is this possible with % character? No, as shown by http://docs.python.org/lib/typesseq-strings.html but you could probably use the 'locale' module instead. I suspect there's also a regular expression that could deal with that, but I don't want to know what it is. ;-) -Peter From gotcha_fza at yahoo.com Sun Apr 11 07:04:27 2004 From: gotcha_fza at yahoo.com (gotcha_fza) Date: Sun, 11 Apr 2004 11:04:27 -0000 Subject: solaris install of python Message-ID: hi has anyone installed pythong on solaris 8 before, i am getting erors when i do a ./configure any ideas why ? regards testbed# ./configure checking MACHDEP... sunos5 checking EXTRAPLATDIR... checking for --without-gcc... no checking for --with-cxx=... no checking for c++... c++ checking for C++ compiler default output... a.out checking whether the C++ compiler works... configure: error: cannot run C++ compiled programs. If you meant to cross compile, use `--host'. See `config.log' for more details. testbed# which c++ /usr/local/bin/c++ testbed # tail config.log ## ----------- ## #define _GNU_SOURCE 1 #define _NETBSD_SOURCE 1 #define _POSIX_C_SOURCE 200112L #define _XOPEN_SOURCE 600 #define _XOPEN_SOURCE_EXTENDED 1 #define __BSD_VISIBLE 1 configure: exit 1 From peter at engcorp.com Fri Apr 9 11:08:58 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 09 Apr 2004 11:08:58 -0400 Subject: Wrapper round x86 Assembler In-Reply-To: <8089854e.0404082353.7bf163a2@posting.google.com> References: <8089854e.0404082353.7bf163a2@posting.google.com> Message-ID: <4dKdnQlIXMIXIevdRVn-gg@powergate.ca> Fuzzyman wrote: > There might be a really good reason why this hasn't been done *or* > someone might have done it and I just can't find it..... *but* > > what about a wrapper to an assembler (presumably for x86 assembly !) > !! > I just wrote some code doing binary operations which would have been > about a zillion times faster in a few lines of assembly code. I refer you to "Pyrex"... -Peter From no at spam.pls Wed Apr 7 08:17:56 2004 From: no at spam.pls (Matthias) Date: 07 Apr 2004 14:17:56 +0200 Subject: OFF-TOPIC:: Why Lisp is not my favorite programming language References: <165b3efa.0403030443.4d591f04@posting.google.com> <40460dd5$0$5916$7a628cd7@news.club-internet.fr> <6in670lrldbjkuujle68a526293j57a7mn@4ax.com> Message-ID: <36w1xn0j823.fsf@hundertwasser.ti.uni-mannheim.de> Stephen Horne writes: > On 6 Apr 2004 13:58:45 -0700, nish20 at netzero.net (Mike Nishizawa) > wrote: > > >mintiSPAMBLOCK at yahoo.com (Minti) wrote in message news:... > > >> However when some one says that the code might be 31.? > >> times slower as compared to C, kinda of scares me. Could assert such > >> figures. I know speed is not the one and only goal but just wondering > >> if these figures are correct. > > It wouldn't surprise me. LISP is normally interpreted - maybe always, > though I'm not certain of that. The interpreter would be written in C. > And, depending on the implementation, the built-in list operations may > well be much more basic than those in Python, for instance, meaning > that more of the relatively sophisticated operations will be handled > using interpreted library code. Sounds reasonable, but is almost completely false: 1.) Lisp is normally compiled. (Almost every Common Lisp implementation compiles to native code, as do many Scheme implementations.) 2.) The built-in list operations are at least as sophisticated as Pythons. (Common Lisp's are more sophisticated.) 3.) Lisp is normally much faster than Python and comes "close" to C (depends on how much you care to optimize your Lisp code). See http://www.norvig.com/python-lisp.html (the colorful table at the bottom of the page) for some data. From goodger at python.org Mon Apr 12 18:33:34 2004 From: goodger at python.org (David Goodger) Date: Mon, 12 Apr 2004 18:33:34 -0400 Subject: OO Bug needs squashing In-Reply-To: <35f7b657.0404121341.6acb8a52@posting.google.com> References: <35f7b657.0404121341.6acb8a52@posting.google.com> Message-ID: <407B193E.8010401@python.org> nick wrote: > Ok I'm more than willing to admit it's probably me but I am > struggling with what appears to be a weird scope issue. > > If you look at the code below I believe day 2 should only contain a > single event. But when you run the prog it prints the events from > day 1 as well. > > Any advice greatly appreciated. First, don't use hard tabs. The standard is to use 4 spaces per indent level. > class Day: > name = None > events = [] > eventD = {} These are class attributes. They're shared by all instances of that class. "events" and "eventD" are mutable, which means that they can change. Instead, move events and eventD into an initializer method: def __init__(self): self.events = [] self.eventD = {} You should also use the __init__ method to populate the object: def __init__(self, name): self.events = [] self.eventD = {} self.name = name > class Event: > start = '' > end = '' > desc = '' def __init__(self, start, end, desc): self.start = start self.end = end self.desc = desc > def loadMonth(): > #Create Day one > day1 = Day() > day1.name = 'day1' Instead of the last 2 lines, use: day1 = Day('day1') > #Create first event for day one > event1 = Event() > event1.start = '10:00' > event1.end = '12:00' > event1.desc = 'event1' Instead of the last 4 lines, use: event1 = Event('10:00', '12:00', 'event1') > day1.events.append(event1) That should be a method instead: day1.add_event(event1) The method would look like this (add under "class Day"): def add_event(self, event): self.events.append(event) That way, if you choose to change the implementation of the events storage later, it will be easy. And so on. I suggest you look at these pages: * Python Tutorial: http://www.python.org/doc/current/tut/ * the FAQ: http://www.python.org/doc/faq/ (especially question 4.21 of http://www.python.org/doc/faq/general.html, which directly answers your original question) * lots more links here: http://www.python.org/topics/learn/ -- David Goodger From klappnase at web.de Fri Apr 23 10:48:15 2004 From: klappnase at web.de (klappnase) Date: 23 Apr 2004 07:48:15 -0700 Subject: tkinter: window always over the rest References: Message-ID: Vicente Palaz?n Gonz?lez wrote in message news:... > Hi, > > I'm programming an application with Tkinter on a Linux platform and > I want to keep always a window over the rest of the windows of my > application, even if it loses its focus, any idea? You could use the Toplevel window?s transient() method: root = Tk() t = Toplevel(root) t.transient(root) root.mainloop() I hope this helps Michael From insert at spam.here Tue Apr 27 14:12:54 2004 From: insert at spam.here (Doug Holton) Date: Tue, 27 Apr 2004 13:12:54 -0500 Subject: Tkinter vs. wxPython? In-Reply-To: <408E9DCA.EC753FE6@shaw.ca> References: <408E9DCA.EC753FE6@shaw.ca> Message-ID: SeeBelow at SeeBelow.Nut wrote: > Do many people think that wxPython should replace Tkinter? Is this > likely to happen? > > I ask because I have just started learning Tkinter, and I wonder if I > should abandon it in favor of wxPython. Could you share a little more info, like are you new to GUI programming, what platform do you develop on (windows, mac, linux), and what features do you need for your application. If you this is your first time using a GUI toolkit I'd recommend sticking with Tkinter. It is simpler to use and there is much more and better documentation since it has been a standard part of Python for a long time. But myself I use wxPython because it has more features. From me at privacy.net Thu Apr 8 04:32:02 2004 From: me at privacy.net (Duncan Booth) Date: 8 Apr 2004 08:32:02 GMT Subject: Are line continuations needed? References: <1078dq6i93pc12d@news.supernews.com> <1078skqn9hgdd19@corp.supernews.com> <1079015hfg56i28@news.supernews.com> Message-ID: "John Roth" wrote in news:1079015hfg56i28 at news.supernews.com: >> Without the backslash continuation, you're forced to write multiline > strings >> with the first line indented differently from the rest of the lines: >> >> mystring = """first line >> second line >> third line""" >> >> Yuck. >> >> Backslash continuation fixes this, as David showed: >> >> mystring = """\ >> first line >> second line >> third line""" >> >> Maybe there will be some other way to do clean multiline strings in >> Python 3.0? > > Since you aparently used tab indentation, your examples came > through with no indentation, so I can't tell what you're talking > about. I think that you might find there wasn't any indentation to lose. Read the point more carefully and you might see he has a valid concern. Consider this (none of the lines are indented): mystring = """\ +---------------+ | '" | +---------------+ """ Without a line continuation there simply isn't any way to write this string and still have the box characters line up neatly. From steve at ninereeds.fsnet.co.uk Tue Apr 6 10:45:33 2004 From: steve at ninereeds.fsnet.co.uk (Stephen Horne) Date: Tue, 06 Apr 2004 15:45:33 +0100 Subject: How to do [1]*4 for a tuple References: Message-ID: On Mon, 5 Apr 2004 21:05:34 -0400, "Vineet Jain" wrote: >I'm not sure I understand why [1]*4 and (1)*4 work differently? [1]*4 >results in [1, 1, 1, 1] while (1)*4 results in 4. There are times when I >have to do the following: > >'%s some value %s and some other text %s' % (a)*3 > >as apposed to > >'%s some value %s and some other text %s' % (a, a, a) > >In this case I always end up doing > >'%s some value %s and some other text %s' % [a]*3 You have the answer to your question already, but you may be better off using a dictionary with the % operator to get named association... >>> a={'a':'aaa'} >>> print '%(a)s some value %(a)s and some other text %(a)s' % a aaa some value aaa and some other text aaa This works particularly well when not all substituted strings are the same, and when you may want to change format strings in such a way that the substitutions may not be in the same order, or may not all be used, etc. In other words, it can be very useful when the format strings are supplied externally. It can be handy when the support guys want to decide the wording of error messages (and change their minds every other day) for instance. -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From peter at engcorp.com Sat Apr 24 22:17:08 2004 From: peter at engcorp.com (Peter Hansen) Date: Sat, 24 Apr 2004 22:17:08 -0400 Subject: command-line args In-Reply-To: <108lqn9mdimaq1a@corp.supernews.com> References: <108lqn9mdimaq1a@corp.supernews.com> Message-ID: <_YqdnbORcfQ4ghbd4p2dnA@powergate.ca> Cameron Laird wrote: > You seem to have given Michael everything he needed. I don't > get it, though. Why must "some code that needs to know the > timeout" import globals? In what context would it not already > be present? We're on different wavelengths, obviously, because I don't even understand your question. Let's try to find the source of the misunderstanding. Here's my take on it: Assuming we're both accepting that the "timeout" value is stored only in a module called globals, and in Python a module is not available in another module unless there is a prior "import" statement importing the required module, it seems to me that code in another module which needs to use "timeout" *must* do an "import globals" first. Having written that, I'm guessing you are thinking about only one module, where "import globals" occurred at the top, and the arg parsing code then executed, and then later on some other code in the same module needed to get to "timeout". In that case clearly "it would already be present". -Peter From anand at easi.soft.net Thu Apr 22 02:38:19 2004 From: anand at easi.soft.net (Anand K Rayudu) Date: Thu, 22 Apr 2004 12:08:19 +0530 Subject: COM & Python References: Message-ID: <4087685B.6040403@easi.soft.net> Hi Larry, Thanks for the suggestion, I have gone through the book, but unfortunately nothing much is discussed about this topic. Being new to MFC i am finding it difficult to get started. I want to just create a dialog box, with my own controls and get the python call backs for them. can some one please share some example source code or any experience regarding this. Any help will be a great start point for me. Regards, Anand Larry Bates wrote: >Get a copy of >Python Programming on Win32 By Mark Hammond, Andy Robinson > >This is the best starting point for you. > >Larry Bates >Syscon, Inc. > >"Anand K Rayudu" wrote in message >news:mailman.752.1082375155.20120.python-list at python.org... > > >>Hi all, >> >>I want to use python with COM extension. I am successful using python as >>client. >>I could interact to my application through COM interfaces from python. >> >>I also want to use the win32ui layer, which wrapped all MFC user >>interface functionality. >>I am just wondering if some on can guide me with some documentation on >>using them. >>I want to know how the call backs are handled in particular. >>Any sample code will be a great start for me. >>If this is possible I can create any dialog boxes with any controls from >>python itself!! :-) >>And take advantage of MFC's View , scroll view and so on. Just exciting!! >> >>Thanks in advance, >>Anand >> >> >> >> >> >> > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From peter at engcorp.com Sun Apr 4 22:45:19 2004 From: peter at engcorp.com (Peter Hansen) Date: Sun, 04 Apr 2004 22:45:19 -0400 Subject: Module import problems In-Reply-To: <30260531.0404041725.746befa0@posting.google.com> References: <30260531.0404041725.746befa0@posting.google.com> Message-ID: simo wrote: > I'm having trouble accessing the imported classes though. > > For example I have login.py which contains something like this: > > class login(wx.Dialog): ... > > Then main.py contains something like this: > > import login > > class MyApp(wx.App): > """define main wx app class""" > def OnInit(self): > login_frame = login() > > The problem is, that when I run main.py, I cannot seem to import login > as a class - I keep getting 'module' object not callable. > > I tried login.login() to not call the module, but the class of the > module, but that doesn't work either, I get 'module' object has no > attribute 'login'. I thought login.login() would look for the def > 'login' not the class anyway? login.login(), based on the precise code that you showed, appears to be the correct thing. I'm not actually trying to understand how your code works, mind you, just looking at it syntactically. If that's giving you the error you say it is, something else is amiss. Do you "shadow" the "login" that comes from the import statement with a function somewhere, or a method, in the class MyApp, which you didn't show? You should be able to use the interactive prompt to "import login" and "login.login" without getting any kind of "no attribute" error. If you can do that, clearly the problem is in the MyApp module. Otherwise you've got something wrong with login.py after all. -Peter From corey.coughlin at attbi.com Wed Apr 14 18:35:27 2004 From: corey.coughlin at attbi.com (Corey Coughlin) Date: 14 Apr 2004 15:35:27 -0700 Subject: Python for PocketPC (Dell Axim - XScale processor) References: Message-ID: Hey, I have one of those too. If you find a version, let me know. Thanks! chrisl_ak at hotmail.com (Chris) wrote in message news:... > Is there a version of Python that will run on the PocketPC platform? > Specifically I have an Axim X5 with Xscale processor... From skip at pobox.com Fri Apr 16 12:22:21 2004 From: skip at pobox.com (Skip Montanaro) Date: Fri, 16 Apr 2004 11:22:21 -0500 Subject: Goodbye TCL In-Reply-To: References: <0LudnSads6NmpuPdRVn-vw@centurytel.net> <107u6ef5a2ise19@news.supernews.com> Message-ID: <16512.2109.190244.452464@montanaro.dyndns.org> Stephen> I would be curious to know what is the biggest-capacity Python Stephen> network application in use? How does it scale in comparison Stephen> with AOLServer? Any ideas? Off the top of my head I have no concrete examples, but you might want to skim these pages: http://www.twistedmatrix.com/services/success http://pythonology.org/success http://www.python-in-business.org/success/ http://www.python.org/Quotes.html http://www.zope.org/Resources/ZopePowered/ I believe people find solutions using the twisted framework scale very well. There's obviously some significant overlap between those pages (Google, ILM and NASA pop up multiple times), and clearly not all of them are using Python to develop large-scale websites but there are lots of interesting entries in a number of fields. the-whole-world-isn't-yet-a-website-ly, y'rs, Skip From siggy2 at supereva.it Thu Apr 8 07:05:35 2004 From: siggy2 at supereva.it (PiErre) Date: 8 Apr 2004 04:05:35 -0700 Subject: win32all 162 installation error [dr watson] References: <33a15593.0404020204.688b85df@posting.google.com> Message-ID: <33a15593.0404080305.1aa59382@posting.google.com> siggy2 at supereva.it (PiErre) wrote in message news:<33a15593.0404020204.688b85df at posting.google.com>... > Hi All, > I am trying to install win32 extension 162 on python 2.2.3 on... [CUT] I found the solution... I was looking for a new version of win32all and I did not realize it has been renamed into pywin32 I apologize... bye, PiErre From fumanchu at amor.org Wed Apr 21 13:13:15 2004 From: fumanchu at amor.org (Robert Brewer) Date: Wed, 21 Apr 2004 10:13:15 -0700 Subject: Stupid Regex Question Message-ID: Jonas Galvez wrote: > > [Fredrik Lundh] > > print re.findall("(.*?)", str) > > But now I'm puzzled. What is that '?' doing, exactly? > > Could you point me any references? http://docs.python.org/lib/re-syntax.html *?, +?, ?? The "*", "+", and "?" qualifiers are all greedy; they match as much text as possible. Sometimes this behaviour isn't desired; if the RE <.*> is matched against '

title

', it will match the entire string, and not just '

'. Adding "?" after the qualifier makes it perform the match in non-greedy or minimal fashion; as few characters as possible will be matched. Using .*? in the previous expression will match only '

'. FuManChu P.S. Top-posting may get you flayed alive by some around here. From shalabh at cafepy.com Fri Apr 9 20:52:35 2004 From: shalabh at cafepy.com (Shalabh Chaturvedi) Date: Fri, 09 Apr 2004 17:52:35 -0700 Subject: Parsing cmd line args problem References: <1081555827.877735@jubilee.esoterica.pt> Message-ID: Paulo da Silva wrote: > Hi. > > I am writing my 1st. python program and I have the following problem: > > I need to build a list of lists (or tuples) for every -i option. > Example: > prog -i xxx -i yyy > and get a list like [[xxx,1],[yyy,1]] > > I have tried this (callback) without any success: > > > Any help please? > Thanks It might be easier to just collect all values for the option in one list and later sort, count or do whatever with it. I believe there is an action in optparse to append values. -- Shalabh From andymac at bullseye.apana.org.au Wed Apr 7 19:04:52 2004 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Thu, 8 Apr 2004 09:04:52 +1000 (EST) Subject: Using python23 to develop an extension for an application that has python22 embedded In-Reply-To: <10787tl9fmth0cd@corp.supernews.com> References: <1073eeubflmchd5@corp.supernews.com> <10787tl9fmth0cd@corp.supernews.com> Message-ID: <20040408084936.Q8581@bullseye.apana.org.au> On Wed, 7 Apr 2004, Michael Geary wrote: > Andrew MacIntyre wrote: > > You can then use another compiler supported by the > > Distutils (MS CL non-optimising compiler, MinGW, > > Borland etc) to build the distributable extension in > > either a Python 2.2 or 2.3 installation, without risking > > mixing C runtime library mismatches (VS.NET uses a > > different CRT than VS6 I understand). If using a 2.3 > > installation, you'll need to substitute a 2.2 import > > library when building the final distributable version. > > Do I understand you correctly? It sounds like you are saying there is a > problem using a DLL built with VC6 and another DLL built with VS.NET in the > same application, but if you were to use a Borland or other compiler, then > you would avoid this problem. No, I was referring to the fact that VS.NET links DLLs to a different C runtime than VS6. Borland may indeed not achieve what I suggested; I have never used it in conjunction with Python. MinGW links by default to the same MSVCRT.DLL as VS6's DLLs (at least the versions I've used do). While mixing C runtime libraries may appear to work for some cases, it doesn't for other cases - file handles/streams and memory allocation are frequent causes of contention (frequently segfaults). I'm aware that you're a much more seasoned Win32 developer than I so expect you have a clearer picture about this; but this is my experience. I have come across an instance where some code produced by an older version of gcc (2.8.1) was the source of a segfault when linked to a body of code produced by a much later version (3.2.1), though it was fine if the rest of the code was also produced by the same version, or a somewhat newer version (2.95). A royal PITA that was; had to rebuild the problematic library (at least I could get the source). -- 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 tim.one at comcast.net Fri Apr 23 15:46:18 2004 From: tim.one at comcast.net (Tim Peters) Date: Fri, 23 Apr 2004 15:46:18 -0400 Subject: Multi-threaded printing and IOErrors in Windows In-Reply-To: Message-ID: [David Bolen] > ... > If that were the case, doing some test prints in your code of very > long strings (the C buffer is probably anywhere from 2-8K) should > be able to reproduce the problem more reliably. stderr and stdout both "blow up" eventually on Windows is they're not attached to something usable. Here's a little Python program: """ import sys i = 0 while 1: sys.stdout.write('x') i += 1 f = open('count.txt', 'w') print >> f, 'wrote', i, 'bytes' f.flush() f.close() """ If I run that from a console with pythonw.exe, it soon dies, and count.txt is left containing "wrote 4096 bytes". Same thing if I use sys.stderr. From solution88pro at hotmail.com Sun Apr 11 19:52:57 2004 From: solution88pro at hotmail.com (Senthoorkumaran Punniamoorthy) Date: Mon, 12 Apr 2004 05:52:57 +0600 Subject: Logging Framework and Method printing Message-ID: I was wondering when using Java's logging framework or Log4J whenever there is a log statement it prints the Method in which the log statement is being used. However in python this doesn't seems to be happening by default and seems like we have to specifically print this using inspect.getouterframes(inspect.currentframe())[1][3] Is there anyway by default I can enable the logging to print the method too? Senthoor _________________________________________________________________ Add photos to your messages with MSN 8. Get 2 months FREE*. http://join.msn.com/?page=features/featuredemail From seb_haase at yahoo.com Sat Apr 17 20:59:01 2004 From: seb_haase at yahoo.com (Sebastian Haase) Date: 17 Apr 2004 17:59:01 -0700 Subject: campaining for PEP 238 - integer division Message-ID: Hi, I'm interested in having more people in our lab using numarray/NumPy instead of MatLab. For that I have put together a couple useful modules and written many myself. But then I got reminded of a new / upcoming feature of Python: "2/3 == 1.5" AKA PEP 238. I'm very interested in putting lots of "from __future__ import division" lines into my code especially since numarray (the new NumPy) now supports it. QUESTION: Is this new/upcoming feature of Python mentioned enough ? Like in the Python tutorial or mailing lists ... A google groups search for "python 238 integer OR division" was giving me one relevant result from Jan2004, another one from May2003, all else even older !!! I think people need to be reminded that PEP238 is really happening and especially new people should be pointed to this -- The fact is that changing something as fundamental as the division operator WILL BRAKE LOTS OF CODE !! I'm just thinking of all the 'a[n/2]' expressions I have in my code. PROPOSAL: This is why I would like to see some special treatment for PEP 238. If the division operator is going to change this should be noted right in the first chapter of the Python tutorial (Python as calculator). Remind all python developers that they will have to change their code. (Actually: is there an easy 'fix' like "from __past__ import division" ?) Cheers, Sebastian Haase From dustin at myaddress.net Wed Apr 21 17:41:47 2004 From: dustin at myaddress.net (Dustin) Date: Wed, 21 Apr 2004 21:41:47 GMT Subject: Python editors for Windows question References: Message-ID: Thank you everyone. I will test out the various editors! :-) "Dustin" wrote in message news:D6Ahc.2737911$iA2.315963 at news.easynews.com... > Hello, > > I just started programming in Python last night, and I've really enjoyed my > experience so far. I would like to know if there is a Windows editor that > recognizes Python and will support a module syntax/definition lists For > instance, let's say that I set form = cgi and then when I hit the period > (".") on the keyboard, a list of objects shows up, such as FieldStorage(), > etc.. Any suggestions are appreciated. Thank you! > > Dustin > > From jcarlson at uci.edu Sat Apr 10 15:21:43 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Sat, 10 Apr 2004 12:21:43 -0700 Subject: wxListCtrl with CheckBox? In-Reply-To: <30260531.0404092256.6b58e3a1@posting.google.com> References: <30260531.0404092256.6b58e3a1@posting.google.com> Message-ID: > I've got a report list and want to have a checkbox in the last column > of each row. Use wx.Grid, it can place checkboxes in cells. - Josiah From rob02omni at vodafone.it Wed Apr 21 04:45:53 2004 From: rob02omni at vodafone.it (Roberto) Date: 21 Apr 2004 01:45:53 -0700 Subject: Getting output from embedded python program References: <2aa196bb.0404190554.74631058@posting.google.com> <4084B179.6020807@magma-da.com> Message-ID: Hi Jeff, Thanks for the reply! > PyRun_File expects dicts for both the third and fourth parameters. I've looked in python manuals but i've missed out this, thanks for pointing me in the right direction. I will try with dicts and post result later. Thanks Again, Roberto Jeff Epler wrote in message news:... > PyRun_File expects dicts for both the third and fourth parameters. > The code you wrote appears to use one module object and one dict object, > but in the (incomplete, non-runnable) code you included, you didn't even > initialize evalModule/evalDict until after the PyRun_File call, nor did > you check for failures along the way. > > Jeff From cookedm+news at physics.mcmaster.ca Tue Apr 13 16:55:41 2004 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Tue, 13 Apr 2004 16:55:41 -0400 Subject: Reommended compiler toolkit References: Message-ID: At some point, Miki Tebeka wrote: > Hello All, > > I'm looking for a pure python compiler toolkit (lexer + parser, like > flex + bison). > ply (which I like most) > SPARK > Yapps > kwParsing [don't know about these] > Plex This is just a lexer. You'll have to write your own parser. Pyrex uses it, along with a hand-written recursive-descent parser. Although it shouldn't be too hard to plug the lexer from this into one of the other packages to do parsing. > PyLR > FlexModule These two aren't pure python. PyLR has a C extension, and looks like it hasn't been updated since 1997. FlexModule uses flex to make a lexer, and also works with BisonModule (which uses bison) to make the parser. I'm guessing for speed FlexModule is probably the fastest, but does anybody have any experience with benchmarking different Python lexer/parsers? -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From wilkSPAM at OUTflibuste.net Fri Apr 16 09:38:53 2004 From: wilkSPAM at OUTflibuste.net (Wilk) Date: Fri, 16 Apr 2004 15:38:53 +0200 Subject: CamelCase versus wide_names (Prothon) References: <87hdvl2dny.fsf@blakie.riol> <87d6692ar8.fsf@blakie.riol> <87wu4gjkwb.fsf@blakie.riol> Message-ID: <87hdvkjb4i.fsf@blakie.riol> Hugh Macdonald writes: > On Fri, 16 Apr 2004 12:07:48 +0200 > Wilk wrote: > >> Why not - instead of _ ? >> >> def my-function() >> >> it doesn't need shift on azerty and qwerty isn'it ? >> >> and we already use it in natural langage... > > So what happens in the following code: > > data = 23 > my = 2 > my-data = 56 > value = 3 > > new-value = my-data-value > > Or would it insist on: > > new-value = my-data - value > or > new-value = my - data - value > > > I think having a character available for names that is also used elsewhere as an operator is a VeryBadThing(TM) (or should that be veryBadThing or very_bad_thing?).... maybe it's possible to replace - by "minus" ? I joke ! you're right, i keep wide_name -- Wilk - http://flibuste.net From tim.one at comcast.net Sun Apr 4 20:47:53 2004 From: tim.one at comcast.net (Tim Peters) Date: Sun, 4 Apr 2004 20:47:53 -0400 Subject: doctest In-Reply-To: Message-ID: [Thomas Heller, on a doctest "pretty printer"] ... > The ctypes tutorial contains (among others) code examples like this: > > >>> from ctypes import * > >>> windll.kernel32 > > >>> cdll.msvcrt > > > This may not be the best documentation, but it shows what the > programmer sees when he experiments with ctypes at the command > prompt. Neither the repr string nor the type of the result is > particularly interesting... Then maybe, to the extent that the output isn't interesting, it does indeed not make for good docs. .... > I used the script above to make sure that the code examples in the > ctypes tutorial are correct (they weren't). And it seems doctest is a > fantastic way to show that. > > Of course it's easy to skim the output manually and see that the > following failure is a minor detail: > """ > ***************************************************************** > Failure in example: print windll.kernel32 > from line #30 of tutorial.stx > Expected: > Got: > """ > > OTOH, it would make more efficient testing if no error would be > reported ;-) How will the doctest pretty printer handle things like > these? Trying to *guess* what is and isn't important in a chunk of output is something doctest has always avoided to date. As I said last time, but it's a tradeoff: doctest strove to be 100% WYSIWYG, and the "doc" part of "doctest" does suffer when that fails. > Will it skip sections like these ' at xxx>', where xxx is a > hex number? I don't think so, but it may do "something like that" if a more precise definition of "sections like these" can be formulated. For a start, Python puts a leading 0x before the address in such reprs: >>> C >>> C() <__main__.C instance at 0x006AC0D0> >>> so the weakest I'd be inclined to entertain is substituting away a match of the regexp r' at 0[xX][\da-fA-F]+>' That wouldn't hide the varying addresses attached to your "handle" output, though. From ville at spammers.com Thu Apr 1 00:48:09 2004 From: ville at spammers.com (Ville Vainio) Date: 01 Apr 2004 08:48:09 +0300 Subject: Python vs Perl (an example) References: Message-ID: >>>>> "Nick" == Nick Monyatovsky writes: Nick> 2. There are many things which are very easy to do in Perl, and Nick> are very cumbersome in Python. Regular expressions is a Nick> vivid example. Saying very generically that Python is easier Nick> than Perl is just an invitation for flame wars. Saying very generically that Python regexps are more cumbersome than Perl one is just an invitation for flame wars. I have heard that statement quite often, yet nobody ever bothers to substantiate it. Hint - you can do s = re.sub m = re.match if the function names are too long for you. And you don't need to re.compile the regexps beforehand, just pass them as strings to the functions. And backslash escaping behaviour can be averted by r"raw strings". The actual regexp syntax is the same as w/ Perl. I guess that's why they are often called 'perl-style' regexps. Nick> If you'd like to demonstrate that Python is easier than Nick> Perl, you'll need to find a better case. This is c.l.py - I don't think there are many who would claim the opposite. Actually, I think Python and Perl are so far apart in the ease of use/complexity/elegance, it's not even funny. I'll give some comments on the script anyway. Nick> my @files; Nick> my $count = 0; Nick> my $total = 0; In Python there's no need for 'my' - every assignment makes the variable local by default. This is a Good Thing, and I doubt you would contest that. Nick> sub retPrevFile Nick> { Nick> my $index = shift; In Py, you just list the arguments in signature. Nick> mkdir "$dirName/$slideName" or die; This idiom is not necessary in Py. You just don't handle errors, the program terminates w/ traceback automatically. Nick> open FILE , ">$file.htm"; Nick> printf FILE $format, $title, $title, $file, $count + 1, $total, Here's a clear inconsistency (FILE doesn't have $, others do). Things like this make a language hard to understand. In Py you just have objects. -- Ville Vainio http://tinyurl.com/2prnb From aku at europe.com Mon Apr 5 11:02:02 2004 From: aku at europe.com (aku) Date: 05 Apr 2004 15:02:02 GMT Subject: design by contract versus doctest Message-ID: <407174ea$0$5066$4d4ebb8e@news.nl.uu.net> There seems to be a contradictive approach in these two things. Example: In the doctest documentation (http://www.python.org/doc/current/lib/module-doctest.html) a required precondition (i.e. n is an integer and >= 0) is verified in the function itself: if not n >= 0: raise ValueError("n must be >= 0") But in "design by contract" this responsibility is squarely on the shoulders of the caller, and is *not* checked in the function. I'm confused as to what the "best" approach is. Isn't it so, that by applying DBC, a lot of unittests can be made redundant? shan. From martin at v.loewis.de Tue Apr 13 18:06:34 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 14 Apr 2004 00:06:34 +0200 Subject: refcounting In-Reply-To: <407c25ca$1@newsflash.abo.fi> References: <407c25ca$1@newsflash.abo.fi> Message-ID: Simon Dahlbacka wrote: > I'm a little confused about the reference counting.. > > static PyObject* MyFunction(PyObject * /*self*/, PyObject *args) { > > PyObject *list; > PyArg_ParseTuple(args, &PyList_Type, &list); > > //do stuff with list elements > > // XXX do I need Py_INCREF(list); here ??? > return list; Yes. PyArg_ParseTuple returns a borrowed reference to the list; the reference is originally help by the argument tuple (which is immutable, so the reference is guaranteed to stay while you hold on to the argument tuple, which is only decrefed in the caller of MyFunction). The result must be a new reference, so you must incref. > PS. are there any documentation explaining the reference counting issues in > more detail than the docs @ python.org ? No. For the specific issue, the documentation says it all: http://docs.python.org/api/arg-parsing.html says "O" (object) [PyObject *] ... The object's reference count is not increased. http://docs.python.org/api/common-structs.html#l2h-821 says PyCFunction ... The function must return a new reference. HTH, Martin From buzzard at urubu.freeserve.co.uk Sun Apr 4 09:39:42 2004 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Sun, 4 Apr 2004 14:39:42 +0100 Subject: Siginificant figures calculating zprob References: <9405c70f.0404031852.155d17d5@posting.google.com> Message-ID: "Sarah Wang" wrote in message news:9405c70f.0404031852.155d17d5 at posting.google.com... > Hello everyone! > > I want to calculate zprob(the area under the normal curve) > with python and I managed to find a function from the > internet. > > But the problem is that the function calculates the result > with only a few significant figures. If I want to get the > 20th number of the result(z-prob) what should I do? Why would you need this degree of precision? I want > to get the confidence level of "6sigma" and all I get at the > moment is "1". > How about posting the code? Check out Gary Strangman's stats.py http://www.nmr.mgh.harvard.edu/Neural_Systems_Group/gary/python.html Duncan From python at rcn.com Fri Apr 9 04:24:58 2004 From: python at rcn.com (Raymond Hettinger) Date: 9 Apr 2004 01:24:58 -0700 Subject: Compact Python library for math statistics References: <3064b51d.0404061038.4d69fd89@posting.google.com> Message-ID: <5d83790c.0404090024.5cefb2ea@posting.google.com> > A statistics module will > be nice to have, although it is easy to write your own. > > Here is a minor suggestion. The functions 'mean' and 'variance' are > separate, and the latter function requires a mean to be calculated. To > save CPU time, it would be nice to have a single function that returns > both the mean and variance, or a function to compute the variance with > a known mean. Like you said, that is easy enough to write on your own. This lightweight module is not meant to replace heavy-weights that already exist outside of the core distribution. The goals are to have a simple set of functions for daily use and for these data reduction functions to work as well as possible with generator expression (one-pass over the data whereever possibe). > (1) In computing the median, there is a line of code > > return (select(data, n//2) + select(data, n//2-1)) / 2 > > I think finding the 500th and 501st elements separately out of a 1000 > element array is inefficient. Isn't there a way to get consecutive > ordered elements in about the same time needed to get a single > element? Select uses an O(n) algorithm, so they penalty is not that much. Making it accomodate selecting a range would greatly complicate and slow down the code. If you need the low, high, percentiles, then it may be better to just sort the data. > (2) The following code crashes when median(x) is computed. Why? > > from statistics import mean,median > x = [1.0,2.0,3.0,4.0] > print mean(x) > print median(x) Hmm, it works for me. What does your traceback look like? > (3) The standard deviation is computed as > > return variance(data, sample) ** 0.5 > > I think the sqrt function should be used instead -- this may be > implemented more efficiently than general exponentiation. The timings show otherwise: C:\pydev>python timeit.py -r9 -n100000 -s "import math; sqrt=math.sqrt" "sqrt(7.0)" 100000 loops, best of 9: 1.7 usec per loop C:\pydev>python timeit.py -r9 -n100000 -s "7.0 ** 0.5" 100000 loops, best of 9: 0.237 usec per loop Raymond Hettinger From python at rcn.com Mon Apr 5 04:43:31 2004 From: python at rcn.com (Raymond Hettinger) Date: Mon, 5 Apr 2004 04:43:31 -0400 Subject: Python is faster than C In-Reply-To: <40711761.5090702@prescod.net> Message-ID: <001c01c41aea$19647560$e841fea9@oemcomputer> > > P.S. If some experimentation shows your code to be useful at the > > interactive prompt, please submit a patch on SF so it won't be lost. [Paul Prescod] > Why put this behaviour in the interactive prompt rather than in repr()? Like the suppression of None, this behavior is only useful for interactive sessions. Also, I don't see how to implement this for repr() since it has to replace the original object with a chain object or tee object. Raymond Hettinger ################################################################# ################################################################# ################################################################# ##### ##### ##### ################################################################# ################################################################# ################################################################# From peter.maas at mplusr.de Fri Apr 2 07:25:51 2004 From: peter.maas at mplusr.de (Peter Maas) Date: Fri, 02 Apr 2004 14:25:51 +0200 Subject: Python conference slogan In-Reply-To: <406D57FF.4040601@mplusr.de> References: <30260531.0404010833.1b834032@posting.google.com> <406C4DDF.5000907@zope.com> <406D57FF.4040601@mplusr.de> Message-ID: Peter Maas wrote: > - Unleash your brain with Python. - Unchain your brain with Python. [stolen from Joe Cockers 'Unchain my heart'] - Unbrace yourself with Python. - Python - think without braces That's all. Now I'm going to do something useful. :) Mit freundlichen Gruessen, Peter Maas -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Hubert-Wienen-Str. 24 Tel +49-241-93878-0 Fax +49-241-93878-20 eMail peter.maas at mplusr.de ------------------------------------------------------------------- From gabriel.cooper at mediapulse.com Tue Apr 27 14:14:11 2004 From: gabriel.cooper at mediapulse.com (Gabriel Cooper) Date: Tue, 27 Apr 2004 14:14:11 -0400 Subject: linux-python arrow-key problem when in interactive interpreter Message-ID: <408EA2F3.3010009@mediapulse.com> I'm running redhat 9 with python 2.3.3 and when I'm in gnome-terminal and inside the python interpreter I can't use the arrow keys anymore. They simply show ^[[A, ^[[B, etc. It doesn't appear to be gnome-terminal's settings as XTerm has the same problem. If just at the command prompt they work fine, I'm able to hit up/down/left/right and see previous/next shell commands or move around to fix typos on the current line... however once I enter the python interpreter it stops working. I have found no options in gnome-terminal for switching anything I would recognize as useful, such as to "VT100" or anything like that. The only remotely similar setting was a character encoding of UTF-8 (unicode) and that didn't seem applicable so I left it alone. Technically this is probably a linux question not a python question but since it only (to my knowledge) happens in the python interpreter I thought you guys might know what I've done wrong. Gabriel. From mike at nospam.com Fri Apr 9 14:34:35 2004 From: mike at nospam.com (Mike Rovner) Date: Fri, 9 Apr 2004 11:34:35 -0700 Subject: Debugging extensions under VS .NET 2003 References: <107dn91j2908rce@corp.supernews.com> Message-ID: Michael Geary wrote: > Gus Tabares wrote: >> If you want to be able to debug your extensions, you will >> [need] to build a debug version of the Python interpreter. > > I'm very curious about this: Can anyone explain why it is necessary? > (And is it *really* necessary?) That is completly unnecessary. If you want to debug python interpretor itself or suspect that your code isn't working as you want due to python behaivour only than you may want to do that. Mike From me at privacy.net Wed Apr 21 06:46:30 2004 From: me at privacy.net (Heather Coppersmith) Date: 21 Apr 2004 06:46:30 -0400 Subject: md5.hexdigest() converting unicode string to ascii References: <77b925de.0404161337.3917ef56@posting.google.com> <77b925de.0404201516.7941cd83@posting.google.com> Message-ID: On 20 Apr 2004 16:16:33 -0700, mgibson at tripwire.com (uebertester) wrote: > I've attempted the suggested solution specifying different > encodings, however, the hash value that is returned does not > match what I expect based upon another utility I'm checking > against. Hash value returned by python specifying utf16 > encoding: 731f46dd88cb3a67a4ee1392aa84c6f4 . Hash value > returned by other utility: 0b0ebc769e2b89cf61a10a72d5a11dda . > Note: I've tried other encoding also. As the utility I'm > verifying against is extensively used, I'm assuming it is > returning the correct value. I appreciate any help in resolving > this as I'm trying to enhance an automated test suite written in > python. Other things that may bite or may have bitten you: o the byte order marker or lack thereof o different newline conventions o trailing newlines or lack thereof o don't forget that there are two utf16 encodings, big endian and little endian Adding to what Peter indicated, the source (code and/or persons) of your extensively used utility may also contain specific test vectors. Regards, Heather -- Heather Coppersmith That's not right; that's not even wrong. -- Wolfgang Pauli From roman.yakovenko at actimize.com Wed Apr 14 01:35:11 2004 From: roman.yakovenko at actimize.com (Roman Yakovenko) Date: Wed, 14 Apr 2004 08:35:11 +0300 Subject: Unable to create com object - need help Message-ID: <2D89F6C4A80FA547BF5D5B8FDDD04523060C60@exchange.adrembi.com> Hi. I need some help. Here is my situation. It is a little bit difficult to explain and/or understand. I'd like to use msdia71.dll. This dll gives you access to program database files created during a build. I register this dll. This is pure com dll. This dll contains 3 top classes. I'd like to create one of them - DiaSource. This class implements IDiaDataSource interface. This fact I can see in dia2.idl. importlib("stdole2.tlb"); [ uuid(e60afbee-502d-46ae-858f-8272a09bd707), helpstring("DiaSource Class") ] coclass DiaSource { [default] interface IDiaDataSource; }; after using makepy I get class DiaSource(CoClassBaseClass): # A CoClass # DiaSource Class CLSID = IID('{E60AFBEE-502D-46AE-858F-8272A09BD707}') coclass_sources = [ ] coclass_interfaces = [ ] If I understand right DiaSource doesn't implements IDiaDataSource interface at all. May be this is a bug, may be I don't understand something. Clarifying this point will be great. There is an other thing, that I don't understand. I can create an instance of this class in VisualBasic 6.0 . (I added a reference to this dll into project). One more thing: I find out that if I use low level api of "pythoncom" module I can create instance of DiaSource class that the only interface it implements is IUnknown. Here I need small hint - what can I do with this instance? More specifiec how can I get the desired interface. ( QueryInterface does not work in this case. see makepy section of this latter ) Or how can I call functions ? I am sorry for such long posting. Also thank you very much for help. Roman From Mike at DeleteThis.Geary.com Mon Apr 26 12:34:08 2004 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Mon, 26 Apr 2004 09:34:08 -0700 Subject: Why we will use obj$func() often References: <84Uhc.22278$dZ1.5087@fed1read04> <8AWhc.23114$dZ1.11070@fed1read04> <40883BFE.B381518A@alcyone.com> <27_hc.23801$dZ1.2716@fed1read04> <40887145.789A2FE8@alcyone.com> <7cki80hj976bia36lhf9er97v073o1pqvm@4ax.com> <1082783076.585831@yasure> Message-ID: <108qeg1lkm5hq8d@corp.supernews.com> > Greg Ewing wrote: > > Hang on a minute. Do you literally mean the immediately > > surrounding function, and not one further out? In > > > > def f(): > > def g(): > > def h(): > > &x = 42 > > h() > > g() > > print x > > > > does the &x in h refer to the x in f? If it does, then I > > don't see how you can deduce that in a single pass. If it > > doesn't, then how do you refer to the x in f from h? Mark Hahn wrote: > You cannot. Yes it literally means the immediately surrounding > function. In your example, I can't think of any scheme we've > discussed that accesses x in function f. Python surely cannot. > > I understand this is quite limiting, but it's simple. As always, > I'm open to suggestions... Ouch. The way I use nested functions in JavaScript, it's essential to be able to use names from higher in the scope chain without worrying about how far up the chain they are. It's not P*thonic, but JavaScript's solution for this keeps looking better to me. When you want a local name, you create it with 'var'. When you refer to a name, it always starts in the current scope and works its way up the chain until it finds the name. As with many things, there's a cost and a benefit. The cost is that you always have to 'var' your local variables. The benefit is that nested functions and closures become very clean and simple. -Mike From eppstein at ics.uci.edu Mon Apr 5 16:37:34 2004 From: eppstein at ics.uci.edu (David Eppstein) Date: Mon, 05 Apr 2004 13:37:34 -0700 Subject: An attempt at guessing the encoding of a (non-unicode) string References: <6pa270h031thgleo4a31itktb95n9e4rvm@4ax.com> Message-ID: In article <6pa270h031thgleo4a31itktb95n9e4rvm at 4ax.com>, Christos "TZOTZIOY" Georgiou wrote: > >I've been getting decent results by a much simpler approach: > >count the number of characters for which the encoding produces a symbol > >c for which c.isalpha() or c.isspace(), subtract a large penalty if > >using the encoding leads to UnicodeDecodeError, and take the encoding > >with the largest count. > > Somebody (by email only so far) has suggested that spambayes could be > used to the task... perhaps they're right, however this is not as simple > and independent a solution I would like to deliver. > > I would believe that your idea of a score is a good one; I feel that the > key should be two-char combinations, but I'll have to compare the > success rate of both one-char and two-char keys. > > I'll try to search for "representative" texts on the web for as many > encodings as I can; any pointers, links from non-english speakers would > be welcome in the thread. BTW, if you're going to implement the single-char version, at least for encodings that translate one byte -> one unicode position (e.g., not utf8), and your texts are large enough, it will be faster to precompute a table of byte frequencies in the text and then compute the score by summing the frequencies of alphabetic bytes. -- David Eppstein http://www.ics.uci.edu/~eppstein/ Univ. of California, Irvine, School of Information & Computer Science From kier at sdf1.net Mon Apr 12 12:56:21 2004 From: kier at sdf1.net (Ray Slakinski) Date: 12 Apr 2004 09:56:21 -0700 Subject: Parsing string array for differences Message-ID: <7598e160.0404120856.217bc8d5@posting.google.com> My below code doesn't do what I need it to do. What I want is to capture the differences between two arrays of data into a new list. So if list A has {Fred, Bob, Jim} and List B has {Jim, George, Fred} I want to capture in list C just {Fred, Jim} y = 0 z = 0 data = {} for element in listB: x = 0 for element in listA: if listA[x] != listB[y]: listC[z] = listB[y] z = z + 1 x = x +1 y = y + 1 Any and all help would be /greatly/ appreciated! Ray From joe at notcharles.ca Sat Apr 3 17:33:22 2004 From: joe at notcharles.ca (Joe Mason) Date: Sat, 03 Apr 2004 22:33:22 GMT Subject: Python is faster than C References: <406F0907.96F37EA1@tunes.org> Message-ID: In article <406F0907.96F37EA1 at tunes.org>, Armin Rigo wrote: > The reason that Psyco manages to outperform the C implementation is not > that gcc is a bad compiler (it is about 10 times better than Psyco's). > The reason is that the C implementation must use a generic '<' operator > to compare elements, while the Psyco version quickly figures out that it > can expect to find ints in the list; it still has to check this > assumption, but this is cheap and then the comparison is done with a > single machine instruction. Why can't the C implementation do the same thing? Joe From nmkolev at uni-bonn.de Mon Apr 26 12:51:32 2004 From: nmkolev at uni-bonn.de (Nickolay Kolev) Date: Mon, 26 Apr 2004 18:51:32 +0200 Subject: Zip with sequences of diffrent length Message-ID: Hi all, I want to make tuples of the elements of a list like this. l = [1, 2, 3] Wanted tuples: (1, 2) (2, 3) (3, None) I can get the first two tuples using zip(l, l[1:]). How do I get the last one? Many thanks in advance, Nicky From mlh at furu.idi.ntnu.no Fri Apr 23 18:57:37 2004 From: mlh at furu.idi.ntnu.no (Magnus Lie Hetland) Date: Fri, 23 Apr 2004 22:57:37 +0000 (UTC) Subject: Atox 0.5 released Message-ID: What is it? =========== Atox is a framework for automated markup. With it one can quite easily write custom scripts for converting plain text into XML in any way one wishes. Atox is normally used as a command-line script, using a simple XML language to specify the desired transformation from text to markup, but it is also possible to build custom parsers using the Atox library. The name (short for ASCII-to-XML) is inspired by such UNIX tools and system functions as atops and atoi. What can it do? =============== With Atox you can write quite general parser that create XML from plain text files, using a special-purpose format language somewhat reminiscent of XSLT. You can also include XSLT fragments in your format description, to use transformations in concert with the Atox markup process. The examples in the distribution demonstrate how you can use Atox to: - Mark up a (relatively simple) technical document (the Atox manual); - Mark up code blocks only through indentation; - Nest lists through indentation - Discern between different indentation "shapes" (e.g. a block quote versus a description list item); - Transform simple LaTeX into XML; - Add XML "syntax highlighting" to Python code; - Mark up screenplays or stageplays, largely based on indentation; - Mark up simple fictional prose; - Mark up simple tables. What's new in 0.5? ================== These are the changes I've made: - Fixed some bugs. - Added support for XSLT fragments in Atox format files. - Added support for non-greedy repetition. - Added several new options to the configuration system. Split input and output encoding and made UTF-8 the default output encoding. Where can I get it? =================== Atox is hosted at SourceForge (http://atox.sf.net) and the current release (0.5) is available for download via its project page (http://sf.net/projects/atox). The Small Print =============== Atox is released under the MIT license. It comes with no warranty of any kind. Also, even though the current version works well, and the project is currently (as per early 2004) being actively developed, there is no guarantee of continued support. What you see is what you get. -- Magnus Lie Hetland "Wake up!" - Rage Against The Machine http://hetland.org "Shut up!" - Linkin Park From drs at remove-to-send-mail-ecpsoftware.com Thu Apr 22 16:16:12 2004 From: drs at remove-to-send-mail-ecpsoftware.com (drs) Date: Thu, 22 Apr 2004 20:16:12 GMT Subject: how to configure apache with mod_python? References: Message-ID: "Gustavo Rahal" wrote in message news:mailman.917.1082645951.20120.python-list at python.org... > Hi > > I just started with mod_python but i can't make it work. I tried to test > the following > http://www.modpython.org/live/current/doc-html/inst-testing.html > but apache still interpretats the mptest.py as plain text. > I'm using fedora 1, apache 2.0.48, mod_python 3.0.4 Have you rebooted/restarted Apache? If so, you need to post the relevant parts of your httpd.conf file (and your .htaccess file if it exists). -d From greg at cosc.canterbury.ac.nz Wed Apr 21 03:37:59 2004 From: greg at cosc.canterbury.ac.nz (greg) Date: Wed, 21 Apr 2004 19:37:59 +1200 Subject: Python CPU? (Re: Python OS) References: Message-ID: <408624D7.9010105@cosc.canterbury.ac.nz> David LeBlanc wrote: > There's a project on sourceforge to develop a Lua microprocessor. Don't know > how active it is, but it could suggest some ideas. Do you have a URL for this? I tried using SourceForge's search function, but couldn't find anything that looked like this. I'm not sure whether this is because it no longer exists, or because SourceForge's search feature sucks. Greg From bokr at oz.net Tue Apr 27 16:00:38 2004 From: bokr at oz.net (Bengt Richter) Date: 27 Apr 2004 20:00:38 GMT Subject: Why we will use obj$func() often References: <84Uhc.22278$dZ1.5087@fed1read04> <8AWhc.23114$dZ1.11070@fed1read04> <40883BFE.B381518A@alcyone.com> <27_hc.23801$dZ1.2716@fed1read04> <40887145.789A2FE8@alcyone.com> <7cki80hj976bia36lhf9er97v073o1pqvm@4ax.com> Message-ID: On Mon, 26 Apr 2004 15:10:22 +1200, Greg Ewing wrote: >Mark Hahn wrote: >> The whole point is to make things simpler, more readable, and more >> efficient, but when people see the & symbol they somehow automatically think >> it's complex. > >The feature itself might not be complex, but it's >unfamiliar, since it's not quite like anything in any >other language they're likely to be familiar with. >So it makes learning the language a more complex >exercise, since it's one more new thing to learn. > >It's also something that will be quite rarely used, >and is totally non-suggestive of its meaning, so I >expect people will be looking it up in the manual a >lot before it finally gets internalised. > >On the other hand, replacing it with a keyword such >as "outer" would make it highly suggestive, to the >point where I'd wager most people wouldn't have to >look it up at all. > >This is a big advantage that words have over >punctuation -- you have much more scope for choosing >one that means something to people. > The word "locals" already exists. If it returned a namespace object instead of a dict proxy when given a nesting-level arg, we could write def f(): x = 123 locals(0).x = 123 # synonym print x # 123 def g(): x = 456 print x # 456 print locals(1).x # 123 locals(1).x = 789 locals(2).x = 101112 print x # 123 g() # 456 then 123 print x # 789 g() # 456 then 789 print x # 101112 exec-ing or eval-ing 'locals(n)' could return a proxy object that would work like the current proxy dict (i.e., a read-only snapshot except if it happened to access globals()). I suppose you could do a declarative form by giving global (or extern or outer) a nesting level too. Hoever, I think lhs := rhs as a spelling of find-and-rebind-lhs would cover most use cases. (Requiring existing and lhs to have been defined first by some lhs = rhs in the current or some lexically enclosing scope). You couldn't reach locally shadowed outer variables of the same name, as you could with locals(n).name, but how often do you really want to do that? Of course, locals(n) and global/extern/outer(n) and := could be all be implemented. Regards, Bengt Richter From rnikaREMOVEnder at adelphia.net Tue Apr 20 22:59:31 2004 From: rnikaREMOVEnder at adelphia.net (Rob Nikander) Date: Tue, 20 Apr 2004 19:59:31 -0700 Subject: Opening MS Word files via Python In-Reply-To: <7b454334.0404201628.371b9e8@posting.google.com> References: <7b454334.0404201628.371b9e8@posting.google.com> Message-ID: Fazer wrote: > I am curious as to how I should approach this issue. I would just > want to parse simple text and maybe perhaps tables in the future. > Would I have to save the word file and open it in a text editor? That > would kind of....suck... Has anyone else tackled this issue? The win32 extensions for python allow you to get at the COM objects for applications like Word, and that would let you get the text and tables. google: win32 python. word = win32com.client.Dispatch('Word.Application') word.Documents.Open('C:\\myfile.doc') But I don't know the best way to find out the methods and properties of the "word" object. Rob From dlissett0 at yahoo.com Tue Apr 6 12:02:32 2004 From: dlissett0 at yahoo.com (Duncan Lissett) Date: 6 Apr 2004 09:02:32 -0700 Subject: Richards bench benchmark References: <6748553f.0403291446.27fb7b93@posting.google.com> <6748553f.0403300836.744e3e22@posting.google.com> <6748553f.0403302317.4595844@posting.google.com> Message-ID: <6748553f.0404060802.6e0d708c@posting.google.com> Peter Hansen wrote in message news:... > The code should be available with > > svn co svn://fortress.engcorp.com/public/bench > > I don't really expect anyone to check it out at this stage, but if you > happen to have a free moment, I wouldn't mind knowing if subversion > is properly visible through my firewall. What do we use to browse that? From imbosol at aerojockey.invalid Thu Apr 1 23:48:06 2004 From: imbosol at aerojockey.invalid (Carl Banks) Date: Fri, 02 Apr 2004 04:48:06 GMT Subject: From python-dev, space vs. tab controversy finally settled References: Message-ID: Wolfram Kraus wrote: > > > Heyho! > > Carl Banks wrote: >> Here's a summary of the final decision Guido made concerning how >> Python will indent code in the future, from python-dev: >> >> Guido had been planning to deprecate tabs in favor of spaces for >> awhile, although there have been good arguments for both tabs and >> spaces. But he was never really comfortable pulling the rug out from >> half the user base. However, today he finally decided on a compromise >> that has all the benefits of both spaces and tabs. >> > [...] > >> So, you should start using Unicode character 0009 to indent right >> away. Python 2.4 will deprecate all indentation not using the new >> indent character, and Python 3.0 will not support any other >> indentation. >> > > Nah, this sucks! This will be the death of Python! I'm switching to > Whitespace: http://compsoc.dur.ac.uk/whitespace/ You people are missing it. Look at what the new indent character is. (It's always funnier when you have to explain it.) -- CARL BANKS http://www.aerojockey.com/software "If you believe in yourself, drink your school, stay on drugs, and don't do milk, you can get work." -- Parody of Mr. T from a Robert Smigel Cartoon From fumanchu at amor.org Thu Apr 15 19:58:09 2004 From: fumanchu at amor.org (Robert Brewer) Date: Thu, 15 Apr 2004 16:58:09 -0700 Subject: Newbie question: matching Message-ID: josh R wrote: > I am trying to write some python to parse html code. I find it easier > to do in perl, but would like to learn some basic python. My code > looks like this: > > line = "eat at joe'sor elseyou'll starve" > so = re.compile("(\.*?\<\\tr\>)") > foo=so.match(line) > print foo.groups() > > I'd like to get an array of elements that looks like this: > > array(0)= eat at joe's > array(1)= or else > array(2)= you'll starve > > Could you please tell me the correct way to do the matching? >>> import re >>> line = "eat at joe'sor elseyou'll starve" >>> re.findall(r".*?", line) ["eat at joe's", 'or else', "you'll starve"] > also, is there something similiar to perl's s/foo/bar/g? re.sub(pattern, repl, string) FuManChu From meyer at acm.org Thu Apr 8 05:22:15 2004 From: meyer at acm.org (Andre Meyer) Date: 8 Apr 2004 02:22:15 -0700 Subject: Python for AI: OWL and CLIPS anyone? Message-ID: <10f99b0f.0404080122.1bcbb6e@posting.google.com> Hi Pythoneers For a project using Python in Artificial Intelligence I am wondering whether useful libraries are available. My interest is primarily in - an ontology parser/generator/editor, ideally for OWL - a rule-based expert system (inference engine), something like CLIPS, ideally linked to OWL Is either of these available for Python? I have not been able to find much information on the Web, yet. Thanks for hints Andre From stach at fr.pl Fri Apr 16 02:35:03 2004 From: stach at fr.pl (Krzysztof Stachlewski) Date: Fri, 16 Apr 2004 08:35:03 +0200 Subject: newbie question References: Message-ID: "jeff" wrote in message news:Xns94CCAEBD1A18Eplasticnospamplsxsin at 216.77.188.18... > i only want the socket to close if the word 'kill' has been sent. > i just tried 'if sdata == "kill\r\n": s.close()', kill\r\n was the string > repr(sdata) returned. the IF statement works, but i'm getting a 'bad file > descriptor' error on the s.close(). This is because you are trying to use a socket that is already closed. You are calling s.close() but you are not break-ing out of the loop. In the next iteration s.recv() is called, but s is closed at that moment. Add a break after the call to s.close(). Stach From kkennedy65 at yahoo.com Mon Apr 5 17:37:37 2004 From: kkennedy65 at yahoo.com (kk) Date: 5 Apr 2004 14:37:37 -0700 Subject: Does Python compete with Java? Message-ID: <8b336527.0404051337.51bb4a1b@posting.google.com> I read this mailing list fairly often, and I am always amazed at what I learn (even not related to Python). I am relatively new to Python. I make my living developing mostly in Java. Python was a "discovery" I made a couple of years ago, and I love the language, but only get to use it at home for hobbies. With all the recent news: - ESR tells Sun to open Java, or be relegated into obscurity by Python, Ruby, and Perl. - Project mono (C# compiler) is touted to be the next great thing in Linux, and will be the dominate language. (by it's creator, of coarse). - This past weekend, Sun signs deal with devil (oops... Microsoft). Now Java "openness" seems to have taken a very large step backwards! I'd like to know if you guys think Python really has a chance to compete with Java, .NET, and any other commercially backed language. The reason I ask is I think it is important to have a "popular" well-supported Open Source language to compete with the big players. PHP seems to have some momentum in popularity, but I much prefer Python as a language. Python has much to offer over Java, VB, etc... Maybe the best chance it has is to ride on the coat-tails of .NET (Python.NET) and the JVM (Jython). Interested to hear your comments. From noemail at noemail4u.com Fri Apr 2 08:53:26 2004 From: noemail at noemail4u.com (Dang Griffith) Date: Fri, 02 Apr 2004 13:53:26 GMT Subject: emergent/swarm/evolutionary systems etc References: Message-ID: On Fri, 2 Apr 2004 10:16:19 +0000 (UTC), "Peter MacKenzie" wrote: >I'll take that to mean that my chances are slim. Although this probability >is mediated my lack of a social life, I've conceived of a contingency >wherein a standard spreadsheet application could be used to facilitate at >least some limited degree of modelling. Given your recommendation, I'll >ensure the feasibility of this option before I commit to the primary >methodology, thereby ensuring that a disappointing rate of progress doesn't >prove fatal for my dissertation. > >Fortunately, I've found an online textbook at >http://www.ibiblio.org/obp/thinkCSpy/index.htm, which appears better suited >to my needs than the standard python documentation, and may alleviate some >of the conceptual and syntactical difficulties I've been experiencing. > >I expect I may be back here for additional aid in the near-future. > The spreadsheet approach may be a suitable alternative, indeed. In the past, I've taught some friends with an accounting background a little about programming, using spreadsheet formulae as examples. Actually, spreadsheets might even have an advantage in your case, because the calculations are performed simultaneously, for all intents and purposes. You don't need to control the "flow". This is a common characteristic of "simulation languages", also. In them, you set up your equations, relationships, dependencies, etc, provide initial conditions, and let them run. There is very little of the linear sequencing of steps that occurs in most popular languages (python, C(etc), lisp/scheme, pascal). To simulate "generations", you will probably need to write a macro that copies one generation to the next (column, or separate sheet). This is ironic, given that the Von Neumann paper that started your interest in the subject is about copying a machine/program. Best of luck, --dang From till at score.is.tsukuba.ac.jp Thu Apr 22 01:42:41 2004 From: till at score.is.tsukuba.ac.jp (Till Plewe) Date: Thu, 22 Apr 2004 14:42:41 +0900 Subject: python shutting down sloooooooowly/tuning dictionaries In-Reply-To: References: <20040421153923.GA13234%till@score.is.tsukuba.ac.jp> Message-ID: <20040422054241.GA15312%till@score.is.tsukuba.ac.jp> On Wed, Apr 21, 2004 at 06:55:24PM +0200, Fredrik Lundh wrote: > > have you tried using > > > > os._exit() > > > > instead of sys.exit() > > better make that > > os._exit(0) > > > and On Wed, Apr 21, 2004 at 12:54:14PM -0400, Tim Peters wrote: > [Till] > > Thanks for the suggestions but unfortunately I already tried disabling > > gc. It did not have any noticable effect (not that I was patient > > enough to time it) nor did using sys.exit(). > > sys.exit() doesn't skip cleanup. os._exit() does, but you use that at your > own risk (it's probably fine, but you've been warned). > Thanks. Using os._exit() works. > > ... > > To give an example of the actual time spans involved: 2-10 minutes for > > running the program and > 30 minutes for shutdown. During that time > > the amount of memory used by python does not seem to vary. > > This sounds like the platform C free() falling into quadratic-time behavior. > You didn't say which version of Python you're using, or which OS + C > runtime, and "stuff like that" varies according to both. This kind of > behavior is generally much rarer under Python 2.3 than under earlier > Pythons -- but if your platform C malloc/free suck, there's not much more > Python can do about that than 2.3 already does. > I am using Python 2.3 and 2.4, {Gentoo,Suse}Linux+gcc3.3, {Free,Net}BSD + gcc3.3, gcc2.95, but I don't remember which combination is the worst offender. Slow shutdowns did occur at least with both Suse9.0 and FreeBSD5.2 on amd64. I will try some other combinations. Thanks again. - Till From achrist at easystreet.com Tue Apr 27 01:20:17 2004 From: achrist at easystreet.com (Al Christians) Date: Mon, 26 Apr 2004 22:20:17 -0700 Subject: How Would You Do: Parsing and Expression Evaluation Message-ID: <108rren1js1hn71@corp.supernews.com> I've got an idea for an application, and I wonder how much of what it takes to create it is available in open source python components. My plan is this -- I want to do a simple spreadsheet-like application: I've used a wxGrid, so I expect that wxPython will do fine for the user interface. The spreadsheet can be organized vertically, one item per line. It might need no more than 100 rows or so. On each line, the user will enter in one column an item (variable) name and, in another column, a formula or expression for computing the item's value. A third column will show the computed value. There will usually be some circular references between the items, but their values will converge quickly with repeated evaluation. The final feature is a button that the user can click when they have the sheet set up correctly -- it will translate the formulas into simple C and python code to perform the same calculations as the spreadsheet. The formulas should be pretty easy -- add, subtract, multiply, divide, log, exponential, and perhaps some user-defined functions. Are there any off-the-shelf python libraries that would make this kind of app much easier? I don't have any special experience related to such things, so I surely don't want to re-invent the wheel out of pure ignorance -- should I try the parsing tools in the standard python library, or will something else work better for me? TIA for any advice, Al From max at alcyone.com Thu Apr 15 22:04:16 2004 From: max at alcyone.com (Erik Max Francis) Date: Thu, 15 Apr 2004 19:04:16 -0700 Subject: CamelCase versus wide_names (Prothon) References: Message-ID: <407F3F20.DB8FA765@alcyone.com> Mark Hahn wrote: > Of course in the Python world you alread have wide_names as your > standard, > but could you for the moment pretend you were picking your standard > from > scratch (as we are doing in the Prothon world) and give your vote for > which > you'd prefer? I'm surprised you're creating your own language and don't have enough internal stylistic sense to make this choice yourself. -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis \__/ I wonder if this grief will ever let me go -- Sade From rnikaREMOVEnder at adelphia.net Tue Apr 20 23:19:38 2004 From: rnikaREMOVEnder at adelphia.net (Rob Nikander) Date: Tue, 20 Apr 2004 20:19:38 -0700 Subject: Generator inside a class prevent __del__ ?? In-Reply-To: <200420041800310664%mday@apple.com> References: <4085BA96.651D2E4A@free.fr> <200420041800310664%mday@apple.com> Message-ID: Mark Day wrote: > still isn't called. There must still be a reference to the object. My > guess is that the generator (directly or indirectly) is referencing the > object, creating a self referential loop. > Python has a garbage collector that will try to find these objects with cyclic references. from test import * >>> a = toto() init >>> a = None >>> import gc >>> gc.garbage [] >>> gc.collect() 4 >>> gc.garbage [] >>> I checked out the documentation for that gc.garbage list and it says that the collector can't free objects in cycles if the cyles have objects that have __del__ methods. So it puts them in this list. I wonder what other garbage collectors do in this situation? Anyone know? Java? Rob From wsr2 at swbell.net Tue Apr 20 18:24:31 2004 From: wsr2 at swbell.net (Bill Rubenstein) Date: Tue, 20 Apr 2004 22:24:31 GMT Subject: How to check if a path *could* be a legal path? References: Message-ID: What is the problem with just creating the file and handling the error case with an except clause? Bill In article , no.spam at no.spam.com says... > Hi, > > I have a string. > This string is to be used as a path for a new file. > I would like to check if this string *could be* a valid file name, > *before* I try to create the file itself. > In other words, I would like to know whether some string violates the > underlying OS's policies (or maybe some more restriced policies, but > portable) considering file paths. > > Example: > > 1. > s = 'C:\file.txt' > > the above is potentially a valid path on my system. > > 2. > s = 'cc:/^- =#jk\kj+.+?! :-)' > > the above is rather invalid and I would like to check it somehow before > I even try to create the file. > > Does the Python library contain a functionality that allows to achieve > this goal? > > From cmg at dok.org Tue Apr 13 11:12:17 2004 From: cmg at dok.org (Chris Green) Date: Tue, 13 Apr 2004 11:12:17 -0400 Subject: pdb + unittest References: <6tadnUz-4_mOfebdRVn-tw@powergate.ca> Message-ID: Peter Hansen writes: > > I'm not entirely clear what you're asking, but generally when > I need to use pdb with unit tests (or any other time), I simply > invoke it with "import pdb; pdb.settrace()" and get the prompt > wherever I want it, single step until I'm satisfied, then type > "c" to continue at full speed. Thanks! For some reason, I thought you had to pass set_trace an argument of the frame you wanted. That's exactly what I want :) -- Chris Green Fame may be fleeting but obscurity is forever. From colin.blackburn at durham.ac.uk Tue Apr 6 08:27:36 2004 From: colin.blackburn at durham.ac.uk (Colin Blackburn) Date: Tue, 06 Apr 2004 13:27:36 +0100 Subject: design by contract versus doctest References: <407174ea$0$5066$4d4ebb8e@news.nl.uu.net> <4072977b$0$1699$afc38c87@news.easynet.co.uk> Message-ID: On Tue, 06 Apr 2004 12:41:45 +0100, Peter Hickman wrote: > Looking at the Eiffel site the contract is enforced within the called > function. Only while checking is turned on. It is a design philosophy. You specify the pre and post-conditions before code is even thought of, it is part of the design. > put (x: ELEMENT; key: STRING) is > -- Insert x so that it will be retrievable through key. > require > count <= capacity > not key.empty > do > ... Some insertion algorithm ... > ensure > has (x) > item (key) = x > count = old count + 1 > end This says that *if* the pre-conditions are met (by the caller) *then* the post-conditions will be guaranteed to be met (by the called method.) All callers know this because the contract is publicly specified. New callers can make use of this method because they know what is required of them and that a given result will be assured if those requirements are met. They know this because the method has been designed correctly for these constraints. If the pre-conditions aren't met then not sensible result is guaranteed. Colin -- From mark at prothon.org Fri Apr 23 15:12:24 2004 From: mark at prothon.org (Mark Hahn) Date: Fri, 23 Apr 2004 12:12:24 -0700 Subject: Why we will use obj$func() often References: <84Uhc.22278$dZ1.5087@fed1read04> <8AWhc.23114$dZ1.11070@fed1read04> Message-ID: "Mark Hahn" wrote in message news:Pedic.28731$dZ1.11479 at fed1read04... > > "Peter Hansen" wrote ... > > > Mike, you haven't been keeping up with the other thread. I think the > > decision is now: > > > > fish_height$some_where() > > That is like SO two-hours-ago. Marcia like, told me that Biff like, said > that Trish like, said camelCase was SO out, can you BELIEVE IT???? Peter: You were making fun of how of fast I'm changing things in Prothon, right? I was going along with that humour in my message. Someone in a private message accused me of making fun of you, which I was definitely not doing. Boy, I better shut up. I'm just getting myself in deeper and deeper trouble every message I post today. From jcarlson at uci.edu Fri Apr 9 00:12:06 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Thu, 08 Apr 2004 21:12:06 -0700 Subject: Are line continuations needed? In-Reply-To: References: <1078dq6i93pc12d@news.supernews.com> <1078skqn9hgdd19@corp.supernews.com> <1079015hfg56i28@news.supernews.com> Message-ID: Graham Breed wrote: >> I think that you might find there wasn't any indentation to lose. Read >> the point more carefully and you might see he has a valid concern. >> Consider this (none of the lines are indented): >> >> mystring = """\ >> +---------------+ >> | '" | >> +---------------+ >> """ >> >> Without a line continuation there simply isn't any way to write this >> string and still have the box characters line up neatly. > > > mystring = """ > +---------------+ > | '" | > +---------------+ > """[1:] > What about Windows? You'd need to use [2:]. I would also say that the trailing string slice is ugly. - Josiah From franck.lepoutre at caramail.com Thu Apr 22 13:17:55 2004 From: franck.lepoutre at caramail.com (francois lepoutre) Date: Thu, 22 Apr 2004 19:17:55 +0200 Subject: Paris python user group? References: <408795ee$0$25893$79c14f64@nan-newsreader-02.noos.net> Message-ID: <4087fd7f$0$21549$79c14f64@nan-newsreader-01.noos.net> > ca me fait penser aux phpbeermeeting tout ca :) > Enfin moi pour boire un coup > je suis toujours d'accord. Bonne nouvelle. Et de quatre ... Les buveurs d'autres bi?res, php en particulier, sont bienvenus. Le python a un gout inimitable cependant. > c'est quoi ce truc de poster un message en anglais + francais ? > sur fr.xxx le francais suffit. et pour l'universalit?, ya esperanto :p Le message a ?t? cross post? sur comp.lang.python pour le cas d'?ventuels informaticiens non francophones scotch?s sur Paris Il y en a ... et pour nos gurus lors de leurs passages dans notre ville lumi?re. Guido, parlez vous fran?ais? Pour l'esperanto, pas de probl?me. Je te laisse le soin de la traduction:) > le plus simple pour commencer serait de creer une liste de diffusion > (mailinglist pour les anglophones), pour ca on a l'embarras du choix (yahoo > groups, ou les mailing lists Sympa, etc). Excellente id?e. Je propose de monter la liste ... apr?s la premi?re r?union et sous r?serve d'atteindre un quorumn, aka nombre de bi?res, suffisant. Histoire de motiver les troupes. A+ Fran?ois From bhoel at web.de Thu Apr 8 14:36:39 2004 From: bhoel at web.de (Berthold Höllmann) Date: Thu, 08 Apr 2004 20:36:39 +0200 Subject: Embedding python in ANSYS: Anyone tried it? References: Message-ID: Hello, "Satish Chimakurthi" writes: > Hello Mr. Berthold, > > A few months ago, I contemplated interfacing/wrapping ANSYS to > Python. I looked at SWIG, BABEL, Boost.Python for this purpose at > that time, only to realise that such direct wrapping is not possible > since ANSYS libraries are basically Fortran based. I thought of the > following work-around to the problem. > > ANSYS allows users to compile their own customized version. It gives > the user access to its vast libraries with the help of some UPF > routines ( look at ANSYS-UPF documentation here > http://www.cesup.ufrgs.br/ansys/prog_55/g-upf/UPS1.htm ). You may be > knowing this. There is a file called ANSCUSTOM in > "/usr/local/ansys/v71/ansys/customize/user" directory. First, I > wrote a "Makefile" and a "make.inc" file based on the information in > ANSCUSTOM. I then wrote a Fortran code in which I used all the UPF > routines I needed to be used with ANSYS. I compiled the Fortran code > with "make.inc" simultaneously to get a binary executable. And > that's it, I was ready to go. The binary executable could be > executed using a specific command which could be found in ANSYS > Installation and Configuration manual, I think. In my case, I was > using ANSYS 7.1, so, I had to execute it as: "anscust71 -custom > ./executable -p ANSYSRF". > > Now, with all that I described above, link between Fortran and ANSYS > has become possible. You can look at F2PY (Fortran to Python > Interface Generator) here http://cens.ioc.ee/projects/f2py2e/ to > have an interface between your Python script and Fortran code that > you would be writing for the purpose. At the moment, my > Python-Fortran interface is very loose. I use Fortran to ANSYS > mostly and do postprocessing work in Python. This is what I am thinking about. Our final aim is to wrap as much functionality of ANSYS to be abble to pre- and postprocess our calculations with the help of Python modules. I have basic knowledge about writing UPF in ANSYS and some experience in writing Python extension modules. I now started wrapping ANSYS UPF routines using f2py and am already able to call some basic python examples from ANSYS. I mainly asked because wrapping a sufficiant amout of the ANSYS interface routines is a lot of stupid typing work, and if sombody else did it before, it would be nice to share the work :-) I won't link my own ANSYS executable, but save time, space and efforts by building a dynamic load shared library for ansys which is available since about ANSYS 6.0 or 6.1. I will do my work using ANSYS 8.1. > Please let me know if you think of any other ideas about wrapping > Python and ANSYS directly. I would appreciate your assistance. A nice thing to try when the basics run is to provide a python interface for generating user elements etc. in Python. But I'm afraid that would require some naugthy magic, is error prone and too much for the first step. Kind regards Berthold H?llmann -- bhoel at web.de / http://starship.python.net/crew/bhoel/ From mwh at python.net Fri Apr 23 07:29:12 2004 From: mwh at python.net (Michael Hudson) Date: Fri, 23 Apr 2004 11:29:12 GMT Subject: python web programming / CMS References: <0kVhc.54316$eB7.29255@newssvr25.news.prodigy.com> <9YWhc.82882$%l7.5377160@phobos.telenet-ops.be> Message-ID: "flupke" writes: > "Michael Hudson" schreef in bericht > news:m3fzavnfy3.fsf at pc150.maths.bris.ac.uk... > > > You can certainly do dynamic content with Zope/Plone, using Page > > Templates and TAL and Scripts (Python) and so on (indeed, quite a > > large portion of Plone is a collection of Page Templates and Python > > scripts). It's probably possible to use Plone and Spyce at the same > > time, but I can't see why you'd want to. > > The reason why i would want to use Plone and Spyce is that Spyce > provides an easy way to include/embed python code in a html file like > one would do with a jsp page. > I don't think that Plone supports something like that or at least not > that nice but i could be wrong. That's what Page Templates are! Ish. Well, Page Templates solve the same problem, though you're encouraged to put significant logic in Python scripts which you call from the template. I happen to agree with the designers of Page Templates that this is a very good idea; I guess others might differ. Cheers, mwh -- I have long since given up dealing with people who hold idiotic opinions as if they had arrived at them through thinking about them. -- Erik Naggum, comp.lang.lisp From ville at spammers.com Wed Apr 28 02:31:45 2004 From: ville at spammers.com (Ville Vainio) Date: 28 Apr 2004 09:31:45 +0300 Subject: Ideas for Python 3 References: Message-ID: >>>>> "Michael" == Michael Walter writes: Michael> Almost. Or write mapc ("map currying") and have: Note - the name mapc is very misleading, because it looks too much like Lisp mapc (mapcar, equicalent to normal python map). -- Ville Vainio http://tinyurl.com/2prnb From alexanro at stud.ntnu.no Sun Apr 18 18:16:52 2004 From: alexanro at stud.ntnu.no (=?iso-8859-1?q?Alexander_R=F8dseth?=) Date: Mon, 19 Apr 2004 00:16:52 +0200 Subject: Pygame References: Message-ID: Den Wed, 14 Apr 2004 21:37:45 -0400, skrev Steve Holden: > Alexander R?dseth wrote: > > [...]> (Note: "ipv6" is just an example, for the sake of the name, I > know that it's not a standard Python-module). >> > In point of fact since Python 2.3 the socket module has handled IPv6. That's not what I said either. I really tried to stress that it was just an example for the sake of the name. Please tell me how I could possibly express this any clearer, so that I can do so in the future. > But if you mean that geeks like, and therefore tend to include, geeky > things in their langauge distributions, you could have a point. I mean that network-geeks have a tendency to ignore anything that's got to do with graphics-programming. > Nothing in the license stops you from building and distributing > "friendly Python", though, so you might consider putting your own > distribution together. If that's too hard, you will at least begin to > get the idea why PyGame (and this, that and the other) aren't in the > standard distribution. > If you get it together I believe you would increase Python's popularity. The point is that it's illogical not to support fullscreen graphics, but a bunch of other stuff, without any explanation whatsoever. The programming languages I know of, has a long tradition of having some way of doing fullscreen graphics natively, and I don't see any reason for Python not to have this possibility. - Alexander From fumanchu at amor.org Sun Apr 4 14:29:57 2004 From: fumanchu at amor.org (Robert Brewer) Date: Sun, 4 Apr 2004 11:29:57 -0700 Subject: Processes with strange behavoir Message-ID: Markus Franz wrote: > #!/usr/bin/python > > import urllib2, sys, socket, os, string > > # set timeout > socket.setdefaulttimeout(4) > > # function for loading and printing a website > def myfunction(url): > try: > req = urllib2.Request(url) > req.add_header('Accept-Language', sys.argv[1]) > req.add_header('User-Agent', 'Mozilla/4.0 > (compatible; MSIE 6.0; > Windows NT 5.1)') > f = urllib2.urlopen(req) > contents = f.read() > output = "\n---PI001---" + sys.argv[2] + > '---PI001---' + '---PI002-' > + sys.argv[2] + '::' + f.geturl() + '::' + sys.argv[2] + > "-PI002---\n" + > contents > print output > del output > f.close() > del contents > del f > del req > except: > pass Question to anyone--are the 'del' statements above doing anything that doesn't happen automatically when the function closes? I was under the impression that such explicit statements were unnecessary, but perhaps I'm unaware of some quirk. FuManChu From samiller at wmis.net Fri Apr 2 09:47:07 2004 From: samiller at wmis.net (Scott Miller) Date: Fri, 2 Apr 2004 09:47:07 -0500 Subject: Unable to launch IDLE Message-ID: I am new to Python (and programming in general). I have downloaded and installed the Windows installer version of Python 2.3. The Python (Command line) runs fine, but I just get the hour glass for a few seconds then it bombs out when I try to run IDLE. OS Win2kPro SP4 Please help me get started :) Thanks in advance. Proelin From rkern at ucsd.edu Thu Apr 29 17:08:16 2004 From: rkern at ucsd.edu (Robert Kern) Date: Thu, 29 Apr 2004 14:08:16 -0700 Subject: Newbe-books In-Reply-To: References: Message-ID: Sarge wrote: > Hi, > I'm newbe of python, but not of programming (a lot of Matlab, some > C, a bit of C++), I want a *good* book on python for self-study. > I'm short of money, I don't want to make any mistakes, so does > anybody have any suggestions (buy this-don't buy that)? My suggestion: don't buy anything, yet. Work through the official tutorial; start converting the more self-contained of your Matlab code to Python; ask questions here, on the Tutor list[1], and the SciPy list as appropriate. Read the source code of the packages you think you'll be using: you'll get a better idea of how to code in Pythonic (or SciPythonic) idiom this way. In my experience, this "jump right in, the water's warm" approach obviates much of the need for an introductory dead-tree book on the language. Which isn't to say that such books aren't good or worthwhile, but when you're strapped for cash, it's better to exhaust the freely available material[2] before heading to the bookstore. Then again, if reading book-length material on the computer screen makes your eyes all googly or you want something you can read on the bus, then dead-tree is the way to go, but I have no suggestions for you. [1] http://mail.python.org/mailman/listinfo/tutor [2] http://www.python.org/doc/Intros.html > Thanx, > Sarge -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From t-meyer at ihug.co.nz Wed Apr 21 23:29:07 2004 From: t-meyer at ihug.co.nz (Tony Meyer) Date: Thu, 22 Apr 2004 15:29:07 +1200 Subject: zip 2 sequences into 1 In-Reply-To: <1ED4ECF91CDED24C8D012BCF2B034F1305FF656F@its-xchg4.massey.ac.nz> Message-ID: <1ED4ECF91CDED24C8D012BCF2B034F13026F2BB5@its-xchg4.massey.ac.nz> > def flatten(s): > for i in s: > for j in i: > yield j > > flatten(zip([1,2,3], "abc")) Or (I find zip confusing, so avoid it :) ): def merge(s1, s2): for i in xrange(min(len(s1), len(s2))): yield s1[i] yield s2[i] >>> import timeit >>> f = "def flatten(s):\n for i in s:\n\n for j in i: yield j" >>> m = "def merge(s1, s2):\n for i in xrange(min(len(s1), len(s2))):\n yield s1[i]\n yield s2[i]" >>> t = timeit.Timer("list(flatten(zip([1,2,3], 'abc')))", setup=f) >>> t.timeit() 8.6624506745969256 >>> t = timeit.Timer("list(merge([1,2,3], 'abc'))", setup=m) >>> t.timeit() 7.8756800096101642 =Tony Meyer From hungjunglu at yahoo.com Sat Apr 3 23:38:36 2004 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 3 Apr 2004 20:38:36 -0800 Subject: Python conference slogan References: Message-ID: <8ef9bea6.0404032038.5c186a09@posting.google.com> # Did you Python today? regards, Hung Jung From projecktzero at yahoo.com Sun Apr 11 15:47:58 2004 From: projecktzero at yahoo.com (rakanishu) Date: 11 Apr 2004 12:47:58 -0700 Subject: Best IDE? References: Message-ID: <4ace7f9f.0404111147.3120288a@posting.google.com> "Stevie_mac" wrote in message news:... > This has prolly been asked 100 times - so please refrain from flaming if you can... > > What's the best MSwindows editor for python? I'm currently using PythonWin (ActiveState) at the moment, its a bit > buggy - but not too bad. I mean, its got autocomplete & tips & help & autoindentaion (not always good tho). > > Thing is, I'm sure there is something better. Is there? > > (is there a VS.NET addin?) You might take a look at Activestate to see about a .NET add-in. Also, Activestate has Komodo which isn't too bad. It's like PythonWin on steroids. A lot of people seem to like JEdit. It runs on nearly any platform that can run Java. I've done a little bit of HTML editing using it. It seem pretty good. I don't know if I'd call 'em IDEs but it's worth taking the time to learn either emacs or vim. Both are very powerful editors that run on multiple platforms. I tried emacs three times, but couldn't get into it. I'm now getting hooked on vim. YMMV. Others that I've heard good things about are Eclipse and Scite. From elainejackson7355 at home.com Mon Apr 26 00:23:31 2004 From: elainejackson7355 at home.com (Elaine Jackson) Date: Mon, 26 Apr 2004 04:23:31 GMT Subject: Andreas' practical language comparison References: Message-ID: <790jc.244413$Pk3.195251@pd7tw1no> At my website (SeanMcIlroy.nexuswebs.net) I keep a compressed file of all the modules I've written so far in the process of teaching myself python. One of them has to do with prime numbers, primitive roots, etc, which I see forms part of your language comparison. There are also python implementations of some standard graph algorithms (Kruskal, Dijkstra) and assorted other mathematical tidbits, as well as some toy games (tic-tac-toe, nim, mastermind). Help yourself to whatever you want. "Andreas Koch" wrote in message news:c6glig$phm$07$4 at news.t-online.com... | Hi all, | | i started a little "practical language comparison" - practical | in the sense that i compare how actual distributions and versions | and their libraries (not abstract language specifications) solve small | test cases like the 8 queens problem. | | Currently there are contributions for 17 different languages, and | none for Phyton (and Lisp. And Forth. And many others ). | If someone is interested in contributing a few implementations, | please have a look at: | | http://www.kochandreas.com/home/language/lang.htm | | and mail me your code snippets (or critics) or post them here. | | thanks a lot, | -- | Andreas | He screamed: THIS IS SIG! From cybermanxu at hotmail.com Fri Apr 30 08:30:14 2004 From: cybermanxu at hotmail.com (Jinming Xu) Date: Fri, 30 Apr 2004 07:30:14 -0500 Subject: Why cannot jump out the loop? Message-ID: Dear Skip, Timothy, Mark andBeno?t, Thank you all for answering my question. And now I know what the problem is. Wish you all have a great day! Take care, Jinming _________________________________________________________________ Express yourself with the new version of MSN Messenger! Download today - it's FREE! http://messenger.msn.com/go/onm00200471ave/direct/01/ From jacek.generowicz at cern.ch Fri Apr 2 04:48:43 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 02 Apr 2004 11:48:43 +0200 Subject: Simple text markup (-> HTML) Message-ID: :::Title::: A simple text markup utility :::/Title::: :::Section Introduction ::: I'm looking for something to help developers wirte documentation for bits of software they are writing. The main (initially only) presentation format will be HTML. The idea is to allow the author to write a plain text file containing the text he wishes to present, annotated with minimally intrusive markup which describes the :::emph::: meaning :::/emph::: of parts of the text. The author should not concern himself with how the output will look; he should trust the rendering process to Do The Right Thing. For example, the author might want to communicate that some portion of text represents source code, or commands to be issued, or output given by a program. :::Example::: A recursive implementation of the Fibonacci function might look like this :::Source::: def fib(n): if n<2: return 1 return fib(n-1) + fib(n-2) :::/Source::: And it works like this :::Input::: fib(8) :::/Input::: :::Output::: 34 :::/Output::: :::/Example::: :::/Section::: :::Section Why not XML ? ::: The idea is that the utility should be minimally intrusive to the author. Given that the author is likely to want to paste source code, having to substitite all occurances of "<" with < and so on is completely unacceptable. As you can see, I have been using triple colons in this presentation as a sufficiently unlikely character combination, to replace XML's "<" and ">". Clearly this is not ideal. Maybe allowing the author to specify how the markup should be identified is a solution ... for example an instruction such as :::SetMarkup ||::: could be used to change the markup identification sequence to two vertical bars (taking effect only in "leafward" parts of the parse tree. ||/Section|| ||Section Why not LaTeX ? || Yes, LaTeX pretty much reifies the idea I am trying to express, and I could use something in the LateX2HTML genre as a backend. Unfortunately LaTeX it not politically acceptable in my environment. (If the markup is sufficiently simple, then something based on s-exprs could pass through the political correctness filters ... as long as implemented in C(++) or Python.) ||Section Automation|| Ideally, I'd like to be able to execute arbitrary Python code within the document source, in order to "suck in" information from elsewhere. ||Source|| ||Macro|| for line in open("example1.cpp",'r'): print line ||/Macro|| ||/Source|| Given the fragment above, the source code in the file "example1.cpp" would be inserted into the document. ||Section Inclusion|| Also, I'd like to be able to inline other sources of the same document format: ||Include ~/docs/fubar.baz|| ||/Section|| ||Section Summary|| Of course, I am not looking for anything that looks exactly like what I have shown. What I have presented here merely serves to illustrate what sort of functionality I am looking for. Neither am I looking for something of industrial strength, but something that would solve more problems than it creates. The bottom line is that I want authors to write something that looks mostly like plain text, and be able to communicate a few key items of meta-information via markup. Any suggestions ? ||/Section|| From p_s_oberoi at hotmail.com Fri Apr 23 23:42:48 2004 From: p_s_oberoi at hotmail.com (Paramjit Oberoi) Date: Fri, 23 Apr 2004 22:42:48 -0500 Subject: CamelCase versus wide_names (Prothon) References: <6e0680ac.0404211252.7f7b4358@posting.google.com> <4086DFA7.9736E7D3@alcyone.com> Message-ID: The problem comes down to the fact that variable names consist of multiple words, and there is no standard way of combining multiple words into one name. But, what if the language was aware of this fact? If the language 'knew' that identifiers potentially consisted of multiple words, maybe it could detect a few different kinds of styles and automatically do the right thing? Or maybe programmers could declare their own personal word-combiner, sort of like a metaclass? I'm not sure of this is a really good idea or a really bad one... -param > That's cool looking but I'm pretty sure impossible to parse the way you > want > :) From matthew at barnes.net Tue Apr 13 17:27:19 2004 From: matthew at barnes.net (Matthew Barnes) Date: 13 Apr 2004 14:27:19 -0700 Subject: Adding properties to objects References: <3a8e83d2.0404130906.2ea796e9@posting.google.com> Message-ID: <3a8e83d2.0404131327.33dfe92a@posting.google.com> matthew at barnes.net (Matthew Barnes) wrote: > Is it possible to add properties to objects dynamically? So the impression I'm getting is that it's *possible* but not really intended, otherwise there would be better support in the core language. Fair statement? I'll take that as a clue that there's probably a cleaner approach to the problem I'm trying to solve. The feedback was informative... thank you all! Matthew Barnes From gabriel.cooper at mediapulse.com Wed Apr 7 11:17:24 2004 From: gabriel.cooper at mediapulse.com (Gabriel Cooper) Date: Wed, 07 Apr 2004 11:17:24 -0400 Subject: Are line continuations needed? In-Reply-To: <10784c8ps1vsu34@news.supernews.com> References: <407409ef.82801353@news.eircom.net> <40740f99@duster.adelaide.on.net> <10784c8ps1vsu34@news.supernews.com> Message-ID: <40741B84.1070305@mediapulse.com> >Technically, you could have split it at the period, but that >might be even worse in terms of readability. > > or the parenthesis... which affects readability much less than at the period... From donn at drizzle.com Sun Apr 18 14:35:38 2004 From: donn at drizzle.com (Donn Cave) Date: Sun, 18 Apr 2004 18:35:38 -0000 Subject: module not callable - why not? References: <107dras2heahcb6@news.supernews.com><8ef9bea6.0404122025.36efc84e@posting.google.com><7xsmf1fxd9.fsf@ruckus.brouhaha.com> <8ef9bea6.0404180823.7a3bc189@posting.google.com> Message-ID: <1082313337.852341@yasure> Quoth "Fredrik Lundh" : | Hung Jung Lu wrote: | | > In prototype-based OOP, you don't have any of these problems. | | most of those problems don't apply if you're using Python in the "old way". | | it's not like you *need* metaclasses, singleton patterns, | staticmethods/classmethods, or class/module properties to | write rock-solid, easily maintained, efficient, and scalable | Python programs. Python works just fine without them. For that matter, I would rather expect software written without them to be more solid and easily maintained. It seems to me that it is easier to reason about the code you're looking at, when it works within a simply structured system and relies on thoughtful design for its elegance, instead of gimmicks. I doubt it's just historical accident that OOP languages more or less all have the class concept, or the type concept. This is an organizing principle, helpful for human brains. Donn Cave, donn at drizzle.com From usenet_spam at janc.invalid Thu Apr 1 23:07:50 2004 From: usenet_spam at janc.invalid (JanC) Date: Fri, 02 Apr 2004 04:07:50 GMT Subject: GUI Frameworks in Python? References: <8089854e.0403300518.3a180414@posting.google.com> Message-ID: Lars Heuer schreef: > Another problem of Mozilla / XUL is, that you've to switch between > your programming languages: JavaScript for XUL and your favorite > programming language in the back. If your favorite programming lang > is JavaScript, you don't have to switch, of course. ;) But look at what Mozilla.org are planning: -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From seberino at spawar.navy.mil Tue Apr 13 02:07:48 2004 From: seberino at spawar.navy.mil (Christian Seberino) Date: 12 Apr 2004 23:07:48 -0700 Subject: twisted dns server look so easy to set up... am i missing something? does it work? Message-ID: http://twisted.sourceforge.net/TwistedDocs-1.2.0rc2/howto/names.html tells you how to create an authoritative dns server in a few lines!?? This is 10 times easier than bind and/or djbdns. Am I missing something? Does this really work that easily??? Anyone tried it?! Chris From aahz at pythoncraft.com Fri Apr 2 20:11:47 2004 From: aahz at pythoncraft.com (Aahz) Date: 2 Apr 2004 20:11:47 -0500 Subject: PEP 328: Imports: Multi-Line and Absolute/Relative References: <2c60a528.0403150152.6af7f53f@posting.google.com> Message-ID: In article , Dieter Maurer wrote: > >Python explicitely adds the directory it finds a script in to the front >of "sys.path". I think it does this because it expects a high >chance that the script *needs* to access modules in this directory. Actually, that's not quite true. If the script is in the current directory, Python prepends "''" to sys.path, which means that you'll have problems if you use os.chdir(). >What about inventing a syntax for absolute imports as well (and let the >behaviour of unadorned imports as it is now). Because absolute imports are the common case. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "usenet imitates usenet" --Darkhawk From dolzenko at rsu.ru Thu Apr 1 11:16:27 2004 From: dolzenko at rsu.ru (Eugeni Doljenko) Date: Thu, 1 Apr 2004 20:16:27 +0400 Subject: Microsoft making Python.NET References: Message-ID: <012f01c41804$af9e75f0$b0fcd0c3@cooler> "April Fools! But This One Is Real ..." Don't you think you're faked? ----- Original Message ----- From: "Greg" Newsgroups: comp.lang.python To: Sent: Thursday, April 01, 2004 6:56 PM Subject: Microsoft making Python.NET > The following article from microsoft describes a workaroind for a bug > in hte beta version of VISUAL PYTHON DOT NET > > http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnaskdr/html/askgui04032001.asp > > When did microsoft put python into the visual studio beta? How did > this not make big news in developmnt circles? > > A.E. > > > > Here is the body of the article: > > FIX: Memory Leak after pickling in Visual Python .NET Beta 1 > > View products that this article applies to. > This article was previously published under Q114345321 > IMPORTANT: This article contains information about modifying the > registry. Before you modify the registry, make sure to back it up and > make sure that you understand how to restore the registry if a problem > occurs. For information about how to back up, restore, and edit the > registry, click the following article number to view the article in > the Microsoft Knowledge Base: > > 114345321/8 Description of the Microsoft Windows Registry > > SYMPTOMS > When pickling an object containing a cyclic graph, the Visual Python > .NET Beta 1 can create references that will not be garbage collected. > > CAUSE > Visual Python .NET Beta 1 does not impose a recursion limit by > default. In this mode, an objects references are evaluated lazily > durring pickling. If the garbage collector runs durring this process, > some objects can be incorrectly referenced. > The failure is due to registry key data that was installed by Visual > Python .NET Beta 1. > > RESOLUTION > WARNING: If you use Registry Editor incorrectly, you may cause serious > problems that may require you to reinstall your operating system. > Microsoft cannot guarantee that you can solve problems that result > from using Registry Editor incorrectly. Use Registry Editor at your > own risk. > > Open Regedit.exe and browse to > HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\8.0\P++\RecursionLimit. > To be safe, back up this registry key: From the File menu, click > Export and save the key to an .reg file. > Set the RecusionLimit key from 0 to 1000. > > STATUS > Microsoft has confirmed that this is a bug in the Microsoft products > that are listed at the beginning of this article. This bug will be > corrected in Visual Python .NET (2004). > > The information in this article applies to: > Microsoft Visual Studio .NET 8.0, Beta 1 > > > -- > http://mail.python.org/mailman/listinfo/python-list From anand at easi.soft.net Mon Apr 19 07:50:34 2004 From: anand at easi.soft.net (Anand K Rayudu) Date: Mon, 19 Apr 2004 17:20:34 +0530 Subject: COM & Python Message-ID: <4083BD0A.1030700@easi.soft.net> Hi all, I want to use python with COM extension. I am successful using python as client. I could interact to my application through COM interfaces from python. I also want to use the win32ui layer, which wrapped all MFC user interface functionality. I am just wondering if some on can guide me with some documentation on using them. I want to know how the call backs are handled in particular. Any sample code will be a great start for me. If this is possible I can create any dialog boxes with any controls from python itself!! :-) And take advantage of MFC's View , scroll view and so on. Just exciting!! Thanks in advance, Anand From python at simon.vc Fri Apr 16 11:26:46 2004 From: python at simon.vc (SimonVC) Date: 16 Apr 2004 08:26:46 -0700 Subject: Embeded python without filesystem References: Message-ID: Maybe have a look at Pippy, which is python for the Palm. As i understand it there is no file system on the Palm. http://pippy.sf.net Cheers VC Jacek Cz wrote in message news:... > Do you have some tips about making Python small (minimal list of > modules) and isolated from filesystem. I have an idea > > #define Py_WITHOUT_FILES > This switch should disable some function/modules from modules sys, > fileobject, but also import from file, path resolving etd. From newsgroups at jhrothjr.com Mon Apr 26 13:38:28 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 26 Apr 2004 13:38:28 -0400 Subject: Is Perl *that* good? (was: How's ruby compare to it older bro References: Message-ID: <108qi9dno1cfnd4@news.supernews.com> "Skip Montanaro" wrote in message news:mailman.25.1082997844.25742.python-list at python.org... > > Peter> I guess it would be interesting to pose the question back to them > Peter> "If you could not use regexes in Perl, would you still like to > Peter> program in it?" or "If you couldn't use mysql in PHP would you > Peter> still use it?" > > Peter> What similar question, if any, would be a difficult one for us > Peter> Python types? > > "If Python didn't support indentation-based block structure would you still > use it?" > > :-) I probably wouldn't have learned it - indentation based block structure has been one of my "nice to have" things from at least the middle '70s, so when I saw it in Python, I learned it to see how it ran, and haven't looked back. However, it's not the reason I stay with it. John Roth > > Skip > > From claird at lairds.com Sat Apr 3 18:12:51 2004 From: claird at lairds.com (Cameron Laird) Date: Sat, 03 Apr 2004 23:12:51 -0000 Subject: emergent/swarm/evolutionary systems etc References: Message-ID: <106uh7jjgf8aebe@corp.supernews.com> In article , Peter MacKenzie wrote: . . . >Fortunately, I've found an online textbook at >http://www.ibiblio.org/obp/thinkCSpy/index.htm, which appears better suited >to my needs than the standard python documentation, and may alleviate some >of the conceptual and syntactical difficulties I've been experiencing. . . . *Thinking ... with Python* isn't in opposition to "the standard Python documentation"; it's complementary. As you perhaps expect, computing is sufficiently ramified to have its own culture. It is VERY common for good, well-regarded, high-status, ... practitioners to be *aware* of "standards", without having *learned* from them, or having learned only highly-specialized material. MANY of the regulars in this newsgroup applaud and have benefitted from *Think- ing ...*. More broadly, no right-thinking Pythoneer says to newcomers, "read 'the standard Python documentation'." We *do* have the habits of recommend- ing the canonical tutorial, *Thinking ...*, and, depending on ones background and aims, several other tutorials and books. You're doing fine. Don't think you have to read "the references" for now; you're OK with "tutorials". -- Cameron Laird Business: http://www.Phaseit.net From sdahlbacSPAMSUCKS at abo.fi Wed Apr 28 17:21:09 2004 From: sdahlbacSPAMSUCKS at abo.fi (Simon Dahlbacka) Date: Thu, 29 Apr 2004 00:21:09 +0300 Subject: wxpython + py2exe + innosetup In-Reply-To: References: <408eca0c$1@newsflash.abo.fi> <30260531.0404272030.3fe52362@posting.google.com> Message-ID: <40902053@newsflash.abo.fi> Thomas Heller wrote: > sdahlbac at abo.fi (Simon Dahlbacka) writes: > > >>simoninusa2001 at yahoo.co.uk (simo) wrote in message news:<30260531.0404272030.3fe52362 at posting.google.com>... >> >>>"Simon Dahlbacka" wrote: >>> >>> >>>>I'm "exefying" an application that uses wxpython, some com to control excel >>>>and word and want to distribute this application. >>>> >>>>after creating the executable with py2exe, it still works fine (at least on >>>>my development machine), however, if I create an installer package with >>>>innosetup, install it and try to run it, I get a busy cursor for a split >>>>second and then.. nothing. no errors no traceback no nothing.. viewing >>>>dependencies does not reveal anything strange, and running the installed >>>>program in a debugger just tells that the application has exited with code >>>>0. > > >>another strange thing is that I tried to sprinkle "print I got here >>statements" all over the place, but didn't see any of those, even >>running from a console. > > > If you build it as windows program (not console), sys.stderr is > redirected to a logfile, and sys.stdout is redirected into the eternal > bitsink. This is to prevent IO errors in your debug print statements, > or when tracebacks are printed. The code which does this is in > py2exe/boot_common.py for your inspection and/or improvements. > > You can also override this default behaviour by assigning your own > objects to sys.stdout and sys.stderr. > > Unfortunately, this very code in py2exe 0.5.0 has a bug, which will be > triggered when the sys module is *not* imported in your main script (the > 'sys' symbol is deleted too early in boot_common.py). > > So, it could be that your program tries to report something, and then > 'crashes' (meaning: fails to initialize). > > I will release py2exe 0.5.1 later this week, which should have fixed > this and other bugs ;-). > > > What I usually do to find out why a program behaves strange, is to build > both a console *and* a windows version (with different names, say > app_c.exe and app.exe). Then, you can (even on the target machine) run > the console version to see the debug prints, and after you have found > and fixed potential problems, run the windows version and delete the > console version again. Or you simply don't create a shortcut for the > console version. hmm, I added a bogus "import sys" and removed zipfile="lib\common.zip" from the setup script, which seemed to generate strange results, py2exe generated lib\shared.zip and installing * from that directory _somehow_ produced lib\common.zip in the install dir (I have absolutely NO clue..), removing that line produces all files in the same directory, which SEEM to work after the little testing I have done, (except the no codecs found, which can be solved by adding encodings, OTOH, I cannot get Mark's solution (from py2exe wiki) to work with 'encodings', 'encodings.latin_1' to just get latin-1 encodings. I'm probably just too stupid to get it or something.. /Simon From johnbunderwood at yahoo.ca Wed Apr 7 08:38:27 2004 From: johnbunderwood at yahoo.ca (John Underwood) Date: Wed, 07 Apr 2004 08:38:27 -0400 Subject: Using python23 to develop an extension for an application that has python22 embedded References: <1073eeubflmchd5@corp.supernews.com> Message-ID: On Tue, 6 Apr 2004 22:02:49 +1000 (EST), Andrew MacIntyre wrote: >On Mon, 5 Apr 2004, John Underwood wrote: > >> Since I do have python23.dll and python23_d.dll (from a successful >> build of 2.3), can I use these to develop an extension for the >> aforementioned commercial application if I stay away from any new >> features in 2.3 (but not in 2.2)? > >You can do the development, but you won't be able to directly distribute >the resulting extension because it will have been linked with python23.dll >when it needs to be linked with python22.dll. > >To make things easier to fudge later, you make sure that your extension is >Distutils'ified from the beginning. > >You can then use another compiler supported by the Distutils (MS CL >non-optimising compiler, MinGW, Borland etc) to build the distributable >extension in either a Python 2.2 or 2.3 installation, without risking >mixing C runtime library mismatches (VS.NET uses a different CRT than >VS6 I understand). If using a 2.3 installation, you'll need to substitute >a 2.2 import library when building the final distributable version. > >The Distutils setup.py script can then provide the installation harness. Thanks for the advice. I have a Borland compiler that I'll try with Disutils. From __peter__ at web.de Thu Apr 29 12:31:01 2004 From: __peter__ at web.de (Peter Otten) Date: Thu, 29 Apr 2004 18:31:01 +0200 Subject: Generic constructors and duplication of internal Python logic References: <87ekqq41ya.fsf@pobox.com> <87oepnzlbp.fsf@pobox.com> <87k707elth.fsf@pobox.com> <87smetxjjj.fsf@pobox.com> Message-ID: John J. Lee wrote: >> Peter Otten wrote: >> def setLocals(d, selfName="self"): >> self = d.pop(selfName) >> for n, v in d.iteritems(): >> setattr(self, n, v) >> >> class Demo(object): >> def __init__(self, foo, bar, baz=2, bang=3): >> setLocals(locals()) > > Perfect! About a hundred times better than my solution. Maybe this > should be a Python Cookbook entry? Did that: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/280381 Peter From mk at net.mail.penguinista Thu Apr 8 07:16:53 2004 From: mk at net.mail.penguinista (=?UTF-8?B?0LTQsNC80ZjQsNC9INCzLg==?=) Date: Thu, 08 Apr 2004 13:16:53 +0200 Subject: My firefox script References: Message-ID: <407534a5@news.mt.net.mk> > Hi. I use mozilla firefox on linux. It's a great browser, but the *nix > version has an annoying problem, that it won't let you open a new > instance from the desktop if the browser is already running. search freshmeat.net for "MSS" -- ?????? (jabberID:damjan at bagra.net.mk) Where do you think you're going today? From peter at engcorp.com Thu Apr 8 09:37:10 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 08 Apr 2004 09:37:10 -0400 Subject: Customizing the python search path depending on source directory In-Reply-To: <5cf809e9.0404071734.26f1078a@posting.google.com> References: <5cf809e9.0404061853.41cd3c85@posting.google.com> <5cf809e9.0404070452.643b7053@posting.google.com> <5cf809e9.0404071734.26f1078a@posting.google.com> Message-ID: <4dudnVzbRvwbyOjdRVn-sw@powergate.ca> Peter Schwalm wrote: > Does the output look different if you run these programs in your > environment? It may take me a moment to get the precise same configuration on my machine, because I don't have it set up to execute .py scripts automatically at the command line just by typing their names. I have to manually invoke "python" and pass it the name of the script. Therefore, before I do this (I need to learn how, first), can you confirm that you get identical results if in each place where you typed "test1.py" you instead typed the equivalent with, for example, "python test1.py"? It's possible Windows' technique for directly invoking scripts your way screws up the sys.path stuff... (I _am_ using "stock" Python 2.3.3 on XP, by the way. I doubt ActiveState's behaves any different in this respect.) -Peter From jcm at FreeBSD-uk.eu.org Tue Apr 27 09:52:07 2004 From: jcm at FreeBSD-uk.eu.org (Jonathon McKitrick) Date: Tue, 27 Apr 2004 14:52:07 +0100 Subject: Problem binding and events Message-ID: <20040427135207.GA5359@dogma.freebsd-uk.eu.org> I have a listbox with bound to bring up an edit dialog. But and do not work. I have a debug print statement, and the program never reaches the event handler. I've tried handlers with 'event' arguments and with no arguments, but neither works. Is there something I am missing here? jm -- My other computer is your Windows box. From SeeBelow at SeeBelow.Nut Tue Apr 13 15:25:29 2004 From: SeeBelow at SeeBelow.Nut (SeeBelow at SeeBelow.Nut) Date: Tue, 13 Apr 2004 19:25:29 GMT Subject: Very Interesting Project for Python Person Message-ID: <407C3EC6.46EF0BC5@shaw.ca> This is part of an open source project at SourceForge. The Python program would have to call some methods that were compiled from C source code. We need someone to add graphics & GUI to an existing C program. The main program, graphics & GUI would be python/tKinter. The graphics would show the path of a virtual sailboat, which has a robot at the helm. The robot is actually an Artificial Neural Network (ANN). We use neuroevolution to discover a competent ANN yachtsman. Visit the URL below to learn more; especially the sourceforge link. Mitchell Timin -- "Many are stubborn in pursuit of the path they have chosen, few in pursuit of the goal." - Friedrich Nietzsche http://annevolve.sourceforge.net is what I'm into nowadays. Humans may write to me at this address: zenguy at shaw dot ca From stach at fr.pl Fri Apr 16 08:00:08 2004 From: stach at fr.pl (Krzysztof Stachlewski) Date: Fri, 16 Apr 2004 14:00:08 +0200 Subject: md5.hexdigest() converting unicode string to ascii References: <77b925de.0404151450.5c1f720a@posting.google.com> Message-ID: "uebertester" wrote in message news:77b925de.0404151450.5c1f720a at posting.google.com... > I'm trying to get a MD5 hash of a registry key value on Windows 2000 > Server. The registry value is a string which is stored as a unicode > string. I can get the registry key value and pass it to md5 via > update(), however, hexdigest() returns a hash value for the ascii > equivalent of the unicode string. Not the hash of the unicode string > itself. I've verified this by creating a text file containing an > ascii form of the string and one containing a unicode form of the > string. The hash returned by md5.hexdigest() matches that when I run > md5sum on the ascii file. The md5() function is defined on character strings not on unicode strings. An unicode string is a sequence of integers. Such sequence may be converted to a character string, but there are many different methods of doing that. In Python you convert an unicode string to a character string by using encoding of your choice. For instance: u"abcd".encode("utf-16") utf-16 is just an example - you have to decide which encoding to choose. Stach From martin at v.loewis.de Mon Apr 19 01:29:02 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 19 Apr 2004 07:29:02 +0200 Subject: using a USB HID device In-Reply-To: References: <40827ce3.1151345337@news.xs4all.nl> <4082e29d.1177387563@news.xs4all.nl> Message-ID: Jeff Epler wrote: > libusb is portable to Linux, BSD including OS X, and Windows. > I don't know of a Python wrapper, however, and my experience using > libusb on windows is limited. > > http://libusb.sf.net > http://libusb-win32.sf.net/ It looks like libusb, on Windows, installs its own kernel driver, which generates devices named \\.\libusb*. So this is not exactly a pure-python solution :-) OTOH, it may well be that USB devices, on Windows, cannot be accessed purely from user mode, and that you always need some sort of kernel driver. Regards, Martin From alex.garel at free.fr Fri Apr 9 17:54:02 2004 From: alex.garel at free.fr (Alex Garel) Date: Fri, 09 Apr 2004 23:54:02 +0200 Subject: how to know who calls a method Message-ID: <40771b75$0$15656$626a14ce@news.free.fr> Hello, Maybe it's a strange question. I heard that salltalk use messages that are sent from one object to another. It seems in other OO languages, method call is quite an implementation of that. The only thing is, the receiver (instance which method is being called) can't retrieve reference of the sender. Is it possible in Python ? Is there a standard way or a workaround. I think about using frame stack (in module inspect) but it only gives me the name of the function from which I was called, not a reference to the object. Why am I asking for such a feature ? It is because I would like an object to be aware of another object reading it so it can signal future change in its value to the last. I can use a getter which precise who is the reader but my attempt was to be able to use a normal getter (x=y) in a Phytonic fashion ! From alloydflanagan at comcast.net Wed Apr 7 18:26:15 2004 From: alloydflanagan at comcast.net (A. Lloyd Flanagan) Date: 7 Apr 2004 15:26:15 -0700 Subject: Does Python compete with Java? References: <8b336527.0404051337.51bb4a1b@posting.google.com> Message-ID: Greg Ewing wrote in message news:... > > I think it's a *good* thing. Python is succeeding very well > by just existing and actually being well designed and useful, > as opposed to having a large company's marketing machine trying > to tell everyone that it is. > Very true. In addition, I think python will gain a lot of "mind-share" as more and more popular applications are written in python. From mgerrans at mindspring.com Sat Apr 10 03:28:32 2004 From: mgerrans at mindspring.com (Matt Gerrans) Date: Sat, 10 Apr 2004 07:28:32 GMT Subject: Parsing cmd line args problem References: <1081555827.877735@jubilee.esoterica.pt> <1081566459.617750@jubilee.esoterica.pt> Message-ID: "Paulo da Silva" wrote: > I got it to work! Is there a better way? Yup. If you're using Python 2.3, then check out the optparse module, if an older vesion, getopt. I didn't like getopt that well, so slapped together something that allowed me to access options in a script like this: from options import opts,env,anyopt,params if opt.verbose: print 'starting' if opt.logfile: logfilename = opt.logfile debug = anyopt.debug if debug: print 'Running under %s's account...' % env.username for param in params: dostuff(param) # ... etc. If an option was specified on the command line as "/o" then opt.o will be True. If an option was specified as "/log:test.log" then opt.log will be "test.log". env gives the same shortcut for environment variables and anyopt gives a combo of the two (so if you specify /debug, or set the debug environment variable it is turned on). params are what remain on the command line after removing argv[0] and all items prefixed with '/' or '-'. The idea was to get consistent command line handling that was very quick and easy to use. I still like this for quick and simple scripts. The weakness is that it is more dynamic, so it doesn't do nifty things like optparse, where it automatically displays command line syntax. - Matt FYI, below is my options.py, but you should probably learn the optparse module, if you're on Python 2.3: """ Three handy instances options classes are contained herein: 1) opts - Command line options. 2) env - Environment 'options'. 3) anyopt - Either command line or environment options (command line options). 4) params - List of non-option command line paramters. """ import os,sys from glob import glob # These are the non-option parameters (like filenames, etc.): params = filter(lambda a:a[0] not in '-/', sys.argv[1:]) #--------------------------------------------------------------------- # FindCommandLineOption() # #--------------------------------------------------------------------- def FindCommandLineOption( opt, caseSensitive = 0 ): """Finds simple (/s) and parameterized (/f:file.ext) options. Returns 1 if a simple option is found, returns the value of an option that specifies on (eg. /f:filename.ext returns filename.ext'. If None is specified, it returns 1 if no parameters were specified.""" result = 0 import sys import string if caseSensitive: case = lambda s: s else: case = string.lower if opt == None: # Special case for None; if none, then we want to if len(sys.argv) == 1: # check whether there were no parameters. result = 1 else: for i in sys.argv[1:]: if i[0] == '-' or i[0] == '/': curOpt = i[1:] if case(opt) == case(curOpt): result = 1 elif ':' in curOpt: parts = string.split(curOpt,':') if case(opt) == case(parts[0]): result = string.join(parts[1:],':') # put together the rest of the parts return result class CommandLineOptions(object): """Like the EnvironmentVariables object, this object gives you a clean and simple interface to the command line options. Here is how you would check for the /v (or -v) option on the command line: opts = CommandLineOptions() if opts.v: print 'You chose the verbose option!' And here is how you would get a file specified by /f:filename: if opts.f: if os.path.isfile(opts.f): filename = opts.f else: print "Who you kiddin'? %s is not a valid file!" % opts.f """ def __getattr__(self, name): if name == 'help' and FindCommandLineOption('?'): return FindCommandLineOption('?') return FindCommandLineOption(name) def __getitem__(self,name): return self.__getattr__(name) opts = CommandLineOptions() #--------------------------------------------------------------------- # EnvironmentVariables # # Need to either inject them into the current scope, or create an object # which has a member for each var. I like the latter, as it is cleaner, # and will avoid hosing locals by using its own namespace. #--------------------------------------------------------------------- class EnvironmentVariables(object): def x__init__(self): import os import string for x in os.environ.keys(): name = string.lower( string.join(string.split(x)) ) exec( "self." + name + "='" + os.environ[x] + "'" ) def __getattr__(self, name): if os.environ.has_key(name): return os.environ[name] else: name = name.replace('_',' ') return os.environ.get(name,'') def __getitem__( self, key ): return os.environ.get(key,'') env = EnvironmentVariables() #--------------------------------------------------------------------- # AnyOption # # Culls options from the command line and the environment variables. #--------------------------------------------------------------------- class AnyOption(object): def __getattr__(self, name): result = opts.__getattr__(name) if not result: result = env.__getattr__(name) return result def __getitem__( self, key ): 'Allows dictionary syntax' result = opts[key] if not result: result = env[key] return result anyopt = AnyOption() #-------------------------------------------------------------------------- # ArgFiles() # # Gets all the files specified on the command line, via wildcards. Also # looks for the /r or /s option, then does a recursive collecting of them. # # It would be a little cleaner if this were a variable, like the others, # instead of a function, but the possibility of a mosterous task resulting # from an innocent command line (eg. "MyProg c:\\*.*' /s") precludes that. # So, this is a generator, allowing the caller not to get stuck in a # long-waiting no-status display situation. #-------------------------------------------------------------------------- def ArgFiles(args=None): files = [] if args == None: args = params for filespec in args: if filespec[0] == '/': continue if opts.r or opts.s: startdir,spec = os.path.split(filespec) for d,subdir,files in os.walk(startdir): for f in glob( os.path.join( d, spec ) ): yield f else: for f in glob(filespec): yield f From bjornhb3 at yahoo.se Sat Apr 3 09:33:05 2004 From: bjornhb3 at yahoo.se (Bjorn Heimir Bjornsson) Date: Sat, 3 Apr 2004 14:33:05 +0000 (UTC) Subject: Verifying temporal properties. Need problems. References: <68771ca.0404010839.39b0c24f@posting.google.com> Message-ID: Hello Loic I'm working with control flow only, generating pushdown systems from the AST that are then checked with the model checker Moped (using LTL properties). A similar approach was taken for JavaCard (http://www.sics.se/fdt/vericode/jcave.html). I chose Python for fun, but at the moment support just a limited subset. I'm unsure how far I will/can go. E.g. some dynamic stuff can't be analysed statically. I also just ignore all data flow, which simplifies everything but means I will not recognise all control flow correctly. I checked some small non-python-specific problems, but experience of others suggest that the aproach scales quite well. This is an MSc thesis, I haven't published anything else. Bjorn From rick.ratzel at magma-da.com Tue Apr 20 01:27:41 2004 From: rick.ratzel at magma-da.com (Rick L. Ratzel) Date: Tue, 20 Apr 2004 05:27:41 GMT Subject: Getting output from embedded python program References: <2aa196bb.0404190554.74631058@posting.google.com> Message-ID: <4084B179.6020807@magma-da.com> Kim wrote: > Hi everyone, > I'm writing a embeded python program, and I want to evaluate some > expression by calling function: > > PyRun_SimpleString("print 'hello'") > > I don't want to output it to stdout but putting it into string somehow > sothat I can process it. > Here is a way to get the result of a Python expression eval from C (derived from example at http://elmer.sourceforge.net/PyCon04/elmer_pycon04.html ) ...obviously, if you evaluate a print statement, you will still get output on stdout though: ... PyObject* evalModule; PyObject* evalDict; PyObject* evalVal; char* retString; PyRun_SimpleString( "result = 'foo' + 'bar'" ) evalModule = PyImport_AddModule( (char*)"__main__" ); evalDict = PyModule_GetDict( evalModule ); evalVal = PyDict_GetItemString( evalDict, "result" ); if( evalVal == NULL ) { PyErr_Print(); exit( 1 ); } else { /* * PyString_AsString returns char* repr of PyObject, which should * not be modified in any way...this should probably be copied for * safety */ retString = PyString_AsString( evalVal ); } ... In this case, you need to know that the expression will evaluate to a string result in order to call PyString_AsString(). If you don't know this, you will have to check the type of the PyObject first. From rpgnmets at aol.com Wed Apr 21 21:52:07 2004 From: rpgnmets at aol.com (Rob Renaud) Date: 21 Apr 2004 18:52:07 -0700 Subject: This is very simple question References: Message-ID: <3759308d.0404211752.225ef92a@posting.google.com> "Fredrik Lundh" wrote in message news:... > but a lousy subject. > > "Eric" wrote; > > > I would want to obtain a list of factors (multiples of 2) given a > > prime number in python. > > > > For example 13=[8,4,1], 5=[4,1], 7=[4,2,1], 15=[8,4,2,1] > > >>> 8*4*1 > 32 > > > I would appreciate a fuction which would do this. > > def func(x): return [2**i for i in range(3,0,-1) if x & 2**i] > > The code is buggy, it won't work for odd numbers... >>> func(5) [4] >>> def func(x): return [2**i for i in range(3,-1,-1) if x & 2**i] ... >>> func(5) [4, 1] But this still leaves us with numbers which are too big. >>> func(243) [2, 1] So this should take care of it... >>> def func(x): return [2**i for i in range(int(math.log(x)/math.log(2)),-1,-1) if x & 2**i] >>> func(323421234) [268435456, 33554432, 16777216, 4194304, 262144, 131072, 65536, 1024, 32, 16, 2] >>> sum(func(323421234)) 323421234 From michele.simionato at poste.it Wed Apr 28 10:37:12 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 28 Apr 2004 07:37:12 -0700 Subject: Why we will use obj$func() often References: <40887145.789A2FE8@alcyone.com> <7cki80hj976bia36lhf9er97v073o1pqvm@4ax.com> <5vJjc.13116$Qy.1954@fed1read04> Message-ID: <95aa1afa.0404280637.595046e8@posting.google.com> "Mark Hahn" wrote in message news:<5vJjc.13116$Qy.1954 at fed1read04>... > I feel strongly that the Python mixture of declaration (global), default > (where assigned) and broken (closures) is broken overall and has to be fixed > in Prothon. I take this as a given. So I see these possible solutions: > > 1) My Ruby-like symbols, which I think are readable and fast-compilable. > > 2) Word-like symbols, which are large, less readable (too me) and > cluttering. > > 3) Declarations, which cause the compiler and user to look around and are > not Pythonic. > > Am I missing any other solutions? You can use a different assignement syntax for outer scope variables; for instance in Scheme there is "set!" which can do that. BTW, I do not think the ability to have read-write closures is that useful in an OOP language; just use objects. I would ignore this "issue". OTOH, I do agree that Python scope rules are not 100% perfect, but I would content myself with changing the rule for "for" loops (see http://groups.google.it/groups?hl=it&lr=&ie=UTF-8&oe=UTF-8&threadm=95aa1afa.0402272327.29828430%40posting.google.com&rnum=1&prev=/groups%3Fhl%3Dit%26lr%3D%26ie%3DUTF-8%26oe%3DUTF-8%26q%3Dsimionato%2Bscope%2Brules%26btnG%3DCerca%26meta%3Dgroup%253Dcomp.lang.python.*) Michele Simionato From t-meyer at ihug.co.nz Thu Apr 29 19:36:54 2004 From: t-meyer at ihug.co.nz (Tony Meyer) Date: Fri, 30 Apr 2004 11:36:54 +1200 Subject: MATLAB2Python In-Reply-To: <1ED4ECF91CDED24C8D012BCF2B034F13060E4F12@its-xchg4.massey.ac.nz> Message-ID: <1ED4ECF91CDED24C8D012BCF2B034F1304677D10@its-xchg4.massey.ac.nz> > An indication that Python takes the interests of beginning > programmers more seriously than those of experienced > scientific programmers is that integer division is going to > be redefined in future versions of the language -- 2/3 = 1 > now but will equal 1.5 in the future. (I think you are > supposed to use 2//3). This is almost right :) >>> 2/3 0 >>> 2//3 0 >>> from __future__ import division >>> 2/3 0.66666666666666663 >>> 2//3 0 I think maybe 3/2 or 3//2 was the intent :) =Tony Meyer From jacek.generowicz at cern.ch Mon Apr 5 04:18:30 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 05 Apr 2004 10:18:30 +0200 Subject: Python is faster than C References: <406F0907.96F37EA1@tunes.org> Message-ID: "Michel Claveau/Hamster" writes: > Yes, but Psyco is writted in C & Python, and it use an C module. > Said "Psyco is faster than C", it's like said "Psyco is faster than Psyco". You appear to be missing the point completely. The language used to implement the tools you use is irrelevant. What is important is the language in which you are programming. Armin's point is that (in certain circumstances) you can achieve a significant speedup by one of two ways - Recode some Python code in C - import psyco; psyco.full() Note: in the second case, this is _all_[*] you have to do; it takes about 2 seconds of work. In the first case it take many hours/days/weeks of tedious and error-prone work. The point is: Why code in C when you can get just as good program speed performance by coding in Python. Put another way: Why code in a low-level, tedious, rigid, error-inducing language, when you can get just as good program speed performance by writing in a high-level, flexible, dynamic, pleasant language. [*] Yes, I'm deliberately keeping things simple in order not to draw attention away from the real point. From bucknuggets at yahoo.com Sun Apr 4 14:39:09 2004 From: bucknuggets at yahoo.com (Buck Nuggets) Date: 4 Apr 2004 11:39:09 -0700 Subject: IBM Developerworks: Learn how to write DB2 JDBC tools in Jython References: <3ea34487.0404031654.596cbd06@posting.google.com> Message-ID: <66a61715.0404041039.2972d92b@posting.google.com> workingdudetor at yahoo.com (Neo) wrote in message news:<3ea34487.0404031654.596cbd06 at posting.google.com>... > Java Libraries + Python Syntax > > > ttp://www-106.ibm.com/developerworks/db2/library/techarticle/dm-0404yang/index.html It's always nice to see more support for agile languages with db2. I know that there's a ton of support for java, but frankly I'm far more interested in seeing db2 for fast-moving tiger-teams than for slow-moving and massive projects. With that in mind great support for python, ruby, php, perl, etc is essential. ks From dietmar at schwertberger.de Mon Apr 19 16:04:02 2004 From: dietmar at schwertberger.de (Dietmar Schwertberger) Date: Mon, 19 Apr 2004 22:04:02 +0200 Subject: MS Project (XML-) file generation Message-ID: Hi! I would like a Webware server to deliver MS Project compatible files for download. Of course I could create files using COM automatisation. For reliability reasons I would prefer not to run an application like Microsoft Project on the server. I think it would be the best to create an XML file. Basically it should be quite simple: - save an empty project file as XML - load this using e.g. minidom - add a node for each task (name, start date, duration) - link the nodes for linked tasks Did anybody do this before? Are there any examples for download (either Project or Word, Excel,...). (My experience with MS Project as well with XML is almost zero.) Regards, Dietmar From ramen at lackingtalent.com Tue Apr 6 15:54:47 2004 From: ramen at lackingtalent.com (Dave Benjamin) Date: Tue, 06 Apr 2004 19:54:47 -0000 Subject: Compact Python library for math statistics References: Message-ID: In article , Chris Fonnesbeck wrote: > Gerrit wrote in message news:... >> wrote: >> > I'm looking for a Python library for math statistics. This must be a cl >> ear set of general statistics functions like 'average', 'variance', 'cova >> riance' etc. >> >> The next version of Python will have a 'statistics' module. It is >> probably usable in Python 2.3 as well. You can find it in CVS: >> >> http://cvs.sourceforge.net/viewcvs.py/*checkout*/python/python/nondist/sa >> ndbox/statistics/statistics.py >> >> I'm not sure whether it's usable in current CVS, though. You may have to >> tweak it a little. > > I'm hoping there will be more functions added to this module (e.g. > median, quantiles, skewness, kurtosis). It wouldnt take much to > include at least the basic summary stats. I would be more than happy > to contribute. I'd really like to see linear regression in the Python stats module. I've used the one from stats.py successfully - this may be a good source of ideas, too: http://www.nmr.mgh.harvard.edu/Neural_Systems_Group/gary/python.html (see stats.py) (apologies if this has already been pointed out somewhere) -- .:[ dave benjamin: ramen/[sp00] -:- spoomusic.com -:- ramenfest.com ]:. : please talk to your son or daughter about parametric polymorphism. : From dmq at gain.com Fri Apr 23 13:45:00 2004 From: dmq at gain.com (David MacQuigg) Date: Fri, 23 Apr 2004 10:45:00 -0700 Subject: Why we will use obj$func() often References: <84Uhc.22278$dZ1.5087@fed1read04> <8AWhc.23114$dZ1.11070@fed1read04> <40883BFE.B381518A@alcyone.com> <27_hc.23801$dZ1.2716@fed1read04> <40887145.789A2FE8@alcyone.com> Message-ID: <7cki80hj976bia36lhf9er97v073o1pqvm@4ax.com> On Thu, 22 Apr 2004 18:28:37 -0700, Erik Max Francis wrote: >Mark Hahn wrote: > >> Well, I do tend to exaggerate a bit. I can understand it when I study >> it, >> but in everyday coding it does not roll off my fingers. Also, it is >> possible to design something new without understanding the old. > >It is _possible_. But it is not a very good idea. > >> I am serious when I say I think that Python has headed off into >> egghead land >> a bit and I feel that keeps a lot of people from switching to it. I >> think >> that this heady stuff scares them off. I really am trying to make >> things >> simpler in Prothon. Now, whether I can succeed or not is another >> question. >> Only time will tell. > >Other than the basic premise of Prothon, every single decision I've seen >you make (or consider) looks wholly stylistic, awkward or even arcane, >and the opposite of the one I, or I think Guido, would have chosen. >Being a fan of Io, I think prototype-languages are interesting. Even so >far, I lost interest in looking at the actual main feature of Prothon, >after seeing all the extra baggage that was brought on in unecessary >stylistic changes. > >Seriously considering every single possible proposal is not >constructive. Without a strong sense of what the language should look >like, Prothon is going to continue to look more and more like Perl. >It's already most of the way there. Mark: """ Please hold off your ad hominem attacks until the product is designed, thank you very much. """ I would take this as constructive criticism, not an ad-hominem attack. -- Perl-like syntax: Special symbols and capitalization to indicate variable scope, closures, dynamic variables, etc. local, Global, .x, ^x, X, &x, x, @x Adding syntax or making changes just because it allows you to do something that can't be done in Python is not good. We have to look at *use cases* for these features and compare them to a well-written Python equivalent. Then, we can see if the benefit is worth the extra syntax. We spend far to much time debating syntax without a clear benefit in mind. Show us a nice closure. -- Special syntax to indicate binding of functions. Python solves this problem neatly, at the expense of some implicitness. bound_func = cat1.func # cat1 is an instance unbound_func = Cat.func # Cat is a class Prothon's insistence on having not a trace of class-like behavior has opened a can-of-worms. Iron out the wrinkles on one place and they pop up in another. == Benefits of Prothon == In spite of these criticisms I do believe Prothon has made a big contribution in the *simplification* of classes. There are also some smaller items worth looking at ( break tags, uniform syntax for mutation!, boolean?, ... ) -- Dave From FBatista at uniFON.com.ar Wed Apr 28 09:46:42 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Wed, 28 Apr 2004 10:46:42 -0300 Subject: Path ... where is my application's home dir? Message-ID: [Marco Aschwanden] #- I want to store a file in the application directory. What is #- the easiest #- way to figure out, where my application is situated? You don't need that, just save it without a path and it'll fall in your current directory. But if you need it for something else: >>> import os.path >>> os.path.curdir '.' >>> os.path.abspath(os.path.curdir) 'C:\\temp' . Facundo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA La informaci?n contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener informaci?n confidencial o propietaria, cuya divulgaci?n es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no est? autorizado a divulgar, copiar, distribuir o retener informaci?n (o parte de ella) contenida en este mensaje. Por favor notif?quenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magn?tico) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telef?nica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electr?nicos pueden ser alterados, motivo por el cual Telef?nica Comunicaciones Personales S.A. no aceptar? ninguna obligaci?n cualquiera sea el resultante de este mensaje. Muchas Gracias. -------------- next part -------------- An HTML attachment was scrubbed... URL: From michael at foord.net Fri Apr 9 03:53:22 2004 From: michael at foord.net (Fuzzyman) Date: 9 Apr 2004 00:53:22 -0700 Subject: Wrapper round x86 Assembler Message-ID: <8089854e.0404082353.7bf163a2@posting.google.com> There might be a really good reason why this hasn't been done *or* someone might have done it and I just can't find it..... *but* what about a wrapper to an assembler (presumably for x86 assembly !) !! I just wrote some code doing binary operations which would have been about a zillion times faster in a few lines of assembly code. I also have fond memories of programming in BBC Basic which had an inline assembler - so you could wrap your assembly program in Basic. It meant some commercial games started with Basic ! Anyway - it would be easy to reserve some memory with a string like object to pass to an 'assembly object' and allow some really nifty (and fast) stuff ?? For simple algorithms it would be very neat. Avoiding memory overflow etc would be up to the assembly code 'chunk' of course. Regards, Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html From kkto at csis.hku.hk Fri Apr 30 07:51:25 2004 From: kkto at csis.hku.hk (Isaac To) Date: Fri, 30 Apr 2004 19:51:25 +0800 Subject: operator double() surprise in cxx References: <7ivfjh988v.fsf@enark.csis.hku.hk> Message-ID: <7iy8od3cqq.fsf@enark.csis.hku.hk> >>>>> "Jeremy" == Jeremy Yallop writes: Jeremy> As a declaration, it's a zero-length array of Py::Float, with a Jeremy> parenthesized declarator, i.e. the same as Jeremy> Py::Float rect[0]; Ah right, thanks for pointing that out. Regards, Isaac. From mark at prothon.org Sat Apr 3 04:16:52 2004 From: mark at prothon.org (Mark Hahn) Date: Sat, 3 Apr 2004 01:16:52 -0800 Subject: Indent testers needed (Prothon) References: <2Msbc.136673$cx5.2385@fed1read04> Message-ID: <8ivbc.141601$cx5.89434@fed1read04> But you can do this without rule 3 which is even uglier... > >>/* loop 2 */ > >>ix = 2 > >>for \ > >> item \ > >> in \ > >> blist \ > >> : > >> alist[ix] = \ > >> alist[ \ > >> ix \ > >> ] From rdjdvd at inwind.it Tue Apr 13 03:27:58 2004 From: rdjdvd at inwind.it (RDJ) Date: 13 Apr 2004 00:27:58 -0700 Subject: Download pyples-11.tgz (under FreeMindLicense) Message-ID: Pyples - Interactive Python Examples http://spazioinwind.libero.it/rdjhome From donn at u.washington.edu Fri Apr 30 15:38:53 2004 From: donn at u.washington.edu (Donn Cave) Date: Fri, 30 Apr 2004 12:38:53 -0700 Subject: What is good about Prothon? References: <108t2tlo06j8vb9@corp.supernews.com> <69cbbef2.0404281446.4e0ab52e@posting.google.com> <69cbbef2.0404291609.72d391db@posting.google.com> <69cbbef2.0404300855.4dce5e5@posting.google.com> Message-ID: In article , "Mark Hahn" wrote: > has wrote: > > > But to answer your question directly: no, simply adding a copy() > > operation (the "trying to please everybody, and ultimately pleasing > > no-one" strategy) won't make me happy; I have no use for another C++. > > You have a very warped mind. To say that having Python two-tier object > construction and Self-like constructs in the same language is C++ is > ludicrous. He's saying `language that tries to please everybody [by adding features like copy instead of doing it right in the first place] == C++' He could have a point. (Is there going to be an optional __copy__ method?) > You have finally answered a question I have asked several times. Having > anything but AS or Self in the language will keep you from being happy. Now > that I know where you stand I can quit wasting my time trying to get you to > help out. > > You keep pitching that you are such a creative artist, but if you were you'd > be helping find a way to solve the conundrum of merging the Python and Self > worlds and making positive contributions instead of just throwing stones. He probably thought they were pearls of wisdom. Guess you don't want any more, anyway. Donn Cave, donn at u.washington.edu From moranar at daleclick.com Tue Apr 20 08:01:11 2004 From: moranar at daleclick.com (Adriano Varoli Piazza) Date: Tue, 20 Apr 2004 09:01:11 -0300 Subject: Dollar sign ($) on foriegn keyboards? (prothon) In-Reply-To: References: Message-ID: <200404200901.12209.moranar@daleclick.com> El Mar 20 Abr 2004 03:22, Mark Hahn escribi?: > We are considering switching to the dollar sign ($) for self, instead > of the period ( . ) we are using now in Prothon. Ruby uses the > at-sign (@) for self, but our new usage of self also includes > replacing the period for some attribute references, as in obj$func() > versus obj.func(), and too many programs treat that as an email > address and screw it up. Also the S in the symbol $ reminds one of > the S in $elf. > > Can people from outside the U.S. tell me if typing the dollar sign > often would be a problem in writing code? Is it available and > somewhat easy to type on international keyboards? Spanish and Latin American QUERTY keyboards: Shift + 4. -- Adriano Varoli Piazza The Inside Out: http://moranar.com.ar ICQ: 4410132 MSN: adrianomd at hotmail.com Claves gpg / pgp en hkp://subkeys.pgp.net From hans at zephyrfalcon.org Sat Apr 3 23:38:40 2004 From: hans at zephyrfalcon.org (Hans Nowak) Date: Sat, 03 Apr 2004 23:38:40 -0500 Subject: Unable to launch IDLE In-Reply-To: References: Message-ID: <406F9150.8080005@zephyrfalcon.org> Scott Miller wrote: > I am new to Python (and programming in general). > > I have downloaded and installed the Windows installer version of Python 2.3. > > The Python (Command line) runs fine, but I just get the hour glass for a few > seconds then it bombs out when I try to run IDLE. > > OS Win2kPro SP4 > > Please help me get started :) Do you have any other application that uses Tcl/Tk? E.g. Ruby, WordNet, maybe even an older version of Python? Sometimes conflicting Tcl/Tk versions cause Python's Tkinter import to fail. -- Hans (hans at zephyrfalcon.org) http://zephyrfalcon.org/ From detlev at die-offenbachs.de Fri Apr 30 06:12:56 2004 From: detlev at die-offenbachs.de (Detlev Offenbach) Date: Fri, 30 Apr 2004 12:12:56 +0200 Subject: pyuic for qtdesigner 3.3 References: Message-ID: <7dl9m1-973.ln1@stargate.solsys.priv> Christopher Grinde wrote: > I've had trubles getting a puic that translates files from qt-designer > 3.3 Does anyone if there exist one, and if so, where to get it? pyuic is part of PyQt. The current snapshot releases definitely support qt-designer 3.3. I don't know this for the 3.11 release. Detlev -- Detlev Offenbach detlev at die-offenbachs.de From http Thu Apr 15 22:35:48 2004 From: http (Paul Rubin) Date: 15 Apr 2004 19:35:48 -0700 Subject: Difficulty Finding Python Developers References: <65cbc3dd.0404140641.3501fde8@posting.google.com> <5d83790c.0404150701.605782a7@posting.google.com> <7xpta8hqe7.fsf@ruckus.brouhaha.com> <7xsmf4kbac.fsf@ruckus.brouhaha.com> Message-ID: <7x7jwg7ipn.fsf@ruckus.brouhaha.com> Roy Smith writes: > My assertion was that you can learn enough to do useful work in a > weekend. You're saying that there are situations where you need to know > more. These are not mutually exclusive statements. They're not, but the discussion was serious production projects. I think in order to do one successfully, you need much more than the ability to "do useful work". I mean, you can learn to operate a car with 6 hours of Driver's Ed, but that doesn't make you ready to be a professional stunt driver. > You also pointed out that the standard Python library doesn't cover > every possible piece of functionality that everybody might ever need. > This is obviously a true statement, but it's equally true for Perl, > Java, TCL, C, C++, Ruby, Smalltalk, etc. And it's a good thing, too. > If everything that everybody ever wanted had already been written, you > and me would be out of a job :-) I don't know about Tcl, Ruby, or Smalltalk. I've generally found that C/C++, Perl, and Java have generally more thorough library coverage than Python does, and also, the restrictions are more likely to be documented and there's fewer of those little surprises. Python may be sort of a victim of its own success. It was designed as a lightweight scripting language, but its designers did such a good job with it that people started using it for complex projects, and minor oversights and shortcomings start turning into serious obstacles in those contexts. From garry at sage.att.com Mon Apr 12 09:26:22 2004 From: garry at sage.att.com (Garry Hodgson) Date: Mon, 12 Apr 2004 13:26:22 GMT Subject: why is python better than eg. smalltalk?? no one has any solid arguments! you should all go to church with all that religious talk! In-Reply-To: References: Message-ID: <2004041209261081776382@k2.sage.att.com> aahz at pythoncraft.com (Aahz) wrote: > I found my editor fifteen years ago. Guess which it is. i wrote my editor 15 years ago. still use it everyday. it's small, fast, minimalist, and does exactly what i want. i occasionally flirt with more powerful things, but always end up back with fred. ---- Garry Hodgson, Technology Consultant, AT&T Labs Be happy for this moment. This moment is your life. From mwh at python.net Mon Apr 26 07:21:56 2004 From: mwh at python.net (Michael Hudson) Date: Mon, 26 Apr 2004 11:21:56 GMT Subject: Magic methods in extension types References: Message-ID: Jacek Generowicz writes: > I am writing an extension type, and wish to add some magic methods > which are not catered for by the tp_ slots (eg tp_init -> > __init__) in PyTypeObject. My methods seem to work correctly when > invoked explicitly (eg obj.__iadd__(3)) but the method seems not to be > associated with the corresponding operator (ie obj += 3 does NOT > work). > > What am I likely to be doing wrong ? Not finding the tp_as_number->nb_inplace_add field? I think *all* magic methods correspond to slots in (or near) the type object -- it's practically the definition of "magic method"! Cheers, mwh -- I sense much distrust in you. Distrust leads to cynicism, cynicism leads to bitterness, bitterness leads to the Awareness Of True Reality which is referred to by those-who-lack-enlightenment as "paranoia". I approve. -- David P. Murphy, alt.sysadmin.recovery From wouter at voti.nl Sun Apr 18 16:19:32 2004 From: wouter at voti.nl (Wouter van Ooijen www.voti.nl) Date: Sun, 18 Apr 2004 20:19:32 GMT Subject: using a USB HID device References: <40827ce3.1151345337@news.xs4all.nl> Message-ID: <4082e29d.1177387563@news.xs4all.nl> >> I want to use Python to interface with an USB HID device (not a >> keyboard or mouse, just something that uses the HID driver to avoid >> the need for a specific driver). Is this possible in pure Python on >> Windows, or even better, in a portable way? > >What is the Win32 API for such devices? To be honest, I don't have the faintest idea. I hoped there would be some abstraction layer (freferrably a portable one) like for serial ports. Wouter van Ooijen -- ------------------------------------ http://www.voti.nl PICmicro chips, programmers, consulting From fumanchu at amor.org Wed Apr 7 16:53:19 2004 From: fumanchu at amor.org (Robert Brewer) Date: Wed, 7 Apr 2004 13:53:19 -0700 Subject: list comprehensions Message-ID: Elaine Jackson wrote: > List comprehensions don't work the way you intuitively expect > them to work.... [...] > Can somebody tell me where to look in the > documentation to find out about list comprehensions? http://www.python.org/doc/current/ref/lists.html explains: "When a list comprehension is supplied, it consists of a single expression followed by at least one for clause and zero or more for or if clauses. In this case, the elements of the new list are those that would be produced by considering each of the for or if clauses a block, nesting from left to right, and evaluating the expression to produce a list element each time the innermost block is reached." FuManChu From dwelch91 at comcast.net Mon Apr 26 21:55:11 2004 From: dwelch91 at comcast.net (djw) Date: Tue, 27 Apr 2004 01:55:11 GMT Subject: How to read a file from another server? Newbie In-Reply-To: References: <%Oejc.16$ph.9@fed1read07> <9ugjc.3709$g31.1370@newsread2.news.atl.earthlink.net> Message-ID: <34jjc.44391$IW1.2353779@attbi_s52> Ivan Voras wrote: > Edward Diener wrote: > >> Sean Berry wrote: >> >>> I am trying to read in a file from another server. >>> >>> If I try >>> x = open("servername:/path/to/file", "r") >> >> >> >> x = open("servername://path/to/file", "r") > > > Um, what does this to? What protocol does it use? I can see how this might work for a Windows server, but wouldn't the forward slashes need to be back slashes? And the path to the file would have to be a shared drive on the server. -D From deetsNOSPAM at web.de Mon Apr 5 08:05:59 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Mon, 05 Apr 2004 14:05:59 +0200 Subject: popen2 trouble References: <406F2905.C685715F@tunes.org> Message-ID: > Try using the 'bufsize' optional argument in the call to popen2. Set it > to 0 to disable all buffering, if you are writing in large chunks (e.g. > calling inn.write(bigstring)). That didn't work - now I'm using pexpect, which simulates a tty. -- Regards, Diez B. Roggisch From joewong at mango.cc Thu Apr 8 06:22:04 2004 From: joewong at mango.cc (Joe Wong) Date: Thu, 8 Apr 2004 18:22:04 +0800 Subject: performance issue Message-ID: <01b301c41d53$57089d90$7f00a8c0@scl01.siliconcreation.com> Hi, Is there any obvious performance gain between 2.3 and 2.1 release? Is this information available on the web site? Regards, - Wong -------------- next part -------------- An HTML attachment was scrubbed... URL: From anton at vredegoor.doge.nl Thu Apr 29 13:11:36 2004 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Thu, 29 Apr 2004 19:11:36 +0200 Subject: outline-style sorting algorithm References: Message-ID: <4091398d$0$122$3a628fcd@reader3.nntp.hccnet.nl> "Delaney, Timothy C (Timothy)" wrote: > foo = sorted(foo, key=lambda x: map(int, x.split('.'))) > print foo Generality is also about making as little assumptions about the data as possible and still provide minimal functionality. For example dropping the "integer" assumption: def _cmp(x,y): L,R = x.split('.'),y.split('.') for a,b in zip(L,R): r = cmp(len(a),len(b)) or cmp(a,b) if r: return r return cmp(len(L),len(R)) def test(): L = ['1.0', '1.0.1', '1.1.1', '1.2', '1.10', '1.11', '1.20', '1.20.1', '1.30', '1.9'] L.sort(_cmp) print L if __name__=='__main__': test() Anton From greg at cosc.canterbury.ac.nz Thu Apr 29 22:27:35 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Fri, 30 Apr 2004 14:27:35 +1200 Subject: Subclasses in Python In-Reply-To: References: Message-ID: Thomas Philips wrote: > Perfect! But tell me, how did you know to use __name__? I typed > dir(object) and dir(Player) in IDLE, and in neither case did __name__ > show up. Probably it's an oversight on the part of whoever implemented the dir() method for classes. I guess you just have to find out things like that by hanging out in c.l.py.:-) -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From pythongnome at hotmail.com Wed Apr 14 08:10:03 2004 From: pythongnome at hotmail.com (Lucas Raab) Date: Wed, 14 Apr 2004 12:10:03 GMT Subject: 3D Graphics Engine References: <8089854e.0404130639.3eb0db62@posting.google.com> Message-ID: "Fuzzyman" wrote in message news:8089854e.0404130639.3eb0db62 at posting.google.com... > I've seen various references to 3D graphics engines - and it's a > little difficult to know where to look. > > I would like (in the long run) to be able to create and explore 3d > worlds - so texture mapping, light sourcing or shading and mesh shapes > would be nice - but I *don't* need the quality of a commercial game > system. Collision detection etc would be nice too. > > Platform for development (!) is win32 - so I would like an engine with > precompiled binaries and a documented python binding available. A > freeware object modeller > > So far I've seen : > > Crystal Spaces - undocumented python binding, no 'easily' available > installation package (I can't see it anyway !!) > > panda 3d - only accepts 3d objects from a comemrcial app (?) > > vpython - very basic ! > > soya 3d - still unstable (??) > > Can anyone reccomend a 3d engine for me to 'muck around with'. > > Regards, > > > Fuzzy > > http://www.voidspace.org.uk/atlantibots/pythonutils.html Personally, I like Panda3d. As it's in Python, it's very easy to learn how to use. Well, let me correct that. It's core is in C++, but you manipulate it through Python. From ralf at tecont.de Tue Apr 6 03:33:06 2004 From: ralf at tecont.de (Ralf Muschall) Date: Tue, 06 Apr 2004 09:33:06 +0200 Subject: [maybe OT] Making posters References: <95aa1afa.0404030143.58c32975@posting.google.com> <95aa1afa.0404050650.2d39b1a5@posting.google.com> Message-ID: <84fzbhlfwt.fsf@tecont.de> michele.simionato at poste.it (Michele Simionato) writes: > What I do not understand is if the "scale" operator automatically splits > the graph in many pages if it becomes too large. Anyway, I have found a way It doesn't. If you really want to do it this way, create many copies of the scaled file and shift the relevant part into the paper using translate. The non-sucking method is to use the command poster(1) which comes with most linux distributions. Ralf -- GS d->? s:++>+++ a+ C++++ UL+++ UH++ P++ L++ E+++ W- N++ o-- K- w--- !O M- V- PS+>++ PE Y+>++ PGP+ !t !5 !X !R !tv b+++ DI+++ D? G+ e++++ h+ r? y? From michael at foord.net Wed Apr 14 15:05:42 2004 From: michael at foord.net (Fuzzyman) Date: 14 Apr 2004 12:05:42 -0700 Subject: Wrapper round x86 Assembler References: <8089854e.0404082353.7bf163a2@posting.google.com> <4dKdnQlIXMIXIevdRVn-gg@powergate.ca> <8089854e.0404100204.504186a0@posting.google.com> <8089854e.0404122329.5dfe5ce1@posting.google.com> <8089854e.0404132323.3283390@posting.google.com> Message-ID: <8089854e.0404141105.37d09320@posting.google.com> Peter Hansen wrote in message news:... > Fuzzyman wrote: > > > In summary - I'm better off learning C and how to write Python > > extensions !! > > It's just a very 'undynamic solution'. > > > > Ho hum.... I've been trying to avoid delving into the arcane > > makefile/linker/compiler chain mysteries... probably be more useful > > anyway. > > That is where Pyrex comes in. You aren't supposed to have to know > all those gory details then. Just some of them. :-) > > > I'm 'aware' of the concepts of memory allocation, garbage collection > > etc - but I'm sure there's plenty more to learn.......... > > I doubt you'll need to encounter those if you're just trying to > squeeze performance out of some bit-twiddling code. > > -Peter More trying to learn some new techniques / tools. The bit twiddling was just a very good example where assembler might actually have been the *simplest* solution. Anyway thanks for your help - maybe I'll look into pyrex as a way of coding python extensions. The only compielr I have is gcc under mingw - and I'm not at all sure it's set up right. Does pyrex still need a C-compiler or *is* pyrex a compiler ? Oh well... I'm sure I'll work it out. Thanks Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html From bram at nospam.sara.nl Wed Apr 14 05:13:34 2004 From: bram at nospam.sara.nl (Bram Stolk) Date: Wed, 14 Apr 2004 11:13:34 +0200 Subject: spherical coordinates Message-ID: <20040414111334.34b5d225@pistache.sara.nl> Hi there, Which module could I use if I want to do spherical coordinates in Python? parnassus, google, and groups.google.com did not give me a good pointer. Thanks, Bram -- ------------------------------------------------------------------------------ Bram Stolk, VR Engineer. SARA Academic Computing Services Amsterdam, PO Box 94613, 1090 GP AMSTERDAM email: bram at nospam.sara.nl Phone +31-20-5923059 Fax +31-20-6683167 "For the costs of subsidized agriculture in the EU, we can have all 56 million European cows fly around the world. First Class." - J. Norberg ------------------------------------------------------------------------------ From noemail at noemail4u.com Thu Apr 15 07:31:27 2004 From: noemail at noemail4u.com (Dang Griffith) Date: Thu, 15 Apr 2004 11:31:27 GMT Subject: Reommended compiler toolkit References: <407d5395$0$27643$61ce578d@news.syd.swiftdsl.com.au> Message-ID: <8e0970f2f571ad8b6b07f7d3bc8a318c@news.teranews.com> On Thu, 15 Apr 2004 01:15:30 +1000, huy wrote: >Miki Tebeka wrote: >> Hello All, >> >> I'm looking for a pure python compiler toolkit (lexer + parser, like >> flex + bison). [snip] > >Have a look at http://dparser.sourceforge.net/ > >It supports BNF (EBNF?) notation which IMO is nicer then the PLY grammar >specs. I haven't tried dparser yet, so let us know how it is (compared >to PLY) if you decide to use it. > But it's not pure python. It includes a Python interface to the C-based parser (via SWIG). OTOH, it does seem pretty powerful. --dang From martin at v.loewis.de Thu Apr 29 16:14:23 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 29 Apr 2004 22:14:23 +0200 Subject: locale.CODESET / different in python shell and scripts In-Reply-To: References: Message-ID: <4091621F.5060307@v.loewis.de> Nuff Said wrote: > Both Python versions give me 'ANSI_X3.4-1968' when I run a script > with 'print locale.nl_langinfo(locale.CODESET)'. > When I execute the same command in an interactive Python shell, > I get the (correct) 'UTF-8'. PLEASE invoke locale.setlocale(locale.LC_ALL, "") before invoking nl_langinfo. Different C libraries behave differently in their nl_langinfo responses if setlocale hasn't been called. Regards, Martin From rebirth at orcon.net.nz Fri Apr 9 06:20:34 2004 From: rebirth at orcon.net.nz (David McNab) Date: Fri, 09 Apr 2004 22:20:34 +1200 Subject: [Jython-users] ANN: SPIRO - a cPython->Jython bridge (amongst other uses) Message-ID: <8501308.1081541401342.JavaMail.SYSTEM@C1879626-a> Hi, Announcing SPIRO - an easy cPython to Java bridge. Background: I spent some time looking for ways to interface between python and java. Jython is great - but it comes at a price where one must forego all python modules containing binaries. Pyro is great too - but presently cannot support running servers under jython. I tried JPE - but its brittleness rules it out for distributing code to others. So I gave up and wrote a new ORB myself: SPIRO - Simple Python Interface to Remote Objects http://www.freenet.org.nz/python/spiro SPIRO allows cPython programs to manipulate Java objects via jython. While it's not exactly CORBA-compliant, it is an easy and simple way to bridge between cPython and Java, with the advantage that it doesn't require any binary compilation. The server-side of SPIRO can be easily built into a standalone .jar file, which together with the cPython Spiro client class, will give your cPython programs access to the full catalogue of java software. Please note - this is an early alpha release, so stability is not guaranteed. If you're a tinkerer, and you feel like joining the development effort, let me know and I'll open a sourceforge account. Present limitations - no support for subclassing Java objects in cPython, no support for exceptions. Cheers David ------------------------------------------------------- This SF.Net email is sponsored by: IBM Linux Tutorials Free Linux tutorial presented by Daniel Robbins, President and CEO of GenToo technologies. Learn everything from fundamentals to system administration.http://ads.osdn.com/?ad_id=1470&alloc_id=3638&op=click _______________________________________________ Jython-users mailing list Jython-users at lists.sourceforge.net https://lists.sourceforge.net/lists/listinfo/jython-users From fredrik at pythonware.com Tue Apr 27 11:47:53 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 27 Apr 2004 17:47:53 +0200 Subject: Problem binding and events References: <20040427135207.GA5359@dogma.freebsd-uk.eu.org> Message-ID: Jonathonwe McKitrick wrote: > I have a listbox with bound to bring up an edit dialog. > But and do not work. (in the dialog? in the listbox? on the keyboard?) > I have a debug print statement, and the program never reaches the event > handler. I've tried handlers with 'event' arguments and with no arguments, > but neither works. > > Is there something I am missing here? if a keyboard binding doesn't work as you expect it to, it's usually because focus is somewhere else. when in doubt, add a widget.focus_set() call to the appropriate location. From fumanchu at amor.org Thu Apr 1 11:14:55 2004 From: fumanchu at amor.org (Robert Brewer) Date: Thu, 1 Apr 2004 08:14:55 -0800 Subject: splitting one dictionary into two Message-ID: jsaul wrote: > I have to split a dict into two dicts. Depending on their values, > the items shall remain in the original dict or be moved to another > one and at the same time be removed from the original dict. > > OK, this is how I do it right now: > > dict1 = { "a":1, "b":3, "c":5, "d":4, "e":2 } > dict2 = {} > klist = [] > > for key in dict1: > if dict1[key] > 3: # some criterion > dict2[key] = dict1[key] > klist.append(key) > > for key in klist: > del dict1[key] > > print dict1 > print dict2 > > That means that I store the keys of the items to be removed from > the original dict in a list (klist) and subsequently remove the > items using these keys. > > Is there an "even more pythonic" way? I'm not sure about "more Pythonic", but this is another way, which iteratively destroys the original dict and produces two new ones: def cleave(mapping, truthfunc): dict1, dict2 = {}, {} while mapping: key, value = mapping.popitem() if truthfunc(key, value): dict1[key] = value else: dict2[key] = value return dict1, dict2 HTH Robert Brewer MIS Amor Ministries fumanchu at amor.org From mcfletch at rogers.com Mon Apr 19 11:59:09 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Mon, 19 Apr 2004 11:59:09 -0400 Subject: Problems using modulo In-Reply-To: References: Message-ID: <4083F74D.7050400@rogers.com> Use repr to see the true values you are dealing with when printing floating point numbers (as distinct from the pretty "%s" formatter): t = 5.8 interval = 2.0 while t < 6.1: print "%r mod %r = %r " % (t, interval, t % interval ) t += 0.1 Then you'll see what's going on: P:\temp>modulofloat.py 5.7999999999999998 mod 2.0 = 1.7999999999999998 5.8999999999999995 mod 2.0 = 1.8999999999999995 5.9999999999999991 mod 2.0 = 1.9999999999999991 6.0999999999999988 mod 2.0 = 0.099999999999998757 So, 5.99999... modulo 2.0 gives you 1.999999... as you would expect. HTH, Mike Griff wrote: >Test program: >=============================================================== >t = 5.8 >interval = 2.0 > >while t < 6.1: > print "%s mod %s = %s " % (t, interval, t % interval ) > t += 0.1 > > _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From project2501 at project2501.cor Wed Apr 14 06:20:50 2004 From: project2501 at project2501.cor (project2501) Date: Wed, 14 Apr 2004 11:20:50 +0100 Subject: spherical coordinates References: <20040414111334.34b5d225@pistache.sara.nl> Message-ID: what do you want to do with spherical coordinates? surely they are simply a transform from cartesian coordinates? On Wed, 14 Apr 2004 11:13:34 +0200, Bram Stolk wrote: > Hi there, > > > Which module could I use if I want to do spherical coordinates in Python? > > parnassus, google, and groups.google.com did not give me a good pointer. > > > Thanks, > > Bram From gandreas at no.reply Fri Apr 23 16:58:02 2004 From: gandreas at no.reply (Glenn Andreas) Date: Fri, 23 Apr 2004 15:58:02 -0500 Subject: CamelCase versus wide_names (Prothon) References: <6e0680ac.0404211252.7f7b4358@posting.google.com> <4086DFA7.9736E7D3@alcyone.com> Message-ID: In article , Antoon Pardon wrote: > If you would define a component as something like an identifier but > without an underscore and then define an identifier as a number > of components attached to each other with underscores you then could > allow a function to have part of its arguments between components. > > Something like: > > copy_to(a,b) > > could then also be written as: > > copy(a)to(b) Or make it like Objective-C or Smalltalk: copy: a to: b (which is odd for either language since there is no reciever for the copy:to: message) Probably wouldn't parse well with an if statement, though: if copy:a to: b: print "it copied" That makes my eyes hurt just looking at it... (I once made a simple scripting language that was built entirely from that syntax, but every "word:" after the first was actually used as a parameter name which could be in any order - it all worked suprisingly well since I could do stuff like: copy: a to: b or copy: a symbolicLink: false to: b or copy: a to: b symbolicLink: false ) From andrew.henshaw at gtri.gatech.edu Fri Apr 2 10:03:31 2004 From: andrew.henshaw at gtri.gatech.edu (Andrew Henshaw) Date: Fri, 2 Apr 2004 15:03:31 +0000 (UTC) Subject: Making the Zen of Python more useful References: <106qp0uivlefo40@corp.supernews.com> Message-ID: In article , peter at engcorp.com says... > >Andrew Henshaw wrote: >> Yesterday, I was writing some test code for a module and I wanted some >> line-oriented text to use as a data source. I thought about using a >> docstring from one of the standard modules; but, it occurred to me that the >> Zen of Python text from the 'this' module would be *much* better, as it is >> more readable and would be a nice thing for our students to see. >> >> Unfortunately, the actual text is difficult to use: >> o the text is ROT-13 encoded and the module's translation routine is >> inline >> o the text is printed to stdout on import. I understand why Tim did this, >> but it did interfere with my purpose. >> >> So, in order to use the module for my test code, I had to implement a short >> ROT-13 translator, import the sys module, redirect stdout to a simple >> object that provided a null write method, import this, restore stdout, and >> then rot13(this.s). > >I'm not sure why you had to do quite all that. The following is >sufficient, and you don't need a custom ROT-13 thingie: > > >>> import StringIO, sys > >>> s = StringIO.StringIO() > >>> sys.stdout = s > >>> import this > >>> sys.stdout = sys.__stdout__ > >>> s.getvalue() >"The Zen of Python, by Tim Peters\n\nBeautiful is ... > >-Peter Much better. Still pretty awkward for the purpose I described. Perhaps, the best solution, overall. Thanks. -- Andy From peter9547 at btinternet.com Sun Apr 4 12:48:19 2004 From: peter9547 at btinternet.com (Peter MacKenzie) Date: Sun, 4 Apr 2004 16:48:19 +0000 (UTC) Subject: emergent/swarm/evolutionary systems etc References: <106uj10g611v0f5@corp.supernews.com> Message-ID: So much to take in, so little time. I'm torn between the creative urge to go forth and embark on this project, and the more pressing need to study-study-study for exams, so please bear with me if I appear a little distracted. My 'psychology' is one that responds better to open possibilities than closed boundaries. Compared to the expansive potential of python, I'd likely become disenchanted with the restrictive structure of spreadsheets. Although I could launch straight into the simpler spreadsheet stuff, getting it to do really interesting stuff may prove tricky in the long run, and I'd be constantly itching to try something more 'fun'. A little investment in learning to program would leave me a happier person, in the short and the long term. Since it's a skill I'd like to acquire anyway, I'm inclined to lean that way regardless of the relative merits of spreadsheets vs. python. It's likely that the added difficulty of implementing it in an unfamiliar format would be taken into consideration in the grading of the dissertation (as is standard practice where the project is faced with obstacles), but do you think that python would make for a 'better' dissertation? As for whittling away a couple of months on background reading, I doubt I'd have the patience. I like to launch straight into things, learning as I go and doing stuff my own way. Generally, I only refer to other peoples' work when I'm really stuck, or when I don't know enough about the subject to even hazard a guess at where to start. Doubtless I'll get really stuck at many points in my simulation attempts, as I've been really stuck just trying to get the simplest of code to work, but I don't see myself pouring over the arcane tomes for longer than is strictly necessary. Not that I intend to be sloppy about my reading - just concise. Also, the 2-month schedule should perhaps be clarified. The actual deadline is the beginning of December, but I'd like to keep fairly pessimistic about the time I'll have, given course considerations, the limited amount of effort I can spare before the first of June (end of exams) as well as the tendency of field work and data mining to eat time like candy. Still, if push comes to shove, I could makes thing fit, one way or another. Cameron Laird wrote in message news:106uj10g611v0f5 at corp.supernews.com... > In article , > Peter MacKenzie wrote: > >Spreadsheets do seem to be an attractive option, but the benefits are not > >without their detractors: > > > >+Easy to work with > >+Require no/limited skill acquisition > >+Flexible > > > >-Cells can only hold single items of data (which can be worked around by > >using arrays of cells to hold multiple attributes for each location) > >-Require no/limited skill acquisition (being familiar and honest with my own > >psychological composition, I know that the only way I'm likely to develop a > >fair degree of programming competence is if there's a driving pressure to do > >so. It's something I'd like to learn, and this gives me the excuse/leverage > >to do so.) > > > >Unknowns: Time series graphical output would be necessary, even if it's > >very primitive. Do you know if the spreadsheet could be set up in such a > >way that cells would change colour depending on their values, or if the > >graph making facilities would be able to create reasonable representations > >of said values so that a series of graphs would be capable of showing up > >phenomena with fluidic (wavelike, turbulent, etc) characteristics? > > > >I'm afraid the temptation to take the hard route my prove too great > >(psychological paradoxes: I always feel good about feeling so terrible about > >these things after I've passed the point of no return in the undertaking, > >and the enormity of the task at hand sinks in - it's a whole adrenalin > >thing), but I'd still like to make a comprehensive assessment of my options > >before I commit to anything. > > > > > > Spreadsheets can do anything. Python can do anything. > > To first approximation, at least. They both have developed > enough to have far more capabilities than you'll exhaust in > a couple of months. > > The key questions are: which better suit your psychology? > Which will get in the way less? Which support "libraries" > of related material in your "domain" (geography)? > > You're not experienced enough with software yet to judge > the first of these questions well. Whatever first impres- > sions Python or Excel make on you are likely to dwindle to > insignicance after a few more weeks of software exploration. > > One of the dimensions your comparison of the two approaches > doesn't cover is robustness of expression and abstraction. > You aren't in a position to appreciate this yet, but Python > beats spreadsheets all to pieces in these regards. Crudely, > you can hand a Python solution to someone else, two years > from now, and he'll understand what you've done, and how to > modify or validate or ... it. I argue strongly that that is > *not* true for spreadsheet solutions. I therefore regard > spreadsheet approaches, except in specialized circumstances, > as anti-scientific, because they don't promote the free > exchange of ideas. > > There's a rich literature on simulation done with computers, > some of it specifically by those coming from geography. It > would be no particular problem to dissipate the entire two > months just reading up on what you plan to do. You need to > figure out a very circumscribed goal, and ask experts on what > you should do to achieve it. > > Reading through *Thinking ... with Python* certainly can be > part of that path. > -- > > Cameron Laird > Business: http://www.Phaseit.net From rnikaREMOVEnder at adelphia.net Wed Apr 21 00:11:07 2004 From: rnikaREMOVEnder at adelphia.net (Rob Nikander) Date: Tue, 20 Apr 2004 21:11:07 -0700 Subject: How to get the ip addresses of a nic In-Reply-To: References: Message-ID: <2sKdnSP1MpnEaRjd4p2dnA@adelphia.com> Bo Jacobsen wrote: > Is there a simple way to get all the ip addresses of a nic, beyound parsing > /etc/sysconfig/..... > > ------------------------------------------------- > Bo Jacobsen > > I just had to do deal with this BS a couple days ago. I couldn't get the socket module to give it to me. The only ways I found were parsing the output of ifconfig (or equivalent on other platforms) or connecting to server and then looking at your socket. I don't like either one. Rob # Method 1 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(('somewebserver', 80)) return s.getsockname()[0] # Method 2 if sys.platform == 'linux2': out = commands.getoutput('/sbin/ifconfig') return re.search('inet addr:(.+?)\s', out).group(1) elif sys.platform == 'win32': si, so = os.popen4('route print') out = so.read() ipPatt = r'\d+\.\d+\.\d+.\d+' return re.search(r'0\.0\.0\.0\s+0\.0\.0\.0\s+' + ipPatt + r'\s+(' + ipPatt + ')', out).group(1) elif sys.platform == 'freebsd5': out = commands.getoutput('/sbin/ifconfig') return re.search('inet (\S+)\s', out).group(1) else: raise Exception('unsupported platform: %s' % sys.platform) From klapotec at chello.at Wed Apr 7 13:53:00 2004 From: klapotec at chello.at (Christopher Koppler) Date: Wed, 07 Apr 2004 17:53:00 GMT Subject: Are line continuations needed? References: <407409ef.82801353@news.eircom.net> Message-ID: On Wed, 07 Apr 2004 14:05:29 GMT, wallacethinmintr at eircom.net (Russell Wallace) wrote: >Hi all, > >Python lets you continue a single logical line across more than one >physical line, either by putting a \ at the end or letting it happen >automatically with an incomplete infix operator. > >I'm wondering how often is this feature needed? Would there be any >problems if it weren't part of the language? I don't have any ready examples, but I do occasionally need it, if only for readability porpoises, or more often to fit a line to a certain length limit. If a parenthetical expression will work, and doesn't look stranger (really can't think of a case), I'll use that. But problems there'll surely be - with legacy code compatibility. >-- >"Sore wa himitsu desu." Not really it isn't ;-) -- Christopher From sridharinfinity at yahoo.com Thu Apr 29 05:59:56 2004 From: sridharinfinity at yahoo.com (Sridhar R) Date: 29 Apr 2004 02:59:56 -0700 Subject: Kiwi References: Message-ID: <930ba99a.0404290159.2f929618@posting.google.com> "Laughlin, Joseph V" wrote in message news:... > Is anyone using the Kiwi wrappers for pygtk? Is there an updated > version of it? The one I can find is from 2002 and it doesn't seem to > work too well (for starters, it's trying to import libglade and not > gtk.glade)... > > Joe Laughlin > Phantom Works - Integrated Technology Development Labs > The Boeing Company You should also be looking at GtkMVC http://sra.itc.it/people/cavada/mvc/ From michele.simionato at poste.it Thu Apr 29 13:30:58 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 29 Apr 2004 10:30:58 -0700 Subject: python 2.3's lambda behaves old fashioned References: Message-ID: <95aa1afa.0404290930.44ac3452@posting.google.com> Uwe Schmitt wrote in message news:... > Hi, > > I just tried (Python 2.3) > > li = [ lambda x: x*a for a in range(10) ] > > which results in > > li[0](1) = 9 > ... > li[9](1) = 9 > > In order to achieve the intended result I had to fall back on the > following trick: > > li = [ lambda x,a=a: x*a for a in range(10)] > > which leads to the expected result. > > Any explanations ??? > > Greetings, Uwe. This should be in the FAQ. Here is a recent thread on the subject: http://groups.google.it/groups?hl=it&lr=&ie=UTF-8&oe=UTF-8&threadm=95aa1afa.0402272327.29828430%40posting.google.com&rnum=1&prev=/groups%3Fhl%3Dit%26lr%3D%26ie%3DUTF-8%26oe%3DUTF-8%26q%3Dsimionato%2Bscope%2Brules%26meta%3Dgroup%253Dcomp.lang.python.* Michele Simionato From davidf at sjsoft.com Thu Apr 22 01:49:52 2004 From: davidf at sjsoft.com (David Fraser) Date: Thu, 22 Apr 2004 07:49:52 +0200 Subject: python shutting down sloooooooowly/tuning dictionaries In-Reply-To: References: <20040421153923.GA13234%till@score.is.tsukuba.ac.jp> <40869D5F.9010408@sweetapp.com> Message-ID: Till Plewe wrote: > On Wed, Apr 21, 2004 at 06:12:15PM +0200, Brian Quinlan wrote: > >>>Since the entire database is too large I typically run the same >>>program 10-100 times on smaller parts. The annoying bit is that the >>>time for finishing one instance of a program before starting the next >>>instance can take a lot of time. ... >> >>You might try disabling garbage collection using the gc module when you >>your application is done. Explicitly closing any files bound to globals >>might then be a good idea. >> >>Cheers, >>Brian >> > > > Thanks for the suggestions but unfortunately I already tried disabling > gc. It did not have any noticable effect (not that I was patient > enough to time it) nor did using sys.exit(). Also, I am not using > threads which excludes another possible explanation. > > To give an example of the actual time spans involved: 2-10 minutes for > running the program and > 30 minutes for shutdown. During that time > the amount of memory used by python does not seem to vary. > > A far as closing files is concerned, I am using cdb for writing > read-only databases and I am using cdb.finish() (there is no explicit > method for closing(); finish writes all key/value pairs to a temporary > file and then moves that file to wherever you want it. But as far as I can see > as soon as that file is written/has been moved no more I/O should take place. > There is no data loss if I simply kill the python program. > > - Till > > Have you tried adding __del__ methods to your objects and printing the time out from them? That may help you work out what is happening David From luis_ at iname.com Tue Apr 13 14:13:51 2004 From: luis_ at iname.com (Lupe) Date: Tue, 13 Apr 2004 19:13:51 +0100 Subject: thank you everyone! eom References: Message-ID: ... From peter at engcorp.com Tue Apr 6 23:03:42 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 06 Apr 2004 23:03:42 -0400 Subject: Customizing the python search path depending on source directory In-Reply-To: <5cf809e9.0404061853.41cd3c85@posting.google.com> References: <5cf809e9.0404061853.41cd3c85@posting.google.com> Message-ID: Peter Schwalm wrote: > My idea was to use site.py / sitecustomize.py in lib/site-packages and > to have sitecustomize.py invoke a directory-specific customizing > module - say dirCustomize.py - located in the script source directory. > > But it seems that this is the wrong place, because at the moment > sitecustomize is imported > > a) the source directory of the script is still not in sys.path Are you sure? Looking at site.py, it appears that the sitecustomize import is done next-to-last, just before sys.setdefaultencoding is deleted. If you concluded this by examining sys.path manually at the point just as sitecustomize is imported, maybe you don't know that the '' entry in sys.path actually represents the source directory of the main script... It would seem your suggested solution above should actually work... -Peter From chrisabruce at yahoo.com Wed Apr 14 14:46:04 2004 From: chrisabruce at yahoo.com (Chris) Date: 14 Apr 2004 11:46:04 -0700 Subject: urlopen differences between python 2.3.3 and python 2.2??? Message-ID: <5bec5d30.0404141046.73580bd@posting.google.com> I am using the code below and it works correctly on python2.2 but gives me a 404 not found error when running on python2.3.3. Is there some difference? Maybe python 2.3.3 is sending different headers? The params string looks to be encoded identically, so must be something with urlopen. Does anyone have any suggestions to get this working from python2.3.3?? Thanks in advance! import httplib,urllib def signup(self, REQUEST): """ Allows us to automatically sign-up a user. """ email = REQUEST['Email'] first_name = REQUEST['FirstName'] last_name = REQUEST['LastName'] if REQUEST.has_key('Company'): company = REQUEST['Company'] else: company = '' if REQUEST.has_key('Address'): address = REQUEST['Address'] else: address = '' if REQUEST.has_key('City'): city = REQUEST['City'] else: city = '' if REQUEST.has_key('State'): state = REQUEST['State'] else: state = '' if REQUEST.has_key('Zip'): zip = REQUEST['Zip'] else: zip = '' if REQUEST.has_key('Phone'): phone = REQUEST['Phone'] else: phone = '' if REQUEST.has_key('Fax'): fax = REQUEST['Fax'] else: fax = '' params_list = {'owner_id_enc':'18164,$1$mGEJB$g1V9TwRwtIEsBj5XsnnN1/', 'user_email':email, 'user_email_fmt':'html', 'user_fname':first_name, 'user_lname':last_name, 'user_company':company, 'user_addr1':address, 'user_city':city, 'user_state':state, 'user_state_other':'', 'user_zip':zip, 'user_phone':phone, 'user_fax':fax, 'user_attr1':'a', 'function':'Subscribe'} params = urllib.urlencode(params_list) f = urllib.urlopen("http://mailermailer.com/x", params) return f.read() print signup(None,{'Email':'test7 at chongopunk.com','FirstName':'Chris','LastName':'Bruce'}) From roman.yakovenko at actimize.com Wed Apr 14 10:33:56 2004 From: roman.yakovenko at actimize.com (Roman Yakovenko) Date: Wed, 14 Apr 2004 17:33:56 +0300 Subject: ctypes.com - unable to call function, read property Message-ID: <2D89F6C4A80FA547BF5D5B8FDDD04523060C65@exchange.adrembi.com> Hi. I am trying for the first time to use ctypes.com module. I have question: I have reference to object that implements IDiaSession interface. IDiaSession._methods_ = IUnknown._methods_ + [ STDMETHOD(HRESULT, "_get_loadAddress", POINTER(c_ulonglong)), STDMETHOD(HRESULT, "getEnumDebugStreams", POINTER(POINTER(IDiaEnumDebugStreams))), I can't find out how I call _get_loadAddress and getEnumDebugStreams methods. I know that in com "get_" is a prefix for property. What should I do ? Also "_get_loadAddress" defined as property. Thanks for help. Roman From PeterAbel at gmx.net Wed Apr 7 16:24:43 2004 From: PeterAbel at gmx.net (Peter Abel) Date: 7 Apr 2004 13:24:43 -0700 Subject: Dynamic creation of an object instance of a class by name References: Message-ID: <21064255.0404071224.344bd74e@posting.google.com> Andre Meyer wrote in message news:... > Hi all > > I have been searching everywhere for this, but have not found a solution, yet. > > What I need is to create is an object that is an instance of a class (NOT a > class instance!) of which I only know the name as a string. This what I tried: > > class A: > def __init__(self, id): > self.id = id > def getID(self): > print self.id > > ca = new.classobj('A', (), {}) > oa1 = ca() > oa2 = new.instance(ca) > > oa1 > <__main__.A instance at 0x007E8AF8> > > oa1.getID() > Traceback (most recent call last): > File "", line 1, in ? > AttributeError: A instance has no attribute 'getID' > > oa2 > <__main__.A instance at 0x007E8AF8> > > oa2.getID() > Traceback (most recent call last): > File "", line 1, in ? > AttributeError: A instance has no attribute 'getID' > > > Thus, both ways only produce a class instance, but NOT an object of that > class!!! How can I get a new object instance??? > What else needs to be filled in for base_classes and __dict__ in new.classobj? > > > Any help is appreciated, this is driving me nuts! > > kind regards > Andre I'm not quite sure if I guess what you mean: Is it? >>> class A: ... def __init__(self,id): ... self.id=id ... def getID(self): ... print self.id ... >>> a=eval('A')('item') >>> a.getID() item Or rather the following? >>> classNEW=new.classobj('classX',(A,),globals()) >>> x=classNEW('another_item') >>> x.getID() another_item >>> The first one evaluates the string 'A' to a class-object from which you can instantiate. >>> eval('A') >>> The second one inherits classNEW() from A() with name 'classX' with the namespace of globals(). >>> classNEW >>> classNEW.__name__ 'classX' >>> where the name of class A() is 'A' >>> A.__name__ 'A' See http://www.python.org/doc/2.2.3/lib/module-new.html ... classobj(name, baseclasses, dict) This function returns a new class object, with name name, derived from baseclasses (which should be a tuple of classes) and with namespace dict. Regards Peter From franck.lepoutre at caramail.com Wed Apr 21 06:24:05 2004 From: franck.lepoutre at caramail.com (francois lepoutre) Date: Wed, 21 Apr 2004 12:24:05 +0200 Subject: A Paris python user group? Message-ID: <40879c82$0$25890$79c14f64@nan-newsreader-02.noos.net> Hi all french speaking, Paris-based python users, Bonjour ? tous les utilisateurs parisiens de python, How many are we to use python in the *Paris* Area? If any ? Enough to build some community life? Combien sommes nous ? utiliser python sur Paris? Assez pour monter une assoc? Two years ago i discovered perl and, by the way, their cheerfull and welcoming Paris user community http://paris.mongueurs.net/ Il y a deux ans, j'ai d?couvert perl et, par la m?me occasion, la chaleureuse ambiance des perl mongueurs de Paris Informal meeting at "La Taverne R?publique" 5, place de la R?publique every month. Socialising, a few drinks, some food (pizzas available for the die-hard... but most would stick to the great local moules-frites mussels-chips Une r?union informelle ? la "Taverne R?publique" 5, place de la R?publique chaque mois. Une ambiance decomplex?e, quelques boissons et des moules-frites (pizzas pour les accros). Great hours re-shaping IT late from 8pm into the night... but I have since switched to python. Des heures agr?ables ? refaire notre industrie ? partir de 8 heures du soir ... Mais depuis je suis pass? ? python. Anyone to join for a "Paris python user group"? Des volontaires pour un groupe parisien ? Same place, same programme, but there's room for negociation, on both the drink and the food :) Nous proposons le m?me lieu et la m?me formule mais nous sommes pr?ts ? discuter :) Fran?ois et Jean From jfabiani at yolo.com Fri Apr 30 14:49:57 2004 From: jfabiani at yolo.com (John Fabiani) Date: Fri, 30 Apr 2004 18:49:57 GMT Subject: web start Message-ID: In the Java world they have a way to start and update programs using web start. Is there something like web start for Python? -- John Fabiani From peter at engcorp.com Mon Apr 12 22:04:38 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 12 Apr 2004 22:04:38 -0400 Subject: Random Numbers and a thought In-Reply-To: <107m8qvphrjd303@corp.supernews.com> References: <107m6f0t4i0gnff@corp.supernews.com> <107m8qvphrjd303@corp.supernews.com> Message-ID: <0qadnfH7L4Ur1-bdRVn-tw@powergate.ca> A Evans wrote: >>What "pattern" are you talking about? > > I would like to take a random number generated by a computer application > then use my application to try and determine the pattern in that application > > Quote me if its impossible http://www.google.ca/search?q=cracking+random+number+generator Reading what's at the first link alone should discourage you. :-) As Kirk indicated, it's basically not possible for any decent random number generator. The fourth link has some pointers on doing it for poor generators (such as the traditional linear congruential one) by doing things like high dimensional graphing and finding lattice structures (to paraphrase that page). This is the sort of stuff where one should go to university and then look into as part of one's PhD thesis... -Peter From rogerb at rogerbinns.com Sat Apr 3 13:03:23 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Sat, 3 Apr 2004 10:03:23 -0800 Subject: Parrot for Python References: <930ba99a.0404030251.c2d2107@posting.google.com> Message-ID: <6sa3k1-4ub.ln1@home.rogerbinns.com> > Why is Java so popular than Python. Java is a great solution for server side stuff. It has the same respect as C++ gets (ie people and PHB's do consider it a "real" language/environment). The class libraries are *way* more advanced than the Python ones. For example compare Python's imaplib with javamail. (Hint: Python pretty much just gives you raw protocol back and you have to figure out what is going on). Other libraries such a JNDI, Activation, JMF etc don't even exist in Python. Have a look at this page: http://java.sun.com/reference/api/index.html And this one: http://java.sun.com/products/ In many cases there are similar libraries for Python, or more often multiple incomplete (incomplete by comparison to Java) implementations out there. Now sometimes you don't need such complete libraries, and Python lets you get the problem solved quicker. Other times you have to augment someone else's library component, which would have been time better spent on your own code. Roger From adeleinandjeremy at yahoo.com Wed Apr 28 20:57:31 2004 From: adeleinandjeremy at yahoo.com (Adelein and Jeremy) Date: Wed, 28 Apr 2004 17:57:31 -0700 (PDT) Subject: Problems installing Python 2.3 with Tkinter linked to Tcl/Tk 8.4 Message-ID: <20040429005731.85659.qmail@web50309.mail.yahoo.com> I have just installed Python 2.3.3, after first installing Tcl/Tk 8.4.6. After successful installation of Tcl/Tk (including passing configure the '--enable-shared' option), and testing both Tcl and Tk, I unpacked Python2.3 and began a frustrating installation. After standard configuration, make told me it was renaming module _tkinter because the module was not found (sorry I am omitting the exact warning message) - I don't understand that completely, but that was what it said. So I then edited the Setup file in Python2.3/Modules/ so that it would 1) include _tkinter, 2) look for tkinter in /usr/local/lib, 3) look for tk.h in /usr/local/include, 4) find X11, and 5) look for libtk8.4 and libtcl8.4. So I went through make and it told me that libtk8.4.so could not be opened. The file existed with read and execute privileges for all in /usr/local/lib, so I was perplexed. I then found a single helpful explanation (among many completely misleading ones) at http://www.talkaboutprogramming.com/group/comp.lang.python/messages/290343.html (which is for Fedora, but works well with RH 8.0. However, upon having written the script that it suggests, and deleting the /usr/local/bin/python, I realized that idle was broken. Also, scripts could not be executed with the sh-bang line at top if written for Python 2.3. So I moved python2.3 over to python again, and realized that idle still wouldn't work because Python will not look for Tcl/Tk where it installs by default. Is there a better solution than the one I followed? If not, is there a plan for generalizing the Python Tkinter installation so that it will look for Tcl/Tk instead of assuming that it knows where it is? I found it messy enough having to deal with multiple Python installations due to RedHat's reliance on old versions, and this is simply a show-stopper when it comes to recommending Python to others. I have to wonder if I am doing something very wrong, but I have no idea where my mistake would be. If nothing else, others with this problem may see this post and at least have a temporary fix. - Jeremy __________________________________ Do you Yahoo!? Win a $20,000 Career Makeover at Yahoo! HotJobs http://hotjobs.sweepstakes.yahoo.com/careermakeover From http Tue Apr 13 05:09:43 2004 From: http (Paul Rubin) Date: 13 Apr 2004 02:09:43 -0700 Subject: How to read & write standard password encrypted ZIP files? References: <19804fd8.0404120411.3497925d@posting.google.com> <19804fd8.0404130029.7b33d6f3@posting.google.com> Message-ID: <7x4qroxmzs.fsf@ruckus.brouhaha.com> k.robert at gmx.de (Robert) writes: > is there a secure encrypted format, that could be read also by common > tools like WinZIP, WinRAR ? There's a proposal for better encryption in zip files, but I don't think it's widely supported yet. From google at evpopov.com Fri Apr 30 04:10:56 2004 From: google at evpopov.com (popov) Date: 30 Apr 2004 01:10:56 -0700 Subject: Doing readline in a thread from a popen4('rsync ...') stream blo cks when the stream ends. References: Message-ID: <7eecf173.0404300010.7cd31c0b@posting.google.com> "Rasmusson, Lars" wrote in message news:... > Hi, > > I have a problem doing I/O in a python thread. > > I want a thread to execute a command using > os.popen, read its input until the end, and > then print 'DONE' and terminate. > > However, the thread hangs when it reaches > the end of the stream. You can have a look here: http://sourceforge.net/tracker/?group_id=5470&atid=105470, looking for 'popen'. requestID #566037 may be of interest, for eg. From loic at yermat.net1.nerim.net Thu Apr 22 13:08:30 2004 From: loic at yermat.net1.nerim.net (Yermat) Date: Thu, 22 Apr 2004 19:08:30 +0200 Subject: alternative python compilers/vms? (like java) In-Reply-To: References: Message-ID: Diez B. Roggisch a ?crit : > project2501 wrote: > > >>are there alternative compilers for python? or different VMs to run the >>bytecode? >> >>similar to IBM java jvm and sun jvm, and other jvms? jikes, gcj? > > > there is jython, a very popular python 2.1 implementation on top of the java > vm. > > Apart from that, AFAIX python is not specified in terms of a vm, as java is. > The bytecode might actually change between versions. > There is also IronPython for .NET. By now, the python byte code is considered as "an implementation detail" that is why it is not specified... It might disappear in the future... or not. ;-) So it seems that we cannot rely on it for whatever purpose ! -- Yermat From elainejackson7355 at home.com Sun Apr 11 14:11:24 2004 From: elainejackson7355 at home.com (Elaine Jackson) Date: Sun, 11 Apr 2004 18:11:24 GMT Subject: Tkinter Button image option References: <8d3ec.74988$Ig.46341@pd7tw2no> Message-ID: "Mike Abel" wrote in message news:dp6nk1-4u1.ln1 at 6.mabelsoft.org... | Sorry it's a german site. Kein Problem. Ganz im Gegenteil: ich habe den genau richtigen Hinweis gefunden. Danke vielmals! From No.Spam.mc at No.Spam.mclaveau.No.Spam.com Mon Apr 26 11:49:36 2004 From: No.Spam.mc at No.Spam.mclaveau.No.Spam.com (Michel Claveau/Hamster) Date: Mon, 26 Apr 2004 17:49:36 +0200 Subject: Paris python user group? References: <408795ee$0$25893$79c14f64@nan-newsreader-02.noos.net> Message-ID: Bonjour ! Dans l'Ard?che, je peux organiser une r?union avec h?bergement (pas cher), salle de travail, et descente de l'Ard?che (ou mini-descente de 7 km si on doit travailler plus). Les parisiens vont baver... @-salutations -- Michel Claveau From peter at engcorp.com Thu Apr 8 09:45:29 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 08 Apr 2004 09:45:29 -0400 Subject: if 'hallo' in ['hallooo','halloooooooo'] problem In-Reply-To: References: Message-ID: <2dydnWYBufjnyujdRVn-hA@powergate.ca> Robert wrote: > I have a little problem and mybe one of you has got the solution. > I would like to check if a string is in a list of strings. > The following returns true: > if 'hallo' in ['halloooo','hallooooooooo']: > pass c:\>python >>> 'hallo' in ['hallooo', 'halllloooo'] False Given that "if" is not an expression, and so "returns" nothing at all, please explain what you mean above... clearly the "in" expression is behaving as you requested... -Peter From fredrik at pythonware.com Fri Apr 16 15:21:20 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 16 Apr 2004 21:21:20 +0200 Subject: Convert from PDF to raster format image References: <8a27e309.0404161054.2a5c5ecc@posting.google.com> Message-ID: "R.Marquez" wrote: > Does any one know of a way to convert PDF documents into a raster > format, such as TIFF or JPEG? Of course to do it in Python would be > my preference, but if you know of another way to do this > programatically I would also be interested. Thanks. did you try ghostscript? http://www.cs.wisc.edu/~ghost/ http://www.ghostscript.com From hans at zephyrfalcon.org Fri Apr 16 02:00:34 2004 From: hans at zephyrfalcon.org (Hans Nowak) Date: Fri, 16 Apr 2004 02:00:34 -0400 Subject: CamelCase versus wide_names (Prothon) In-Reply-To: References: Message-ID: <407F7682.8040709@zephyrfalcon.org> Mark Hahn wrote: > We have agreed in Prothon that unlike Python we are going to be 100% > consistant in our var and method naming. We will not have run-together > words like iteritems, we are going to always have seperated words like > has_key. > > Now we are in the midst of a discussion of camelCase versus wide_names. So > far our arguments are: > > 1) CamelCase is more elegant, modern, more readable, and more efficient in > character usage. > > 2) Wide_names is cleaner, more readable, compatible with C, which is the > standard module language for Python and Prothon. Wide_names is also the > Python standard. > > Of course in the Python world you alread have wide_names as your standard, > but could you for the moment pretend you were picking your standard from > scratch (as we are doing in the Prothon world) and give your vote for which > you'd prefer? That would be wide_names. CamelCase would be tolerable. In my own code, I use a mixture: CamelCase for class names, wide_names for everything else (inspired by older Python code). Not mixedCase, mind you; IMHO, that's an atrocity. If you're going to use caps in names, then at least the first letter should be capitalized. Putting the capitals somewhere in the middle but not in the front seems very unnatural to me. -- Hans (hans at zephyrfalcon.org) http://zephyrfalcon.org/ From joe at notcharles.ca Sun Apr 4 00:24:45 2004 From: joe at notcharles.ca (Joe Mason) Date: Sun, 04 Apr 2004 05:24:45 GMT Subject: Python is faster than C References: <406F0907.96F37EA1@tunes.org> <406F6020.F1361B55@tunes.org> Message-ID: In article <406F6020.F1361B55 at tunes.org>, Armin Rigo wrote: > Joe Mason wrote: >> > The reason is that the C implementation must use a generic '<' operator >> > to compare elements, while the Psyco version quickly figures out that it >> > can expect to find ints in the list; it still has to check this >> > assumption, but this is cheap and then the comparison is done with a >> > single machine instruction. >> >> Why can't the C implementation do the same thing? > > You could, if you wanted to optimize specifically lists of integers. If > you did the result would probably be really fast. The problem is that > you can only really special-case so many types: the C code has to deal > with all cases without knowing which cases are likely. The Psyco > version quickly figures out that for this list it pays off to make a > special case for integers; with another list, the machine code would be > different, special-cased differently. Ah, good point. (In fact, not special-casing lots of things in the C code is exactly what I was arguing against in my other post.) Joe From cmg at dok.org Wed Apr 7 09:34:47 2004 From: cmg at dok.org (Chris Green) Date: Wed, 07 Apr 2004 09:34:47 -0400 Subject: Python Documentation Blows! References: <20040330181802.04141.00000304@mb-m17.aol.com> Message-ID: Peter Hansen writes: > anton muhin wrote: > >> Maybe just start a wiki based on the current documentation? It >> shouldn't be too difficult, should it? > > What part of http://wiki.wxpython.org/ is not adequate? One problem wxpython's wiki seems to have is not enough time to refactor it (coupled with the namespace changing from wxEVENT => wx.EVENT ) and lots of nodes being empty or partially duplicated. What PHP seems to have over it is taking a full docset and then allowing posts to refer to the documentation. If there could be a "official manual" / commentary section with enough people(!) to maintain the look and factor out poor hanging questions, such a project would be very useful. This is a pretty major task as the part of wikis that make it easy to add a small bit of commentary also make it hard to refactor into a coherent document. -- Chris Green I've had a perfectly wonderful evening. But this wasn't it. -- Groucho Marx From jason at tishler.net Fri Apr 30 15:30:31 2004 From: jason at tishler.net (Jason Tishler) Date: Fri, 30 Apr 2004 15:30:31 -0400 Subject: Python Image Library (PIL) build error on Cygwin In-Reply-To: <40928190.5060004@holdenweb.com> References: <40928190.5060004@holdenweb.com> Message-ID: <20040430193031.GA1728@tishler.net> Steve, On Fri, Apr 30, 2004 at 12:40:48PM -0400, Steve Holden wrote: > Yup, now I can't find the Tk library, Does the following from the Cygwin Python README help? 4. _tkinter users should note that Cygwin tcltk is really a Win32 package and hence, does *not* understand Cygwin style paths. To use the _tkinter module you must define the following environment variables: $ export TCL_LIBRARY=$(cygpath -w /usr/share/tcl$version) $ export TK_LIBRARY=$(cygpath -w /usr/share/tk$version) 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 mark at prothon.org Tue Apr 27 19:48:48 2004 From: mark at prothon.org (Mark Hahn) Date: Tue, 27 Apr 2004 16:48:48 -0700 Subject: What is good about Prothon? References: <69cbbef2.0404271534.6a7c90e6@posting.google.com> Message-ID: has wrote: > (Note: scripts are compiled, so you'll need a Mac to view source.) Can you at least make a screen snapshot available or something for the "rest of us"? From vineet at eswap.com Mon Apr 5 21:07:15 2004 From: vineet at eswap.com (Vineet Jain) Date: Mon, 5 Apr 2004 21:07:15 -0400 Subject: int('2.1') does not work while int(float('2.1')) does Message-ID: int('2.1') does not work while int(float('2.1')) does. If int can covert a float object then there is no reason why a float string should not be converted too. When I do int('2.1') I get the following error: >>> a = int('2.0') Traceback (most recent call last): File "", line 1, in ? ValueError: invalid literal for int(): 2.0 This does not seem very pythonic VJ From reverse.ku.oc.issolok at nothypgnal.delrest.co.uk Wed Apr 28 05:12:46 2004 From: reverse.ku.oc.issolok at nothypgnal.delrest.co.uk (Paul Sweeney) Date: Wed, 28 Apr 2004 09:12:46 +0000 (UTC) Subject: debugging code References: <3064b51d.0404271139.6ec7057@posting.google.com> <408ee541$0$46510$39cecf19@news.twtelecom.net> Message-ID: "Rick Ratzel" wrote in message news:408ee541$0$46510$39cecf19 at news.twtelecom.net... > > Python defines __debug__ to True by default, and False when > optimizations are enabled...meaning you can enable/disable code without > having to define/undefine vars ahead of time and without having to > change it prior to deployment. This is how the "assert" statement > works. I agree with Rick on using __debug__ not your own variables, as suggested elsewhere > You can only set __debug__ through the use of -O or -OO. There is a typo here (but all the examples that followed were correct), You can only set __debug__ *to False* through the use of -O or -OO. From peter at engcorp.com Mon Apr 12 18:01:07 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 12 Apr 2004 18:01:07 -0400 Subject: I am puzled about numbers In-Reply-To: <107m446tlvs9u01@corp.supernews.com> References: <107lvs6mree8pee@corp.supernews.com> <107m446tlvs9u01@corp.supernews.com> Message-ID: <4NqdnV5ZNrU-jObdRVn-hA@powergate.ca> A Evans wrote: > which brings me to another question seeing these patterns I am making with > numbers how random is the random function in python I mean is it really > possible for a computer to think randomly or is it a pattern like this Google can help with such questions, and it's a very good idea to get in the habit of checking there first when faced with a question like this about computers. Using the search "all about random numbers" I quickly found this: http://www.krellinst.org/UCES/archive/modules/monte/node1.html There are dozens and dozens of other such pages. -Peter From ben.held at staarinc.com Fri Apr 2 13:27:05 2004 From: ben.held at staarinc.com (Ben Held) Date: 2 Apr 2004 10:27:05 -0800 Subject: Major memory leak during embedding Python in C++ Message-ID: Having recently upgraded to Python 2.4, I am having a large memory leak with the following code built with VC++ 6.0: PyObject *pName, *pModule; Py_Initialize(); pName = PyString_FromString(argv[1]); pModule = PyImport_Import(pName); Py_DECREF(pName); PyObject* pModule2 = PyImport_ReloadModule(pModule); Py_DECREF(pModule2); Py_DECREF(pModule); Py_Finalize(); return 0; I get leaks of over 500 kb. I have another program which is much more complex, in which every call to PyImport_ReloadModule is leaking 200+ kb, even though I am calling Py_DECREF correctly. Help! From jbperez808 at wahoo.com Tue Apr 27 12:40:42 2004 From: jbperez808 at wahoo.com (Jon Perez) Date: 27 Apr 2004 16:40:42 GMT Subject: CPU usage of Python interpreter doing empty while loop under XP References: <7kpr805ou6g8ucm9rok4nodkolcp02viig@4ax.com> Message-ID: Peter Hansen wrote: > How does that help your debugging? That will tell us whether > sleep(0) is a better alternative, or whether there is really > something else you should be doing instead. > > (I have never had occasion to use "while 1: pass" in Python, ever.) > > -Peter I'm trying to debug an event-driven framework I wrote myself and there are some iffy situations where a quick and dirty way to halt execution and view the state of some variables with print is to insert a while 1: pass (or sleep(0)). The only reason sleep(0) is better than pass in my situation is that when I try to do other things under the OS before I've had a chance to break out of the program, I don't get a slowdown. From sean at sands.beach.net Tue Apr 27 13:45:42 2004 From: sean at sands.beach.net (Sean Berry) Date: Tue, 27 Apr 2004 17:45:42 GMT Subject: Could someone explain this to a newbie Message-ID: >>> text = 'zone "southernpine.com" {' >>> text.lstrip("zone \"") 'southernpine.com" {' This is expected. >>> text = 'zone "newsouthpine.com" {' >>> text.lstrip("zone \"") 'wsouthpine.com" {' This is not. What happened to the ne... I suppose that is the secret, because I have tried with other words beginning with ne and they do not work either. -- From tismer at stackless.com Thu Apr 1 21:30:08 2004 From: tismer at stackless.com (Christian Tismer) Date: Fri, 02 Apr 2004 04:30:08 +0200 Subject: Stackless Website down, Project gone, I'm dead. Message-ID: <406CD030.5010506@stackless.com> Dear Former Stackless Users, I have to use this list to announce something really bad to you, since all the Stackless lists are defunct: The Stackless project is finally dead, now and forever. If this doesn't affect you, please don't worry and just ignore it. I don't take any responsibilities for any harm brought to you, your family or your descendants because of this message, because I'm finally gone. Here is the really sad story, for all who care. ----------------------------------------------- I can't tell how sorry I am, since I really wanted it to survive until its sucessor, namely PyPy, is mature. But reality is cruel, and truth is no longer something that I can change with my small brains. I'm too old and burned out, now. On Mach 31st, some bad intruder has broken into our CVS server. (S)he has replaced all of our files by some dummy entries. This was quite bad, since the new Stackless developer group was happily hacking on after the sprint, March 10-14, and we were updating CVS on a very frequent basis. As a result, all sources of Stackless Python are totally lost, now. Since I always was a very emotion driven guy, I thought this was the right situation to say good-bye to you all. My life is ending, soon, and so is my project. We could try to find some backups, but I do say NO!, Please, do appropriate cleanup! Some more reasoning: The fact that this happened to me, as a more than old IT specialist, tells its own story about my deficiencies. Having grown beyond the age of 50, I don't deserve to lead a young and eager group of developers, anymore. Instead, I should provide them all with the survival pack to start their own endeavor. This is what I was trying, under the hood, till today. I hereby ask everybody who still happens to have an old, maybe valid copy of the repository, to update it soon. It will be vaporized in seconds, as well, and this is the path to go. I don't want any Stackless repository to survive bejond myself! The evil truth of real life has told me where my path is headed to. Please make no attempt to revive Stackless. It is completely dead, and I'm going to take it with me into my cold, lonely grave. I have spent the rest of my time on it, and now I want to rest on it, since my time is over. So please avoid to mention it any longer, not in news, not in interviews, and *please* absolutely don't use it!!! Stackless is gone, Tismer is gone, and this is good, since I already have told you all the lies that I could tell you in a lifetime. Rest In Peace forever with -- Stackfull Python -- p.s.: I've taken the capsule, short time ago. p.p.s.: This message was sent to you on April 2, to make sure that it is not misinterpreted as a bad April 1 joke. The bad joke was about that bad intruder. See you soon, in heaven or somehwere else :-) AAAAAAAHRGGGGG +:+ hi grandma:::: you're here??? -- 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 mobile +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 jwei at ciena.com Wed Apr 28 16:11:42 2004 From: jwei at ciena.com (jianchiwei) Date: Wed, 28 Apr 2004 20:11:42 -0000 Subject: asp script engine registrition Message-ID: question: I run c:\python23\Lib\site-packages\win32comext\axscript\client\pyscript.py and it told me Registered: Python Registration of Python ActiveX Scripting Engine complete. But, when I run a asp script <%@LANGUAGE=Python%>

Python - Test

I still get HTTP/1.1 500 Server Error caused by the first line of code "<%@LANGUAGE=Python%>". It seems to me that python script engine is not correctly registered. Could someone help me on this please? Thanks J.W. From imbosol at aerojockey.invalid Tue Apr 20 00:44:57 2004 From: imbosol at aerojockey.invalid (Carl Banks) Date: Tue, 20 Apr 2004 04:44:57 GMT Subject: module parameters References: Message-ID: Jim Jewett wrote: > > > I have often wanted to pass arguments to a module. > > Tyically, these are globals, such as DEBUG or VERBOSE that are set > at the top of the module -- and I want to use a different value. > For modules that provide a service (such as logging), I would like > to make my changes before the defaults are set up. > > Assuming that the loaded module is cooperative, what is the least > ugly way to pass these parameters? > > (1) Alter/Check __builtins__ > (2) Alter/Check a "well-known" module, such as settings, for an > attribute named after the loading module.* > (3) Alter/check a modsettings module specific to module mod. > (4) Use an import hook > (5) Accept that there will be some inefficiencies and reset after > the initial load. > > * I'm not aware of any such well-known module yet, but if others > agree that it sounds like a good idea, I will write one. I'm not sure if it's a common enough need to have a standard way to do it, if that's what you're suggesting. I suspect most programmers, if they do use such module "arguments", will design it so that they can be set after the module is imported. In fact, this is what I recommend. (Then again, there is PEP 329 on the table.) But, if you really need these arguments set before importing the module, then I recommend #2, and the well-known module to use is __main__. __main__ is the top level module, the one where the program begins. Just set whatever arguments you need at the top-level, and have the cooperating module import __main__ and use whatever it needs. -- CARL BANKS http://www.aerojockey.com/software "If you believe in yourself, drink your school, stay on drugs, and don't do milk, you can get work." -- Parody of Mr. T from a Robert Smigel Cartoon From jack at performancedrivers.com Fri Apr 9 18:50:20 2004 From: jack at performancedrivers.com (Jack Diederich) Date: Fri, 9 Apr 2004 18:50:20 -0400 Subject: automatically generating file dependency information from python tools In-Reply-To: References: Message-ID: <20040409225020.GA15371@performancedrivers.com> On Fri, Apr 09, 2004 at 10:16:39PM +0000, Moosebumps wrote: > Say you have a group of 20 programmers, and they're all writing python > scripts that are simple data crunchers -- i.e. command line tools that read > from one or more files and output one or more files. > > I want to set up some sort of system that would automatically generate > makefile type information from the source code of these tools. Can anyone > think of a good way of doing it? You could make everyone call a special > function that wraps the file() and detects whether they are opening the file > for read or write. If read, it's an input, if write, it's an output file > (assume there is no r/w access). Then I guess your special function would > output the info in some sort of repository, which collects such info from > all the individual data crunchers. > > The other thing I could think of is statically analyzing the source code -- > but what if the filenames are generated dynamically? I'd be interested in > any ideas or links on this, I just started thinking about it today. For > some reason it seems to be a sort of problem to solve with metaclasses -- > but I haven't thought of exactly how. > In answer to the question you /almost/ asked: http://www.google.com/search?q=python+make+replacement From steve at ninereeds.fsnet.co.uk Tue Apr 6 22:52:14 2004 From: steve at ninereeds.fsnet.co.uk (Stephen Horne) Date: Wed, 07 Apr 2004 03:52:14 +0100 Subject: OFF-TOPIC:: Why Lisp is not my favorite programming language References: <165b3efa.0403030443.4d591f04@posting.google.com> <40460dd5$0$5916$7a628cd7@news.club-internet.fr> Message-ID: <6in670lrldbjkuujle68a526293j57a7mn@4ax.com> On 6 Apr 2004 13:58:45 -0700, nish20 at netzero.net (Mike Nishizawa) wrote: >mintiSPAMBLOCK at yahoo.com (Minti) wrote in message news:... >> However when some one says that the code might be 31.? >> times slower as compared to C, kinda of scares me. Could assert such >> figures. I know speed is not the one and only goal but just wondering >> if these figures are correct. It wouldn't surprise me. LISP is normally interpreted - maybe always, though I'm not certain of that. The interpreter would be written in C. And, depending on the implementation, the built-in list operations may well be much more basic than those in Python, for instance, meaning that more of the relatively sophisticated operations will be handled using interpreted library code. Python itself is at least 10 times slower than C for many things (though the library often provides efficient algorithms that are actually faster than anything you'd write for yourself even in C). An implementation that has more of the standard operations built in, or which used just-in-time compilation etc, may well run much faster. >I would ask what the C program is doing. If it beats LISP at it's own >game which is, list processing, then that would be different. It is always possible to beat any interpreted language for speed using C if you are willing to put in the time and effort. 90% or more of interpreters were written in C themselves, and by writing directly in C you are avoiding the need for any interpreting at run-time. > I don't >think I would choose to write an enterprise application in it, but I >think it's as good a choice as anything for any type of parsing >applications. And to the smart guy who feels like he can take a stab >at me for calling lisp a parsing language... consider: a parser is, >by definition, something that analyzes or separates (input, for >example) into more easily processed components. Let's take a >document, for instance. If I wanted to parse the document and >separate it into words, I would write a parser to do so. What is a >document but a list of words separated by spaces... an especially good >application for a LISt Processing language. Parsing isn't that heavy in list processing. Neither is handling a large document. In parsing, you are mostly dealing with one symbol at a time. The way you access that symbol, whether you read it directly from a file or input stream at need or keep it in a memory buffer, is the least significant thing going on in the parser. Though the work done by most practical parsers at run-time (rather than when the parser tables are generated from the grammar) is not that complex. In most cases in parsing, the language is pretty much immaterial. Though the table-generating for, for instance, an LR-style parser (basically what a tool like yacc does) needs to do a lot of set operations on potentially quite large sets, and some fairly time consuming searches and closures. Basically, it's something I wouldn't want to do in Lisp purely for speed reasons. I have done it in Python, and the result wasn't exactly practical - though it probably could have been with more work and some C extension optimisations. With large documents, while you can see the document as being a (potentially huge) list of characters or words, you wouldn't want to use a simple flat list data structure, again for performance reasons. You wouldn't use a linked list because it would take too much time to iterate through, not to mention the potentially very large storage overhead - two pointers for a doubly-linked list takes 8 bytes, more than the average word, and that's not even considering mallocs rounding-up-to-a-multiple-of-x-bytes overhead. You wouldn't use a simple resizable array because of the time wasted on insertions and deletions, shifting the tail end backward and forward in memory. I've never done this for a mutable document (I have for an immutable document, but you can get away with a lot in that case) but I figure that I'd create a kind of database table of 'chunks', along with a few indexes into that table (using either tree or hash based methods). And style and other non-text information would probably mostly be separated out into other tables, with their own indexes. ie I would learn a trick or two from the relational database guys, who have been handling large sets of data reliably and efficiently for a long time. Actually, this in-memory relational database thing is quite a useful technique. In particular, it helps to reinforce the idea of keeping your main data in an easily accessible place, and not hidden deeply in the private internals of various of classes - so when you need to do something you didn't anticipate before, the data you need to access is easily available with maybe just an extra method or two on your datastore object. Data hiding should only be done with care IMO. Anyway, again this isn't a very big issue in terms of language selection. Python might be a pretty good choice, though, simply because there is both a convenient data-table type (list of tuples) and a convenient index type (dictionary) built-in and ready to go. Though I suspect a C extension might be needed to get good performance for a few operations with very large documents on slow machines. C++ is also in the running with the STL containers - harder to use, a little more flexible, hard to say on speed. Python may actually be faster as hashing is normally faster than red-black trees for handling indexes, but then hashes don't support efficient in-order iteration so it depends on how the data is accessed as much as anything. -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From notarangelotonio_*_no_*_ at _*_*tiscali.it Mon Apr 26 15:02:27 2004 From: notarangelotonio_*_no_*_ at _*_*tiscali.it (Tonio) Date: Mon, 26 Apr 2004 19:02:27 GMT Subject: Embedding Python in C++ Message-ID: <71djc.147368$Kc3.4878757@twister2.libero.it> Hi i'm a italian student. I must create a virtual machine which call python script from Visual C++ program. My teacher tell me use swig fror make this work. I use Swig for import in Python class, object, variables of C++, but my problem are when in C++ i must call script Python. I find many article, but i don't find a working example. Can you advise me how i call python script from C++? Have you example which can you send me (in my email)? (my script use only int, float, string and object, class). Thanks. From greg at cosc.canterbury.ac.nz Tue Apr 6 01:03:24 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Tue, 06 Apr 2004 17:03:24 +1200 Subject: Python conference slogan In-Reply-To: References: Message-ID: Dave Benjamin wrote: > Python: It starts with "P" and runs on Linux. > ;) Python: it starts with "P" and that rhymes with "C" and that stands for Cool! -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From junkmail at solumslekt.org Fri Apr 2 17:53:11 2004 From: junkmail at solumslekt.org (Leif B. Kristensen) Date: Sat, 03 Apr 2004 00:53:11 +0200 Subject: String concatenation References: <7xisgi24fm.fsf@ruckus.brouhaha.com> <406D27A7.6550A00B@alcyone.com> <406D2CD5.878EBD4E@alcyone.com> <406D2FA2.6E5118CC@alcyone.com> Message-ID: The "feature" is also submitted to the KDE bugtrack, see . Apparently, "real programmers" don't cut and paste code samples from KNode. Go figure. regards, -- Leif Biberg Kristensen http://solumslekt.org/ Validare necesse est From ramen at lackingtalent.com Sun Apr 4 23:48:55 2004 From: ramen at lackingtalent.com (Dave Benjamin) Date: Mon, 05 Apr 2004 03:48:55 -0000 Subject: Prothon, metaclasses, Zope [Was: A 'Python like' language] References: <95aa1afa.0403272243.78d60724@posting.google.com> <95aa1afa.0404011933.5cc5e959@posting.google.com> <95aa1afa.0404022235.3962343@posting.google.com> Message-ID: In article , Aahz wrote: > > Ick. That's odd -- I thought my DNS provider didn't do that kind of > thing, but I'm guessing they've been under such overload that they had > to. Please forward that message with full headers to > a****y at p***x.com -- my local spam filters shouldn't trap it. Just a few words of advice - never post your email address on Usenet unless: a) you don't mind getting flooded with spam, or b) you obfuscate it in some way Especially given the context of this conversation, it made me wince when I saw you post a secondary email address in plaintext to get around spam problems with your primary one... Peace, Dave -- .:[ dave benjamin: ramen/[sp00] -:- spoomusic.com -:- ramenfest.com ]:. : please talk to your son or daughter about parametric polymorphism. : From peter at engcorp.com Wed Apr 21 15:26:16 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 21 Apr 2004 15:26:16 -0400 Subject: Time In-Reply-To: References: Message-ID: Jonas Galvez wrote: > If I have a tuple like this: > > (year, month, day, hour, minute) > > Is there a way to automatically generate a string like this? > > "YYYY-MM-DDTHH:MM:00" > > I remember seeing something about it somewhere... wanted to be sure. You want to read about the "time" module: >>> t = (2004, 4, 21, 15, 33) >>> import time >>> time.strftime('%Y-%m-%dT%H:%M:00', t+(0,0,0,0)) '2004-04-21T15:33:00' I left the "T" in there as a literal because I don't know what you meant it to be and there's no obvious single-character substitution. -Peter From tjreedy at udel.edu Thu Apr 29 13:58:10 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 29 Apr 2004 13:58:10 -0400 Subject: Subclasses in Python References: Message-ID: You have needed edit already. To explain a bit more ... > #Private methods for class Player > def __init__(self,name): > self.name = name > self.strength = self.__class__.initial_strength > self.__class__.n +=1 > print self.__class__ print object # is same as print str(object) # ie, prints stringifies everything > Interestingly, if I do a class comparison of the form > > if self.__class__== Alien: > foo > elif self.__class__== Player > bar > > The comparison proceeds correctly. Here self.__class__ is left as the class object, as usual, and not stringified. > How can I get it to print the class > name cleanly? Do I have to convert to a > string That is what you did to print it '-) >and then use one or more string functions to clean it up? Fortunately not. Terry J. Reedy From klapotec at chello.at Thu Apr 29 17:12:48 2004 From: klapotec at chello.at (Christopher Koppler) Date: Thu, 29 Apr 2004 21:12:48 GMT Subject: Newbe-books References: Message-ID: On Thu, 29 Apr 2004 20:13:40 GMT, Sarge wrote: >Hi, >I'm newbe of python, but not of programming (a lot of Matlab, some >C, a bit of C++), I want a *good* book on python for self-study. >I'm short of money, I don't want to make any mistakes, so does >anybody have any suggestions (buy this-don't buy that)? > You could always search this group's archive via Google groups for opinions, this question comes up quite frequently. My personal preference, coming from a relatively similar background, would be O'Reilly's Learning Python, which is now out in a second edition covering the new features up to Python 2.3. But why not try the online tutorial(s) and reference, combined with the interactive experience that Python gives you, it's usually all you need if you're already familiar with programming in general. -- Christopher From fumanchu at amor.org Tue Apr 13 13:29:06 2004 From: fumanchu at amor.org (Robert Brewer) Date: Tue, 13 Apr 2004 10:29:06 -0700 Subject: Does Python compete with Java? Message-ID: Jakub Fast wrote: > not-very-readable syntax: operator overloads and static > methods. is this an issue that is argued over? Those are (at least) two issues, but, yes, they are argued over. You might want to search comp.lang.python and the python-dev mailing list for examples of each; there are quite a few. The syntax for staticmethod (and classmethod, etc.) is currently being discussed in terms of decorators in PEP 318: http://www.python.org/peps/pep-0318.html. The use of a new keyword 'static' is not a dictator-approved option, IIRC; however, other syntaxes are being actively developed. Read the PEP. Generic syntax mangling (like '~~>') is not happening anytime soon, I don't think. Again, you should probably search python-dev for a pronouncement from Guido on that issue, but previous conversations we've had here generally end with some Pythonista saying: "LISP is over there ==>" Saying, in effect, that it isn't Pythonic. Greg Ewing was thinking specifically on getting "and", "or" and "not" to be overridable: http://groups.google.com/groups?group=comp.lang.python.*&selm=c1bobu%241 g1p9e%241%40ID-169208.news.uni-berlin.de&rnum=1 I'm not sure how far he got, but I'd still appreciate it myself (Greg? <:) I'm still using & | and - instead, since those are overridable. Robert Brewer MIS Amor Ministries fumanchu at amor.org From gerrit at nl.linux.org Tue Apr 20 07:03:43 2004 From: gerrit at nl.linux.org (Gerrit) Date: Tue, 20 Apr 2004 13:03:43 +0200 Subject: How to check if a path *could* be a legal path? In-Reply-To: References: Message-ID: <20040420110343.GB17588@nl.linux.org> Maciej Sobczak wrote: > 1. > s = 'C:\file.txt' > > the above is potentially a valid path on my system. > > 2. > s = 'cc:/^- =#jk\kj+.+?! :-)' > > the above is rather invalid and I would like to check it somehow before > I even try to create the file. > > Does the Python library contain a functionality that allows to achieve > this goal? No. It's different on different platforms. On Unix, for example, everything without \0 (ascii 0) is legal. I don't know the rules Windows needs, but apparantly they are more strict, or else the second path would be potentially valid as well. There may be a 3rd party package that has this functionality, however, or something in a windows-specific package. Can't you pass it to exists? Maybe os.path.exists makes a different between ENOENT and invalid paths... Gerrit. -- Weather in Twenthe, Netherlands 20/04 12:25: 12.0?C Scattered clouds partly cloudy wind 4.0 m/s SSW (57 m above NAP) -- Experiences with Asperger's Syndrome: EN http://topjaklont.student.utwente.nl/english/ NL http://topjaklont.student.utwente.nl/ From tjreedy at udel.edu Fri Apr 30 20:40:19 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 30 Apr 2004 20:40:19 -0400 Subject: calling functions at the same time References: <1095ijdb5jotvf1@corp.supernews.com> Message-ID: "Bart Nessux" wrote in message news:c6unuq$d0f$1 at solaris.cc.vt.edu... > I need to ping 4 hosts at exactly the same time from the same machine (I > plan to timestamp the pings) to test and measure network conditions over > different routes to different hosts. Putting all the ping hosts in a list > and looping through it is not a fair or balanced way to do this because of > the time differences. If you do 24 trials, one for each permutation, the result would be about as fair and balanced as you can get. Terry J. Reedy From aahz at pythoncraft.com Mon Apr 12 22:20:26 2004 From: aahz at pythoncraft.com (Aahz) Date: 12 Apr 2004 22:20:26 -0400 Subject: list comprehensions References: Message-ID: In article , Dave Benjamin wrote: >In article , Aahz wrote: >> In article , >> Elaine Jackson wrote: >>> >>>List comprehensions don't work the way you intuitively expect them >>>to work. I realize many people have no intuitions about how list >>>comprehensions 'should' work, so if you recognize yourself in this >>>description, feel free to go back to whatever you were doing before. If >>>you're still here, though, I invite you to consider the following >>>definition: >> >> Short response: don't write complex listcomps. > >Would you consider a 2D loop too complex for a listcomp? It depends. If it's something simple, go ahead. If you've got an ``if`` or a complex expression, I'd think real hard. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Why is this newsgroup different from all other newsgroups? From klappnase at web.de Tue Apr 27 05:37:06 2004 From: klappnase at web.de (klappnase) Date: 27 Apr 2004 02:37:06 -0700 Subject: Question on creating Tkinter Widgets References: Message-ID: "Adonis" wrote in message news:... > I am creating some widgets by inheriting from Tkinter.Frame and populating > the frame with whatever the widget will be then creating certain > attributes/methods to be accessed later. My question is, is this a poper way > to create widgets or should I take a different approach? > > Any help is greatly appreciated. > > Adonis So far this sounds perfectly "proper" to me. Usually when I create my own widgets it looks like: class Mywidget(Tkinter.Frame): def __init__(self, master, special_attribute='default', *args, **kw): Tkinter.Frame.__init__(self, master, *args, **kw) def widget_method1(self): <.......> (etc.) Sounds like you are doing quite the same. Regards Michael From No.Spam.mc at No.Spam.mclaveau.No.Spam.com Sun Apr 18 14:13:10 2004 From: No.Spam.mc at No.Spam.mclaveau.No.Spam.com (Michel Claveau/Hamster) Date: Sun, 18 Apr 2004 20:13:10 +0200 Subject: Creating function object from text References: <40815ab3$0$16479$61fed72c@news.rcn.com> Message-ID: Bonjour ! Ce code fonctionne, chez moi : src='''def toto(i): return i*2''' exec src print toto(3) # => 6 Mais, dans certains cas, je suis oblig? d'ajouter : global toto Bonne soir?e ! -- Michel Claveau From antivirus at mairs.de Thu Apr 1 03:55:45 2004 From: antivirus at mairs.de (antivirus at mairs.de) Date: Thu, 01 Apr 2004 10:55:45 +0200 Subject: Sicherheitshinweis Message-ID: <20040401091132.63FD2AFF3@mail.mairs.de> Eine Mail, die von dieser Adresse versendet wurde, enth?lt m?glicherweise einen Virus. Aufgrund der Tatsache, dass viele aktuelle Viren und Mailw?rmer bestimmte Dateianh?nge verwenden, werden diese automatisch von unserem Server abgeblockt. Bitte ?berpr?fen Sie Ihr System auf Viren oder geben Sie Ihrem System-Administrator Bescheid. Viren und W?rmer f?lschen oft die Absenderadresse. M?glicherweise erreicht diese Meldung daher nicht den eigentlichen Verursacher. In diesem Fall bitten wir Sie, diese Nachricht zu ignorieren. Sollten Sie bewusst eine Datei an eine unserer Mailadressen gesendet haben und diese wurde geblockt, m?chten wir Sie bitten, sich mit dem Empf?nger der Mail in Verbindung zu setzen. A mail sent by this account is possibly infected with a virus. Viruses and worms often use mail attachments with special extensions, that are blocked by our server. Please check your system for viruses, or ask your system administrator to do so. Viruses and worms often fake the sender address of a mail. Perhaps you are not the sender of this email. If so, please excuse and ignore this mail. If You wanted to send us a file that was blocked, please contact the recipient of the mail. From: python-list at python.org To: spamfalle at mairs.de Subject: *****SPAM***** Mail Delivery (failure datenschutz at falk.de) Matching Subject: *mail delivery (failure* From jepler at unpythonic.net Tue Apr 20 14:50:59 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Tue, 20 Apr 2004 13:50:59 -0500 Subject: Getting output from embedded python program In-Reply-To: References: <2aa196bb.0404190554.74631058@posting.google.com> <4084B179.6020807@magma-da.com> Message-ID: <20040420185058.GF2937@unpythonic.net> PyRun_File expects dicts for both the third and fourth parameters. The code you wrote appears to use one module object and one dict object, but in the (incomplete, non-runnable) code you included, you didn't even initialize evalModule/evalDict until after the PyRun_File call, nor did you check for failures along the way. Jeff From Kyler at news.Lairds.org Wed Apr 7 21:08:21 2004 From: Kyler at news.Lairds.org (Kyler Laird) Date: Thu, 08 Apr 2004 01:08:21 GMT Subject: Pyrex list is down References: Message-ID: <74jek1-3qs.ln1@snout.lairds.org> Paul Prescod writes: >It seems like nothing has gone in or out for days: >http://lists.copyleft.no/pipermail/pyrex/2004-April/thread.html I hate mailing lists anyway. I'd much rather use Usenet. I automatically select any articles in this group with "pyrex" in the subject. --kyler From project2501 at project2501.cor Wed Apr 7 06:27:58 2004 From: project2501 at project2501.cor (project2501) Date: Wed, 07 Apr 2004 11:27:58 +0100 Subject: python thread scheduler? References: Message-ID: to clarifgy, i'm seeing responec times as low as 0.3 seconds when the client has 5 worker threads... rising to an average of about 8 seconds with 50 threads... and more ith 100 threads. here is what the python threads do (simplified): while (work units remaining): take time send request to server get responce from server take time record time difference sleep for a small interval (to yield, and to vary the request rate) reduce work unit by 1 i get flat graphs of responce time against request rate (which doubles a specified number of times, after 10 work units. i would expect the graphs to start to vary non-linearly ... especially at higher numbers of threads (say 50 or more) and request rates of 256 per second or more ... From greg at cosc.canterbury.ac.nz Thu Apr 29 07:01:14 2004 From: greg at cosc.canterbury.ac.nz (greg) Date: Thu, 29 Apr 2004 23:01:14 +1200 Subject: ANN: Pyrex 0.9.1 Message-ID: Pyrex 0.9.1 is now available: http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/ Enhancements: * Calling of inherited C methods * Python class __modname__ is set properly * Test suite available for download Plus numerous bug fixes -- see CHANGES.txt in the distribution or on the web page for details. What is Pyrex? -------------- Pyrex is a new language for writing Python extension modules. It lets you freely mix operations on Python and C data, with all Python reference counting and error checking handled automatically. From deetsNOSPAM at web.de Tue Apr 27 08:15:32 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Tue, 27 Apr 2004 14:15:32 +0200 Subject: Regular Expressions References: Message-ID: ..:: sjf ::.. wrote: > Thanks. And now, let's assume that I have a following strings: > S1 = "B - TYPE2: any_text_2 TYPE3: any_text_23" > S2 = "C - TYPE2: any_text_3" > > and I want to have one regular expression that produce only following > data: ("B", "any_text_2") > ("C", "any_text_3") > that is, any characters starting TYPE3 till end will be omitted. > How do make this? r"(.) TYPE. : ([^ ]*)" -- Regards, Diez B. Roggisch From p_s_oberoi at hotmail.com Wed Apr 28 00:27:42 2004 From: p_s_oberoi at hotmail.com (Paramjit Oberoi) Date: Tue, 27 Apr 2004 23:27:42 -0500 Subject: Is Perl *that* good? References: <108q51j4dscn7dc@corp.supernews.com> <87fzaqmm8t.fsf@strauser.com> <38ec68a6.0404262308.50029919@posting.google.com> Message-ID: >> if myregex.match(line): >> xyz = myregex.lastm.group('xyz') > > Hmm. The reason this hasn't been done is that it makes the match > method non-reentrant. For example, suppose you call some functions in > between the matching and use of the matched object, like this: Another thing in perl that makes regexes convenient is the 'default' variable $_. So, maybe the following could be done: line_a = re.compile(...) line_b = re.compile(...) rx = re.context() for rx.text in sys.stdin: if rx(line_a).match(): total += a_function() + rx[1] elif rx(r'^msg (?P.*)$').match(): print rx['text'] elif rx(line_b).match(munge(text)): print 'munged text matches' // similarly rx.{search, sub, ...} But, as Peter Hansen pointed out, maybe this is more suited to a personal utility module... What are the considerations for whether something should or shouldn't be in the standard library? From aahz at pythoncraft.com Sun Apr 11 01:20:34 2004 From: aahz at pythoncraft.com (Aahz) Date: 11 Apr 2004 01:20:34 -0400 Subject: new-style class instance check References: Message-ID: In article , Richard Gruet wrote: > >How to determine that an object o is for sure an instance of a new-style >class, without knowing of which specific class ? >That is, if I define a function: > >def isNewStyleClassInstance(o): > pass ## to be completed > >.. I want to pass the following test: > >def C: pass >def CNew(object): pass > >assert not isNewStyleClassInstance(C()) # InstanceType >assert isNewStyleClassInstance(CNew()) >assert not isNewStyleClassInstance(1) # instance of type int ># and naturally for all other types of o the function should return False. class UserClass(object): pass class CNew(UserClass): pass You can automate this within a module by setting __metaclass__. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Why is this newsgroup different from all other newsgroups? From loic at yermat.net1.nerim.net Wed Apr 28 15:17:17 2004 From: loic at yermat.net1.nerim.net (Yermat) Date: Wed, 28 Apr 2004 21:17:17 +0200 Subject: Path ... where is my application's home dir? In-Reply-To: References: Message-ID: Duncan Booth a ?crit : > Tim Golden wrote in > news:mailman.81.1083164606.25742.python-list at python.org: > > >>>And yes, the best place to store this information would be in >>>the user's >>>home dir, but then: Where is it? How to find it under Windows - every >>>version of windows changes the place for home dirs. It would >>>be nice to >>>have something like this in a system/version independet way: >>> >>>sys.users_home_dir >>> >>>Is there anything like it in Python? >> >>There's nothing that strictly does that. You could >>use os.path.expanduser ("~") but in Windows (at least >>on my Win2K box) it returns "c:/" which is just about >>acceptable for a one-user machine, but obviously not >>for multi-user. >> >>The usual way to do this on Windows is to use the >>winshell functions from pywin32: >> >> >>from win32com.shell import shell, shellcon >>print shell.SHGetPathFromIDList ( >> shell.SHGetSpecialFolderLocation (0, shellcon.CSIDL_APPDATA) >>) >> >> >>which, on my machine, gives: >> >>C:\Documents and Settings\goldent\Application Data > > > A simpler way to get the same information: > > import os > print os.environ['APPDATA'] > And for the user dir, you can do (at least on Win2000, not try elsewhere) : os.getenv('HOMEDRIVE') + os.getenv('HOMEPATH') -- Yermat From peter at engcorp.com Sat Apr 24 13:20:21 2004 From: peter at engcorp.com (Peter Hansen) Date: Sat, 24 Apr 2004 13:20:21 -0400 Subject: command-line args In-Reply-To: <408A9C33.4070401@mlug.missouri.edu> Message-ID: (Michael, I'm keeping this on the mailing list, if you don't mind. I prefer not answering offline questions, unless the customer is a paying one. ;-) Michael [mailto:mogmios at mlug.missouri.edu] wrote: > Peter Hansen wrote: > > Michael wrote: > > >What do you do about multiple processes (of the same program) > > >running at once? Save to /tmp//globals.py or something like > > >that? > > > >Why would you save anything? If you're just parsing command-line > >arguments, the settings are not persistent, are they? Just kept in > >memory for the duration of the current program. If you have multiple > >processes, each gets its own command line arguments and thus its own > >in-memory values from globals.py. > > > In what way can you create a module and import it from other > modules without saving it as a file? > [snip] > No interest in persisitance. What I'm doing right now creates > the globals_.py file when command-line options are > parsed and deletes > globals_.py* when the program stops. What I mean is this. You create globals.py ahead of time, the usual way with a text editor. It can contain defaults if you wish, or be empty. E.g.: (globals.py) logging = False userName = None timeout = 5.0 Then you simply import this where you are doing the command-line argument parsing: import globals, getopt opts, args = getopt.getopt(sys.argv[1:], 'at:fse:') # or whatever for opt, val in opts: if opt = '-t': globals.timeout = float(val) # etc etc Then, elsewhere where you need to use the values, just do another import. (some code that needs to know the timeout) import globals, time time.sleep(globals.timeout) # or whatever There is no reason to create the .py file on the fly... (This works because after the first import of a module inside an application, subsequent imports do *not* re-read the .py file, but simply get a reference to the already-imported module object from the sys.modules dictionary.) -Peter From roy at panix.com Mon Apr 5 21:02:24 2004 From: roy at panix.com (Roy Smith) Date: Mon, 05 Apr 2004 21:02:24 -0400 Subject: Does Python compete with Java? References: <8b336527.0404051337.51bb4a1b@posting.google.com> <1073su4etm95p35@news.supernews.com> Message-ID: "John Roth" wrote: > recently some of the industry gurus have been questioning whether the > additional complexity of static typing and other Java complexities is > paying its weight as compared to Python, especially when used in a > TDD type development environment. Yeah, tell me about it. I've been playing around with some JSP stuff lately. Here's a method I wrote: protected void doLogin (HttpServletRequest request, HttpServletResponse response) throws ServletException { String name = (String) request.getParameter ("name"); String password = (String) request.getParameter ("password"); Connection connection = getDbConnection (request); try { LoginModel model = new LoginModel (connection); boolean loginIsValid = model.validate (name, password); if (loginIsValid) { makeMainPage (request); forward (request, response, "/main.jsp"); } else { forward (request, response, "/badLogin.jsp"); } } catch (SQLException exception) { throw new ServletException (exception); } catch (IOException exception) { throw new ServletException (exception); } } It's just filled with extraneous crap that's only there to make the java complier happy and has nothing to do with the logic of my application. The type declarations and casts are just the beginning. The interface I'm inheriting from requires that the only exception I throw be ServletException, so I need to catch all the others are re-throw. Here's what the same logic would look like in Python, as a mechanical transliteration: def doLogin (request, response): name = request.getParameter ("name"); password = request.getParameter ("password"); connection = getDbConnection (request); model = LoginModel (connection); loginIsValid = model.validate (name, password); if loginIsValid: makeMainPage (request); forward (request, response, "/main.jsp"); else: forward (request, response, "/badLogin.jsp"); 13 lines of code instead of the original 26! This 2:1 ratio seems to be pretty typical in my experience. It's not that I'm cramming more application logic onto each line in the Python version, it's that I'm getting rid of the fluff that takes up lines without adding anything useful. The end result is that it's harder to write, and the effort that goes into making the compiler happy is that much less effort that I can put into making sure I really understand how my application should be designed, and testing it. It's a seeing the forest for the trees kind of issue. I think it's also a lot easier to read and understand the Python version. Pretty much every line maps directly to the application logic, with very little overhead. Found on the web (http://www-users.cs.york.ac.uk/~susan/joke/foot.htm)... > How to Shoot Yourself In the Foot > [....] > Java > You locate the Gun class, but discover that the Bullet class is abstract, so > you extend it and write the missing part of the implementation. Then you > implement the ShootAble interface for your foot, and recompile the Foot > class. The interface lets the bullet call the doDamage method on the Foot, > so the Foot can damage itself in the most effective way. Now you run the > program, and call the doShoot method on the instance of the Gun class. First > the Gun creates an instance of Bullet, which calls the doFire method on the > Gun. The Gun calls the hit(Bullet) method on the Foot, and the instance of > Bullet is passed to the Foot. But this causes an IllegalHitByBullet > exception to be thrown, and you die. They don't have one for Python, but I expect it would be something like this: You create a Foot object and call its shoot() method. The bullet makes a hole in your foot, but by that time you've gotten dragged into a huge flamewar about the relative merits of spaces vs. tabs for indentation and barely notice the pain. From fredrik at pythonware.com Wed Apr 21 14:15:53 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 21 Apr 2004 20:15:53 +0200 Subject: Stupid Regex Question References: Message-ID: Jonas Galvez wrote: > And I do it by 'hand' hehe :-) I didn't do any 'top-posting' at all, a few posts back, you "top-posted" a followup to your own post. From alexanro at stud.ntnu.no Sun Apr 18 18:02:20 2004 From: alexanro at stud.ntnu.no (=?iso-8859-1?q?Alexander_R=F8dseth?=) Date: Mon, 19 Apr 2004 00:02:20 +0200 Subject: Pygame References: Message-ID: I pretty much agree with you, that Python should not become to huge. > I ask again what you think should be the criteria for including > something in the standard distribution. I would say that Python should include anything that involves hardware access on a relatively low level, and have the rest as external modules and packages. Access to fullscreen 2d-graphics, and possibly 3d-graphics as well are just as "natural" as access to network cards, harddrives or any other piece of hardware. I just don't see the logic in obmitting it. - Alexander From mwh at python.net Thu Apr 1 12:25:26 2004 From: mwh at python.net (Michael Hudson) Date: Thu, 1 Apr 2004 17:25:26 GMT Subject: ANNOUNCE: 'goto' for Python References: Message-ID: Camilo Olarte writes: > >> Entrian Solutions is pleased to announce version 1.0 of the 'goto' > >> module. > >> > >> This adds the 'goto' and 'comefrom' keywords to Python 2.3, adding > >> flexibility to Python's control flow mechanisms and allowing Python > >> programmers to use many common control flow idioms that were previously > >> denied to them. > > >>>>>> What is the day today ? Oh yes the first of April ! <<<<<< > > OOUCH ! I Almost believe it! There's nothing to believe: it works! Cheers, mwh -- "Sturgeon's Law (90% of everything is crap) applies to Usenet." "Nothing guarantees that the 10% isn't crap, too." -- Gene Spafford's Axiom #2 of Usenet, and a corollary From xiaohua_sun at yahoo.com Sat Apr 17 02:15:30 2004 From: xiaohua_sun at yahoo.com (SunX) Date: 16 Apr 2004 23:15:30 -0700 Subject: newbie question on gnuplot.py References: <337e6cd5.0404152030.17da017e@posting.google.com> Message-ID: <337e6cd5.0404162215.32424c00@posting.google.com> Thank you Peter, and I forgot to mention it is running on Win/2000 and XP, both had the same problem. Also ran pgnuplot.exe, according to README. Nothing worked. Has anyone had the luck of runnnig gnuplot.py on windows? Thanks again Howard "peter" wrote in message news:... > "SunX" wrote in message > news:337e6cd5.0404152030.17da017e at posting.google.com... > > I've got python, Numeric, gnuplot all installed but am having a hard > > time to install gnuplot.py correctly. Tried to follow the documents, > > including the readme, ... but always getting "ImportError: No module > > named gnuplot" or "ImportError: No module named Gnuplot". And my > > directorey only has _Gnuplot.py, not Gnuplot anyway. > > Help please. > > you should probably look where Gnuplot.py got installed (have no idea what > platform you're on, or how you installed it) and make sure that this > directory is in your PYTHONPATH.. > > also, since you're looking at plotting packages, you might want to check out > matplotlib.. > cheers. > peter From ramen at lackingtalent.com Mon Apr 5 02:57:19 2004 From: ramen at lackingtalent.com (Dave Benjamin) Date: Mon, 05 Apr 2004 06:57:19 -0000 Subject: Fake post alert(was: Stackless Website down, Project gone, I'm dead.) References: <20040402195104.186481807.eric@zomething.com> Message-ID: In article , Christian Tismer wrote: > Eric @ Zomething wrote: > >> someone identified as "Christian Tismer" wrote: >> >> >>>I don't deserve this honor, since I didn't write that nonsense. >>>But many thanks, anyway. >> >> >> per the headers rec'd- >> >> this post: gd31e.g.pppool.de ([80.185.211.30] >> the fool post: gd31e.g.pppool.de ([80.185.211.30] > > Yes, it was the same company network. Not going into details... > Christian Tismer doesn't lock his workstation! I'm telling!! =) Cheers, Dave -- .:[ dave benjamin: ramen/[sp00] -:- spoomusic.com -:- ramenfest.com ]:. : please talk to your son or daughter about parametric polymorphism. : From __peter__ at web.de Sun Apr 4 16:29:48 2004 From: __peter__ at web.de (Peter Otten) Date: Sun, 04 Apr 2004 22:29:48 +0200 Subject: Processes with strange behavoir References: Message-ID: Markus Franz wrote: > Today I created a script called load.py for using at the command line > written in Python 2.3. > This script should load as many websites as given on the comand line and > print them with a seperation string to stdout. The loading was done in > parallel. (I used processes for this.) > > The script was started by the following command: > > ./load.py en 58746 http://www.python.com > > Well, everything was fine. Then I wanted to load a second website and so I > started the script with the following command: > > ./load.py en 58746 http://www.python.com http://www.linux.org > > The behaviour was strange: The last website (http://www.linux.org) was > loaded and printed twice. > > Then I started the script for a third time with the following command: > > ./load.py en 58746 http://www.python.com http://www.linux.org > http://www.suse.com > > The result was: First websites was loaded and shown once, second website > twice, and the third website was loaded and shown for four times! > > (This behaviour occurs with ANY address given to the script...) > > > Does anybody know an answer to my problem??? I think the structure of your script should be import os, sys for arg in sys.argv[1:]: pid = os.fork() if pid == 0: print arg # placeholder for the download routine break As you have omitted the break statement, each child will complete the for loop and thus continue to fork() for the remaining entries in sys.argv[1:]. Peter From moosebumps at moosebumps.com Fri Apr 9 20:38:02 2004 From: moosebumps at moosebumps.com (Moosebumps) Date: Sat, 10 Apr 2004 00:38:02 GMT Subject: automatically generating file dependency information from python tools References: <107eag4pnl2ar35@news.supernews.com> Message-ID: > I'm not entirely clear on what the purpose of this is. I normally > think of "makefile" type information as something needed to compile > a program. This is something that isn't usually needed for Python > unless you're dealing with C extensions. Then I'd suggest looking at > SCons (www.scons.org). Well sorry for being so abstract, let me be a little more concrete. I am working at a video game company, and I have had some success using Python for tools. I am just thinking about ways to convince other people to use it. One way would be to improve the build processes, and be able to do incremental builds of art assets without any additional effort from programmers. Basically I'm trying to find a way to do some work for free with python. The idea is that there are many different types of assets, e.g. 3D models, textures/other images, animations, audio, spreadsheet data, etc. Each of these generally has some tool that converts it from the source format to the format that is stored in the game on disk / in memory. Hence they are usually simple command line data crunchers. They take some files as input and just produce other files as output. Currently, we don't have time to generate the dependency information necessary for incremental building, so we generally just build everything over again from scratch, which takes 20 PCs the entire night. The problem is that the pipeline changes frequently, and nothing is really documented, especially the dependencies. It would be nice if there was a way to automatically get these from the individual data crunchers, which may be written by many different people. It eliminates the redundancy of having dependency information in the source code of the individual tools, and also in a separate file that specifies dependency info (like a makefile). So instead rebuilding the whole game, or having to know exactly which files to rebuild (which some people know, but many others don't), the "make" tool would be able to read the dependency information generated, and check dates on the source files to see what changes, and build the minimum number of things to get the game up to date. Currently lots of unnecessary things are rebuilt constantly. > What I'm getting is that you want to tie the individual programs > to the files that they're processing. In other words, build a catalog > of "if you have this kind of file, these are the availible programs that > will process it." Well, that is not exactly the point, but hopefully that information would fall out of the automatic processing of the individual command line tools. > So the basic question is: are the files coming in from the command > line or are they built in? If the latter, I'd probably start out by pulling > strings that have a "." or a "/" or a "\" in them, and examining the > context. Or look at calls to modules from the os.path library. They could be either "statically" specified in the source code, or only known at runtime. > More than likely you'll find a number of patterns that can be > processed and that will deal with the majority of programs. The > thing is, if you've got a bunch of programmers doing that kind > of work, they've probably fallen into habitual ways of coding > the repetitive stuff. Yes, that is true, and everything works OK now, but there are thousands and thousands of lines of redundant code, and the build process is very slow. I'm just trying to separate out the common parts of every tool, rather than having all that information duplicated in dozens of little command line utilities. MB From afriere at yahoo.co.uk Fri Apr 23 01:10:14 2004 From: afriere at yahoo.co.uk (Asun Friere) Date: 22 Apr 2004 22:10:14 -0700 Subject: Deleting objects - my earler post got garbled References: <40883067.4000702@v.loewis.de> Message-ID: <38ec68a6.0404222110.43416e1d@posting.google.com> "Martin v. L?wis" wrote in message news:<40883067.4000702 at v.loewis.de>... > There is no way to explicitly delete an object in Python. So what does "del " actually do then? From No.Spam.mc at No.Spam.mclaveau.No.Spam.com Fri Apr 23 15:44:07 2004 From: No.Spam.mc at No.Spam.mclaveau.No.Spam.com (Michel Claveau/Hamster) Date: Fri, 23 Apr 2004 21:44:07 +0200 Subject: Paris python user group? References: <408795ee$0$25893$79c14f64@nan-newsreader-02.noos.net> Message-ID: Bonsoir ! L'id?e est int?ressante. Je serait assez tent?, s'il n'y avait pas cette s?gr?gation pro-parisienne. C'est vrai, quoi ! Pourquoi vous limiter ? Paris ? Il y a des coins nettement moins pollu?s que Paris, et donc plus productif (pythoniquement parlant). Vive l'Ard?che ! @+ -- Michel Claveau From moosebumps at moosebumps.com Fri Apr 9 20:39:55 2004 From: moosebumps at moosebumps.com (Moosebumps) Date: Sat, 10 Apr 2004 00:39:55 GMT Subject: automatically generating file dependency information frompython tools References: Message-ID: > > In answer to the question you /almost/ asked: > > http://www.google.com/search?q=python+make+replacement > That is definitely of interest to me, but I would want to go one step further and automatically generate the dependency info. I haven't looked specifically at these make replacements, but I would assume you have to use a makefile or specify dependency info in some form like a text file. What I am looking for is a way to automatically generate it from the source code of the individual tools that the make program will run, or by running the tools in some special mode where they just spit out which files they will read/write. MB From piet at cs.uu.nl Mon Apr 5 11:49:38 2004 From: piet at cs.uu.nl (Piet van Oostrum) Date: 05 Apr 2004 17:49:38 +0200 Subject: Working with bytes. References: <406EE606.4000604@yahoo.com> <406f33b6$0$30963$3a628fcd@reader1.nntp.hccnet.nl> <4071273d$0$132$3a628fcd@reader1.nntp.hccnet.nl> Message-ID: >>>>> Bernhard Herzog (BH) wrote: BH> Piet van Oostrum writes: >> Yes, you could in principle use 94 characters. There is a scheme called >> btoa that encodes 4 bytes into 5 ASCII characters by using BASE85, but I >> have never seen a Python implementation of it. It shouldn't be difficult, >> however. BH> Is that the same as PDF/PostScript Ascii85? If so, there's an BH> implementation somewhere in reportlab, IIRC. They are slightly different AFAIK. Postscript uses '~' and btoa uses 'x' as terminating character. For the OP's use it doesn't matter of course. -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP] Private email: P.van.Oostrum at hccnet.nl From Holger.Joukl at LBBW.de Mon Apr 5 07:50:37 2004 From: Holger.Joukl at LBBW.de (Holger Joukl) Date: Mon, 5 Apr 2004 13:50:37 +0200 Subject: python processes names Message-ID: >>By default if we have many different python processes running >>simultaneously, then we can only see python python python for three >>different python processes. I would much rather see >>first_python_program_name.py, second_python_program_name.py and >>third_python_program_name.py listed by ps. You might want to make the scripts executable by 1 .chmod u+x .py 2. putting s.th. like #! /usr/local/bin/python as the first line of the script files (with your appropriate python interpreter path) and start them directly from the command line with ./