From 00515879256 at fastwebnet.it Mon Mar 22 06:45:28 2004 From: 00515879256 at fastwebnet.it (Glauco) Date: Mon, 22 Mar 2004 12:45:28 +0100 Subject: httplib throw a proxy Message-ID: <%lA7c.4248$jY1.3441@tornado.fastwebnet.it> I'm using a library based on httplib. Recently i've done a conversion for use of https with a key and certificate file. This goes perfectly :-) . Now, the problem is passing throw an http_proxy. It seems because httplib (based on socket.py) try to autenticate on the proxy. I'm only with this problem ? it's impossible :-| any ideas ? thank's all Glauco From fma at doe.carleton.ca Sat Mar 27 23:48:39 2004 From: fma at doe.carleton.ca (Fred Ma) Date: 28 Mar 2004 04:48:39 GMT Subject: Choosing Perl/Python for my particular niche References: <40652B0D.7C313F77@doe.carleton.ca> Message-ID: <40665A39.DF0AC455@doe.carleton.ca> Petri wrote: > > In article <40652B0D.7C313F77 at doe.carleton.ca>, Fred Ma says... > > One thing I expect to have to do is to modify design > > files. For example, there is a tool which takes ASCII > > hardware desscription language (HDL) and converts it > > to a C++ (augmented by hardware simulation library). > > The translator is freeware, so has limitations which I > > have to make up for by tweaking the HDL code. > > The translator, is it doing the Verilog stuff you mention later in the thread? > Why not check if you can't replace the translator altogether with an existing > Perl module: > http://search.cpan.org/search?query=verilog&mode=all > > Well, I know nothing about your problem area, but it's a tip in case you hadn't > thought about checking CPAN. > > Petri Actually, I was spending much of last week installing many of those tools! The translater (verilator) is Perl-based, written by Wilson Snyder (author of many of those tools) and relies on many of those tools. But thanks for the tip... Fred From john at neggie.net Wed Mar 24 15:18:17 2004 From: john at neggie.net (John Belmonte) Date: Wed, 24 Mar 2004 15:18:17 -0500 Subject: portable /dev/null again In-Reply-To: <16481.60337.370411.907718@montanaro.dyndns.org> References: <4061D154.8090809@neggie.net> <16481.60337.370411.907718@montanaro.dyndns.org> Message-ID: <4061ED09.1080506@neggie.net> Skip Montanaro wrote: > How about: > > class nullFile: > def _null(self, *args, **kwds): > pass > > def __getattr__(self, name): > return self._null Hi, Unless I'm misunderstanding your code, this object is not going to give me a legitimate file descriptor that I can pass to another program. -John -- http:// if ile.org/ From newsgroups at jhrothjr.com Fri Mar 26 13:47:46 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Fri, 26 Mar 2004 13:47:46 -0500 Subject: A 'Python like' language References: <40645d8f$0$10775$afc38c87@news.easynet.co.uk> Message-ID: <1068up4kn49778@news.supernews.com> "David MacQuigg" wrote in message news:p1u860l6q98sc6ppihje55ptna298ub7si at 4ax.com... > On Fri, 26 Mar 2004 16:42:54 +0000, Peter Hickman > wrote: > > >Well after all this discussion it would appear that a 'Python like' > >language has appeared => Prothon. http://www.prothon.org/index.html > > > >Very alpha, sort of like Python (if you consider the indenting is what > >makes Python unique) and sort of Ruby in its use of prefixes to define > >scoping etc (although there is no reference to this trait being borrowed > >from Ruby). It also quotes Self as being an influence. > > Very interesting ... Yes, especially since they didn't learn their lessons about tab as an indentation character. That means that I can't send a Prothon program (or snippet from one) using Outlook Express, which automaticlly strips tabs from the front of lines, thus destroying the indentation. An interesting language that has just dropped off of my radar screen as being unusable in my environment. John Roth From emile at fenx.com Tue Mar 2 14:53:05 2004 From: emile at fenx.com (Emile van Sebille) Date: Tue, 2 Mar 2004 11:53:05 -0800 Subject: python.exe vs pythonw.exe difference? References: Message-ID: Tim: > [Thomas] > > I get exactly the same, on Win XP Pro, both for sys.stdout and > > sys.stderr. > > That's good to know! Thanks. > > > ... > > Since it seems XP shows the same behaviour than win98SE, has the > > behaviour of Python changed? Were IOErrors ignored on sys.stdout or > > sys.stderr in earlier versions? > > No, the same program fails the same way here under pythonw 2.2.3 and 2.1.3 > (with s/file/open/ and s/True/1/). The OP wasn't clear about what "it" > meant, though (in "it used to work"). I guess it's most likely he meant > running Zope 2.5 as a service used to work, not that running Zope 2.5 by > hand from a DOS box with pythonw used to work, but don't know. It's > certainly possible that something relevant changed in Zope, and/or in how > Zope tries to live with Windows services. To clarify, at that site I'm migrating from zope2.5/python2.1/win2k box to zope2.7/python2.3/winxppro. When "it used to work" I was referring to my product running within zope as a service. For initial debugging in the new environment, I started in console mode. Once things stabilized, I started the service up and the problem surfaced. Backtracking through the code I found the service starting the application as per my earlier post with pythonw.exe which led me to the direct comparison. It did look like there'd been some significant refactoring going on within zope and windows service interaction, but replicating the effect directly using pythonw vs python seems to take that out of the picture. (hence the post to the python list and not the zope list. I really should remember that python-dev is an open list now...) At this point, I won't be back to that site before next week, although I may take some time to test this weekend. It sounds like I should rework any areas that spew output to the console. Is there something better than checking os.path.basename(sys.executable)? > > ideas-ain't-code-ly y'rs - tim That'd be too easy! Just ask that other Tim... Emile van Sebille emile at fenx dot com emile at fenx.com From __peter__ at web.de Fri Mar 5 18:07:30 2004 From: __peter__ at web.de (Peter Otten) Date: Sat, 06 Mar 2004 00:07:30 +0100 Subject: Split a sentence by punctuations using Python References: <14b36d18.0403051444.21b3937e@posting.google.com> Message-ID: chad wrote: > I want to split sentences by using punctuations, numeric numbers as > the delimiters. > > For example, suppose I have a text that contains sentences like so: > > "To help you get there a bit faster, I will be driving at 120 miles an > hour (I am just kidding). Is that OK?" > > Now, I want to get the following segments from this text: > > To help you get there a bit faster > I will be driving at > miles an hour > I am just kidding > Is that OK > > You know, string.split does not work for this objective. So how can i > achieve this? Thanks. >>> s 'To help you get there a bit faster, I will be driving at 120 miles an hour (I am just kidding). Is that OK?' >>> r = re.compile("[,.?()\\d]+ *") >>> print "\n".join(r.split(s)) To help you get there a bit faster I will be driving at miles an hour I am just kidding Is that OK >>> Is this OK? Note the trailing empty line. If this is not desired, just remove the last list item if empty. Peter From jcarlson at nospam.uci.edu Mon Mar 29 03:45:59 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Mon, 29 Mar 2004 00:45:59 -0800 Subject: How To capture an id into an array.. In-Reply-To: References: Message-ID: > The __del__ method may not always be called. I find the WeakValueDictionary > handy (which internally uses callbacks I think). OOO, even better, use the weakref standard method for doing it. I haven't done extensive testing, but on those occasions where I've used the class I provided earlier, everything eventually got deleted. It was likely a function of the object heirarchy and interaction in my tests and applications. That is, not likely to be duplicated by any sane person *wink*. - Josiah From axelboldt at yahoo.com Fri Mar 26 08:45:53 2004 From: axelboldt at yahoo.com (Axel Boldt) Date: 26 Mar 2004 05:45:53 -0800 Subject: Semantics of == References: <40200384.0403161538.7407d9e2@posting.google.com> <4057A2A0.CC63C070@alcyone.com> <40200384.0403170657.5c81a456@posting.google.com> <4058E18D.15C51614@alcyone.com> <40200384.0403180544.337681f1@posting.google.com> <405A2FD4.E8713170@alcyone.com> <40200384.0403250532.3c8b6e6a@posting.google.com> <40635CD4.C518231C@alcyone.com> Message-ID: <40200384.0403260545.262ee105@posting.google.com> Erik Max Francis wrote > What part of the semantics are you unclear about? Two sequences are > equal if they are element-wise equal. That definition is circular. > That is the definition that people rely on, Yes. > that's the definition that the interpreter uses, No. > and that definition is even consistent with the behavior you saw with the > self-referencing lists which for some reason surprised you. Yes, s==w is consistent with the definition, but s!=w would also have been consistent with it. Consider for instance the following definition: * all strings and numbers are called "well-founded" * a list is called well-founded if and only if all its elements are well-founded. l=[] l.append(l) Is l well-founded? Both answers "yes" and "no" are consistent with the above definition. If you write a program to determine whether a given list is well-founded, it will run into an infinite loop. Similarly, if you try to write a program implementing the above simple-minded definition of list-equality, it'll run into an infinite loop. Since Python does not run into an infinite loop, it must use a different definition. Axel From sigurd at 12move.de Fri Mar 26 17:32:55 2004 From: sigurd at 12move.de (=?iso-8859-1?q?Karl_Pfl=E4sterer?=) Date: Fri, 26 Mar 2004 23:32:55 +0100 Subject: Passing items of a lsit as arguments References: Message-ID: On 26 Mar 2004, Tobias Pfeiffer <- me at privacy.net wrote: > the Tkinter.Canvas.create_polygon function. I got the coordinates in a > long list but how can I achieve that every item in this list is passed as > a single parameter? > Example: > bla = [(1,2), (3,4), (5,6), ...] > has to become > create_polygon((1,2), (3,4), (5,6), ..., fill=blue) Either: apply(create_polygon, bla) or: create_polygon(* bla) KP -- You know you've been sitting in front of your Lisp machine too long when you go out to the junk food machine and start wondering how to make it give you the CADR of Item H so you can get that yummie chocolate cupcake that's stuck behind the disgusting vanilla one. From k.robert at gmx.de Mon Mar 22 08:05:21 2004 From: k.robert at gmx.de (Robert) Date: 22 Mar 2004 05:05:21 -0800 Subject: webbrowser.open_new alternatives for Windows Message-ID: <19804fd8.0403220505.509b6ee2@posting.google.com> how can i open a _NEW_ browser window on Windows ? (It should be browser independent. at least for IE, Mozilla & Netscape) i found a snippet/suggestion for "IE only" in this group but it doesn't work, open also in old window: from win32com.client import Dispatch def start(url): w=Dispatch("InternetExplorer.Application") w.Navigate2(url) w.visible=1 start("http://www.python.org") start("http://www.zope.com") Robert From usenet_spam at janc.invalid Fri Mar 5 12:16:50 2004 From: usenet_spam at janc.invalid (JanC) Date: Fri, 05 Mar 2004 17:16:50 GMT Subject: OT(Slightly): Thanks to Python. References: <104emss6ca09l45@news.supernews.com> Message-ID: Jacek Generowicz schreef: > * (defmethod foo ((x integer)) > * (defmethod foo ((x string)) > The ANSI standard for the _dynamically typed_ language shown above, Maybe someone can explain, but the above doesn't look like "dynamic typing" to me...? -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From grey at despair.dmiyu.org Mon Mar 8 21:33:54 2004 From: grey at despair.dmiyu.org (Steve Lamb) Date: Tue, 09 Mar 2004 02:33:54 GMT Subject: Sending bulk email from a Python script References: <2004030818081575249%cs1spw@bathacuk> Message-ID: On 2004-03-09, Simon Willison wrote: > We've already looked at mailman and a number of other packages. None of > them fit our requirements as we need to be able to tie the list > administration in to our existing user authentication / admin control > panel, plus we want to tie the email lists to our membership databases. > We've got most of the other infrastructure already, we just need an > efficient way of sending out bulk emails to a large list of addresses. I submit to you that either hacking in authentication and a method to extract your membership database to a Mailman list would be far simpler than attempting to implement a bulk SMTP client along with the associated support structures (bounce handling, et al). ;) Python is, if nothing else, extremely modular. Or so I am told. =D -- 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 jaustin at post.harvard.edu Wed Mar 24 00:03:11 2004 From: jaustin at post.harvard.edu (Jess Austin) Date: 23 Mar 2004 21:03:11 -0800 Subject: PEP 318 References: Message-ID: Ronald Oussoren wrote in message news:... > On 23-mrt-04, at 1:15, Jess Austin wrote: > > class foo(object): > > def __foo_method(...) > > .... > > bar = decorator1(__foo_method) > > baz = decorator2(__foo_method, arg1, arg2) > > > > I can't imagine the exact use for this, but I can imagine that there > > could be a use. If the syntax remains as it is, that is. This PEP > > seems to shoot itself in the foot in this respect. > > The syntax in PEP318 is syntactic sugar for the most common use of > function decorators, the current syntax would still be supported. That's good to hear. Should this be made explicit in the PEP? From brian at chrissyandbrian.com Tue Mar 9 15:40:45 2004 From: brian at chrissyandbrian.com (Brian) Date: 9 Mar 2004 12:40:45 -0800 Subject: wine as a platform independent GUI toolkit Message-ID: http://www.python.org/doc/faq/gui.html lists the Python interfaces/wrappers/bindings to various widget sets (Tcl/Tk, wxWindows, Qt, GTk+, FLTK, FOX, and OpenGL). I'm surprised that nothing exists for wine. The only solution I can think of is to install the win32 python and Pythonwin, but this seems akward to me. Is there any way for me to run a python script natively on linux that drives a win32 gui (running with wine). In other words, is there any way to hook into the Wine widget toolkit? From premshree_python at yahoo.co.in Mon Mar 15 21:28:15 2004 From: premshree_python at yahoo.co.in (=?iso-8859-1?q?Premshree=20Pillai?=) Date: Tue, 16 Mar 2004 02:28:15 +0000 (GMT) Subject: Static Typing in Python In-Reply-To: Message-ID: <20040316022815.34801.qmail@web8311.mail.in.yahoo.com> --- Joe Mason wrote: > In article > , > Premshree Pillai wrote: > > Err...you probably have the wrong idea of static > > typing, I think. Static typing has to do with > explicit > > declaration (initialization) of variables (and not > of > > variable types). Like in C, C++, etc, Python too > is > > Is that an official definition from somewhere? > Cause I always thought > static typing was about variable types. > > Joe > -- > http://mail.python.org/mailman/listinfo/python-list Hmm...I might have been a little wrong there. However, what I wanted to stress was that it's the explicit declaration of the variable that matters (that makes static typing what it is). ===== -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 pwatson at redlinec.com Sat Mar 13 16:20:20 2004 From: pwatson at redlinec.com (Paul Watson) Date: Sat, 13 Mar 2004 15:20:20 -0600 Subject: Interpreting \ escape sequences in strings Message-ID: <40537b16$1_1@themost.net> How can I get the escapes from a command line parameter interpreted? The user provides a string on the command line. The string might contain traditional escapes such as \t, \n, etc. It might also contain escaped octal or hex such as \001 or \x09. The escapes are coming into sys.argv[] without shell interpretation. Do I need to use the compile module to make this work? Any suggestions? === $ cat ./try_arglen2.py #! /usr/bin/env python import sys, StringIO print sys.argv[1] print sys.argv[1] % () sf = StringIO.StringIO() print >> sf, sys.argv[1], c = sf.getvalue() sf.close() print "now" + c + "is" + c + "the" # This works because the interpreter is processing the escapes. sf = StringIO.StringIO("\001") c = sf.getvalue() sf.close() print "now" + c + "is" + c + "the" === $ ./try_arglen2.py '\001' \001 \001 now\001is\001the now?is?the From skip at pobox.com Tue Mar 16 09:58:38 2004 From: skip at pobox.com (Skip Montanaro) Date: Tue, 16 Mar 2004 08:58:38 -0600 Subject: Deprecating reload() ??? In-Reply-To: References: <6kk6501shlve52ds2rjdopa73jhpchprg3@4ax.com> Message-ID: <16471.5662.587304.503908@montanaro.dyndns.org> >> What if one of your users does something like 'y = M1.x + 1'; then >> what are you going to do? Dave> The goal is *not* to put the program into the state it "would have Dave> been" had the changes in M1 been done earlier. That is Dave> impossible. We simply want to have all *direct* references to Dave> objects in M1 be updated. The above looks like a pretty direct reference to M1.x. <0.5 wink> It seems to me that you have a continuum from "don't update anything" to "track and update everything": don't update update global update all direct update anything funcs/classes references everything reload() super_reload() Dave nobody? Other ideas have been mentioned, like fiddling the __bases__ of existing instances or updating active local variables. I'm not sure precisely where those concepts fall on the continuum. Certainly to the right of super_reload() though. In my opinion you do what's easy as a first step then extend it as you can. I think you have to punt on shared objects (ints, None, etc). This isn't worth changing the semantics of the language even in some sort of interactive debug mode. Sitting for long periods in an interactive session and expecting it to track your changes is foreign to me. I will admit to doing stuff like this for short sessions: >>> import foo >>> x = foo.Foo(...) >>> x.do_it() ... TypeError ... >>> # damn! tweak foo.Foo class in emacs >>> reload(foo) >>> x = foo.Foo(...) >>> x.do_it() ... but that's relatively rare, doesn't go on for many cycles, and is only made tolerable by the presence of readline/command retrieval/copy-n-paste in the interactive environment. Maybe it's just the nature of your users and their background, but an (edit/test/run)+ cycle seems much more common in the Python community than a run/(edit/reload)+ cycle. Note the missing "test" from the second cycle and from the above pseudo-transcript. I think some Python programmers would take the opportunity to add an extra test case to their code in the first cycle, where in the second cycle the testing is going on at the interactive prompt where it can get lost. "I don't need to write a test case. It will just slow me down. The interactive session will tell me when I've got it right." Of course, once the interactive sessions has ended, the sequence of statements you executed is not automatically saved. You still need to pop back to your editor to take care of that. It's a small matter of discipline, but then so is not creating aliases in the first place. Dave> Reload() will always be a function that needs to be used Dave> cautiously. Changes in a running program can propagate in strange Dave> ways. "Train wreck" was the term another poster used. Precisely. You may wind up making reload() easier to explain in the common case, but introduce subtleties which are tougher to predict (instances whose __bases__ change or don't change depending how far along the above continuum you take things). I think changing the definitions of functions and classes will be the much more likely result of edits requiring reloads than tweaking small integers or strings. Forcing people to recreate instances is generally not that big of a deal. Finally, I will drag the last line out of Tim's "The Zen of Python": Namespaces are one honking great idea -- let's do more of those! By making it easier for your users to get away with aliases like x = M1.x you erode the namespace concept ever so slightly just to save typing a couple extra characters or executing a couple extra bytecodes. Why can't they just type M1.x again? I don't think the savings is really worth it in the long run. Skip From Spam at ivonet.nl Mon Mar 1 11:43:14 2004 From: Spam at ivonet.nl (Ivo) Date: Mon, 1 Mar 2004 17:43:14 +0100 Subject: How to use __getattribute__ to access a class attribute? References: <40425d1b$0$41761$5fc3050@dreader2.news.tiscali.nl> Message-ID: <40436822$0$140$3a628fcd@reader1.nntp.hccnet.nl> A good read you can find : www.diveintopython.com "Ruud de Jong" wrote in message news:40425d1b$0$41761$5fc3050 at dreader2.news.tiscali.nl... > I have the situation where I need to construct the name > of a static method, and then retrieve the corresponding > function from a class object. > > I thought I could just use __getattribute__ for this purpose. > This works fine if I already have an instantiation of the class, > but not when I try this on the class object directly. > > A bare bones example: > > >>> class C(object): > def a(): > print "static method a" > a = staticmethod(a) > > It works for a instantiation of class C: > > >>> x = C() > >>> x.a > > >>> x.__getattribute__('a') > > >>> x.__getattribute__('a')() > static method a > > But for the class object it works differently: > > >>> C.a > > >>> C.__getattribute__(C,'a') > > >>> C.a() > static method a > >>> C.__getattribute__(C,'a')() > > Traceback (most recent call last): > File "", line 1, in -toplevel- > C.__getattribute__(C,'a')() > TypeError: 'staticmethod' object is not callable > > After some experimentation and documentation searching, > I found that to get at the actual function, the __get__ > method for the staticmethod descriptor must be called: > > >>> C.__getattribute__(C,'a').__get__(None, C) > > >>> C.__getattribute__(C,'a').__get__(None, C)() > static method a > > If I use an class instance as the first argument > it works OK. But I ran into this problem when I tried > to use __getattribute__ in the __new__ function of a class > -- there is no class instance yet at that point, > and calling C() there leads to infinite recursion. > > Another variant that worked is to call __getattribute__ > on the metaclass: > > >>> type(C).__getattribute__(C,'a') > > >>> type(C).__getattribute__(C,'a')() > static method a > > But according to section 3.3.2.1 of the Language Reference > (More attribute access for new-style classes), > __getattribute__ "... should return the (computed) attribute value". > This could be interpreted to say that __getattribute__ should > return the function, not the staticmethod object. > > Is there a reason for this difference in behavior? > From jcarlson at nospam.uci.edu Fri Mar 19 20:12:10 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Fri, 19 Mar 2004 17:12:10 -0800 Subject: Package name with '.' in them: Python Bug ? In-Reply-To: References: Message-ID: > Since it seems to be definitly illegal, it would only worth further work > if I would somehow 'fix' python to work with this kind of names, which > is both above my skills and likely unwanted. Having a clear error > message at import time would be nice anyway. I've only ever heard of you wanting such behavior. I honestly doubt that anyone is going to try to fix something that is not considered broken. You should consider renaming your files. Are names like "name_1.py" good enough for your use? - Josiah From FBatista at uniFON.com.ar Fri Mar 12 12:36:26 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Fri, 12 Mar 2004 14:36:26 -0300 Subject: Exiting Tkinter when using IDLE Message-ID: Jason Harper wrote: #- You have two issues here: #- #- 1. Don't use the quit method, instead just close your #- window. Your QUIT #- button could perhaps use: #- command=self.destroy Used command=master.destroy. This way I'm telling "destroy" to the Tk instance. #- 2. Don't call mainloop() if IDLE already has one running. Try this: #- #- import sys #- if "idlelib" not in sys.modules: #- root.mainloop() Thank you very much! As Gerrit Muller, I think this should be standard information. It's important because Tkinter is the built in GUI and IDLE is the built in IDE. Don't know if Fredrik Lundh is reading this, but I used "An Introduction to Tkinter" from him and I think these issues should be there. . 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 joe at notcharles.ca Wed Mar 24 12:01:58 2004 From: joe at notcharles.ca (Joe Mason) Date: Wed, 24 Mar 2004 17:01:58 GMT Subject: declaring multimethods [Was: Re: PEP 318] References: <95aa1afa.0403222352.2679dde@posting.google.com> <95aa1afa.0403232104.328356ea@posting.google.com> Message-ID: In article , Skip Montanaro wrote: > Using the proposed PEP 318 semantics, at the time decorator() is > called, it will be passed a function object but "__mul__" will not have been > seen yet. However, the function object's func_name field should have been > filled in. That should give it enough information to build a new function Oh, good. That's what I proposed in another post - I guess I didn't read the PEP closely enough to realize it was already like this. (It's a bit weird to have a function with a func_name filled in, but actually looking up that func_name will return something else or nothing! But there would never be a reason to do that when you already have the function object, so it's a useful asymmetry.) > type names. That presents another problem. Classes, unlike functions, > don't have name attributes, so mapping the names passed to multimethod() to Perhaps they should. (But that's another PEP!) > It certainly seems doable, but the end result doesn't seem all that pretty. > I think it would look sort of like: > > class Matrix [attributes(_name="Matrix")]: (Why not just "class Matrix: _name = "Matrix" ..."? "attributes" looks a little wordy to me. Just a question of style, but I want to know if there's a technical reason I'm missing.) > def __mul__(self,other) [multimethod("Matrix","Matrix")]: > ... > return result > > def __mul__(self,other) [multimethod("Matrix","Vector")]: > ... > return result > > def __mul__(self,other) [multimethod("Matrix","Scalar")]: > ... > return result I think my preferred way to do this would be just class MatrixBase: pass class Matrix(MatrixBase): def __mul__(self, other) [multimethod(MatrixBase, MatrixBase)]: ... return result That gets around the only case that won't work due to visibility, without forcing all the other cases to use ugly strings. Joe From jepler at unpythonic.net Tue Mar 16 09:00:36 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Tue, 16 Mar 2004 08:00:36 -0600 Subject: Replace accented chars with unaccented ones In-Reply-To: References: Message-ID: <20040316140036.GF2446@unpythonic.net> On Tue, Mar 16, 2004 at 08:26:08AM +0100, Nicolas Bouillon wrote: > Thank you both for your answer. They works well both very good. > > First, i believe i doesn't work, because the error i've made is to > forgot the "u" for string : u"?". Because my file was already utf-8 > encoded (# -*- coding: UTF-8 -*-), i thinks the "u" is not necessary... > i was wrong. When there are non-unicode string literals in a file, they are simply byte sequences. Take this program, for instance: # -*- coding: utf-8 -*- s = "?" print len(s), repr(s) $ python bytestr.py 2 '\xc3\xa9' Jeff From bh at intevation.de Mon Mar 15 06:26:54 2004 From: bh at intevation.de (Bernhard Herzog) Date: Mon, 15 Mar 2004 12:26:54 +0100 Subject: PEP 328: Imports: Multi-Line and Absolute/Relative References: <2c60a528.0403150152.6af7f53f@posting.google.com> Message-ID: and-google at doxdesk.com (Andrew Clover) writes: >> A package writer does know which external modules/packages he needs >> and can avoid to use the name of one of these modules for his >> own modules. > > But it's not just used in packages, where the filenames of sibling > modules are known. There may be scripts in directories with many > unrelated files, for which relative importing would be highly > undesirable (or even, in a directory where someone other than the > owner has write-access, a possible security risk). That's a completely different issue. The pep is about relative imports in a package. The problem you describe comes from Python inserting the directory containing the script to sys.path. Bernhard -- Intevation GmbH http://intevation.de/ Skencil http://sketch.sourceforge.net/ Thuban http://thuban.intevation.org/ From skip at pobox.com Thu Mar 25 10:55:06 2004 From: skip at pobox.com (Skip Montanaro) Date: Thu, 25 Mar 2004 09:55:06 -0600 Subject: Make 'def' and 'class' usable within expressions In-Reply-To: <3c7xaqh0.fsf@python.net> References: <4062EF99.1050802@zope.com> <4062F88C.40200@zope.com> <3c7xaqh0.fsf@python.net> Message-ID: <16483.218.773211.911225@montanaro.dyndns.org> >> What I don't like about the third alternative is the subtle >> distinction between parentheses and square brackets. It seems like >> newbies would have a hard time with it, as would advanced programmers >> who are looking over a new code base. Thomas> That may be true, especially for classes. But as understand it, Thomas> the main purpose of PEP 318 is for function decorators, not Thomas> class decorators. And for functions it is clearer, since you Thomas> always have a parameter list. I'm working on changes to PEP 318 which incorporate class decorators. Michael Hudson's latest patch supports them. Skip From FBatista at uniFON.com.ar Fri Mar 19 12:16:25 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Fri, 19 Mar 2004 14:16:25 -0300 Subject: Spanish FAQ Message-ID: People: I translated the Python General FAQ. It's in http://www.taniquetil.com.ar/facundo/python/index.html I'm trying to get it hosted in python.org, if the location changes, I'll tell you. Enjoy it! . 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 LISTSERV at LSV.CERAMICS.ORG Mon Mar 1 14:05:27 2004 From: LISTSERV at LSV.CERAMICS.ORG (L-Soft list server at clayart (1.8d)) Date: Mon, 1 Mar 2004 14:05:27 -0500 Subject: Message ("Your message dated Mon, 1 Mar 2004 13:14:41 -0600...") Message-ID: <402A21D600017F0E@mercury.acers> (added by mercury.acers) Your message dated Mon, 1 Mar 2004 13:14:41 -0600 with subject "Re: Your document" has been submitted to the moderator of the CLAYART list: Mel Jacobson . From llothar at web.de Fri Mar 19 15:33:51 2004 From: llothar at web.de (Lothar Scholz) Date: 19 Mar 2004 12:33:51 -0800 Subject: Slow Python - what can be done? References: <480e9240.0403180943.64bee13d@posting.google.com> Message-ID: <6ee58e07.0403191233.598912fc@posting.google.com> sewall93 at rocknroll.umcs.maine.edu (Jason) wrote in message news:<480e9240.0403180943.64bee13d at posting.google.com>... > Hey, > > I'm an experience programmer but new to Python. I'm doing a simple > implementation of a field morphing techinique due to Beier and Neely > (1992) and I have the simple case working in Python 2.3 - but it's > REALLY slow. > > Basically, you specify two directed line segments in the coordinate > system of a raster image and use the difference between those two > lines to transform the image. > > for a 400 x 600 image, python takes about 30 seconds to run the > algorithm. This seems way to slow - I would expect it to run in a > matter of a few seconds. Here's the code: what should I do to speed > things up? I know I'm going to get a "do it in C/make a C extension" > but that defeats the purpose: I'd like to know what Python can do > here. If you can't go with the mentioned compilers (psycho) or libraries there is nothing else then writing C. Python is best at glueing code together. Writing numerical or highly mathematical algorithms in python will always result in 10000% overhead. Maybe you want to look at GNU eiffel (smarteiffel). Remember there is no silver bullet ! From miki.tebeka at zoran.com Wed Mar 10 03:54:53 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Wed, 10 Mar 2004 10:54:53 +0200 Subject: [OT] C unit testing suite Message-ID: Hello All, I'm looking for a good C unit testing suite. Any recommendations? Thanks. Miki From trevp_spam at trevp.net Wed Mar 24 02:11:42 2004 From: trevp_spam at trevp.net (Trevor Perrin) Date: Wed, 24 Mar 2004 07:11:42 GMT Subject: pyOpenSSL is dead or not? In-Reply-To: References: <405fe1b6$0$298$636a15ce@news.free.fr> Message-ID: Roger Binns wrote: >>Any new stuff I write (ha!) I'll use the most recent Python. > > > It would be really nice if you could get together with TLS Lite. We already have (perhaps unbeknownst to Ng ;-). TLS Lite can use M2Crypto for fast RSA and ciphers. > That way Python will have a pure Python implementation of it > all, but also native code accelerators. You have both also > done integration work with the Python standard library > (httplib, xmlrpc etc) and there isn't any value in > duplication. The APIs are different so you couldn't directly re-use the integration work. But M2Crypto integrates with things I don't, like urllib, xmlrpclib, Zope, etc. If I get around to trying to integrate with those things, I'll probably try to steal some ideas... Trevor From rogerb at rogerbinns.com Mon Mar 22 02:50:06 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Sun, 21 Mar 2004 23:50:06 -0800 Subject: Python bytecode compatibility between interpreter versions References: <0qudndSnJMpWbsfdRVn-uA@powergate.ca> <7okui1-3no.ln1@home.rogerbinns.com> Message-ID: <8ei2j1-69c.ln1@home.rogerbinns.com> > Is it really the case that it isn't even recommended to distribute one's > application as .pyc files? > > In commercial apps for which one might not want to distribute the source > for, it would be really nice if one can count on just requiring the end-user > to install a version of Python (but not extra extension modules anymore) and > then distribute the app as a bunch of .pyc's packaged in a .zip file and > use the PYTHONPATH method you showed. Just remember to provide a set of > .pyc's for each version of Python you support. In the Java world, the JVM is a seperate installable component. Some installers like ZeroG will install them for you. In general all Java bytecode is expected (but not required) to share the main system JVM. In Python, if you want to distribute an application, and you don't want the user to have to install Python or any extensions, you use one of the installer generators out there. They gather up the interpretter, your code and extension libraries and dump them all into one directory. They then include a stub that makes them all work together. It especially has no reliance on any pre-installed interpretter. If you want to see this in action, try my project at http://bitpim.sf.net The downloads give you a program that runs on Windows, Mac and Linux without any prerequisites. If you examine the install directory, you will find the find Python interpretter DLL or binary, all needed extension shared libraries and the program code (often as .pyc files in a zip archive or appended to the main binary). Note that the installer generator happens to know what formats and other quirks the Python interpretter works with which is why it does include some .pyc's. > In Java, profiling info may not be written out to disk, but the > bytecodes certainly are (they are what is in the class files). Which > is roughly equivalent to what happens with .pyc files, correct? You are pedantically correct in that they both contain bytecode, but the level is different. *If* the JVM wrote out HotSpot compilations and profiling information, the resulting files would be analogous to .pyc files. They would not be *required* for execution, and they would be automatically regenerated if necessary (eg if you changed source files). In theory it could then execute from them without requiring the original class files, but that would be an implementation specific thing. > .pyc > files don't contain profiling info, nor was I ever aware that the Python > VM even does run-time behaviour profiling... (Pysco may, though) I don't know of any implementations that do, but the implementations are free to do so. As I keep saying, .pyc files are an implementation specific detail of one version of one implementation of the Python interpretter. It can make as many intermediate file formats and contents as it wants, as can any other implementation. The only requirement for a conforming Python implementation is that it execute Python *source*, and how it does it under the scenes is not specified. > In practice though, there is really just one implementation of Python > (with the standard libraries... excluding Jython) which works using the > same bytecode mechanism on _all_ platforms, so as far as I can tell, > it would be quite feasible to distribute applications in .pyc form. If you distribute the exact interpretter that generated those exact .pyc files then you will be fine in practise. That is what the various installer generators out there do. Some examples are py2exe, cx_Freeze and BundleBuilder which is what my project uses on Windows, Linux and Mac respectively. With the addition of zip imports in Python 2.3, I think things will lead to a unification of the installer generators out there (there have been several different ones, often limited to a subset of platforms for historical reasons). Roger From paul at boddie.net Fri Mar 5 06:04:17 2004 From: paul at boddie.net (Paul Boddie) Date: 5 Mar 2004 03:04:17 -0800 Subject: Python as replacement for PHP? References: <403fa54b@news.zianet.com> <99dce321.0403031518.56f61c7c@posting.google.com> <7xad2x5wfm.fsf@ruckus.brouhaha.com> <23891c90.0403040241.60eb33a4@posting.google.com> <7x7jy0o8qd.fsf@ruckus.brouhaha.com> <7x7jy0cg4h.fsf@ruckus.brouhaha.com> Message-ID: <23891c90.0403050304.b637d@posting.google.com> Paul Rubin wrote in message news:<7x7jy0cg4h.fsf at ruckus.brouhaha.com>... > > Yes, but once you add such a module, you're no longer comparing PHP to > Python. You're comparing PHP to {Python plus some third party package > whose stability etc. you have to evaluate from scratch}. That's an > issue that people trying to deploy real-world production servers care > about regardless of how much academics and hobbyists tend to brush it > off. So how does it all work when you're deploying something in, say, C or C++? Those languages don't give you anything above and beyond basic input/output support and some nice data structures (if you're lucky). Now, I know that the average Microsoft shop will then state that they're really developing something with Visual Studio and the usual Microsoft libraries, and that supposedly gives you the "comfort" of having Microsoft responsible for everything, but even then you're likely to run out of road at some point. What kind of pitch do you make to management then, or has management already attained "buzzword bingo" by that stage? > cookedm+news at physics.mcmaster.ca (David M. Cooke) writes: > > > > And hey, if you're choosing a database module, you've got to have > > already chosen a database -- MySQL, PostgreSQL, SQLite, etc. This is a > > bigger choice than "how do I talk to it." The Python DB-API makes it > > relatively easy to write code where the difference in talking to > > different databases is only in your SQL, and not how you call it. > > No, the DB-API doesn't help you write code at all. It's the DB-API > plus it's implementation that lets you write code. The implementation > doesn't come with Python, so you have to look elsewhere for it. So, you're worried about compliance, support, maintenance and so on. What about stuff like mxODBC? Do you think that there's a real market opportunity for supported super-distributions of Python, like ActivePython but with a broader scope? ["complex additional modules maintained by outsiders"] > Brushing that off and saying "Spyce, CherryPy, etc. are all out there, just > download them" Well, that was a suggestion that things exist which potentially do PHP-like stuff as easily as PHP makes it happen. I can't confirm that, though, since I'm not really impressed by the PHP/ASP style of development and not inclined to experiment in depth with those technologies just to be able to tell someone what they should be using when they'd get a much better understanding by looking into the matter themselves. > is only a matter of degrees better than responding to "Program XYZ is > full of bugs and crashes all the time and the developers ignore > everyone" with "that's no big deal, it's open source, you can fix the > bugs yourself and then it will be fine". As I'm sure most of us are aware, selecting technologies tends to involve assessing various factors before dropping those technologies into our solutions. If "program XYZ" really is that bad, then you probably don't want to fix it yourself unless there really is nothing else that comes close to solving the same problems. But at least some of the Web frameworks can be regarded as being mature enough for real world use, and the decision to choose one of them can't really be more involved than that to adopt Python in the first place. Now, I think you do have a point about the number of technologies and packages that may need to be combined in order to make a solution, but I think that this can be addressed by packaging combinations of such technologies. You see some of this kind of thing with Zope and derivatives (and even with Apache and PHP, by the way), and it'd be nice to see the Web-SIG looking into this area, too. Paul From rainerd at eldwood.com Mon Mar 1 03:02:25 2004 From: rainerd at eldwood.com (Rainer Deyke) Date: Mon, 01 Mar 2004 08:02:25 GMT Subject: Why Python? References: Message-ID: Ed Murphy wrote: > On Mon, 01 Mar 2004 05:12:48 +0000, Rainer Deyke wrote: >> 2. Python programs are somewhat difficult to distribute compared to >> programs in languages that compile to native code. > > How do you figure this one? Something to do with statically linked > libraries? (I'm a Python newbie, but have been programming in general > for almost 20 years, about half of that professionally.) Basically you have to distribute the Python interpreter along with your program, since you generally can't rely on the end user having (the correct version of) Python installed. -- Rainer Deyke - rainerd at eldwood.com - http://eldwood.com From wallacethinmintr at eircom.net Thu Mar 18 12:40:03 2004 From: wallacethinmintr at eircom.net (Russell Wallace) Date: Thu, 18 Mar 2004 17:40:03 GMT Subject: Extending Python Syntax with @ References: <104v3lrijtse657@news.supernews.com> <104v8flf6f1bp95@news.supernews.com> Message-ID: <4059deac.74176280@news.eircom.net> On Wed, 10 Mar 2004 18:15:57 -0500, "John Roth" wrote: >How much real development (I don't mean archiving) do we do >today on systems without appropriate tools? Very little. The issue >isn't trying to develop on systems without appropriate tools, it's >developers that won't use tools that help them work. I'll happily use a fancy tool when I find one that doesn't suck. If and when that ever happens, I'll be willing to start considering using a language that requires such. -- "Sore wa himitsu desu." To reply by email, remove the small snack from address. http://www.esatclear.ie/~rwallace From tim.golden at viacom-outdoor.co.uk Mon Mar 29 02:42:07 2004 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Mon, 29 Mar 2004 08:42:07 +0100 Subject: monitoring a directory Message-ID: MG> Note that ReadDirectoryChangesW is available only MG> on the NT platforms (XP, 2000, NT4, NT3.51 SP3). MG> If you need portability to Win95/98/Me, you'll need MG> to fall back to FindFirstChangeNotification as the MG> cookbook recipe uses. Good point. I'm afraid that as we're up to Win2k+ here almost across the board, I've tended to stop checking platform-specific stuff as closely as I used to when we were supporting large amounts of Win9x. Sorry. I've added a page to my own site outlining the different techniques, and I'll add something to it warning about Windows version dependencies. http://tgolden.sc.sabren.com/python/win32_how_do_i/watch_directory_for_chang es.html MG> Does win32file.ReadDirectoryChangesW provide a way to tell if MG> it's availableor not? I'm not in a position to test at the moment, but as far as I recall the pywin32 code in general does do a check for whether a function is available before it builds it in. Haven't checked. 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 theller at python.net Wed Mar 3 02:32:52 2004 From: theller at python.net (Thomas Heller) Date: Wed, 03 Mar 2004 08:32:52 +0100 Subject: NT service (setting Description string) References: Message-ID: "Larry Bates" writes: > Anybody know what variable I need to define in my > class to set the long description that shows up > in the Services control panel applet? > > _svc_name_ holds the short name > _svc_display_name_ holds the long name > _svc_?????_ holds the description There isn't any yet. Apparently you have to call the win32 api ChangeServiceConfig2() (but maybe it can also be done with the wmi module). Thomas From claird at lairds.com Sun Mar 14 11:11:55 2004 From: claird at lairds.com (Cameron Laird) Date: Sun, 14 Mar 2004 16:11:55 -0000 Subject: Tkinter3000 References: <89WdnQhnm6Gkwdfd4p2dnA@adelphia.com> Message-ID: <105912baareej68@corp.supernews.com> In article , Fredrik Lundh wrote: >"Robert" wrote: > >> Is the WCK still an active project? > >yes. wck 1.0 for tkinter was released in december 2003, and >should be considered as a stable release. . . . For those reading along at home, I'll provide a few words of explanation: "The Widget Construction Kit (WCK) is an extension API that allows you to implement all sorts of custom widgets, in pure Python." I'd say the WCK not only allows, but even *encourages*, widget customization. -- Cameron Laird Business: http://www.Phaseit.net From billb at isp.net.au Mon Mar 29 22:14:39 2004 From: billb at isp.net.au (Bill) Date: 30 Mar 2004 03:14:39 GMT Subject: CSV to Browser Bookmark file Message-ID: I currently have all of my Bookmarks under WinXP in a PIM, which will allow me to export them as a CSV file ( fields are "Category,Page-Title,URL,Comments - all fields of no fixed length). Is there a program/script that will output the info from csv to a browser bookmark file - Any browser as I want to move the bookmarks from Windows to Linux - unfortunately the PIM wont run under Wine in Linux and I am not a programmer so I have no idea how to convert the file. Thanks in advance for any help. Bill From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Sun Mar 7 08:41:20 2004 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Sun, 07 Mar 2004 14:41:20 +0100 Subject: attachment In-Reply-To: References: <4049ad99$0$564$e4fe514c@news.xs4all.nl> Message-ID: <404b2680$0$564$e4fe514c@news.xs4all.nl> ketulp_baroda at yahoo.com wrote: > User can submit any attachment and can view all the attachments > submitted by other users. > Attachment contents can be anything. > So where should I store the attachment 1)In database 2)In a file on > server You give too little information to provide a conclusive answer. However, Putting stuff in a database can be complicated (BLOBs and stuff) but usually takes care of concurrency control (i.e. accessing the data by multiple users at the same time; everyone should only see THEIR file(s)). Storing stuff in the filesystem is by far the easiest. You don't have to set up and access a database. But you DO have to make sure that each file is uniquely named (you don't want me to overwrite your 'curriculum.doc' now do you) and probably have to do some concurrency control yourself. Also you have to think of a way to identify which files belong to which user, and make sure that user A cannot access user B's files. --Irmen From peter at semantico.com Fri Mar 26 11:42:54 2004 From: peter at semantico.com (Peter Hickman) Date: Fri, 26 Mar 2004 16:42:54 +0000 Subject: A 'Python like' language Message-ID: <40645d8f$0$10775$afc38c87@news.easynet.co.uk> Well after all this discussion it would appear that a 'Python like' language has appeared => Prothon. http://www.prothon.org/index.html Very alpha, sort of like Python (if you consider the indenting is what makes Python unique) and sort of Ruby in its use of prefixes to define scoping etc (although there is no reference to this trait being borrowed from Ruby). It also quotes Self as being an influence. From samsnead at sammy.com Sat Mar 20 16:25:09 2004 From: samsnead at sammy.com (Sam Snead) Date: Sat, 20 Mar 2004 16:25:09 -0500 Subject: Time of Day Message-ID: Hello, Is there a formula/function I can use to convert the Unix time stamp to a time of day? Thanks, Sam From fpetermaas at netscape.net Fri Mar 12 07:50:19 2004 From: fpetermaas at netscape.net (Peter Maas) Date: Fri, 12 Mar 2004 13:50:19 +0100 Subject: Static Typing in Python In-Reply-To: References: Message-ID: Peter Maas schrieb: > class doesTypeChecking: > def __init__self(): Correction: def __init__(self): -- ------------------------------------------------------------------- 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 afriere at yahoo.co.uk Wed Mar 31 01:47:31 2004 From: afriere at yahoo.co.uk (Asun Friere) Date: 30 Mar 2004 22:47:31 -0800 Subject: Equality and identity References: <3cfvfkmi337.fsf@nelja.ifi.uio.no> Message-ID: <38ec68a6.0403302247.2f49f047@posting.google.com> Marius Bernklev wrote in message news:<3cfvfkmi337.fsf at nelja.ifi.uio.no>... > In python, it seems like immutable objects are equal under both > equality and identity: > > >>> 5 == 5 > True > >>> 5 is 5 > True > >>> "hei" == "hei" > True > >>> "hei" is "hei" > True > It only seems that way. Note: >>> a = 5 >>> b = 5 >>> 100 is 100 True >>> #but: >>> a = 100 >>> b = 100 >>> a is b False >>> #but also!: >>> a = 100;b = 100 >>> a is b True >>> # for strings: >>> a = 'hello' >>> b = 'hello' >>> a is b True >>> a = 'hello world' >>> b = 'hello world' >>> a is b False >>> a = 'hello world';b = 'hello world' >>> a is b True As was pointed out, this is implementation dependant. Our favourite implementation interns small integers and simple strings (and apparently also equivalent strings and integers created on the same line(?)), for optimisation purposes. These are really exceptional. You shouldn't find this behaviour in defined classes for instance. The behaviour of tuples in this regard as much more 'normal.' From Me at privacy.net Mon Mar 22 11:27:39 2004 From: Me at privacy.net (Gernot) Date: Mon, 22 Mar 2004 17:27:39 +0100 Subject: OFF-TOPIC:: Why Lisp is not my favorite programming language References: <165b3efa.0403030443.4d591f04@posting.google.com> <404675da@news.tce.com> <1sw3c.20562$rD5.1087@twister.socal.rr.com> <405ef463.40371149@news.eircom.net> Message-ID: Program a game - it's fun for a 13year old. And games are made with GLBasic from GLBasic.com. qed. Gernot Frisch. "Russell Wallace" schrieb im Newsbeitrag news:405ef463.40371149 at news.eircom.net... > On Wed, 10 Mar 2004 04:03:09 GMT, "Bootstrap Bill" > wrote: > > >I was 15 when I got my first computer, a 4k TRS-80 Model I with Level I > >BASIC, cassette tape for storage. It was several years before I could afford > >a system with a floppy drive, let alone a hard drive.. I spent nearly all my > >free time for months teaching myself BASIC programing, mostly trial and > >error. The book that came with my Model I was a great introduction to > >programming. > > Those were the days ^.^ > > >My 13 year old niece wants to learn programming. What's the best > >introductory language for her? > > I'd recommend Python as a good introductory language - easy, > intuitive, but definitely not dumbed down. > > -- > "Sore wa himitsu desu." > To reply by email, remove > the small snack from address. > http://www.esatclear.ie/~rwallace From jjl at pobox.com Sat Mar 6 17:26:20 2004 From: jjl at pobox.com (John J. Lee) Date: 06 Mar 2004 22:26:20 +0000 Subject: Is Eric S Raymond still a "Pythoneer" References: <2ae25c6b.0403020006.6b99e590@posting.google.com> <2ae25c6b.0403021100.400af290@posting.google.com> Message-ID: <87brn9d33n.fsf@pobox.com> paddy3118 at netscape.net (Paddy McCarthy) writes: > paddy3118 at netscape.net (Paddy McCarthy) wrote in message news:<2ae25c6b.0403020006.6b99e590 at posting.google.com>... [...] > > I wondered if there are any more recent interviews/articles from ESR > > on his scripting language tools. I would be interested to know if he > > still usesPython? Did he try any other "scripting" languages such as > > Ruby or Lua? [...] > Oh, no! I sent the above, then found the right thing to search for in > Google and came up with this interview from January: > http://www.internetnews.com/dev-news/article.php/3306511 > > It seems ESR is still a Pythoneer, and I have another important > article to add to my trove. [...] If you come to the Python UK conference (part of the ACCU Spring conference), you may even meet him in person. He's a keynote speaker in the Open Source event that's also taking place at the ACCU conference, but I imagine he'll be mingling with Pythonistas too. https://www.accu.org/conference/ (the site is due for a significant revamp next week, so check back for more details on the Python conference and Open Source forum) John From eric at zomething.com Tue Mar 9 23:25:29 2004 From: eric at zomething.com (Eric @ Zomething) Date: Tue, 9 Mar 2004 20:25:29 -0800 Subject: How to open a file, read from it, and retrieve information from it? Message-ID: <20040309202529.1304261957.eric@zomething.com> bugsyboy9 at yahoo.com described: > >From a GUI interface, a user needs to request a string to be searched > from a file and bring the string back, if it is in the file, and > display it in a different field within the same GUI. Basically, I > need to be able to open a file, parse its contents, and bring the > requested information back and display it in a GUI window. The fun is in the doing, but here are some links you might want to explore: File objects: http://www.python.org/doc/current/lib/bltin-file-objects.html Tkinter GUI: http://www.pythonware.com/library/an-introduction-to-tkinter.htm Regular expressions: http://www.python.org/doc/current/lib/module-re.html here's how easy it can be (to do something easy) in Python: IDLE 1.0 >>> from easygui import * >>> fname=fileopenbox() #opens a file dialog and returns a selected file name >>> fl=file(fname,'r') #opens the file for reading >>> fString=fl.read() #reads the file into a string >>> pos=fString.find("contract") #finds the first position of the string "contract" in the file string >>> pos 273 If you start playing with it, you'll start enjoying it, I say. Try, do, Google, repeat. Eric Pederson Pythonista since... February 2004! From peufeu at free.fr Mon Mar 29 04:02:38 2004 From: peufeu at free.fr (PF) Date: Mon, 29 Mar 2004 11:02:38 +0200 Subject: Orders of magnitude References: Message-ID: It all boils down to how much space your keys take. When you look for dupes, you must hold only the keys in memory, not the data (it'll be a lot faster this way). I'd say create a bsddb with btree sort to hold all your keys. Should take about 20 minutues to fill it. Then scan it in sorted key order, and duplciates will appear next to each other. From eric at zomething.com Mon Mar 15 23:52:11 2004 From: eric at zomething.com (Eric @ Zomething) Date: Mon, 15 Mar 2004 20:52:11 -0800 Subject: Python and Microsoft Excel files Message-ID: <20040315205211.286098248.eric@zomething.com> benoit wrote > I want to import and export Microsoft Excel files. > Are there libraries for this ? I'd be interested to hear if there are some good Python libraries which work with the ".xls" file format. Python does have CSV, if you can achieve what you want by exporting the data in comma separated format and then manipulating it. http://www.python.org/doc/current/lib/module-csv.html Also, there is pyXLWriter (though I haven't tried it): http://www.python.org/pypi?:action=display&name=pyXLWriter&version=0.3a1 I have considered that there must be great Java libraries for MS Office within the OpenOffice.org suite. It would be sweet to be able to wrap some algorithms from OOo source in Python, but I am not sure of the licensing, nor quite where in that source to find the treasure. the .xls=>XML=>PDF (etc.) would be nice to have around... From andrew-pythonlist at puzzling.org Wed Mar 24 01:00:57 2004 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Wed, 24 Mar 2004 17:00:57 +1100 Subject: PEP 318 In-Reply-To: <95aa1afa.0403232104.328356ea@posting.google.com> References: <95aa1afa.0403222352.2679dde@posting.google.com> <95aa1afa.0403232104.328356ea@posting.google.com> Message-ID: <20040324060057.GA31881@frobozz> On Tue, Mar 23, 2004 at 09:04:44PM -0800, Michele Simionato wrote: > Skip Montanaro wrote in message news:... > > > > Okay, but can you explain the mechanism or point me to the original post? I > > can't find it on Google (probably too recent). Multimethod(a,b)() won't > > know that each call is for __mul__ will it (maybe it will peek at the > > func_name attribute)? From what you posted, all I saw was multiple > > definitions of __mul__. Only the last one will be present as a method in > > the class's definition. > > > > Skip > > Please take what I posted just as an idea (it is not even my idea!), not as > an implementation proposal. > I don't have an implementation, but I am pretty much convinced that it is > possible and not that hard. > I am not suggesting that we put multimethods in Python 2.4. > I am just noticing that the notation could be used to denote > multimethods too, as Ville Vainio suggested (sorry for the mispelling, > Ville!). > > Just to support your point that the decorator idea is a Pandora box, and > we can extract anything from it ;) But the decorator syntax doesn't help with this case at all. You *could* hack up multimethods today, though, by abusing metaclasses: class Foo: ... class __mul__(multimethod): def Matrix(self, other): ... def Vector(self, other): ... The definition of multimethod would be something like this: class _multimethod(type): def __new__(cls, name, bases, d): if d.get('__metaclass__') == _multimethod: return super(_multimethod, cls).__new__(cls, name, bases, d) else: def multi(self, *args): try: meth = d['_'.join([arg.__class__.__name__ for arg in args])] except KeyError: raise TypeError, 'No multimethod for type(s) %r' % map(type, args) else: return meth(self, *args) return multi class multimethod: __metaclass__ = _multimethod This is only very lightly tested. Extending this to cope with subclasses of types, etc, is left as an exercise for the reader. FWIW, here is what I tested it with: if __name__ == '__main__': class C: class __mul__(multimethod): def int(self, other): return 'Integer multipication!' def C(self, other): return 'Selfness squared!' class test(multimethod): def int_str(self, i, s): return 'Testing %r, %r' % (i, s) c = C() print c * 1 print c * c try: print c * "x" except TypeError, e: print e.args[0] print c.test(2, 'two') try: print c.test('x', 'y') except TypeError, e: print e.args[0] -Andrew. From peter at engcorp.com Tue Mar 16 16:07:31 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 16 Mar 2004 16:07:31 -0500 Subject: Result of ``a is b'' In-Reply-To: <40200384.0403161255.7fca7a8c@posting.google.com> References: <40200384.0403151632.35496ee6@posting.google.com> <40200384.0403161255.7fca7a8c@posting.google.com> Message-ID: Axel Boldt wrote: > David MacQuigg wrote > > >>>>>x = 'akdijfkdienlskfi' >>>>>y = 'akdijfkdienlskfi' >>>>>x is y >> >> True >> >>>>>x = 'a b' >>>>>y = 'a b' >>>>>x is y >> >> False > > > Wow. So it seems that the action of "is" on immutables is unspecified > and implementation dependent, thus useless to the programmer. Absolutely not! "is" does what it does, and the definition of what it does is very explicit. It checks *identity*, not equality. In both examples above, the code is semantically meaningless because you are checking identity on two things which you just created at the command line, out of thin air. They may or may not be identical, but whether they are or not has no importance. I'm not being very clear, but what I mean is that "is" should be used when *identity* is important to you. For example, you have a particular object and you want to check whether a method call returns that particular object, perhaps as a "sentinel" value. "is" is what you want here, because you are checking whether *that specific object* is being returned, not whether the returned item equals that object in value. There are very good (and correct) times to use "is", but the trivial examples above aren't them... -Peter From no at spam.invalid Wed Mar 10 16:04:07 2004 From: no at spam.invalid (Russell E. Owen) Date: Wed, 10 Mar 2004 13:04:07 -0800 Subject: question: numarray c extension error handling? Message-ID: I'm writing a C extension for numarray and am puzzled about the idiom for error handling. The documentation seems to say one should always decref an array after calling NA_InputArray, etc., to convert numarray args to C arrays. However, the example and also the numarray code suggests that it's OK to return early via (for example) PyErr_Format without doing the DECREF. For example, I have appended a very abbreviated version of the sample code. Comments? I'll plow ahead and follow the example (i.e. with early return) but I was wondering if anyone knew why this was OK. Perhaps I should put in a request to the numarray project for a clarification in the documentation. -- Russell static PyObject * Py_Convolve1d(PyObject *obj, PyObject *args) { PyObject *okernel,...; PyArrayObject *kernel...; if (!PyArg_ParseTuple(args, "OO|O", &okernel, ...)) return PyErr_Format(_convolveError, "Convolve1d: Invalid parameters."); /* Align, Byteswap, Contiguous, Typeconvert */ kernel = NA_IoArray(okernel, tFloat64, C_ARRAY); ... if (!kernel...) return PyErr_Format( _convolveError, "Convolve1d: error converting array inputs."); ... Py_XDECREF(kernel); ... } The relevant section of the docs (section 12.3 High-level API): The return value of each function (NA_InputArray, NA_OutputArray, or NA_IoArray) is either a reference to the original numarray object, or a reference to a temporary numarray. Following execution of the C-code in the extension function body this pointer should *always* be DECREFed. From __peter__ at web.de Thu Mar 11 18:13:36 2004 From: __peter__ at web.de (Peter Otten) Date: Fri, 12 Mar 2004 00:13:36 +0100 Subject: Create static method dynamically References: Message-ID: Salvatore wrote: > def hello(): > print "hello" > Is there a way of making 'hello' a > static method of 'myClass ? >>> class Test: ... def addStaticMethod(name, func): ... setattr(Test, name, staticmethod(func)) ... addStaticMethod = staticmethod(addStaticMethod) ... >>> def hello(): print "hello" ... >>> t = Test() >>> t.addStaticMethod("hello", hello) >>> t.hello() hello >>> Even simpler, if you know the method name beforehand: >>> Test.world = staticmethod(hello) >>> t.world() hello Peter From franga at shentel.net Wed Mar 24 18:42:04 2004 From: franga at shentel.net (Francis Avila) Date: Wed, 24 Mar 2004 18:42:04 -0500 Subject: State of Python scripting on Mac OS X? Message-ID: I just got a Mac, and I want to script it using Python. (I tried a few things with AppleScript, but I swear it's like COBOL++, and the data types are very cumbersome to use.) Since Apple has Python out of the box, I thought it would support scripting OOTB too, but apparently not. Python needs an OSA scripting component to be an OSA-compliant language. I'm not entirely clear on what that means, though, because OSA seems to sometimes refer to an API, sometimes to an IPC, and sometimes to a "component". Searching around I get old and/or conflicting reports on what constitutes OSA support, whether there's a package that gives Python such support, where I can get it, and how I can make the OS recognize it. For example, I can't get an answer to a question as simple as how one can select Python in the Script Editor, and what relation this has to OSA. I can't seem to find a nice architectural overview of OSA. Or, would I be able to use the Python standard library, or only the events that other Applications provide? And so on. The best I can seem to find now is PyObjC, which is lower-level than what I want. Other things I turn up (the AppScripting package or the MacPython IDE) seem to provide some sort of interface to OSA, but not an OSA component itself. Or at least that's what they seem to be claiming. (In any case, these never show up in script editor as an "OSA".) So I guess I'm asking if anyone knowledgeable can point me in the right direction or tell me the current state of Python for AppleScript-ing. If there's a project that's building a "complete" OSA scripting component for Python, I might be interested in participating. -- Francis Avila From velomanhere at hotmail.com Sun Mar 21 11:22:11 2004 From: velomanhere at hotmail.com (Velomanhere) Date: 21 Mar 2004 08:22:11 -0800 Subject: Newbie Help with IMAPLIB Module Message-ID: <3e8ef6f.0403210822.71344764@posting.google.com> I am just learning Python and need some assistance with the IMAPLIB module. I am trying to check whether there are any unread messages in the mailbox of the IMAP server. I have found the following object imap.recent() which returns a tuple with the number of mesages that haven't been checked. However, this isn't exactly what I want. The definition of the "RECENT" flag in IMAP only returns a number if no other program has checked the mailbox. From the RFC: "This session is the first session to have been notified about this message; subsequent sessions will not see \Recent set for this message." Does anyone know how I can check if \Seen flag is *not* true on any messages in the mailbox and then return how many message are not tagged as /Seen Here is what I have so far: import imaplib def imapcheck(): """Check IMAP server for messages""" newmessages = () imap=imaplib.IMAP4("server.domain.com") imap.login("username", "password") newmessages = imap.recent() if [None] not in newmessages: print "You have new messages" def main(): imapcheck() From tismer at stackless.com Tue Mar 30 10:37:31 2004 From: tismer at stackless.com (Christian Tismer) Date: Tue, 30 Mar 2004 17:37:31 +0200 Subject: Orders of magnitude In-Reply-To: References: Message-ID: <4069943B.6010900@stackless.com> Robert Brewer wrote: ... >>[discussion of hashing snipped] > > > Thanks again. Really, thanks! > > However, I think you're letting the arrow fly before you've seen the > target. Oops :-) This was a late-night session, then I tend to shoot early :-) > I understand hashing and making a bucket for each possible first > character (I should have read your code more thoroughly). That is a fine > technique, and it was already on my short list of workarounds.> However, > your _complete_ solution isn't feasible for my dataset, because I'm > comparing some fields within each record, not entire records. Sure, that's why I have a file-like object as parameter, and you are supposed to do you preprocessing and create the string that should represent the interesting part of a record. I didn't plan to code that for you, but expected you would want to provide your function and use stuff at your convenience. > For > example, with rows like: > > "Michael","Kemperson","26002","me at aol.com","64.12.104.18" > "Ryan","Thomas","46723","myfriend at yahoo.com","209.244.21.23" > "Vicki","Thomas","46723","myfriend at yahoo.com","209.244.21.23" > "Shanuana","Hedlund","10415","andi at yahoo.com","122.150.184.175" > > ...I need to keep Ryan and dump Vicki, based on shared email and IP, but > *not* on the other fields. If Vicki had the same email but a different > IP, don't drop that record, but blank out the 2nd phone number. In > addition, most but not all files have phone numbers, which get the same > treatment. That's why I said I have three dicts/indexes. That's bad, of course, since you were asking how to find duplicates in database records, which means for me, that a single processing step is possible which calculates the unique information from the current record, only. If you actually need grouping and decisions based upon that, the apporach doesn't work, since you need to hold all the information to further process it. In this case, an external sorting process might make sense, with the record fields rearranged with email and IP going first, then you can probably do a sequential process over the data. 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 dave at nullcube.com Sun Mar 28 06:59:35 2004 From: dave at nullcube.com (Dave Harrison) Date: Sun, 28 Mar 2004 21:59:35 +1000 Subject: pysqlite Message-ID: <20040328115935.GA17901@dave@alana.ucc.usyd.edu.au> hi all, I need to be able to flash a database with the sql def'ns I have, and it works if I pipe my file into sqlite, but when I execute the same data as a giant string I get no error, but the database isn't flashed. anyone have any ideas ? Ive tried stripping out newlines, all whitespace reduced to single spaces etc etc ... -- Dave Harrison Nullcube dave at nullcube.com http://www.nullcube.com From talktojamesblair at yahoo.com Sat Mar 27 10:33:15 2004 From: talktojamesblair at yahoo.com (james blair) Date: 27 Mar 2004 07:33:15 -0800 Subject: python & mysql probelm References: Message-ID: Hi Thanks FuManChu ,you solved the problem Thanks, James From python at apocalyptech.com Tue Mar 9 09:42:37 2004 From: python at apocalyptech.com (CJ Kucera) Date: Tue, 9 Mar 2004 08:42:37 -0600 Subject: optparse variable parsing? In-Reply-To: <404DD3C0.8050207@python.org> References: <20040308232639.GB11572@unisrv.net> <404DD3C0.8050207@python.org> Message-ID: <20040309144237.GB11755@unisrv.net> David Goodger wrote: > An "option argument". The answer is no, optparse doesn't support > optional option arguments. The main reason is that it makes a command > like "cmd -abc" impossible to parse reliably: is it equivalent to > "cmd -a bc" or to "cmd -a -b -c"? In the Python tradition, optparse > chooses not to guess. Yeah, true, there is a measure of ambiguity there. In that case I suppose I'd prefer to just sort of "require" the dashes to signify options, if there's a question as to what's an option and what's not, but whatever... > I would suggest that you should have two different options here, a > simple switch and an option which expects/requires an argument. > That's easier to document as well. Yeah, that's what I've been doing, it's just a bit tight because right now the program already accepts fourteen options, and finding options that make sense while keeping them down to one-letter arguments (don't like having to have more than one letter per arg) can get a bit challenging. :) Well, thanks for the confirmation! -CJ -- WOW: Kakistocracy | "The ships hung in the sky in much the same apocalyptech.com/wow | way that bricks don't." - Douglas Adams, python at apocalyptech.com | _The Hitchhiker's Guide To The Galaxy_ From tismer at stackless.com Fri Mar 5 20:02:29 2004 From: tismer at stackless.com (Christian Tismer) Date: Sat, 06 Mar 2004 02:02:29 +0100 Subject: is perl better? In-Reply-To: References: Message-ID: <40492325.4080709@stackless.com> Terry Reedy wrote: ... > Besides trying Hansen's idea of popen instead of systen() (or vice versa), > 3 ideas: > > 1. Write minimal Perl program to make call, and call that from Python ;-) Haahaahaa good joke. More of this, please :) > 2. Rewrite Java program to input long list from file instead of command > line, if such is possible (I have no idea) and if you can write Java or get > someone who does (no idea of that either). Constructive approach, although... > 3. Read win perl source to determine what system calls it is using and then > use Hammond's PyWin extensions to do same from Python. Well, I never claimed that Python is always better than Perl. There are cases where Perl is really better than Python. This might be such a case, and I don't mind. There are many cases where Fortran is better than Python, which don't turn me into a Fortran user. Years ago I claimed: Python is the second best computer language in the world. The best has just to be developed. Meanwhile I know what the best will be. No need to tell everybody that this will be PyPy. Same language, but at machine speed, and with almost no dependency of clumsy system libraries. next-time-we'll-do-that-with-perl - ly y'rs -- 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 biner.sebastien at ouranos.ca Tue Mar 9 14:26:57 2004 From: biner.sebastien at ouranos.ca (biner) Date: 9 Mar 2004 11:26:57 -0800 Subject: getting size of gif Message-ID: Hello all, I would like to know if there is a module out there to help me get the size of a gif image. The idea is to verify that the size is not greater than a certain value before forcing it toward a given dimension in a web page. Also, is there any way to know which function is used if we use two module that define the same function with the same name and arguments. E.g. the join function is present in the string module and the os.path module with string as input and output. Is there a way to force Python to tell me of the possible conflict? Thanks in advance. Ciao! Sebastien Biner. biner.sebastien at ouranos.ca From loic at yermat.net1.nerim.net Fri Mar 5 13:48:24 2004 From: loic at yermat.net1.nerim.net (Yermat) Date: Fri, 05 Mar 2004 19:48:24 +0100 Subject: How to find size of file? In-Reply-To: References: Message-ID: Walter Huf a ?crit : > Hi, I'm the same one with the CGI download problem. This time, however, I > want to send the client the size of the file that will be downloaded. How > would I find the size of the file, so I can include that in the headers? > > --Walter Huf-- > hufman at cobalty.com > http://hufman.cobalty.com > > > -----= Posted via Newsfeeds.Com, Uncensored Usenet News =----- > http://www.newsfeeds.com - The #1 Newsgroup Service in the World! > -----== Over 100,000 Newsgroups - 19 Different Servers! =----- def sizeOf(f): f.seek(0,2) return f.tell() From skip at pobox.com Fri Mar 5 23:39:10 2004 From: skip at pobox.com (Skip Montanaro) Date: Fri, 5 Mar 2004 22:39:10 -0600 Subject: python bnf somewhere? In-Reply-To: References: Message-ID: <16457.21998.68334.325512@montanaro.dyndns.org> Corey> Hey everyone, sorry to bug people, but I remember seeing a nice Corey> complete BNF for python somewhere in the documentation but I Corey> can't for the life of me find it anymore. Anyone have a link? There are references all over the language reference (everywhere a BNF productions is shown) to http://www.python.org/doc/current/ref/grammar.txt This is probably what you were thinking of. Skip From grey at despair.dmiyu.org Wed Mar 17 17:24:31 2004 From: grey at despair.dmiyu.org (Steve Lamb) Date: Wed, 17 Mar 2004 22:24:31 GMT Subject: Newbie Python (Game) Programming Question References: Message-ID: On 2004-03-17, Tina wrote: > Are there any good pages for RPG related items in Python? Everything I've > seen so far has been first-person shooter type stuff. And coming from a > BASIC background, I'm falling back on some of that coding style when I know > there's a better way. Might want to look into the OpenRPG project. It is a client/server application that allows people to play RPGs over the internet. It provides the framework for characters, rules, maps, chatting, die rolls and so on. -- 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 bob at redivi.com Fri Mar 5 18:21:04 2004 From: bob at redivi.com (Bob Ippolito) Date: Fri, 5 Mar 2004 18:21:04 -0500 Subject: securely overwrite files with Python In-Reply-To: <16457.1332.559268.412335@montanaro.dyndns.org> References: <2004030517425550073%bob@redivicom> <16457.1332.559268.412335@montanaro.dyndns.org> Message-ID: On Mar 5, 2004, at 5:54 PM, Skip Montanaro wrote: > >>> First: It is not possible. Let me cite some sentences from shred(1): >>> >>> CAUTION: Note that shred relies on a very important assumption: that >>> the filesystem overwrites data in place. This is the traditional way >>> to do things, but many modern filesystem designs do not satisfy this >>> assumption. > > Bob> Somewhat OT, Mac OS X 10.3 is one of the operating systems > where > Bob> this assumption is false. Files smaller than a certain size > get > Bob> automatically moved around on the disk when it makes sense to > do so > Bob> in order to reduce fragmentation. > > I'm not sure I understand how that can work. Suppose I have multiple > (hard) > links to a small file named "small". If the OS moves it around to > reduce > fragmentation (implying it will have a different inode next time it's > opened) how does it efficiently track down and change all inode > references > to it? In theory it could keep a cache mapping inode numbers back to > the > directories which reference them, but that could consume a fairly large > chunk of memory to maintain. I can't speak to what it does exactly, I'm no HFS+ or xnu expert, but I know it only applies to files under 20mb on journaled HFS+ file systems... I believe that HFS+ has a level of indirection between the file's "inode" (HFS+ probably calls it something else) and the set of blocks it is represented with on disk, so I don't believe that moving the blocks around really has anything to do with hard links or creating a new inode. You can look for yourself if you're particularly interested.. it's part of the APSL licensed Darwin 7.x kernel (xnu): ( should be mountable by WebDAV ) http://www.opensource.apple.com/darwinsource/10.3.2/xnu-517.3.7/bsd/hfs/ files of interest would be: hfs_hotfiles.c hfs_readwrite.c hfs_vnops.c In particular, you would be interested in the hfs_relocate function in hfs_readwrite.c. -bob From maxm at mxm.dk Fri Mar 12 04:59:50 2004 From: maxm at mxm.dk (Max M) Date: Fri, 12 Mar 2004 10:59:50 +0100 Subject: Extending Python Syntax with @ In-Reply-To: References: <104v3lrijtse657@news.supernews.com> Message-ID: <405189fc$0$152$edfadb0f@dread11.news.tele.dk> Y2KYZFR1 wrote: > That is what Python is missing is an quality IDE that is cross > platform. All the ones out now suck when compared to something like > IDEA or Together. > > anyone that thinks about following up this post with anything about vi > or emacs can just stop right now and go back to their hole. An IDE isn't worth much in many use cases. I see the reason in it when developing gui apps. But for my work I honestly don't see any use for it. Basically a good tabbed editor suits my needs. The only two things I really miss is: 1) A good refactoring tool. Search and replace can be a bit hit'n miss sometime. 2) A context aware class browser, that would show the classes with the methods & defined attributes they have in the current context. So that I could do a little less grep'ing and manual backtracking of ancestor objects. So maybe I *do* ned a good IDE anyway :-) regards Max M From jbperez808 at yahoo.com Sun Mar 21 12:14:02 2004 From: jbperez808 at yahoo.com (Jon Perez) Date: Mon, 22 Mar 2004 01:14:02 +0800 Subject: Python bytecode compatibility between interpreter versions In-Reply-To: References: Message-ID: Anyway, we can at least count on the fact that a .pyc compiled by a particular Python version (say, Python 2.1.1) on one platform (say, Mac), will run on another platform (say, Solaris) as long as the interpreter has the same minor version (say, Python 2.1.0). uh... right? From noah at noah.org Fri Mar 19 20:33:24 2004 From: noah at noah.org (Noah) Date: 19 Mar 2004 17:33:24 -0800 Subject: Select on Win XP References: Message-ID: shifflett at nps.navy.mil (D. Shifflett) wrote in message news:... > Hi all, > I am trying to run a Python program > on my Win XP box, that I brought over from a Linux box. >... > select() doesn't return until I have sent a packet > even though I am using a short timeout (1 second) > > ilist = [] > ilist.append(my_sock) > print "readerthread - my_sock %d" % my_sock.fileno() > while not self._stopevent.isSet(): > > print "about to select" > il,ol,el = select(ilist,[],[],1) One thing you might try this for your ilist: ilist.append (my_sock.fileno()) In theory it shouldn't matter. The socket docs say that socket.fileno() is useful for working with select. It's confusing since docs for select.select() say you can pass in a list of an objects supporting fileno() or you can pass integer filedescriptors, so why would socket.fileno() says it's useful for working with select.select()? I don't know, but comeing from a C background using select, I would eliminate any confusion and just use select with an integer list. Let me know if that helps at all. Yours, Noah From rick_muller at yahoo.com Tue Mar 16 11:09:11 2004 From: rick_muller at yahoo.com (Rick Muller) Date: 16 Mar 2004 08:09:11 -0800 Subject: Advice needed: large OpenGL + Widgets Project for Molecular Graphics References: <5eb8fb88.0403151925.4f63842b@posting.google.com> <4056c9c5$0$4143$3a628fcd@reader2.nntp.hccnet.nl> Message-ID: <5eb8fb88.0403160809.177eeb8@posting.google.com> anton at vredegoor.doge.nl (Anton Vredegoor) wrote in message > > VPython [1] seems to combine all requirements, OpenGl and NumPy > integration, easy to install and use, and at least in my case it makes > one very enthusiastic about 3-d programming in Python. > I'm a long-time fan of VPython, but I didn't think it provided widgets. Can I use some widget set to make buttons to control applications? From donn at u.washington.edu Mon Mar 29 16:55:06 2004 From: donn at u.washington.edu (Donn Cave) Date: Mon, 29 Mar 2004 13:55:06 -0800 Subject: process wrapper? References: <5ficndxjntWG4frd38DK-w@speakeasy.net> <1080539401.173853@yasure> <2pWdnQuWrvGhE_Xd38DK-g@speakeasy.net> Message-ID: In article <2pWdnQuWrvGhE_Xd38DK-g at speakeasy.net>, "Steve @ Waypath" wrote: ... > For reasons not clear to me, I get the error: > bad interpreter: No such file or directory > when I include the path to the python interperter. I've tried a number of > approaches: > #!python > #!/usr/bin/python > #!/usr/bin/env python > > (I've got the x bit set on the test files, so it's not a permissions > problem. ) This, I'm guessing, isn't a python problem, and would seem to be > my roadblock. I've done some preliminary searches for an answer, but nothing > has panned out so far; if anyone has any ideas... The first one wouldn't work for sure. Second one works if python is in /usr/bin, third one works if python is in some directory in PATH and env is in /usr/bin. Assuming your own shell is bash, try "type python" and "type env" to see where those programs are. [re zombie processes] > I've read other posts (many yours, I think :) indicating something like > this, but I confess I don't understand the relationship between waitpid() > and spawnv(), how I would use the former with the latter. spawnv returns a process ID, if you use os.P_NOWAIT. It returns the process exit status if you use os.P_WAIT. If you look at the code, in os.py, you will see that this second variation is essentially implemented by applying waitpid() to the first. Donn Cave, donn at drizzle.com From Petri_member at newsguy.com Sat Mar 27 19:47:09 2004 From: Petri_member at newsguy.com (Petri) Date: 27 Mar 2004 16:47:09 -0800 Subject: Choosing Perl/Python for my particular niche References: <40652B0D.7C313F77@doe.carleton.ca> Message-ID: In article <40652B0D.7C313F77 at doe.carleton.ca>, Fred Ma says... > One thing I expect to have to do is to modify design > files. For example, there is a tool which takes ASCII > hardware desscription language (HDL) and converts it > to a C++ (augmented by hardware simulation library). > The translator is freeware, so has limitations which I > have to make up for by tweaking the HDL code. The translator, is it doing the Verilog stuff you mention later in the thread? Why not check if you can't replace the translator altogether with an existing Perl module: http://search.cpan.org/search?query=verilog&mode=all Well, I know nothing about your problem area, but it's a tip in case you hadn't thought about checking CPAN. Petri From opengeometry at yahoo.ca Wed Mar 31 16:19:55 2004 From: opengeometry at yahoo.ca (William Park) Date: 31 Mar 2004 21:19:55 GMT Subject: Fetching websites with Python References: Message-ID: 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 In parallel? Hmm... play around with lynx -dump http://... > a1 & lynx -dump http://... > a2 & lynx -dump http://... > a3 & sleep 15 kill %1 %2 %3 for i in a1 a2 a3; do cat $i echo ---xxx--- done rm a1 a2 a3 In serial, the code becomes for i in http://... http://... http://... ; do lynx -connect_timeout=15 -dump $i echo ---xxx--- done > (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? > > Thanks. > > Yours sincerely > > Markus Franz > > -- William Park, Open Geometry Consulting, Linux solution for data processing and document management. From Greg.Lindstrom at acxiom.com Mon Mar 29 10:20:10 2004 From: Greg.Lindstrom at acxiom.com (Lindstrom Greg - glinds) Date: Mon, 29 Mar 2004 09:20:10 -0600 Subject: Socket Help Message-ID: Hello- I have a python routine (Python 2.2.3 on Windows 2000 "Professional") using a socket connection. Problem is, the backend service I'm connecting to will hang every so often and the socket will simply wait for a response which will never come. I'm thinking of putting in a routine to check the socket's status, which now brings in threading. Before I go to the trouble I thought I'd ask if there is a simple way to verify my socket is still communicating. It's running about 200 transactions per second...if I put in the threaded timer I'd have it take a look every few seconds to see if the "TotalRecordsProcessed" counter has been incremented. Your constructive thoughts are requested. Thanks! --greg ********************************************************************** 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. -------------- next part -------------- An HTML attachment was scrubbed... URL: From mghsm at hotpop.com Sat Mar 13 10:44:25 2004 From: mghsm at hotpop.com (Richie Adler) Date: Sat, 13 Mar 2004 12:44:25 -0300 Subject: Any known bitmap/resource/image collection for a Spanish card deck? Message-ID: Does anyone know of a bitmap/resource/image collection for a Spanish card deck? I'm planning to create a new cardgame which requires this kind of deck (prototyping in Python and possible final development in Delphi; flames about my tool choices will be gently dropped into the bit bucket) I'd be very thankful about any information regarding this matter. -- o-=< Richie Adler >=-o UnROT13 e-mail address to write directly to me From __peter__ at web.de Mon Mar 29 14:56:09 2004 From: __peter__ at web.de (Peter Otten) Date: Mon, 29 Mar 2004 21:56:09 +0200 Subject: Integer, 64 Bit, signed and unsigned References: Message-ID: Torsten Mohr wrote: > Hi, > > i'd like to use 64 Bit Integer values in Python, > can anybody give me a hint on what are the limits > in Python? > > Can i use signed and unsigned 64 Bit Integers? > > > Thanks for hints, > Torsten. >>> 10**100 10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000L As for signed integers, the sky's the limit :-) Peter From cookedm+news at physics.mcmaster.ca Tue Mar 16 20:47:37 2004 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Tue, 16 Mar 2004 20:47:37 -0500 Subject: Semantics of == References: <40200384.0403161538.7407d9e2@posting.google.com> Message-ID: At some point, axelboldt at yahoo.com (Axel Boldt) wrote: > Still trying to understand "=="... It appears as if two equal objects > can become unequal if you perform the same operations on them: > > >>> l=[1] > >>> s=l > >>> l.append(s) You're building a cyclic list: l contains a reference to itself. General advice: don't do that unless you know what you're doing. > >>> w=[1] > >>> r=[1,w] > >>> w.append(r) > >>> s > [1, [...]] > >>> w > [1, [1, [...]]] > >>> s==w > True > > Note that they're equal, yet are printed differently. Element-by-element, they're equal, yes. > >>> s[0]=2 > >>> w[0]=2 > >>> s==w > False > > All of a sudden they have become unequal. That's b/c s originally looked like this if we expand out the recursion a few more levels: [1, [1, [1, [1, [...]]]]] where each sub-list is also s. w also looks like [1, [1, [1, [1, [...]]]]] where the *second* sub-list is w. Set the first elements to 2: s is now: [2, [2, [2, [2, ...]]]] w is now: [2, [1, [2, [1, ...]]]] See? The second sub-list of w is not w, so it wasn't changed. -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From grelens at NOSPAMyahoo.NOTNEEDEDfr Wed Mar 10 06:14:09 2004 From: grelens at NOSPAMyahoo.NOTNEEDEDfr (GrelEns) Date: Wed, 10 Mar 2004 12:14:09 +0100 Subject: trap attributeError from inside a dict ? References: <404ed174$0$307$626a14ce@news.free.fr> Message-ID: <404ef86f$0$289$626a14ce@news.free.fr> "Peter Otten" <__peter__ at web.de> a ?crit dans le message de news: c2mp83$b4l$02$1 at news.t-online.com... > Personally, I would put custom objects into a normal dictionary instead of > playing one of these tricks. you convince me thanks i will do it this way, best regards From matt.gerrans at hp.com Tue Mar 23 20:02:20 2004 From: matt.gerrans at hp.com (Matt Gerrans) Date: Wed, 24 Mar 2004 01:02:20 GMT Subject: Human validation with an image References: <2ca51434.0402181235.460befe3@posting.google.com> Message-ID: "Dennis Reinhardt" wrote: > > (E.g. "What color is the sky?" > > black - night time > white - cloudy day > red - http://www.sunherald.com/mld/sunherald/news/nation/7495641.htm > blue - clear day Reminds me of a conversation with my two-year-old: Me: "What color is that red fish?" Her: "Blue!" From afriere at yahoo.co.uk Tue Mar 23 23:08:25 2004 From: afriere at yahoo.co.uk (Asun Friere) Date: 23 Mar 2004 20:08:25 -0800 Subject: name of 'name' References: Message-ID: <38ec68a6.0403232008.307dbf54@posting.google.com> "Larry Bates" wrote in message news:... > Not exactly sure I understand the question, but here > goes: > > If you are talking about a class, you can get the > classname from : > > self.__class__.__name__ > > Hope info helps. > > -Larry > Nope, that would give the name of the class of the instance, whereas her code retrieves the name of the instance itself. Eg. >>> name = lambda x: [y for y in globals().keys() if globals()[y]==x][0] >>> foo = 5 >>> bar = 'hello' >>> baz = [foo, bar] >>> baz[0].__class__.__name__ 'int' >>> name(baz[0]) 'foo' >>> From alessandro at sephiroth.it Fri Mar 26 15:05:19 2004 From: alessandro at sephiroth.it (Alessandro Crugnola *sephiroth*) Date: Fri, 26 Mar 2004 20:05:19 GMT Subject: extract parameters from a WSDL Message-ID: <3209c.106332$z23.4489468@news3.tin.it> Hi, i'm trying to use the SOAPpy library in order to get all the informations from the in params of a WSDL method. I can gen easily the parameter type, but in case this is a complex type i can't ba able to navigate the types toward to simple base type.. and the documentation with the .zip is poor. Can someone give me a link or a simple explanation on how to do that? thanks in advance From m_schellens at hotmail.com Thu Mar 11 06:15:25 2004 From: m_schellens at hotmail.com (Marc Schellens) Date: Thu, 11 Mar 2004 20:15:25 +0900 Subject: NumPy (numarray) problem with C code In-Reply-To: References: Message-ID: Thanks, I think I was using the wrong documentation. marc David M. Cooke wrote: > At some point, Marc Schellens wrote: > > >>Following the NumPy documentation, I took over some C code, >>but run into an error. >>Does anybody have a suggestion? >>Thanks, >>marc >> >> >>gdlpython.cpp:225: `PyArray_Type' undeclared (first use this function) >> >>#include >>// python numarray is used >>#include > > > I don't know how you're compiling, but you're probably better off > using > #include "Python.h" > #include "numarray/arrayobject.h" > > and specifying the proper include directory. This way you're not > hardcoded to the Python version. distutils automatically adds the > proper directory to the compile line, for instance. > > You're using numarray, so you may want to use the numarray interface > instead of the Numeric compability interface. Include > "numarray/libnumarray.h" instead of "numarray/arrayobject.h" > > >>// ... >> >>BaseGDL* FromPython( PyObject* pyObj) >>{ >> PyObject *object; >> >>// following is line 225 >> if( !PyArg_ParseTuple(pyObj, "O!", &PyArray_Type, &object)) > > > There is no such thing as PyArray_Type in numarray, and actually, > there isn't one array type. I'd check for the specific > string/long/complex/double types first (your code below).. > > >> { >> // non-array - try other >> PyErr_Clear(); >> // string >> char* s; >> if( PyArg_ParseTuple(pyObj, "s", s)) >> return new DStringGDL( string(s)); >> PyErr_Clear(); >> // integer >> DLong l; >> if( PyArg_ParseTuple(pyObj, "l", &l)) >> return new DLongGDL( l); >> PyErr_Clear(); >> // complex >> Py_complex c; >> if( PyArg_ParseTuple(pyObj, "D", &c)) >> { >> DComplexDbl cc( c.real, c.imag); >> return new DComplexDblGDL( cc); >> } >> PyErr_Clear(); >> // float >> DDouble d; >> if( PyArg_ParseTuple(pyObj, "d", &d)) >> return new DDoubleGDL( d); >> >> throw GDLException( "FromPython: Cannot convert python object.") ; >> } > > > and use NA_InputArray() to get the array. This returns NULL if it > can't make the argument an array. You're using the Numeric > compatibility functions below; you might as well use the numarray > equivalents instead. > > >> // array type >> PyArrayObject* array = (PyArrayObject*) object; >> >> int nDim = array->nd; >> int item_type = array->descr->type_num; >> >> // make array contiguous >>// array = static_cast< PyArrayObject*> >>// (PyArray_ContiguousFromObject( object, >>// item_type, >>// 0,0)); >> array = (PyArrayObject*) PyArray_ContiguousFromObject( object, >> item_type, >> 0,0); >> if( array == NULL) >> throw GDLException( "FromPython: Error making array contiguous.") ; > > > Note that array will be NULL also if it's not an array; this would be > a better way to use it. > > Replace the above with something like > > PyArrayObject* array = NA_InputArray(object, tAny, NUM_C_ARRAY); > if (array == NULLL) { > throw GDLException( "FromPython: Error making array contiguous.") ; > } > int item_type = array->descr->type_num; > > Double-check the numarray C API documentation as to whether you should use > NA_InputArray or NA_IoArray. > > Haven't looked at the following carefully: > >> size_t dimArr[ MAXRANK]; >> if( nDim > MAXRANK) >> { >> Warning( "FromPython: Array has more than "+MAXRANK_STR+ >> " dimensions. Extending last one."); >> size_t lastDim = array->dimensions[ MAXRANK-1]; >> for( size_t i=MAXRANK; idimensions[ i]; >> for( size_t i=0; i> dimArr[ i] = array->dimensions[ i]; >> dimArr[ MAXRANK-1] = lastDim; >> nDim = MAXRANK; >> } >> else >> { >> for( size_t i=0; i> dimArr[ i] = array->dimensions[ i]; >> } >> >> dimension dim( dimArr, nDim); > > > > Use the numarray types instead: tUInt8, tInt8, tInt16, tFloat64, etc: > > >> switch( item_type) >> { >> // case PyArray_NOTYPE: //UNDEF*** >> case PyArray_UBYTE: //BYTE >> return NewFromPyArrayObject< DByteGDL>( dim, array); >> case PyArray_SHORT: //INT >> return NewFromPyArrayObject< DIntGDL>( dim, array); >> case PyArray_INT: //LONG >> return NewFromPyArrayObject< DLongGDL>( dim, array); >> case PyArray_FLOAT: //FLOAT >> return NewFromPyArrayObject< DFloatGDL>( dim, array); >> case PyArray_DOUBLE: //DOUBLE >> return NewFromPyArrayObject< DDoubleGDL>( dim, array); >> case PyArray_CFLOAT: //COMPLEX >> return NewFromPyArrayObject< DComplexGDL>( dim, array); >> // case PyArray_NOTYPE: //STRING*** >> // case PyArray_NOTYPE: //STRUCT*** >> case PyArray_CDOUBLE: //COMPLEXDBL >> return NewFromPyArrayObject< DComplexDblGDL>( dim, array); >> // case PyArray_NOTYPE: //PTR*** >> // case PyArray_NOTYPE: //OBJECT*** >> case tUInt16: //UINT* >> return NewFromPyArrayObject< DUIntGDL>( dim, array); >> case tUInt32: //ULONG* >> return NewFromPyArrayObject< DULongGDL>( dim, array); >> default: >> throw GDLException( "FromPython: Unknown array type.") ; >> } >> >> return NULL; // compiler shut-up >>} > > From uche at ogbuji.net Sun Mar 14 23:27:27 2004 From: uche at ogbuji.net (Uche Ogbuji) Date: 14 Mar 2004 20:27:27 -0800 Subject: pyXML beginner questions References: Message-ID: Sebastian Fey wrote in message news:... > hi, > > id like to do the following: > > (1) open a .xml, change something and save it. > problem is: how to save/serialize? > i tried xml.dom.ext.Print, but this resolves all entities and serializes > the xml with resolved entities. (see example below) Sounds as if you want a lexical round-trip. Very few XML processing packages allow for this. I'd check whether pxdom supports this. If not, I don't expect you'll find it in Python. http://www.doxdesk.com/software/py/pxdom.html > (2) id also like to load external parsed entities referenced in the xml. > MSXML provides an extension(?) to DOM which returns the uri to an > entityReference-NODE. > any similar in pyXML. actually, is nodetype entityReference implemented > in pyXML. i always get the nodeType of the resolved entity, ie 3 > (NODE_TEXT) with a internal unparsed entity. Again pxdom will get you closest. --Uche From jcarlson at nospam.uci.edu Fri Mar 5 02:09:13 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Thu, 04 Mar 2004 23:09:13 -0800 Subject: Parsing xml file using python In-Reply-To: References: Message-ID: > PyXML would be a perfect solution - and easy too. Even easier would be to use an SGML parser: http://flangy.com/dev/python/striphtml.html Works for XML, HTML, etc. - Josiah From theller at python.net Thu Mar 25 15:16:15 2004 From: theller at python.net (Thomas Heller) Date: Thu, 25 Mar 2004 21:16:15 +0100 Subject: Problems with py2exe 0.50 and win98se and win2k References: Message-ID: jamesl at appliedminds.com (James Laamnna) writes: >> >> Can it be that py2exe collects some system dlls in the dist dir? > > The dlls it collects are: > python23.dll (needed) > qt-mt230nc.dll (needed - i use pyqt) > libsip.dll (also for pyqt) > > Also it collects: > ddraw.dll > glu32.dll > opengl32.dll > > Not sure why it collects those last 3. > Could that be the problem? Yes, that's the problem. I just examined the last three dlls with dependencywalker, and found that opengl32.dll on my XP Pro, SP 1 system uses the IsWow64Process function in kernel32.dll. Looking at opengl32.dll file properties, the file version is "5.1.2600.1106 (xpsp1.020828-1920)", which look xp specific. Using the XP version of this file (and I guess the same holds for ddraw.dll and glu32.dll) on win98 or win2k surely leads to desaster. I think that you must install DDraw and OpenGL on the target system 'the official way', and not by using the files that py2exe collects. py2exe has a simple mechanism which tries to exclude 'system dlls', but obviously it fails in this case. Therefore you should use the 'dll_excludes' option, the wiki has an example how to use it. Thomas From look at www.covingtoninnovations.com.for.address Tue Mar 23 20:36:49 2004 From: look at www.covingtoninnovations.com.for.address (Michael A. Covington) Date: Tue, 23 Mar 2004 20:36:49 -0500 Subject: IDLE won't launch, and other frustrations References: Message-ID: On the trail of figuring out why IDLE won't launch, look at 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 Tkinter >>> Tkinter._test() Traceback (most recent call last): File "", line 1, in ? File "C:\PYTHON23\lib\lib-tk\Tkinter.py", line 3640, in _test root = Tk() File "C:\PYTHON23\lib\lib-tk\Tkinter.py", line 1564, in __init__ self.tk = _tkinter.create(screenName, baseName, className) _tkinter.TclError: Can't find a usable init.tcl in the following directories: {C:\WN16\LIB\TCL7.6} {C:\WN16\LIB\TCL7.6} C:/WN16/LIB/tcl8.4 C:/Python23/lib/tcl8.4 C:/lib/tcl8.4 C:/library This probably means that Tcl wasn't installed properly. >>> Here \WN16 is where *another* TCL/TK application *used* to reside. And the TCL stuff definitely *does* exist under C:\Python23\tcl\tcl8.4 (not lib\tcl8.4). By default does Python 2.3.3 install itself incorrectly???!! From bart_nessux at hotmail.com Fri Mar 12 15:57:26 2004 From: bart_nessux at hotmail.com (Bart Nessux) Date: Fri, 12 Mar 2004 15:57:26 -0500 Subject: root password in a .py script In-Reply-To: <7xoer1ls3j.fsf@ruckus.brouhaha.com> References: <7xoer1ls3j.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > If they have changed the root password on their machine, then the old > root password in your script won't work on that machine. > > Find another way to do what you're asking. Well, it works. They change the password and the script changes it back... try it yourself on Mac OSX 10.3.x, before claiming it doesn't work. def set_pass(): import pexpect import time # pexpect is an addon module. # It has to be installed manually. set = r"password" child = pexpect.spawn("/usr/bin/passwd") child.expect_exact("New password:") child.sendline(set) time.sleep(0.1) child.expect_exact("Retype new password:") child.sendline(set) time.sleep(0.1) child.close() From dontbotherworld at yahoo.com Sat Mar 13 00:04:25 2004 From: dontbotherworld at yahoo.com (dont bother) Date: Fri, 12 Mar 2004 21:04:25 -0800 (PST) Subject: typecasting: a string object to a dictionary object In-Reply-To: Message-ID: <20040313050425.74690.qmail@web60810.mail.yahoo.com> Hi, Thanks! Just one more favour. I want to sort the entries on this new dictionary. (Increasing order) and convert it back to a string where each values are not separated by , but by space. ie. for example: I have a string s of the form index: value, index: value, index: value I converted it to a dictionary by the method you suggested. I want to sort the entries now, with increasing order of index. Once I have the sorted dictionary, I want to convert it back to a string of the form 1 index:value index:value index:value Note, that 1 is added because I am creating feature vectors of the type "spam". index: value pairs are now separated by space instead of comma and finally I want to write this to a file. The whole notion of making a string to a dictionary was because of sorting. Can you extend this piece of code for the above objective. I will indeed be very grateful to you. import string # define a test string s1 = "" # get rid of the < and > by taking a slice s1 = s1[1:-1] # split string at the commas s2 = string.split(s1,',') mydict = {} for item in s2: a,b = string.split(item,":") mydict[a] = b print mydict[a] print "Dictionary is: ", mydict Thanks Dont --- midtoad wrote: > dont bother wrote: > > > I have a string: > > > > feature_vector. It is of the form > > > > > > I want to make this string into a dictionary so > that I > > can apply .keys() method > > okay, here's a solution, assuming that your < and > > are part of the string. > If not, remove the line where you take a slice. > I'm sure that there are > more Pythonic solutions, but this works... > > --- > import string > > # define a test string > s1 = "" > # get rid of the < and > by taking a slice > s1 = s1[1:-1] > # split string at the commas > s2 = string.split(s1,',') > mydict = {} > for item in s2: > a,b = string.split(item,":") > mydict[a] = b > print mydict[a] > print "Dictionary is: ", mydict > --- > > cheers > Stewart > > -- > http://mail.python.org/mailman/listinfo/python-list __________________________________ Do you Yahoo!? Yahoo! Mail - More reliable, more storage, less spam http://mail.yahoo.com From timr at probo.com Fri Mar 26 02:24:21 2004 From: timr at probo.com (Tim Roberts) Date: Thu, 25 Mar 2004 23:24:21 -0800 Subject: Beginner Threaded file reading access References: <2835a96b.0403230909.35be2b7b@posting.google.com> Message-ID: <4im76054evpqbgkk2ja96rq66t1rm9r2uk@4ax.com> jnoller at reference-info.com (Jesse Noller) wrote: > >I'm fairly new to python as a language - and really new to >multithreaded application dev, so please be gentle. > >Right now, I have a script that basically looks like: > >def foo(): > > f = open(file, "r") > for lines in file.readlines: > do something > bar(var, var) > write stuff to a results file > file.close > return > >foo() > >Now, what the file I am opening contains is a whole bunch of lines >with a filepath in it I need to process with foo() and bar() - each >transaction writes some data to some log files. > >I am trying to figure out with how best to approach multithreading >this Multithreading will not help this sequence unless (A) you have multiple processors, or (B) the processing in bar() needs to wait for something. If bar() is CPU bound, you would get the same performance by just executing sequentially. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From michael at stroeder.com Mon Mar 29 11:50:57 2004 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Mon, 29 Mar 2004 18:50:57 +0200 Subject: ANN: python-ldap-2.0.0pre21 Message-ID: Find a new pre-release of python-ldap: http://python-ldap.sourceforge.net/ python-ldap provides an object-oriented API to access LDAP directory servers from Python programs. It mainly wraps the OpenLDAP 2.x libs for that purpose. Additionally it contains modules for other LDAP-related stuff (e.g. processing LDIF, LDAPURLs and LDAPv3 schema). Changes: Wrapped OpenLDAP's ldap_whoami_s(). Fixed incompability with OpenLDAP 2.2 libs. Code cleaning. ---------------------------------------------------------------- Released 2.0.0pre21 2004-03-29 Changes since 2.0.0pre20: setup.py: * runtime_library_dirs is set Modules/: * (Hopefully) fixed building with OpenLDAP 2.2 libs in errors.c * Removed meaningless repr() function from LDAPObject.c * Removed setting LDAP_OPT_PROTOCOL_VERSION in l_ldap_sasl_bind_s() * Modified string handling via berval instead of *char in l_ldap_compare_ext() makes it possible to compare attribute values with null chars. * Wrapped ldap_sasl_bind() for simple binds instead of ldap_bind() since 1. the latter is marked deprecated and 2. ldap_sasl_bind() allows password credentials with null chars. * Removed unused sources linkedlist.c and linkedlist.h * Function l_ldap_whoami_s() only added if built against OpenLDAP 2.1.x+ libs (should preserve compability with 2.0 libs) ldap.ldapobject: * LDAPObject.bind() only allows simple binds since Kerberos V4 binds of LDAPv2 are not supported anymore. An assert statement was added to make the coder aware of that. * Renamed former LDAPObject.sasl_bind_s() to LDAPObject.sasl_interactive_bind_s() since it wraps OpenLDAP's ldap_sasl_interactive_bind_s() From dmq at gain.com Sat Mar 27 10:41:42 2004 From: dmq at gain.com (David MacQuigg) Date: Sat, 27 Mar 2004 08:41:42 -0700 Subject: A 'Python like' language References: <40645d8f$0$10775$afc38c87@news.easynet.co.uk> <1068up4kn49778@news.supernews.com> Message-ID: On Sat, 27 Mar 2004 07:58:44 -0600, Skip Montanaro wrote: >Thanks to Microsoft, attachments frequently don't pass through mail servers >these days. I know I filter all attachments out of a couple small mailing >lists I manage. I've never had this problem. Is this something MS exchange does? >At any rate, I agree with John that the Prothon folks got this particular >bit dead wrong. If they wanted to avoid tab/space problems they should have >required that all indentation use only spaces, not only tabs. The advantage of tabs ( a small one in my opinion ) is that the reader can adjust the actual spacing to his preference. Another advantage is that you can add leading spaces for purely cosmetic reasons (lining up columns in a continuation line ). The tabs control the syntax. x = 1.23 + 2.34 + 3.45 + 4.56 + \ 5.23 + 6.34 + 7.44 + 8.56 # Which number is slightly off ? The solution I believe, is to have a special 'publishing' mode where tabs are replaced by the character sequence '. ' with however many spaces the sender wants. The dots actually make large, deeply-nested blocks easier to read. Of course, we will need a matching import mode, converting the dot-space sequences back to tabs. -- Dave From peter at engcorp.com Tue Mar 30 08:55:25 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 30 Mar 2004 08:55:25 -0500 Subject: GUI Frameworks in Python? In-Reply-To: References: Message-ID: Greg Krohn wrote: > Peter Hansen wrote: > >> ... >> I don't understand this, though it's been mentioned before. >> >> On my machine, launching the wxPython Demo app takes roughly 0 seconds >> before the splash screen appears, and I can immediately click on it >> and get the app itself, for a total launch time of: immeasurably fast. > > On my machine (WinXP Pro, AMD 2400, 512MB) it takes a little over three > seconds before the splash shows and maybe another two seconds for the > main frame to show. It takes a little over a second to load IDLE. The first time I launched IDLE, it took almost three seconds. (I don't have the Python installer compile .py files ahead of time.) After that it takes about one second as well. I'm curious about the differences with wxPython. Three seconds seems unusually long when on a slightly slower machine I can do it in well under a second. Was that the first time you ran it? Many other apps open? I have over 256MB RAM free when I try this... -Peter From bignose-hates-spam at and-benfinney-does-too.id.au Sun Mar 14 22:26:33 2004 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 15 Mar 2004 14:16:33 +1050 Subject: Seeking advice on GUI code architecture References: Message-ID: On Sun, 14 Mar 2004 22:29:08 -0500, Qp wrote: > My problem is this: how do you keep your GUI code seperate from as much > underlying code as possible? In the last decade, the "pattern language" method of formalising common architectural solutions has been increasingly popular in programming. It is especially popular in things like interface programming, where the architecture chosen has a dramatic effect on the efficacy and efficiency of the program. What you want may be the "Model-View-Controller" pattern. Others may suggest other patterns. You would be well advised to read up on current common patterns in interface design. -- \ "I think a good gift for the President would be a chocolate | `\ revolver. And since he's so busy, you'd probably have to run up | _o__) to him real quick and hand it to him." -- Jack Handey | Ben Finney From skip at pobox.com Sat Mar 13 11:19:16 2004 From: skip at pobox.com (Skip Montanaro) Date: Sat, 13 Mar 2004 10:19:16 -0600 Subject: Unicode is driving me nuts! In-Reply-To: <20040313083545.50340.qmail@web13007.mail.yahoo.com> References: <16466.22306.480990.299621@montanaro.dyndns.org> <20040313083545.50340.qmail@web13007.mail.yahoo.com> Message-ID: <16467.13444.992381.764066@montanaro.dyndns.org> Anthony> Thank you, Skip. You know what, I guess I'll give up using Anthony> unicode, as you also mentioned you used to have headache with Anthony> it. Anthony> I'll probably just read by bytes and check if the byte is a Anthony> Chinese character. If it is, read 2 bytes instead. What do Anthony> you think? This way, I will hopefully not to have a lot of Anthony> unreadable characters. I should have been clearer. I wasn't suggesting that you not use Unicode. That way lies madness. Don't give up. Unicode isn't intractable. It is a somewhat different way of thinking about handling text. In my case I already had a large set of Python programs and a MySQL database which knew nothing about Unicode so converting them was more difficult than if I'd started from scratch with Unicode (which wasn't available in Python when I began Musi-Cal in 1995). I tried a couple simple hacks which didn't work (different than, but with the same shortcut idea in my head as your "read a byte, sniff for a Chinese character" idea). Once I bit the bullet and converted to Unicode (and the utf-8 encoding when I needed raw bytes) it wasn't as hard as I'd expected. I think Python is still a little schizophrenic in some regards, returning strings when the content is pure ASCII and returning Unicode objects otherwise. In some places you need to test. In the future I hope we see more of a string/Unicode convergence with a separate byte object for character data that doesn't represent some kind of text (like the string representation of code objects). The two biggest problems which remain for me are: * I'm still using a Perl/Mason web front-end which doesn't do Unicode right * Web form submissions lack of consistent encoding information I still have to sniff those inputs to guess at the encoding. This is more frequent than you might think even for a website which has a largely US/Canadian user base. In short, you need a basic understanding of Unicode issues. The Joel on Software web page someone else posted is a decent start. Googling for "python unicode" will yield a nice tutorial from ReportLab and several other interesting links. Play around with some small examples. When designing your application consider all the possible input sources and output destinations. When writing text to files or databases that are not Unicode-aware make sure you store everything using one encoding (I recommend utf-8). That way, other programs which read that data (or your own program later on) can assume the encoding. When reading input data make sure you understand the auxiliary properties of the data source (for instance, grab the content-type header from the HTTP response of pages you download from the net - but be prepared to catch errors and guess, as it can sometimes be wrong). If working with data of unknown encoding you'll have to figure out some heuristics for guessing the data encoding. Did I mention you need to know how all input and output text is encoded? The most important thing to remember (JoS points this out) is: It any nuthin' unless you know the encoding. Did I say that enough? unicode('\xfe\xff\x00<\x00w\x00i\x00n\x00k\x00>', "utf-16").encode("ascii") Skip From amy-g-art at cox.net Sat Mar 20 03:01:48 2004 From: amy-g-art at cox.net (Amy G) Date: Sat, 20 Mar 2004 00:01:48 -0800 Subject: Help getting the md5 module to work References: Message-ID: I have never used the md5 module that python offers... but after reading this post I thought I would try it out. >>> n = md5.new() >>> n.update("help") >>> n.hexdigest() '657f8b8da628ef83cf69101b6817150a' But I run FreeBSD 5.0 and when I execute $ echo help | openssl md5 45b758a4f518f3ff31363696132f5f5a What gives? What am I missing here? Thanks in advance for shedding some light on my "easy" question. Carl Banks" wrote in message news:m1O6c.25774$P45.20864 at fe1.columbus.rr.com... > Grumfish wrote: > > I'm trying to use the md5 module but it gives me a different result from > > what other programs give. This is the code I have and the result from > > hexdigest() never matches what I expect. Its probably something stupid > > but its driving me crazy. > > > > f = file (filename, "r") > > m = md5.new() > > data = f.read (CHUNK_SIZE) > > while data != "": > > m.update (data) > > data = f.read (CHUNK_SIZE) > > > I'll wager this is happening on Windows. When reading data in text > mode on Windows, Python converts "\r\n" sequence to "\n". You need to > open the file in binary mode. Try changing the first line to: > > f = file(filename,"rb") > > > > > -- > 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 roy at panix.com Wed Mar 17 19:46:31 2004 From: roy at panix.com (Roy Smith) Date: Wed, 17 Mar 2004 19:46:31 -0500 Subject: attributes of Python classes References: <3064b51d.0403171605.75ec1ba0@posting.google.com> <4058F086.490C215B@alcyone.com> Message-ID: In article <4058F086.490C215B at alcyone.com>, Erik Max Francis wrote: > beliavsky at aol.com wrote: > > > I have started using classes with Python and have a question > > about their use. > > > > In Python, 'attributes are all "public" and "virtual" in C++ > > terms; they're all accessible everywhere and all looked up > > dynamically at runtime' (Quoting "Learning Python", 2nd. ed., > > p367). It seems to me that two good conventions are to > > > > (1) initialize all attributes in the __init__ function > > (2) avoid creating new attributes elsewhere that are not initialized > > in > > __init__ > > > > I have not followed these conventions so far, and sometimes > > it is difficult for me to tell what attributes an instance of > > a class has. Are these conventions good? > > Yes, I think so, provided a key feature of the class in question isn't > that it's inherently dynamic (in which case it's inherently infeasible > to do this) -- an example might be a class that you'd like to mimic the > interface of a module, so it effectively acts like a dictionary but it > allows attribute access to access the dictionary as well. > > I certainly follow them as best as is possible in my own code; I can > only think of once instance in an old project where I don't do that, and > it's marked as ugly in the code. I agree that initializing all attributes in __init__ is a good idea. Even if you initialize them to None and overwrite them in some other method before ever accessing the value, it's still a nice way to help soem future reader understand your class better. If it's a good idea to have self-documenting code, I guess it's an even better idea to have executable comments :-) From newsgroups at jhrothjr.com Sat Mar 13 06:16:19 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 13 Mar 2004 06:16:19 -0500 Subject: Static Typing in Python References: Message-ID: <1055re3j9v2oja1@news.supernews.com> "Premshree Pillai" wrote in message news:mailman.349.1079161675.19534.python-list at python.org... > --- Jacek Generowicz > wrote: > Jacek Generowicz > writes: > > > > > Peter Maas writes: > > > > > > > Premshree Pillai schrieb: > > > > > How do I force static typing in Python? > > > > > > > > You have to enforce it by code instead of > > declaration, i.e. you > > > > have to do runtime type checking. > > > > > > Just what do you understand "static typing" to > > mean ? > > > > I ask because I am prepared to accept that you have > > a different > > working definition of "static typing" from mine, but > > people who > > actually want static typing typically want it > > because they think it > > gives them the following advantages: > > > > a) type errors caught at compile time, > > > > b) faster program exectution. > > > > The code you showed: > > > > > > class doesTypeChecking: > > > > def __init__(self): > > > > self.__dict__["aString"] = "" > > > > self.__dict__["aFloat"] = 0.0 > > > > > > > > def __setattr__(self, attr, value): > > > > if type(self.__dict__[attr]) != > > type(value): > > > > raise ValueError, "Type mismatch > > for attribute %s\n" % attr > > > > will catch no type errors at compile time, and will > > slow down > > execution, so I suspect that Premshree will be > > disapponinted with it. > > > > > > (BTW, my definition of "static typing" is "type > > checking is done at > > compile time" ... your example really looks like > > dynamic typing to > > me ... albeit with some restrictions on attribute > > types.) > > > > > > Premshree: Python is dynamically typed. There is no > > way to enforce > > static typing. There is something called > > "pychecker" which > > might be of some help to you. Why do you > > think that you > > want static typing in Python ? > > -- > > http://mail.python.org/mailman/listinfo/python-list > > Yes, I am aware that Python is dynamically typed, and > so is Perl, right? In Perl, we have the "use strict > vars" pragma to force variable declaration. Is there > something like it in Python? No. > Don't you think forced variable declaration is an > important requirement in a language? No. John Roth > > ===== > -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 mogmios at mlug.missouri.edu Mon Mar 29 10:44:24 2004 From: mogmios at mlug.missouri.edu (Michael) Date: Mon, 29 Mar 2004 07:44:24 -0800 Subject: Tabbing probs In-Reply-To: <40682BD8.3040501@stackless.com> 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> <406829FF.5060304@mlug.missouri.edu> <40682BD8.3040501@stackless.com> Message-ID: <40684458.9030507@mlug.missouri.edu> > No, I think you don't get at the real problem: > People do use tabs which are 8 spaces, but they > want their code to be indented by steps of four. > This creates mixed tabbing, and that's what you > see way too often when reading foreign code. > You have to adjust your editor to *that* tabbing, > before editing the file, and then convert or > live with it. How would this create mixed tabbing unless sometimes they are using spaces as tabs and sometimes using tabs as tabs? Will stopping the use of tabs improve the situation or will that just mean that some people use four spaces for indention and some people use eight.. both being a hack to try to make spaces act like tabs. Why does it matter if a tab is 4 spaces long or 8 spaces long? Either way blocks should line up assuming that nobody incorrectly tries to use spaces as tabs. If we get rid of support for using tabs for indenting then what? Some people (like myself) will continue using programs that insert tabs when they press the tab key and everyone else will still be adjusting their editors to try to substitute the desired number of spaces when the tab key is pressed. What would be fixed? It took a long time to convince me that Python wasn't insane for making whitespace significant. If people really have so much trouble with it (I don't) maybe it is a bad idea to use it to indicate code blocks? From aghuloum at cs.indiana.edu Mon Mar 8 15:13:30 2004 From: aghuloum at cs.indiana.edu (Abdulaziz Ghuloum) Date: Mon, 8 Mar 2004 15:13:30 -0500 Subject: OFF-TOPIC:: Why Lisp is not my favorite programming language References: <165b3efa.0403030443.4d591f04@posting.google.com> <404675da@news.tce.com> Message-ID: <0001HW.BC723E1A0003EDD1F02845B0@news.indiana.edu> On Thu, 4 Mar 2004 10:31:57 -0500, Joe Marshall wrote (in message ): > "Dale King" writes: >> Feel free to name a language that you think is dead and someone will tell >> you someplace that it is still in active use. > > Focal > FX > Lakota > REBOL 1.x At IU, we use Focal in the digital design course to stress-test our hand-built PDP8s. Aziz,,, From grelens at NOSPAMyahoo.NOTNEEDEDfr Wed Mar 3 04:10:27 2004 From: grelens at NOSPAMyahoo.NOTNEEDEDfr (GrelEns) Date: Wed, 3 Mar 2004 10:10:27 +0100 Subject: input from sdtin or file... Message-ID: <4045a103$0$28147$636a15ce@news.free.fr> hello, i wonder if there is a more pythonic way to do this : having input of a script either from a file or from stdin if the file is not provided, see below. what do you think of it ? is there a better way ? i have noticed some strange behaviour with stdin having sometimes to do 2 * ctrl-z to end the input, or also stange temporizing when using os redirection (like ./myscript.py References: Message-ID: Zhi Peng wrote: > Hi! > Does anyone know if MySql support unicode data? > ?????? This isn't exactly a Python question, is it? Anyway, even here Google is your friend, leading fairly quickly to http://www.mysql.com/doc/en/Charset.html -Peter From tyrone_1066 at yahoo.com Sat Mar 27 15:50:42 2004 From: tyrone_1066 at yahoo.com (J Hamilton) Date: 27 Mar 2004 12:50:42 -0800 Subject: Variable in Regex Message-ID: In Perl in can put a scalar variable in a regex as the pattern. for example: m/$var/ where $var contains the string I want to match Is there a way to do this in Python? From rogerb at rogerbinns.com Mon Mar 22 13:04:17 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Mon, 22 Mar 2004 10:04:17 -0800 Subject: Neat Trick for Loading Modules with unknown Name References: Message-ID: > __import__ doesn't handle packages, right? The above with exec() > appears, unfortunately, to be the simplest approach(*) to handling > *arbitrary* imports, even if they are nested as in xml.sax.whatever. Depends on your definition of *arbitrary* :-) I had the need to load files that could have any arbitrary filename in any arbitrary location (ie not even remotely anywhere near sys.path). import imp module=imp.load_source("__ignore", file, open(file, "rt")) You can name your module something better than I did. I was loading a whole bunch of files whose names are not even valid for Python modules, and I didn't care what they thought they were called (the module object above was stuck in a dictionary). Roger From claird at lairds.com Tue Mar 23 11:19:57 2004 From: claird at lairds.com (Cameron Laird) Date: Tue, 23 Mar 2004 16:19:57 -0000 Subject: Python for large projects References: <7xisgxt51r.fsf@ruckus.brouhaha.com> <105uk4987h7tm77@corp.supernews.com> <7xad28313c.fsf@ruckus.brouhaha.com> Message-ID: <1060otdm07s0678@corp.supernews.com> In article <7xad28313c.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: . . . >I keep hearing this, but I don't see any large (much less very large) >applications that have been done in Python; Zope is medium sized. > >Suppose you wanted to write any of the following: > >1) Optimizing C/C++ compiler, like GCC >2) Full featured web browser, like MSIE or Mozilla >3) Full featured office suite, like MS Office or Open Office or KDE >4) Avionics for the space shuttle >5) Internals of a large telephone/data switch >6) Tax processing software for the IRS >7) Operating system kernel (Linux: the next generation) >8) Accounting software for a big bank >9) Full featured database like Oracle or Postgres >10) ... well you get the idea. > >Which, if any, would you write in Python? By "write in Python" I mean . . . I'd DEFINITELY feel comfortable with 1). Do you think of GCC as "big", in that sense? I don't; maybe there's some- thing I'm missing, even though I've maintained other compilers on and off for a couple of decades. For 5) I'm infatuated with Erlang, of course. I'd probably change careers rather than work with 2) or 3). 9)'s another area where I have deep experience, and, no, I can't get my thoughts past C or assembler there. That might be personal habituation. Anyway, who *has* "gone big"? Easy answers: Industrial Light & Magic, Rackspace, Walt Disney Feature Animation, ... and, arguably one of the ten biggest "applications" on the planet: Google! -- Cameron Laird Business: http://www.Phaseit.net From llothar at web.de Tue Mar 23 21:53:54 2004 From: llothar at web.de (Lothar Scholz) Date: 23 Mar 2004 18:53:54 -0800 Subject: fox 1.2.x and FXPy References: <4e1cc86c.0403151008.669e2e45@posting.google.com> Message-ID: <6ee58e07.0403231853.16e1f88a@posting.google.com> David Bolen wrote in message news:... > Of course, you could rebuild the DLL removing support for the various > stuff you don't currently need, but that's not too convenient for > maintaining over time, and not everyone has the facilities for > rebuilding the wxPython DLL from wxWidgets source. > > I seem to recall reading that 2.5.x might contain (or support) > fracturing the main monolithic DLL into well-defined smaller pieces > that hopefully will improve this. I'm not sure. Is this a wxPython problem or does a C++ wxWidget also loads so slow ? If it is the former i would think that it comes from a naive coding style that forces all bindings done at startup and not when first used. And i guess if someone would change this, it the wxPython team is happy to include this fix. From tjreedy at udel.edu Tue Mar 2 10:29:53 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 2 Mar 2004 10:29:53 -0500 Subject: Feature request: subclassing FunctionType [Was: Some languageproposals] References: <95aa1afa.0402262158.5b33de79@posting.google.com><95aa1afa.0403010014.4222ce8e@posting.google.com> <95aa1afa.0403012224.506dd07c@posting.google.com> Message-ID: "Michele Simionato" wrote in message news:95aa1afa.0403012224.506dd07c at posting.google.com... > 1. Assuming all "for" loops and list comprehensions are replaced > with Haskell bindings rules, what about backward compatibility > problems? For instance: is there enough code relying on the loop > variable being available outside the loop? Guido has given things like the following as an intentional reason for the current rule (and for for...else): for item in seq: if acceptable(item): break else: item = None # item is now either the first acceptible item in seq or None If you do not like the iteration var remaining bound, you can explicitly delete it. If it is automatically deleted, constructions like the above are rendered more difficult. A list comp encapulates a specialized for loop whose specific job is to produce a list. It makes more sense to delete the binding automatically there since a) there is no way, when seq is empty, to force a binding to *something*, with else and b) the last item of the list is readily available anyway as result[-1]. Terry J. Reedy From jepler at unpythonic.net Mon Mar 15 18:39:18 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 15 Mar 2004 17:39:18 -0600 Subject: xreadlines() being used with file.tell() and file.seek() In-Reply-To: References: Message-ID: <20040315233918.GA13552@unpythonic.net> xreadlines() internally does something like this [using the Python 2.3 generator function syntax]: def xreadlines(f): while 1: chunk = f.readlines(sizehint) if not chunk: break for line in chunk: yield line Unless you happen to seek() just as xreadlines is between chunks, the result of the seek won't be seen until later, when the next chunk is read. Your input file is far too small to notice this effect. Similarly, after you've started an xreadlines() on a file, the file will tell() you that it is after the end of all the lines in chunk. xreadlines is supposed to be fast, and it really doesn't care what other file-like object assumptions it invalidates to get that result. Jeff From newsgroups at jhrothjr.com Wed Mar 31 08:15:53 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Wed, 31 Mar 2004 08:15:53 -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> Message-ID: <106lh64rda8t9d4@news.supernews.com> "Didier Morandi" wrote in message news:c4e6jv$10te$1 at biggoron.nerim.net... > > What against-top-posting people do not WANT to understand is that the very first > interest of posting is, to me, to get help or information. > > So, you post your question and, by definition, you remember what it was (well, I > hope so). > > Then, you go back to the ng the day after and if you got an answer, you are > interested in the answer, not to reread your post. That's a very good point. One of the forums I read is Baen's Bar (Baen Publishing) where the publisher has an ironclad rule that responses to him *must* be top posted. He is absolutely not going to hit the page down button to see whether there was anything interesting in the response. If he doesn't see it where his eyes are pointing, it might as well not exist. I suspect it's the only way he gets through his mail to get anything done. AFAIC, it doesn't matter whether you put your response at the top or bottom; what matters to me is whether I can find what you're talking about quickly. That means ruthless pruning of the post so that old stuff gets deleted. John Roth From fredrik at pythonware.com Sun Mar 14 06:41:05 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 14 Mar 2004 12:41:05 +0100 Subject: Tkinter3000 References: <89WdnQhnm6Gkwdfd4p2dnA@adelphia.com> Message-ID: "Robert" wrote: > Is the WCK still an active project? yes. wck 1.0 for tkinter was released in december 2003, and should be considered as a stable release. > Also, at one point there was going to be an O'Reilly book on > Tkinter, did that die? yes. From kbk at shore.net Sat Mar 20 17:00:00 2004 From: kbk at shore.net (Kurt B. Kaiser) Date: Sat, 20 Mar 2004 22:00:00 GMT Subject: Idle won't start - Update References: <8eh830tlh056hk21hm9v49m3qcinjv4pq9@4ax.com> <0cq930hneq0bni65g6viroa86l5lj6ogt0@4ax.com> Message-ID: <87y8pvrxgg.fsf@hydra.localdomain> David MacQuigg writes: > With the Task Manager, I see about 8 pythonw.exe processes running!! > I killed them all. Now things seem back to normal. That's the right thing to do. > > The only thing I can think of that has been unusual in the last few >days is that I have been running IDLE simultaneously with Python from >the command line, This should not be a problem. I do it all the time. >and doing some testing in both windows of computations involving >illegal floating-point numbers ( inf and nan ). This does not cause >a crash, or anything beyond the usual traceback in python. > > I noticed that when I start Python from a command line, I get one > process (python.exe) in the Task Manager. When I start Python using > IDLE, I get two processes (both named pythonw.exe). Often you get three. The GUI, the subprocess mainthread, and the subprocess socket_thread. On Unix, you get two. > I tried starting and closing multiple copies of IDLE. Now this you don't want to do. Right now IDLE uses one port to communicate with the subprocess and only one instance of IDLE with subprocess is allowed. In the future IDLE will be enhanced to allow multiple instances with subprocess. You can run as many IDLE instances with the -n switch as you like in parallel with the single instance of IDLE with subprocess. >This seems to leave some zombie 'pythonw.exe' processes still alive. Yes, they are trying to connect to the GUI. If you write code which causes the subprocess to block, e.g. sleep(999) and then restart the shell, you will see a zombie left behind. In 999 seconds it should disappear. But it is possible to write code which blocks forever. On Unix, a restart also sends a SIGKILL to the subprocess, which takes care of the zombies, but that isn't available on Windows. >Another strange phenomenon - I always get two more 'pythonw.exe' >processes with each start of IDLE, but sometimes I get an extra >window, and sometimes not. Closing the extra windows leaves one more >'pythonw.exe' than when I started, so they do accumulate. A couple of months ago improvements were made to the robustness of the subprocess communication. If you can use the current CVS, you may get better results and I'd be interested in hearing about any further problems. I'm away for a bit, so I can't follow up immediately. -- KBK From hungjunglu at yahoo.com Mon Mar 15 19:15:00 2004 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 15 Mar 2004 16:15:00 -0800 Subject: Deprecating reload() ??? References: <6kk6501shlve52ds2rjdopa73jhpchprg3@4ax.com> Message-ID: <8ef9bea6.0403151615.df97eb9@posting.google.com> David MacQuigg wrote in message news:... > On Mon, 15 Mar 2004 11:33:04 -0600, Jeff Epler > wrote: > > >The only problem I can see with reload() is that it doesn't do what you > >want. But on the other hand, what reload() does is perfectly well > >defined, and at least the avenues I've seen explored for "enhancing" it > >look, well, like train wreck. > > It's worse than just a misunderstanding. It's a serious limitation on > what we can do with editing a running program. As I said in another message, you CAN do the kinds of things you want to do (edit-and-continue), if you use weakrefs, and use classes instead of modules. Take a look at the weakref module. I am not saying that it's trivial in Python: it does require a bit of work, but edit-and-continue in Python is definitely doable. I've done it, many other people have done it. (Of course, if you asked whether the Ruby behavior is better, I'd think so. I think it's better to automatically replace class behavior on reload, by default, and leave open the possibility of explicitly refusing replacement. Python is the opposite: by default the class behavior does NOT get modified, and you have to do somework to replace it.) I think it is an historical accident in Python that modules are not made more class-like. Another thing I have seen people wishing having is getter/setter accessor methods (or properties) for module-level attributes. It usually is a better practice in Python to store attributes in classes rather than modules, exactly because down the future you'd often start to wish having class-like behaviors for your modules. regards, Hung Jung From ark at acm.org Wed Mar 17 17:01:55 2004 From: ark at acm.org (Andrew Koenig) Date: Wed, 17 Mar 2004 22:01:55 GMT Subject: Result of ``a is b'' References: <40200384.0403151632.35496ee6@posting.google.com><40200384.0403161255.7fca7a8c@posting.google.com><40200384.0403170530.57b6bba4@posting.google.com> Message-ID: "Terry Reedy" wrote in message news:mailman.97.1079541755.742.python-list at python.org... > Deducing details of the implementation *is*, for people with a certain > curiosity, a legitimate usage, in spite of your distain for such. > Explaining the bahavior of > > a=[1] > b=a > a[0]=2 > print b > > is another use for 'is'. Lists are mutable, so there's no proposal to change the behavior of "is" in this context. From python at rcn.com Sun Mar 21 15:10:32 2004 From: python at rcn.com (Raymond Hettinger) Date: 21 Mar 2004 12:10:32 -0800 Subject: mutable list iterators - a proposal References: <5d83790c.0403170242.759ac8d9@posting.google.com> Message-ID: <5d83790c.0403211210.703991c2@posting.google.com> > > Also, I'm not sure your proposal is self-consistent. If I read it > > correctly, there is a strong notion of having the iterator remember > > the last item emitted even if its position changes. However, with a > > combination of slice deletion and insertion, the notion of the last > > item emitted becomes muddy: > > > > lyst = range(10) > > it = iter(lyst) > > for i in xrange(5): > > it.next() > > lyst[3:7] = [20] > > print it.next() # Should this print 20 or 7 ? > > In this case my class returns a 20. My thinking on this was that if a > slice containing the "normal" next item is replaced by a slice, When designing a new type, the trick is to avoid areas where two different people could reasonably expect different "normal" behaviors. Otherwise, you're doing more harm than good and making it likely that your users will stumble into a class of bugs that are extremely difficult to hunt down. They are truly much better off with the paradigm of looping through one list and building another. In-place alteration is as icebergs are to the Titanic. Only the simplest cases are reasonable (changing values but not size; or reverse iterating and popping away items after the current position). > > Py2.4 adds a new type, collections.deque(), that can reasonably be > > made to do what your asking (workable because there is no slicing, > > just appending or popping from either end and setitem value > > mutations): . . . > This looks great. It would indeed work for the class I had in mind. > Frankly, the fact that the iterator for deque works *correctly* seems > to beg the question, "why doesn't the iterator for list work > correctly?" What makes lists different is that slicing operations can alter them in the middle. The inconsistencies disappear at the end points. Deques only mutate at the ends, so you always have a clear definition of "what's next". > There follows a revision of the > code I posted originally, which attempts to demonstrate that. The code is an improvement, but still suffers from the definitional ambiguity mentioned above. I believe this is inescapable. Consider a line at movie, you leave the line, others join in the middle, others leave, a few more join, a few more leave, now who is the person who "naturally" comes after you. 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. > import itertools Hey, hey, I love to see people using my module ;-) > class muterable_list(list): > """just like a list except it iterates gracefully under > mutation""" There is one word in the docstring that is debatable. Any guesses ;-) Raymond Hettinger From ngps at netmemetic.com Tue Mar 23 20:29:35 2004 From: ngps at netmemetic.com (Ng Pheng Siong) Date: 24 Mar 2004 01:29:35 GMT Subject: pyOpenSSL is dead or not? References: <405fe1b6$0$298$636a15ce@news.free.fr> Message-ID: According to Roger Binns : > M2Crypto does work on Windows, Linux and Mac. Developed on FreeBSD. ;-) > I did however have > to spend almost a week to get things working well, mainly because > M2Crypto is geared to work on Python 1.5 and up, Just showing its age, is all. I use Zope 2.6 with Python 2.1. When I move to Zope 2.7 on Python 2.3 I'll forget about Python 2.1. Any new stuff I write (ha!) I'll use the most recent Python. Cheers. -- Ng Pheng Siong http://firewall.rulemaker.net -+- Firewall Change Management & Version Control http://sandbox.rulemaker.net/ngps -+- Open Source Python Crypto & SSL From jgrahn-nntq at algonet.se Fri Mar 12 12:30:37 2004 From: jgrahn-nntq at algonet.se (Jorgen Grahn) Date: Fri, 12 Mar 2004 17:30:37 +0000 (UTC) Subject: root password in a .py script References: Message-ID: On Fri, 12 Mar 2004 12:11:30 -0500, Bart Nessux wrote: > I have to place a root password into a Python script. Is there a way to > encode it so that one can't read the password when viewing the file, but > when the sting is used it's decoded? For example: The only remotely secure way is to do what Unix does in /etc/passwd (to name a well-documented example). As far as I can see. /Jorgen -- // Jorgen Grahn Would You Let One Marry Your Sister?'' From tjreedy at udel.edu Fri Mar 19 13:07:29 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 19 Mar 2004 13:07:29 -0500 Subject: lambda trouble References: Message-ID: "Darabos Daniel" wrote in message news:Pine.GSO.4.58L0.0403191736410.14978 at balu... > Hi! > > I was doing something like this: > > >>> def p( x ): > ... print x > ... > >>> l = [] > >>> for i in range( 5 ): > ... l.append( lambda: p( i ) ) > ... > >>> for k in l: > ... k() > ... > 4 > 4 > 4 > 4 > 4 > > And it surprised me a little. I was expecting to see 0, 1, 2, 3, 4. If you had written for i in range(5): def f(): return p(i) l.append(f) would you have still been surprised? Or given that f is constant, how about the exactly equivalent def f(): return p(i) for i in range(5): l.append(f) or even the equivalent def f(): return p(j) for i in range(5): l.append(f) j=i def p(z): print z > After some brainwork I now kind of understand what happens and I even > found a solution like this: > > >>> def mylambda( fn, *args ): > ... return lambda: apply( fn, args ) > ... > >>> l = [] > >>> for i in range( 5 ): > ... l.append( mylambda( p, i ) ) > ... > >>> for k in l: > ... k() > ... > 0 > 1 > 2 > 3 > 4 > > But I still feel a bit unsatisfied. Do you have some advice for me? Remember that 1) 'lambda args: expr' basically abbreviates 'def f(args): return expr'; and 2) function code bodies only execute when the function is called, and in particular, do not dereference or access globals until called. While a function is being constructed, it is irrelevant that a global even exist, let along that it be in use as a loop var. Terry J. Reedy From kirk at strauser.com Fri Mar 12 15:10:08 2004 From: kirk at strauser.com (Kirk Strauser) Date: Fri, 12 Mar 2004 20:10:08 GMT Subject: root password in a .py script References: <87y8q5g8sg.fsf@strauser.com> Message-ID: <87r7vxg755.fsf@strauser.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 At 2004-03-12T19:46:53Z, Bart Nessux writes: > 1. To administer the machine. To my knowledge, there is absolutely nothing that can be done by root that cannot be done via an appropriately-configured sudo. I administer a raft of servers and literally *never* type the root password unless I'm logging in at a console in single-user mode. > 2. All they have to do is click a check-box to disable ssh in OSX. Gotcha. Wouldn't something along the lines of "don't do this, or else we won't be able to help you when you need it, and it just makes more work for everyone involved" go a long way? > 3. I didn't know about chpass. I mentioned it above already, but to re-iterate: you really need to read up on 'sudo' as well. It's the solution you're looking for. > 4. We're informal. Admins are noramlly only called when the user has > *really* messed something up. We put out their fires. When we try to stop > them from creating fires, we become over-bearing and > controlling... classic admin/user relationship. Understood. - -- Kirk Strauser The Strauser Group Open. Solutions. Simple. http://www.strausergroup.com/ -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.4 (GNU/Linux) iD8DBQFAUhja5sRg+Y0CpvERAkI1AKCSLg6GknHxlxBOzgjv66eX0xA2wQCfQkgN D5vAlAoxNeiVgWxsNJ+xLxI= =jCOf -----END PGP SIGNATURE----- From gnupeaker at yahoo.com Thu Mar 25 05:20:34 2004 From: gnupeaker at yahoo.com (Eyal Lotem) Date: Thu, 25 Mar 2004 02:20:34 -0800 (PST) Subject: Split a string by length In-Reply-To: Message-ID: <20040325102034.61803.qmail@web61110.mail.yahoo.com> I am not sure this is the best method, but a very useful function I've been using is: def divide(seq, size): return [seq[i:i+size] for i in xrange(0, len(seq), size)] >>> divide('aabbcc', 2) ['aa', 'bb', 'cc'] (Works on non-strings too) I put it in a common library and I reuse it all the time. I'd love to see it in the standard library, but until then.. :) --- Pascal wrote: > Hello, > How can I do to simulate this way: > 'aabbcc'.split(2) -> ['aa', 'bb', 'cc'] > I tried with a 'slice' but this didn't run: > [item for item in 'aabbcc'[::2]] -> ['a', 'b', 'c'] > Thanks. __________________________________ Do you Yahoo!? Yahoo! Finance Tax Center - File online. File on time. http://taxes.yahoo.com/filing.html From bad_addy at no_domain.com Thu Mar 25 18:59:12 2004 From: bad_addy at no_domain.com (Tina) Date: Thu, 25 Mar 2004 23:59:12 GMT Subject: Inheriting Classes Across Files References: <1066rp8nj7al3e1@news.supernews.com> Message-ID: I tried that as I understand it. I'm sure I'm making a silly error in all this. Here is a simple example of what I'm trying: --- (File super_class.py) --- class base_class: def sample(): return "Returned!" --- (File sub_class.py) --- import super_class class derived_class(base_class): def sample2(): return "Returned Twice!" --- (End) --- Traceback (most recent call last): File "/home/tina/python/test/sub_class.py", line 3, in -toplevel- class derived_class(base_class): NameError: name 'base_class' is not defined John Roth wrote: > > "Tina" wrote in message > news:E6K8c.748$Dv2.185 at newsread2.news.pas.earthlink.net... >> In my program I need derived classes to inherit from the super class. >> >> I can do this but I'd like to split the super class into it's own file. >> >> How do you do this? When I split the code I start getting errors. > > The module with the superclass has to be imported before > the subclass is defined. > > Be very careful you don't get into an import loop. > That way lies madness. > > John Roth >> From jacek.generowicz at cern.ch Mon Mar 22 05:14:29 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 22 Mar 2004 11:14:29 +0100 Subject: In what python release was this introduced.. References: <74dd441a.0403220126.12ec063f@posting.google.com> Message-ID: htgk at mail.com (Moe A) writes: > Hi, > > i need to list dependencies for my package & was wondering in what > python release could you start making 'in ' calls with more > than one char..eg: > > "JESUS" in bible > > instead of > > "J" in bible Python 2.2.2 (#1, Feb 8 2003, 12:11:31) [GCC 3.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> 'def' in 'abcdefghij' Traceback (most recent call last): File "", line 1, in ? TypeError: 'in ' requires character as left operand >>> Python 2.3.3 (#1, Jan 16 2004, 15:07:34) [GCC 3.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> 'def' in 'abcdefghij' True >>> From idbaxter at semdesigns.com Sat Mar 6 10:04:38 2004 From: idbaxter at semdesigns.com (Ira Baxter) Date: Sat, 6 Mar 2004 09:04:38 -0600 Subject: Ast tree and python code References: Message-ID: <4049e7e6$9@giga.realtime.net> "Yermat" wrote in message news:c25e3r$2052$1 at biggoron.nerim.net... > Does someone know how I can reverse an AST tree back into python code > with few modification ? > What I want to do is to complete trees before writing them back but in a > way not to far from the original code ? Especially, indentation, line > return, etc. > > Of course, I could program it myself but if someone already done it... If you insist on doing this in Python, I don't have any help. Otherwise, if you want to carry out arbitrary transforms on Python code, you might be interested in the DMS Software Reengineering Toolkit. It parses many languages (including Python) into a language specific AST, can carry out source-to-source transformations on those trees, and can then prettyprint source text from those tree. It retains comments, indentation, the format of numbers, you name it. See http://www.semanticdesigns.com/Products/DMS/DMSToolkit.html. -- Ira D. Baxter, Ph.D., CTO 512-250-1018 Semantic Designs, Inc. www.semdesigns.com ----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==---- http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups ---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =--- From peter at semantico.com Thu Mar 11 09:50:57 2004 From: peter at semantico.com (Peter Hickman) Date: Thu, 11 Mar 2004 14:50:57 +0000 Subject: Extending Python Syntax with @ In-Reply-To: References: Message-ID: <40507cd4$0$15845$afc38c87@news.easynet.co.uk> David MacQuigg wrote: > If you believe as I do that Python is not yet the ultimate language, > and some syntactical changes are still to come, then it seems like > using a very distinct symbol like @ may have some merits. If what motivates you is the 'ultimate language' and think you can get closer to it by adding special characters then you are going to be very disappointed. The history of computing is littered with 'ultimate languages' that have had much more thought put into them than adding special characters to an existing language (C++ comes to mind) and they all have in common the fact that they failed. To be fair C++ was never touted as an 'ultimate language' but you get the picture. If you feel python has a significant flaw then say what it is and how you believe it would best be addressed. Using @ as a special character is just adding sugar to the syntax. Maybe what we need is a language that has only a grammer and the syntax / vocabulary comes from the objects. Or is that AppleScript? From mpyle at legato.com Wed Mar 31 17:13:43 2004 From: mpyle at legato.com (Michael Pyle) Date: Wed, 31 Mar 2004 14:13:43 -0800 Subject: Prothon Prototypes vs Python Classes Message-ID: <96F3EC4BDF504540BB9715CBE9DACB8B09B028B8@pa-mail1.legato.com> > 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. > > So....when I ask the object returned from Foo() what its type is, what do I get? Or is this something that doesn't really have much meaning in a prototype based language? --mike -------------- next part -------------- An HTML attachment was scrubbed... URL: From mogmios at mlug.missouri.edu Wed Mar 31 06:44:27 2004 From: mogmios at mlug.missouri.edu (Michael) Date: Wed, 31 Mar 2004 03:44:27 -0800 Subject: python & mysql probelm In-Reply-To: References: Message-ID: <406AAF1B.6010205@mlug.missouri.edu> > But why not use a genuine parametrized query: > > cursor.execute("select * from projects where projectid " > "between %s and %s", (id1, id2)) > > Especially if you need to execute the same query several times with > changing parameters this is faster as far as I know, because the query > is prepared once. Really? I have wondered what the difference was. Is there any other difference in doing it this way rather than with string substitution? From fperez528 at yahoo.com Mon Mar 8 17:46:28 2004 From: fperez528 at yahoo.com (Fernando Perez) Date: Mon, 08 Mar 2004 15:46:28 -0700 Subject: os.popen() failing under ipython+cygwin, I'm stumped. References: <404CA5D1.6080706@zoran.com> Message-ID: Miki Tebeka wrote: > I've installed IPython 0.5.0 with `python setup.py install' > then: [snip] I hope you also end up using/enjoying it :) > Maybe upgrade your cygwin? My dll version is 1.5.7-1 > (run `cygcheck -s | egrep "^cygwin"' to find your version) > > HTH. > Miki Many thanks, I passed your message along to the user with the problem. However, even if this fixes it, the difference in behavior between ipython and python troubles me. I'd like to understand why they do different things in this case. Best regards, and thanks again for taking the time to set things up for a test. Fernando From joe at notcharles.ca Thu Mar 25 14:46:45 2004 From: joe at notcharles.ca (Joe Mason) Date: Thu, 25 Mar 2004 19:46:45 GMT Subject: Make 'def' and 'class' usable within expressions References: <4062EF99.1050802@zope.com> <4062F88C.40200@zope.com> Message-ID: In article , Thomas Heller wrote: > BTW, how would you specify base classes for ICustomer? > > ICustomer = Interface(class, IBaseInterface): > def get_id(): > """Return the customer ID""" Oh, right, that points up another inconsistency in the syntax I wanted to point out: it really should be ICustomer = Interface(class: def get_id(): """Return the customer ID""" pass ) Otherwise, how do we pass multiple to the function? PairOfClasses = Interfaces(class: pass, class: pass) The PEP318 decorators doesn't support this, of course, but it doesn't pretend to. This syntax looks like just a regular function call which should allow multiple parameters, though. You could say that only the last parameter of a function call can be a def or class expression, which then gets bound to the next definiton found. But what about if (class): That's an expression too. Does the : bind to the embedded class or the if? Can of worms. In a C-delimeted language, embedding a large {...} sequence inside a function call would be awkward, but not deadly. Here, I think Python's delimiting has defeated you. Joe From whisper at oz.net Thu Mar 4 20:09:13 2004 From: whisper at oz.net (David LeBlanc) Date: Thu, 4 Mar 2004 17:09:13 -0800 Subject: Parsing xml file using python In-Reply-To: <14b36d18.0403041649.252d2e7c@posting.google.com> Message-ID: > Hello, all, > > I am new to Python. > > I need to read an XML document and ignore all XML tags and write only > those between the tags to a text file. In other words, if I have an > XML document like so: > > This > is > a > test > > I need to write "This is a test" to a text file. How do I achieve > this? Thanks. PyXML would be a perfect solution - and easy too. Dave LeBlanc Seattle, WA USA From hugh-m at moving-picture.com Tue Mar 30 11:37:54 2004 From: hugh-m at moving-picture.com (Hugh Macdonald) Date: Tue, 30 Mar 2004 17:37:54 +0100 Subject: GUI Frameworks in Python? In-Reply-To: References: <8089854e.0403300518.3a180414@posting.google.com> Message-ID: <20040330173754.7624261d.hugh-m@moving-picture.com> On Tue, 30 Mar 2004 20:21:58 +0200 Riccardo Attilio Galli wrote: > >> > GTK: Unknown - I'm looking into it today > >> > > >> > >> Is this Linux only ? > >> (pardon my terrible ignorance...) > > > > Yeah - it is... I'n only developing for Linux here... > > It's false. > I'm developping a gtk program which run in both linux and windows. Sorry - when I answered the original question I thought he was asking if I was developing for Linux only... looking back, I have no idea why I got that idea.... -- Hugh Macdonald The Moving Picture Company From JimJJewett at yahoo.com Tue Mar 23 14:39:05 2004 From: JimJJewett at yahoo.com (Jim Jewett) Date: 23 Mar 2004 11:39:05 -0800 Subject: PEP318 alternate syntax idea References: Message-ID: Stephen Horne wrote in message news:... > ... if decorators really catch on, there could be cases where > they are applied repeatedly to many functions, and > possibly with many decorators. > ... [Could we move the redundant lists to a single preamble] > how about... > def [staticmethod, ...] : > # could use alternate keyword such as 'decorate' > def a (a1, a2) : > "this function is decorated" > ... > def b (b1, b2) : > "this function is also decorated" > ... > def c (c1, c2) : > "this function is _not_ decorated" > ... This was soundly rejected. I liked the idea myself, until Phillip Eby explained what I was missing. In python, block_starter: indented_code1 indented_code2 implies something about the how the *indented* code will be run. It may get skipped (if/else), repeated (for/while) or delayed (class, def), but it will definately do something strange. With decorators, the function definition itself is normal (and therefore should not be indented); it is the decorators that run at an unexpected time. using: decorator1 decorator2 decorator3 def a (args): pass may still be an option, but it doesn't answer your request for a *single* preamble. I agree that creating a lambda *just* to bundle the decorators is ugly, but if you really have a large number of decorators that always go together ... maybe there is a good name for the collection. -jJ From a-steinhoff at web.de Tue Mar 16 15:47:48 2004 From: a-steinhoff at web.de (Armin Steinhoff) Date: 16 Mar 2004 12:47:48 -0800 Subject: Swig-Python problems References: Message-ID: m.finardi at itia.cnr.it (matteo) wrote in message news:... > Hi, I've got a problem with SWIG and Python2.2.I've installed the > SWIG1.3.21 releaseunder QNX6.2 platform .I tried to make the exemple > example.c (in the directory ../Swig/Exemple/python/simple) > /* File : example.c */ > > #include > double My_variable = 3.0; > > int fact(int n) { > if (n <= 1) return 1; > else return n*fact(n-1); > } > > int my_mod(int x, int y) { > return (x%y); > } > > char *get_time() > { > time_t ltime; > time(<ime); > return ctime(<ime); > }. > After the commans: > > swig -python example.i > gcc -c example.c example_wrap.c -I/usr/local/python2.2 At first ... please use qcc and not gcc. qcc -c -fPIC example.c example_wrap.c -I/usr/local/python2.2 should work ... > ld -shared example.o example_wrap.o -o _example.so > > I use Python module as follows > > >>> import example > > and I've got the message: "Memory falut (core dumped)" > What can I do?? ... use Pyrex :) Armin Steinhoff From dont_reply_here at somewhere.net Thu Mar 4 15:47:07 2004 From: dont_reply_here at somewhere.net (John Clayton) Date: Thu, 4 Mar 2004 20:47:07 +0000 Subject: Howl & ZeroConf References: <2004030419430275249%thisaddresswontwork@nowherenet> Message-ID: <2004030420470763887%dontreplyhere@somewherenet> On 2004-03-04 19:49:47 +0000, Skip Montanaro said: > > John> Has there been any discussion / planning of integrating howl as an > John> external module into Python? > > Not that I'm aware of. What's howl? > > Skip It's a cross platform impl of zeroconf (aka Rendezvous in Apple parlance) From jcarlson at nospam.uci.edu Fri Mar 19 03:34:05 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Fri, 19 Mar 2004 00:34:05 -0800 Subject: Extending Python Syntax with @ In-Reply-To: <0001HW.BC7FDC4D003B1D7CF0284600@netnews.comcast.net> References: <104v3lrijtse657@news.supernews.com> <104v8flf6f1bp95@news.supernews.com> <0001HW.BC7FDC4D003B1D7CF0284600@netnews.comcast.net> Message-ID: >>Personally, I find most standard IDEs to be bloated pieces of shit. >>When did it become reasonable to need 100+ megs to edit source code? > > Not all IDEs are this large. For instance, Apple's Project Builder > (version 2.1) is 2.6 MB, while the Mac version of CodeWarrior Pro 8 is > 9.9 MB. These sizes are just the executables, and don't include > compilers, linkers, libraries, headers, documentation and examples. But > you would need all these things for a command line based development > environment. I never said /all/, I said /most/. In the same vein as your reply, a standard Python install is somewhere around 30 megs and includes Idle (not quite an IDE, but it gets the job done). DJGPP (a c/c++ compiler for dos) is also around 30 megs installed, and includes an IDE, compiler, linker, libaries, headers, etc. However, if we were to take a look at some standard tools that current university students and even a measurable portion of industry professionals use; Eclipse, MS Visual Studio, and others, you'll note the tendency of bloat. - Josiah From jacek.generowicz at cern.ch Fri Mar 12 11:02:47 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 12 Mar 2004 17:02:47 +0100 Subject: Static Typing in Python References: <33bd6435fb366a01954fafca8a8f34e3@news.teranews.com> Message-ID: Dang Griffith writes: > On 12 Mar 2004 13:56:53 +0100, Jacek Generowicz > wrote: > >Just what do you understand "static typing" to mean ? > Doesn't that usually mean typing with a high noise-to-signal ratio? What, you mean like this: std::list > l; l.push_back(std::pair(1,"hello")); as opposed to l = [(1, 'hello')] ? I like your definition :-) From roy at panix.com Sat Mar 27 07:57:05 2004 From: roy at panix.com (Roy Smith) Date: Sat, 27 Mar 2004 07:57:05 -0500 Subject: A 'Python like' language References: <40645d8f$0$10775$afc38c87@news.easynet.co.uk> Message-ID: "Jon Franz" wrote: > What I found interesting was: > - the stackless-ness What does stacklessness do for me as an application programmer? From premshree_python at yahoo.co.in Sat Mar 13 02:07:50 2004 From: premshree_python at yahoo.co.in (=?iso-8859-1?q?Premshree=20Pillai?=) Date: Sat, 13 Mar 2004 07:07:50 +0000 (GMT) Subject: Static Typing in Python In-Reply-To: Message-ID: <20040313070750.53383.qmail@web8309.mail.in.yahoo.com> --- Jacek Generowicz wrote: > Jacek Generowicz writes: > > > Peter Maas writes: > > > > > Premshree Pillai schrieb: > > > > How do I force static typing in Python? > > > > > > You have to enforce it by code instead of > declaration, i.e. you > > > have to do runtime type checking. > > > > Just what do you understand "static typing" to > mean ? > > I ask because I am prepared to accept that you have > a different > working definition of "static typing" from mine, but > people who > actually want static typing typically want it > because they think it > gives them the following advantages: > > a) type errors caught at compile time, > > b) faster program exectution. > > The code you showed: > > > > class doesTypeChecking: > > > def __init__(self): > > > self.__dict__["aString"] = "" > > > self.__dict__["aFloat"] = 0.0 > > > > > > def __setattr__(self, attr, value): > > > if type(self.__dict__[attr]) != > type(value): > > > raise ValueError, "Type mismatch > for attribute %s\n" % attr > > will catch no type errors at compile time, and will > slow down > execution, so I suspect that Premshree will be > disapponinted with it. > > > (BTW, my definition of "static typing" is "type > checking is done at > compile time" ... your example really looks like > dynamic typing to > me ... albeit with some restrictions on attribute > types.) > > > Premshree: Python is dynamically typed. There is no > way to enforce > static typing. There is something called > "pychecker" which > might be of some help to you. Why do you > think that you > want static typing in Python ? > -- > http://mail.python.org/mailman/listinfo/python-list Yes, I am aware that Python is dynamically typed, and so is Perl, right? In Perl, we have the "use strict vars" pragma to force variable declaration. Is there something like it in Python? Don't you think forced variable declaration is an important requirement in a language? ===== -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 ivoras at __geri.cc.fer.hr Wed Mar 3 04:50:56 2004 From: ivoras at __geri.cc.fer.hr (Ivan Voras) Date: Wed, 03 Mar 2004 10:50:56 +0100 Subject: Impersonation In-Reply-To: References: Message-ID: Vedran Furac wrote: > ..and this runs the program but not as a target user. Program is started just > normal as it would be without impersonation. Any idea why? IIRC, the 'current' user has to be an administrator or have some special security privileges (backup operator?) to be allowed to impersonate other users. From dmq at gain.com Fri Mar 26 13:43:54 2004 From: dmq at gain.com (David MacQuigg) Date: Fri, 26 Mar 2004 11:43:54 -0700 Subject: A 'Python like' language References: <40645d8f$0$10775$afc38c87@news.easynet.co.uk> Message-ID: On Fri, 26 Mar 2004 16:42:54 +0000, Peter Hickman wrote: >Well after all this discussion it would appear that a 'Python like' >language has appeared => Prothon. http://www.prothon.org/index.html > >Very alpha, sort of like Python (if you consider the indenting is what >makes Python unique) and sort of Ruby in its use of prefixes to define >scoping etc (although there is no reference to this trait being borrowed >from Ruby). It also quotes Self as being an influence. Very interesting ... Quoting from Prothon's home page: ''' Over time capabilities have been added to the core Python language, ... and Python has became loaded with features, some quite complex. ''' So all they need is an automatic translation from Python to Prothon, then they can grab all of Python's libraries, and bypass ten years of development. :>) We really need in Python a clear separation of advanced features from the basic syntax. No more lambda calculus in the basic part. :>) -- Dave From __peter__ at web.de Sat Mar 13 03:47:56 2004 From: __peter__ at web.de (Peter Otten) Date: Sat, 13 Mar 2004 09:47:56 +0100 Subject: Performance penalty for using properties? References: Message-ID: Kenneth McDonald wrote: > Now that I'm back to Python and all the new (to me) cool features, > I find I'm using properties a lot, i.e. I'm defining: > > foo = property(fset=..., fget=...) > > for a number of properties, in many of my classes. I'm not using > them for anything performance critical yet, but could see myself > doing so in the future. Can anyone comment on the performance > costs associated with properties vs. simple attribute lookup? It seems I'm becoming obsessed with timeit.py :-) class Test(object): def getvalue(self): return self._value value = property(getvalue) t = Test() t._value = 123 $ timeit.py -s"from property import t" "t._value" 1000000 loops, best of 3: 0.207 usec per loop $ timeit.py -s"from property import t" "t.getvalue()" 1000000 loops, best of 3: 0.918 usec per loop $ timeit.py -s"from property import t" "t.value" 1000000 loops, best of 3: 1.03 usec per loop Roughly factor five, most of the time being consumed by the implied function call. Peter From andersjm at inbound.dk Wed Mar 24 16:50:40 2004 From: andersjm at inbound.dk (Anders J. Munch) Date: Wed, 24 Mar 2004 22:50:40 +0100 Subject: Voting (was Re: PEP 318 References: <95aa1afa.0403230250.4c9da7a2@posting.google.com> <1060m0593q1uo0d@news.supernews.com> Message-ID: <406203c0$0$208$edfadb0f@dread16.news.tele.dk> "John Roth" wrote: > "Michele Simionato" wrote: > > Ick! Having passed through PEP 308, I just prefer directly agree with > Guido's > > decision without any votation at all ;) > > Half of the 308 problem was because Guido wasn't willing to make a decision. > > The other half was the voting method used. The third half of the problem was the people got wound up about details in the voting system. Details that would have been relevant in a winner-takes-all vote, but were less than interesting in a BDFL-guidance-vote. - Anders From jcarlson at nospam.uci.edu Sat Mar 6 13:57:27 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Sat, 06 Mar 2004 10:57:27 -0800 Subject: Can python read up to where a certain pattern is matched? In-Reply-To: References: <20040306021634.77057.qmail@web13004.mail.yahoo.com> Message-ID: > Note that I've only lightly tested that code, and it's probably very > inefficient. It is all right except for the string addition. Each addition produces a new string. For a final string of length n, you will have created n strings, and had to write n*(n-1)/2 = O(n^2) bytes. Ick. For long sentences (more than 1000 characters, the timing difference becomes significant), the below is far faster: def sentences(iterable): sentence = [] for char in iterable: sentence.append(char) if char in ('.', '!', '?'): yield ''.join(sentence).strip() sentence = [] sentence = ''.join(sentence).strip() if sentence: yield sentence - Josiah From mark at prothon.org Mon Mar 29 17:32:39 2004 From: mark at prothon.org (Mark Hahn) Date: Mon, 29 Mar 2004 14:32:39 -0800 Subject: Prothon Prototypes vs Python Classes References: <106dukh7ncf9ad4@news.supernews.com> Message-ID: > I would guesstimate that the tab indentation mostly serves to > kill the interest of many who would otherwise take a deeper > look. Prothon has announced that we are caving in and going to spaces instead of tabs, even though both of the Prothon authors abhor spaces. "Ville Vainio" wrote in message news:du73c7r7tub.fsf at lehtori.cc.tut.fi... > >>>>> "Mark" == Mark Hahn writes: > > Mark> I certain that it IS possible to add ANYTHING to Python. My > Mark> whole motivation for Prothon was to start fresh with a clean > Mark> slate and have less. I'm still experimenting with things > Mark> that can be removed. > > I guess the issue is whether it would have been simpler to fork the > CPython interpreter, providing patches that enable the prototype-based > programming. It would have been quite a jump start, if feasible. > > Mark> Having said that, I think there are things about Prothon > Mark> that really kick ass. The combination of threaded > Mark> interpreter with extremely simple locking objects is > Mark> exceeding my expectations. This engine is really going to > Mark> shine when it matures. > > Sounds great. If you prove that it's the faster approach, perhaps > we'll be seeing something like that in CPython soon. > > FWIW, I would guesstimate that the tab indentation mostly serves to > kill the interest of many who would otherwise take a deeper > look. There are many (like me) who think that the approach is > fundamentally wrong. > > -- > Ville Vainio http://tinyurl.com/2prnb From dmq at gain.com Tue Mar 9 16:04:13 2004 From: dmq at gain.com (David MacQuigg) Date: Tue, 09 Mar 2004 14:04:13 -0700 Subject: "print" as function not statement References: Message-ID: On Sun, 07 Mar 2004 16:57:29 -0800, Paul Prescod wrote: >This is just a trial balloon. It isn't even in proper PEP format yet. >Don't take it too personally! > >Pre-pep for a show() built-in function. > > This pre-PEP describes a replacement for the Python print > statement. Obviously the replacement of such a popular > statement will take time and cause dislocation. It must > therefore be done very gradually and carefully. Nevertheless, > the print statement stands out in Python because of its > quirky syntax and semantics. This PEP proposes to migrate > the print statement towards standardized function syntax. At this point, my initial reaction was "no way". After reading the rest of the proposal, I say "yes". Your arguments are very convincing. >Problems with "print" > > New users are constantly asking how to print elements without > trailing whitespace. And the answer is easy, but not obvious to a beginner, and also something beginners tend to resist, as if having once been spoiled on a print statement without parens, it is now too much work to type printX( ... ) This to me, is the most powerful argument. > The use of a trailing comma to disable newline has no clear > relation to any other syntax elsewhere in Python. > > The cheveron syntax is similarly unique. Both good points. > "print" is the one of only two statement-generating keywords > that is not a flow-control or scope-control operator. Don't care. I have never thought about the underlying 'nature' of these statements, and I wouldn't fault a language for this. > Because print is a statement, it cannot be used in contexts > like list comprehensions and lambda functions. I've hit this snag. > The word "print" is very common in English usage and would be > very useful for method and function names. It is a (very) > long-term goal of this PEP to free it up for this purpose. Perhaps we could retain the deprecated form in a module to be accessed with from __the_past__ import print :>) [ snip ] >Proposed solution: "show" > > I propose a new built-in function called "show". It can take an > arbitrary number of positional arguments and three optional > keyword arguments: > > * separator - string to use to separate the string > displays of the objects that are written. Defaults > to a single space. > > * trailer - string that follows the string displays > of the objects that are written. Defaults to a > single newline. > > * to - a file object to write the strings to. Defaults > to sys.stdout. > > Some examples: > > show(5) > > show(5, to = sys.stderr) > > show(5, 6, separator = ",") > > show(5, 6, trailer = "\n\n") > > show("Five", 5, "Six", 6) > > show(show) This is clearly the right way to re-write an old function, extending the options, but preserving the old behavior as a default. I would like to do the same with some of the convenience functions in the os.path module (exists, isfile, isdir). Convenience is fine, but don't hide the primitives. >Possible Extensions > > Debug-useful return value > [ snip ] > x = show(j[x]).y(a[x]) This would be very handy. Go for it !! -- Dave From ciw42 at hotmail.com Tue Mar 2 19:17:34 2004 From: ciw42 at hotmail.com (ciw42) Date: 2 Mar 2004 16:17:34 -0800 Subject: Lua Book References: <2ae25c6b.0403020006.6b99e590@posting.google.com> <1048rn8lpr0acde@corp.supernews.com> <1049gqe9n762hf6@corp.supernews.com> Message-ID: <75a58466.0403021617.7f765581@posting.google.com> claird at lairds.com (Cameron Laird) wrote in message news:<1049gqe9n762hf6 at corp.supernews.com>... > In article , > Pete Shinners wrote: > >Cameron Laird wrote: > >> Incidentally, have you heard the news about Lua? Look at > >> . > > > >I have no experience with Lua, but some of the code examples from the book > >may frighten me away for good. > > > >http://www.inf.puc-rio.br/~roberto/book/code/allwords.lua.html > > > > > > > >I suppose Python's recent introduction of generators makes this rather trivial. > > > >def allwords(): > > for line in sys.stdin: > > for word in line.split(): > > yield word > > > >for word in allwords(): > > print word > > > > > > > > Provocative comparison; perhaps Roberto will even join in > and comment here. In any case, there's still a place for > Lua, and I think there's value in the discussion of Lua > that comp.lang.python has already hosted. Ordered a copy of the Lua book as the language seemed quite interesting and potentially useful. The full text was available on the 'net, but I like to read this sort of material whilst travelling. Although it starts out describing quite a nicely structured language (occasionally similar in concept to, but never as readable as Python) as the book proceeds, the more in-depth examples become harder to read (a lot more like Perl) and having finished the book I was left feeling that the core language offered nothing useful over Python, in fact it was rather lacking in many areas. Don't get me wrong, I know if I had a good enough reason I could quite quicky and reasonably happily start developing in Lua, but it's unlikely to ever come close to Python for general purpose coding. That said, it may well fit the bill for a new embedded low-spec PC-based device we'll be starting development on in a few months time. The Python runtime is just too big and this is one area where Lua wins out, so we'll just have to wait and see. From joe at notcharles.ca Sat Mar 27 22:45:32 2004 From: joe at notcharles.ca (Joe Mason) Date: Sun, 28 Mar 2004 03:45:32 GMT Subject: Newbie Class Questions References: <94CdnVqi7o8rn_vdRVn-vg@centurytel.net> Message-ID: In article <94CdnVqi7o8rn_vdRVn-vg at centurytel.net>, Ed Suominen wrote: > I think it would be cool for my "AutoText" class (see below, hereby GPL'd) > to be able to tell what subclasses inherit from it and instantiate objects > for all of those subclasses to implement a "AutoAll" function.. Any ideas? Check out http://www.phyast.pitt.edu/~micheles/python/meta1.html and http://www.phyast.pitt.edu/~micheles/python/meta2.html. It's advanced, but it'll do what you want. I just used your question as an example in the "Prothon Prototypes vs Python Classes" thread, including the actual metaclass that'll do what you want. Here it is again: autoall = [] def AutoAll(): l = [] for i in autoall: l.append(i()) return l class AutoRegister(type): def __init__(klass, name, bases, dict): autoall.append(klass) Then just add the line "__metaclass__ = AutoRegister" to your AutoText definition, and all its subclasses will automatically inherit it. > I have all of 3 days experience with OOP and Python, so please bear with me. Might be a little early for metaclasses, then... Joe From skip at pobox.com Wed Mar 3 09:23:22 2004 From: skip at pobox.com (Skip Montanaro) Date: Wed, 3 Mar 2004 08:23:22 -0600 Subject: E-mail account disabling warning. In-Reply-To: <95aa1afa.0403030526.728de57b@posting.google.com> References: <95aa1afa.0403030526.728de57b@posting.google.com> Message-ID: <16453.59994.314114.784746@montanaro.dyndns.org> Michele> I have got today a very similar message, but from my University provider. We got it here at Northwestern (same form, personalized for the Northwestern community). The central group that worries mightily about this stuff has sent out several alerts about it. Michele> Fortunately, I got suspicious when I was asked to run an Michele> executable and I asked to the University before. It is a very Michele> subtle virus! This is social engineering at its best (or worst, depending on your perspective). I suspect it has been very effective for the perpetrators. Skip From skip at pobox.com Thu Mar 4 14:49:47 2004 From: skip at pobox.com (Skip Montanaro) Date: Thu, 4 Mar 2004 13:49:47 -0600 Subject: Howl & ZeroConf In-Reply-To: <2004030419430275249%thisaddresswontwork@nowherenet> References: <2004030419430275249%thisaddresswontwork@nowherenet> Message-ID: <16455.34907.488510.740799@montanaro.dyndns.org> John> Has there been any discussion / planning of integrating howl as an John> external module into Python? Not that I'm aware of. What's howl? Skip From jepler at unpythonic.net Tue Mar 23 10:42:37 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Tue, 23 Mar 2004 09:42:37 -0600 Subject: how to "touch" a file In-Reply-To: References: Message-ID: <20040323154237.GF24314@unpythonic.net> I think that "touch -m" works like this function, by using stat to get the atime, then setting an identical atime and new mtime with utime. def set_mtime(fn, mtime=None): if mtime is None: mtime = time.time() atime = os.stat(fn).st_atime os.utime(fn, (atime, mtime)) Jeff From fgeiger at datec.at Thu Mar 4 02:04:09 2004 From: fgeiger at datec.at (F. GEIGER) Date: Thu, 4 Mar 2004 08:04:09 +0100 Subject: MVC-type Framework in Python References: Message-ID: I never felt comfortable with MVC. Since I read Holub's articles on JavaWorld, I know how to do it *much* better. And to implement the concepts shown there in Python is a breeze. HTH Franz GEIGER P.S.: Don't have the URLs handy right now. Tell me if you can't find the stuff. I'll then look for the URLs. "Andreas Pauley" schrieb im Newsbeitrag news:mailman.6.1078342287.736.python-list at python.org... > Hi, > > I'm interested in finding a nice way to develop applications that have > their business logic separated from the user interface (among other > things). This should enable easier maintenance, more flexibility and > (ideally) less development time for the app. > > I've recently read about the Model-View-Controller design framework > (originally used in SmallTalk applications, or so it seems). > What python-specific tools/frameworks would you recommend that can be used > to implement MVC, or something similar (or perhaps better) than MVC? > > I'm looking for something that can help build > interface-independent applications, with all logic in a central place. > There would typically be a GUI interface, character interface and > web-based interface, all accessing the same python logic. > The interfaces need not be python-specific. I would like, for example, to > have an existing PHP website access the same logic. > > Another thing that would be nice is centralized validation. > If you change your validation rules in one place, the interfaces get to > know that without you having to change code on the interface. > Is it feasible to have python extract validation rules from the database > (e.g. a varchar(20) field) and pass that through to a gui interface that > would limit the amount of characters entered to 20? If you then change the > database field to a varchar(30), the change should be > detected without having to change any other code. > > At the moment I'm just researching all of the different options for > designing/implementing applications (typically multi-user database-driven > apps), so I would appreciate any ideas. I assume some ideas have proven > themselves more feasible in production environments than others. > > Regards, > Andreas. > > From amy-g-art at cox.net Wed Mar 24 20:23:22 2004 From: amy-g-art at cox.net (Amy G) Date: Wed, 24 Mar 2004 17:23:22 -0800 Subject: Any way to get information from fun objects about their parameters? References: Message-ID: <6wq8c.41433$Bg.18366@fed1read03> "Amy G" wrote in message news:rqq8c.41431$Bg.29453 at fed1read03... > "Kenneth McDonald" wrote in message > news:slrnc64bcn.2qa.kmmcdonald at g4.gateway.2wire.net... > > For autodocumentation purposes, I'd like to be able to load a module > > and then find out the following information about functions and > > methods defined within it: > > > > 1) Parameter names and order > > 2) Default value, if any, associated with each parameter > > 3) If the *param or **param conventions are used in the > > parameter list. > > > I had thought of writing a mod for this kind of info too, but all I really > needed was what help() output. However, it would me nice to have > this functionality. > > > > > Reading documentation about function objects, the only > > relevant information I can extract is a tuple representing > > default param values, which is not useful to me. > > > > I know I could probably do this by parsing the module, but > > I would strongly prefer a simpler way. > > You could parse the output of help(). That would probably be > easier than parsing the module itself. > This won't return their order however. It is listed alphabetically. > > I'd have thought that, > > like docstrings and many other properties, the parameter info > > would also be stored with function objects. > > As far as I know this info is not strored. > > > From max at alcyone.com Wed Mar 10 20:08:36 2004 From: max at alcyone.com (Erik Max Francis) Date: Wed, 10 Mar 2004 17:08:36 -0800 Subject: Extending Python Syntax with @ References: Message-ID: <404FBC14.7F7EC705@alcyone.com> Ivan Voras wrote: > David MacQuigg wrote: > > > syntax. Seems like we could put the @ symbol to good use in these > > situations. Examples: > > No, don't do that!! I hate perl precisley because of littering the > code > with 'special characters'! The beauty of python code as it is, is that > it reads like a book, with punctuation to help the reader, rather than > the typesetter. Further, @ and $ are already used by some Python meta-applications in order to signal embedding Python code in something else, since these symbols are not used in Python itself. Templating systems often rely on such symbols not being in the language and staying out. But the Perlification of Python is the most relevant objection here. -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE \__/ An ounce of hypocrisy is worth a pound of ambition. -- Michael Korda From jcarlson at nospam.uci.edu Mon Mar 15 18:16:22 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Mon, 15 Mar 2004 15:16:22 -0800 Subject: How to use Sockets with wxPython? In-Reply-To: References: Message-ID: > EVT_TIMER(self, self.timer.GetId(), self.SocketPoller) Oops, should be: wx.EVT_TIMER(self, self.timer.GetId(), self.SocketPoller) From jzgoda at gazeta.usun.pl Sat Mar 6 10:34:10 2004 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Sat, 6 Mar 2004 15:34:10 +0000 (UTC) Subject: Newby Question: Generic Database Object Interface Needed References: <1Rc2c.2356$u92.1037@fe3.columbus.rr.com> Message-ID: kbass pisze: > I have checked the database resources at the Python website and performed a > Google search but I cannot find the information that I needed. I searched > sourceforge and found PDO: Python Database Objects at > http://pdo.neurokode.com/index.php . This seems to have the functionality > that I need. Are there any other modules (or programs) that have the same > functionality? I would like to do some comparisons. SQLObject -- http://www.sqlobject.org/ -- Jarek Zgoda http://jpa.berlios.de/ From ketulp_baroda at yahoo.com Mon Mar 22 10:42:47 2004 From: ketulp_baroda at yahoo.com (ketulp_baroda at yahoo.com) Date: 22 Mar 2004 07:42:47 -0800 Subject: Any reportlab user here?? Message-ID: Hi I am drawing a vertical barchart for project vs start date The vertical bars are for projects. Now, at the top of each bar I also want to display the number of projects. Also I want to show the color convention i.e Say I have different bars for H.R projects,etc... Now,if HR project bars are of blue colors then at the side of graph I want to show a small rectangle of blue color with "H.R project" beside it. How should I do this? Regards, Ketul From jacek.generowicz at cern.ch Fri Mar 19 03:35:56 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 19 Mar 2004 09:35:56 +0100 Subject: loop scope References: Message-ID: danb_83 at yahoo.com (Dan Bishop) writes: > One way to avoid this problem is to have an explicit scope-creating > construct instead. > > def foo(a): > scope outer: > a = 3 > scope inner: > a = 4 > print a # prints 4 > print outer.a # prints 3 > print foo.a # prints the function parameter > print a # inner.a is out of scope, so prints 3 > foo.b = 5 # Creates a new function-scope variable. > print b # prints 5 I think that the elegance of nested scopes relies on the language being able to find the innermost scope which contains the given name, _without_ help from the programmer. But this relies on being able to distinguish binding from re-binding. From janssen at parc.com Mon Mar 8 16:32:23 2004 From: janssen at parc.com (Bill Janssen) Date: Mon, 8 Mar 2004 13:32:23 PST Subject: distutils & Java components: a JavaExtension for distutils? Message-ID: <04Mar8.133226pst."58611"@synergy1.parc.xerox.com> Hi! I'm putting together a package that is primarily Python but includes some Java components. I'd like to write a single setup.py file for the whole thing, instead of using Makefiles, but I don't see any way to build Java jar files under distutils. Has anyone developed a module for handling this? Perhaps something like JavaExtension? Bill From technoumena at yahoo.com Wed Mar 31 23:22:39 2004 From: technoumena at yahoo.com (Technoumena) Date: Thu, 01 Apr 2004 04:22:39 GMT Subject: Fetching websites with Python In-Reply-To: References: Message-ID: > How can I do this? Perhaps something like this: import urllib2, thread, time, sys thread_count = len(sys.argv) - 1 pages = [] lock = thread.allocate_lock() def timer(): global lock time.sleep(15) lock.release() def get_page(url): global thread_count, pages, lock try: pages.append(urllib2.urlopen(url).read()) except: pass thread_count -= 1 if thread_count == 0: lock.release() lock.acquire() thread.start_new_thread(timer, ()) for url in sys.argv[1:]: thread.start_new_thread(get_page, (url,)) lock.acquire() print '\n---xxx---\n'.join(pages) Please have a nice day. Regards, Technoumena From http Thu Mar 18 01:17:12 2004 From: http (Paul Rubin) Date: 17 Mar 2004 22:17:12 -0800 Subject: SHA-based subclass for random module References: <7xptbgjpk4.fsf@ruckus.brouhaha.com> <5d83790c.0403170101.1a0a6452@posting.google.com> Message-ID: <7xk71iwufr.fsf@ruckus.brouhaha.com> python at rcn.com (Raymond Hettinger) writes: > Because SHA-1 is a digest function, additional input can be tacked on > without impacting invertibility. That gives you an opportunity to > incorporate the Mersenne Twister to take advantage of its provably > long period. I don't see any point to including Mersenne Twister output in the SHA update. If you want to make sure of a long period, it's easier to just mix in a simple counter. Note that the generator I posted should have period about 2**160 since in order to repeat, two different SHA states would have to repeat simultaneously. From rogerb at rogerbinns.com Sun Mar 21 18:17:54 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Sun, 21 Mar 2004 15:17:54 -0800 Subject: Python bytecode compatibility between interpreter versions References: Message-ID: Jon Perez wrote: > Anyway, we can at least count on the fact that a .pyc compiled > by a particular Python version (say, Python 2.1.1) on one platform > (say, Mac), will run on another platform (say, Solaris) as long > as the interpreter has the same minor version (say, Python 2.1.0). > > uh... right? Nope. They are an implementation specific thing. The interpretter puts version and other information in them, and regenerates them on the fly. There is nothing wrong with an interpretter deciding to regenerate them every single day in a different format, or based on the moon phase, or your login id or anything else. Roger From balajibalaraman2001 at yahoo.co.in Sun Mar 28 18:22:33 2004 From: balajibalaraman2001 at yahoo.co.in (BALAJI RAMAN) Date: Sun, 28 Mar 2004 23:22:33 -0000 Subject: How To capture an id into an array.. Message-ID: Hello everybody!!! I'm pretty much new to this OOP... I have a problem.. Here is a part of code that I'm writing class V(E): """ This is a variable for MPY""" def __init__(self): print id(self) check=[] check.append(id(self)) self.val = None what I do is call say v1=V() so it means that v1 belongs to the variable class.. Again if I call v2=V() so now v2 also belong to this class.. I want to keep a track of all the instances of this class.. and store their ids in an array.. any help in this regards is appreciated... Balaji From rawbobb at hotmail.com Sun Mar 28 11:40:24 2004 From: rawbobb at hotmail.com (bobb) Date: Sun, 28 Mar 2004 16:40:24 GMT Subject: ZODB for beginners - the most simple example ? References: <282f826a.0403272353.39a80af6@posting.google.com> Message-ID: I'd try the zope at zope.org group. "Richard Shea" wrote in message news:282f826a.0403272353.39a80af6 at posting.google.com... > Hi - I'm trying to use ZODB but I'm having trouble getting started. > Can anyone point me at a very simple example ? > > I've had a look at 'ZODB/ZEO Programming Guide' > (http://zope.org/Wikis/ZODB/FrontPage/guide/node2.html) but although > it's good stuff it's not clear to me how the pieces of example fit > together to produce something that works. > > I've also read 'Introduction to the Zope Object Database' > (http://www.python.org/workshops/2000-01/proceedings/papers/fulton/zodb3.htm l) > which has good examples but they rely on a module called 'PTextIndex' > which (as far as I can see) is not defined anywhere. > > So if anyone could point me at a very, very simple ZODB usage example > I'd be very grateful (and I should just say that both of the above > resources are very helpful so thanks to their authors). > > thanks > > Richard. From jacek.generowicz at cern.ch Mon Mar 15 09:32:31 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 15 Mar 2004 15:32:31 +0100 Subject: loop scope References: <0vdb505qigqvp8eahhp5qubnuh1v7n7k61@4ax.com> Message-ID: Gon?alo Rodrigues writes: > Is it (entirely) correct to say that class opens a new scope? I don't > think so, >>> class foo: ... a = 3 ... def bar(self): ... print a ... >>> f = foo() >>> f.bar() Traceback (most recent call last): File "", line 1, in ? File "", line 4, in bar NameError: global name 'a' is not defined Bleargh! You are right. Now that you bring it up, I recall bumping up against it before. > since names bound within the class body become attributes of the > class object, they are not local variables -- you can reach them > from the outside. That in itself does not prevent "class" from introducing a scope. It just means that there are ways of getting at things in that scope ... just like here: def foo(): a = [3] def show(): print a[0] def inc(n): a[0] += n return show, inc show, inc = foo() show() # prints 3 inc(2) show() # prints 5 "a" is definitely in the scope introduced by "foo", but you can reach it from the outside. > There were discussions about this in in the python dev list. The only > proposal that stuck in my memory was an extension of the global > keyword where you had an option of specifying the scope, something > like: > > def g(*args): > > x = None > > def f(*args): > global x in g Hmmm ... the explicit naming of the scope sort of piddles all over the elegance of nested scopes. But maybe the generality of being able to specify *any* enclosing scope has some applications, though none come to mind immediately. OTOH: def g(): x = None def g(): x = None def g(): global x in g Just *which* g are we talking about ? Let's just stick to finding the innermost binding of the name :-) Of course, the name "global" is completely inappropriate, but I guess they're trying to avoid a new keyword. From fake at fake.net Mon Mar 1 14:03:59 2004 From: fake at fake.net (Andrei) Date: Mon, 1 Mar 2004 20:03:59 +0100 Subject: Skins for Python GUI !! References: <5cc5bb23.0402292136.399c776a@posting.google.com> Message-ID: Somesh Bartakkay wrote on 29 Feb 2004 21:36:35 -0800: > I recently seen a small GUI program with Skins allplied. > the library used for that is Activeskin. > i wanna know weather Any GUi-Skins are available for pythons GUI ? > or how to use the activeskins for python gui(say ANy )?? I don't know any - don't like skins neither. PyUI (http://pyui.sourceforge.net/) is the most non-standard UI I know. You could also code your own in e.g. PyGame, but then it's still inside a window I suppose. And presumably you could code for Windows using win32all api calls, but I suspect that wouldn't be a lot of fun. -- 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 mkur at poczta.gazeta.pl Fri Mar 26 19:55:22 2004 From: mkur at poczta.gazeta.pl (=?ISO-8859-2?Q?Micha=B3?= Kurowski) Date: Sat, 27 Mar 2004 00:55:22 +0000 (UTC) Subject: python-ldap and Sun ONE Directory server Message-ID: Hi, I'd like to ask you whether anyone have built python-ldap against Sun ONE Directory v5.2 on a Solaris 9. Seems developers do not support such config, but many places on the web suggest it *is* possible and I would be a major pitta if I had to kick out my Ldap server now ... I've got python-ldap-2.0.0pre20 and use gcc 3.3.1. It complains "ldap_schema.h" cannot be found - and in fact Sun does not have any include file of that name. I just hope it is actually possible ... -- Michal Kurowski From sc0rp at hot.pl Fri Mar 26 13:25:40 2004 From: sc0rp at hot.pl (Jacek Trzmiel) Date: Fri, 26 Mar 2004 19:25:40 +0100 Subject: mod_python exception catching, other repetitious per-page actions References: Message-ID: <406475A4.5DCE359C@hot.pl> "Karl A. Krueger" wrote: > I'm in the middle of refactoring a small mod_python Web application, > which uses the Publisher handler. I have never used Publisher handler myself. Yes, I've read about it, but I've decided to not use it after seeing that I will have to explicitly tell which modules/functions I DON'T want external user to be able to run - completely broken idea from security POV. > One thing I would like to do is factor all of the top-level database > connecting, top-level exception handling, and error-page generation into > a single place. Whenever an exception occurs not trapped locally -- > including an error connecting to the database -- I want to generate an > HTML error page instead of throwing the stacktrace at the user. [...] > One thing I have considered is to handle _all_ the pages through a > single function, which would look up the specific pages by name: If you do this then you may as well drop Publisher handler completely. One handle() function will work for you. > ... but this has the problem that it sacrifices the argument name > matching which is a major useful feature of mod_python Publisher. Not so big, as you need to validate arguments format anyway. With calls like this: pos = self.GetFsInt( 'posId' ) lastDate = self.GetFsDate( 'lastDate' ) you can get arguments from FieldStorage, ensure that arguments are present and convert them to usable format (e.g. string=>datetime.date). Some examples: def RaiseMangled( self ): raise apache.SERVER_RETURN, apache.HTTP_BAD_REQUEST def RaiseNotFound( self ): raise apache.SERVER_RETURN, apache.HTTP_NOT_FOUND def GetFsString( self, key, default=None ): if(default != None): if self.fs.has_key(key): value = self.fs[key] else: value = default else: value = self.fs[key] if not isinstance( value, str ): self.RaiseMangled() return value def GetFsInt( self, key ): try: return int( self.GetFsString(key,'') ) except ValueError: self.RaiseMangled() def GetFsDate( self, key ): try: return Url2Date( self.GetFsString(key,'') ) except ValueError: self.RaiseMangled() I've used one method in class to handle db connections, dispatch requests and handle errors: def handler( req ): h = Handler() return h.Handle( req ) class Handler: [...] def Handle(req): try: db = DbAccess.ConnectDb( dbName, host, user ) self.fs = util.FieldStorage( self.req, True ) [...] self.req.add_common_vars() env = req.subprocess_env self.script = env['SCRIPT_NAME'] self.cmd = self.script[ rfind(self.script,'/')+1: ] if self.cmd == '': self.HandleMenu( db ) elif self.cmd == 'PosDailyFeed': self.HandlePosDailyFeed( db ) elif self.cmd == 'PosDailySubmit': self.HandlePosDailySubmit( db ) [...] else: self.RaiseNotFound() [...] except: [...] # handler for urls like this: # /PosDailyFeed?posId=3&date=2004-03-22 def HandlePosDailyFeed( self, db ): pos = self.GetFsInt( 'posId' ) date = self.GetFsDate( 'date' ) pb = self.CreatePageBuilder( db ) valueDict = db.GetPosWorkerData( date, pos ) BuildDailyFeedPage( pb, db, date, pos, valueDict, String2Html(db.GetPosName(pos)) ) self.SendPage( pb ) > I'm not sure if keyword args are exactly the Right Thing either. It also > would make the URLs even longer than they already are, though I can > kludge that with Apache URL rewriting rules. (Bleah.) If you use straight handler() function instead of Publisher handler then you have complete freedom how your URLs will look like. Best regards, Jacek. From bob at redivi.com Fri Mar 5 17:05:56 2004 From: bob at redivi.com (Bob Ippolito) Date: Fri, 5 Mar 2004 17:05:56 -0500 Subject: Module dependencies References: Message-ID: <2004030517055616807%bob@redivicom> On 2004-03-05 16:29:20 -0500, Lee Harr said: > On 2004-03-05, Nicolas Fleury wrote: >> Hi everyone, >> I was wondering, it there any common application to show direct and >> indirect dependencies of a module? Something with html output like >> pydoc? >> Thx and Regards, >> Nicolas > > > I suppose egrep will do an ok job for direct dependencies ... > > egrep "^import" foo.py There's also the modulefinder module, which scans bytecodes for import statements, but I don't believe it has any sort of nice html output. -bob From grey at despair.dmiyu.org Mon Mar 8 17:42:57 2004 From: grey at despair.dmiyu.org (Steve Lamb) Date: Mon, 08 Mar 2004 22:42:57 GMT Subject: Sending bulk email from a Python script References: <2004030816344216807%cs1spw@bathacuk> Message-ID: On 2004-03-08, Simon Willison wrote: > I'm looking into building a simple one-way (announce only) mailing list > system. The system will bulk-send messages to lists of around 5,000 email > addresses. What's the most efficient way of delivering this kind of email > volume from a Python script? The script will be running on a dedicated > server with full access to sendmail etc. Install Mailman and make the list postable only by you. :P -- 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 gstein at lyra.org Thu Mar 25 08:24:25 2004 From: gstein at lyra.org (gstein at lyra.org) Date: Thu, 25 Mar 2004 05:24:25 -0800 Subject: received your email Message-ID: <200403251324.i2PDOPZ4025377@nebula.lyra.org> Hi, [ Re: Re: Developement ] I have received your email, but it may take a while to respond. I'm really sorry to have to hook up this auto-responder, as it is so impersonal. However, I get a lot of email every day and find it very difficult to keep up with it. Please be patient while I try to get to your message. Please feel free to resend your message if you think I've missed it. I'll always respond to personal email first. If your email is regarding some of the software that I work on (if you have questions, comments, suggestions, etc), then please resend it to the appropriate mailing list: mod_dav WebDAV ViewCVS Subversion edna Thank you! Cheers, -g -- Greg Stein, http://www.lyra.org/ From ruach at chpc.utah.edu Thu Mar 4 14:50:32 2004 From: ruach at chpc.utah.edu (Matthew Thorley) Date: Thu, 04 Mar 2004 12:50:32 -0700 Subject: Redirecting stdout and stdin Message-ID: I am working on a script that calls a program ssh in this case. The script needs to be non-interactive so I need python to comunicate with ssh. I am having difficult time opening a pipe to the program and reading and writing output to it. I tried using popen something like: ssh = popen('ssh user at host') if ssh[1].readline = 'something': ssh[0].write('password') Etc... But everytime I run the thing stdout still shows up on the command line and I get propmted to enter the password interactively. Any thoughts ? thanks much -matthew From tdelaney at avaya.com Mon Mar 1 17:18:07 2004 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Tue, 2 Mar 2004 09:18:07 +1100 Subject: Thoughts on new vs traditional idioms Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE013E66FE@au3010avexu1.global.avaya.com> > From: Peter Otten > > Not particular frequent, but anyway: > > >>> sample = [[1,2], (3,4)] > >>> copies = [seq.__class__(seq) for seq in sample] > >>> for s, c in zip(sample, copies): > ... if s is c: print s > ... > (3, 4) > > Assuming all immutable classes are "smart enough": That's a *very* big assumption - one I would never make. It is explicitly stated that immutable objects *may* be reused. For some functions and methods, it states that they *will* be reused in certain situations. Only in those cases can or should you rely on that behaviour. Tim Delaney From happ_dickson at yahoo.ca Tue Mar 2 18:24:52 2004 From: happ_dickson at yahoo.ca (b0x) Date: Tue, 2 Mar 2004 17:24:52 -0600 Subject: HOWTO: Python 2.3 on Fedora Core 1 Linux References: Message-ID: <8169b602ffb91e592c69bbc1888a7f39@localhost.talkaboutprogramming.com> hey, thx alot for this topic,i had so many problems in installing tkinter , google didnt help me this time, but your toipc did :0) .. From kbass at midsouth.rr.com Tue Mar 16 19:10:14 2004 From: kbass at midsouth.rr.com (kbass) Date: Wed, 17 Mar 2004 00:10:14 GMT Subject: Dictionary & data References: <1079475979.24696.0@lotis.uk.clara.net> Message-ID: "Garry Knight" wrote in message news:1079475979.24696.0 at lotis.uk.clara.net... | In message , kbass wrote: | | > I have retrieved data from a database and I want to place this data into a | > dictionary or something like a HashMap (in Java). Can someone point me to | > an example? | | Here's most of what you'll need to handle dictionaries: | | d1 = {} # create empty dictionary | d2 = {"one": 1, "two": "two", 3: "three"} # create and populate dictionary | d3 = {1: 'spam', {'a': 'b'}} # nesting | d2["two"] = 42 # adding, changing | d3[1]['a'] = 'c' # changing value in nested dictionary | x = d2['two'] # fetch using index | y = d3[1]['a'] # fetch from nested dictionaries | cnt = len(d2) # get no. of key/value pairs | del d2[3] # remove key/value | for k in d2.keys(): # loop over keys | for v in d2.values(): # loop over values | for k,v in d2.items(): # loop over key/value pairs | d = d2.keys; d.sort() # get sorted list of keys | | It's probably a good idea to work your way through the tutorial here: | http://www.python.org/doc/2.3.3/tut/tut.html | | -- | Garry Knight | garryknight at gmx.net ICQ 126351135 | Linux registered user 182025 Thanks for the information. At least you weren't rude about it. kbass From dmq at gain.com Thu Mar 25 18:45:08 2004 From: dmq at gain.com (David MacQuigg) Date: Thu, 25 Mar 2004 16:45:08 -0700 Subject: Special symbols again (was Re: The problem with "as") References: <7x1xnlqs77.fsf@ruckus.brouhaha.com> <8ef9bea6.0403221354.574ebdaf@posting.google.com> <1M-dnXrds_WKG8LdRVn-jw@comcast.com> <7n34609f4t6uueb79aia3km2pm68orh0u6@4ax.com> Message-ID: On Thu, 25 Mar 2004 00:24:34 GMT, Joe Mason wrote: >In article <7n34609f4t6uueb79aia3km2pm68orh0u6 at 4ax.com>, David MacQuigg wrote: >> By "modified syntax" I mean an extension of the current standard >> syntax, e.g. the "decorators" we are now considering adding to the >> current standard function definition syntax, or the extra "arguments" >> we were discussing for the print statement. > >Why is the current standard priveleged? A few years down the road, half >of the basic functionality of the language will have special symbols in >front of it, just because it was proposed after an arbitrary date. The >symbol wouldn't tell anything about the features it's attached to except >the relatively uninteresting fact of when they were added to the >language. The key distinction is "basic" syntax vs "extensions". Every language has to make tradeoffs - doing everything possible and satisfying every special need vs. keeping things simple but more laborious for advanced users. Things generally start simple, then as experience accumulates, more stuff gets added. Thus the correlation with date you have noticed. My guess is that Python has maybe a dozen or so significant "extensions" still to be added to the basic syntax. Even if it is "half the functionality" still to come, as you envision, it won't be the basic half, which is already in place. Interestingly, my argument for a consistent extension syntax is *stronger* the more numerous we assume these extensions will be. Imagine a hundred new extensions, with mystifying names like 'lambda', or 'staticmethod', each with a different syntax, all woven into the basic syntax of the language. This would be a nightmare for new users and those who can't spend a lot of time staying proficient. Someone asked me in another discussion to name one feature that would justify adding a symbol to the language. My answer was - I can't imagine any single new feature that would be worth the cost of adding a symbol. It only makes sense if the symbol is used in enough places that it acquires a benefit for non-expert users - that benefit being a clear signal that "This is an extension syntax. You can probably understand this statement by ingoring the extension. You don't have to learn it in your first use of the language." With a good extension syntax, the tradeoffs will be easier. We can satisfy more advanced requests, while not burdening the basic user. >> "Second class" has negative connotations. A better description would > >Yes, I used it deliberately. Singling out syntax as non-basic makes it >second class. What if you predict wrong? What if it catches on like >wildfire and gets taught in Day 2 of every class? Now your symbol has >no meaning at all, because it's part of what everybody considers basic. We have to assume that the developers, guided by our wonderful discussions, will make the right choices as to what is basic and what is not. These decisions are made all the time in setting up defaults for a module, chosing the most needed options in a print statement, etc. If it turns out that static methods become more popular than basic methods, we have the same problem as chosing the wrong defaults in a new module. The fact that it *might* happen is not a good argument that we shouldn't even *try* to make a sensible choice. Presenting all choices as being equal is *guaranteed* to be wrong. >Yep, I recall you bringing this up at the time and not convincing >anybody. I'm glad Python development is guided by reason, not popular vote. And I do appreciate your willingness to engage in reasoned discussion. >> The key design goal is to *mimimize* the number of syntactic >> variations we have to introduce as we extend the language. The >> proposed @() syntax seems like it would work in *many* places, and it >> always has the same general meaning -- "This is a modification of the >> basic syntax you already understand." To learn the details of a > >That's a meaning that's too general to be of any use. If the new syntax >is successful, it's no longer a modification, it's a basic syntax now, >so now @ means "this is either new, or not". > >> particular variation, you read the manual on the particular statement >> where the variation occurs. @(staticmethod) - read about it under >> "def". print @(...) - read the manual on 'print'. > >People will recognize things they don't understand without an @ sign, by >virtue of not knowing what they are. @(staticmethod) won't tell me to >look under def any more than [staticmethod] will, and if I see something >I don't recognize near a print statement, I'll already know to read the >manual on 'print'. It's not enough that the user recognize something he doesn't understand and be able to find it in the docs. The number of these things can be overwhelming. I remember the first time reading about static methods, and not having enough time to really understand what they were. The time was wasted, and had I needed to work with any code having static methods, I would have given up. The problem is that new users need guidance as to where they should focus their efforts in learning the language. A properly-designed nameless-function syntax would avoid the obfuscation of lambda functions. Any user who understands basic functions would have no difficulty with such an extension. -- Dave From imbosol at aerojockey.invalid Sat Mar 27 17:21:59 2004 From: imbosol at aerojockey.invalid (Carl Banks) Date: Sat, 27 Mar 2004 22:21:59 GMT Subject: A 'Python like' language References: <40645d8f$0$10775$afc38c87@news.easynet.co.uk> <95aa1afa.0403262049.4b2a6f78@posting.google.com> <95aa1afa.0403271039.5a351884@posting.google.com> Message-ID: Michele Simionato wrote: > David MacQuigg wrote in message news:... >> On 26 Mar 2004 20:49:00 -0800, michele.simionato at poste.it (Michele >> Simionato) wrote: >> This is a small problem with a simple solution (see my earlier post), >> and one that will retain the advantages of tabs. > > Which advantages? If the contest you're submitting your program to has hard byte limit, and you need large indents to properly document your code. (That is one thing.) -- 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 ieyf4fu02 at sneakemail.com Wed Mar 24 01:15:42 2004 From: ieyf4fu02 at sneakemail.com (Greg Ewing (using news.cis.dfn.de)) Date: Wed, 24 Mar 2004 18:15:42 +1200 Subject: PEP 318 In-Reply-To: <7x1xnlqs77.fsf@ruckus.brouhaha.com> References: <99dce321.0403211817.3704fe2@posting.google.com> <7x1xnlqs77.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > The syntax can be extended, i.e. "def foo() as generator" looks to me > to be a lot more explicit than "def foo()" followed by having the > compiler search the function body for a yield statement in order > to decide if it's a generator. While I happen to agree that generators ought to be created using something other than a plain "def", it couldn't be done this way. Generators need to be compiled differently from the beginning -- you can't turn an ordinary function into a generator by wrapping it in anything. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From lbates at swamisoft.com Thu Mar 11 09:52:07 2004 From: lbates at swamisoft.com (Larry Bates) Date: Thu, 11 Mar 2004 08:52:07 -0600 Subject: File.read() sometimes not reading everything References: Message-ID: Your file may contain an EOF character before the actual end of file. You might want to try f=open('myFile','rb') to open in binary mode, which would ignore EOF characters and read the entire file. -Larry "Boris Boutillier" wrote in message news:pan.2004.03.11.10.07.48.456622 at arteris.net... > HI all, > > I came across a strange behaviour with read method, and I'm not sure if > this is a filesystem problem or a misuse of this method. > I do the simple following thing : > f = open ('myFile','r') > content = f.read() > f.close() > > When I use this lines really intensively sometimes, at random the content > is not the full content, it lacks some lines at the end. > When reading the file.read docstring I see that there can be some problems > with non-blocking file, but I suppose open() is by default creating a blocking > file. > > Is the file line-buffered by default ? This could be a reason for this > early EOF, as I'm reading all the lines at once, and there is several > lines in the file ? > > I'm at the moment trying to replace the previous read call by: > content = '\n'.join(f.readlines) > Not sure if this will work better, I'll say you. > > Any other idea of this strange behaviour ? Can this be a problem with > filesystem also ? > > Any ideas welcomed ! > > Boris From python-list at qbcon.com Tue Mar 23 09:24:49 2004 From: python-list at qbcon.com (Andreas Pauley) Date: Tue, 23 Mar 2004 14:24:49 +0000 (GMT) Subject: Sending ICMP Packets Message-ID: <20040323132841.V409@bsd4.intranet.qbcon.com> Hi, I'd like to generate my own icmp packets from within python. Typically this would include sending an ECHO_REQUEST and checking if I get an ECHO_REPLY back. But I would also like to send/receive other icmp types, like timestamp and timestamp replies. At the moment I'm playing with the socket module: import socket icmp=socket.getprotobyname('icmp') s = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp) My "s" object has a sendto() method which accepts a string and an address (according to the socket docs), but I'm not sure what the value of the string should be. Does anyone have some simple example code that will ping a host? This is part of some firewall tests that I'm writing as unit tests, so if anyone knows of tools out there that can help with firewall testing I'd appreciate that aswell. Regards, Andreas From eric.brunel at N0SP4M.com Mon Mar 1 04:13:06 2004 From: eric.brunel at N0SP4M.com (Eric Brunel) Date: Mon, 01 Mar 2004 10:13:06 +0100 Subject: tkinter test field, scrolling, threads References: <403fc9bc_6@corp.newsgroups.com> Message-ID: Bob Greschke wrote: > I have a program where the user pushes a button, a "starting" message is > .inserted to a text field with an associated scroll bar, a thread is started > that inserts a "working..." message on to the end of the text field until > stopped, or until the loop finishes. The loop sleeps for about 3 seconds > every time through (I'm just prototyping at this point). The mainloop just > waits for the user to hit the same button again which will set a flag and > cause the thread to terminate early, otherwise it doesn't have anything to > do. update()'s and update_idle_tasks() get called anytime anything is > written to the text field. Everything works fine until the text field fills > up then the program just freezes with no errors on the console window. If I > change the starting of a thread to a regular function call then everything > works fine. > > What is going wrong? If you do not post any code, it will be difficult for anyone to help you. Knowing your Python and tcl/tk versions and your platform will help too. I know that there are some issues regarding Tkinter and threads, but the following code works: --text+threads.py------------------ from Tkinter import * import time, threading root = Tk() t = Text(root, width=8, height=4) t.pack(side=LEFT, fill=BOTH) vs = Scrollbar(root, orient=VERTICAL, command=t.yview) vs.pack(side=RIGHT, fill=Y) t.configure(yscrollcommand=vs.set) root.update() def thLoop(): i = 0 while 1: t.insert(END, 'spam %s\n' % i) i += 1 time.sleep(1) th = threading.Thread(target=thLoop) th.setDaemon(1) th.start() root.mainloop() ----------------------------------- Tested with Python 2.1.1, tcl/tk 8.3.2 on Linux Mandrake 8.0 -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From steve at ninereeds.fsnet.co.uk Thu Mar 4 17:05:22 2004 From: steve at ninereeds.fsnet.co.uk (Stephen Horne) Date: Thu, 04 Mar 2004 22:05:22 +0000 Subject: Again: Please hear my plea: print without softspace References: <4041796c.2181078@news.muenster.de> <1rfj4etyhlcw6$.1evn1aiuzkinp$.dlg@40tude.net> <40448d4f.8911015@news.muenster.de> <17O0c.432676$I06.4900877@attbi_s01> <4046aa14.9853593@news.t-online.de> <2s2c4053vpk3o3b0hauea23cb0q11ihl74@4ax.com> <404795ce.683812@news.muenster.de> Message-ID: <3o9f40tpvn2bj29p5g23i4et9hv3qii4hu@4ax.com> On Thu, 04 Mar 2004 22:12:14 +0100, Peter Maas wrote: >Martin Bless schrieb: >> And then: Is it possible to reopen sys.stdout if the platform ist not >> Unix-like? > >Yes but e.g. Win32 does not know /dev files, so am not sure what >to substitute for /dev/tty. DOS had a "device" called CON which is >still alive in Win32 consoles (echo Hi > CON) but I have not tested >that. > >Mit freundlichen Gruessen, > >Peter Maas Easy solution - write your extender such that it takes the original file in the constructor... sys.stdout = ExtendedFile (sys.stdout) One thing, though - can't this cause problems when different modules separately import 'sys'. Given that the new sys.stdout should be compatible with the old one (use inheritance and just add/override the required methods) I'm far from sure, but this approach makes me feel a bit uneasy - I suspect a future of obscure and hard to trace bugs. -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From opengeometry at yahoo.ca Sat Mar 6 15:41:56 2004 From: opengeometry at yahoo.ca (William Park) Date: 6 Mar 2004 20:41:56 GMT Subject: Need better string methods References: <0d4k40987t6d70bahqil3geth640bufgoc@4ax.com> Message-ID: David MacQuigg wrote: > The resistance will come from people who throw at us little bits and > pieces of code that can be done more easily in their chosen CPL. > String processing, for example, is one area where we may face some > difficulty. Here is a typical line of garbage from a statefile > revision control system (simplified to eliminate some items that pose > no new challenges): > > line = "..../bgref/stats.stf| SPICE | 3.2.7 | John Anderson \n" > > The problem is to break this into its component parts, and eliminate > spaces and other gradoo. The cleaned-up list should look like: > > ['/bgref/stats.stf', 'SPICE', '3.2.7', 'John Anderson'] > > # Ruby: > # clean = line.chomp.strip('.').squeeze.split(/\s*\|\s*/) > > This is pretty straight-forward once you know what each of the methods > do. > > # Current best Python: > clean = [' '.join(t.split()).strip('.') for t in line.split('|')] Both Bash shell and Python can split based on regular expression. However, shell is not a bad alternative here: tr -s ' \t' ' ' | sed -e 's/ ?| ?/|/g' -e 's/^ //' -e 's/ $//' | while IFS='|' read -a clean; do ... done -- William Park, Open Geometry Consulting, Linux solution for data processing and document management. From dave at pythonapocrypha.com Sat Mar 13 00:14:15 2004 From: dave at pythonapocrypha.com (Dave Brueck) Date: Fri, 12 Mar 2004 22:14:15 -0700 Subject: How to stop a listening socket.accept()? References: Message-ID: <007701c408ba$08ac8600$6401fea9@YODA> kvdvm wrote: > It seems that the accept() method acts as stubborn as a mule to get a > connection request even if I close it in another thread. > > Any idea will be deeply appreciated. You can either make it non-blocking and use select in a loop, or you can have a global flag indicate when it's time to shutdown, and open a dummy connection to it, e.g. (untested): class GV: quit = 0 listenAddr = ('127.0.0.1', 2000) def Listen(listenSock, handler): while 1: newSock, sockFrom = listenSock.accept() if GV.quit: newSock.close() break handler(newSock, sockFrom) def StopListening(): GV.quit = 1 socket(AF_INET,SOCK_STREAM).connect(listenAddr) -Dave From paul at prescod.net Mon Mar 29 23:34:48 2004 From: paul at prescod.net (Paul Prescod) Date: Mon, 29 Mar 2004 20:34:48 -0800 Subject: Pyrex talks from Pycon In-Reply-To: <4067BCC8.5010209@prescod.net> References: <4067BCC8.5010209@prescod.net> Message-ID: <4068F8E8.70603@prescod.net> Paul Prescod wrote: > > I hope this helps me. Please report any mistakes. > ... Whoa. I've gotta get more sleep. I meant to say: "I hope this helps someone." Paul Prescod From fredrik at pythonware.com Sun Mar 14 06:32:57 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 14 Mar 2004 12:32:57 +0100 Subject: Tkinter: how to refresh a canvas without duplicates? References: <20040228011336.3e4a9e0f@pc-00065.midtoad.homelinux.org> Message-ID: "stewart" wrote: > > if you need to rapidly redraw things in a Tkinter widget, the WCK is > > often a lot more efficient: > > > > http://www.effbot.org/zone/wck.htm > > I've tried to install this, but when I run 'python setup.py install', it > complains that it "cannot find /usr/lib/python/2.3/config/Makefile". Why > would this be? looks like you're using a prepackaged Python that doesn't include the developer files (include files, libraries, etc). look for "python-dev" or "python-devel" kits (or get the python sources, and build your own interpreter from scratch). also see: http://www.python.org/doc/faq/extending.html#i-want-to-compile-a-python-module-on-my-linux-system-but-some-files-are-missing-why From tjreedy at udel.edu Wed Mar 10 11:59:43 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 10 Mar 2004 11:59:43 -0500 Subject: Working around a lack of 'goto' in python References: <7id67l8dro.fsf@enark.csis.hku.hk> <7ismggofrt.fsf@enark.csis.hku.hk> Message-ID: "Isaac To" wrote in message news:7ismggofrt.fsf at enark.csis.hku.hk... > >>>>> "Jeff" == Jeff Epler writes: > > Jeff> Are you certain that calling a function allocates a dictionary? A > Jeff> function's locals are stored as indices in a C array unless a > Jeff> function uses bare exec. I'm not sure what a dictionary is needed > Jeff> for. > > You mean a function which calls the locals() function is byte-compiled > differently from a function that won't call locals()? Of course. One has a call to the locals() function and the other does not. Note that writing to the dict returned by locals() is *NOT* guaranteed to affect the local namespace that the dict is a copy of. Specifics can be version dependent, as revealed by disassembly with the dis module. Terry J. Reedy From cookedm+news at physics.mcmaster.ca Thu Mar 4 14:57:02 2004 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Thu, 04 Mar 2004 14:57:02 -0500 Subject: Python as replacement for PHP? References: <403fa54b@news.zianet.com> <99dce321.0403031518.56f61c7c@posting.google.com> <7xad2x5wfm.fsf@ruckus.brouhaha.com> <23891c90.0403040241.60eb33a4@posting.google.com> <7x7jy0o8qd.fsf@ruckus.brouhaha.com> Message-ID: At some point, Paul Rubin wrote: > paul at boddie.net (Paul Boddie) writes: >> Really? At the fundamental level, the DB-API is pretty well >> standardised, and there's a collection of well-written modules that >> mostly adhere to it. > > Nope. Look in the Python distribution, there's nothing like that > there, and similarly in the Python reference manual. Yeah, there's > some random third party modules and docs, but see above, those don't > exist ;-). http://python.org/peps/pep-0249.html PEP 249 is the DB-API. Ok, so it's not in the standard distribution -- as you said, there aren't any (SQL) database modules in the standard distribution [1]. But this is the standard API for database interfacing (and it's not a third-party API, either). Most third-party modules conform to it (except for weird or old ones). [1] maybe gadfly will get added at some point, though. And hey, if you're choosing a database module, you've got to have already chosen a database -- MySQL, PostgreSQL, SQLite, etc. This is a bigger choice than "how do I talk to it." The Python DB-API makes it relatively easy to write code where the difference in talking to different databases is only in your SQL, and not how you call it. -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From daniel.dittmar at sap.com Mon Mar 29 09:53:47 2004 From: daniel.dittmar at sap.com (Daniel Dittmar) Date: Mon, 29 Mar 2004 16:53:47 +0200 Subject: A 'Python like' language References: <40645d8f$0$10775$afc38c87@news.easynet.co.uk> <95aa1afa.0403262049.4b2a6f78@posting.google.com> Message-ID: Joe Mason wrote: > In article , Mark Hahn wrote: >>> But I wonder what effect the lack of reference counting has >>> on cache-friendliness of the memory management system. >> >> I don't see how the lack of something could hurt the cache. Do you >> mean the garbage colector? The mark and sweep just behaves like >> another app running at the same time and uses a hunk of the cache to >> do it's job. Other than that I can't think of anything unfriendly >> to the cache. Am I missing something in your question? > > This, I think: > > http://gcc.gnu.org/ml/gcc/2002-08/msg00552.html On the other hand, reference counting requires access to the memory even if only a reference is copied. This can't be good for cache locality either. Daniel From p2esp at yahoo.com Tue Mar 2 05:24:26 2004 From: p2esp at yahoo.com (p2esp) Date: Tue, 2 Mar 2004 02:24:26 -0800 (PST) Subject: xmlrpclib timeouts Message-ID: <20040302102426.2869.qmail@web61004.mail.yahoo.com> Hello, I'm using the xmlrpclib module to contact an XMLRPC server that takes a long time to send results back. My client timeouts. The question is whether there is a way to have an xmlrpclib client that never timeouts. I have been searching for some code examples on how to do that, but I could not find any in the xmlrpclib documentation. Thanks for any hints. __________________________________ Do you Yahoo!? Yahoo! Search - Find what you?re looking for faster http://search.yahoo.com From wmwd2zz02 at sneakemail.com Wed Mar 3 22:52:29 2004 From: wmwd2zz02 at sneakemail.com (Greg Ewing (using news.cis.dfn.de)) Date: Thu, 04 Mar 2004 16:52:29 +1300 Subject: insertion in lists In-Reply-To: References: Message-ID: Lupe wrote: > I'm trying to have a kind of multi-dimensional list which seems to me to be > the best way to have an array of not known extension, at the begining of > the program. You might also like to consider using a dictionary indexed by a tuple, which behaves like a sparse array, so you can do things like d = {} d[0, 0] = 'a' d[5, 7] = 'b' without having to worry about pre-allocating lists and sub-lists of the right lengths first. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From roy at panix.com Tue Mar 9 16:05:06 2004 From: roy at panix.com (Roy Smith) Date: Tue, 09 Mar 2004 16:05:06 -0500 Subject: Working around a lack of 'goto' in python References: Message-ID: Joe Mason wrote: > In article , Roy Smith wrote: > > OK, I'll bite. What's wrong with exceptions for breaking out of deeply > > nested loops? > > Philosophically, the termination condition of a loop isn't an > exceptional circumstance. The normal flow of control is when you fall out the bottom of the loop when your control test goes false. Breaking out of the middle is indeed an exceptional circumstance; it is an exception to the normal flow of control. People tend to think of exceptions as errors, but they don't have to be. Now, to be fair, imagine a construct like this: try: for i in range (iMax): for j in range (jMax): for k in range (kMax): if thisIsIt (i, j, k): raise IFoundIt print "it's not there" except IFoundIt: print "yes it is" Presumably the expectation is that the thing you're looking for will exist somewhere in the i,j,k coordinate space. Falling out the bottom of the loop is now the error condition. I think this is what you were getting at, and I agree that this turns the whole concept of an exception on its ear. The example above is one where I think factoring it out into a function makes the most sense: def whereIsTheThing (): for i in range (iMax): for j in range (jMax): for k in range (kMax): if thisIsIt (i, j, k): return (i, j, k) raise ItsNotThere > Practically, exceptions are overkill. Using named break (or faking it > with goto) is "static multi-level exit", while an exception is dynamic. > It takes more overhead at runtime That's certainly true in C++. In complied/static languages like C++, there can be a significant speed difference between things that can be done at compile time and things that need to be done at run time (like constructing exception objects). In Python, the cost of using exceptions is way less. I just tried a little test, timing a bunch of breaks vs raises to get out of an inner loop (code listing below). My timing results were: count = 10000, the break way took 7.349000 seconds count = 10000, the exception way took 8.121592 seconds Yeah, the exceptions were slower, but only 10% slower, and that's for a loop that did essentially no useful work, so it's all overhead. The difference would be smaller if the loop did anything real. I'm not likely to let such a small change in execution time drive my code design. If I was worried about such small speed gains, I wouldn't be writing in Python. I would try repeating this example in C++, but the thought of how many lines of code I'd have to write to do it has convinced me that it should be left as "an excercise for the reader" :-) > and if you don't catch it right it > can escape up the call stack. Well, yeah, but the answer to that is you catch it. In fact, that's one of the nice things about exceptions. If you don't catch it correctly, you find out about it fast. If you mis-code a goto or break label, you just quietly execute the wrong code. > A more pragmatic argument is that, for C++, [...] > // declare an EndLoopException class, which I forget how to do because > // I haven't used C++ exceptions in ages I think what you've demonstrated here is not so much that exceptions are a bad thing, but that C++'s implementation of exceptions (like most things in C++) is overly complicated. I find it interesting that many people who come from a C++ background (especially those who migrated from C) tend to dislike exceptions. It must have been something in the water when they were growing up :-) -------------- #!/usr/bin/env python import time class Break (Exception): pass x = 10000 t0 = time.time () count = 0 for i in range (x): for j in range (x): break count += 1 t1 = time.time () print "count = %d, the break way took %f seconds" % (count, t1 - t0) t0 = time.time () count = 0 for i in range (x): try: for j in range (x): raise Break except Break: pass count += 1 t1 = time.time () print "count = %d, the exception way took %f seconds" % (count, t1 - t0) From reynoldjr at verizon.net Tue Mar 23 23:53:53 2004 From: reynoldjr at verizon.net (Reynold DeMarco Jr) Date: Wed, 24 Mar 2004 04:53:53 GMT Subject: study_hall Message-ID: I have created a new Yahoo group for college students Please join http://groups.yahoo.com/group/study_hall/ From ahk at writeme.com Fri Mar 26 09:34:06 2004 From: ahk at writeme.com (ahk) Date: 26 Mar 2004 06:34:06 -0800 Subject: Gtk / pyGtk: How to remove the close button at the top right corner of the dialog window? Message-ID: As subject. TIA. From salvatore at nolog.org Fri Mar 19 16:53:23 2004 From: salvatore at nolog.org (Salvatore) Date: Fri, 19 Mar 2004 22:53:23 +0100 Subject: XML Message-ID: Hello, I'am trying to parse an XML file using sax and Python 2.3 on windows class FindIssue(saxutils.DefaultHandler): AttributeError: 'module' object has no attribute 'DefaultHandler' Doesn't DefaultHandler makes part of saxutils ? Thank you for your responses Salvatore From newsgroups at jhrothjr.com Sun Mar 28 18:32:25 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Sun, 28 Mar 2004 18:32:25 -0500 Subject: Prothon Prototypes vs Python Classes References: <106dukh7ncf9ad4@news.supernews.com> Message-ID: <106eo695a9t8820@news.supernews.com> "Harald Massa" wrote in message news:Xns94BBF152E6BBcpl19ghumspamgourmet at 62.153.159.134... > Mark, > > I see most discussion about Prothon is concerning prototypes. > > Can you explain to me in easy words, why it is NOT possible to integrate > prototypes into Python to stand "side by side" with classes? > > I never had a problem to "add an attribute" to an existing object; I really > can't see why it should be more than some small hacks to allow "adding a > function to an existing object". As you note, you can do that with a simple assignment, and it will work. The two problems are: 1. The clone operation 2. Syntax sugar to make it all nice and palatable. I suspect that a usable clone() operation is less than 10 lines. The syntax sugar, on the other hand, will IMNSHO, take forever to get agreement. John Roth > > > Harald From rpm1deleteme at direcway.com Mon Mar 29 20:19:07 2004 From: rpm1deleteme at direcway.com (RPM1) Date: Mon, 29 Mar 2004 20:19:07 -0500 Subject: Britney Spears nude References: <1080607371.97814.0@iris.uk.clara.net> Message-ID: "Garry Knight" wrote in ... > In message , RPM1 wrote: > > > My wife , (yes my wife not me), was watching > > a program on TV about this girl who was having > > plastic surgery to look just like B. Spears. It seems > > she hadn't inherited the same kind of attributes that > > the base class has so she was having them overridden > > to match the base class. So my question is which > > instance of B. spears are we talking about? > > Don't know, but it explains the single title, 'OOPs, I did it again'... Damn! How did I miss that one! I think that must be worth 25 points. :-) LOL Patrick From gandreas at no.reply Thu Mar 25 16:44:01 2004 From: gandreas at no.reply (Glenn Andreas) Date: Thu, 25 Mar 2004 15:44:01 -0600 Subject: Make 'def' and 'class' usable within expressions References: <1065uf99la6if29@news.supernews.com> Message-ID: In article , Shane Hathaway wrote: > Glenn Andreas wrote: > > What do you do if the expression is in an "if" statement? > > > > > > if map(def(x,y,z),list1,list2,list3): > > # what goes here? The body of the function > > # or the body of the if? And how does the rest of it > > # look? > > Ah, that's an interesting concern. The same applies to "for" and > "while" statements. This would have to be a syntax error. Rewriting it > isn't too difficult, though, if you're willing to create an extra variable. > > condition = map(def(x,y,z),list1,list2,list3): > function body > if condition: > do stuff > Wasn't the whole point of the use of "def in expression" to avoid having to use an extra variable? After all, you currently can use an extra variable and get the exact same result: def myMapFunction(x,y,z): # body of function if map(myMapFunction,list1,list2,list3): # body of if So basically, at that point, if you want to use def in expressions, for control expressions you'd need an extra variable, which is exactly the state you've got today (you just move that varible from a function to a value from). > > Also, limiting to "one per expression" prevents you from doing something > > like: > > > > myHandlers = { > > "click" : def(x,y): > > print "click at x,y" > > "enter" : def(): > > print "mouse entered" > > "exit" : def(): > > print "mouse exited" > > } > > That example reads well, although it's odd that each function can have a > different set of arguments. I think you'd really want a "case" > statement instead, but Guido doesn't seem to want that. > > Shane > I was thinking more the case where you hand that dictionary to something like a bridge for an external UI system (in this example it might be to handle the various callbacks that might be bound to a button). The external (native) system would just know that it has a dictionary with a bunch of "handlers" associated with keys. Granted, it may be easier to hand the native UI system an object with specific methods which it could call (PyObject_CallMethod), but one can certainly imagine the system as described being used. Personally, I like the idea of anoymous functions, and that: x = def(arg): print args+1 and def x(arg): print arg+1 are the same doesn't bother me (Lua does this exact same thing - even pointing out that the equivalent syntax for the latter form is nothing but syntactic sugar for the former (though with the word "function" instead of "def")). Still, the whole thing comes down to the fact that statements are terminated by new-lines & use indentations, and expressions are (normally) within a single line (and ignore indentation when they aren't). The impediance between the two is pretty high, so trying to mix them isn't going to be easy or pretty. From nid_oizo at yahoo.com_remove_the_ Tue Mar 30 12:34:48 2004 From: nid_oizo at yahoo.com_remove_the_ (Nicolas Fleury) Date: Tue, 30 Mar 2004 12:34:48 -0500 Subject: Why '==' ?? In-Reply-To: References: <8089854e.0403300510.1971c24@posting.google.com> Message-ID: JCM wrote: > a = b = c > a = b == c In fact, it is very funny to see the effect of a=b=c in Basic (or at least in the Microsoft implementation I know of). a = 2 b = 3 c = 3 a = b = c a is assigned 1, which is the result of comparison of b and c. So in Basic, the first = is like = in Python, and the other are like ==. This is horrible... From tismer at stackless.com Tue Mar 30 10:21:07 2004 From: tismer at stackless.com (Christian Tismer) Date: Tue, 30 Mar 2004 17:21:07 +0200 Subject: Orders of magnitude In-Reply-To: References: <000c01c415fb$4f6a5600$0000fea9@simonxp> Message-ID: <40699063.1080005@stackless.com> Josiah Carlson wrote: >> p.s.; this is the last time I manually will remove a "nospam" >> email entry. Who should remove all the spam mailings, if people >> like you don't help with it? :-) > > > No need to CC me, I read the newsgroup and will read the message > anyways. :) Yeah, I may as well toss the nospam portion, that is why I > have the bayesian filter. > > I'm curious to know what what email/newsgroup client you are using, your > email client does not seem to produce proper "References:" and > "In-Reply-To:" headers, which breaks message threading. The headers > claim Mozilla, but I thought I'd ask anyways. What's wrong with """ To: Simon Wittber References: <000c01c415fb$4f6a5600$0000fea9 at simonxp> In-Reply-To: <000c01c415fb$4f6a5600$0000fea9 at simonxp> """ ? it is the latest windows mozilla. 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 stewart at midtoad.homelinux.org Fri Mar 5 22:29:17 2004 From: stewart at midtoad.homelinux.org (midtoad) Date: Sat, 06 Mar 2004 03:29:17 GMT Subject: Curiosity question on signatures References: Message-ID: Gon?alo Rodrigues wrote: > Does this "feature" of being able to treat positional arguments as > named arguments have any use? Does anybody make any use of it? Is > there any rationale on why it's in the language? Oi Gon?alo, tudo bem? my reference Python Web Programming by Steve Holden has a good section on functions and arguments. He would likely say in response to your post that in your example you are not using positional arguments as named arguments. Rather, you are providing arguments as keywords. Python doesn't restrict you unnecessarily, so you can provide the arguments in the way that you prefer. One restriction however does exist: all the positional arguments have to come before the keyword arguments; that's because you may a case with a variable number of keyword arguments, so they have to come at the end. Stewart From david at rebirthing.co.nz Sat Mar 13 19:37:27 2004 From: david at rebirthing.co.nz (David McNab) Date: Sun, 14 Mar 2004 13:37:27 +1300 Subject: How to move and then use an installed python? In-Reply-To: References: Message-ID: <4053A947.8000606@rebirthing.co.nz> AFAIK, when Python gets compiled, the binary ends up with hardwired file/directory paths. Since you've moved the python tree, you have two choices: 1) Recompile python for its new location, and reinstall all the extra packages 2) Explicitly set the PYTHONHOME and/or PYTHONPATH environment variables (see man python). David Baz ???? wrote: > All, > > If I have installed python 2.3.3 in /opt/thirdparty directory. Can I > copy the contents of the thirdparty directory to my rpm/SOURCES > directory as part of my software_a rpm package then reuse it and > install in /home/mydir? > > So I have tried this and i have the following errors: > > error: Failed dependencies: > /opt/thirdparty/bin/python is needed by Avalon-dev-de > > How can I use an installed python package? Should I build it with a > different option? > > Thanks > > B. > > -- Kind regards David -- leave this line intact so your email gets through my junk mail filter From ross at karchner.com Tue Mar 2 10:23:13 2004 From: ross at karchner.com (Ross M Karchner) Date: Tue, 02 Mar 2004 10:23:13 -0500 Subject: xmlrpclib timeouts In-Reply-To: References: Message-ID: Maybe a timeoutsocket with really long timeout value would do what you want? http://www.timo-tasi.org/python/timeoutsocket.py import timeoutsocket timeoutsocket.setDefaultSocketTimeout(86400) # 24 hours -Ross p2esp wrote: >>>Hello, >>> >>>I'm using the xmlrpclib module to contact an XMLRPC >>>server that takes a long time to send results back. > > My > >>>client timeouts. >>> >>>The question is whether there is a way to have an >>>xmlrpclib client that never timeouts. I have been >>>searching for some code examples on how to do that, >>>but I could not find any in the xmlrpclib >>>documentation. >>> >>>Thanks for any hints. > > >>"Client that never times out" is not a good idea, > > generally. > >>Nothing in life is certain, but even moreso in > > distributed > >>systems. Timeouts are there to protect you from all > > kinds > >>of problem conditions (busy server, crashed >>server, etc.). You really don't want your client to > > be in a > >>position of waiting for a response that is never > > going to > >>come. > > > ... > >>Paul > > > Thank you Paul for your informative message. > > I do understand it's not a good idea to do this, and I > will check what you suggest. Nevertheless, I still > want to know: can a "never timeout" client be written > in xmlrpclib? > > > __________________________________ > Do you Yahoo!? > Yahoo! Search - Find what you?re looking for faster > http://search.yahoo.com > From uce at ftc.gov Tue Mar 2 12:10:01 2004 From: uce at ftc.gov (Gordon Airport) Date: Tue, 02 Mar 2004 12:10:01 -0500 Subject: vim & python In-Reply-To: References: <221dd125.0403011151.504ce09d@posting.google.com> Message-ID: gabor wrote: > On Tue, 2004-03-02 at 02:48, poiboy wrote: > >>Normally I use GVim next to .... > > > i always wanted to ask this... > why people use GVIm and not the normal-vim-in-a-terminal? > > what is the advantage of gvim? > > thanks, > gabor > > So when you need to use a command that you don't use frequently you don't have to dig through docs somewhere, you can just find it in the menus. Or, if you work in windows it's more natural. From joe at notcharles.ca Mon Mar 15 17:47:59 2004 From: joe at notcharles.ca (Joe Mason) Date: Mon, 15 Mar 2004 22:47:59 GMT Subject: Static Typing in Python References: <4055a71e$0$28265$afc38c87@news.easynet.co.uk> <4055cb43$0$7558$afc38c87@news.easynet.co.uk> <4055ec40$0$15725$afc38c87@news.easynet.co.uk> Message-ID: In article , Jacek Generowicz wrote: > Python's type system is what it is, regardless of anybody's opinion > about it, and regardless of how knowledgeable anybody is about > anything. This is blatantly obvious to anyone who actually _thinks_ > about it. Take it to comp.lang.platonic. Joe From rmb25612 at yahoo.com Wed Mar 10 19:04:11 2004 From: rmb25612 at yahoo.com (Richard James) Date: 10 Mar 2004 16:04:11 -0800 Subject: Searching comp.lang.python References: Message-ID: <2c60f0e0.0403101604.2dd82a1b@posting.google.com> "Mulugeta Maru" wrote in message news:... > I went to the Python site to search posts made by group members. I am not > sure whether there is this functionality exists. If it does could you please > help a new comer. > > Thanks. > > MM Use this link: http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&group=comp.lang.python The group search box is at the top of the webpage. -- R.J. From vedranf at riteh.hr Thu Mar 11 19:36:25 2004 From: vedranf at riteh.hr (Vedran Furac) Date: Fri, 12 Mar 2004 01:36:25 +0100 Subject: Video module? References: Message-ID: Mickel Gr?nroos wrote: > Hi! > > Is anybody aware of some good Python module for playing video (mpeg-2, > mov, avi or similar)? I looked at pygame.movie, but it does not seem maybe this: From fowlertrainer at anonym.hu Mon Mar 1 10:40:54 2004 From: fowlertrainer at anonym.hu (fowlertrainer at anonym.hu) Date: Mon, 1 Mar 2004 16:40:54 +0100 Subject: KinterBasDB problems in Linux Message-ID: <6829126481.20040301164054@anonym.hu> Hello ! Very interesting thing: When I copy this script to another dir, it is working, but in this directory is not working. Only different is to this dir is used by an symlink. The python is not working good with symlinked dirs ??? >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> So: in Debian Sarge, some interesting thing happened. When I start python with: /usr/bin/python it is starting the py2.3 When I write this: import kinterbasdb the py2.3 is not say this: "import _kinterbasdb as _k" "ImportError: No module named _kinterbasdb" only do the import. So it is working. BUT ! If I write this line to a script: #!/usr/bin/python import kinterbasdb this error I get: "import _kinterbasdb as _k" "ImportError: No module named _kinterbasdb" Why ? What I do wrong ?????? Anybody know it ? Monday, March 1, 2004, 12:15:04 PM, you wrote: UG> I don't have any proplems with cross-platform issues. UG> Working on Win2000 + suse linux 8.2, 9.0 and FB 1.5, UG> kinterbasdb from http://sourceforge.net/projects/kinterbasdb/ I try with apt-get install "kidb", and do same things. UG> Try this version! UG> Uwe UG> fowlertrainer at anonym.hu wrote: >> Hello ! >> >> I have a problem. >> I create my projects in Windows, and I write a database synchronizing >> utility for copy a gdb changes to another gdb. Some of these products >> is need to run in linux. >> >> I'm very tired, because I download (apt-get install >> python2.3-kinterbasedb) the module, what working good in Windows, but >> in linux I get this message when I try to start my script: >> >> bha:/kepes# ./syncmdb2teldb.py >> Traceback (most recent call last): >> File "./syncmdb2teldb.py", line 2, in ? >> import kinterbasdb >> File "/home/fixshare/kepes/kinterbasdb/__init__.py", line 41, in ? >> import _kinterbasdb as _k >> ImportError: No module named _kinterbasdb >> bha:/kepes# >> >> >> The test file is: >> File: syncmdb2teldb.py Col 0 321 bytes 100% >> #!/usr/bin/python >> import kinterbasdb >> >> import sys >> # Base datas >> >> srcdb=kinterbasdb.connect(dsn='192.168.1.17:/mpanni/bha/database/teldata.gdb',us >> er='sysdba',password='m',charset="win1250") >> desdb=kinterbasdb.connect(dsn='192.168.1.17:/mpanni/bha/database/mpanni.gdb',use >> r='sysdba',password='m',charset="win1250") >> print "ok" >> >> 1Help 2UnWrap 3Quit 4Hex 5Line 6RxSrch 7Search 8Raw 9Unform 10Quit >> >> In the package dir: >> >> bha:/usr/lib/python2.3/site-packages/kinterbasdb# ls -l >> total 152 >> -rw-r--r-- 1 root root 29691 Jul 19 2002 __init__.py >> -rw-r--r-- 1 root root 32036 Feb 27 17:44 __init__.pyc >> -rw-r--r-- 1 root root 32036 Feb 27 17:44 __init__.pyo >> -rw-r--r-- 1 root root 56072 Sep 28 16:32 _kinterbasdb.so >> bha:/usr/lib/python2.3/site-packages/kinterbasdb# >> >> >> What I do wrong, or what is it ???? >> (The Zope with Kinterbasdb is working good in this linux, so no >> connection problem...) >> >> thanx for every help ! >> -- Best regards, fowlertrainer mailto:fowlertrainer at anonym.hu From bblackmoor at spamcop.net Sun Mar 7 16:17:22 2004 From: bblackmoor at spamcop.net (Brandon Blackmoor) Date: Sun, 07 Mar 2004 16:17:22 -0500 Subject: Python as replacement for PHP? In-Reply-To: References: <403fa54b@news.zianet.com> <99dce321.0403031518.56f61c7c@posting.google.com> Message-ID: R. Rajesh Jeba Anbiah wrote: > > HTH. HAND. Is this your signature or nickname, or does it perhaps mean something in your native language (like "ciao", for example)? I assumed it was your signature, but it doesn't resemble your name, so I thought it may mean something else. Perhaps it's like those "geek codes" some people put in their signatures? bblackmoor 2004-03-07 From cmg at dok.org Tue Mar 23 15:04:55 2004 From: cmg at dok.org (Chris Green) Date: Tue, 23 Mar 2004 15:04:55 -0500 Subject: difflib + object sequences Message-ID: Hello Folks, I'm attempting to use difflib's SequenceMatcher to pull out the matching subsequences of a list of objects. Code is below. object matches a[0] and b[0] match for 3 elements a[5] and b[5] match for 0 elements integer matches a[0] and b[0] match for 3 elements a[4] and b[4] match for 1 elements a[5] and b[5] match for 0 elements Note that the expected matches at a[4] and b[4] are missing with the object. I've narrowed this down to difflib.py ( both 2.3 and CVS's ) using a dictionary on the backend and hash(Misc(1)) != hash(Misc(1)). Is this expected behavior? http://sourceforge.net/tracker/?func=detail&atid=105470&aid=660098&group_id=5470 shows some coments on objects inheriting a default __hash__ ret self(id). If I define __hash__ as return hash(self.val), things work as expected. Now the question is, what should I log as a bug? The existing bug 660098? Documentation could use an example like this test? Something busted with difflib? Thanks for your help, Looking forward to pycon tommorrow. Chris Code: from difflib import SequenceMatcher class Misc(object): def __init__(self, val): self.val = val def __cmp__(self, other): return cmp(self.val,other.val) def __str__(self): return str(self.val) def test_sm(seqA, seqB): # new sequence matcher with no junk defined sm = SequenceMatcher(None, seqA, seqB) blockList = sm.get_matching_blocks() for block in blockList: print "a[%d] and b[%d] match for %d elements" % block if __name__=='__main__': # define 2 very similar sequences with a cmp operator objA = [Misc(1), Misc(2), Misc(3), Misc(96), Misc(24)] objB = [Misc(1), Misc(2), Misc(3), Misc(42), Misc(24)] intA = [1,2,3,96,24] intB = [1,2,3,42,24] print "object matches" test_sm(objA,objB) print "integer matches" test_sm(intA,intB) -- Chris Green Fame may be fleeting but obscurity is forever. From dmq at gain.com Sun Mar 14 07:14:20 2004 From: dmq at gain.com (David MacQuigg) Date: Sun, 14 Mar 2004 05:14:20 -0700 Subject: Deprecating reload() ??? References: <09b350henbtk9vnai0v7fhtbsqbmubl7vn@4ax.com> <7cj4c.2733$G3.21896@localhost> <8ok3505b3b3g22bk8ci6iagptqav2cfi6r@4ax.com> <6kk6501shlve52ds2rjdopa73jhpchprg3@4ax.com> Message-ID: On Sat, 13 Mar 2004 14:27:00 -0600, Skip Montanaro wrote: > David> I'm not sure at this point if an improved reload() is worth > David> pursuing, ... > >I wrote something and threw it up on my Python Bits page: > > http://www.musi-cal.com/~skip/python/ I get AttributeErrors when I try the super_reload function. Looks like sys.modules has a bunch of items with no '__dict__'. I'll work with Skip via email. -- Dave From egusenet at verizon.net Thu Mar 25 12:06:06 2004 From: egusenet at verizon.net (Eric) Date: Thu, 25 Mar 2004 12:06:06 -0500 Subject: [Slightly OT] Re: Voting References: <95aa1afa.0403230250.4c9da7a2@posting.google.com> <1060m0593q1uo0d@news.supernews.com> <10637ibo30epo6f@news.supernews.com> <89feb3ba.0403241233.32ea8604@posting.google.com> Message-ID: <1gb7bj1.xgiqcjp3ro1iN%egusenet@verizon.net> Joe Mason wrote: > In article <89feb3ba.0403241233.32ea8604 at posting.google.com>, Eric wrote: > > Joe Mason wrote in message > >news:... > > > >> (The crux of the flamewar is that Condorcet tends to elect > >> "compromise candidates" who are few peoples' favourite but palatable to > >> most, while IRV is more likely to elect people that are the first choice > >> of a large block but hated by others. Which is preferable is a matter > >> of philosophy.) > > > > > I cannot see how IRV and a Condorcet method would differ should a > > certain candidate receive a large block of first place votes. For if a > > certain Candidate is the first choice of a large block, it has a > > distinct advantage in both IRV and Condorcet over all the other > > candidates, but will not necessarily be the winner in either. > > I think the contentious scenario was two large opposed blocks and a > small centrist block (C): > > [redid the ballots to put them in a form accepted by online calculators] > > 49:A>C>B > 48:B>C>A > 3:C > > In Condorcet, we get: > [snip] > So C is the winner. But, say the IRV proponents, only 3% of the > population actually want C to win! Yes, I understand this is the claim that some IRV proponents would make. However, no such definitive statement can honestly be asserted based on those ballots. With most (if not all) ranked ballot methods (including Condorcet and IRV), if a voter truly does not want a Candidate to win, the way the indicate that is by leaving that Candidate unranked. In this case, the A & B voters did not leave C unranked. Both groups clearly stated that they preferred C to their primary opponent. What we do not know, because neither IRV nor Condorcet collects the strength of the preference (there are inherent problems with doing such a thing which is beyond the scope of this message), is how strong the preference is for the A & B voters for C rather then their primary opponent. For example, it could be that: (The numbers in parenthesis indicate the strength of how much the candidates are liked on a linear 0 - 100 scale) 49 A(100) > C(99) > B(0) 48 B(100) > C(99) > A(0) 3: C(100) Should this be true, one would be hard pressed to develop a credible and compelling argument that C should not be the winner. However, it is also possible that: 49 A(100) > C(1) > B(0) 48 B(100) > C(1) > A(0) 3: C(100) In which case, an argument can be made that C should not be the winner. But, like I stated, neither IRV nor Condorcet collect such information, so, what is the fairest way to deal with this? Both IRV and Condorcet both assume that your top choice has a strength of 100. However, they differ greatly in the assumptions made about lower preferences. With IRV, if your top choice is eliminated, your second choice is automatically promoted to a strength of 100, regardless of how you actually feel about that candidate. For example, say a voter had voted (I've included theoretical preference strengths): A(100) > B(1) > C(0) but that A was eliminated. IRV recasts their vote as: B(100) > C(0) A Condorcet method assumes that the strengths of the preferences should be distributed evenly among the ranked candidates. I find this assumption to be far more compelling in the general case because it is simply not believable that all the A & B voters in any genuine situation would have the exact same feelings towards the other candidates. Condorcet makes assumptions about the average feeling towards the other candidates. It is also interesting to note that nearly every other ranked ballot method will also select C as the winner. IRV seems to stand alone in the assertion that the winner should be someone other then C. Based on: http://cec.wustl.edu/~rhl1/rbvote/calc.html http://condorcet.ericgorr.net/ http://www.duniho.com/remote-mamcalc.php > Anyway, the real question in this forum is whether Condorcet is a good > method for voting on a PEP. If you would like to see how Condorcet and IRV behave with in genuine ranked ballot elections, you can check out: http://ericgorr.net/library/tiki-index.php?page=BallotArchives If anyone is aware of other places where ranked ballots from real elections can be collected, let me know. I am working on collecting the ranked ballots for the uk.* USENET hierarchy votes. From jacek.generowicz at cern.ch Mon Mar 8 04:24:13 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 08 Mar 2004 10:24:13 +0100 Subject: OT(Slightly): Thanks to Python. References: <104emss6ca09l45@news.supernews.com> Message-ID: JanC writes: > Jacek Generowicz schreef: > > > * (defmethod foo ((x integer)) > > > * (defmethod foo ((x string)) > > > The ANSI standard for the _dynamically typed_ language shown above, > > Maybe someone can explain, Sure ... > but the above doesn't look like "dynamic typing" to me...? In order to preserve us from a long thread full of irrelevancies, maybe I should first ask you to tell me what _you_ mean by dynamic typing. However, I'll take the plunge ... My definition of dynamic typing can be summarized as follows: "Objects know their own type. Variables do not have a type." So, let's try the following code (defmethod foo (x) (format t "~&~s has some type or other." x)) (defmethod foo ((x integer)) (format t "~&~s is an integer." x)) (defmethod foo ((x string)) (format t "~&~s is a string." x)) (loop for item in (list 1 "hmm" (list 1 2) (make-hash-table) (vector)) do (foo item)) And we get the output: 1 is an integer. "hmm" is a string. (1 2) has some type or other. # has some type or other. #() has some type or other. - Note that item (a variable) is undeclared; nowherere do you specify it's type. (That doesn't mean that it's dynamically typed though - see implicitly statically typed languages such as ML, for counterexamples.) - Note that item is bound to objects of completely different types (integer, string, list, hash-table and array, in this case) at different times. (This _does_ mean that it's dynamically typed.) Perhaps you thought that it doesn't look like dynamic typing because of superficial similarities with C++ method overloading: void foo(std::string x) { std::cout << x << " has type string." << std::endl; } void foo(int x) { std::cout << x << " has type int." << std::endl; } The important difference is that C++ does this "dispatch" at _compile time_, and in order to do it, you must tell the compiler, in the source code, a priori, the type with which you will be calling the function, by providing a type declaration of the variable which you will be passing to the function. For example: int i; // I'm telling the compiler that i will always be an int ... foo(i) // The compiler decides (at compile-time) which version of foo // will be called (at run-time), on the basis of the type // I gave above. i = "hello" // Error, I promised the compiler that i would always be // an int and now I'm breaking my promise. Contrast this to our mystery language: (let ((i 2)) ; No type declaration (foo i) ; Dispatch done at runtime (setq i "hello") ; Variable rbound to object of different type (foo i)) ; Another runtime dispatch, different method called Does this help ? From RobMEmmons at cs.com Wed Mar 10 22:03:23 2004 From: RobMEmmons at cs.com (Robert M. Emmons) Date: Wed, 10 Mar 2004 21:03:23 -0600 Subject: Python scripting for GNumeric In-Reply-To: References: Message-ID: <404FD6FB.2040100@cs.com> > I recommended two of my friends currently using Excel and VBA Gnumeric > as a replacement. It seems they are using a lot of VBA in conjunction > with Excel. You may be better of using Open Office. It has a spreadsheet call Calc. The spreadsheet can be programed in JavaScript, Basic, and Python among other's I believe. I have not done this, but it should be equivalent to MS Office generally. Only concern I have is that all of this is "developmental" meaning recent... which means programs can get the job done, but other's may find the documentation is a little thin. OO runs on linux and Windows, and maybe mac. Rob From aahz at pythoncraft.com Sun Mar 28 21:44:42 2004 From: aahz at pythoncraft.com (Aahz) Date: 28 Mar 2004 21:44:42 -0500 Subject: Python for large projects References: <1060p59d9rg9819@corp.supernews.com> <8ef9bea6.0403260837.72a8fade@posting.google.com> Message-ID: [quoting unsnipped, voting this for post of the week] In article <8ef9bea6.0403260837.72a8fade at posting.google.com>, Hung Jung Lu wrote: > >I use C++ and Python everyday. Let us be fair and point out some good >things about each of them. > >(a) In compiled language like C++, changing function prototypes and >variable names is comfortable, because the compiler will find all >those spots that you need to change. In Python, you do not have the >same level of comfort. Sure, there are other techniques, but it's >different than clicking a button. > >(b) Cameron said something very true in my opinion: for large >projects, you want Python. But he said so without giving more details. >So let me add some comments. > >In my opinion, the essence of software development is code/task >factorization. It seems such a trivial concept, but if you really >really think about it, goto statements, loops, functions, classes, >arrays, pointers, OOP, macros/templates, metaprogramming, AOP, >databases, etc, just about every single technique in programming has >its base in the concept of code/task factorization. Take for instance >classes and inheritance, basically, you factor out the common parts of >two classes and push it up into a common parent class. To go one level >deeper, my belief is that at the bottom, all human intellectual >activities are based on factorization: no more, no less. > >In large projects, you'll find that you need to factor out even more. >Let us take an example. Suppose you write an application, and later on >you realize that you need to make it transactional: that is, if some >exceptions happen, you want to roll back the changes. Now, this kind >of major after-thought is terrible for languages without >metaprogramming capabilities. To add a new feature, you will have to >make modifications in hundreds or thousands of spots. Another example, >suppose your software is versioned, more over, you have different >versions for the application and for the data file format, and your >application needs to work with legacy file formats. Again, without >metaprogramming capabilities, your code will have many redundant lines >of code, or be cluttered with tons of if-statements or >switch-statements. Another similar problem: you have several different >clients that buy your application, and they want some different extra >features. Again, without metaprogramming, your code will be either >hard to code (using virtual functions, function pointers, and/or >templates in C++), or will be cluttered with if-else- and switch- >statements (a terrible practice that will make your code >unmaintainable.) > >As your project grows more and more complex (become threaded, many new >clients requirements, support for legacy versions, using distributed >computing in a cluster, etc.) you will realize more and more that you >need to factorize efficiently, otherwise your pain will be unbearable. > >When you have reached that point, you'll come to appreciate simplicity >and purity in a language. Frankly, Python is good but still not good >enough. > >For large projects, if you use a rigid language, then your best bet is >to use tons of programmers coding trivial interfaces and APIs to make >up for the shortcomings of the language. In flexible languages like >Python, you often can use metaprogramming features to factor out the >common areas. At that point, I think that issues like automatically >finding name changes as I mentioned in point (a) become small issues, >because you will have bigger concerns. The fact that you may miss a >name change or function header change is not the thing that will kill >you. The fact that your entire system is unmaintainable is the thing >that will kill you. Don't look at individual bugs when you are talking >about large projects, because your worry should not be there: your >worry should be focused on how to make your system maintainable. Bugs >can and will be fixed. But if your language does not allow you to >factorize efficiently, at the end of the day, that's what's going to >kill you. > >regards, > >Hung Jung -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "usenet imitates usenet" --Darkhawk From paschen at mavd.de Thu Mar 4 06:21:49 2004 From: paschen at mavd.de (Bjoern Paschen) Date: Thu, 04 Mar 2004 12:21:49 +0100 Subject: Calling C programs References: Message-ID: <1078399266.860576@mail.mavd.de> C GIllespie wrote: > I have a simple C program which outputs a string. I want to be able to > call this progam from python and assign the output to a variable. What's > the best way to do this? > I've tried > os.system('/tmp/hello') > os.execv('/tmp/hello',[' ']) > but I can't seem to store the return value. One possible way is to use os.popen(). http://www.python.org/doc/current/lib/os-newstreams.html Bjoern From joe at notcharles.ca Sun Mar 28 11:28:18 2004 From: joe at notcharles.ca (Joe Mason) Date: Sun, 28 Mar 2004 16:28:18 GMT Subject: Newbie Class Questions References: <94CdnVqi7o8rn_vdRVn-vg@centurytel.net> <95aa1afa.0403280715.18292937@posting.google.com> Message-ID: In article <95aa1afa.0403280715.18292937 at posting.google.com>, Michele Simionato wrote: > Those links refer to the drafts on my personal home page. They could > disappear. It is much better to refer to the published versions (which > are also fancier): > > http://www-106.ibm.com/developerworks/library/l-pymeta.html > http://www-106.ibm.com/developerworks/library/l-pymeta2 Oh, sorry. I didn't realize they were drafts - I figured the developerworks articles were syndicated. I thought it would be more salutory to point to your personal copies. Joe From http Sat Mar 20 20:51:06 2004 From: http (Paul Rubin) Date: 20 Mar 2004 17:51:06 -0800 Subject: SHA-based subclass for random module References: <7xptbgjpk4.fsf@ruckus.brouhaha.com> <5d83790c.0403190105.69ca83e7@posting.google.com> <7x8yhxtast.fsf@ruckus.brouhaha.com> <5d83790c.0403192207.1389f4bb@posting.google.com> <405cefb6$0$120$3a628fcd@reader3.nntp.hccnet.nl> Message-ID: <7x4qsjnf1x.fsf@ruckus.brouhaha.com> anton at vredegoor.doge.nl (Anton Vredegoor) writes: > I wonder why it is necessary to do the bit twiddling once one has > chosen to multiply by a fraction instead of directly putting the bits > inside a float. If 1.0 / 2**53 is just some arbitrary value (and why > not: A floats' smallest value is a lot smaller than that?) then we can > generate integers of other sizes and divide them by other floats, for > example: I think life gets very complicated once you start trying to generate denormalized floats. They aren't uniformly distributed on the unit interval, so if you make random numbers by dividing uniformly distributed integers by some constant, you'll get way too many denorms. If your application is using so many random numbers that it much chance of ever seeing one below 2**-53, maybe you need to use extended precision or something. Note this whole thing gets into the precise properties of machine floats, and Python in principle is not supposed to be IEEE-dependent. (The magic number 2**-53 is an IEEE artifact). From No.Spam.mc at No.Spam.mclaveau.No.Spam.com Mon Mar 29 05:12:41 2004 From: No.Spam.mc at No.Spam.mclaveau.No.Spam.com (Michel Claveau/Hamster) Date: Mon, 29 Mar 2004 12:12:41 +0200 Subject: Orders of magnitude References: Message-ID: Bonjour ! Les dictionnaires sont plus rapides lors de la recherche ("... in ..."), car il y a utilisation de la clef. Avec une liste, la recherche est s?quentielle. in english (try) : For search (... in ...) : - dictionnary use key search - list use sequentiel search @-salutations -- Michel Claveau From hufman at cobalty.com Wed Mar 3 22:04:27 2004 From: hufman at cobalty.com (Walter Huf) Date: 3 Mar 2004 21:04:27 -0600 Subject: Sending binary data over CGI Message-ID: Okay, I'm busy making a wonderful cgi program, and everything is working wonderfully so far. I'm using the standard cgi library and the Cookie library and they have been a huge help. Thanks to those who have created them! However, if I try to send binary data, like jpgs, through cgi, the data gets corrupted in a very small manner. Whenever my program sends the character 10, it gets converted to character 13+character 10. I found out this only happens when I send data to stdout. If I send the data to a standard file object, it works fine. However, with the stdout, the problem arises. Here is the relevant part of the code: ---Begin from sys import stdout def senddownloaddata(file): #file is a pointer to an open file line=file.read(1) #file pointer opening and closing are while len(line)==1: # handled outside of function stdout.write(line) line=file.read(1) stdout.write(line) ---End Now the code that copies files: ---Begin curdir="C:\windows\desktop" temp=file(curdir+"/bach.it","rb",0) out=file(curdir+"/bach2.it","wb",0) data=temp.read(1) while len(data)==1: out.write(data) data=temp.read(1) temp.close() out.close() ---End I'm using Windows 98 SE with an Apache 2.0.44 Win32 server. That all works fine. The first line of the interactive script says: PythonWin 2.3.2 (#49, Nov 13 2003, 10:34:54) [MSC v.1200 32 bit (Intel)] on win32. I'm assuming that means I have Python 2.3.2. Everything else in the program works very nice, except for the data corruption. Please help me with this problem. It has me stumped. Thanks in advance! --Walter Huf-- hufman at cobalty.com -----= Posted via Newsfeeds.Com, Uncensored Usenet News =----- http://www.newsfeeds.com - The #1 Newsgroup Service in the World! -----== Over 100,000 Newsgroups - 19 Different Servers! =----- From roccomoretti at hotpop.com Wed Mar 17 14:11:18 2004 From: roccomoretti at hotpop.com (Rocco Moretti) Date: Wed, 17 Mar 2004 13:11:18 -0600 Subject: PEP 328: Imports: Multi-Line and Absolute/Relative In-Reply-To: References: <104q64b2uf3nl0b@news.supernews.com> Message-ID: Aahz wrote: > In article <104q64b2uf3nl0b at news.supernews.com>, > John Roth wrote: >>A reference beginning in the current directory is thus: >> >>import *.spam.eggs > > > That's functionally equivalent to the suggested > > import .spam.eggs I don't see the above syntax referenced in the PEP. As I read the PEP, I would have thought the above would have been prohibited. Quoth the PEP: """There does seem to be agreement that relative imports will require listing specific names to import (that is, import foo as a bare term will always be an absolute import).""" I took this to mean that relative imports would require the "from ... import ... [as ...]" syntax ("listing specific names" of variables in a module to import), and "import ..." would always be absolute (importing a module as a "bare term" without reference to specific variables to import). I take it since you are the PEP author, this is a mistaken impression. But I am at a loss to figure out what exactly is implied by the quoted phrase above. -Rocco From sc0rp at hot.pl Wed Mar 24 03:29:42 2004 From: sc0rp at hot.pl (Jacek Trzmiel) Date: Wed, 24 Mar 2004 09:29:42 +0100 Subject: CGI with python help newbie References: <406139F0.F5FF2E79@hot.pl> Message-ID: <406146F6.ECBBF992@hot.pl> Amy G wrote: > it simply prints the code to the browser when I go to the page. Install mod_python first, then add required directives to http.conf. You can find details in mod_python manual. Best regards, Jacek. From ajsiegel at optonline.com Mon Mar 15 15:07:45 2004 From: ajsiegel at optonline.com (Arthur) Date: Mon, 15 Mar 2004 20:07:45 GMT Subject: loop scope References: Message-ID: On Mon, 15 Mar 2004 10:26:41 -0800, Donn Cave wrote: > >Taking list comprehensions, because that's what the original >post took at least as an example and because that's the only >case that is new enough to half seriously consider changing - > > t = f(a/c) > ... # and then later, > sl = [t * t for t in range(3)] > >In this case, I would argue that it's an error for t to escape >the expression scope _because_ it's used outside that scope - >actually I think that was where we came in. Yeah, I guess that is where the danger is, if I had been previously bound "t" and had it rebound against my expectations Which was not exactly the case I fell into. Thinking about it, I - and hopefully others - at least have an intuitive sense of knowing what they don't know. I guess there were always enough variable names at my disposal that I have avoided using something as a iterator variable that I have used for some other purpose in the same scope. Just to be safe. And knowing I don't fully understand what is happening under the covers.. Good boy. me. Art > My personal view >is that a list comprehension should have its own internal scope, >period, but is that what `intuition' would lead most Python >programmers to expect? I don't know. > > Donn Cave, donn at u.washington.edu From newsgroups at jhrothjr.com Mon Mar 29 16:04:06 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 29 Mar 2004 16:04:06 -0500 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><406829FF.5060304@mlug.missouri.edu><106gg1jifa2n9c2@news.supernews.com> Message-ID: <106h3tg3rh7as7e@news.supernews.com> "Terry Reedy" wrote in message news:mailman.73.1080588424.20120.python-list at python.org... > > "John Roth" wrote in message > news:106gg1jifa2n9c2 at news.supernews.com... > > I think you misunderstood. There is no "standard" length of > > a tab. A tab is supposed to insert (or otherwise render the > > equivalent of inserting) enough spaces to go to the next "tab stop", > > which by convention is a multiple of 8 columns on a fixed > > width mechanical typewriter. This is where tabs originated. > > Actually, the mechanical typewrite standard (in US, 1960s) was every 5 > spaces == 1/2 inch (10 chars per inch, fixed). That was also the standard > paragraph indent. WordPerferct, for one program, stuck with 1/2 inch even > as it accommodated different fixed and variable pitched fonts. I remember > thinking 8 spaces a bit weird when I first used Unix (early 80s). You're right about that, although that was only for the 1st tab. After that, it was whereever you needed them for columns. > Power-of-2 4 and 8 are computerisms. Don't remember about Teletypes, nor > about typewriters in non-inch countries. I don't think it was a power of two thing. I very vaguely remember some papers on the "ideal" tab spacing for inserting tabs in TTY data streams. They were there to shrink runs of spaces to something the mechanical teletypes could move over faster. Some of the computations to insert a tab and then a specific number of nulls to compensate for the exact mechanics at the other end got quite intricate. John Roth > > Terry J. Reedy > > > > From nid_oizo at yahoo.com_remove_the_ Mon Mar 1 11:10:59 2004 From: nid_oizo at yahoo.com_remove_the_ (Nicolas Fleury) Date: Mon, 01 Mar 2004 11:10:59 -0500 Subject: Garbage collector and threads Message-ID: Hi everyone, I just discovered, correct me if I'm wrong, that as long as a threading.Thread is running, its destructor will not be called, because it is referring to himself. So if I have something like: class MyThread(threading.Thread): def __init__(self): self.cancelEvent = threading.Event() threading.Thread.__init__(self) def __del__(self): self.cancel() def run(self): self.cancelEvent.wait() def cancel(self): self.cancelEvent.set() I must call cancel from the outside if I want the destructor to be called (note that I don't want deamon threads). I can make a wrapper over threading.Thread to have the behaviour I want: have a thread with __del__ called when it is not referred by another thread. But my question is, and I don't have an overall vision of the issue at all, should that be the default behaviour anyway? Regards, Nicolas From theller at python.net Fri Mar 12 12:05:21 2004 From: theller at python.net (Thomas Heller) Date: Fri, 12 Mar 2004 18:05:21 +0100 Subject: py2exe win32all: Can write, but not read FileVersion ... References: <4050fab2_5@127.0.0.1> Message-ID: [about version resources created by py2exe] "Roger Upole" writes: > The language and codepage are getting reversed in the resource created. > If you switch them in the call to GetFileVersionInfo, everything shows up. > Roger Cool. So it seems this fix to py2exe\resources\VersionInfo.py makes everything fine: Replace this line VarFileInfo(0x040904B0)]) with this: VarFileInfo(0x04B00409)]) Thanks, Thomas From balex at sympatico.ca Tue Mar 23 23:36:36 2004 From: balex at sympatico.ca (Brian) Date: Tue, 23 Mar 2004 23:36:36 -0500 Subject: nomenclature for units Message-ID: This may seem trivial, but ... I'm looking for the correct nomenclature to describe project code and its corresponding testing code. For instance, in a manual I might say something like "Every unit possesses its own unit containing code to establish correctness ..." Every unit? possesses its own unit? ... Many thanks, Brian. From grahamd at dscpl.com.au Wed Mar 3 00:53:48 2004 From: grahamd at dscpl.com.au (Graham Dumpleton) Date: 2 Mar 2004 21:53:48 -0800 Subject: xmlrpclib timeouts References: Message-ID: p2esp wrote in message news:... > Hello, > > I'm using the xmlrpclib module to contact an XMLRPC > server that takes a long time to send results back. My > client timeouts. > > The question is whether there is a way to have an > xmlrpclib client that never timeouts. I have been > searching for some code examples on how to do that, > but I could not find any in the xmlrpclib > documentation. > > Thanks for any hints. Hmm, I always thought that the XML-RPC client in the xmlrpclib module was written already to do exactly that. Ie., it will block until it gets a response. There is no timeout functionality within it. Is the server you are talking to within your own network, or are you going through some sort of HTTP proxy either explicitly or implicitly, or even some sort of router equipment that does special things with HTTP requests. HTTP proxies often have timeouts such that if a request takes too long to get back a response, it will drop the connection. In other words, the problem may not be with the XML-RPC client but some part of the intermediate network. Also, what is the XML-RPC server written in? Could it perhaps be dropping the connection if the server side code takes too long? From max at alcyone.com Tue Mar 16 19:43:31 2004 From: max at alcyone.com (Erik Max Francis) Date: Tue, 16 Mar 2004 16:43:31 -0800 Subject: Result of ``a is b'' References: <40200384.0403151632.35496ee6@posting.google.com> <40200384.0403161255.7fca7a8c@posting.google.com> Message-ID: <40579F33.CB547F8@alcyone.com> Axel Boldt wrote: > David MacQuigg wrote > > > >>> x = 'akdijfkdienlskfi' > > >>> y = 'akdijfkdienlskfi' > > >>> x is y > > True > > >>> x = 'a b' > > >>> y = 'a b' > > >>> x is y > > False > > Wow. So it seems that the action of "is" on immutables is unspecified > and implementation dependent, thus useless to the programmer. It's less useful for testing mere equivalence, yes, because that's not what it's intended to do. It tests identity. Here whether the two strings are not just equal but _identical objects_ is an implementation detail. If you ever rely on this behavior, your code will not be portable to other implementations of Python. -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE \__/ Here day fights with night. -- (the last words of Victor Hugo) From jmeile at hotmail.com Thu Mar 11 10:39:59 2004 From: jmeile at hotmail.com (Josef Meile) Date: Thu, 11 Mar 2004 16:39:59 +0100 Subject: Python style guidelines In-Reply-To: References: <3064b51d.0403101112.3449e987@posting.google.com> <405035a3$1@pfaff2.ethz.ch> Message-ID: <405087fc$1@pfaff2.ethz.ch> >>>>>a='test' >>>>>if a.find('foo'): >> >>... print "foo was found" >>... >>foo was found > > > a.find does not return a boolean, so that particular style guideline > does not apply. I know, but I found this on the Zope source, which means that there is people thinking that the False on python includes negative values. From droog at orange.gov Wed Mar 17 22:07:05 2004 From: droog at orange.gov (droog) Date: Thu, 18 Mar 2004 03:07:05 GMT Subject: New to Python. References: Message-ID: I was looking for the simpliest way of doing it. This is what I tried to do. f = open('C:\Python23\Samples\Bob.txt', 'r') counter = 0 while True: line = f.readline() if len(line) == 0: break if line.find('customer'): counter = counter + 1 print 'Found it ' + str(counter) On Thu, 18 Mar 2004 02:53:48 GMT, droog wrote: > >Hello! > >I have just started learning python and encountered a problem. >All I wanted to do, was to open a text file search and count the >number of occurances of a single word and print that count. >Thanks for help. From kbk at shore.net Fri Mar 19 00:28:15 2004 From: kbk at shore.net (Kurt B. Kaiser) Date: Fri, 19 Mar 2004 05:28:15 GMT Subject: Help on Tkinter installation References: Message-ID: <87wu5hv21c.fsf@hydra.localdomain> John Slimick writes: > Prior to this I installed ActiveTCL8.4 . > > So I made what I thought were the appropriate > changes to the "tkinter" section of Setup, I went up > a level (to /usr/src/redhat/SOURCES/Python-2.3.2), > did a "make" and this is what I got: > > file libtk8.4.so does not exist > > Well, when I do a locate, I find libtk8.4.so > in > > /usr/local/ActionTcl/lib/libtk8.4.so > > So I am caught with some kind of path problem. > > Any ideas or suggestions? Your tk library is installed in a very non-standard location. Python can't find it. I suggest you install tcl and tk from the RH rpms, here's tk, you can search for tcl: http://speakeasy.rpmfind.net/linux/rpm2html/search.php?query=tk&submit=Search+...&system=&arch= Then put setup back the way it was and try again. If you are going to use ActiveState products, then install the whole package including their version of Python. If you do that, then direct further questions to them. -- KBK From dj00302003 at yahoo.com Wed Mar 3 15:04:46 2004 From: dj00302003 at yahoo.com (Jay Davis) Date: 3 Mar 2004 12:04:46 -0800 Subject: Automatic web form transactions Message-ID: <1d17eeb7.0403031204.466e4ca@posting.google.com> We've been using the excellent ClientForms module with urllib2 to read forms, fill them in, and then submit with 'response = urlopen(form.click())'. The process usually works very well. But some forms, which work straightforward in a browser, don't work with form.click(). For instance, in one simple form the response is: "Sorry, this form cannot be posted to from external source." I'm wondering if the reason it generates that response is because it is looking for a standard browser. In that case, I should be able to send some browser string that it likes. I don't think I can use the webbrowser module because while that lets you launch a browser, it doesn't have an interface to fill in forms, click the submit button, and so on. One obvious long term solution is for me to learn much more about the details of html form processing, especially low level details in the htmllib and ClientForm modules. But a nice quick solution would be helpful too. If its any use, the offending form is:
New Loc
Thanks, J From uche at ogbuji.net Sun Mar 14 23:02:30 2004 From: uche at ogbuji.net (Uche Ogbuji) Date: 14 Mar 2004 20:02:30 -0800 Subject: .lstrip().rstrip() -> .strip() and other String/Unicode suggestions References: <14b36d18.0403050216.ad3a7f5@posting.google.com> <877jxzv10y.fsf@mrbun.watterson> Message-ID: nikita_raja at yahoo.com (Sam Smith) wrote in message news:... > def characters(self, content): > self.content = self.content.lstrip().rstrip() + " " + content FYI, you can just use the following, which is equivalent: self.content = self.content.strip() + u" " + content Notice how I also maintain the Unicode object character of self.content Overall, it would be much more efficient to use cStringIO or even treat self.content as a list and use f.write(u' '.join(ReadXML.content)) Watch out for encoding issues on write if you do (rightly) stick to Unicode objects: use a codec-wrapped output stream. Concatenating strings with + is notoriously wasteful. See, for example: http://mail.python.org/pipermail/xml-sig/2000-August/003198.html --Uche http://uche.ogbuji.net From smallbee at rediffmail.com Mon Mar 15 09:51:39 2004 From: smallbee at rediffmail.com (Somesh Bartakkay) Date: 15 Mar 2004 06:51:39 -0800 Subject: Error Message & IDLE - PyShell Message-ID: <8f198e47.0403150651.12f973cc@posting.google.com> i wanna write python scripts in my LOCAL language, and wanna collect the error msg in same language/font with IDLE or any other IDE ..can help me ? how its possible without touching python interpreter src code ? ThanX in +vance ! From kobayashi at netcourrier.com Mon Mar 29 04:33:33 2004 From: kobayashi at netcourrier.com (kobayashi) Date: 29 Mar 2004 01:33:33 -0800 Subject: Readonly attributes ... Message-ID: Hi all python users, A question about readonly attributes once again, but even reading the threads about "properties" and "descriptors", I can't find exactly what I want. Let a developper to write the class class A(object): def __init__(self): self.x = 1 self.setX(2) return def getX(self): return self.__x def setX(self, value): self.__x = value return x = property(getX, setX) pass Of course, the developper can set the attribute 'x' in the class ... Now, the user part : a = A() print a.x a.x = 1 # I want this operation to raise print a.x a.setX(23) # I want this operation to raise too !! print a.getX() I can't find a way to do that ... but may be I've missed something ! Cheers, K. From wmwd2zz02 at sneakemail.com Thu Mar 11 22:34:51 2004 From: wmwd2zz02 at sneakemail.com (Greg Ewing (using news.cis.dfn.de)) Date: Fri, 12 Mar 2004 16:34:51 +1300 Subject: 2D List comprehension & replace In-Reply-To: References: Message-ID: Paul McGuire wrote: > "Larry Bates" wrote in message > news:ZOednXPakP64mczdRVn-jA at comcast.com... > >>[[y or None for y in x] for x in l] > > Well if that works, then this must too: > > [y or None for x in l for y in x] No, that will give you a single-level list, not a list of lists. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From peter at engcorp.com Sat Mar 6 20:09:25 2004 From: peter at engcorp.com (Peter Hansen) Date: Sat, 06 Mar 2004 20:09:25 -0500 Subject: ready to use python, need help with GUI decision In-Reply-To: References: <20040303181544.GB74292@dogma.freebsd-uk.eu.org> <4046EE84.9080700@rebirthing.co.nz> Message-ID: <6Fu2c.2306$G3.18772@localhost> Ed Cogburn wrote: > David McNab wrote: > >> My personal favourite is Tkinter, with the 'steroids' that go by the >> name of PMW. > > Have you also tried wxPython? I'm not advocating, just want to know if > you've also tried "the other one". :) What does PMW do for Tkinter? > I've seen opinions suggesting wxPython was "better" than (standard) > Tkinter, but I've never seen PMW mentioned before when comparing the > two. If you've used wxPython previously, how does Tkinter+PMW compare > to it? Anyone? I've used both, and didn't find PMW any more compelling than I found Tkinter alone. I still find that wxPython fits my brain better and gives me better results. This, however, is an area where individual mileage definitely varies, based on past reports here that strongly support either the one or the other approach depending on who's writing. -Peter From richard at cogsci.ed.ac.uk Thu Mar 11 18:59:07 2004 From: richard at cogsci.ed.ac.uk (Richard Tobin) Date: 11 Mar 2004 23:59:07 GMT Subject: An XML parser is an XML parser. Period. References: <402931E4.C1E50E92@engcorp.com> <40294322.7AF2C6D7@engcorp.com> <40294D36.B0AEE3C4@engcorp.com> <402A69C2.FC8DABA@engcorp.com> <402A84FF.42CCB137@hotmail.com> <402A87FD.5879C6DC@engcorp.com> Message-ID: > So once more: AFAICT PyRXPU is an XML parser. PyRXP is certainly not > an XML parser. The substrate RXP is not an XML parser either when > compiled without Unicode support and although I respect Thompson and > Tobin as much as I do the PyRXP developers, they were really confusing > themselves and others when they said "It complies fully with the W3C > test suites (although we have compiled it without Unicode support for > the time being)." Sorry to respond to a thread long after its sell-by date. Just for the record, the statement above was made by the PyRXP people, not us. RXP's 8-bit mode exists because it was originally written to replace a "normalized SGML" parser in an existing (8-bit) application. I wouldn't recommend compiling it in that mode for any except the most constrained applications. -- Richard From antonyliu2002 at yahoo.com Wed Mar 10 20:26:00 2004 From: antonyliu2002 at yahoo.com (Anthony Liu) Date: Wed, 10 Mar 2004 17:26:00 -0800 (PST) Subject: What is wrong? The minidom or the XML file? In-Reply-To: <404FBBA1.A8B53E8A@alcyone.com> Message-ID: <20040311012600.46688.qmail@web13012.mail.yahoo.com> Erik, What do you mean by "where these Chinese characters come from"? I think I got lost. --- Erik Max Francis wrote: > Anthony Liu wrote: > > > Another question: If I insert some Chinese > characters > > in the sample xml document, then again the same > python > > code cannot parse it. It python code got choked > > whenever it hits the 1st Chiese character. > > > > Python says: > > > > ExpatError: not well-formed (invalid token): line > 3, > > column 7 > > > > The problem remains even if I try > encoding="UTF-16" or > > encoding="GB2312" or encoding="GBK" in the xml > > document. > > > > Note that GB2312 and GBK are Chinese encodings. > > If you're getting errors, then the encoding > specified in the XML > document type declaration doesn't patch what you've > pasted in. It > matters where these Chinese characters come from, > since they're going to > be a part of some encoding and you haven't said what > it was; if your > document is UTF-8, you need to paste UTF-8 in. > > -- > __ Erik Max Francis && max at alcyone.com && > http://www.alcyone.com/max/ > / \ San Jose, CA, USA && 37 20 N 121 53 W && > &tSftDotIotE > \__/ Love is the true price of love. > -- George Herbert > -- > http://mail.python.org/mailman/listinfo/python-list __________________________________ Do you Yahoo!? Yahoo! Search - Find what you?re looking for faster http://search.yahoo.com From edcjones at erols.com Fri Mar 5 07:20:21 2004 From: edcjones at erols.com (Edward C. Jones) Date: Fri, 05 Mar 2004 07:20:21 -0500 Subject: Python's equivalent of C++ std::multimap In-Reply-To: References: Message-ID: <40487191$0$3103$61fed72c@news.rcn.com> Boogie El Aceitoso wrote: > What's Python's equivalent of C++'s std::multimap? Is there any 'multidict'? > O:-) See MultiDict.py at http://members.tripod.com/~edcjones/pycode.html From donn at drizzle.com Sat Mar 27 11:51:02 2004 From: donn at drizzle.com (Donn Cave) Date: Sat, 27 Mar 2004 16:51:02 -0000 Subject: Choosing Perl/Python for my particular niche References: <40652B0D.7C313F77@doe.carleton.ca> <406532F7.D56DC671@doe.carleton.ca> <106b8ptboh4ig4a@corp.supernews.com> Message-ID: <1080406261.496998@yasure> Quoth claird at lairds.com (Cameron Laird): ... | I *really* don't know how to respond to this; a | sentence with "sed", "conditional" and "convenient" | leaves me at a loss. I personally find sed more frustrating than useful, for anything past the common one-line application. But I know of a very accomplished sed programmer for whom it's the other way around - not only can he solve complex problems in sed, he once professed to be baffled by the common structured-procedural languages. I reckon him to be a person of extraordinary intellect, because of his exceptional ability with sed, but he was pretty firmly convinced that he couldn't do much with a programming language like C or Python. Of course not a programmer by trade. I believe he never did go on to prove himself wrong on that. In my opinion, it's a matter of very deep learning about how to solve problems. Most of us were introduced to programming with procedural languages - BASIC, assembler, Pascal, FORTRAN and so on, which for all their differences are essentially the same in principle when it comes to solving a problem. We can move from one of these languages to another fairly easily, but not sed - what's the point of such a useless language! But here are these few, mostly non-programmers, who started with sed and can do amazing things with it. We see a crippling lack of features, where they see spartan elegance, because at a very fundamental level they get it and we don't. Donn Cave, donn at drizzle.com From joe at notcharles.ca Sun Mar 28 11:26:45 2004 From: joe at notcharles.ca (Joe Mason) Date: Sun, 28 Mar 2004 16:26:45 GMT Subject: Newbie Class Questions References: <94CdnVqi7o8rn_vdRVn-vg@centurytel.net> Message-ID: In article , Peter Otten wrote: > Joe Mason wrote: > >>>> I think it would be cool for my "AutoText" class (see below, hereby >>>> GPL'd) to be able to tell what subclasses inherit from it and >>>> instantiate objects for all of those subclasses to implement a "AutoAll" >>>> function.. Any ideas? >> >> Actually, somebody pointed out in the other thread that Python has a >> __subclasses__ function, so AutoAll can just do "for i in >> AutoText.__subclasses__:". > > My first reaction was disbelief :-) Now we can change > > # add as base whenever you create a new subclass of AutoText > class AutoAll(AutoUrl, AutoEmphasis): > pass > > to > > AutoAll = type("AutoAll", tuple(AutoText.__subclasses__()), {}) Woah. That's a weird one. You're on the right track, but what you're doing here is creating a class with absolutely nothing in it - not even the default attributes that I'll show below. What you really want to do is make class normally, but only override the base classes. Fortunately, that's even easier: class AutoAll(tuple(AutoText.__subclasses__())): pass ... except that doesn't work, and nobody's been able to explain to me why not. So, I'll turn to metaclasses for the clean solution. But first: > Do you know what the last dictionary parameter of type() is for? A cursory > glance over the 2.3 library did not bring up a usecase of type() with three > parameters. It's the __dict__ of the class that's about to be created: >>> class Verbose(type): ... def __new__(*args): ... print "new: ", args ... return type.__new__(*args) ... def __init__(*args): ... print "init: ", args ... type.__init__(*args) ... >>> class Empty(object): __metaclass__ = Verbose ... new: (, 'Empty', (,), {'__module__': '__main__', '__metaclass__': }) init: (, 'Empty', (,), {'__module__': '__main__', '__metaclass__': }) >>> class HasAnAttr(Empty): x = 1 ... new: (, 'HasAnAttr', (,), {'x': 1, '__module__': '__main__'}) init: (, 'HasAnAttr', (,), {'x': 1, '__module__': '__main__'}) (Hmm, I guess the __metaclass__ means that first one is not Empty after all...) The metaclass I just made hooks in to the class creation, in this case just to print some extra stuff and then call the normal one. Here's one that replaces the bases cleanly: class AutoTextSubclasses(type): def __new__(metaclass, name, bases, attrs): return type.__new__(metaclass, name, tuple(AutoText.__subclasses__()), attrs) class AutoAll: __metaclass__ = AutoTextSubclasses That'll throw away the normal "bases" list, and do the same thing your type class did - make "bases" out of __subclasses__ - except it passes through the attrs unchanged. (You can replace both uses of "type" in AutoTextSubclasses with Verbose to see what's happening.) Joe From Sibylle.Koczian at Bibliothek.Uni-Augsburg.de Wed Mar 31 06:21:19 2004 From: Sibylle.Koczian at Bibliothek.Uni-Augsburg.de (Sibylle Koczian) Date: Wed, 31 Mar 2004 13:21:19 +0200 Subject: python & mysql probelm In-Reply-To: References: Message-ID: Robert Brewer schrieb: > james blair wrote: > >>I am having a problem executing following query: >>cursor.execute("select * from projects where projectid between '%s' >>and '%s'"%(id1,id2)) > Try dropping the single quotes around each %s > > cursor.execute("select * from projects where projectid " > "between %s and %s" % (id1, id2)) But why not use a genuine parametrized query: cursor.execute("select * from projects where projectid " "between %s and %s", (id1, id2)) Especially if you need to execute the same query several times with changing parameters this is faster as far as I know, because the query is prepared once. Koczian -- Dr. Sibylle Koczian Universitaetsbibliothek, Abt. Naturwiss. D-86135 Augsburg Tel.: (0821) 598-2400, Fax : (0821) 598-2410 e-mail : Sibylle.Koczian at Bibliothek.Uni-Augsburg.DE From guy at NOSPAM.r-e-d.co.nz Wed Mar 24 20:21:40 2004 From: guy at NOSPAM.r-e-d.co.nz (Guy Robinson) Date: Thu, 25 Mar 2004 13:21:40 +1200 Subject: confused with xml and minidom Message-ID: Hello, I've got an xhtml file which contains a number of html tables. I want to parse these tables and based on values in the TD cells of the body of the table delete the row and replace it with additional rows. Then write the xhtml file to a new file. so input.xhtml
param param2 param3
becomes output.xhtml ... etc
r1v1 r1v2 r1v3
r2v1 r2v2 r2v3
r3v1 r3v2 r3v3
if I get the table by: xmldoc = minidom.parse('templates/input.xhtml') table = xmldoc.getElementsByTagName('table') how do I then get the first row of with the parameters. Delete this row and insert the new rows? table.childnode('tbody').getElementsByTagname('tr') doesn't work. Any help or examples of what I'm trying to do appreciated. Thanks, Guy From skip at pobox.com Wed Mar 24 12:56:06 2004 From: skip at pobox.com (Skip Montanaro) Date: Wed, 24 Mar 2004 11:56:06 -0600 Subject: String formatting with floats... can't get it! In-Reply-To: References: Message-ID: <16481.52150.849798.685939@montanaro.dyndns.org> >>> '%2.2f' % 2.33 '2.33' Facundo> Why in this last line I don't get ' 2.33'? Because the total field width you declared was only 2. You need a field width of at least 5 to get a space preceeding the one's digit: >>> '%5.2f' % 2.33 ' 2.33' The two digits in the format specifier don't add. The first digit is the overall width of the field. The second digit is how much precision to display to the right of the decimal point. Skip From bnetNOSPAM at ifrance.com Fri Mar 12 13:55:48 2004 From: bnetNOSPAM at ifrance.com (=?iso-8859-1?q?Beno=EEt_Dejean?=) Date: Fri, 12 Mar 2004 19:55:48 +0100 Subject: overloading __getattr__ and inheriting from dict Message-ID: class TargetWrapper(dict): def __init__(self, **kwargs): dict.__init__(self, kwargs) __getattr__ = dict.__getitem__ __setattr__ = dict.__setitem__ __delattr__ = dict.__delitem__ then tw = TargetWrapper() tw.a = "spam" # ok del tw.a # ok tw.b = "egg" print tw.b last line give me an AttributeError: 'TargetWrapper' object has no attribute 'b' if i define def __getitem__(self, name): return dict.__getitem__(self, name) __getattr__ = __getitem__ then the accessing the b attribute is ok. what's wrong ? From aahz at pythoncraft.com Sun Mar 14 10:04:42 2004 From: aahz at pythoncraft.com (Aahz) Date: 14 Mar 2004 10:04:42 -0500 Subject: where can I find Paris Hilton video? References: Message-ID: In article , Gon?alo Rodrigues wrote: >On Sat, 13 Mar 2004 23:24:59 -0500, "Tim Peters" >wrote: >>[montezum] >>> >>> where can I find Paris Hilton video? >> >>comp.lang.perl.misc > > > >QOTW (What the QUOTM or even QUOTY!) Seconded! -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "usenet imitates usenet" --Darkhawk From jdrugo at gmx.at Sun Mar 7 16:56:20 2004 From: jdrugo at gmx.at (Jan Drugowitsch) Date: Sun, 7 Mar 2004 21:56:20 +0000 Subject: ImportError when trying to import own C++ module Message-ID: <200403072156.25664.jdrugo@gmx.at> Hi everyone! I am trying to access a C++ class which is wrapped in a Python object from another C++ class which is also wrapped in a Python object. I have used the following file structure: AClass.h: Declaration of AClass typedef of PyObject containing AClass AClass.cpp: Including AClass.h Implementation of AClass PyAClass.cpp: Including AClass.h Python interface to access AClass BClass.cpp: Including AClass.h Declaration of BClass Implementation of BClass Python interface to access BClass AClass has the methods unsigned int value() const; // reading private value void setValue(const unsiged int); // setting private value BClass has the method unsigned int value(const AClass* aclass) const; // returning aclass->value() (remember: just a proof-of-concept) I'm using DistUtils to compile the libraries. AClass.so links AClass.cpp and PyAClass.cpp, BClass.so links BClass.cpp and AClass.cpp. Using AClass in Python works without problems, importing BClass, however, gives the following error: >>> import BClass Traceback (most recent call last): File "", line 1, in ? ImportError: ./BClass.so: undefined symbol: _ZNK6AClass5valueEv BClass.so, however, seems to contain that symbol: % nm BClass.so | grep _ZNK6AClass5valueEv U _ZNK6AClass5valueEv Any ideas what can go wrong there? Any hints are appreciated Cheers, Jan P.S.: I'm sorry if this question has been asked a thousand times. It is very hard to search for in the archives as 'ImportError' is usually a bug in some software and no solution is given to resolve it. -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: signature URL: From bojohan+news at dd.chalmers.se Fri Mar 19 20:41:22 2004 From: bojohan+news at dd.chalmers.se (=?iso-8859-1?q?Johan_Bockg=E5rd?=) Date: Sat, 20 Mar 2004 02:41:22 +0100 Subject: Static Typing in Python References: <4055a71e$0$28265$afc38c87@news.easynet.co.uk> Message-ID: Donn Cave writes: > module Main (main) where > > diff a b | a < b = b - a > | otherwise = a - b > > main = do > putStrLn (show (diff 2 5)) > putStrLn (show (diff 2.3 5)) > > $ runhugs num.hs > 3 > 2.7 > > Haskell automatically converts between numeric types, to perform > arithmetic including comparisons. Haskell has no implicit conversions. What you see is an effect of having overloaded numeric constants. Prelude> :type 0 :: Int 0 :: Int Prelude> :type 0 :: Float 0 :: Float 0 is not an Int here: Prelude> let x = 0 in 1.0+x 1.0 The type of x is never converted, so this does not work: Prelude> let x = 0::Int in 1.0+x ERROR: Illegal Haskell 98 class constraint in inferred type *** Expression : let {...} in 1.0 + x *** Type : Fractional Int => Int -- Johan Bockg?rd From dmq at gain.com Fri Mar 26 16:54:51 2004 From: dmq at gain.com (David MacQuigg) Date: Fri, 26 Mar 2004 14:54:51 -0700 Subject: A 'Python like' language References: <40645d8f$0$10775$afc38c87@news.easynet.co.uk> Message-ID: On Fri, 26 Mar 2004 16:42:54 +0000, Peter Hickman wrote: >Well after all this discussion it would appear that a 'Python like' >language has appeared => Prothon. http://www.prothon.org/index.html > >Very alpha, sort of like Python (if you consider the indenting is what >makes Python unique) and sort of Ruby in its use of prefixes to define >scoping etc (although there is no reference to this trait being borrowed >from Ruby). It also quotes Self as being an influence. What I found most interesting about this language is that it *doesn't use classes* !! All objects are derived directly from other objects, some of which are "prototypes", that is, objects which were designed to be just templates to produce other objects. I downloaded the interpreter, and it installed flawlessly on my XP machine! I ran through the examples from their webpage, and they worked as shown! As I am generating objects from prototypes, I am thinking - How can this be so simple? Surely we must need classes for something. What about static methods? Is all of this just cruft in Python? The torture never stops. :>) -- Dave From afriere at yahoo.co.uk Fri Mar 19 01:30:45 2004 From: afriere at yahoo.co.uk (Asun Friere) Date: 18 Mar 2004 22:30:45 -0800 Subject: Result of ``a is b'' References: <38ec68a6.0403171642.7199763c@posting.google.com> <405A5EC9.6010503@yahoo.com.au> Message-ID: <38ec68a6.0403182230.49e90fac@posting.google.com> Steve wrote in message news:<405A5EC9.6010503 at yahoo.com.au>... > Asun Friere wrote: > > > In fact __eq__ can be redefined even /so as to be an equivalence > > relation/ such that x==y => True and x is y => False. The > > 'fundamental properties' posisted, are simply not fundamental. > > I think you have mis-read those fundamental properties. > They were: > > (1) If x and y refer to the same object, "x is y" > yields True. > > (2) If "x is y" yields True, "x==y" also yields True. > Equivalently, if "x==y" yields False, "x is y" also > yields False. > > Property (2) assumes that __eq__ implements an > equivalence relation. > > Notice that your objection that x==y returns True and x > is y returns False is *not* one of those properties. You're right I did misread them. Mea culpa! > I don't think the argument that one can redefine __eq__ > to be something other than an equivalence relation is a > particularly strong argument. I would call that a bug, > even if it is a deliberate bug. If "==" doesn't do > equality, then it is an exceedingly bad piece of design. I don't think you can call the intended and and expected behaviour of a program a 'bug.' On the other hand, apart from trying to show that these properties are not truely 'fundamental,' I find it difficult to conceive of a useful application of this kind of redefinition of the equivalence function. So yes, we should expect that identical objects also to be equivalent. In any case, now that you brought me back to what Andrew Koenig actually wrote, I accept his propositions should hold true when __eq__ implements what could justifiably be called an equivalence function, whether they are rightly called 'fundamental' or not. From patois at calvix.org Sat Mar 20 03:56:20 2004 From: patois at calvix.org (Yannick Patois) Date: Sat, 20 Mar 2004 09:56:20 +0100 Subject: Package name with '.' in them: Python Bug ? In-Reply-To: References: Message-ID: Josiah Carlson wrote: >> But I dont know, I wont say that this has to be fixed in any way >> outside of the programmer's code. > I've never seen python modules named like: valid_name.1.py Well, I wrote one (it's generated names, that's why it happenned) ;) > Considering that you have shown that it does not work, and that there is > documentation stating that it is not /meant/ to work The doc is not so explicit. It says that hierarchical modules are not handled by load_module(), fine, i dont want to handle hierarchicals one, just a simple one that has a don in its name. > then the error is > in the way /you/ name /your/ modules, not the way Python handles > /incorrectly/ named modules. That's exactly what I said, and I tend to believe it. Yannick -- _/ Yannick Patois \___________________________________________________ | web: http://feelingsurfer.net/garp/ | Garp sur irc undernet | | email: patois at calvix.org | | | ATTAC dans le Pays de Gex: http://attacgex.ouvaton.org | From vonehr at ipm.fhg.de Tue Mar 30 02:57:14 2004 From: vonehr at ipm.fhg.de (Markus von Ehr) Date: Tue, 30 Mar 2004 09:57:14 +0200 Subject: queue for large objects, object references Message-ID: Hi, in a data acquisition program I have several threads, one thread grabbing images and another doing some processing. I'd like to make my own image class containing the image and additional information (a lot of data, some Megabytes). Then I'd like to transfer this object to another thread. I tried to transfer an image over a queue and it works! (see code below) Is the data transferred or only a reference? How could I hold the data global and transfer only a reference that no data has to be copied (speed, memory)? Thanks for any answer, Markus ************************************** import Image import Queue import thread import time class Send: def __init__(self, queue, filename): self.queue = queue self.image = Image.open(filename, 'r') def send(self): self.queue.put(self.image) class Recv: def __init__(self, queue): self.queue = queue thread.start_new_thread(self.MyThread, (10,)) def MyThread(self, start): while 1: while not self.queue.empty(): img = self.queue.get() img.save("result.bmp") time.sleep(0.3) msgq = Queue.Queue(0) sender = Send(msgq, "test.bmp") receiver = Recv(msgq) sender.send() time.sleep(2) From mwh at python.net Mon Mar 15 07:58:30 2004 From: mwh at python.net (Michael Hudson) Date: Mon, 15 Mar 2004 12:58:30 GMT Subject: overloading __getattr__ and inheriting from dict References: Message-ID: Beno?t Dejean writes: > class TargetWrapper(dict): > > def __init__(self, **kwargs): > dict.__init__(self, kwargs) > > __getattr__ = dict.__getitem__ > __setattr__ = dict.__setitem__ > __delattr__ = dict.__delitem__ > > > > then > > tw = TargetWrapper() > tw.a = "spam" # ok > del tw.a # ok > tw.b = "egg" > print tw.b > > last line give me an > AttributeError: 'TargetWrapper' object has no attribute 'b' > > if i define > > def __getitem__(self, name): > return dict.__getitem__(self, name) > > __getattr__ = __getitem__ > > then the accessing the b attribute is ok. what's wrong ? I'm not sure, but changing __getattr__ = dict.__getitem__ to __getattribute__ = dict.__getitem__ makes things behave more like I think you expect. Cheers, mwh -- Of course, it obviously is beta hardware so such things are to be expected, but that doesn't mean that you can't point your fingers and generate a nelson style HAHA at a multi billion dollar corporation's expense. -- CmdrTaco on slashdot.org From jacek.generowicz at cern.ch Mon Mar 1 03:14:29 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 01 Mar 2004 09:14:29 +0100 Subject: Some language proposals. References: Message-ID: Josiah Carlson writes: > Perhaps you want the below. You seem to be interested in doing things > with classes and not instances. > > > class Callable: > def __call__(self): > print "!" > > class C: > foo = Callable() > > - Josiah Perhaps you want to read again: http://www.google.com/groups?safe=images&ie=UTF-8&oe=UTF-8&as_umsgid=tyfk72amei6.fsf%40pcepsft001.cern.ch&lr=&hl=en Here's the relevant part: Jacek Generowicz writes: > >>> class foo: pass > ... > >>> class callable: > ... def __call__(self): print self > ... > >>> instance = callable() > >>> def meth(self): print self > ... > >>> foo.meth = meth > >>> foo.instance = instance > >>> f = foo() > >>> f > <__main__.foo instance at 0x815fa64> > >>> f.meth() > <__main__.foo instance at 0x815fa64> # self == f > >>> f.instance() > <__main__.callable instance at 0x815f624> # self != f > >>> f.meth > > > >>> f.instance > <__main__.callable instance at 0x815f624> # Hmm, it's not a method > >>> > > meth behaves like a Python method, instance does not. From jkn at nicorp.f9.co.uk Mon Mar 22 09:32:24 2004 From: jkn at nicorp.f9.co.uk (Jon Nicoll) Date: 22 Mar 2004 06:32:24 -0800 Subject: [OT] Compilable Python-like language? References: <405ed061$0$10776$afc38c87@news.easynet.co.uk> Message-ID: <8351bb33.0403220632.5becbc0c@posting.google.com> Hi Peter Peter Hickman wrote in message news:<405ed061$0$10776$afc38c87 at news.easynet.co.uk>... [...] > Fran?ois Pinard wrote: > > Such reactions always astonish me, especially given the good guy I know > > I am! :-) In French (maybe in English too?) we say that we "put white > > gloves" when we get extremely cautious ... > > The UK English phrase would be to "put on kid gloves" kid gloves being > very soft and gentle type of leather (supposedly made from juveniles). er, I think 'supposedly made from [the skin of] juvenile _goats_ ...' Regards Jon N From theller at python.net Wed Mar 3 03:02:29 2004 From: theller at python.net (Thomas Heller) Date: Wed, 03 Mar 2004 09:02:29 +0100 Subject: py2exe in Windowsxp References: <38f75b16.0403022320.1f56ce00@posting.google.com> Message-ID: vijay_srr at yahoo.com (Vijay) writes: > Hello, > > Is py2exe 0.5.0 supported in Windows XP? In the project homepage in > SourceForge.net, only Win95/95/2000 are listed. Sure. I will correct that. Thanks, Thomas From erno-news at erno.iki.fi Mon Mar 22 10:11:04 2004 From: erno-news at erno.iki.fi (Erno Kuusela) Date: 22 Mar 2004 17:11:04 +0200 Subject: In what python release was this introduced.. References: <74dd441a.0403220126.12ec063f@posting.google.com> Message-ID: htgk at mail.com (Moe A) writes: > Hi, > > i need to list dependencies for my package & was wondering in what > python release could you start making 'in ' calls with more > than one char..eg: > > "JESUS" in bible > > instead of > > "J" in bible more new and improved sequence/iterators behaviour fun: Python 2.3.3 (#2, Jan 13 2004, 00:47:05) [GCC 3.3.3 20040110 (prerelease) (Debian)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> 'x'.join({'foo': 'bar'}) 'foo' i actually ran into this when i was staring at code written by a coworker and wondered how on earth it ever worked... (it didn't, since it really meant to use a list and wanted order to be preserved, but it misbehaved silently instead of raising an exception). -- erno From jjl at pobox.com Mon Mar 8 15:15:16 2004 From: jjl at pobox.com (John J. Lee) Date: 08 Mar 2004 20:15:16 +0000 Subject: Mailing list hosting? References: <8765dhd2dr.fsf@pobox.com> Message-ID: <878yibccyz.fsf@pobox.com> OK, freelists.org *was* promising. The submit button on the signup page leads to a page displaying raw HTML with no content of interest. I guess the site is no longer active. John From godoy at ieee.org Wed Mar 24 07:15:50 2004 From: godoy at ieee.org (Jorge Godoy) Date: Wed, 24 Mar 2004 09:15:50 -0300 Subject: Abstraction library for Authentication (module like PEAR Auth) References: <899f842.0403230824.4a4ba0ab@posting.google.com> Message-ID: On Ter 23 Mar 2004 22:08, Stuart Bishop wrote: > If you don't mean login via form web authentication, I don't see > much point - its just a call to an authenticate(username, password) > method for the protocols you mention. And if you introduce other > protocols such as Kerberos, Passport, biometric, or challenge > response schemes the abstraction would become too complex to be > generally useful. One can always rely on PAM... It can talk to different sources and any other authentication can be implemented, provided that it has a plugin and return the right values for success/failure. Your interface would be with PAM only and then PAM would talk to the rest of the authentication system. -- Godoy. From tjreedy at udel.edu Mon Mar 29 14:27:03 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 29 Mar 2004 14:27:03 -0500 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><406829FF.5060304@mlug.missouri.edu> <106gg1jifa2n9c2@news.supernews.com> Message-ID: "John Roth" wrote in message news:106gg1jifa2n9c2 at news.supernews.com... > I think you misunderstood. There is no "standard" length of > a tab. A tab is supposed to insert (or otherwise render the > equivalent of inserting) enough spaces to go to the next "tab stop", > which by convention is a multiple of 8 columns on a fixed > width mechanical typewriter. This is where tabs originated. Actually, the mechanical typewrite standard (in US, 1960s) was every 5 spaces == 1/2 inch (10 chars per inch, fixed). That was also the standard paragraph indent. WordPerferct, for one program, stuck with 1/2 inch even as it accommodated different fixed and variable pitched fonts. I remember thinking 8 spaces a bit weird when I first used Unix (early 80s). Power-of-2 4 and 8 are computerisms. Don't remember about Teletypes, nor about typewriters in non-inch countries. Terry J. Reedy From skip at pobox.com Sun Mar 21 09:46:33 2004 From: skip at pobox.com (Skip Montanaro) Date: Sun, 21 Mar 2004 08:46:33 -0600 Subject: Reload() Confusion In-Reply-To: References: Message-ID: <16477.43721.529162.718723@montanaro.dyndns.org> >> It is my understanding that the reloaded objects become *new* objects >> in memory, available only via a fully-qualified reference to the new >> module. The old objects remain in memory until the last reference to >> them is gone. Mel> It seems to me that the module keeps its identity over the reload: Yup. The module remains the same, but its __dict__ is repopulated. Skip From pycon at python.org Wed Mar 10 16:37:31 2004 From: pycon at python.org (Steve Holden) Date: Wed, 10 Mar 2004 16:37:31 -0500 Subject: View Talks - Buy 'Zen of Python' Tshirt - Free with PyCON by 17th Message-ID: Dear Python User: View the Talks online and Reserve your Zen of Python Shirt now or get one free if you register for PyCON 2004 by the 17th. Don't miss the most important Python event of the year. PyCON 2004 is only 2 weeks away. If you haven't registered for PyCON, please do so immediately before the regular registration expires March 17th. http://www.pycon.org/dc2004/register We are extending the Free T-Shirt offer to all regular registrants (valued at $20). See the shirts online at http://www.pycon.org/dc2004/shirts.pt We are also taking orders for extra shirts, including shipping to those that cannot attend. Please email zope at toenjes.com to reserve your shirts. All requests must be received by March 19. Price will be $20 + $5 shipping and handling. We will ship them sometime around mid-April. Payment instructions from the Python Software Foundation will follow. The Talks schedule is now published and can be viewed at http://www.python.org/pycon/dc2004/schedule.html For more about PyCON... http://www.pycon.org regards Steve Holden Chairman, PyCON DC 2004 From bob at redivi.com Mon Mar 1 14:56:00 2004 From: bob at redivi.com (Bob Ippolito) Date: Mon, 1 Mar 2004 14:56:00 -0500 Subject: Why Python? References: <1045c7gfn9ipj38@corp.supernews.com> <1046gip10m5m9bc@corp.supernews.com> Message-ID: <2004030114560084492%bob@redivicom> On 2004-03-01 09:02:01 -0500, claird at lairds.com (Cameron Laird) said: > In article <1045c7gfn9ipj38 at corp.supernews.com>, > Robert M. Emmons wrote: > . > [apt comments] > . > . >> What's not good in python: >> >> * If speed is more important than coding time use C/C++ instead. >> * If you want to obscruate your code maybe a compiled langague is better. >> >> Rob > > Note the availability of pyobfuscate http://www.lysator.liu.se/~astrand/projects/pyobfuscate/ >. > > Myself, in the absence of more details, I advise people for > whom speed is important to work in Python--but be prepared > to combine it with C coding (or even assembler! I've been > experimenting lately ...). One thing to note is that it is *reasonable* to combine C, C++, assembly, etc with Python because the Python API is consistent and understandable, and doesn't require a confusing "precompiler" (though, Pyrex is a great one). -bob From opengeometry at yahoo.ca Tue Mar 9 11:59:39 2004 From: opengeometry at yahoo.ca (William Park) Date: 9 Mar 2004 16:59:39 GMT Subject: How to convert string to list without eval or exec References: Message-ID: Oliver Kurz wrote: > Hello, > > could someone give me a solution how to convert a string to a list without using eval or exec? > > The string looks like: > > '[["abc","abc",["abc","abc"],"abc"],["abc","abc",["abc","abc"],["abc",["abc","abc"]],"abc"],"abc"]' > > and should be converted to a list: > > [['abc', 'abc', ['abc', 'abc'], 'abc'], ['abc', 'abc', ['abc', 'abc'], ['abc', ['abc', 'abc']], 'abc'], 'abc'] > > I'm not allowed to use eval or exec. - write to a file - load the file as module :-) -- William Park, Open Geometry Consulting, Linux solution for data processing and document management. From skip at pobox.com Tue Mar 16 16:06:26 2004 From: skip at pobox.com (Skip Montanaro) Date: Tue, 16 Mar 2004 15:06:26 -0600 Subject: Is Python type safe? In-Reply-To: <16471.26244.889193.809339@montanaro.dyndns.org> References: <221d8dbe.0403161043.52406195@posting.google.com> <16471.26244.889193.809339@montanaro.dyndns.org> Message-ID: <16471.27730.251856.976365@montanaro.dyndns.org> Skip> Python: yes. I don't know about Java or C# but my guess is that Skip> since C++ has casts you can make it do some type unsafe things. Sorry to follow up to my own post, but unions also create type unsafety. Unlike Pascal's records (remember them?), C/C++ unions are not discriminated, so you can write values into the union using one slot and read using another: #include int main(int argc, char *argv[]) { union { float f; int i; } x; x.f = 3.14159; fprintf(stderr, "%x\n", x.i); } (pause while Skip reboots the one neuron that knows anything about unions and compiles this to see if he's got it right...) which produces: % make foo cc -c -o foo.o foo.c cc foo.o -o foo % ./foo 40490fd0 Skip From bdesth.quelquechose at free.quelquepart.fr Tue Mar 16 04:16:48 2004 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 16 Mar 2004 10:16:48 +0100 Subject: Static Typing in Python In-Reply-To: References: Message-ID: <4056c036$0$308$626a14ce@news.free.fr> Premshree Pillai wrote: (snip) > > Yes, I am aware that Python is dynamically typed, and > so is Perl, right? In Perl, we have the "use strict > vars" pragma to force variable declaration. Is there > something like it in Python? > > Don't you think forced variable declaration is an > important requirement in a language? No. From owp at utanet.at Wed Mar 17 03:41:05 2004 From: owp at utanet.at (Simon Erikson) Date: 17 Mar 2004 00:41:05 -0800 Subject: wxPython "Frames within Frames" References: Message-ID: Peter Hansen wrote in message news:... > > (This is probably a somewhat religious matter, and in any case perhaps > you have very good reasons for wanting MDI, but just in case you aren't > set on doing it, other options might also be much simpler to code.) > > -Peter Thanks for your effort. I am actually looking for something *other* than MDI; sorry for the confusion. Simon. From mogmios at mlug.missouri.edu Wed Mar 31 00:15:09 2004 From: mogmios at mlug.missouri.edu (Michael) Date: Tue, 30 Mar 2004 21:15:09 -0800 Subject: tabbing probs In-Reply-To: <16490.15980.814876.690888@montanaro.dyndns.org> 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> <406829FF.5060304@mlug.missouri.edu> <106gg1jifa2n9c2@news.supernews.com> <406848CD.5070100@mlug.missouri.edu> <106glq882vcn659@news.supernews.com> <4068AD29.6020907@mlug.missouri.edu> <16490.15980.814876.690888@montanaro.dyndns.org> Message-ID: <406A53DD.6090105@mlug.missouri.edu> >Not if that's what I asked it to do. I have python-mode in Emacs set to use >4-space indents and only insert SPACE characters, not TAB characters. >Pressing the TAB key while the cursor is at the beginning of line inserts or >deletes enough SPACEs to put the cursor at the correct indentation for the >current line (based upon the indentation and content of the previous line). > > If you tell it to do that then that's fine. But then if you can do that then why can't you just tell the editor to handle tabs as tabs? The whole discussion being about why tabs should be removed because some editors are to stupid to handle them correctly, or maybe just some programmers are to stupid to tell their editor how to handle tabs. If you can tell the editor to not allow mixing of spaces and tabs then the entire issue would be moot. >not if I placed my editor in e.e. cummings mode... > > That'd be rather funny. It reminds me of the time I wrote a projects documentation in Suess-like language. >It has nothing to do with the editors considered in isolation. By in large >they are doing exactly what the programmers ask them to do. The problem is >with the interchange of program files between unlike systems (via whatever >means: email, CVS checkins, grabbing from a web page, etc) which have tools >(editors in particular) which interpret TAB characters differently based >upon how the programmers have configured them. To the best of my knowledge >no systems interpret SPACE characters in weird ways, so using them to >indicate indentation is the only foolproof solution. > > I have experienced the problem of cutting and pasting from some apps where tabs are replaced as spaces. Annoying, but still an error in those apps and not in Python. On the rare occassion that happens I just fix the code. I would like if Python could spit out warnings where tabs and spaces were mixed. That'd be a handy alert in cases where I might forget to fix a line. I can see that the mishandling of tabs by certain apps is annoying. I just don't see how adding Python to that list will be any less annoying. From stewart at midwinter.ca Fri Mar 19 16:07:49 2004 From: stewart at midwinter.ca (Stewart Midwinter) Date: 19 Mar 2004 13:07:49 -0800 Subject: Package name with '.' in them: Python Bug ? References: Message-ID: <9396ba6f.0403191307.2968a6c1@posting.google.com> Yannick Patois wrote in message news:... > If now I just *rename* file B to B.1, without any change in the code > (except name='B' become name='B.1' in aTest.py), content of B.1.py file > being exacty the same as content of B.py, I get: > .... > Any idea ? Is it well a bug ? Some feature I didnt understood ? I read > about submodule naminig using dots as separator, but I cant relate it > towhat I saw here. Salut Yannick: J'ose offrir une r?ponse.... I work with submodules. They're in some folder, which has subfolders (call them fbm, uti, and a few others). If I place an empty file in my root folder called __init__.py, I can refer to modules in the subfolders by a dot notation. For example, if I have a file process.py in subfolder fbm, I can say: import fbm.process I speculate that when you renamed B to B.1, Python interpreted your intent to import a module called 1 in subfolder B. J'esp?re que cela aide un peu! Stewart From Scott.Daniels at Acm.Org Wed Mar 3 12:01:33 2004 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 03 Mar 2004 09:01:33 -0800 Subject: i'm lost in list manipulation In-Reply-To: <40460bb3$0$28116$636a15ce@news.free.fr> References: <40460bb3$0$28116$636a15ce@news.free.fr> Message-ID: <404617fd$1@nntp0.pdx.net> GrelEns wrote: > hello, > > having a list like ['a', 'b', 'c', 'd'] i would like to get > > [['a', '-', 'b', 'c', 'd'], > ['a', 'b', '-', 'c', 'd'], > ['a', 'b', 'c', '-', 'd'], > ['a', '-', 'b', '-', 'c', 'd'], > ['a', 'b', '-', 'c', '-', 'd'], > ['a', '-', 'b', '-', 'c','-', 'd']] > > that is adding successively an item between at all the available place, and > i just can't get my brain doing that :( Maybe: Think of all possible places. How many are there? At each of these places you either put a dash or not. Sounds like binary to me. -- -Scott David Daniels Scott.Daniels at Acm.Org From michele.simionato at poste.it Sun Mar 28 10:15:10 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 28 Mar 2004 07:15:10 -0800 Subject: Newbie Class Questions References: <94CdnVqi7o8rn_vdRVn-vg@centurytel.net> Message-ID: <95aa1afa.0403280715.18292937@posting.google.com> Joe Mason wrote in message news:... > Check out http://www.phyast.pitt.edu/~micheles/python/meta1.html and > http://www.phyast.pitt.edu/~micheles/python/meta2.html. Those links refer to the drafts on my personal home page. They could disappear. It is much better to refer to the published versions (which are also fancier): http://www-106.ibm.com/developerworks/library/l-pymeta.html http://www-106.ibm.com/developerworks/library/l-pymeta2 The only advantages of the drafts is that you can get the reStructuredText version, convert it to PDF and print it. Michele Simionato From guido at python.org Wed Mar 10 00:01:11 2004 From: guido at python.org (Guido van Rossum) Date: Tue, 09 Mar 2004 21:01:11 -0800 Subject: PyCON: Pre-registration ends in one week! Message-ID: <200403100501.i2A51BM03182@guido.python.org> In one week (Weds March 17), pre-registration for PyCON will close. Right now, you can register for $250. After that, you will need to register at the door, and the cost will be $300. Save yourself $50! PyCON is a community-oriented conference targeting developers (both those using Python and those working on the Python project). It gives you opportunities to learn about significant advances in the Python development community, to participate in a programming sprint with some of the leading minds in the Open Source community, and to meet fellow developers from around the world. The organizers work to make the conference affordable and accessible to all. DC 2004 will be held March 24-26, 2004 in Washington, D.C. at the GWU Cafritz Conference Center. The keynote speakers are Mitch Kapor, Guido van Rossum, and Bruce Eckel. There will be a four-day development sprint before the conference (March 20-23). We're looking for volunteers to help run PyCON. If you're interested, subscribe to http://mail.python.org/mailman/listinfo/pycon-organizers Don't miss any PyCON announcements! Subscribe to http://mail.python.org/mailman/listinfo/pycon-announce You can discuss PyCON with other interested people by subscribing to http://mail.python.org/mailman/listinfo/pycon-interest The central resource for PyCON DC 2004 is http://www.pycon.org/dc2004/ See you all there!!! --Guido van Rossum (home page: http://www.python.org/~guido/) From rmunn at pobox.com Sat Mar 20 09:11:46 2004 From: rmunn at pobox.com (Robin Munn) Date: Sat, 20 Mar 2004 14:11:46 GMT Subject: Import a module from parent package References: <1a884f4a.0403191219.3c6ff12d@posting.google.com> Message-ID: Peter L. Buschman wrote: > I have a package tree laid out like this > > foo/bar/module/submodule > foo/bar/module/submodule/test > foo/bar/module/submodule/test/test1.py > foo/bar/module/submodule/test/test2.py > ... > > What I want is for test1.py and test2.py to be able > to import their parent "submodule" as part of a regression > testing scheme. I could do this by putting "import foo.bar.module.submodule" > in them, but this code won't necessarily always be installed in foo/bar. > > Is there a way to do something like this from test1.py and test2.py? > > import __parent__.__parent__.submodule > > That way, no matter where the entire "module" package gets installed, the > regression tests will always be able to find and import their parent modules > whose functionality they need to test. > > Essentially, this is like referencing ../../submodule from the command-line. I needed something very similar last year; I had this directory structure: topdir/ topdir/usefulmodule.py topdir/subdir1/ topdir/subdir1/somecode.py topdir/subdir2/ topdir/subdir2/morecode.py Both somecode.py and morecode.py needed to use functions from usefulmodule.py. I solved it as follows: ----- Begin somecode.py ----- import os import sys # Other imports... sys.path.append('..') import usefulmodule sys.path.remove('..') . . . ------ End somecode.py ------ ----- Begin othercode.py ----- import os import sys # Other imports... sys.path.append('..') import usefulmodule sys.path.remove('..') . . . ------ End othercode.py ------ In your case, you'd want to add '../..' to sys.path. I think this will solve your problem. -- Robin Munn rmunn at pobox.com From artur_spruce at yahoo.com Mon Mar 22 17:33:54 2004 From: artur_spruce at yahoo.com (AdSR) Date: 22 Mar 2004 14:33:54 -0800 Subject: PEP 318 References: Message-ID: Skip Montanaro wrote... > I will reiterate my comment from before: PEP 318 is about more than just > static and class methods. Here are a few examples from the python-dev > discussion. You (and Stephen Horne) got your point. Passing that grep over 3rd party packages might be interesting too... On other note, regarding the initial subject of this thread: Is there going to be any voting poll about the syntax in foreseeable future? My preferred style would be the "standard" one proposed in the PEP. Cheers, AdSR From derekledbetter at mindspring.com Fri Mar 19 02:07:57 2004 From: derekledbetter at mindspring.com (Derek Ledbetter) Date: Fri, 19 Mar 2004 07:07:57 GMT Subject: Extending Python Syntax with @ References: <104v3lrijtse657@news.supernews.com> <104v8flf6f1bp95@news.supernews.com> Message-ID: <0001HW.BC7FDC4D003B1D7CF0284600@netnews.comcast.net> On Fri, 12 Mar 2004 9:08:10 -0800, Josiah Carlson wrote (in message ): > Personally, I find most standard IDEs to be bloated pieces of shit. > When did it become reasonable to need 100+ megs to edit source code? Not all IDEs are this large. For instance, Apple's Project Builder (version 2.1) is 2.6 MB, while the Mac version of CodeWarrior Pro 8 is 9.9 MB. These sizes are just the executables, and don't include compilers, linkers, libraries, headers, documentation and examples. But you would need all these things for a command line based development environment. -- Derek Ledbetter derekl at serve.com Heavy boots of lead fills his victims full of dread Running as fast as they can Iron Man lives again! From plb at iotk.com Sat Mar 20 09:42:34 2004 From: plb at iotk.com (Peter L. Buschman) Date: 20 Mar 2004 06:42:34 -0800 Subject: Import a module from parent package References: <1a884f4a.0403191219.3c6ff12d@posting.google.com> Message-ID: <1a884f4a.0403200642.697cdafb@posting.google.com> Thanks for the info guys! :) --PLB Peter Hansen wrote in message news:... > Peter L. Buschman wrote: > > > That way, no matter where the entire "module" package gets installed, the > > regression tests will always be able to find and import their parent modules > > whose functionality they need to test. > > > > Essentially, this is like referencing ../../submodule from the command-line. > > See http://www.python.org/peps/pep-0328.html for what would appear to be > some related material. > > -Peter From aahz at pythoncraft.com Sat Mar 13 14:07:48 2004 From: aahz at pythoncraft.com (Aahz) Date: 13 Mar 2004 14:07:48 -0500 Subject: need optimizing help References: <68aadb4a.0403131007.8eeeb26@posting.google.com> Message-ID: In article <68aadb4a.0403131007.8eeeb26 at posting.google.com>, rabbits77 wrote: > >I have a dictionary with a very very large(possibly millions) of >key/value pairs. If it's literally millions, you probably want to use a database. Just the dictionary itself (not even talking about the objects used for keys and values) will take at least 12MB per million entries on a machine with 32-bit addresses. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "usenet imitates usenet" --Darkhawk From leo at bella.local Wed Mar 10 06:17:20 2004 From: leo at bella.local (leo) Date: 10 Mar 2004 22:17:20 +1100 Subject: name of this python program Message-ID: hi there when i start a python script with python myprog.py how can i find out the name of my script ("myprog.py") inside the script itself. looking for something like args[0]... cheers, leo From noelrivera at excite.com Sun Mar 7 00:42:32 2004 From: noelrivera at excite.com (fossil_blue) Date: 6 Mar 2004 21:42:32 -0800 Subject: Why can't Lists be private variables in a class Message-ID: Why we can't define a list as a private variable in a class such as __SYMTAB = [ ] class Myclass: def __init__(self): #some constructor here def __PlayWithList(arg1): # This doesn't work it compains about not having not having attribute index or append # Why? try: self.__SYMTAB.index(arg1) except ValueError: self.__SYMTAB.append(arg1) But it the list was public SYMTAB = [ ] it would work. Why? Thanks, Noel From remy.blank_asps at pobox.com Tue Mar 9 04:16:00 2004 From: remy.blank_asps at pobox.com (Remy Blank) Date: Tue, 09 Mar 2004 10:16:00 +0100 Subject: "Virtual" file system mock object - replacing stuff in __builtins__ In-Reply-To: <6ee58e07.0403051620.40d3b42@posting.google.com> References: <404844e3$1@epflnews.epfl.ch> <6ee58e07.0403051620.40d3b42@posting.google.com> Message-ID: <404d8b50$1@epflnews.epfl.ch> Lothar Scholz said the following: > Setup a test directory with data files and in the setUp method copy > the items from the directory to a temporary directory. Do the tests > with the temporary directory and remove it in the tearDown method. That's a solution I rejected quite early, for the following reasons: - The simplest program I wrote has 64 test cases, and to ensure that tests are independent, I would have to re-create the test directory before every test. This is very time-consuming, and doesn't fit well with the "write test - run - failure - write code - run - success - refactor - run - success" coding cycle. Currently, the whole test suite runs in less than a second. - One program is meant to be used by "root", because it changes file ownerships and modes. I definitely don't want to run my test suite as root (if only to avoid wiping my hard disk by error). > This is the simplest case to avoid strange effects. What strange effects do you expect (other than due to bugs in the mock file system, that can be avoided with an extensive test suite)? -- Remy Remove underscore and anti-spam suffix in reply address for a timely response. From jacek.generowicz at cern.ch Fri Mar 12 11:13:19 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 12 Mar 2004 17:13:19 +0100 Subject: loop scope References: Message-ID: David MacQuigg writes: > On Fri, 12 Mar 2004 14:06:38 GMT, Arthur > wrote: > > >On Thu, 11 Mar 2004 17:54:56 -0700, David MacQuigg > >wrote: > > >>Scopes are defined by the boundaries of functions, classes and > >>modules, not for loops. This is essential, or you would have to > >>declare global variables inside most for loops. > The one exception I can think of is what Terry Reedy mentioned - the > iteration variable in a list comprehension. In some future > optimization, they may neglect to save that variable. I hope they > don't do that (even though it really has no use). I just like the > consistency we now have in treatment of all local variables. You can maintain that consistency by extending the list of "boundaries" which define scopes; you already mentioned classes, functions and modules ... now simply add list comprehensions (or loops), and you will maintain perfect consistency of treatment of local variables, without leaking variables out of list comprehensions (or loops). From http Mon Mar 22 18:20:47 2004 From: http (Paul Rubin) Date: 22 Mar 2004 15:20:47 -0800 Subject: What's missing from python? References: <405ee0d0$0$63627$5a6aecb4@news.aaisp.net.uk> <405f0803$0$15618$afc38c87@news.easynet.co.uk> <7x8yhsj3bm.fsf@ruckus.brouhaha.com> <405f148a$0$10522$afc38c87@news.easynet.co.uk> Message-ID: <7xekrk31v4.fsf@ruckus.brouhaha.com> Peter Hickman writes: > > Python advertises a "batteries included" approach to the library which > > means it's supposed to include most of the stuff that users need, > > instead of making them download the stuff from random places. > > The 'batteries included' stuff is more a distribution / packaging > issue than the standard library. At least coming from Tcl where we > have a 'batteries included' distribution including all sorts of nice > things. However this does not mean that they are part of the standard > library. Well, the contents of the standard library certainly sounds like a distribution/packaging issue to me. > Simple feature / library count as a measure of progress is flawed. Big > time need not equate with bloat, besides Perl has a massive library of > modules (CPAN) but they are not part of the standard library and this > has not held Perl back. When there's enough stuff written for Python, maybe it will also get something like CPAN. However, CPAN is somewhat of a pain in the neck compared to just including the needed stuff. People do ask all the time for a super-sized Perl distribution that includes everything from CPAN, or includes lots more CPAN stuff than the standard distro does, or even for a simple CD-ROM dump of the CPAN contents. > We need to recognize the divide between language features and a basic > distribution. A 'batteries included' distribution of Python, a la Tcl, > which includes a selection of useful libraries is a good idea but > there is no need to make it part of the standard library. > > I want my Python in a Nutshell to be a single volume not an encyclopedia. For sure, there's some attractiveness to making three separate distros: minimal, normal (like the current one), and encyclopedic. However, that's a lot of work, so the current strategy seems to be to have one distro that strikes a reasonable balance between minimal and encyclopedic, providing enough stuff to meet the needs of application implementers in Python's targeted areas. Right now there are significant gaps in the library but with luck that will improve over time. From antonyliu2002 at yahoo.com Thu Mar 4 19:49:09 2004 From: antonyliu2002 at yahoo.com (chad) Date: 4 Mar 2004 16:49:09 -0800 Subject: Parsing xml file using python Message-ID: <14b36d18.0403041649.252d2e7c@posting.google.com> Hello, all, I am new to Python. I need to read an XML document and ignore all XML tags and write only those between the tags to a text file. In other words, if I have an XML document like so: This is a test I need to write "This is a test" to a text file. How do I achieve this? Thanks. From jeremy at alum.mit.edu Mon Mar 15 10:47:34 2004 From: jeremy at alum.mit.edu (Jeremy Hylton) Date: Mon, 15 Mar 2004 10:47:34 -0500 Subject: PyCon BOF schedule Message-ID: <1079365654.3337.83.camel@localhost.localdomain> http://www.python.org/cgi-bin/moinmoin/PyConBofs Sign up for PyCon Birds of a Feather (BOF) sessions, which will be held on March 24 and 25, Wednesday and Thursday evenings, from 8 to 11 pm. A BOF is an informal session, organized by attendees, to discuss a topic of interest. They are held in the evening so that they don't conflict with talks. Jeremy Hylton From jepler at unpythonic.net Fri Mar 5 16:08:36 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Fri, 5 Mar 2004 15:08:36 -0600 Subject: file.readline() after a seek() breaking up lines In-Reply-To: References: Message-ID: <20040305210836.GI31275@unpythonic.net> When you open a file in text mode, the only offsets that are valid for 'seek()' are ones returned by 'tell()' (or 0, presumably). In practice, you can seek to arbitrary offsets on most operating systems, though the results on Windows are confused by the fact that text files store '\n' as a two-byte sequence. This is what the library reference means when it says If the file is opened in text mode (mode 't'), only offsets returned by tell() are legal. Use of other offsets causes undefined behavior. http://python.org/doc/lib/bltin-file-objects.html When you open a file in binary mode, all offsets less than the file length are valid, but in a text file most of them will be in the middle of a line. (they're byte offsets into a file you think of as being made of individual lines) So, anyway, when you seek to a random offset, you are usually in the middle of a line, and the first readline() returns that partial line. You can do one of several things: * Read the file and gather all line offsets, then pick one of them (requires reading the whole file each time) * Read the file in a line at a time and pick the word as you go (If this is the n'th line, then 1/n of the time replace the "line to be printed" with this line. At the end of the file, print the line to be printed) * Read the file once and write an index of offsets. Then, pick a random offset from this file, seek to it, and read * Pick a byte offset, and discard the first line read. You'll never use the very first line of the file, and longer lines are preferred over shorter lines (actually, lines *following* longer lines are preferred...) * Pick a byte offset and scan backwards until you get to the start of the file or the start of a line, then readline. Again, longer lines are preferred over shorter lines by this method * Create a record-oriented format, so that you can seek to a multiple of the record length and read a word. All words must be shorter than reclen. The old unix "fortune" program used the second method. I'm sure there are other things you could do as well. Jeff From Henrik.Weber at sdm.de Tue Mar 9 09:00:15 2004 From: Henrik.Weber at sdm.de (Henrik Weber) Date: 9 Mar 2004 06:00:15 -0800 Subject: Using Pythonwin to poke at Windows apps? Message-ID: <44254d3d.0403090600.3b14d84c@posting.google.com> Hello all, I'm trying to read information about widgets from running instances of win32 applications. My current victim is the Explorer on a XP box. I'm trying to access the menu bar. On XP this is not a standard menu but a toolbar. So far I can retrieve a PyCWnd object with win32ui: >>> e = win32ui.FindWindow("ExploreWClass", None) >>> w = win32ui.FindWindowEx(e, None, "WorkerW", None) >>> w = win32ui.FindWindowEx(w, None, "ReBarWindow32", None) >>> t = win32ui.FindWindowEx(w, None, "ToolbarWindow32", None) >>> t = win32ui.FindWindowEx(w, t, "ToolbarWindow32", None) >>> hex(t.GetSafeHwnd()) '0x602d8' >>> print t object 'PyCWnd' - assoc is 01275A88, vi=, notify=0,ch/u=0/0, mh=0, kh=0 I know that t now refers to a ToolbarWindow32 widget but seemingly win32ui doesn't. Is there a way to get a PyCToolbar object from this? Or do I have to continue by sending messages? I tried sending a TB_GETBUTTON message with win32gui.SendMessage, using a Python array to reserve some memory for the TBBUTTON structure, but so far I have only succeeded in crashing the Explorer. What would be the right way to send a message that needs some memory to put the results into? Thanks Henrik From FBatista at uniFON.com.ar Thu Mar 11 12:50:45 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Thu, 11 Mar 2004 14:50:45 -0300 Subject: Exiting Tkinter when using IDLE Message-ID: I tested the following simple code: ----------------- from Tkinter import * class App: def __init__(self, master): frame = Frame(master) frame.pack() self.button = Button(frame, text="QUIT", fg="red", command=frame.quit) self.button.pack(side=LEFT) self.hi_there = Button(frame, text="Hello", command=self.say_hi) self.hi_there.pack(side=LEFT) def say_hi(self): print "hi there, everyone!" root = Tk() app = App(root) root.mainloop() ----------------- I'm on Python 2.3 (#46, Jul 29 2003, 18:54:32) [MSC v.1200 32 bit (Intel)] on win32. When I double click the program, it works OK. When I execute it from IDLE, the first time I push the "QUIT" button, I just receive a second prompt in IDLE and nothing else happens. The second time I push the "QUIT" button, the program exits, but also exits IDLE! Do you know what's happening? With this behaviour it's difficult to develop using IDLE, :( . Facundo From kkrueger at example.edu Fri Mar 26 15:20:08 2004 From: kkrueger at example.edu (Karl A. Krueger) Date: Fri, 26 Mar 2004 20:20:08 +0000 (UTC) Subject: mod_python exception catching, other repetitious per-page actions References: Message-ID: Jacek Trzmiel wrote: > "Karl A. Krueger" wrote: >> I'm in the middle of refactoring a small mod_python Web application, >> which uses the Publisher handler. > > I have never used Publisher handler myself. Yes, I've read about it, > but I've decided to not use it after seeing that I will have to > explicitly tell which modules/functions I DON'T want external user to > be able to run - completely broken idea from security POV. Actually, Publisher never exposes modules imported into yours. It traverses your module for names and types before exposing anything -- it won't expose any object whose name begins with an underscore, or any module. (Oddly enough, it does expose exceptions, but just their string representation.) If anyone reading this is concerned about Publisher security, these audit functions might help: def AuditModuleForPublisher(module): import types for name in module.__dict__: object = module.__dict__[name] if name.startswith("_"): # name starts with an underscore, not exposed pass elif type(object) == types.ModuleType: # object is a module, not exposed pass elif type(object) == types.FunctionType: print ":: Exposed function:", name elif isinstance(object, str) or isinstance(object, unicode): if "passw" in name or "PASSW" in name: print "!! Your %s password is %s." % (name, object) else: print ":: Exposed string:", name else: print ":: Exposed variable:", name A nicer one: def SymbolsExposedToPublisher(module): return [ sym for sym in module.__dict__ if (not sym.startswith("_")) and (type(module.__dict__[sym]) != type(module)) ] By enumerating the list of functions and variables you *intend* to expose, a unit test should not be too hard to derive from this. >> One thing I have considered is to handle _all_ the pages through a >> single function, which would look up the specific pages by name: > > If you do this then you may as well drop Publisher handler completely. > One handle() function will work for you. I agree. However, since I want the functionality of Publisher's argument name mapping, that is not what I want to do. -- Karl A. Krueger Woods Hole Oceanographic Institution Email address is spamtrapped. s/example/whoi/ "Outlook not so good." -- Magic 8-Ball Software Reviews From piet at cs.uu.nl Wed Mar 10 05:48:57 2004 From: piet at cs.uu.nl (Piet van Oostrum) Date: 10 Mar 2004 11:48:57 +0100 Subject: cmdline args to a piped python prog References: Message-ID: >>>>> "leo" (L) wrote: L> hi there L> a python file can evaluate cmdline arguments like L> python myprog.py arg1 arg2 arg3... L> when i feed python with my program via terminal input like L> cat myprog.py | python L> how can i then specifiy the cmdline arguments arg1 arg2 arg3...? You could say cat myprog.py | python - arg1 arg2 arg3 Then sys.argv[1:] contains the arguments. By the way cat myprog.py | python * is equivalent to python * < myprog.py No need for cat. -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP] Private email: P.van.Oostrum at hccnet.nl From vijay_srr at yahoo.com Wed Mar 3 23:12:17 2004 From: vijay_srr at yahoo.com (Vijay) Date: 3 Mar 2004 20:12:17 -0800 Subject: py2exe in Windowsxp References: <38f75b16.0403022320.1f56ce00@posting.google.com> Message-ID: <38f75b16.0403032012.646eb85@posting.google.com> Thomas Heller wrote in message news:... > Thomas Heller writes: > > > vijay_srr at yahoo.com (Vijay) writes: > > > >> Hello, > >> > >> Is py2exe 0.5.0 supported in Windows XP? In the project homepage in > >> SourceForge.net, only Win95/95/2000 are listed. > > > > Sure. I will correct that. > > Impossible, unfortunately. SF doesn't know about win XP. > > Thomas Does this mean that it is supported but you can't update this information in the homepage in SF? Thanks in advance, Vijay. From skip at pobox.com Wed Mar 31 12:30:34 2004 From: skip at pobox.com (Skip Montanaro) Date: Wed, 31 Mar 2004 11:30:34 -0600 Subject: test for nan In-Reply-To: References: Message-ID: <16491.58.314701.226126@montanaro.dyndns.org> John> Is there a better way to test for NaN than John> str(p1)=='nan' John> where p1 is a float? Saw this in the list archives earlier today: >>> inf = float("1e9999") >>> inf Inf >>> nan = inf-inf >>> nan NaN >>> p1 = 5.0 >>> p1 == nan False Skip From etienne at epoz.org Wed Mar 17 10:35:28 2004 From: etienne at epoz.org (Etienne Posthumus) Date: Wed, 17 Mar 2004 16:35:28 +0100 (CET) Subject: heapq iteration? In-Reply-To: <20040317070212.2058820938.eric@zomething.com> Message-ID: On Wed, 17 Mar 2004, Eric @ Zomething wrote: > I'm missing something critical about how heapq works. I assumed I could iterate through the heap, but I get partial iteration: Do this in stead: l = [56, 208, 89, 413, 273, 199, 73, 21, 89, 13, 27, 199, 273, 413, 11, 22, 56, 2, 208] heapq.heapify(l) while l: m = heapq.heappop(l) print m, '\t', l It is generally not a good idea to modify a list while you are iterating over it. Remember that heappop actually modifies the list. --- EP From fnord at u.washington.edu Fri Mar 5 14:53:53 2004 From: fnord at u.washington.edu (Lonnie Princehouse) Date: 5 Mar 2004 11:53:53 -0800 Subject: Overriding builtin types Message-ID: Dear gurus-at-large, Does anyone know if there's a mechanism to make the interpreter use user-defined classes for interpreting literals, instead of the builtin types? For instance, wouldn't it be cool if the following code raised an exception? -------------------- class IllegalValue(Exception): pass class NaturalNumber(int): base_init = int.__init__ one = 1 def __init__(self, value): NaturalNumber.base_init(self, value) if self < NaturalNumber.one: raise IllegalValue __builtins__.int = NaturalNumber print -1 -------------------- I realize that there are other ways to do this, e.g. print NaturalNumber(-1), but the above just seems like it would be much more elegant. Right now the only way I can see of doing it is to tack on a pre-interpreter that will substitute LITERAL -> ArbitraryFunction(LITERAL) implicitly, but that's a lot of effort and hardly efficient... -ljp From 00515879256 at fastwebnet.it Tue Mar 16 04:14:27 2004 From: 00515879256 at fastwebnet.it (Glauco) Date: Tue, 16 Mar 2004 10:14:27 +0100 Subject: ZSI proxy problem In-Reply-To: References: <3fb251d3.21252950@News.CIS.DFN.DE> <3fb2c34a.3907929@News.CIS.DFN.DE> Message-ID: Does anyone used this library throw an http proxy ? This library is based on httplib and now is not implemented this features. Does anyone added proxy support to httplib ? I'm only with this problem ? Glauco -- -------------------------------------------------------- << Maccaroni! Ma 'che gli ammericani magnano i maccaroni e bevono er vino? Gli ammericani magnano il toast, la mostarda, lo yogurt... ammazza che schifo.. Maccarone, mi guardi? con quella faccia intrepida? Maccarone, m'hai provocato e io me te magno!>> Alberto Sordi -------------------------------------------------------- * glauco at uriland.it * www.uriland.it * ICQ: 115323690 From jbenson at sextans.lowell.edu Mon Mar 8 21:56:54 2004 From: jbenson at sextans.lowell.edu (Jim Benson) Date: Mon, 8 Mar 2004 19:56:54 -0700 (MST) Subject: a desired python editor In-Reply-To: <200403081844.00023.gherron@islandtraining.com> Message-ID: On Mon, 8 Mar 2004, Gary Herron wrote: > On Monday 08 March 2004 06:13 pm, Jim Benson wrote: > > Hi, > > > > Does anyone know of a source code editor for python > > that has the following characteristics: > > > > 1) Freeware (desired) > > 2) Runs on Linux (required) > > 3) Syntax high lighting (required) > > 4) A separate window for each file opened (desired) > > 5) A way of seeing (and jumping to) the names of all methods/functions > > data elements in the file. (required) > > Emacs gives you all of the above As i wrote the email...i had a sneaking suspicion that i should perhaps look back at emacs. On unix i started with vi, moved to emacs then to xemacs, then to others. Its been awhile since i looked at either emacs or xemacs. > > > 1 and 2 are no-brainers, although, as a matter of terminology, > calling it freeware is going cause severe heartburn for some. Yes...i thought about adding a comment about freeware, opensource... but i didn't bother to look up and re-read the documents. I guess i should. My sincere apologies to Richard Stallman and others. I promise to go back and re-read the distinctions. > > Items 3 and 5 come from python-mode.el, which is distributed with > python. > > Item 4 will take a one line bit of configuration. > > Gary Herron Thanks...i'm collecting all suggestions and i will try them out. Jim From peter at engcorp.com Sat Mar 20 17:51:49 2004 From: peter at engcorp.com (Peter Hansen) Date: Sat, 20 Mar 2004 17:51:49 -0500 Subject: Time of Day In-Reply-To: References: Message-ID: Sam Snead wrote: > Is there a formula/function I can use to convert the Unix time stamp to > a time of day? What do you mean by "Unix time stamp"? The number of seconds since the beginning of the epoch? Or something else? time.localtime() would be the most obvious answer, if I'm even nearly answering the right question. From ville at spammers.com Tue Mar 23 11:36:39 2004 From: ville at spammers.com (Ville Vainio) Date: 23 Mar 2004 18:36:39 +0200 Subject: PEP 318 References: <95aa1afa.0403222352.2679dde@posting.google.com> Message-ID: >>>>> "Skip" == Skip Montanaro writes: Michele> def __mul__(self,other) as multimethod(Vector,Scalar): Michele> ... Michele> etc. Michele> Way cool, actually :) Skip> Okay, but can you explain the mechanism or point me to the Skip> original post? I can't find it on Google (probably too Skip> recent). Multimethod(a,b)() won't Too recent, or it's because my name is Vainio, not Vanio :-). Skip> know that each call is for __mul__ will it (maybe it will Skip> peek at the func_name attribute)? From what you posted, all Skip> I saw was multiple definitions of __mul__. Only the last Skip> one will be present as a method in the class's definition. My post didn't offer anything beyond what Michele suggested. I didn't present any clear mechanism to do the trick, but I figured it ought to be possible via func_name attribute, as you suggest. Every declaration would inject a mapping to some global data structure, and the actual function call would look it up somehow. Perhaps the actual callable should be bound to the name by doing f = make_multimethod("f") after doing all the declarations. Sadly this limits the usability by preventing declaration of new variations after the final binding. Obviously the wrapper function could always return the multimethod dispatcher for that function name to force the resulting binding to be the dispatcher at all times. OTOH, I might be misunderstanding something. -- Ville Vainio http://tinyurl.com/2prnb From http Fri Mar 5 22:07:22 2004 From: http (Paul Rubin) Date: 05 Mar 2004 19:07:22 -0800 Subject: securely overwrite files with Python References: <2004030517425550073%bob@redivicom> Message-ID: <7x3c8mr7v9.fsf@ruckus.brouhaha.com> Thomas Bellman writes: > A file system that moves around files when you overwrite them, > will only move the data blocks, not the inode. The inode will > stay the same, and in the same position on the storage device. If the old blocks get moved to new by copying them and then updating the block pointers in place, it may be impossible to find the old blocks by normal means to overwrite them. But data recovery could still find them, so you haven't securely deleted the file by overwriting just the new blocks. There's really no way to securely delete info from a hard drive. The best you can do is encrypt the data so only ciphertext is stored. Then if you manage to securely destroy the decryption key (a much smaller piece of data than the whole file), the file is unrecoverable. In fact you only need enough securely-eraseable media to hold one key, and still be able to maintain destroyable keys for any number N of files, where securely erasing a file takes O(log N) operations. I have a Usenet post with further details and a pointer to some Python code at: http://www.google.com/groups?selm=7xr8hsfsak.fsf_-_%40ruckus.brouhaha.com From fumanchu at amor.org Sun Mar 7 17:08:39 2004 From: fumanchu at amor.org (Robert Brewer) Date: Sun, 7 Mar 2004 14:08:39 -0800 Subject: dynamic names Message-ID: Val Bykoski wrote: > I'm currently in a familiar to many business of filing my tax > return. Being a big fan of Python and to make the process > less painful, > i started by writing my favored schedules A,B,C, and the most favored > form 1040 in Python. Everything was a real fun until i got to the > very famous motif "add lined Lx to Ly". > This is my naive (master)piece: > > def sumL(L1,L2): > # sum up a range of Ls > tot=0. > for L in range(L1,L2+1): > #nL=exec("L%s" % L) > tot=tot + ("L%s" % L) > return tot Val, If I were writing the same thing, I would probably stop using a separate name for L1, L2, etcetera; instead I would put them in a list: def sum_lines(lines, lowerbound, upperbound): tot=0. for line in lines[lowerbound:upperbound + 1]: tot += line return tot >>> lines = [3.0, 4.0, 5.0, 6.0, 7.0] >>> sum_lines(lines, 2, 4) 18.0 Of course, once you've put them in a list, you can just use the builtin sum() function: >>> sum(lines[2:5]) 18.0 ...which saves the extra function definition and call overhead, and makes your code more readable and more manageable. Hope that helps! Robert Brewer MIS Amor Ministries fumanchu at amor.org From jcarlson at nospam.uci.edu Wed Mar 3 21:43:50 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Wed, 03 Mar 2004 18:43:50 -0800 Subject: Numeric array of objects In-Reply-To: <3064b51d.0403031508.53498c6f@posting.google.com> References: <3064b51d.0403031508.53498c6f@posting.google.com> Message-ID: > You create a 1-D Numeric array of n floats with > > x = zeros(n,Float) > > How do you create a Numeric array of n instances of class 'xy', where > for example xy is defined as follows: > > class xy: > def __init__(self,x=0.0,y=0.0): > self.x = x > self.y = y > > I want the elements of the array to be initialized to the default > value of xy, (0.0,0.0). I have read the Martelli's explanation on p309 > of the book "Python in a Nutshell", but I still don't get it. Numeric.array([xy() for i in xrange(n)], Numeric.PyObject) - Josiah From IDONTHAVEEMAIL at ntlworld.com Mon Mar 8 17:12:32 2004 From: IDONTHAVEEMAIL at ntlworld.com (Rich) Date: Mon, 08 Mar 2004 22:12:32 +0000 Subject: Unicode (Japanese) fonts in Images Message-ID: Im trying to create images from a python script which have unicode characters in them. So far Ive tried: PIL: Cant get it to do unicode fonts & It wont give me info like fontAccent. PyGame: Will display unicode fonts, and give me font info but wont display them below about 20points in size, and if I render them large and scale them they look naff. Gimp-Py: Cant get it to work gdmodule: Erm, cant get it to work very well, and ive use it under php and know it dosent give font info ReportLab: Looked great, cant get unicode to work, and it looks from forum postings that you cant do asian fonts into png's ... yet! ImageMagick: Looks great, got everything, font info the lot. But cant get it to do asian fonts ... help! Ive got msgothic/msmincho installed, and Im using PythonMagick and have the following code: from PythonMagick import * from Drawable import * img = Image( '1000x600', 'white' ) img.font = "e:\\winnt\\fonts\\msgothic.ttc" img.fontPointsize = 72 kanji = u'\ufffe\ua295\uc07b' img.draw( Text( 0 , 100, kanji.encode( 'UTF-8' ), 'UTF-8' ) ) img.write( 'magick.gif' ) Am I doing anything obviously wrong? I think Im doing something wrong as at the moment the produced .gif has three squares showing. This is what normally happens when I get the whole unicode thing mixed up. Under php and gd I used to get this when I specified the unicode char string wrong. Am I doing that ... help Many thanks in advance Rich From skip at pobox.com Mon Mar 1 09:57:56 2004 From: skip at pobox.com (Skip Montanaro) Date: Mon, 1 Mar 2004 08:57:56 -0600 Subject: Group comment In-Reply-To: References: Message-ID: <16451.20340.53654.699810@montanaro.dyndns.org> ketulp> Can I comment a group of statements together i.e ketulp> If I a 4 statements say: ketulp> i=1 ketulp> i+=1 ketulp> print i ketulp> print i+1 ketulp> Instead of commenting each satement iindividually by # is there ketulp> something which allws me to comment these 4 statements in one go ketulp> as in C++ using /*...*/ Many people use triple-quoted strings for this: """ i=1 i+=1 print i print i+1 """ It's not a comment, strictly speaking, however it generally achieves the desired results. Even less comment-like is "if False:": if False: i=1 i+=1 print i print i+1 That has the disadvantage that you need to reindent the lines of interest. Skip From o_gloom at mail.com Wed Mar 10 03:47:50 2004 From: o_gloom at mail.com (gloom) Date: 10 Mar 2004 00:47:50 -0800 Subject: DispatchWithEvents when have internal COM interfaces References: <9f115c52.0403090254.3ec6c567@posting.google.com> Message-ID: <9f115c52.0403100047.7b060047@posting.google.com> Well, problem solved. After: cd = nero.GetDrives(NERO_MEDIA_CD)[0] I can do: WithEvents(cd, DriveEvents) and it works. The question is, can I do it without WithEvents, but with DispatchWithEvents() somehow, so I can refer to self? Good day, Omer. From jylevy at pacbell.net Tue Mar 9 00:09:57 2004 From: jylevy at pacbell.net (Jacob Levy) Date: Tue, 09 Mar 2004 05:09:57 GMT Subject: [ANNOUNCE] e4Graph 1.0a11 Message-ID: <404D5214.6040703@pacbell.net> I am pleased to announce the 1.0a11 release of e4Graph, the eleventh Alpha release. This is definitely the final Alpha release for 1.0, the next release is 1.0b1. WHAT IS IT: e4Graph is a C++ library that allows programs to store graph-like data persistently and to access and manipulate that data efficiently. With e4Graph, you can arrange your data in the most natural form that reflects the relationships between its parts, rather than having to force it into a table-like format. The e4Graph library also allows you to concentrate on the relationships you want to represent, and not on how to store them in a database. You can modify data items, and add and remove connections and relationships between pieces of data on the fly. e4Graph allows you to represent an unlimited number of different connections between pieces of data, and your program can selectively manipulate the data according to the relationships it cares about, not having to know about other connections represented in the data set. The e4Graph package also provides bindings in several other languages, currently Tcl, Python and Java, and allows input/output of object graphs via an XML representation. The e4Graph package is built on top of Metakit 2.4.9.2, and optionally uses Tcl 8.4.4, Python 2.2.3, Java 1.1 or later, and Expat 1.95.7. WHERE TO GET: Downloads: http://sourceforge.net/projects/e4graph/ Homepage: http://www.e4graph.com/e4graph/ Changelog: http://www.e4graph.com/e4graph/changes.txt Installation: http://www.e4graph.com/e4graph/e4install.html WHAT IS NEW: I decided to skip 1.0a10 since Daniel Steffen released AquaTclBI for MacOS 10.x which contained a snapshot of the CVS repository and called that "e4graph 1.0a10". This way we avoid confusion between two different sourcebases; the 1.0a10 code in AquaTclBI contains several bugs that are fixed in this release. This release is mainly a bug-fix release. Several bugs related to vertex movement were fixed, and the semantics of vertex addressing and movement have been normalized. Several uses of uninitialized variables were fixed to eliminate random incorrect behaviors. Made callbacks behave more consistently. A bug where a storage was incorrectly being marked as unstable was fixed. A new timestamp mechanism was added to allow applications to poll for events instead of installing callbacks. Several new permissions were added to allow fine control over what a user program can do with a storage. The semantics of vertex and node detach callbacks were changed to be asynchronous, and the timestamp at which a node or vertex detach is recorded is arbitrarily later than the time at which the action actually occurs. A mechanism was added to allow a user program to control whether vertices are cached, to speed up lookup. From http Mon Mar 29 02:53:08 2004 From: http (Paul Rubin) Date: 28 Mar 2004 23:53:08 -0800 Subject: Orders of magnitude References: Message-ID: <7xwu5484yj.fsf@ruckus.brouhaha.com> "Robert Brewer" writes: > I'm dedup'ing a 10-million-record dataset, trying different approaches > for building indexes. The in-memory dicts are clearly faster, but I get > Memory Errors (Win2k, 512 MB RAM, 4 G virtual). Any recommendations on > other ways to build a large index without slowing down by a factor of > 25? Sort, then remove dups. From tmohr at s.netic.de Mon Mar 29 14:25:11 2004 From: tmohr at s.netic.de (Torsten Mohr) Date: Mon, 29 Mar 2004 21:25:11 +0200 Subject: Integer, 64 Bit, signed and unsigned Message-ID: Hi, i'd like to use 64 Bit Integer values in Python, can anybody give me a hint on what are the limits in Python? Can i use signed and unsigned 64 Bit Integers? Thanks for hints, Torsten. From gandalf at geochemsource.com Thu Mar 11 03:56:12 2004 From: gandalf at geochemsource.com (Gandalf) Date: Thu, 11 Mar 2004 09:56:12 +0100 Subject: psycopg problem References: <40501FA1.6030801@geochemsource.com> Message-ID: <405029AC.1070108@geochemsource.com> Oh my god! I tried the same with other modules too. Here are the resulsts: 1. psycopg: when a command fails, it will terminate the trasaction but it tells that it will ignore other commands until the end of the transaction block 2. PyGreSQL: when a command fails, it will terminate the trasaction but it tells that it will ignore other commands until the end of the transaction block 3. pyPgSQL: when a command fails, it will terminate the trasaction without furhter notice (!!!) I see big problems here. I tried these too: Oracle, FireBird, MS SQL, SAP DB. I was able to run an erroneous SQL and then continue my transaction (e.g. execute other commands in the same transaction). In my situation, I just can't tell if a command will fail or not. If would be too hard and too slow to determine if a command will fail or not. Hey, this is why exceptions was born! From the other side, I must be able to commit or rollback all my changes at the end of the block, depending on several things. Can anybody help me please? Gandalf wrote: > > Hi All! > > Every time I get an error psycopg refuses to execute further commands > in the same transaction: > > psycopg.ProgrammingError:ERROR: current transaction is aborted, > commands ignored until end of transaction block > > Why is that? I would like to decide if I want to continue my > transaction or not. Isn't it possible? > > Best, > > G > > From __peter__ at web.de Thu Mar 11 18:00:49 2004 From: __peter__ at web.de (Peter Otten) Date: Fri, 12 Mar 2004 00:00:49 +0100 Subject: subclassing list and adding other variables ? References: <4050d0df$0$289$626a14ce@news.free.fr> Message-ID: GrelEns wrote: > i wonder if this possible to subclass a list or a tuple and add more > attributes ? also does someone have a link to how well define is own > iterable object ? [You tried hard] With lists it is the standard procedure of overriding __init__() and calling the baseclass method: >>> class List(list): ... def __init__(self, iterable, a): ... list.__init__(self, iterable) ... self.a = a ... >>> a = List((1,2,3), "abc") >>> a [1, 2, 3] >>> a.a 'abc' Tuples are immutable and thus changes in __init__() will not affect the tuple items. They are set in the __new__() method instead. >>> class Tuple(tuple): ... def __new__(cls, *args): ... return tuple.__new__(cls, args[0]) ... def __init__(self, seq, a): ... self.a = a ... >>> b = Tuple((1,2,3), "abc") >>> b (1, 2, 3) >>> b.a 'abc' For a minimal iterable class, let __iter__() return self and next() calculate the next value or raise a StopIteration exception when there are no more values: >>> class Iterable: ... def __init__(self, start, maxval): ... self.value = start ... self.maxval = maxval ... def __iter__(self): return self ... def next(self): ... if self.value > self.maxval: ... raise StopIteration ... result = self.value ... self.value *= -2 ... return result ... >>> for n in Iterable(1, 500): ... print n, ... 1 -2 4 -8 16 -32 64 -128 256 -512 (I've got a hunch that Iterator would have been a more appropriate name, but you may judge on your own, see http://www.python.org/doc/current/tut/node17.html) Peter From ark at acm.org Tue Mar 16 20:54:46 2004 From: ark at acm.org (Andrew Koenig) Date: Wed, 17 Mar 2004 01:54:46 GMT Subject: Result of ``a is b'' References: <40200384.0403151632.35496ee6@posting.google.com> <40200384.0403161255.7fca7a8c@posting.google.com> Message-ID: "Axel Boldt" wrote in message news:40200384.0403161255.7fca7a8c at posting.google.com... > Wow. So it seems that the action of "is" on immutables is unspecified > and implementation dependent, thus useless to the programmer. Hardly. It has two fundamental properties, which can sometimes be useful: 1) If x and y refer to the same object, "x is y" yields True. 2) If "x is y" yields True, "x==y" also yields True. Equivalently, if "x==y" yields False, "x is y" also yields False. > Maybe one could redefine "is" on immutables as follows: for strings > and numbers it acts as "==", for tuples it acts as componentwise "is". > That would be a more useful operator IMHO. Can you give a realistic example of code that would benefit from such a change? From bob at redivi.com Tue Mar 2 22:53:14 2004 From: bob at redivi.com (Bob Ippolito) Date: Tue, 2 Mar 2004 22:53:14 -0500 Subject: Group comment References: Message-ID: <2004030222531443658%bob@redivicom> On 2004-03-02 21:30:36 -0500, Ben Finney said: > On Tue, 02 Mar 2004 17:40:27 -0800, Josiah Carlson wrote: >> May as well use an "if False:" construct and gain the benefit of >> visual indentation, regardless of an editor's syntax highlighting >> capability. > > As well as losing any possible ambiguity about whether the code will be > executed. I like it. Some editors will even key in on this, like #if 0 in C. From jcarlson at nospam.uci.edu Sun Mar 28 20:10:15 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Sun, 28 Mar 2004 17:10:15 -0800 Subject: windows ce In-Reply-To: <4066969e$0$5634$636a15ce@news.free.fr> References: <4066969e$0$5634$636a15ce@news.free.fr> Message-ID: > Does anybody know if there is an implementation of python on windows ce? Google is your friend: http://www.google.com/search?q=windows+ce+python&sourceid=mozilla-search&start=0&start=0&ie=utf-8&oe=utf-8 - Josiah From mark at mceahern.com Wed Mar 24 10:07:25 2004 From: mark at mceahern.com (Mark McEahern) Date: Wed, 24 Mar 2004 10:07:25 -0500 Subject: best module for parsing a small xml file In-Reply-To: <4061a11e$0$277$ba620e4c@news.skynet.be> References: <4061a11e$0$277$ba620e4c@news.skynet.be> Message-ID: Geiregat Jonas wrote: > What's the best module for pasring a small xml file ? from xml.dom import minidom doc = minidom.parse(filename) // m From mark at prothon.org Tue Mar 30 01:46:42 2004 From: mark at prothon.org (Mark Hahn) Date: Mon, 29 Mar 2004 22:46:42 -0800 Subject: A 'Python like' language References: <40645d8f$0$10775$afc38c87@news.easynet.co.uk> <1068up4kn49778@news.supernews.com> <58cb60lmovocadg9p3ghu39t4ga343gfvd@4ax.com> <37S9c.58035$cx5.39835@fed1read04> Message-ID: <1J8ac.68390$cx5.23284@fed1read04> I need a better understanding of this. You are suggesting the self stay with a function like a closure of sorts? In my mind, anytime you say obj.func(), func is called on obj, no ifs ands or buts. How could it be otherwise? When would you want it otherwise? You say fragile. What breaks? "Greg Ewing (using news.cis.dfn.de)" wrote in message news:c4avp5$2g4b0b$1 at ID-169208.news.uni-berlin.de... > Mark Hahn wrote: > >> f = someobj.somemeth > >> someotherobj.g = f > >> someotherobj.g() > >> > >> What does the "self" object inside the call to somemeth > >> refer to then -- someobj, or someotherobj? > > > > It refers to someotherobj. > > You have a problem, then. This means passing functions around > is fragile. If you store one in an attribute of an object, it > mutates into something different when you get it back out > again. > > -- > Greg Ewing, Computer Science Dept, > University of Canterbury, > Christchurch, New Zealand > http://www.cosc.canterbury.ac.nz/~greg > From mogmios at mlug.missouri.edu Wed Mar 31 18:21:30 2004 From: mogmios at mlug.missouri.edu (Michael) Date: Wed, 31 Mar 2004 15:21:30 -0800 Subject: wxPython book (was Re: Python Documentation Blows!) In-Reply-To: References: <40699A31.8000708@yahoo.com> <406a753b$0$12020$79c14f64@nan-newsreader-02.noos.net> Message-ID: <406B527A.5010707@mlug.missouri.edu> >There's one in the pipeline. Don't know how much more than that I >should say; I've changed the Subject: line in case the authors are >monitoring this group. > > That's great to hear. If they post a link to somewhere I can sign up to be notified when it's available I'll definately buy a copy. From H.Duerer at gmx.net Mon Mar 22 09:46:30 2004 From: H.Duerer at gmx.net (Holger Duerer) Date: Mon, 22 Mar 2004 14:46:30 +0000 Subject: SHA-based subclass for random module References: Message-ID: <87oeqpaqih.fsf@Ronaldann.demon.co.uk> >>>>> "Raymond" == Raymond Hettinger writes: >> Since the size of plaintext is only 2^53, can't I just >> calculate all 2^53 md5 values in advance, and invert the output >> of MD5Random to get MT outputs, then attack MT just like any >> LFSR? Raymond> Change the plaintext line to read: Raymond> plaintxt = str(Random.getrandbits(self, 128)) Raymond> Now, 128 bits of input space gets digested to 128 bits Raymond> and then only 53 of those bits are used in to compute the Raymond> float. That should preclude the formation of an Raymond> inversion table. I don't know what getrandbits does exactly. But if it uses the normal PRNG code, doesn't that mean that your plaintext still has only 32 bits of entropy? I.e. if you want to do an inversion lookup table, you would only have to calculate the 2^32 possible outcomes of this call and not all 2^128 theoretically possible ones? Holger From roy at panix.com Fri Mar 12 10:06:36 2004 From: roy at panix.com (Roy Smith) Date: Fri, 12 Mar 2004 10:06:36 -0500 Subject: Xemacs syntax highlighting In-Reply-To: <16465.52956.35691.13784@montanaro.dyndns.org> References: <1d17eeb7.0403111721.7aae9a76@posting.google.com> <16465.52956.35691.13784@montanaro.dyndns.org> Message-ID: On Mar 12, 2004, at 9:53 AM, Skip Montanaro wrote: > >>> What version of python-mode.el are you using? I use the latest >>> version from CVS (4.51). > > Roy> I just downloaded python-mode.el a couple of days ago from > Roy> www.python.org and got version 4.6, for use with GNU Emacs > 21.2.1 > Roy> on my Mac OSX box. > > Hmmm... I'll have to track that down and update it. I don't see > python-mode.el in the source for the python.org website. Do you have > a URL? It's at http://www.python.org/emacs/python-mode/. This also happens to be google hit #1 for "python emacs mode" :-) > > Try the version here instead: > > http://cvs.sourceforge.net/viewcvs.py/python-mode/python-mode/ I'll give that a shot, thanks. BTW, although Apple ships OSX with both emacs and python pre-installed, they don't include the python-mode.el. Any idea what the best way is to suggest to Apple that they include it? They also ship python without gnu readline enabled :-( From remy.blank_asps at pobox.com Tue Mar 9 12:26:14 2004 From: remy.blank_asps at pobox.com (Remy Blank) Date: Tue, 09 Mar 2004 18:26:14 +0100 Subject: "Virtual" file system mock object - replacing stuff in __builtins__ In-Reply-To: <104rjfeotprjqdc@news.supernews.com> References: <404844e3$1@epflnews.epfl.ch> <104rjfeotprjqdc@news.supernews.com> Message-ID: <404dfe36$1@epflnews.epfl.ch> John Roth wrote: > "Remy Blank" wrote in message > news:404844e3$1 at epflnews.epfl.ch... >>Now my questions: >> - Am I doing something fundamentally forbidden (replacing stuff in >>existing modules like __builtins__ or os)? > > Yes. It's never a good idea to replace stuff on the system > level, and some day it might become impossible. That's too bad. When test-driving code in C++, you have to use an abstraction layer between your code and the file system accessors, to be able to replace it by a mock object for testing. I always thought it was an advantage of Python to be able to use the "native" calls and still replace them by stubs for testing purposes. > Well, I don't know about "better" but what I've discovered > is that file system scans are ideal usages of the Visitor pattern. > I've got a single module that contains the guts of the file > system scanner and a number of useful utility methods (such > as loading a file into memory, writing it out and setting the > stats). The visitor pattern really is an elegant solution for scanning a file system. I think I'll give it a try. If I understand you correctly, your scanner module is the abstraction layer I mentioned above, and you can replace it by stubs for test cases. Maybe that's the most reasonable way to go. But it would still be useful to have a generic scanner mock object that simulates a file system. -- Remy Remove underscore and anti-spam suffix in reply address for a timely response. From aahz at pythoncraft.com Fri Mar 5 08:35:51 2004 From: aahz at pythoncraft.com (Aahz) Date: 5 Mar 2004 08:35:51 -0500 Subject: OT: Lisp isn't chocolate (was Re: OFF-TOPIC:: Why Lisp is not my favorite programming language References: <165b3efa.0403030443.4d591f04@posting.google.com> Message-ID: [c.l.py added back in] In article , Ray Dillinger wrote: >nobody wrote: >> >> This article is posted at the request of C.W. Yang who asked me to >> detail my opinion of Lisp, and for the benefit of people like him, >> who may find themselves intrigued by this language. > >The solution to your problem is obvious. Just treat Lisp like >Chocolate; if you don't like it, you can't have any. OTOH, using a braindead netnews client that reposts the same content tends to destroy one's credibility. ;-) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Do not taunt happy fun for loops. Do not change lists you are looping over." --Remco Gerlich, comp.lang.python From afriere at yahoo.co.uk Thu Mar 18 19:41:14 2004 From: afriere at yahoo.co.uk (Asun Friere) Date: 18 Mar 2004 16:41:14 -0800 Subject: Result of ``a is b'' References: <40200384.0403151632.35496ee6@posting.google.com> <40200384.0403161255.7fca7a8c@posting.google.com> <40200384.0403170530.57b6bba4@posting.google.com> <38ec68a6.0403171750.7a300cb2@posting.google.com> <40200384.0403180514.341fe3b0@posting.google.com> Message-ID: <38ec68a6.0403181641.5c416b30@posting.google.com> axelboldt at yahoo.com (Axel Boldt) wrote in message news:<40200384.0403180514.341fe3b0 at posting.google.com>... > Probably because basic built-in strings form a type > that's not a class and you can't inherit from it. You sure can! (Providing, of course your python is >= 2.2) Try this: class MyString (str) : pass foo = MyString('the things you can do in python!') foo.__class__ is MyString isinstance(foo, str) MyString.mro() > > For instance I might have a class 'Name', in a names database, which > > is a specialised string. In this case '==' function looks to the > > contents of the strings being compared, while 'is' tells me whether > > these two strings are the same object. Thus "if name0 == name1 and > > not name0 is name1" will tell me that I am dealing with a duplicate > > record. > > If you make Name a class that contains a string as a data attribute ... Now you know the above all this is irrelevant, yes? I mean composition may be a valid strategy, but it doesn't really address the question, of how your proposed changes would affect inheritence. The problem with my example (well it's probably a problem with the Python definition :P), is that while you could be pretty sure that the condition "if name0 == name1 and not name0 is name1" indicates a duplicate, its facility to find /all/ duplicates is implementation dependent (ie it works because only built-in types like 'int' and 'str' are 'cached' to the same objects, and programmer defined classes such as 'Name' or 'MyString' are not). Which leads to my next point ... > > > a program in which a large (or at least > > important) part of the logic was contained in the __eq__ method to the > > class you created > It might be instructive to play with the difference between identity and equivalence in the abstract. What I mean is this, imagine that 'is' really means 'is' rather the 'is located at.' Given the current implementation (and probably any future implementation), one can do this, bearing in mind the caveat that special considerations apply with regard to some built-in types. Doing so might lead to an appreciation the power of this distinction in an abstract OO context, which in turn might lead towards advocating a very different kind of change to the meaning of 'is.' Rather than inconsistently conflating the concept of identity with equivalence (which imo your proposal does), one might argue for a guarantee that an implementation /never/ cache different instances of a programmer created class to the same memory location. > > I mean you wouldn't really be in a > > situation to advocate a redefinition of the identity/equivalence > > relationship unless you had, would you? > > Why not? Because you would be advocating a change to an aspect of the language you don't use, but which other programmers do. From miki.tebeka at zoran.com Tue Mar 9 01:02:46 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Tue, 09 Mar 2004 08:02:46 +0200 Subject: a desired python editor In-Reply-To: References: Message-ID: <404D5E06.7000303@zoran.com> Jim Benson wrote: > 1) Freeware (desired) > 2) Runs on Linux (required) > 3) Syntax high lighting (required) > 4) A separate window for each file opened (desired) > 5) A way of seeing (and jumping to) the names of all methods/functions > data elements in the file. (required) VIm (http://vim.sf.net) gives you 1-4. If you use ctags you can have 5 as well. Learning curve is steep (just like Emacs) but when you're at the top it's amazing (mouse? we don't need no stinking mouse :-) HTH. Miki From Kyler at news.Lairds.org Thu Mar 11 19:01:54 2004 From: Kyler at news.Lairds.org (Kyler Laird) Date: Fri, 12 Mar 2004 00:01:54 GMT Subject: Extending Python Syntax with @ References: <104vtblamboehab@corp.supernews.com> <2f9050pq22u53o7aqo9i8ebqj11vo9kilg@4ax.com> <1050odofl644aac@corp.supernews.com> Message-ID: <5ga7i1-ug6.ln1@snout.lairds.org> cookedm+news at physics.mcmaster.ca (David M. Cooke) writes: >The lambda depends on a global variable too (or at least, a variable >up one scope). That's quite a significant difference. The *result* of the lambda does not depend on a global variable. >def make_translation_function(GCPs, type, invert=False): > if type == 'LSF' and len(GCPs) < 12: > # Do lots of time-consuming magic to calculate A, B, ... > def LSF_function(x, y): > xy = x*y > lon = x*A + y*B + xy*C + ... > lat = x*G + y*H + xy*I + ... > return (lon, lat) > return LSF_function Ah...*that's* what I needed. I hadn't considered that a defined function could be passed out of the scope like that. Thank you. --kyler From cyhawk at sch.bme.hu Fri Mar 19 11:48:32 2004 From: cyhawk at sch.bme.hu (Darabos Daniel) Date: Fri, 19 Mar 2004 17:48:32 +0100 Subject: lambda trouble Message-ID: Hi! I was doing something like this: >>> def p( x ): ... print x ... >>> l = [] >>> for i in range( 5 ): ... l.append( lambda: p( i ) ) ... >>> for k in l: ... k() ... 4 4 4 4 4 And it surprised me a little. I was expecting to see 0, 1, 2, 3, 4. After some brainwork I now kind of understand what happens and I even found a solution like this: >>> def mylambda( fn, *args ): ... return lambda: apply( fn, args ) ... >>> l = [] >>> for i in range( 5 ): ... l.append( mylambda( p, i ) ) ... >>> for k in l: ... k() ... 0 1 2 3 4 But I still feel a bit unsatisfied. Do you have some advice for me? Cheers, Daniel From axelboldt at yahoo.com Wed Mar 17 18:19:30 2004 From: axelboldt at yahoo.com (Axel Boldt) Date: 17 Mar 2004 15:19:30 -0800 Subject: Semantics of == References: <40200384.0403161538.7407d9e2@posting.google.com><4057A2A0.CC63C070@alcyone.com> <40200384.0403170657.5c81a456@posting.google.com> Message-ID: <40200384.0403171519.418a73a4@posting.google.com> "Terry Reedy" wrote > I vaguely remember a discussion on PyDev list, some years ago, of > 'equality' of infinite recursive structures. I believe there was a change > in the direction of simplicity and robustness to the current algorithm from > a more ambitious algorithm that might have detected s != w -- but which > sometimes had problems. Nowadays, an equality test which detects difference of s and w could be defined by comparing the strings pickle.dumps(s) and pickle.dumps(w). Axel From srovner at us.ibm.com Thu Mar 4 13:57:58 2004 From: srovner at us.ibm.com (Sonia Rovner) Date: 4 Mar 2004 10:57:58 -0800 Subject: tkFileDialog.askopenfilename Message-ID: <8a5a6d82.0403041057.30d4c773@posting.google.com> tkFileDialog.askopenfilename only allows you to open an existing file. I want to allow my users to enter a new filename in the dialog box. Can anyone help? From mwilson at the-wire.com Thu Mar 18 09:47:43 2004 From: mwilson at the-wire.com (Mel Wilson) Date: Thu, 18 Mar 2004 09:47:43 -0500 Subject: loop scope References: Message-ID: In article , Jacek Generowicz wrote: >mwilson at the-wire.com (Mel Wilson) writes: > >> Far too few. After the `nested x` statement comes >> `nested nested x` and `nested nested nested x`, > >Nope. You would never write more than one "nested". It would be an >instruction to Python _not_ to treat the name as local, [ ... ] Sorry. Bad reading. I came to my senses sometime yesterday. I don't like the idea of rebinding names non-locally, but that's taste. Nothing to do with the logic of your idea. Regards. Mel. From ketulp_baroda at yahoo.com Wed Mar 3 04:53:17 2004 From: ketulp_baroda at yahoo.com (ketulp_baroda at yahoo.com) Date: 3 Mar 2004 01:53:17 -0800 Subject: Escape problem References: Message-ID: Jeff Epler wrote in message news:... > The exact answer depends on what library you're using in your > application. > > THe low-level answer is that you must properly escape characters that > would otherwise be treated specially by html. > > For example, the output needs to look like this > > > ... > > > If you do not escape or otherwise treat specially the " characters, the > resulting non-html output will contain something like > > > ... this kind of bug can also lead to cross-site scripting (XSS) problems, > for instance if an attacker can control the string in question and sets > it to something like '">'... > > Jeff Thanks that solyed my problem From ramen at lackingtalent.com Mon Mar 15 11:12:07 2004 From: ramen at lackingtalent.com (Dave Benjamin) Date: Mon, 15 Mar 2004 16:12:07 -0000 Subject: Static Typing in Python References: <1056g3f7jnt2jcc@news.supernews.com> Message-ID: In article , Miki Tebeka wrote: > Hello John, > >>>Who says Python is not strongly typed? Python *is* >>>strongly typed. The problem I am facing is that Python >>>is also dynamically typed, and I want static typing. >> >> >> So do a lot of other people. If you want static >> typing, go use a language that has it, like Java, >> C++ or C#. > You can give ML (http://www.ocaml.org/) a try. All the type checking you > can think of... Without the strong finger-typing! =) -- .:[ dave benjamin: ramen/[sp00] -:- spoomusic.com -:- ramenfest.com ]:. : please talk to your son or daughter about parametric polymorphism. : From whisper at oz.net Mon Mar 8 22:05:43 2004 From: whisper at oz.net (David LeBlanc) Date: Mon, 8 Mar 2004 19:05:43 -0800 Subject: a desired python editor In-Reply-To: Message-ID: > 1) Freeware (desired) -check! > 2) Runs on Linux (required) -check! > 3) Syntax high lighting (required) -check! - over 20 languages > 4) A separate window for each file opened (desired) -check! (tabs) > 5) A way of seeing (and jumping to) the names of all methods/functions > data elements in the file. (required) -check! (folding) > Scite - http://www.scintilla.org From joshway_without_spam at myway.com Mon Mar 15 14:29:57 2004 From: joshway_without_spam at myway.com (JCM) Date: Mon, 15 Mar 2004 19:29:57 +0000 (UTC) Subject: Static Typing in Python References: <4055a71e$0$28265$afc38c87@news.easynet.co.uk> Message-ID: Jacek Generowicz wrote: > Ludovic Aubry writes: ... >> > Try as you will, Python would not allow you to do any of these things, >> > because it is _strongly typed_ with respect to these operations on these >> > types. >> Python will allow you to multiply string with integers for example ;) > Yes, and in that respect it is weakly typed. Here I disagree. Python has a rule for multiplying a string and an integer--this isn't an exmaple of weak typing. No re-interpretation of data representation is being done. From danb_83 at yahoo.com Thu Mar 18 16:24:51 2004 From: danb_83 at yahoo.com (Dan Bishop) Date: 18 Mar 2004 13:24:51 -0800 Subject: loop scope References: Message-ID: Jacek Generowicz wrote in message news:... [snip] > Imagine (for the sake of brevity of argument --- I wouldn't dream of > suggesting such a "line-noise" syntax for Python) that you could use > "x := 3" to mean "create a new local binding for x", while "x = 3" > would mean "find the innermost x and rebind it", with function > parameters, loop variables, list comprehension variables all behaving > as if they were using ":=". Now you'll find that you gain a lot of > flexibility to do what is appropriate with scopes of variables used in > loops etc., and you have an opportunity to fix the immutability of > closures ... > > (Of course there are "issues" ... what happens, for > example when you say > > def foo(a): > a := 3 > a := 4 > > ... does that make three nested scopes for a?, is it an error?) One way to avoid this problem is to have an explicit scope-creating construct instead. def foo(a): scope outer: a = 3 scope inner: a = 4 print a # prints 4 print outer.a # prints 3 print foo.a # prints the function parameter print a # inner.a is out of scope, so prints 3 foo.b = 5 # Creates a new function-scope variable. print b # prints 5 From theller at python.net Thu Mar 11 08:36:15 2004 From: theller at python.net (Thomas Heller) Date: Thu, 11 Mar 2004 14:36:15 +0100 Subject: py2exe win32all: Can write, but not read FileVersion ... References: Message-ID: "Werner Merkl" writes: > Hi, > > > Python is really great, for small to big programs. For my colleagues and > some circumstances I sometimes need to "compile" a script using py2exe. > > Cause I use Windows, I like to use the (Windows) ability, to add some > version infos, comments, etc to the exe file. > > If I use explorer to check, these properties are visible and correct. > But if I use _win32api.GetFileVersion_ , I get nothing for the language > dependent resource... > > At the end you may see my example source code, which is almost the > original code from win32all and py2exe. Just compile and start. This is a known (to me, at least) bug: the version info resources are probably not correct - they also don't show up on win98. But I never cared enough to fix that. It would be great if someone could do this, the code is all in Python, in py2exe\resources\VersionInfo.py. > BTW: I found the same behavior for (most/all?) .pyd from win32all > and for PythonWin.exe. That may, or may not, be related. I have no idea. Thomas From goodger at python.org Tue Mar 9 11:31:05 2004 From: goodger at python.org (David Goodger) Date: Tue, 09 Mar 2004 11:31:05 -0500 Subject: Remembered arguments to a function In-Reply-To: <20040309160842.66870.qmail@web60108.mail.yahoo.com> References: <20040309160842.66870.qmail@web60108.mail.yahoo.com> Message-ID: <404DF149.4030605@python.org> wruuqr ewfjbc wrote: > Should I have expected the behavior of this function? > Is this a bug? Is it wise to exploit this behavior? That's a FAQ. See , question 4.21 "Why are default values shared between objects?". -- David Goodger From frr149 at telefonica.net Fri Mar 5 04:01:55 2004 From: frr149 at telefonica.net (Boogie El Aceitoso) Date: Fri, 05 Mar 2004 10:01:55 +0100 Subject: Python's equivalent of C++ std::multimap Message-ID: Hi, What's Python's equivalent of C++'s std::multimap? Is there any 'multidict'? O:-) Thanks From P at draigBrady.com Tue Mar 30 04:22:35 2004 From: P at draigBrady.com (P at draigBrady.com) Date: Tue, 30 Mar 2004 10:22:35 +0100 Subject: ESR's fortune.pl redone in python - request for critique In-Reply-To: References: Message-ID: <40693C5B.2060101@draigBrady.com> Adelein and Jeremy wrote: > I have recently completed a mini-project with the goal of rewriting > in Python Eric Raymond's fortune.pl script > (http://www.catb.org/~esr/fortunes/fortune.pl-unconfuse-apache), I did a very quick fortune file parser as part of: http://www.pixelbeat.org/rotagator P?draig. From ssk at chol.net Thu Mar 25 17:05:15 2004 From: ssk at chol.net (Sam Kong) Date: 25 Mar 2004 14:05:15 -0800 Subject: How do I get the reference of window in DOM? Message-ID: Hello! Now I know how to get dom of ie using the following code. from win32com.client import DispatchEx ie = DispatchEx('internetexplorer.application') ie.visible = 1 ie.navigate(url) dom = ie.Document My question is that how do I get the window reference from dom? I want to close the ie from my Python code. I don't know how to access the window object. ie.Window is not the answer. Thanks in advance. Sam From newsgroups at jhrothjr.com Sun Mar 28 20:31:38 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Sun, 28 Mar 2004 20:31:38 -0500 Subject: Prothon Prototypes vs Python Classes References: <106dukh7ncf9ad4@news.supernews.com> <106eo695a9t8820@news.supernews.com> Message-ID: <106ev65lpu59614@news.supernews.com> "John Roth" wrote in message news:106eo695a9t8820 at news.supernews.com... > "Harald Massa" wrote in message > news:Xns94BBF152E6BBcpl19ghumspamgourmet at 62.153.159.134... > > Mark, > > > > I see most discussion about Prothon is concerning prototypes. > > > > Can you explain to me in easy words, why it is NOT possible to integrate > > prototypes into Python to stand "side by side" with classes? > > > > I never had a problem to "add an attribute" to an existing object; I > really > > can't see why it should be more than some small hacks to allow "adding a > > function to an existing object". > > As you note, you can do that with a simple assignment, > and it will work. The two problems are: > > 1. The clone operation > > 2. Syntax sugar to make it all nice and palatable. > > I suspect that a usable clone() operation is less > than 10 lines. The syntax sugar, on the other hand, > will IMNSHO, take forever to get agreement. > > John Roth Sigh. I'm replying to my own post. After I posted this, I remembered that something needs to be done to set up an inheritance chain among instances. That requires a custom __getattribute__() magic method, which will not be all that easy to write. John Roth > > > > > > Harald > > From jamesl at appliedminds.com Wed Mar 24 14:25:37 2004 From: jamesl at appliedminds.com (James Laamnna) Date: 24 Mar 2004 11:25:37 -0800 Subject: Problems with py2exe 0.50 and win98se and win2k Message-ID: So, users of my program have been reporting the following: On Win98SE the program refuses to start, at all. On Windows2000, they get a dialog box saying: "The procedure entry point IsWow64Process could not be located ... in kernel32.dll" Screenshot: http://not-9-plz.com/beibhinn/kort.jpg With previous py2exe versions, there have been no problems. Any help? Thanks. From wmwd2zz02 at sneakemail.com Sun Mar 14 19:39:05 2004 From: wmwd2zz02 at sneakemail.com (Greg Ewing (using news.cis.dfn.de)) Date: Mon, 15 Mar 2004 13:39:05 +1300 Subject: Python style guidelines In-Reply-To: <92c59a2c.0403122308.35513650@posting.google.com> References: <3064b51d.0403101112.3449e987@posting.google.com> <4050EAA3.9010807@wberry.org.x> <92c59a2c.0403122308.35513650@posting.google.com> Message-ID: MetalOne wrote: > I finally agree that long unabbreviated names are better. Years later, > I realize that expressions can be hard to read with long variable > names. It occurs to me that mathematics always use one character > variables like x,y,z or the greek symbols. I think the important thing is not to use *arbitrary* abbreviations. There is usually more than one plausible way to abbreviate a long word to a medium-size word. Remembering that it's abbreviated and exactly how it's abbreviated is a cognitive burden that one can do without. Deciding on no abbreviations cuts out a whole lot of degrees of freedom that provide little benefit. Extremely short names in the mathematics style are something else, I think -- not so much abbreviations as a different approach to naming altogether. It often makes sense, especially if the names tie in with symbols used in mathematics literature on the subject. Also, local names are different from global ones. It probably doesn't matter much what sort of names you use locally, but global ones need to be as memorable as possible. Descriptive, fully-spelled-out names seem to be best for that. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From anton at vredegoor.doge.nl Tue Mar 16 18:18:33 2004 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Wed, 17 Mar 2004 00:18:33 +0100 Subject: SHA-based subclass for Random module References: <7xhdwsjpib.fsf@ruckus.brouhaha.com> Message-ID: <40578bfa$0$9515$3a628fcd@reader1.nntp.hccnet.nl> Paul Rubin wrote: >http://www.nightsong.com/phr/python/sharandom.py > >This is intended to be less predicable/have fewer correlations than >the default Mersenne Twister or Wichmann-Hill generators. Comments >are appreciated. Nice idea, and thanks for SHAring, but I can't comment about its predictability. What I know about MD5 or SHA is that these algorithms try to dislocate bits as fast as possible per iteration. Consider the code below not as a tested random function but as an exercise in floating point bit twiddling. (although it seems to work reasonably well in a scatterplot) Anton """ I used this URL: URL: http://www.psc.edu/general/software/packages/ieee/ieee.html more specific, this line: S EEEEEEEEEEE FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF and this : If 0= 14: s0,s1,offset = f(s0),f(s0+s1),0 b = chr(ord(s1[offset]) | 0xf0) c = s1[offset+1:offset+7] offset += 7 return struct.unpack('>d','?'+b+c)[0]-1 def test(n=10000): return sum([arand() for i in xrange(n)])/n if __name__=='__main__': print test() From jcb at iteris.com Fri Mar 12 17:12:38 2004 From: jcb at iteris.com (MetalOne) Date: 12 Mar 2004 14:12:38 -0800 Subject: Want to build an interactive TopLevel for Javascript Message-ID: <92c59a2c.0403121412.7babab0e@posting.google.com> I would like to build an interactive interpreted mode(TopLevel) similar to what Python provides when run without a script. I want the TopLevel interpreter for JavaScript. I don't care about JavaScript needing to access a web browser DOM. I just want to try out basic language statements. I know there is jscript.dll in my winnt\system32 directory. I am guessing that it supports COM. I figure this would be just a few lines of Python code, but I don't know how to get started. From shoot at the.moon Thu Mar 11 15:33:22 2004 From: shoot at the.moon (Steve Horsley) Date: Thu, 11 Mar 2004 20:33:22 +0000 Subject: Solaris knows I'm using pexpect! Message-ID: I am trying to automate changing of a password for a particular user account (for use by scripts, not people). I am trying to use the command "passwd testuser" as root. Of course I can do this by hand. I have succesfully used pexpect to do this in a script on Linux, a bit like this: import pexpect p = pexpect.spawn("/bin/sh") p.sendline("passwd testuser\r") pw = randomPassword() p.sendline(pw + "\r") p.sendline(pw + "\r") I skipped the checking code in the above summary. This works fine on Linux, but on Solaris, the response to "passwd testuser" is "Access denied" rather than "Enter new password:". Solaris somehow knows I'm using expect rather than directly driving the passwd command, and won't play ball. Does anyone know how I can automate this password change? Thanks, Steve. From ataru at nospam.cyberspace.org Wed Mar 3 09:30:21 2004 From: ataru at nospam.cyberspace.org (Christopher Benson-Manica) Date: Wed, 3 Mar 2004 14:30:21 +0000 (UTC) Subject: OFF-TOPIC:: Why Lisp is not my favorite programming language References: <165b3efa.0403030443.4d591f04@posting.google.com> Message-ID: In comp.lang.c nobody wrote: ^^^^^^^^^^^ > This article is posted at the request of C.W. Yang who > asked me to detail my opinion of Lisp, and for the benefit > of people like him, who may find themselves intrigued by > this language. Wow, isn't that nice of you to post for Mr. Yang. I'm sure I, like everyone on comp.lang.c, is utterly fascinated by Lisp and Mr. Yang's critique of it. Likewise, I'm sure, for the happy inhabitants of comp.lang.c++, comp.lang.java.programmer, and comp.lang.python. Followups set, anonymous crossposting troll. > The opinions expressed herein are my personal ones, coming > from several years of experience with Lisp. I did plenty of > AI programming back in the day, which is what would now be > called "search" instead. > Due to time constraints, I will refrain from posting any > follow-ups here. Participants of other newsgroups are well > aware of comp.lang.lispers' tendency to engage in personal > attacks, so a productive discussion with them is unlikely > anyway. > Permission is granted to copy and distribute this document > without restrictions. > ========================================================= > Why Lisp is not my favorite programming language. > ========================================================= > (In the following, "Lisp" refers to ANSI Common Lisp) > This article is a collection of facts anyone interested in > Lisp should know about. > --------------------------------------------------------- > FACT 1: The fastest Lisp implementations are slow > (See any third-party benchmark: The Great Computer Language > Shootout comes to mind, but the Coyote Culch test is in my > optinion even better: it is a professional-quality > interlanguage benchmark) > As a rule of thumb, the most hand-optimized Lisp programs > will be longer than their C/C++ equivalents, and will run > 2-20 times slower using the best compilers. > This alone is half the truth. To get such performance out > of Lisp, one has to add type declarations and shed all > safety checks, which is analogous to casting /everything/ > to (void*) in C. This is needed to turn off type tag checks > at run time. > Sadly, Lisp code that was posted to USENET by Pascal > Bourguignon for the Coyote Gulch test did not measure up > even to these low expectations and was 31.6 times slower > than C++, using CMUCL 18d as a Lisp compiler and Intel C++ > 7.1 (with -O3 -xW optimization switches) as a C++ compiler > on Pentium IV. > --------------------------------------------------------- > FACT 2: No one but a small clique of fanatics likes it > No matter how odd or perverted the cause, there will be > followers. In fact, the odder the cause, the fewer, but > more fervent its followers are. Look at any religious cult, > like Scientology, or take a peek in comp.lang.lisp and > listen to Lisp zealots talk about 'making sacrifices for > the cause' (in all seriousness!). Look up "a public > apology" thread started by Pascal Costanza as an excellent > example. > ZEALOTS STOP AT NOTHING TO ADVANCE THEIR CAUSE, AND > PERSONALLY ATTACKING ANYONE WITH A DISSENTING OPTINION IS > THE FIRST THING IN THEIR ARSENAL. > --------------------------------------------------------- > FACT 3: The vast majority of people who study Lisp in > school, never want to use it again. > You should already know this if you studied or taught CS > where Lisp courses were offered. Even those students who > are fond of Scheme are usually disgusted by Lisp. > --------------------------------------------------------- > FACT 4: Lisp is the most complicated language in the world > It has the biggest standard specification document, which > is also the most obfuscated one - something a lawyer > pretending to be a programmer could have written. C, C++ > and Fortran 95 specs are much better written, by people who > can communicate directly and eloquently. > --------------------------------------------------------- > FACT 5: Despite its size, Lisp does not define threads or > GUI. > Large libraries are very useful when programming, however > Lisp's many functions and macros hardly qualify. > --------------------------------------------------------- > FACT 6: There is no open-source cross-platform native-code > compiler > It was suggested that GCL (GNU Common Lisp) is the only > exception. However, it needs to be noted, that despite its > name, GCL is a dialect of its own, is quite slow even by > Lisp standards, and most alarmingly, unlike with other > compilers, its license requires your, programmer, code to > be GPL if you distribute it with GCL. (Because you will > need to use GCL both as a compiler and a run time library) > --------------------------------------------------------- > FACT 7: There is no standard C interface. > C has become a lingua franca for interlanguage APIs. It may > be unfair, but not having a standard C interface is a > serious problem for any language. > EPILOGUE: > I do not hate Lisp, and I think it was a fine tool decades > ago, and I am not going to say "Lisp sucks". However, now > that we have superior languages for coding close to the > iron, high-performance computing, number crunching, > algorithms, scripting and gluing components together, Lisp > should be finally retired. -- Christopher Benson-Manica | I *should* know what I'm talking about - if I ataru(at)cyberspace.org | don't, I need to know. Flames welcome. (blank lines added below to keep my newsreader happy) From rogerb at rogerbinns.com Mon Mar 29 16:50:35 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Mon, 29 Mar 2004 13:50:35 -0800 Subject: [Fwd: Re: examples of doing syadmin activities as a web app] References: <40660D22.6010200@mlug.missouri.edu><16487.23252.815170.476932@montanaro.dyndns.org> Message-ID: Michael wrote: > I don't know if Python has a way to access an SSL > wrapped XML-RPC server? Don't imagine it'd be to hard to implement > though. I just haven't had a reason to need to since thus far all my > XML-RPC apps don't need to be secure or are inside a secure network. > > Might be worth the effort of implementing? You will need to define your constraints. For example do you need the SSL connections to stay open and be used for multiple requests (I did in my project as I am remoting serial ports). What do you need to do about certificate checking, and is any human intervention allowed/expected? The current Python standard library does no SSL, no certificate checking, and makes a new connection per request. See another thread on the issues behind fixing that, which are a fair bit more involved on the server end. (You also need to consider which Python versions you want to support). Something else you may want to consider is using connections over SSH instead. SSH gives your stdout and stderr from the remote end, so you read what is going on as a progress report. You could structure your app so that a web browser (and/or XML-RPC) is used to talk to the web server, and then from the web server you fan out to the machines being administered by using SSH. That way you can provide feedback, need nothing installed on the machines being admin'ed (except SSH), and do mass changes to multiple machines. Roger From jcarlson at nospam.uci.edu Mon Mar 15 19:32:04 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Mon, 15 Mar 2004 16:32:04 -0800 Subject: SHA-based subclass for Random module In-Reply-To: <7xhdwsjpib.fsf@ruckus.brouhaha.com> References: <7xhdwsjpib.fsf@ruckus.brouhaha.com> Message-ID: > This is intended to be less predicable/have fewer correlations than > the default Mersenne Twister or Wichmann-Hill generators. Comments > are appreciated. FYI: Mersenne Twister is a pretty spiffy pseudo random number generator...it is also /really/ fast. From what I can gather, you are using the SHA hash to behave like a random-number generator through updating the hash with a constant string and the previous state. On the one hand, the SHA hash is not known to be generally invertable for any of the uniquely-mapped 160 bit input strings, or really for any non-trivial initial states or input strings. It could very well be that it is not invertable for any string or state, but I've not done suitable research to know for sure. Quite nice for an invertable perspective and suggesting that short cycles in state are rare, if even possible. On the other hand, you could just as easily use the MD5 hash. The only thing you get from SHA is perhaps more bits of state. I don't know which one is faster though. Now, a good question to be asked is, "What the hell do the SHA and MD5 hashes do?" Really, they take input character-by-character, perterb some current state with some non-trivially flowing functions with feedback, and produce a seemingly-random output that /should/ be uniform over the output space. Whether or not they produce output that /is/ uniform over the output space is probably the result of some involved paper that I've not read. One thing to remember is that the Mersenne Twister is known to cycle in state only after 2**19937-1 calls. Since you haven't done any measurable analysis of your method, or how often it would cycle in state during the repeated re-setting of the state to the hash of some relatively short input-string, that is only pseudo-random near the end (the previous hash), I expect that yours may not fare much (if any) better. One could exploit the features of both, and perhaps end up with a random number generator that cycles less often (if sha cycles in S iterations, and the mersenne twister cycles in M iterations, a new algorithm that cycles in SM iterations is possible, if S and M are coprime), but without actually analyzing their interaction, the behavior of such a random number generator is really only open for speculation. - Josiah From mogmios at mlug.missouri.edu Mon Mar 29 08:59:40 2004 From: mogmios at mlug.missouri.edu (Michael) Date: Mon, 29 Mar 2004 05:59:40 -0800 Subject: Prothon Prototypes vs Python Classes In-Reply-To: <406828F4.2020103@stackless.com> 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> <4067C167.5050708@mlug.missouri.edu> <40681B2B.2080106@stackless.com> <406826CA.6070107@mlug.missouri.edu> <406828F4.2020103@stackless.com> Message-ID: <40682BCC.6020607@mlug.missouri.edu> > If you are on anyone's machine, maybe some Linux server, and > you don't find time to install an editor, then you use vim > for instance, and it depends on its configuration how it > handles Python code. Some indent for you the wrong way. > You have no choice if you are fixing something in a hurry. > I make my living by using several editors on several machines, > all the time. 95 % is ok, but it often comes to situations where > I have to hack "that code on this machine right now", and the user > won't give me the rights or the time to fine-tune my editor > environment. > There is also no choice of "hands-off". The customer wants me > to handle such minor problems as "the expert". > This is no matter of choice but daily practice :-) I understand. It just seems a bad idea to try to make the language work with the editors instead of fixing the editors to work with the language. If you're using spaces to act like tabs instead of tabs just because some editors munge tabs. From richie at entrian.com Tue Mar 30 09:18:50 2004 From: richie at entrian.com (Richie Hindle) Date: Tue, 30 Mar 2004 15:18:50 +0100 Subject: GUI Frameworks in Python? In-Reply-To: References: Message-ID: [Peter] > I'm curious about the differences with wxPython. Three seconds seems > unusually long when on a slightly slower machine I can do it in well > under a second. Was that the first time you ran it? Many other apps > open? I have over 256MB RAM free when I try this... I tried it on this 3GHz 1GB XP box and it took 3.5 seconds to bring up the wxPython demo's splash banner. That was with lots of other stuff running and not having run it before during this session, but with plenty of available RAM and nothing soaking the processor. Try it after a clean boot or a good long disk-cache-hammering spell of doing something else - you might find it's slower than you think. -- Richie Hindle richie at entrian.com From fma at doe.carleton.ca Sat Mar 27 23:29:11 2004 From: fma at doe.carleton.ca (Fred Ma) Date: 28 Mar 2004 04:29:11 GMT Subject: Choosing Perl/Python for my particular niche References: <40652B0D.7C313F77@doe.carleton.ca> Message-ID: <406655A2.CCC571E@doe.carleton.ca> Paul McGuire wrote: > > "Fred Ma" wrote in message > news:40652B0D.7C313F77 at doe.carleton.ca... > > > One thing I expect to have to do is to modify design > > files. For example, there is a tool which takes ASCII > > hardware desscription language (HDL) and converts it > > to a C++ (augmented by hardware simulation library). > > The translator is freeware, so has limitations which I > > have to make up for by tweaking the HDL code. > > If you eventually find yourself in the Python realm, please look into the > pyparsing text parsing module, more information at > http://pyparsing.sourceforge.net/. I have implemented an easily-extended > 99% Verilog parser using this module, and it may provide some shortcuts for > you in dealing with your HDL files. > > -- Paul McGuire Hi, Paul, I took a look at your website. I've decided to go Perl for now, and ramp up on Python on the side. I think a parser has a higher level of intelligence than regex'ing, but I hesitate to jump into it at the moment because thesis time is running out. I may do some adhoc regex'ing, either with sed/Perl/gvim (it's quick and dirty, but suitable for the time crunch of my current circumstance, which is a hard deadline on the thesis). Also, I'm doing the quick-and- dirty because of limitations of an *existing* verilog parser (and translator) which I don't want to delve into right now, for the same reason. But thanks for the heads up. If things work out in the long run, and I get to know Python, I know there is a verilog parser to keep an eye out for. Fred From tjreedy at udel.edu Thu Mar 4 20:05:05 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 4 Mar 2004 20:05:05 -0500 Subject: Especialized generator References: Message-ID: "Boogie El Aceitoso" wrote in message news:hltd409mao1mmlk6kn5rjk00i5342p8pk6 at 4ax.com... > I want to write a generator that specializes on os.walk. It should yield only > certain kinds of files. > > What's the best way of doing this? How do you save the state on the base > generator? For those who didn't get the chaining idea (latter reply): something like def boogie_walk(testarg, *walkargs): for item in os.walk(*walkargs): if : yield item I presume there is also ifilter() or something in itertools that will do the same. Terry J. Reedy From maarten at remove_this_ws.tn.tudelft.nl Fri Mar 26 05:07:00 2004 From: maarten at remove_this_ws.tn.tudelft.nl (Maarten van Reeuwijk) Date: Fri, 26 Mar 2004 11:07:00 +0100 Subject: Vector math References: Message-ID: Josiah Carlson wrote: > Check numarray: > http://www.stsci.edu/resources/software_hardware/numarray > and Numeric Python: > http://www.pfdubois.com/numpy/ I bumped into the same problem, but couldn't find those features, so I wrote them myself using the Numeric package. Below follows an example where I rotate the z-axis 45 degrees. >>> from manips import * >>> from Numeric import * >>> a = array([1,1,1.]) >>> base = [array([1,0,0]), array([0,1,0]), array([0,0,1])] >>> newbase = rotatebase(base, [0,0,45 / 180. * 3.14]) >>> changebase(a, newbase) array([??1.41421345e+00,???5.63088062e-04,???1.00000000e+00]) >>> a = transpose(array([ [1,1,1.],[-1,-1,-1.]])) >>> transpose(changebase(a, newbase) ... ) array([[??1.41421345e+00,???5.63088062e-04,???1.00000000e+00], ???????[?-1.41421345e+00,??-5.63088062e-04,??-1.00000000e+00]]) the 'transpose' commands in the second example are needed because the changebase algorhytm expects an array containing only x, y and z values. Below follow the two routines. HTH, Maarten def changebase(vecfield, newbase): ????"""?Changes?the?base?of?the?vectorfield.?newbase?is?a?list?containing the ???????new?basevectors?(each?is?a?1D-array).?vecfield?is?a?list?containing ???????the?fields?for?the?individual?vector?components?fields.?The?lenght?of ???????the?vecfield?and?newbase?lists?must?be?identical.?The?new?field?is ???????calculated?as: ????????????* ??????????u?????=??u???b ????????????i????????j???i,j ???????Clearly,?the?basevectors?are?the?new?principal?directions?relative ???????to?the?CURRENT?coordinate?system. ???????""" ????vf?=?vecfield ????nb?=?newbase ????nf?=?[] ????if?size([vf[0]])?==?1: ????????isfield?=?False ????????tc?=?vf.typecode() ????else: ????????isfield?=?True ????????tc?=?vf[0].typecode() ????tmp?=?array(vf[0],?tc,?savespace?=?1) ????for?bcomp?in?range(len(newbase)): ????????if?isfield: ????????????tmp[:]?=?0 ????????else: ????????????tmp?=?0 ????????for?vcomp?in?range(len(newbase)): ????????????tmp?=?tmp?+?nb[bcomp][vcomp]?*?vf[vcomp] ????????nf.append(array(tmp)) ????if?not?isfield: ????????nf?=?array(nf,?tc,?savespace?=?1).flat ????return?nf def rotatebase(base, rotation): ????"""?Rotates?the?base?(given?as?a?list?of?lists?or?array?objects)?over?a ????????angle?given?by?rotation.?The?transformation?happens?according?to: ??????????????_?????????????????????_???????????_????????????????????_ ?????????????|??1??????0??????0??????|?????????|?cos?b???0?????sin?b??| ????????Rx?=?|??0??????cos?a??-sin?a?|??;?Ry?=?|?0???????1?????0??????| ?????????????|_?0??????sin?a??cos?a?_|?????????|_-sin?b??0?????cos?b?_| ???????????????????????????????_????????????????_ ??????????????????????????????|??cos?c??-sin?c?0?| ?????????????????????????Rz?=?|??sin?c??cos?c??0?| ??????????????????????????????|_?0??????0??????1_| ???????????????z ???????????????^ ???????????????| ???????????????| ???????????????|??????????????????Rx?:?rotation?along?x-axis?(a?pos?from?y -> z) ???????????????|-------->?y???????Ry?:?rotation?along?y-axis?(b?pos?from?z -> x) ?????????????/????????????????????Rz?:?rotation?along?z-axis?(c?pos?from?x -> y) ???????????/ ?????????x ????????newbase?=?Rx?*?Ry?*?Rz?*?base?(all?matrix?multiplications) ??????""" ????alpha,?beta,?gamma?=?rotation ????sa?=?sin(alpha);?ca?=?cos(alpha) ????sb?=?sin(beta);??cb?=?cos(beta) ????sg?=?sin(gamma);?cg?=?cos(gamma) ????rot?=?array([[cb?*?cg???????????????,?-cb?*?sg???????????????, sb??????],?\ ?????????????????[sa?*?sb?*?cg?+?ca?*?sg,?-sa?*?sb?*?sg?+?ca?*?cg,?-sa?* cb], \ ?????????????????[-ca?*?sb?*?cg?+?sa?*?sg,?ca?*?sb?*?sg?+?sa?*?cg,?ca?* cb ]]) ????newbase?=?[] ????for?bv?in?base: ????????newbase.append(matrixmultiply(rot,?array(bv))) ????return?newbase -- =================================================================== Maarten van Reeuwijk Thermal and Fluids Sciences Phd student dept. of Multiscale Physics www.ws.tn.tudelft.nl Delft University of Technology From s4somesh at yahoo.co.in Tue Mar 2 07:19:36 2004 From: s4somesh at yahoo.co.in (Somesh Bartakkay) Date: 2 Mar 2004 04:19:36 -0800 Subject: wxGlade not Running ! References: Message-ID: <5cc5bb23.0403020419.9c7b14d@posting.google.com> "Delaney, Timothy C (Timothy)" wrote in message news:... > > From: Somesh Bartakkay > > > > i installed wxGlade on System xp, when i started it ..its not > > running ? > > http://www.catb.org/~esr/faqs/smart-questions.html > > Tim Delaney Thanx !! i want to develope GUI for python applications with wxGlade on windows platform (win Xp). i have python 2.2 with wxpython 2.4 and python 2.3 with wxpython 2.4. i installed win32 binary of wxGlade got from sourceforge, i remember at first installation program has successfully launched the application but after that its not running , means NO effect tho i double clicked on icon ... i tried all options even i uninstalled all pythons/wxpythons etc ... From garryknight at gmx.net Mon Mar 29 19:34:25 2004 From: garryknight at gmx.net (Garry Knight) Date: Tue, 30 Mar 2004 01:34:25 +0100 Subject: Integer, 64 Bit, signed and unsigned References: Message-ID: <1080606863.11331.0@nnrp-t71-01.news.uk.clara.net> In message , Peter Otten wrote: > As for signed integers, the sky's the limit :-) Surely that's where you calculate pi... -- Garry Knight garryknight at gmx.net ICQ 126351135 Linux registered user 182025 From gabor at z10n.net Tue Mar 2 10:02:19 2004 From: gabor at z10n.net (gabor) Date: Tue, 02 Mar 2004 16:02:19 +0100 Subject: vim & python In-Reply-To: References: <221dd125.0403011151.504ce09d@posting.google.com> Message-ID: <1078239738.8515.9.camel@dubb> On Tue, 2004-03-02 at 02:48, poiboy wrote: > Normally I use GVim next to .... i always wanted to ask this... why people use GVIm and not the normal-vim-in-a-terminal? what is the advantage of gvim? thanks, gabor From peter at engcorp.com Sat Mar 13 10:13:32 2004 From: peter at engcorp.com (Peter Hansen) Date: Sat, 13 Mar 2004 10:13:32 -0500 Subject: Static Typing in Python In-Reply-To: References: Message-ID: Premshree Pillai wrote: > Not forcing variable initialization does have its > problems. Here's what I mean: http://www.livejournal.com/users/premshree/10624.html?thread=53376#t53376 I believe PyChecker will catch such problems easily in most cases. Also, developing your code using test-driven development entirely avoids that and many other problems without requiring the developer to waste time writing variable declarations all over the place, reducing readability and maintainability. -Peter From karthik at james.hut.fi Wed Mar 3 03:31:01 2004 From: karthik at james.hut.fi (Karthikesh Raju) Date: Wed, 03 Mar 2004 10:31:01 +0200 Subject: best way to read a configuration file Message-ID: <2dy8qimiwq.fsf@itl-pc87.hut.fi> Hi All, i am wondering about the best way to read in a configuration file that goes like: ########### [users] source_dir = '/home/karthik/Projects/python' data_dir = '/home/karthik/Projects/data' result_dir = '/home/karthik/Projects/Results' param_file = $result_dir/param_file res_file = $result_dir/result_file comment = 'this is a comment' K = 8 simulate_K = 0 N = 4000 mod_scheme = 'QPSK' Na = K+2 ###################### As of now i use config parser and i get this in a dictionary but a) but i have users.na and not users.Na (all the fields are in lower case) b) all the rhs arguements are string, but i have handled this by trying " try eval(rhs) ... except ..." block c) Na = 'K+2' though does not work, would like to have Na = 10, but i get users.na = 'K+2' d) result_file, param_file should actually be should be with pathname extensions filled in. Have looked in c.l.py none one ofthe suggestions was to use splitlines, this cant handle blank lines, other was to have config.py .. Hope to get some solution for this .. with warm regards karthik -- ----------------------------------------------------------------------- Karthikesh Raju, email: karthik at james.hut.fi Researcher, http://www.cis.hut.fi/karthik Helsinki University of Technology, Tel: +358-9-451 5389 Laboratory of Comp. & Info. Sc., Fax: +358-9-451 3277 Department of Computer Sc., P.O Box 5400, FIN 02015 HUT, Espoo, FINLAND ----------------------------------------------------------------------- From guettli at thomas-guettler.de Mon Mar 1 07:06:27 2004 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Mon, 01 Mar 2004 13:06:27 +0100 Subject: Image width, height. References: Message-ID: Am Mon, 01 Mar 2004 11:38:11 +0000 schrieb Premshree Pillai: > Hello, > > Is there a Py module available using which I can find > the width and height of any image format? Hello, try 'identify -format "%w %h"' with popen. identify is part of imagemagick. Sorry, that's no python module, but maybe it helps you, too. HTH, Thomas From afriere at yahoo.co.uk Wed Mar 17 19:42:09 2004 From: afriere at yahoo.co.uk (Asun Friere) Date: 17 Mar 2004 16:42:09 -0800 Subject: Result of ``a is b'' References: Message-ID: <38ec68a6.0403171642.7199763c@posting.google.com> "Andrew Koenig" wrote in message news:... > "Robert Brewer" wrote in message > news:mailman.67.1079492061.742.python-list at python.org... > Andrew Koenig wrote: > > "Axel Boldt" wrote in message > > news:40200384.0403161255.7fca7a8c at posting.google.com... > > > > > Wow. So it seems that the action of "is" on immutables is > unspecified > > > and implementation dependent, thus useless to the programmer. > > > > Hardly. It has two fundamental properties, which can > > sometimes be useful: > > > > 1) If x and y refer to the same object, "x is y" yields True. > > > > 2) If "x is y" yields True, "x==y" also yields True. > > Equivalently, if > > "x==y" yields False, "x is y" also yields False. > > Assuming nobody has overridden __eq__, of course. ;) > > Indeed -- if == is redefined so as not to be an equivalence relation, all > bets are off. In fact __eq__ can be redefined even /so as to be an equivalence relation/ such that x==y => True and x is y => False. The 'fundamental properties' posisted, are simply not fundamental. From cs1spw at bath.ac.uk Mon Mar 8 19:08:15 2004 From: cs1spw at bath.ac.uk (Simon Willison) Date: Mon, 8 Mar 2004 18:08:15 -0600 Subject: Sending bulk email from a Python script References: Message-ID: <2004030818081575249%cs1spw@bathacuk> On 2004-03-08 16:42:57 -0600, Steve Lamb said: > Install Mailman and make the list postable only by you. :P We've already looked at mailman and a number of other packages. None of them fit our requirements as we need to be able to tie the list administration in to our existing user authentication / admin control panel, plus we want to tie the email lists to our membership databases. We've got most of the other infrastructure already, we just need an efficient way of sending out bulk emails to a large list of addresses. Thanks, Simon From wmwd2zz02 at sneakemail.com Thu Mar 11 22:12:50 2004 From: wmwd2zz02 at sneakemail.com (Greg Ewing (using news.cis.dfn.de)) Date: Fri, 12 Mar 2004 16:12:50 +1300 Subject: Extending Python Syntax with @ In-Reply-To: <7xptbjdl2f.fsf@ruckus.brouhaha.com> References: <5d83790c.0403111415.6485048@posting.google.com> <7xptbjdl2f.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > What about the assert statement? Should that be a function too? No, because then the compiler wouldn't be able to optimise it away when asserts are turned off. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From bo at systemhouse.dk Sun Mar 7 07:31:27 2004 From: bo at systemhouse.dk (Bo Jacobsen) Date: Sun, 7 Mar 2004 13:31:27 +0100 Subject: New to Python; what about #include, extern and function prototypes References: <20040307020101.539$r9@news.newsreader.com> Message-ID: > In article (Sun, 07 Mar > 2004 05:14:20 +0100), Bo Jacobsen wrote: > > > I'm new to Python, and it looks as if there is no > > C like "#include and extern" or function protypes. > > That's right. > > > No shell like ". > > ../filename" > > I don't understand this part. > > > Is there any way to implement them ? > > I don't know. I've been a C programmer for almost exactly 20 years: Neither > "extern" nor function prototypes are necessary in Python. > > > PS: For me, "import module" is no replacement for include. > > "import" and "#include" do not have exactly the same meaning but they > accomplish more or less the same result. > > What is it you're trying to do that requires these C/C++ features? I'm looking for a future replacement for bash and I have a number of large shell scripts that need to be translated to a language that are better at handling more complicated datatypes. I'm been looking at perl and python, and I really like the strict syntax, handling of function parameters etc. Without include and function prototyping though, will probably have the effect that large source files, with a lot of function definitions at the top, will be generated. Not god. Perl on the other hand has it all, including very productive features as built-in regular expressions, file scanning etc. but I dont like all the type-characters and the "lose" syntax. . ./filename Is the shell "include/execute" command. Bo From No.Spam.mc at No.Spam.mclaveau.No.Spam.com Wed Mar 17 19:05:53 2004 From: No.Spam.mc at No.Spam.mclaveau.No.Spam.com (Michel Claveau/Hamster) Date: Thu, 18 Mar 2004 01:05:53 +0100 Subject: Unicode and UrlEncode! References: Message-ID: OK ?a marche avec : sret=translate_french_to_english('s?dimentation'.decode("latin-1").encode("u tf-8")) et aussi pour : sret=translate_french_to_english('s?dimentation'.decode("latin-1").encode("u tf-8")) Merci pour lui. (thanks). @-salutation -- Michel Claveau From eric at zomething.com Tue Mar 30 00:55:03 2004 From: eric at zomething.com (Eric @ Zomething) Date: Mon, 29 Mar 2004 21:55:03 -0800 Subject: PyPerl 1.0.1 [requires Visual Studio compiler?] Message-ID: <20040329215503.1365541070.eric@zomething.com> It seems like this is the second time I have come across this with a Python module, and I'd like to get some perspective on it. I tried to build PyPerl (on my Win XP machine) and got the following: Microsoft Windows XP [Version 5.1.2600] (C) Copyright 1985-2001 Microsoft Corp. C:\Python23\Lib\site-packages\pyperl-1.0.1>setup.py install running install running build running build_py creating build creating build\lib.win32-2.3 copying dbi.py -> build\lib.win32-2.3 copying dbi2.py -> build\lib.win32-2.3 copying perlpickle.py -> build\lib.win32-2.3 copying perlmod.py -> build\lib.win32-2.3 running build_ext error: Python was built with version 6 of Visual Studio, and extensions need to be built with the same version of the compiler, but it isn't installed. As I'm a just poor boy with a dog, I do not own or use Visual Studio (as nice as it may be). I do have/use the mingw 2.95.2-1 C++ compiler (in case of an emergency or if my life gets too simple). Is it possible to build this module with what I have? Should I expect to need Visual Studio from time to time for building Python modules which dive into C++? Am I totally off track here? Is this just what I get for not absorbing some readme file? Eric Pederson From peter at engcorp.com Wed Mar 17 13:06:22 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 17 Mar 2004 13:06:22 -0500 Subject: Python behaviour with unrecognized string escapes (was Re: imaplib.IMAP4: Bug in implementation) In-Reply-To: <40585BB3.5000307@mxm.dk> References: <40585BB3.5000307@mxm.dk> Message-ID: Max M wrote: > Oliver Kurz wrote: > > > I call the uid like this > > > > uid("STORE",uid,"+FLAGS(\SEEN)") > > > Are you shure you don't mean:: > > uid("STORE",uid,"+FLAGS(\\SEEN)") > > You are trying to create a non-existent special character, escaping the > s in your example. > > I am not quite shure how Python reacts to that. Python 2.3.3 (#51, Dec 18 2003, 20:22:39) [MSC v.1200 32 bit (Intel)] >>> '\s' '\\s' >>> '\\s' '\\s' Seems that it if it doesn't recognize the escape, the effect is the same as if you had escaped the escape character in the first place... -Peter From roy at panix.com Wed Mar 17 22:02:47 2004 From: roy at panix.com (Roy Smith) Date: Wed, 17 Mar 2004 22:02:47 -0500 Subject: New to Python. References: Message-ID: In article , droog wrote: > Hello! > > I have just started learning python and encountered a problem. > All I wanted to do, was to open a text file search and count the > number of occurances of a single word and print that count. > Thanks for help. > Well, I'll point you in the right direction. To open a file, use the "open" function. You can loop through the lines with something like "for line in file:". Depending on exactly how you define "word", you might want to look at the split() string method, or maybe some regular expression matching with the "re" module. There, that should be enough to get you started with your homework assignment :-) From JasonHarper at pobox.com Sun Mar 14 19:15:00 2004 From: JasonHarper at pobox.com (Jason Harper) Date: Sun, 14 Mar 2004 17:15:00 -0700 Subject: Exiting Tkinter when using IDLE References: <87y8q52pvb.fsf@hydra.localdomain> <4052BD1F.B8190E0D@pobox.com> <87brmz3khm.fsf@hydra.localdomain> <4054A2A5.9032BE1B@pobox.com> Message-ID: <4054F475.C71B96EA@pobox.com> Ok, this hasn't been tested very well, but it seems to make IDLE+subprocess work as I'd want it to with Tkinter applications. Just replace Lib/idlelib/run.py with this file: http://home.earthlink.net/~jasonrandharper/run.py You can even do interactive experimentation with Tkinter now. Try this: >>> from Tkinter import * >>> root = Tk() >>> mainloop() At this point, IDLE's shell window would normally cease to accept input. Now, you immediately get a prompt back, although internally it's working rather differently than a normal prompt. Meanwhile, the Tk window is fully movable, resizable, and closable. >>> Button(root, text="spam!").pack() The button immediately appears and is clickable (of course, it doesn't do much). >>> Button(root, text="die!", command=root.destroy).pack() If you use this button, or close the window, the mainloop will exit. You'll need to create a new root window, and start a new mainloop() if you want to do anything further with Tk. Jason Harper From no at sp.am Mon Mar 22 19:34:32 2004 From: no at sp.am (DH) Date: Mon, 22 Mar 2004 18:34:32 -0600 Subject: The problem with "as" [was "Re: PEP 318"] In-Reply-To: <8ef9bea6.0403221354.574ebdaf@posting.google.com> References: <99dce321.0403211817.3704fe2@posting.google.com> <7x1xnlqs77.fsf@ruckus.brouhaha.com> <8ef9bea6.0403221354.574ebdaf@posting.google.com> Message-ID: <1M-dnXrds_WKG8LdRVn-jw@comcast.com> Paul Rubin wrote: >"def foo() as staticmethod" certainly looks best to me aesthetically. It does look better with simple examples. But think of other potential uses for an "as" keyword, and it might have problems. Visual Basic uses "as" in function declarations to declare types, not for function decorators. VB example: Function foo (x as Integer, y as Float) as Integer Possible future Python example that uses "as" differently: def foo(x as int, y as float) as int: "this function returns an integer, and takes an int & float params" If we use the list syntax for decorators instead of "as", we might be able to do something like: def foo(x as int, y as float) [synchronized, classmethod] as int: ... See this thread: http://mail.python.org/pipermail/python-dev/2004-February/thread.html#42780 From claird at lairds.com Sat Mar 27 21:11:40 2004 From: claird at lairds.com (Cameron Laird) Date: Sun, 28 Mar 2004 02:11:40 -0000 Subject: Choosing Perl/Python for my particular niche References: <40661C14.8365E058@doe.carleton.ca> Message-ID: <106cd2srpsjq571@corp.supernews.com> In article <40661C14.8365E058 at doe.carleton.ca>, Fred Ma wrote: . . . >On the topic of speed, It's surprising to hear that this can be possibly rivaled >by Perl/Python, considering that even my matlab code is about 10x slower than >C++. That's with extensive profiling and round-about coding styles to exploit >vectorization tricks, and no such effort in the C++ code. Some of the >limitations are pretty fundamential e.g. large speed penalties for invoking >nonbuiltin functions. Such limitations discourage clear coding practice e.g. >huge swaths of code to avoid encapsulating some functionality in its own >function. Together with the sometimes roundabout coding style, it can detract >from the matlab's high level ease of programming and clarity, especially >considering that C++ can be brought to a high level with its STL library. And >this speed disparity shows up despite matlab's mission to develop in a way that >rivals 3G languages. Speed considerations aside, however, matlab is infinitely >easier to use and to read. With time, perhaps the limitations will shrink. > >This is not to say that Perl/Python will have the same limitations. They are, >however, more general purpose languages, so I expect that speed is less of a >priority than in scientific computing (compared to other important priorities). >Hence, learning curve aside, some time needs to be invested in exploring its >speed in a realistic scientific applications. For me, this is an option for the >more distant future rather than the immediate term. I spent quite alot of time >in this phase with matlab, trying to squeeze out all possible speed before >conceding that some of the limits were fundamental, at least in the current >release. > >One thing I learned was that speed characterization was not a simple. Many of >the tasks found in scientific computing are done blistering fast by matlab. It >is not until you put together a larger application when you start running into >the limitations. Aside from the speed penalties of calling nonbuiltins, . . . 'Couple of reactions: first, I think it's entirely healthy for you to focus on finishing your dissertation. Everything else is and should be subordinate to that. Picking up as much of Perl as you need to achieve that goal, but not more, is thoroughly sensible. Second, be aware that I'm the only one in this thread who has made explicit claims that it's reasonable to expect Perl- or Python-based applications to rival those in C++ for performance. Maybe I'm wrong, or, more charitably, maybe I'm making assumptions that I've kept implicit. It certainly is possible to exhibit comparable-looking C and Python programs, where the former is over a hundred times as fast as the latter. Still, I'm sticking with my claim: for practical, effective algorithmic experimentation, PDL, Numpy, and comparable exten- sions bring 'P' programs' achieved speed up to the level of C++. Ultimately, you're right: "speed characterization [is] not simple." Perl and Python feel like breaths of fresh air after Matlab precisely for their scalability and maintainability. Matlab just doesn't generalize and abstract and express as agilely as the more general-purpose programming languages. -- Cameron Laird Business: http://www.Phaseit.net From skip at pobox.com Mon Mar 15 06:49:58 2004 From: skip at pobox.com (Skip Montanaro) Date: Mon, 15 Mar 2004 05:49:58 -0600 Subject: Deprecating reload() ??? In-Reply-To: References: <09b350henbtk9vnai0v7fhtbsqbmubl7vn@4ax.com> <7cj4c.2733$G3.21896@localhost> <8ok3505b3b3g22bk8ci6iagptqav2cfi6r@4ax.com> <6kk6501shlve52ds2rjdopa73jhpchprg3@4ax.com> Message-ID: <16469.39014.567636.658228@montanaro.dyndns.org> Dave> Maybe we could somehow switch off the generation of shared objects Dave> for modules in a 'debug' mode. You'd have to disable the integer free list. There's also code in tupleobject.c to recognize and share the empty tuple. String interning could be disabled as well. Everybody's ignored the gorilla in the room: >>> sys.getrefcount(None) 1559 In general, I don't think that disabling immutable object sharing would be worth the effort. Consider the meaning of module level integers. In my experience they are generally constants and are infrequently changed once set. Probably the only thing worth tracking down during a super reload would be function, class and method definitions. Skip From peter at engcorp.com Tue Mar 16 08:24:19 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 16 Mar 2004 08:24:19 -0500 Subject: newbie question: nop statement for try/except In-Reply-To: References: Message-ID: leo wrote: > hi there > > the "try/[except|finally]" construct seems to need the second part "except" > resp. "finally" due to syntactical reasons. > > but in some cases i guess i do not need any statement in the second > part. but just carrying on without an idented block doesn't work. > > so, is there something a no-operation statement? "pass" (Without the quotes.) (Actually, with the quotes would work too, for reasons I'll leave up to the reader to find out. :-) -Peter From roberto at inf.puc-rio.br Wed Mar 3 07:37:33 2004 From: roberto at inf.puc-rio.br (Roberto Ierusalimschy) Date: Wed, 03 Mar 2004 09:37:33 -0300 Subject: Lua Book Message-ID: <200403031237.i23CbXb27583@arraial.inf.puc-rio.br> > Provocative comparison; perhaps Roberto will even join in > and comment here. As I was invited, I will give a few short comments: >I suppose Python's recent introduction of generators makes this rather >trivial. You should read the book. There you would learn that Lua offers coroutines (the real ones). With them, you can write a generator quite similar to the piece you wrote: function allwords () return coroutine.wrap(function () for line in io.lines() do for word in string.gfind(line, "%w+") do coroutine.yield(word) end end end) end for word in allwords() do print(word) end You can also write it in a Ruby-iterator style (using anonymous functions instead of blocks): function allwords (yield) for line in io.lines() do for word in string.gfind(line, "%w+") do yield(word) end end end -- usage example local count = 0 allwords(function (word) count = count + 1 end) print("number of words: " .. count) > The full text [of the book] was available on the net Please notice that the text available on the net is an old version; it is quite different from the final book. > having finished the book I was left feeling that the core language > offered nothing useful over Python, in fact it was rather lacking > in many areas. [...] it's unlikely to ever come close to Python for > general purpose coding. This is a sensible opinion. (And apparently well based, as you read the book :) Lua and Python have different goals; and different people have different opinions. -- Roberto From wenming_hu2002 at hotmail.com Thu Mar 4 21:28:46 2004 From: wenming_hu2002 at hotmail.com (wenming_hu) Date: Fri, 5 Mar 2004 10:28:46 +0800 Subject: how to write python server page by using mod_python? Message-ID: i want to set the default page of a site, the same as writing asp or jsp. who can tell me how to realize that? er, i have a another question, i want to put my site in a separate directory, (for example, e:\psp_site), i put the following in apache's config: AddHandler python_program .py PythonHandler main PythonAutoReload On PythonDebug On but to my disappointed, it doesn't work! :-( who can help me? From bokr at oz.net Tue Mar 2 20:40:07 2004 From: bokr at oz.net (Bengt Richter) Date: 3 Mar 2004 01:40:07 GMT Subject: python.exe vs pythonw.exe difference? References: Message-ID: On Tue, 2 Mar 2004 14:06:36 -0500, "Tim Peters" wrote: >[Thomas Heller] >> [I'm currently reading python-list via the gmane nntp interface, I >> don't know whether there really is a gmane.comp.web.zope.devel >> newsgroup] > >I don't know either, so I'll copy you directly. > >[Tim] >>> ... >>> Here's a Python program to try: >>> >>> """ >>> import sys >>> if 1: # edit to 1 for stdout, 0 for stderr >>> console = sys.stdout >>> else: >>> console = sys.stderr >>> >>> import traceback >>> tb = file('tb.txt', 'w') >>> >>> try: >>> i = 0 >>> while True: >>> i += 1 >>> console.write('.') >>> except: >>> print >> tb, "Died when trying to write byte", i >>> traceback.print_exc(file=tb) >>> tb.close() >>> """ >>> >>> Under Win98SE, and regardless of whether it writes to stdout or >>> stderr, it dies when run under pythonw, and tb.txt contains this >>> after: >>> >>> Died when trying to write byte 4097 >>> Traceback (most recent call last): >>> File "wr.py", line 14, in ? >>> console.write('.') >>> IOError: [Errno 9] Bad file descriptor > >[Thomas] >> I get exactly the same, on Win XP Pro, both for sys.stdout and >> sys.stderr. > >That's good to know! Thanks. > >> ... >> Since it seems XP shows the same behaviour than win98SE, has the >> behaviour of Python changed? Were IOErrors ignored on sys.stdout or >> sys.stderr in earlier versions? > >No, the same program fails the same way here under pythonw 2.2.3 and 2.1.3 >(with s/file/open/ and s/True/1/). The OP wasn't clear about what "it" >meant, though (in "it used to work"). I guess it's most likely he meant >running Zope 2.5 as a service used to work, not that running Zope 2.5 by >hand from a DOS box with pythonw used to work, but don't know. It's >certainly possible that something relevant changed in Zope, and/or in how >Zope tries to live with Windows services. > >> IIRC, /F first proposed that pythonw.exe should create a console to >> have a place to show tracebacks. Sounds like a good idea to me. > >Some way of having pythonw not drop output into the bit bucket has sounded >like a good idea to everyone for about a decade now . > >ideas-ain't-code-ly y'rs - tim > You can call AllocConsole safely at the last moment before spewing text, I think, and without even checking if there already is one (I think it will quietly do nothing if there is, IIRC from old Delphi days). I don't think people want to see console windows along with their GUIs when things are normal, but post mortem is another thing, and this is a simple call. Also it gives you a handy separate window to put debug messages to just by using print, which can be handy with if __debug__: -conditional code or temporary hacks. _____________________________________________________________________________ The AllocConsole function allocates a new console for the calling process. BOOL AllocConsole(VOID) Parameters This function has no parameters. Return Value If the function succeeds, the return value is TRUE. If the function fails, the return value is FALSE. To get extended error information, call GetLastError. Remarks A process can only be associated with one console, so AllocConsole fails if the calling process already has a console. A process can use the FreeConsole function to detach itself from its current console, and then it can call AllocConsole to create a new console. If the calling process creates a child process, the child inherits the new console. AllocConsole also sets up standard input, standard output, and standard error handles for the new console. The standard input handle is a handle to the console's input buffer, and the standard output and standard error handles are handles to the console's screen buffer. To retrieve these handles, use the GetStdHandle function. This function is primarily used by graphics applications to create a console window. Graphics applications are initialized without a console. Console applications are normally initialized with a console, unless they are created as detached processes (by calling the CreateProcess function with the DETACHED_PROCESS flag). See Also CreateProcess, FreeConsole, GetStdHandle _____________________________________________________________________________ AllocConsole should be easy to call through one of the win32 interfaces. Maybe we should just make a DLL that would just do that and nothing else when imported. Re Emile's situation, I think there may be an additional factor. I.e., output from a windows service to an interactive window requires a special checkbox somewhere in the service setup, I think, since services normally run as a non-interactive process with separate user identity from whoever might be locally logged on. That bit in your '.' output suggests to me that there's a 4k buffer write being triggered and that is the thing that runs into no place to write. I wonder if it wouldn't trigger earlier with newlines or explicit flush or -U ? HTH Regards, Bengt Richter From tjreedy at udel.edu Thu Mar 4 20:19:26 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 4 Mar 2004 20:19:26 -0500 Subject: Again: Please hear my plea: print without softspace References: <4041796c.2181078@news.muenster.de><1rfj4etyhlcw6$.1evn1aiuzkinp$.dlg@40tude.net><40448d4f.8911015@news.muenster.de><17O0c.432676$I06.4900877@attbi_s01><4119c4e0d1dd457d3637e1316d5513ac@news.teranews.com> Message-ID: "David MacQuigg" wrote in message news:f0oe40hujm0rqcci2fgrhc445qgjs9anfe at 4ax.com... > On Thu, 04 Mar 2004 12:52:27 GMT, Dang Griffith > >On Tue, 02 Mar 2004 10:32:35 -0700, David MacQuigg wrote: > > > >>The 'print' statement is just shortcut for 'sys.stdout.write' with > >>some convenience features suitable for most users. \ > >'print' is not a shortcut for 'sys.stdout.write'. Depends on how fussy one is being about the meaning of 'shortcut'. 'Syntactic sugar' is another way to put it. > I'm not using the word 'shortcut' very precisely. I think you were precise enough for informal clp discussion with no retraction needed. > Mark Lutz says what > I mean more clearly in Learning Python, 2nd ed. p. 143: "the print > statement ... provides a user-friendly interface to the sys.stdout > object, with bit of default formatting." And Guido said much the same about 5 years ago in clp. Terry J. Reedy From steve at ninereeds.fsnet.co.uk Sun Mar 7 21:54:38 2004 From: steve at ninereeds.fsnet.co.uk (Stephen Horne) Date: Mon, 08 Mar 2004 02:54:38 +0000 Subject: Working around a lack of 'goto' in python References: <9gpm405d952ooq37bmeilacks37o4on086@4ax.com> <71tm409egnua4ncic1siadnk7fi9rqnp8e@4ax.com> Message-ID: <4vln40d5cepfccljgtksjpi054pfb7u1fo@4ax.com> On Sun, 07 Mar 2004 15:49:07 -0500, Roy Smith wrote: >In some respects, you're right. Certainly, both ways get you the same >pseudo-random flow of control, but that's inherent in a state machine. >What the function-per-state approach gets you is modularity. Each >function at least has its own namespace and set of local variables. This is actually pretty much the point. The function involved is only sufficiently complex to warrant unit tests when taken as a whole. The processing within a state could be compared with the inner loop of, say, an strcpy. A little more complex, but only a little. The total number of states is pretty small, 6 in total, with the awkwardness of a non-state-based approach resulting entirely from the arrangement of transitions. And as I said, it is what I call 'short running' - the whole thing runs to completion in probably a few hundred cycles for typical cases. If the states had a significant amount of code I'd agree with you, but as it stands it is easier and more useful to write the unit tests for that one function. I just wish I had the example ten years ago, when I suggested the exactly this pattern as a potential justification for gotos to a college lecturer but couldn't think of a use case. It's so unfair that I don't get to say 'told you so, told you so, nur nur na-nur nur' :-) Anyway, the point is, no - I'm not nuts. Honest. Well, I am, but not about this. It's just a bizarre special case, interesting only as... well, not even interesting really I suppose - I'm just bored. -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From cnoviello at hotmail.com Sat Mar 6 13:41:20 2004 From: cnoviello at hotmail.com (Carmine Noviello) Date: Sat, 06 Mar 2004 18:41:20 GMT Subject: Working around a lack of 'goto' in python References: Message-ID: > (1) deeply nested loops > > for (k=0; k < 10; ++k) > for (j=0; j < 10; ++j) > for (i=0; i <10; ++i) > if (/* some test */) goto END; done = 0 while k < 10 and not done: k += 1 while j < 10 and not done: j+=1 while i < 10 and not done: i+=1 if /*some test*/: done = 1 > and (2) repeating a while or for loop from the beginning: > > BEGIN: > for (n=0; n < 20; ++n) > if (/* some test */) goto BEGIN; > while n < 20: if /*some test*/: n = 0 There is always a way to not use "goto". -- Don't you know why your Python application has crashed? Take a look to http://www.pycrash.org My Home Page http://cnoviello.altervista.org From ville at spammers.com Tue Mar 2 04:20:33 2004 From: ville at spammers.com (Ville Vainio) Date: 02 Mar 2004 11:20:33 +0200 Subject: Is Eric S Raymond still a "Pythoneer" References: <2ae25c6b.0403020006.6b99e590@posting.google.com> Message-ID: >>>>> "Paddy" == Paddy McCarthy writes: Paddy> from ESR on his scripting language tools. I would be Paddy> interested to know if he still usesPython? Did he try any Paddy> other "scripting" languages such as Ruby or Lua? Yes - for example he wrote a prototype of his SCO source code comparison tool in Python. I think he still mostly uses Python for the stuff he writes himself. -- Ville Vainio http://tinyurl.com/2prnb From jgentil at sebistar.net Sun Mar 14 23:05:17 2004 From: jgentil at sebistar.net (Jon-Pierre Gentil) Date: Sun, 14 Mar 2004 22:05:17 -0600 Subject: Problem with parsing XML In-Reply-To: References: Message-ID: <1079323517.1117.29.camel@mastermind> On Sun, 2004-03-14 at 21:01, James Laamnna wrote: > So I have an XML document with é and other non-XML chars. > I'm wondering the best way to parse this using xml.dom.minidom. > > I've tried using a translation document to transmate é to é > But now the characters just disappear. > Any suggestions? Use DOCTYPE entity declarations? Like this: ]> You can define é too. -- Jon-Pierre Gentil : PGP Key ID 0xA21BC30E AIM: Zenethian : Jabber: jgentil at jabber.org -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 204 bytes Desc: This is a digitally signed message part URL: From fidtz at clara#spam#.co.uk Thu Mar 25 06:53:00 2004 From: fidtz at clara#spam#.co.uk (DomF) Date: Thu, 25 Mar 2004 11:53:00 -0000 Subject: Any way to get information from fun objects about their parameters? References: Message-ID: <1080215476.12849.0@ersa.uk.clara.net> Damn, I was hoping for a question about cars and beer :) "Kenneth McDonald" wrote in message news:slrnc64bcn.2qa.kmmcdonald at g4.gateway.2wire.net... > For autodocumentation purposes, I'd like to be able to load a module > and then find out the following information about functions and > methods defined within it: > > 1) Parameter names and order > 2) Default value, if any, associated with each parameter > 3) If the *param or **param conventions are used in the > parameter list. > > Reading documentation about function objects, the only > relevant information I can extract is a tuple representing > default param values, which is not useful to me. > > I know I could probably do this by parsing the module, but > I would strongly prefer a simpler way. I'd have thought that, > like docstrings and many other properties, the parameter info > would also be stored with function objects. > > Thanks, > Ken From afriere at yahoo.co.uk Wed Mar 17 20:50:01 2004 From: afriere at yahoo.co.uk (Asun Friere) Date: 17 Mar 2004 17:50:01 -0800 Subject: Result of ``a is b'' References: <40200384.0403151632.35496ee6@posting.google.com> <40200384.0403161255.7fca7a8c@posting.google.com> <40200384.0403170530.57b6bba4@posting.google.com> Message-ID: <38ec68a6.0403171750.7a300cb2@posting.google.com> axelboldt at yahoo.com (Axel Boldt) wrote in message news:<40200384.0403170530.57b6bba4 at posting.google.com>... > Why would anybody ever want to > know whether two strings or tupels are internally stored at the same > location, other than to deduce details of the Python implementation? Most obviously to tell whether they are the same object or not. While this is not an issue with simple strings, have you considered what effect your suggestions would have on classes inheriting from str? For instance I might have a class 'Name', in a names database, which is a specialised string. In this case '==' function looks to the contents of the strings being compared, while 'is' tells me whether these two strings are the same object. Thus "if name0 == name1 and not name0 is name1" will tell me that I am dealing with a duplicate record. Now this might not be the best way to find duplicates in practice, it's simply first thing that popped into my head in response to your question. But I don't think I'm able to anticipate all the ways in which all programmers might want to apply the distinction between equivalence and identity in their programs? Are you? By the way you /have/ written a program in which a large (or at least important) part of the logic was contained in the __eq__ method to the class you created, haven't you? I mean you wouldn't really be in a situation to advocate a redefinition of the identity/equivalence relationship unless you had, would you? From anthony_barker at hotmail.com Tue Mar 23 11:24:38 2004 From: anthony_barker at hotmail.com (Anthony_Barker) Date: 23 Mar 2004 08:24:38 -0800 Subject: Abstraction library for Authentication (module like PEAR Auth) Message-ID: <899f842.0403230824.4a4ba0ab@posting.google.com> Are there any modules for python that provide abstraction for authentication? Pear Auth supports POP3 LDAP SOAP passwd file SAMBA IMAP RADIUS http://pear.php.net/manual/en/packages.auth.php Anthony http://xminc.com/mt/ From dmq at gain.com Wed Mar 10 12:04:00 2004 From: dmq at gain.com (David MacQuigg) Date: Wed, 10 Mar 2004 10:04:00 -0700 Subject: Regex Match Problem References: <59c05c40.0403100717.30e6dbb2@posting.google.com> Message-ID: <8nhu4059js0lrc10ks9io6p4j70r7abj96@4ax.com> On 10 Mar 2004 07:17:12 -0800, bradwiseathome at hotmail.com (bdwise) wrote: >I have this in my body tag: > >something();something(); >document.thisForm.textBox1.focus();something(); > >And I want to find a part between the semicolons that ends in focus() >and remove the entire value between the semicolons. > >My Regular Expression looks like this but it is not matching, can >anyone help? > >";([^.]*).focus()" You need to escape the metacharacters. Try r";.*\.focus\(\).*;" Also, use a raw quote, so you don't have to escape the escapes. Don't forget to set re.DOTALL if you want the '.*' to capture newlines also. There is a nice interactive tool for testing these expressions at ../Pyton23/Tools/Scripts/redemo.py There is a good intro to regular expressions at http://www.amk.ca/python/howto/regex/ -- Dave From mjackson at alumni.caltech.edu Fri Mar 26 15:03:45 2004 From: mjackson at alumni.caltech.edu (Mark Jackson) Date: 26 Mar 2004 20:03:45 GMT Subject: import a modified module References: <5fs8601oef2glokd0i8tbbvso84rrjdku5@4ax.com> Message-ID: David MacQuigg writes: > The docs on reload are a little confusing. I've written a piece at > http://ece.arizona.edu/~edatools/Python/Reload.htm > > Your comments are welcome. Hm. Your second ("more detailed") example is visually confusing, and matters aren't helped by your use of what I would call suboptimal (or at least nonstandard-for-Python) terminology such as "references." This leads you into at least technical error, e.g. Perhaps the most confusing thing about reload is that it changes only references in its own namespace (with names like "M1.a" above). It does not change references outside this namespace (with names like "a" above ). An admittedly pathological counterexample: >>> import M1 >>> from M1 import a, b >>> print M1.a, M1.b [1, 2] abc >>> print a, b [1, 2] abc >>> reload(M1) >>> print M1.a, M1.b [1, 2, 3] ABC >>> print a, b [1, 2, 3] abc How did a (in the __main__ namespace) track a (in the M1 namespace)? Easy - in editing M1.py I replaced: a = [1, 2] with: a.append(3) Of course that *is* pathological - as is, M1.py cannot be freshly imported because a would have no initial binding. But I think in explaining reload() one should strive for a formulation under which this outcome would not be surprising. (Really, to have a hope of understanding reload one first has to understand import.) -- Mark Jackson - http://www.alumni.caltech.edu/~mjackson The supreme misfortune is when theory outstrips performance. - Leonardo da Vinci From james at ractive.ch Wed Mar 31 16:55:03 2004 From: james at ractive.ch (Jean-Pierre Bergamin) Date: Wed, 31 Mar 2004 23:55:03 +0200 Subject: Simulate socket with files or stdin/stdout Message-ID: 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). +------------+ stdout stdin +------------+ socket.write | |------------------->| python- |---------------- | Simulation | | script | | |<-------------------| |<--------------- +------------+ stdin stdout +------------+ socket.read 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 Now my question is, if someone has done something similar and can give me some hints where to start, what to look for etc. Maybe someone even has another idea how to solve this problem. A skript that does something similar like "netcat" would be a good starting point, since I'm really new to python programming. The script should be usable on the MAC, PC and UNIX platform. I'm very thankful for any input you can give me to find a good solution for this. Thanks James From steve at ninereeds.fsnet.co.uk Tue Mar 9 19:41:16 2004 From: steve at ninereeds.fsnet.co.uk (Stephen Horne) Date: Wed, 10 Mar 2004 00:41:16 +0000 Subject: Working around a lack of 'goto' in python References: <5sbs40l90vpumpp3u72a4259gp83j4mfih@4ax.com> Message-ID: <60ps40h8v483t10kg3misnbsqfrhe1nigo@4ax.com> On Tue, 09 Mar 2004 16:55:22 -0500, Roy Smith wrote: >In article <5sbs40l90vpumpp3u72a4259gp83j4mfih at 4ax.com>, > Stephen Horne wrote: > >> I'm just me. > >Yeah, that's what they all say. Rats, I've been caught! OK, I confess, I'm not me at all ;-) -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From glingl at aon.at Thu Mar 4 13:43:48 2004 From: glingl at aon.at (Gregor Lingl) Date: Thu, 04 Mar 2004 19:43:48 +0100 Subject: how fast is Python code - another detail Message-ID: <404778E4.9090601@aon.at> "Quality of design" may - for instance - consist in deleting 7 characters: Today I made - by accident - an interesting observation. The following is a snippet from a program which computes anagrams from a wordlist: def find_anagrams(wordlist): d = {} for word in wordlist: sig = anagram_signature(word) if sig not in d: d[sig] = [] # d.setdefault intentionally not used return d On my machine it computes d for a wordlist of 10000 items in less than 0.13s and for a wordlist of 20000 items in less than 0.25s Today one of my students inadvertedly wrote in the fifth line if sig not in d.keys(): and now timing of find_anagrams had the following results: for a wordlist of 10000 items approx. 9.33s, i.e a factor of approx 65 slower and for a wordlist of 20000 items approx. 60s, i.e. a factor of approx 250 slower. (!!!) (Imagine that the full wordlist in this example has 45000 entires, so an additional factor of 16 applies ...) I think this is a very astonishing and relevant difference! I think I understand why it is the case - the timing factor is proportional to the square of len(wordlist), because in every loop a list d.keys() has to be computed and now this has to be used for searching for the key sig, while for sig in d uses some built-in generator-property of dictionaries ... (?) *on_the_other_ hand* I thought, that those two idioms are semantically identical. So my question: why does the Python interpreter not recognize this identity and internally replace the latter by the first in order to get *much* better performance? - would this lead to wrong results in some cases? - or would it be too difficult to implement? - or is this considered a problem of minor importance? - or was it only forgotten to do? - or what else? Regards, Gregor P.S.: Or was the key in dict idiom introduced exactly inorder to solve this problem? From dw-google.com at botanicus.net Sun Mar 21 21:17:54 2004 From: dw-google.com at botanicus.net (David M. Wilson) Date: 21 Mar 2004 18:17:54 -0800 Subject: PEP 318 References: Message-ID: <99dce321.0403211817.3704fe2@posting.google.com> Nicolas Fleury wrote... > Personnally, I prefer the "as" syntax to the other proposed (and by a > large margin). However, I feel that it is making the language more > complex and I'm far from sure it's worth the effort. I'd +1 for the 'as' syntax too, it's more descriptive and feels 'pythonic' (much as the term disgusts me) in its verbosity. Personally, I think for the meager benefit this new syntax brings, it appears to be a rather large and incompatible waste of time. With the exception of syntactic beauty, does this really add anything to Python? It gives programmers two ways of doing something very basic indeed. Both proposed syntaxes will inevitably break existing source analysers, etc. Even preferring the 'as' syntax, 'def foo(x) as bar' doesn't really make that much sense to me. staticmethods are wrapper objects and much better expressed as 'foo = staticmethod(foo)', where you at least know some kind of layering or transformation is being applied to foo (if there isn't, why is this person using the same variable name? etc). With 'as', it suggests some kind of aliasing is taking place, or some kind of different type of object creation, which isn't the case. It's also very specific syntax, I'd have hoped big language changes like this would be reserved for larger, more fundamental, and general changes that everyone can find useful. Did I say I didn't think it's worth it already? :) David. From hakan at netg.se Sat Mar 6 22:48:47 2004 From: hakan at netg.se (Hakan Nilsson) Date: Sun, 7 Mar 2004 04:48:47 +0100 (CET) Subject: Pushing file name to browser In-Reply-To: <4049E0D5.2000504@cfl.rr.com> Message-ID: On Sat, 6 Mar 2004, pxlpluker wrote: > I what to dynamically create a page that has download links to file > stored on disk. > > the part i don't know how to do (or if its possible) is to a different > name appear in the browser DL window. > > i.e. I want the files stored with a random string but when being DL to > have real name show in File Save dialog. > > in essence i want to push the file name to the browser > > Fred This is not so much a python issue as it is an issue of knowing what the browsers do when they get special input. But, since I recently did this myself I have the answer handy. ;o) Most browsers check the name between the last / and the end of the line (or "?" if you have extra get-parameters) and put that as default name in the file save-dialog. So all you need to do is something like the following: info = { "filename": "apa.txt", "fileid": "10001" } the_url = '%(filename)s'%info As far as I can tell you are only interested in the file id, then this should work with no problem for you and you can get the id-parameter through the standard cgi-object, or however you chose to do. The filename (essentially anything you chose to put between the / and the ?) will be available through an extra-path-info variable, probably also available in the standard cgi-object. Hope this helps, /Hakan - Hi! I'm a .signature virus! Copy me into your .signature file to help me spread! From Pieter.Claerhout at Creo.com Tue Mar 2 03:08:05 2004 From: Pieter.Claerhout at Creo.com (Pieter Claerhout) Date: Tue, 2 Mar 2004 09:08:05 +0100 Subject: NT Services and EventLog problems Message-ID: <490316A24CC5D411ACD700B0D078F7F003915F12@cseexch01.cse.creoscitex.com> Hi Larry, try the following: win32evtlogutil.AddSourceToRegistry('AFR', 'C:\Python22\Lib\site-Packages\win32\servicemanager.pyd', 'Application') The PythonService.exe doesn't contain the messages, but servicemanager.pyd does. cheers, pieter Creo pieter claerhout | product support prinergy | tel: +32 2 352 2511 | pieter.claerhout at creo.com | www.creo.com IMAGINE CREATE BELIEVE(tm) -----Original Message----- From: python-list-bounces+pieter.claerhout=creo.com at python.org [mailto:python-list-bounces+pieter.claerhout=creo.com at python.org] On Behalf Of Larry Bates Sent: 02 March 2004 00:20 To: python-list at python.org Subject: NT Services and EventLog problems I have tried everything I know to get my NT service to make correct entries in the NT Event Log when the service is started and stopped (and eventually when permanent failures occur). I'm copying the code I see on page 356 of Python Programming on Win32 and for the life of me I cannot get this to work properly. Basically I have the following code snippet at the top of my SvcDoRun method: import servicemanager servicemanager.LogMsg( servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED, (self._svc_name_,'')) I also inserted the following to make the proper registry entries when the service is installed: win32evtlogutil.AddSourceToRegistry('AFR', 'C:\Python22\Lib\site-Packages\win32\PythonService.exe', 'Application') The entry that gets put into the Event Log is as follows: The description for Event ID ( 4098 ) in Source ( PythonService ) cannot be found. The local computer may not have the necessary registry information or message DLL files to display messages from a remote computer. You may be able to use the /AUXSOURCE= flag to retrieve this description; see Help and Support for details. The following information is part of the event: AFR, . Note: _svc_name_="AFR" Something is not set correctly, but for the life of me I cannot determine what. Thanks in advance for any assistance. Regards, Larry Bates -- http://mail.python.org/mailman/listinfo/python-list From JimJJewett at yahoo.com Wed Mar 24 23:33:23 2004 From: JimJJewett at yahoo.com (Jim Jewett) Date: 24 Mar 2004 20:33:23 -0800 Subject: PEP318 alternate syntax idea References: Message-ID: Skip Montanaro wrote in message news:... > Jim> With decorators, the function definition itself is normal > Jim> (and therefore should not be indented); it is the decorators > Jim> that run at an unexpected time. > Jim> using: > Jim> decorator1 > Jim> decorator2 > Jim> decorator3 > Jim> def a (args): > Jim> pass > Note that the undent at the end of the using: block also implies > that "we're done" with the block. If I wrote > using: > decorator1 > decorator2 > decorator3 > def a (args): > pass > def b (args): > pass > would a and b both be decorated or just a? What about if I wrote Just a. (If you want grouping, then you'll need a third header clause to indicate that the using is done.) if blocks (and for and while blocks, with the else) have the same issue. The grammar production continues if and only if the next non-indented line is a valid continuation header clause. if test: stmt stmt elif: # elif continues an if stmt stmt else: # else continues an if stmt if test: stmt x = 5 # a binding does not continue an if; now it is over. > using: > decorator1 > decorator2 > decorator3 > x = really_complex_default() > def a (arg1, arg2=x): > pass > Would a be decorated or not? Syntax error. using: header clause not followed by def: or class: header clause. The one part that feels awkward to me is that the optional clause (using:) comes first instead of second (elif:) or last (else:). -jJ From slimick at venango.upb.pitt.edu Wed Mar 17 17:37:16 2004 From: slimick at venango.upb.pitt.edu (John Slimick) Date: Wed, 17 Mar 2004 22:37:16 +0000 (UTC) Subject: Help on Tkinter installation Message-ID: I want to do a little Tkinter in my 1 credit python practicum, but I am having problems getting everything installed correctly. A sample of the problem is below: ------------------- The python source, test.py ------------------ from graphics import * def main(): win = GraphWin("My Circle", 100, 100) c = Circle(Point(50,50), 10) c.draw(win) main() ----------- result of $python test.py -------------------------- Traceback (most recent call last): File "test.py", line 1, in ? from graphics import * File "/home/slimick/cs198/graphics.py", line 85, in ? import Tkinter File "/usr/local/lib/python2.3/lib-tk/Tkinter.py", line 38, in ? import _tkinter # If this fails your Python may not be configured for Tk ImportError: No module named _tkinter ------------result of $locate _tkinter ------------------------------ /usr/src/redhat/SOURCES/Python-2.3.2/Mac/Build/_dummy_tkinter.mcp /usr/src/redhat/SOURCES/Python-2.3.2/Mac/Build/_dummy_tkinter.mcp.exp /usr/src/redhat/SOURCES/Python-2.3.2/Mac/Modules/_dummy_tkinter.c /usr/src/redhat/SOURCES/Python-2.3.2/Modules/_tkinter.c /usr/src/redhat/SOURCES/Python-2.3.2/PC/os2vacpp/_tkinter.def /usr/src/redhat/SOURCES/Python-2.3.2/PCbuild/_tkinter.dsp -------------------------------------------------------------------- I would appreciate any help on this. And, thanks in advance john slimick slimick at pitt,edu university of pittsburgh at bradford From ketulp_baroda at yahoo.com Sat Mar 6 03:45:13 2004 From: ketulp_baroda at yahoo.com (ketulp_baroda at yahoo.com) Date: 6 Mar 2004 00:45:13 -0800 Subject: attachment References: Message-ID: ketulp_baroda at yahoo.com wrote in message news:... > Hi > I am trying to upload a file using > I want to know what is the best way to store this uploaded file > Should I store it in the databse?? > Or should I store the entire file on the server?? If I decide to store the file on the server,then di I have to use ftp to copy the file on the server?? From jcarlson at nospam.uci.edu Sat Mar 20 02:00:57 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Fri, 19 Mar 2004 23:00:57 -0800 Subject: FreeBSD or OpenBSD for Python? In-Reply-To: References: Message-ID: > I have not tried CPython or Twisted. FYI: CPython is the C-based implementation of the interpreter. Unless you've been running Jython, PyPi, or some other 3rd party developed Python interpreter, you're running CPython. - Josiah From deetsNOSPAM at web.de Wed Mar 17 06:31:52 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Wed, 17 Mar 2004 12:31:52 +0100 Subject: destructuring tuple and list References: <8dad5312.0403162334.435de9c6@posting.google.com> Message-ID: Sebastien de Menten wrote: > Hi, > > Is there a reason to not extend the tuple destructuration in functions > to any expression ? > For instance, we can: > def f(x, y, *tail): > return tail + (x,y) > f(3,4,5,6) -> (5,6,3,4) > or > f(*(3,4,5,6)) -> idem > > But I can't do: > (x,y, *tail) = (3,4,5,6) > and get > x=3 > y=4 > tail = (5,6) > Same question for lists... I've also thought about that. s/t like real pattern matching might be cool, but is probably too much of a paradigm shift. What I do is this: l = (5,6,3,4) x,y,tail = l[0:2], l[:2] IMHO not too ugly.... -- Regards, Diez B. Roggisch From jepler at unpythonic.net Tue Mar 16 08:57:08 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Tue, 16 Mar 2004 07:57:08 -0600 Subject: Replace accented chars with unaccented ones In-Reply-To: References: Message-ID: <20040316135706.GE2446@unpythonic.net> On Mon, Mar 15, 2004 at 06:19:00PM -0800, Josiah Carlson wrote: > Translating the replacements pairs into a dictionary would result in a > significant speedup for large numbers of replacements. > > mapping = dict(replacement_pairs) > > def multi_replace(inp, mapping=mapping): > return u''.join([mapping.get(i, i) for i in inp]) > > One pass through the file gives an O(len(inp)) algorithm, much better > (running-time wise) than the string.replace method that runs in > O(len(inp) * len(replacement_pairs)) time as given. Thanks for posting this. My other code was pretty hopeless, but for some reason .get(i, i) didn't come to mind as a solution. Jeff From davecook at nowhere.net Wed Mar 3 07:59:53 2004 From: davecook at nowhere.net (David M. Cook) Date: Wed, 03 Mar 2004 12:59:53 GMT Subject: Which Python module for PostgreSQL? References: Message-ID: In article , Ganesan R wrote: > I was referring to python2.3-pgsql which is the same as pyPgSQL. Oh, those wacky Debian kids and their renamings. I assumed pgsql was the "standard" module that ships with postgres. pyPgSQL seems to handle booleans quite transparently. Dave Cook From Henrik.Weber at sdm.de Thu Mar 11 08:26:48 2004 From: Henrik.Weber at sdm.de (Henrik Weber) Date: 11 Mar 2004 05:26:48 -0800 Subject: Using Pythonwin to poke at Windows apps? References: <44254d3d.0403090600.3b14d84c@posting.google.com> Message-ID: <44254d3d.0403110526.68157d29@posting.google.com> Thomas Heller wrote in message news:... > Henrik.Weber at sdm.de (Henrik Weber) writes: > > > Hello all, > > > > I'm trying to read information about widgets from running instances of > > win32 applications. My current victim is the Explorer on a XP box. I'm > > trying to access the menu bar. On XP this is not a standard menu but a > > toolbar. So far I can retrieve a PyCWnd object with win32ui: > > > >>>> e = win32ui.FindWindow("ExploreWClass", None) > >>>> w = win32ui.FindWindowEx(e, None, "WorkerW", None) > >>>> w = win32ui.FindWindowEx(w, None, "ReBarWindow32", None) > >>>> t = win32ui.FindWindowEx(w, None, "ToolbarWindow32", None) > >>>> t = win32ui.FindWindowEx(w, t, "ToolbarWindow32", None) > >>>> hex(t.GetSafeHwnd()) > '0x602d8' > >>>> print t > > object 'PyCWnd' - assoc is 01275A88, vi=, notify=0,ch/u=0/0, > > mh=0, kh=0 > > > > I know that t now refers to a ToolbarWindow32 widget but seemingly > > win32ui doesn't. Is there a way to get a PyCToolbar object from this? > > No idea. I had hoped that there might be a way to cast or convert a PyCWnd object to an object of a child class or to construct a PyCToolbar object from an hwnd, something like that. > > > Or do I have to continue by sending messages? I tried sending a > > TB_GETBUTTON message with win32gui.SendMessage, using a Python array > > to reserve some memory for the TBBUTTON structure, but so far I have > > only succeeded in crashing the Explorer. What would be the right way > > to send a message that needs some memory to put the results into? > > If you go this way, ctypes is what you need. And Simon Bruning has > written a series of articles which also might be helpful: > > http://www.brunningonline.net/simon/blog/archives/000652.html Yes, I've read those articles. He does something similar to what I want where he retrieves the content from an edit widget. My attempt that I described above was inspired by this. Now I've tried this with ctypes: from ctypes import * import win32ui, win32con e = win32ui.FindWindow("ExploreWClass", None) w = win32ui.FindWindowEx(e, None, "WorkerW", None) w = win32ui.FindWindowEx(w, None, "ReBarWindow32", None) t = win32ui.FindWindowEx(w, None, "ToolbarWindow32", None) t = win32ui.FindWindowEx(w, t, "ToolbarWindow32", None) class TBBUTTON(Structure): _fields_ = (("iBitmap", c_int), ("idCommand", c_int), ("fsState", c_byte), ("fsStyle", c_byte), ("bReserved", c_byte * 2), ("dwData", POINTER(c_long)), ("iString", c_char_p)) b = TBBUTTON() f = windll.user32.SendMessageA TB_GETBUTTON = win32con.WM_USER + 23 print f(t.GetSafeHwnd(), TB_GETBUTTON, 0, byref(b)) When I run it the first time I get a return value 1. However the TBBUTTON structure contains mostly zeroes. Running it again crashes the Explorer. Even if I open another Explorer the script will crash it with every subsequent execution until the machine is rebooted. So obviously I'm doing something wrong, but what? Henrik From claird at lairds.com Wed Mar 3 14:55:15 2004 From: claird at lairds.com (Cameron Laird) Date: Wed, 03 Mar 2004 19:55:15 -0000 Subject: Python and Multi-Physics References: Message-ID: <104ce13eo7sn00f@corp.supernews.com> In article , Satish Chimakurthi wrote: . . . >emphasize the spirit of using python in scientific research. I know of >few companies like CFDRC and laboratories like LLNL who use python >extensively for the kind of research I am talking about(from web). Is >there any other individual or company devoted to such research ? Please . . . There are lots. LOTS. Enough that it'd be a full-time job cataloguing them. While I launched with the idea of (among other things) indexing such initiatives, I've long since abandoned the fantasy of keeping up. Look through the Proceedings of the Annual Python Conferences. I think you'll find those useful. -- Cameron Laird Business: http://www.Phaseit.net From jcarlson at nospam.uci.edu Fri Mar 19 12:24:07 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Fri, 19 Mar 2004 09:24:07 -0800 Subject: Extending Python Syntax with @ In-Reply-To: <405b0049.148328857@news.eircom.net> References: <104v3lrijtse657@news.supernews.com> <104v8flf6f1bp95@news.supernews.com> <4059deac.74176280@news.eircom.net> <105jorolc069r50@news.supernews.com> <405b0049.148328857@news.eircom.net> Message-ID: Well, two points. First, why does it have to be a "fancy" >>tool? The only editors I use basically have syntax highlighting >>and code folding (at least, I think that's what it's called.) >>There are a lot of other features I'd like to have, but I'm not >>about to spend time with a learning curve that needs a full >>mountaineering outfit to scale. > > Well then we're agreed, neither of us uses fancy tools :) (Don't know > what code folding is, but I also like syntax highlighting.) http://scintilla.sourceforge.net/SciTEImage.html The above link will show you what code folding looks like. Look at the function definitions. - Josiah From mogmios at mlug.missouri.edu Tue Mar 30 02:58:46 2004 From: mogmios at mlug.missouri.edu (Michael) Date: Mon, 29 Mar 2004 23:58:46 -0800 Subject: Prothon Prototypes vs Python Classes In-Reply-To: <9C8ac.68303$cx5.4075@fed1read04> References: <106dukh7ncf9ad4@news.supernews.com> <4068D66A.7060800@sneakemail.com> <9C8ac.68303$cx5.4075@fed1read04> Message-ID: <406928B6.7000102@mlug.missouri.edu> >>but you could allow either all-tabs or all-spaces in a given file. >> >> > >Maybe that the is most sensible solution I've heard yet. > That'd seem agreeable to me. Especially if how strict the rule was could be set at run time as a Python argument. So you could either have mixed spaces and tabs refuse to run, give an error, or be ignored and run (if possible) as we might currently expect. From mwh at python.net Mon Mar 1 07:20:14 2004 From: mwh at python.net (Michael Hudson) Date: Mon, 1 Mar 2004 12:20:14 GMT Subject: Limitations of 30 Day Eval? References: Message-ID: Jarek Zgoda writes: > Markus Wankus pisze: > > > Dumbass...sorry - wrong newsgroup. Damn this new newsreader! > > Use slrn. With ^C you could cancel this message. Well, you could /try/... cancel propagation not being one of the more reliable things in the univers. Cheers, mhw -- SCSI is not magic. There are fundamental technical reasons why it is necessary to sacrifice a young goat to your SCSI chain now and then. -- John Woods From virusalert at ouhk.edu.hk Tue Mar 23 03:48:20 2004 From: virusalert at ouhk.edu.hk (virusalert at ouhk.edu.hk) Date: Tue, 23 Mar 2004 16:48:20 +0800 Subject: ***Symantec Anti-Virus detected a repairable/quarantined virus in a message you sent Message-ID: <013301c410b3$98091920$251ea8c0@staffdmn.ouhk.edu.hk> ***This message was generated by Symantec Anti-Virus*** Subject of the message: Re: Re: Re: Your document Attachment (if any) : document_4351.pif <> This e-mail and its attachments, if any, are confidential and contain information for an intended recipient. The Open University of Hong Kong (OUHK) disclaims any liability for any loss or damage if this e-mail is received by any person who is not the intended recipient. If you are not the intended recipient, you must not use, retain, disclose, copy, print, forward or disseminate this e-mail or any attachments. If you have received this e-mail in error, please notify us by e-mail immediately and delete this e-mail and any attachments immediately. E-mail transmission cannot be guaranteed to be completely secure or error free. No responsibility is accepted by the OUHK for any loss or damage arising in any way from receipt or use thereof. Any implicit or explicit assertions of fact or expressions of opinion are those of the author and need not represent those of the OUHK. From jcarlson at nospam.uci.edu Mon Mar 15 14:53:35 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Mon, 15 Mar 2004 11:53:35 -0800 Subject: loop scope In-Reply-To: References: Message-ID: > t = f(a/c) > ... # and then later, > sl = [t * t for t in range(3)] > > In this case, I would argue that it's an error for t to escape > the expression scope _because_ it's used outside that scope - > actually I think that was where we came in. My personal view > is that a list comprehension should have its own internal scope, > period, but is that what `intuition' would lead most Python > programmers to expect? I don't know. From what I understand, the above case is taken care of in Python 2.4 In the case of: t = f(a/c) ... # and then later, s1 = [] for t in range(3): s1.append(t * t) The behavior is unchanged in 2.4, t gets rebound. - Josiah From sigurd at 12move.de Wed Mar 3 14:53:50 2004 From: sigurd at 12move.de (=?iso-8859-1?q?Karl_Pfl=E4sterer?=) Date: Wed, 03 Mar 2004 20:53:50 +0100 Subject: Efficiently test for positive re.match then use the result? References: <20040303102526934-0800@news.qwest.net> Message-ID: On 3 Mar 2004, elmlish <- elmlish at netscape.net wrote: > Mostly what I've seen people do is to first test for the match, and then > try matching again to get the results. This would seem to be pretty > inefficient to me. Where did you see that? Often you see code like: m = re.match('foo', 'foobar') if m: do_something with m > I've tried making the match, then sending it to a variable, then testing > if the variable is good and then finally using it, but this still seems > overkill. It isn't; you can't have directly an return value from assignment in Python like e.g in C, so you can't write code like: if m = re.match('foo', 'foobar'): do_somethiing_with_m Global vars are also normally not set from re-matching (you could write your own matching function which sets a global var; but that's seldom a good idea ). > I'm also trying to use this in list comprehensions, mostly because they > are kind of fun. What I've got right now looks something like this. >>>> alist = ['boo','hoo','choo'] >>>> [re.match('choo',line) for line in calist if re.match('choo',line)] > [<_sre.SRE_Match object at 0x11e218>] > This is a small test, but what I will be looking for various matches in > is a large special purpose text file. > Does anyone have input on how something like this _should_ be done? > thanks, I don't know how it _should_ be done but I can tell you how it _could_ be done. Use a class like the following: class Matcher (object): __slots__ = ('reg', 'match') def __init__ (self, reg): self.reg = reg self.match = None def __call__ (self, val): self.match = self.reg(val) if self.match: return True Now you could use it like: >>> alist = ['boo','hoo','choo'] >>> reg = Matcher(re.compile('choo').match) >>> [reg.match for c in alist if reg(c)] [<_sre.SRE_Match object at 0xb3de58>] >>> That's no overkill. But if you wanted it even lighter you could use a closure (but don't tell anyone :-) ) def matcher (reg): res = [None] def fun (s): m = reg(s) if m: res[0] = m return m return res, fun You use it like that: >>> res, reg = matcher(re.compile('choo').match) >>> [res[0] for c in alist if reg(c)] [<_sre.SRE_Match object at 0xa14e90>] >>> Or you simply write: >>> reg = re.compile('choo').match >>> filter(None, [reg(line) for line in alist]) [<_sre.SRE_Match object at 0xb3df38>] Even for a big list filter(None, ...) is fast. KP -- You know you've been sitting in front of your Lisp machine too long when you go out to the junk food machine and start wondering how to make it give you the CADR of Item H so you can get that yummie chocolate cupcake that's stuck behind the disgusting vanilla one. From gandalf at geochemsource.com Thu Mar 18 09:50:14 2004 From: gandalf at geochemsource.com (Gandalf) Date: Thu, 18 Mar 2004 15:50:14 +0100 Subject: cgi lib question Message-ID: <4059B726.70801@geochemsource.com> Hi All! I'm using IIS with Python (as an ActiveScript language). I would like to upload files with multipart/form-data. Here is my code: length = Request.TotalBytes data = Request.BinaryRead(length) f = cStringIO.StringIO(data[0]) values = cgi.parse_multipart(f,header) And the HTML code:
File 1:
File 2:
File 3:
File 4:

It works well when I upload text files (Content type:text/plain). However, it raises an exception when I try to upload a binary file (octet-stream). Here is the message: Python ActiveX Scripting Engine (0x80020009) Traceback (most recent call last): File "'... Jeff From zapazap at yahoo.com Mon Mar 1 03:24:19 2004 From: zapazap at yahoo.com (zapazap) Date: 1 Mar 2004 00:24:19 -0800 Subject: Pythonic control of VMware -- ctypes does not provide access to 'menu' gui-control. Message-ID: <4b3b1124.0403010024.7d044ac1@posting.google.com> Dear Snake Charming Gurus, (Was: http://mail.python.org/pipermail/python-list/2004-January/204454.html) First, a thank you to Tim Golden, Thomas Heller, and Mark Hammond for your earlier help with this problem. I am uncertain about what etiquette calls for, but more on that later. My Objective: I am trying to control the _VMWare Desktop_ application pythonically on WinXP Professional OS, with hopes of doing the same later on Linux. (If it can be done easily on Linux I might quit the WinXP work now, but I have never done any automation like this on Linux before.) My Progress: I have been trying to extend Simon Brunning's _winGuiAuto_ module to deal with tabs listviews. This was the subject of my previous thread. I am facing a more fundamental problem. I am unable even to exercise the application's main menu, which is something I thought winGuiAuto in its present form should have been able to do. My Test: I have a unittest that successfully opens and closes both _Notepad_ and _Freecell_, but fails to close _VMware_. My Suspicion: I suspect that there is a different "path" (so to speak) to the menu control in the VMWare application than exists in the other two applications. Question #1 (My Etiquette): Having said "Much Thanks!!" at the end of my first post, should I have written back in thanks, privately or publicly? I greatly appreciated the help (and helpful it was), but have long thought "thanks in advance" covered the "friction" of followup thanks. But I recently read ESR's "How To Ask Questions The Smart Way" and am not so sure. Question #2: Is my suspicion correct? Might I have to go through several nested controls before I get to the menu control of some apps? If so, I think may need to search for some interactive browser and/or debugger for windows app to reverse engineer the app's structure. But I fear how much windows arcana I will need to learn if I am to do this :-( -- advice of any sort would sure be encouraging. Question #3: Perhaps life would be much easier for me if I do it in Linux? (Since most of my work will eventually be done inside the VMs, the host OS does not matter so greatly to me.) Let me say that my goal is for a user to be able to see ONLY the virtual machine, but be able to have snapshots taken and restored, devices reassigned, etc, from within the VM without seeing the host. I will just have the VM talk to the Host via sockets, that is no problem to hack on. My only difficulty is having a process on the host actually drive the VMWare application in a way that does not require the VM to leave full-screen mode. Perhaps this description might help someone in their helping me? My failing unittest follows. It was run under Python 2.3.2. Thank you again! - Bryan Hann (zapazap AT yahoo DOT com) ---------------snip------------------------------------------------- # Warning: close all instances of NOTEPAD, FREECELL # and VMWARE before running this test import os import sys import time import unittest import ctypes import win32con import win32gui ########################################## # begin user configurable values ########################################## # path to vmware folder VMWARE_HOME = 'D:\\Progra~1\\VMware\\VMware~1' # number of seconds to wait for the OS to respond to a change request. DELAY = 2.0 # command prefix CMD = 'start cmd /c ' ########################################## # end user configurable values ########################################## class Test_CloseViaMenu(unittest.TestCase): def test_freecell(self): # I document this method; the others are similar. # text to be found in the title of a freecell application appname = 'FreeCell' command = CMD + appname # ensure no currently running instance of the application assert not get_hwnds(appname) # launch the application os.system(command) # give it time time.sleep(DELAY) # get the (unique) hwnd for the application's main window [hwnd] = get_hwnds(appname) # find the id for the Game|Exit menu entry hmenu = ctypes.windll.user32.GetMenu(hwnd) assert hmenu, 'Application %s has no menu!' % appname assert menu_name(hmenu,0)=='&Game' hmenu = ctypes.windll.user32.GetSubMenu(hmenu, 0) assert menu_name(hmenu,9)=='E&xit' ExitID = ctypes.windll.user32.GetMenuItemID(hmenu, 9) # try to close the application win32gui.PostMessage(hwnd, win32con.WM_COMMAND, ExitID, 0) # give it time time.sleep(DELAY) # it should be gone now assert not get_hwnds(appname) def test_notepad(self): appname = 'Notepad' command = CMD + appname assert not get_hwnds(appname) os.system(command) time.sleep(DELAY) [hwnd] = get_hwnds(appname) # find the id for the File|Exit menu entry hmenu = ctypes.windll.user32.GetMenu(hwnd) assert hmenu, 'Application %s has no menu!' % appname assert menu_name(hmenu,0) == '&File' hmenu = ctypes.windll.user32.GetSubMenu(hmenu, 0) assert menu_name(hmenu,8) == 'E&xit' ExitID = ctypes.windll.user32.GetMenuItemID(hmenu, 8) win32gui.PostMessage(hwnd, win32con.WM_COMMAND, ExitID, 0) time.sleep(DELAY) assert not get_hwnds(appname) def test_vm(self): appname ='VMware' command = CMD + appname assert not get_hwnds(appname) os.system(command) time.sleep(DELAY) [hwnd] = get_hwnds(appname) # find the id for the File|Exit menu entry hmenu = ctypes.windll.user32.GetMenu(hwnd) assert hmenu, 'Application %s has no menu!' % appname assert menu_name(hmenu,0)=='&File' hmenu = ctypes.windll.user32.GetSubMenu(hmenu, 0) assert menu_name(hmenu,12)=='E&xit' ExitID = ctypes.windll.user32.GetMenuItemID(hmenu, 8) win32gui.PostMessage(hwnd, win32con.WM_COMMAND, ExitID, 0) time.sleep(DELAY) assert not get_hwnds(self.appname) def menu_name(hMenu,nn): """ Given an hMeny and index nn, return the name of the nn-th item in the menu. """ dummy = ctypes.c_buffer("\000" * 32) ctypes.windll.user32.GetMenuStringA( ctypes.c_int(hMenu), ctypes.c_int(nn), dummy, ctypes.c_int(len(dummy)), win32con.MF_BYPOSITION ) return dummy.value def get_hwnds(text): """ Return list of all top level hwnds with specified text in the title. """ fn = win32gui.GetWindowText list = [] win32gui.EnumWindows( (lambda hwnd,acc: acc.append(hwnd)), list) return [ hwnd for hwnd in list if text in fn(hwnd) ] if __name__=='__main__': fn = sys.getwindowsversion win_ver = {4: "NT", 5: "2K", 6: "XP"}[fn()[0]] assert win_ver in ["2K","XP"] if not win_ver == "2K": print >> sys.stderr, 'warning: tested only on windows 2K' os.environ['PATH'] = os.environ['PATH'] + ';' + VMWARE_HOME unittest.main() ########################################## # The following is the output I got ########################################## """ ..F ====================================================================== FAIL: test_vm (__main__.Test_CloseViaMenu) ---------------------------------------------------------------------- Traceback (most recent call last): File "U:\test.py", line 95, in test_vm assert hmenu, 'Application %s has no menu!' % appname AssertionError: Application VMware has no menu! ---------------------------------------------------------------------- Ran 3 tests in 5.137s FAILED (failures=1) """ From pxlpluker at cfl.rr.com Tue Mar 9 23:18:48 2004 From: pxlpluker at cfl.rr.com (pxlpluker) Date: Tue, 09 Mar 2004 23:18:48 -0500 Subject: Explane File modes please -- In-Reply-To: <433f4c9a.0403091824.2d3ed304@posting.google.com> References: <433f4c9a.0403091824.2d3ed304@posting.google.com> Message-ID: <404E9728.10906@cfl.rr.com> What exactly does the underlined text mean. w & a obviously mean you are going to update the file. So what does the + mean on w+ & a+ mean? Also please could someone explain w+ truncating the file. I may just be dense so please be patient :) ------------------------------------------------------------------------- [Copy from python 2.3.3 help file] file( filename [, mode [, bufsize ] ] ) Return a new file object (described earlier under Built-in Types). The first two arguments are the same as for stdio's fopen(): filename is the file name to be opened, mode indicates how the file is to be opened: 'r' for reading, 'w' for writing (truncating an existing file), and 'a' opens it for appending (which on some Unix systems means that all writes append to the end of the file, regardless of the current seek position). Modes 'r+', 'w+' and 'a+' open the file for updating (note that 'w+' truncates the file). Append 'b' to the mode to open the file in binary mode, on systems that differentiate between binary and text files (else it is ignored). If the file cannot be opened, IOError is raised. -------------- next part -------------- An HTML attachment was scrubbed... URL: From skip at pobox.com Sun Mar 7 09:10:27 2004 From: skip at pobox.com (Skip Montanaro) Date: Sun, 7 Mar 2004 08:10:27 -0600 Subject: Introspection at the module level? In-Reply-To: References: Message-ID: <16459.11603.826538.710113@montanaro.dyndns.org> Roy> I've got a module that defines a bunch of constants: Roy> OP_FOO = 1 Roy> OP_BAR = 2 Roy> OP_BAZ = 37 Roy> and so on. The values are all unique. I want to build, at module Roy> import time, a reverse map of these constants, i.e. I want to end Roy> up with: Roy> {1: "OP_FOO", 2: "OP_BAR", 37: "OP_BAZ"} Have a look at http://manatee.mojam.com/~skip/python/ConstantMap.py Skip From jcarlson at nospam.uci.edu Mon Mar 15 20:27:44 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Mon, 15 Mar 2004 17:27:44 -0800 Subject: Error Message & IDLE - PyShell In-Reply-To: <8f198e47.0403150651.12f973cc@posting.google.com> References: <8f198e47.0403150651.12f973cc@posting.google.com> Message-ID: > how its possible without touching python interpreter src code ? I don't believe it can be done. - Josiah From claird at lairds.com Sun Mar 28 00:04:07 2004 From: claird at lairds.com (Cameron Laird) Date: Sun, 28 Mar 2004 05:04:07 -0000 Subject: Regular Expressions References: <76adnc77cvMUl_vdRVn-jA@centurytel.net> <76adncn7cvNZl_vdRVn-jA@centurytel.net> Message-ID: <106cn6797h0aje1@corp.supernews.com> In article <76adncn7cvNZl_vdRVn-jA at centurytel.net>, Ed Suominen wrote: >Sorry, the RE should be '(\d+)\s+\"([\w\']+)[,\s]+([\w\']+)' > >Ed Suominen wrote: > >> m = sre.search('(\d+)\s+\"[\w\'][,\s]+([\w\'])', s) >> x = (int(m.group(1)), group(2), group(3)) . . . And the bound list should be ... well, how 'bout I just start from the top? import sre s = '''740446505 "O'HANLON, Benjamin"''' m = sre.search('''(\d+)\s+"([\w']+)[,\s]+([\w']+)''', s) x = (int(m.group(1)), m.group(2), m.group(3)) print x I see we're appropriately ignoring multiple commas, missing close quotes, ... -- Cameron Laird Business: http://www.Phaseit.net From tcsh-bugs-bounces at mx.gw.com Wed Mar 3 08:46:26 2004 From: tcsh-bugs-bounces at mx.gw.com (tcsh-bugs-bounces at mx.gw.com) Date: Wed, 03 Mar 2004 08:46:26 -0500 Subject: Your message to Tcsh-Bugs awaits moderator approval Message-ID: Your mail to 'Tcsh-Bugs' with the subject hello 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://mx.gw.com/mailman/confirm/tcsh-bugs/10ccbeb6da37f131d1b278a7b0e1aebbb5e075ef From jcarlson at nospam.uci.edu Sat Mar 20 04:56:18 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Sat, 20 Mar 2004 01:56:18 -0800 Subject: Python bytecode compatibility between interpreter versions In-Reply-To: References: <0qudndSnJMpWbsfdRVn-uA@powergate.ca> Message-ID: > I was just curious wrt deployment issues. So I guess it is > fair to say that .pyc files are not as flexible as Java > class files which are at least forward compatible in most > cases (i.e. old class files will run on newer JVMs). It is not about Python being "less flexible" than Java, Python is evolving. It is also stated in the docs somewhere that bytecode is not guaranteed to be forwards or backwards compatible. > I'm sure a 2.N.x .pyc can run on a 2.N.y interpreter though, > right? :-D Yeah, they try not to do bytecode changes mid point releases. > The answers also make me curious about how CPython's VM works. > I suppose that, unlike Java, it is constantly being reworked > in more extensive ways from one dot-version to another. Would > that also explain why there is no detailed spec detailing how > CPython's VM works (since its design is not as nailed down as, > say, the JVM)? Virtual machine, interpreter, call it what you want. There is probably documentation somewhere, but the best idea (if you are interested) is to just take a dive into the source. It is all browsable on sourceforge. > As a programmer, I find installing (and uninstalling) Python > extensions to be about as easy as one can wish for. However, > for end users, it would be great if we can someday have the > equivalent of a Java Runtime Environment with all the important > extensions already included. Then Python developers can distribute > ..pycs to end-users and expect them to work with few to no issues. IMO you are better off packaging them with py2exe or an equivalent for your platform. Then you can guarantee that your users are running python version x.y.z, and not x.y.a (minor releases are to fix relatively important bugs, which may effect the execution of your program). > The things I would like to see in this hypothetical Python Runtime > Environment (PRE) would be Pygame, PyOpenGL, PyGtk (once it finally > matures on Aqua), and the other popular extensions they rely on (like > Numeric - although the current PyOpenGL is experimenting with > using numarray instead). Such a PRE would not be small, and trying to get compatible versions of all of those 3rd party modules, for every supported platform, would be a pain in the ass. > It may not necessarily have to be the current lightweight distro being > released by the offical Python maintainers, but a separate one > specifically geared for end users who mainly wish to use 3rd party apps > written in Python. Due to Python's nature, such a PRE would also > automatically be an effective developer environment, nullifying the > need for an SDK edition. There already exist 3rd party Python distributions with various add-ons. I don't know of any off the top of my head (because I have no need for them), but I have heard mention of them here. - Josiah From bouil at bouil.org.invalid Wed Mar 24 14:28:35 2004 From: bouil at bouil.org.invalid (Nicolas Bouillon) Date: Wed, 24 Mar 2004 20:28:35 +0100 Subject: py files includings each others In-Reply-To: <1061q52ke6rjsad@news.supernews.com> References: <1061q52ke6rjsad@news.supernews.com> Message-ID: John Roth a ?crit, le 24.03.2004 02:46 : > Hope this helps. Thanks. From max at alcyone.com Tue Mar 23 17:57:10 2004 From: max at alcyone.com (Erik Max Francis) Date: Tue, 23 Mar 2004 14:57:10 -0800 Subject: 3D apps in Python? References: <405FB88A.12995153@alcyone.com> Message-ID: <4060C0C6.3BA8FF23@alcyone.com> Lee Harr wrote: > ZOE (http://www.alcyone.com/software/zoe/) looks really nice. Thanks, although I never would have suspected someone would describe it as "nice." I was expecting more along the lines of, "So what?" :-) -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE \__/ The meaning of life is that it stops. -- Franz Kafka From __peter__ at web.de Mon Mar 29 04:58:48 2004 From: __peter__ at web.de (Peter Otten) Date: Mon, 29 Mar 2004 11:58:48 +0200 Subject: Orders of magnitude References: Message-ID: Robert Brewer wrote: > # bsddb version: c = bsddb.btopen(None) > for i in x: > if i not in c: > c[i] = None You might try a minor change: for i in x: c[i] = None The fewer the redundancies the larger the speed gain (I suppose; that really needs testing to be sure). Peter From maxm at mxm.dk Thu Mar 11 03:54:04 2004 From: maxm at mxm.dk (Max M) Date: Thu, 11 Mar 2004 09:54:04 +0100 Subject: Zippping a directory recursively from Python script on Windows In-Reply-To: References: <404f0141$0$183$edfadb0f@dread12.news.tele.dk> Message-ID: <4050292C.6060200@mxm.dk> Mike C. Fletcher wrote: > Max M wrote: > > Honestly, I wouldn't do this myself, I just tell everyone to get tar and > gzip, but here's a simple example of using ZipFile for creating zips of > directories. You'd want to check for .jpg, .mpg, etceteras and avoid > compressing those most likely, but the basics are there. Ok I got around to trying out the tarfile module, and as usual it was far easier than I would have suspected. import tarfile package = 'somedir' tf = tarfile.open('%s.tar.gz' % package, 'w:gz') tf.add(package) tf.close() So much for using command line tools for this... ;-) Thanks for all the pointers. regards Max M From dw-google.com at botanicus.net Mon Mar 22 07:51:58 2004 From: dw-google.com at botanicus.net (David M. Wilson) Date: 22 Mar 2004 04:51:58 -0800 Subject: PEP 318 References: <99dce321.0403211817.3704fe2@posting.google.com> Message-ID: <99dce321.0403220451.4061cac5@posting.google.com> Ville Vainio wrote... > The current foo=staticmethod(foo) makes the Python 'staticmethod' seem > like a hack. Many users of staticmethod won't even need to know that > wrapping takes place. I find myself in diametric opposition here. :) Users (read: developers) /should/ know how staticmethod is working under it's skin, that's (and hopefully no-one here disagrees) a bloody good thing. The fact that defining a static method is a simple assignment tells the developer a lot more about Python's internal workings than extra syntax does. It's far more general, it's explicit, and it's readable. I can't see at all how it can be considered a hack. If at some future date, staticmethod becomes intrinsicly linked to the Python core in some magical way, then I can see an argument for extra syntax, but as it stands, staticmethod is a wrapper, defining a staticmethod is equivalent to "foo = staticmethod(foo)", and "def foo as staticmethod" is in my books rather ambiguous. > It certainly discourages people from using the > feature in the first place. Again, I can't see how. > And when did syntactic beauty stop mattering? Don't get me wrong, I love lovely looking code, but I don't like code that wears makeup, which is what this is. We can already do this via another, simple, more descriptive means. David. From rogerb at rogerbinns.com Sat Mar 27 14:21:30 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Sat, 27 Mar 2004 11:21:30 -0800 Subject: xmlrpc, httplib and SSL References: Message-ID: <0r0hj1-824.ln1@home.rogerbinns.com> Skip Montanaro wrote: > [snip summary of changes] > > Roger> I now have code that works for me and my project. However it > Roger> wouldn't really be appropriate for going back into the standard > Roger> library because it spends most of its time having to subvert the > Roger> design and implementation of the existing classes. > > Roger> However I was wondering if anyone was working on fixing the (IMHO > Roger> horrible) mess and wants any moral support? > > Sounds like you've done most of the work already. Why not post a few > patches to SF for the various affected modules? The standard modules need to be redesigned! And M2Crypto would have to be the standard SSL. And as I state in the first paragraph you quote, it has to subvert the existing classes. Think of my code as the result of using chainsaws and band-aids all over the existing code. The end result works fine for me and my project. But I wouldn't remotely want to change the existing library to anything like it. Here were the goals I was trying to meet. The current Python library does not remotely meet them. XML-RPC client: - Connections are made over SSL - A callback to verify the certificate if there is no CA or other defined mechanism - HTTP/1.1 is used, and the connection is reused if still open - HTTP authentication is used - Automatic reopen of connection if above one doesn't work (eg remote end closed it after timeout) - Be thread safe (eg one connection per thread - don't reuse across threads) XML-RPC server: - Connections are accepted over SSL - Callbacks to verify incoming connections, certificates and credentials of the connections - Verification of HTTP authentication information - Connections are kept open/keep-alive (HTTP/1.1) - Use of a bounded thread pool that handles the connections Roger From niurka.perez at cimex.com.cu Tue Mar 23 14:13:00 2004 From: niurka.perez at cimex.com.cu (niurka.perez at cimex.com.cu) Date: Tue, 23 Mar 2004 14:13:00 -0500 Subject: class methods and variables Message-ID: <0403241080.AA1080144333@ws3.cimex.com.cu> Having the class Name, is there any way to obtain the class methods or even the variables it has defined? Is there in python something like the Java reflection? Thanks Niurka From cris.tobal at free.fr Fri Mar 19 00:44:08 2004 From: cris.tobal at free.fr (cristobal) Date: 18 Mar 2004 21:44:08 -0800 Subject: batching script on the web Message-ID: I all, I'd like to make a script that can request pages on the web, put some information on a web page like login and password, as if I had done it through a mozilla interface. Through a sery of clic, I'll get a page that I like to parse to fetch some information. (This must be able to go through https connection.) If some one can give me indication how to begin with this, it will be very helpfull. My main problem is to maitain a session with the serveur, it's not only a problem to get url, but sequence of "clic" while keeping a http session open on the server side. thanks for every suggestion. From jdhunter at ace.bsd.uchicago.edu Wed Mar 31 07:51:46 2004 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Wed, 31 Mar 2004 06:51:46 -0600 Subject: Creating Charts In-Reply-To: ("Thomas Guettler"'s message of "Wed, 31 Mar 2004 09:23:50 +0200") References: Message-ID: >>>>> "Thomas" == Thomas Guettler writes: Thomas> Hi! I need to create some simple charts with python. A Thomas> list contains integers between 0 and mymax. Thomas> I want to see how the values are distributed (How many are Thomas> 0, how many are mymax, ...). The result should be a small Thomas> (200x200) png file. Thomas> matplotlib: Too much gtk binding (I only need a png) - The web page may have given this impression, but it's not correct. matplotlib is totally independent of GTK. It *can* render to GTK, but it isn't required. GTK was the first matplotlib backend and perhaps this is why is gets so much prominence on the web page. But now you can use it with GTK, WX or Tk, or none of the above to simply generate PNG or PS figures. To render to PNG w/o a GUI, use the antigrain (agg) backend as described at http://matplotlib.sourceforge.net/backends.html#Agg. Basically, you just need * Download the src distribution, edit setup.py and set BUILD_AGG = True, do a normal setup.py install. * Edit the config file to make agg your default backend by setting backend : Agg in your matplotlibrc file; see http://matplotlib.sourceforge.net/.matplotlibrc. This file should be placed in your HOME dir. Then you can make your small histogram figure as follows from matplotlib.matlab import * x = someInts # your data here hist(x, 100) # 100 is the number of histogram bins savefig('myfig.png', figsize=(4,4)) # figsize in inches Hope this helps, John Hunter From kirk at strauser.com Mon Mar 22 16:55:06 2004 From: kirk at strauser.com (Kirk Strauser) Date: Mon, 22 Mar 2004 21:55:06 GMT Subject: Decent way to trace resource leaks? Message-ID: <87r7vk7dnc.fsf@strauser.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 I've written a fairly complex application [1] that runs under Windows XP with ActiveState Python. I'm reasonably sure that I'm freeing all allocated resources, but my process seems grow slowly but steadily over time. Worse, my network administrator seems to think that it's locking network resources and not freeing them, and while I don't *think* that's the case, I can't be certain. Ideally, I'd like to find a way to dump the process's object hierarchy to the screen or a file in a tree or graph format. Even without variable names, it'd be tremendously helpful to see that there are 87 instances of Foo objects, each with 20 Bar objects as data members. Although I'm running the application on Windows, I'm doing all development on a Linux system (using Subversion to synchronize source trees across machines, in case anyone is interested), so I'd prefer something native to Python and not a Windows-specific GUI debugger. [1] Said application implements a SOAP interface to Microsoft Access and FoxPro databases so that the Unix applications I'm writing can query those systems. - -- Kirk Strauser The Strauser Group Open. Solutions. Simple. http://www.strausergroup.com/ -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.4 (GNU/Linux) iD8DBQFAX2Aw5sRg+Y0CpvERArOaAJ4/VdLdqLZzetF4pIu/Gb43vCIX7QCfZq+X leYooXAV4mW29af/tCcGCp0= =Kl5V -----END PGP SIGNATURE----- From tim.golden at viacom-outdoor.co.uk Thu Mar 25 03:45:51 2004 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: 25 Mar 2004 00:45:51 -0800 Subject: Python / COM / Word References: <5cf809e9.0403241936.5fe98316@posting.google.com> Message-ID: <8360efcd.0403250045.273b3e9b@posting.google.com> peter.schwalm at epost.de (Peter Schwalm) wrote in message news:<5cf809e9.0403241936.5fe98316 at posting.google.com>... > .... > > >>> w1 = win32com.client.DispatchEx ("Word.Application") > .... > > "DispatchEx" is a solution I have long searched for. Thank you very > much! > > And a question: where do you have the info about DispatchEx from? Does > there exist a documention for win32com? And if yes: where? Ah. I don't remember where I found out about it; either on this list or on the python-win32 mailing list, I expect. Such documentation as there is for win32com is: 1) The documentation that comes with the pywin32 extensions (in various forms) 2) In Mark Hammond & Andy Robinson's Python Programming on Win32 (or something like that) 3) On the python & python-win32 lists 4) On various people's websites But you probably knew that... Tim From michele.simionato at poste.it Fri Mar 26 23:49:00 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 26 Mar 2004 20:49:00 -0800 Subject: A 'Python like' language References: <40645d8f$0$10775$afc38c87@news.easynet.co.uk> Message-ID: <95aa1afa.0403262049.4b2a6f78@posting.google.com> David MacQuigg wrote in message news:... > What I found most interesting about this language is that it *doesn't > use classes* !! All objects are derived directly from other objects, > some of which are "prototypes", that is, objects which were designed > to be just templates to produce other objects. Yes, this seemed interesting to me too. But when arrived at the sentence "Prothon only allows tabs for indentation" I couldn't continue reading ;-) Michele Simionato From vincent at visualtrans.de Thu Mar 4 15:41:43 2004 From: vincent at visualtrans.de (vincent wehren) Date: Thu, 4 Mar 2004 21:41:43 +0100 Subject: what is a good intro book on python ? References: Message-ID: ----- Original Message ----- From: "Larry" Newsgroups: comp.lang.python Sent: Thursday, March 04, 2004 7:35 PM Subject: what is a good intro book on python ? > I'm a C++/java programmer and have done a bunch of perl coding. > I am thinking of maybe learning python. What's a good intro primer, easy to read > good examples, understandable, maybe not one of those 2 inch thick books etc. ? "Learning Python, Second Edition" by David Ascher and Mark Lutz (1.13 inches) perhaps? And then, not so much *intro* but absolutely *vital*: "Python in a Nutshell" by Alex Martelli (1.14 inches) "Python Cookbook", by Alex Martelli, David Asher (Editors) (1.10 inches) HTH, Vincent Wehren From bignose-hates-spam at and-benfinney-does-too.id.au Wed Mar 3 22:33:39 2004 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 4 Mar 2004 14:23:39 +1050 Subject: OT(Slightly): Thanks to Python. References: Message-ID: On Thu, 04 Mar 2004 02:11:35 GMT, Adonis wrote: > with my background in Python, giving me the knowledge of OOP I dove > into Java like a pro, everything came easy to me, I fully understood > the language, everything was just some clarification and learning the > syntax (I still dislike Java, but to each its own), so I am writing > this as a thank you to everyone who contributes to Python. Python has introduced many students to the benefits of properly-implemented OOP. It's good to know that you've got this strong start. It may interest you to know that Python's suitability as a language for teaching programming has long been a conscious goal of the language's creator, and something with which he actively involves himself: -- \ "I don't care to belong to a club that accepts people like me | `\ as members." -- Groucho Marx | _o__) | Ben Finney From dmq at gain.com Tue Mar 30 16:25:06 2004 From: dmq at gain.com (David MacQuigg) Date: Tue, 30 Mar 2004 14:25:06 -0700 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> <40675F08.9070402@mlug.missouri.edu> <258fd9b8.0403301237.60528600@posting.google.com> Message-ID: On 30 Mar 2004 12:37:25 -0800, magnus at thinkware.se (Magnus Lyck?) wrote: >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. Maybe Prothon will *become* Python 3.0 That could happen quicker than migrating all the Python libraries to Prothon. Open source is an amazing phenomenon! Nothing like a little kick-in-the-butt competition to stimulate progress. :>) -- Dave From teiffel at attglobal.net Tue Mar 2 16:24:23 2004 From: teiffel at attglobal.net (Marcello Pietrobon) Date: Tue, 02 Mar 2004 16:24:23 -0500 Subject: Regular expressions help In-Reply-To: <403BACC5.5060902@advalvas.REMOVEME.be> References: <6af33541.0402241054.77ae5c61@posting.google.com> <403ba857$0$1110$6c56d894@feed0.news.be.easynet.net> <403BACC5.5060902@advalvas.REMOVEME.be> Message-ID: <4044FB87.1080804@attglobal.net> Bernard Delm?e wrote: >> That one matches the "name george" part of "name georgeharry" as well, >> which he didn't want. > > > Indeed; my bad. I mostly wanted to mention redemo, for which > the windows installer should create a shortcut, really... > Agreed From dmq at gain.com Tue Mar 23 20:40:07 2004 From: dmq at gain.com (David MacQuigg) Date: Tue, 23 Mar 2004 18:40:07 -0700 Subject: The problem with "as" [was "Re: PEP 318"] References: <99dce321.0403211817.3704fe2@posting.google.com> <7x1xnlqs77.fsf@ruckus.brouhaha.com> <8ef9bea6.0403221354.574ebdaf@posting.google.com> <1M-dnXrds_WKG8LdRVn-jw@comcast.com> Message-ID: On Tue, 23 Mar 2004 08:39:19 GMT, Joe Mason wrote: >In article , Joe Mason wrote: >> Not a big fan of that syntax - I have to keep the parameter names and >> types in sync by counting. >> >> def foo(x [accepts(int)], y [accepts(float)]) [returns(int)]: >> >> is a little better, except now we're getting very verbose. >> >> For decorators in general, I like >> >> def foo() as [decor1, decor2, decor3]: >> >> You get an explicit list syntax, but it's set off by a keyword so they don't >> run together to the eye. Because the keyword keeps it unambiguous, you >> could even allow a tuple instead of a list: "def foo() as (x, y, z)". >> >> So I definitely favour a keyword, but perhaps "as" is to generic. What >> about "has" or "with"? A less generic keyword will lead to odd phrases like "has int" or "with staticmethod", or different keywords for each phrase. The problem with using different keywords for each phrase is - after we get a collection of them, it becomes a problem for beginners to remember which one to use in each situation. Even if you try to chose a keyword which is self-explanatory, a lot of people don't get the meaning you intended (e.g. 'yield' as in 'produce' rather than 'give way', 'lambda' as in 'lambda calculus'). What we need is something short, neutral in meaning, and usable in any situation where you need to modify an existing syntax, i.e. a symbol. Re-use of the same symbol to mean "modified syntax" in any context, will avoid the Perl problem (too many symbols with idiosyncratic meanings). Beginners will learn very quickly that the special symbol means "similar to the standard syntax, but RTFM if you don't yet know this variation". Locating the right documentation will be easy, because it will always be at the end of the discussion on the normal form of the statement. I would give an example, but I worry it will degenerate this discussion into a debate over whether it looks like something bad in language X. Let's see if we can discuss this on a higher level first. Does it make sense to have a general symbol for modifications of the simple standard syntax? -- Dave >Come to think of it, the verbose example with "has" becomes (assuming a >shorter decorator name): > > def foo(x has sig(int), y has sig(float)) has returns(int): > >Since you might not need the full list syntax for a single decorator. >That's not too bad looking. > >(No, I'm not seriously proposing decorators on parameters at this point.) > >Joe From tjreedy at udel.edu Sat Mar 6 23:41:14 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 6 Mar 2004 23:41:14 -0500 Subject: Need better string methods References: <0d4k40987t6d70bahqil3geth640bufgoc@4ax.com> <404A9883.3010407@stackless.com> Message-ID: "Christian Tismer" wrote in message news:404A9883.3010407 at stackless.com... > I have no idea what OP is. Original Poster. From mwh at python.net Mon Mar 15 09:40:16 2004 From: mwh at python.net (Michael Hudson) Date: Mon, 15 Mar 2004 14:40:16 GMT Subject: Deprecating reload() ??? References: <09b350henbtk9vnai0v7fhtbsqbmubl7vn@4ax.com> <7cj4c.2733$G3.21896@localhost> <8ok3505b3b3g22bk8ci6iagptqav2cfi6r@4ax.com> <6kk6501shlve52ds2rjdopa73jhpchprg3@4ax.com> Message-ID: Skip Montanaro writes: > >> >I wrote something and threw it up on my Python Bits page: > >> > > >> > http://www.musi-cal.com/~skip/python/ > >> > >> I get AttributeErrors when I try the super_reload function. Looks > >> like sys.modules has a bunch of items with no '__dict__'. > > Michael> They'll be None, mostly. > > What's the significance of an entry in sys.modules with a value of None? > That is, how did they get there and why are they there? Something to do with packags and things that could have been but weren't relative imports, I think... >>> from distutils.core import setup >>> import sys >>> for k,v in sys.modules.items(): ... if v is None: ... print k ... distutils.distutils distutils.getopt encodings.encodings distutils.warnings distutils.string encodings.codecs encodings.exceptions distutils.types encodings.types distutils.os distutils.re distutils.sys distutils.copy Cheers, mwh -- It's actually a corruption of "starling". They used to be carried. Since they weighed a full pound (hence the name), they had to be carried by two starlings in tandem, with a line between them. -- Alan J Rosenthal explains "Pounds Sterling" on asr From dale at bewley.net Thu Mar 18 01:22:41 2004 From: dale at bewley.net (Dale Bewley) Date: Thu, 18 Mar 2004 01:22:41 -0500 (EST) Subject: Please confirm your message to dale In-Reply-To: <20040318062125.3FBDF3EE56@bewley.net> References: <20040318062125.3FBDF3EE56@bewley.net> Message-ID: <1079590961.29117.TMDA@bewley.net> dale has NOT seen your email yet! This message was created automatically by mail delivery software (TMDA). Your message attached below is being held because the address has not been verified. To release your message for delivery, please send an empty message to the following address, or use your mailer's "Reply" feature. dale-confirm-1079590961.29117.c829d8 at bewley.net This confirmation verifies that your message is legitimate and not junk-mail. You should only have to confirm your address once. If you do not respond to this confirmation request within 14 days, your message will not be delivered. -------------- next part -------------- An embedded message was scrubbed... From: python-list at python.org Subject: Your IP was logged Date: Thu, 18 Mar 2004 01:30:51 -0800 Size: 829 URL: From s.meyer at technology-network.de Wed Mar 17 09:43:44 2004 From: s.meyer at technology-network.de (Sebastian Meyer) Date: Wed, 17 Mar 2004 15:43:44 +0100 Subject: Problem with threads and signals References: Message-ID: On Wed, 17 Mar 2004 11:22:47 +0100, Holger Joukl wrote: > Does the shutdown function get called when you issue the signal? > How exactly do you handle the event communication in the treads? shutdown > methods? > Please post the relevant code. the shutdown function does not get called, it seems the signal gets lost the threads shutdown function looks like: --- CODE --- # self._done is a threading.Event object def shutdown(self): self._done.set() > Btw, I am new to python2.x (not new to python, though). This is not working > code, > is it? > threads = {} > threads["dircheck"] = TimedDirectoryCheck("/tmp/dpf/notify") > threads["process"] = BatchProcessor() > # start the threads > for th in threads: > th.start() # <---- Does that work??? > of cource does this work, ... makes life a lot easier and saves up variable names ... :-)) Sebastian From kmmcdonald at wisc.edu Sat Mar 13 02:42:57 2004 From: kmmcdonald at wisc.edu (Kenneth McDonald) Date: Sat, 13 Mar 2004 07:42:57 GMT Subject: Performance penalty for using properties? Message-ID: Now that I'm back to Python and all the new (to me) cool features, I find I'm using properties a lot, i.e. I'm defining: foo = property(fset=..., fget=...) for a number of properties, in many of my classes. I'm not using them for anything performance critical yet, but could see myself doing so in the future. Can anyone comment on the performance costs associated with properties vs. simple attribute lookup? Thanks, Ken From bignose-hates-spam at and-benfinney-does-too.id.au Fri Mar 12 22:50:35 2004 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 13 Mar 2004 14:40:35 +1050 Subject: root password in a .py script References: <87y8q5g8sg.fsf@strauser.com> <7x8yi5wfyd.fsf@ruckus.brouhaha.com> Message-ID: On 12 Mar 2004 20:04:10 -0800, Paul Rubin wrote: > Rather than entering the plaintext password through the passwd > command, your best bet is for your script to edit /etc/passwd or > /etc/shadow and replace the new hashed password with the correct one. No, that makes the increasingly incorrect assumption that the passwords are stored and accessed via those files. Many systems use NIS or LDAP or other protocol-based account table management methods, and the 'passwd' command is often set up to use that method. Affecting /etc/* files in such a case would have no effect on the root password. -- \ "I bought some batteries, but they weren't included; so I had | `\ to buy them again." -- Steven Wright | _o__) | Ben Finney From joewong at mango.cc Wed Mar 24 01:10:43 2004 From: joewong at mango.cc (Joe Wong) Date: Wed, 24 Mar 2004 14:10:43 +0800 Subject: how to detect connection closed by server? References: <004401c41156$18c17dd0$7f00a8c0@scl01.siliconcreation.com> <40611FB7.19737291@hot.pl> Message-ID: <00ba01c41166$be5319b0$7f00a8c0@scl01.siliconcreation.com> Hi Jacek, If the server never send some reply back to the client, it is not possible for the client to determine if the server had actually received the data ( e.g., server called accept() but not calling recv() to read data from client, then close() the client socket right away ). Am I right? If this is the case, I can't really rely on the socket function in the client program to tell if the server has read the data.. Regards, - Wong ----- Original Message ----- From: "Jacek Trzmiel" To: "Joe Wong" Cc: Sent: Wednesday, March 24, 2004 1:42 PM Subject: Re: how to detect connection closed by server? > > Joe Wong wrote: > > Client: > > - create socket > > - connect to port XYZ at server > > - send some data to server > > - close the socket > > > > The problem I found is that, after the server perform the listen() > > call, the client program can sucessfully perform connect(), send() and > > close() on the socket > > AFAIR with T/TCP it's entriely possible to open connection, send small > payload and close connection in one single IP packet. > > > even the server process does not perform the > > accept() and recv() call. Is this a general behaviour of the socket or > > I am not writing my program properly? > > Close only sending part of the socket and then block on read. It will > either: > - report EOF if server accepted and then closed connection without > sending any data, > - return some data if server sent it, > - report some kind of error otherwise. > > Best regards, > Jacek. > > From tismer at stackless.com Sat Mar 20 12:38:04 2004 From: tismer at stackless.com (Christian Tismer) Date: Sat, 20 Mar 2004 18:38:04 +0100 Subject: Package name with '.' in them: Python Bug ? In-Reply-To: References: <105mmlt1ld7jvb9@news.supernews.com> <8ef9bea6.0403192150.57dbddef@posting.google.com> Message-ID: <405C817C.5010406@stackless.com> Terry Reedy wrote: > "Hung Jung Lu" wrote in message > news:8ef9bea6.0403192150.57dbddef at posting.google.com... > ... >>A little hyphen would have made a whole world of difference. The >>original poster was referring to "class-static variable", > > In Python, that is a meaningless term to me. Sure, but you knew that the OP was a fresh Python user, and using terminology of other languages was obvious. If he knew better, he wouldn't have used this phrasing. So why not simply explaining the difference in the first place? 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 jcarlson at uci.edu Tue Mar 30 13:01:35 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Tue, 30 Mar 2004 10:01:35 -0800 Subject: emergent/swarm/evolutionary systems etc In-Reply-To: References: Message-ID: > From this, and other reading on genetic algorithms, I've found that nearly > all of the applications being developed and used are far 'stronger' than > what I have in mind. Most critically, the great preponderance of uses > involve a program that simply modulates a set of given variables in search > for an answer, rather than modifying the source code itself. Understandably, > this is because, as stated above, such 'weak' methods are of limited use for > most problems (I wouldn't want to fly in a plane that had been designed by > one). > Since, at the moment, I'm more interested in a 'pet cyber slime' than a tool > for designing efficient circuit layouts, such 'strong' applications are of > limited use. Even the 'state space' and 'random search' examples above are > considerably 'stronger' than I would desire to use. > For me, the goal is not only to create a program that can find an optimal > solution to a problem, but which can also find better ways of learning - > something disallowed by a fixed-algorithm engine. Take this with a grain of salt, but generally, expecting computers to learn is a high expectation. From neural networks (aka connectionist networks), genetic algorithms, naive bayesian statistics, etc., the desire in all of these cases is for a system that responds to a certain environment, produces some reasonable solutions in this environment, and works reasonably well in other environments. The one limitation of all these approaches is that the algorithms and methods for doing this have limited knowledge (usually a few hundred bytes of state), no higher-order insight, etc. The algorithms, when given proper input and design, can solve certain problems. You may get lucky and your algorithm/data is applicable to another problem, but those situations are the rare exception, rather than the rule. These 'learning' methods do the best when applied to what you have shown is called 'strong' problems. The 'weak' problems I've seen worked on, generally had weak (read poor) results. The stronger your problem, the better results you will likely have. > There's a lot of other interesting stuff on this site, but it'll take a > while to examine it all, and it'll be quite a while more before I have the > time to start on Stephen Wolfram's "A New Kind of Science". One question > though - can I, indeed, create, modify, run and save files using just a > python script? Don't think of Python as a scripting language. It can be used that way, but Python has better built-in data structures and language features than the most used languages out there (C, C++ and Java). Can you create a file? Certainly, open a file for writing that didn't previously exist... file_for_writing = open('filename', 'wb') Can you modify a file? Certainly, open a file for reading and updating that exists... file_for_updating_in_place = open('filename', 'r+b') 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) Want to save a file? fil = open('filename', 'wb') fil.write("some string of what you want to write") fil.close() - Josiah From tismer at stackless.com Mon Mar 29 08:47:32 2004 From: tismer at stackless.com (Christian Tismer) Date: Mon, 29 Mar 2004 15:47:32 +0200 Subject: Prothon Prototypes vs Python Classes In-Reply-To: <406826CA.6070107@mlug.missouri.edu> 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> <4067C167.5050708@mlug.missouri.edu> <40681B2B.2080106@stackless.com> <406826CA.6070107@mlug.missouri.edu> Message-ID: <406828F4.2020103@stackless.com> Michael wrote: > >> I think there are enough editors available to be able >> to use one with fixed font. > > > Exactly. I'd say the same thing about the problem with tabs. If your > editor has some weird issue with tabs then fix it or use a different > editor. It seems a bit odd to me that it's an issue at all. > >> worse: you can lose indentation and totally mess up >> The problems with mixed tabs and spaces are even >> >> You gave the best example by yourself: Use different editors, >> even with fixed fonts, and you will wonder how they try >> to "optimize" your tabs. Some try to help you with the indentation, >> but they use tabs, even if you are not aware of it. >> I don't say it is a hard problem. But it is an extra complication >> which consumes a reasonable amount of Python code to check/repair, >> like tabnanny. > > > Why should an editor change anything in your program at all unless you > tell it to? If it's changing tabs to spaces or vice versa then it sucks. > If I want something optimized I'll enter a command telling it to do so. > Otherwise hands off. If you are on anyone's machine, maybe some Linux server, and you don't find time to install an editor, then you use vim for instance, and it depends on its configuration how it handles Python code. Some indent for you the wrong way. You have no choice if you are fixing something in a hurry. ... > A tab is a tab. This sounds like adding complexity in the effort to > avoid complexity. If your editors are broken then stop using them. I make my living by using several editors on several machines, all the time. 95 % is ok, but it often comes to situations where I have to hack "that code on this machine right now", and the user won't give me the rights or the time to fine-tune my editor environment. There is also no choice of "hands-off". The customer wants me to handle such minor problems as "the expert". This is no matter of choice but daily practice :-) -- 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 bassw at hotmail.com Fri Mar 12 15:07:55 2004 From: bassw at hotmail.com (Bas) Date: 12 Mar 2004 12:07:55 -0800 Subject: use -> instead of lambda?? References: Message-ID: <8fe46d4f.0403121207.30dd56d3@posting.google.com> David MacQuigg wrote in message news:... > Seems like we need a simple way to extend Python syntax that doesn't > break existing syntax or clash with any other syntax in Python, is > easy to type, easy to read, and is clearly distinct from the "base" > syntax. Seems like we could put the @ symbol to good use in these > situations. Examples: > [...] > @x,y:x*x+y*y -- anonymous function > [...] > It certainly beats adding ugly statements like 'lambda'. Couldn't we use -> instead?? This wouldn't introduce the the @ symbol (currently forbidden??), but only uses symbols that are already used. It is thus just another operator. The -> symbol is already used a lot in the help strings, so why not use it in the language also?? Maple (symbolic math program) also uses -> for anonymous functions. From biner.sebastien at ouranos.ca Tue Mar 9 16:28:53 2004 From: biner.sebastien at ouranos.ca (biner) Date: 9 Mar 2004 13:28:53 -0800 Subject: installing PIL without jpeg? Message-ID: Hello, following a question about getting the size of a gif image, a good soul (thank you Skip) adised me to install PIL in order to do so. I am trying do do make the installation on an IRIX platform as a user. I did as told in the readme and used the configure script with the --prefixe=dir with dir pointing to a directory of my own. I got an error message in the "make" process when the JpegDecode.c was compiled because jpeglib.h was not found. I tried to use configure with the --without-jpeg flag but the Makefile doesn't change. I tried to look in the configure script in order to get the jpeg related object ou of the list which is put in the Makefile but I have a (very) hard time making any sense of the configure script. Is there a simple way to install PIL without the jpeg library? Thanks. From mwh at python.net Wed Mar 3 14:01:10 2004 From: mwh at python.net (Michael Hudson) Date: Wed, 3 Mar 2004 19:01:10 GMT Subject: E-mail account disabling warning. References: <95aa1afa.0403030526.728de57b@posting.google.com> Message-ID: michele.simionato at poste.it (Michele Simionato) writes: [virus] > > it's not from anyone at python.org, and the zip file attached contains a > > Windows virus. But if you run it anyway, I'm sure Guido will be happy to > > fly to your house and clean up your PC. > > > > it's-the-least-he-could-do-for-you-ly y'rs - tim > > I have got today a very similar message, but from my University provider. I got a dozen or so, all claiming to be from the 'ac.uk' email organizers, a bug that the author needs to fix in the next version... > I don't think SpamAssassin could have filtered it. The spammers are > evolving and becoming smarter and smarter, I fear the day they will > be able to pass the Turing tests and we will be no more able to > distinguish automatically generated spam from real e-mail .... Uh, not quite there yet in my email (unless you habitually get email with subjects like "comedian gordon sideband numinous climatic"). Cheers, mwh -- I also feel it essential to note, [...], that Description Logics, non-Monotonic Logics, Default Logics and Circumscription Logics can all collectively go suck a cow. Thank you. -- http://advogato.org/person/Johnath/diary.html?start=4 From jacek.generowicz at cern.ch Fri Mar 12 07:56:53 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 12 Mar 2004 13:56:53 +0100 Subject: Static Typing in Python References: Message-ID: Peter Maas writes: > Premshree Pillai schrieb: > > How do I force static typing in Python? > > You have to enforce it by code instead of declaration, i.e. you > have to do runtime type checking. Just what do you understand "static typing" to mean ? From joshway_without_spam at myway.com Tue Mar 30 08:50:39 2004 From: joshway_without_spam at myway.com (JCM) Date: Tue, 30 Mar 2004 13:50:39 +0000 (UTC) Subject: Why '==' ?? References: <8089854e.0403300510.1971c24@posting.google.com> Message-ID: Fuzzyman wrote: > I may be about to get flamed as some heretic against the ancient > way..... but if assignment in conditional statements isn't > possible.... why do we need to use '==' instead of just '=' for if and > while statements ? > It's possible there are places where the interpreter could fail to > understand it, but I haven't found them yet. If there *aren't* any > situations where one could be confused for the other... then it's not > needed and is annoying :-) a = b = c a = b == c From srn at fn.com.au Fri Mar 19 15:11:28 2004 From: srn at fn.com.au (Stephen Robert Norris) Date: Fri, 19 Mar 2004 20:11:28 GMT Subject: Package name with '.' in them: Python Bug ? References: Message-ID: On Fri, 19 Mar 2004 19:12:03 +0100, Yannick Patois wrote: > Hi, > > > Terry Reedy wrote: >> "Yannick Patois" wrote in message >>>Under some naming conditions of module files, it seems that python lost >>>class static variables values. >> Since 'static variable' is not a Python concept, I do not know what you >> mean. > > As you're so smart and you read the following, how do you call 'a' in > class A ? > That's what I want to qualify. > There's no need to be hostile. I'd call it a class variable. It's certainly not static in any sense of the word I'd use. >>>The value 1 obtained as expected (A.a is a static value and keept as >> such). >> Given that you rebound A.a to 1 from None, I especially do not know >> what you mean. > > I dont understand. You explicitly construct the A instance with 1, so what do you expect to happen? A.a is set to None as a class variable, then changed to 1 by the constructor. > >>>If now I just *rename* file B to B.1, without any change in the code >>>(except name='B' become name='B.1' in aTest.py), content of B.1.py file >>>being exacty the same as content of B.py, I get: >> >> As you seem to be aware, Python expects modules to have a 'nice' name >> consisting of >> legal_Python_indentifier.py. > > Which are ? Where to find this info ? Check the Python Reference Manual. > >> If you evade this, you are a bit on your own >> and may run into untested corner cases. > > Untested area contains bugs, that's why it's interesting to test them. The only potential bug here is that perhaps python should have raised an error when the import happened. > To me, that's look to be a bug. > > Yannick I think the bug is in how you understand Python, not in python. Stephen From craigmnet at REMOVEcow.physics.wisc.edu Fri Mar 12 17:40:46 2004 From: craigmnet at REMOVEcow.physics.wisc.edu (Craig Markwardt) Date: 12 Mar 2004 16:40:46 -0600 Subject: root password in a .py script References: <7xoer1ls3j.fsf@ruckus.brouhaha.com> Message-ID: Bart Nessux writes: > Paul Rubin wrote: > > If they have changed the root password on their machine, then the old > > root password in your script won't work on that machine. > > > > Find another way to do what you're asking. > > Well, it works. They change the password and the script changes it > back... try it yourself on Mac OSX 10.3.x, before claiming it doesn't work. If you can run as root, or even if not, why not simply check /etc/passwd for changes to the root account. And mail a notification to whoever, if it changed. And it's less overbearing. More dangerously, one could attempt to rewrite that entry in /etc/passwd, but that sounds like a recipe for eventual disaster. Craig -- -------------------------------------------------------------------------- Craig B. Markwardt, Ph.D. EMAIL: craigmnet at REMOVEcow.physics.wisc.edu Astrophysics, IDL, Finance, Derivatives | Remove "net" for better response -------------------------------------------------------------------------- From lbates at swamisoft.com Fri Mar 12 12:57:49 2004 From: lbates at swamisoft.com (Larry Bates) Date: Fri, 12 Mar 2004 11:57:49 -0600 Subject: UNC paths in file object open References: <4051f619$0$6547$ed9e5944@reading.news.pipex.net> Message-ID: Graham, path=r"\\servername\sharr\folder\file.ext" works on my machine (I use it all the time). Remember that backslash is an "escape" character so you must us r"" or double the number of backslashes without the "r": path="\\\\servername\\share\\folder\\file.ext" -Larry Bates "Graham" wrote in message news:4051f619$0$6547$ed9e5944 at reading.news.pipex.net... > I ma trying to open a file on a network share > > ie \\servername\share\folder\file > > afile = open( \\server\share\folder\file, "r" ) > > have also tried > afile = open( //server/share/folder/file, "r" ) # as per the Python cookbook > advice on page 113 namely " use / regardless of the proclivities of the > underlying operating system". > > Neither work. > > I am running python on XP and accessing win 2000 share. > > Thanks for any help > > Graham Smith > > PeopleSoft Technical Team Leader > OXFAM GB > +44 (1865) 313255 > gsmith at oxfam.org.uk > > > From fpetermaas at netscape.net Mon Mar 1 07:59:23 2004 From: fpetermaas at netscape.net (Peter Maas) Date: Mon, 01 Mar 2004 13:59:23 +0100 Subject: Python as replacement for PHP? In-Reply-To: References: <403fa54b@news.zianet.com> <40408c29$0$2435$626a14ce@news.free.fr> Message-ID: Bart Nessux schrieb: >>The only points I see in favor of PHP are : >>- it's a de facto standard, widely used, widely available, and well >>established > > > That's exactly right. That's my point. I meant nothing more. That's ALL? No preference for specific PHP issues that makes you choose/recommend it over Python? If youre "stupidity" posting has anything to do with logic then I must conclude that you consider everbody who doesn't use the de facto standard (choosing e.g. Linux over Windows, Python over Perl) bordering on stupidity. Strange, to say the least. 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 nid_oizo at yahoo.com_remove_the_ Fri Mar 5 13:35:40 2004 From: nid_oizo at yahoo.com_remove_the_ (Nicolas Fleury) Date: Fri, 05 Mar 2004 13:35:40 -0500 Subject: is perl better? In-Reply-To: References: Message-ID: jon c wrote: > if you try and execute the command directly from bat you get the error > input line too long! > > can perl be somehow bypassing the windows terminal and running the > command directly (does this make sense?) system uses the shell, even with Perl (in Perl it actually depends on what are the parameters). But the shell can be bypassed, so I guess this is a shell limit. Like said Peter, we need to know: - How is it called in Perl. - How is it called in Python, and do you have the same problem by using popen. Regards, Nicolas From davidjtaylor at optushome.com.au Fri Mar 26 00:45:05 2004 From: davidjtaylor at optushome.com.au (sydneyguru) Date: Fri, 26 Mar 2004 16:45:05 +1100 Subject: Newbie trying to use HTTPS, pls help Message-ID: <4063c33b$0$3953$afc38c87@news.optusnet.com.au> Hi, I think the sockets module has not been compiled for ssl. That's my guess at why this won't work... Can anyone suggest a better way.. set up params & headers ... >>> conn = httplib.HTTPSConnection("betting.sports555.com") // imaginary url >>> conn.request("POST", "/cgi-bin/login", params, headers) Traceback (most recent call last): File "", line 1, in ? conn.request("POST", "/cgi-bin/login", params, headers) File "D:\Python22\lib\httplib.py", line 701, in request self._send_request(method, url, body, headers) File "D:\Python22\lib\httplib.py", line 723, in _send_request self.endheaders() File "D:\Python22\lib\httplib.py", line 695, in endheaders self._send_output() File "D:\Python22\lib\httplib.py", line 581, in _send_output self.send(msg) File "D:\Python22\lib\httplib.py", line 548, in send self.connect() File "D:\Python22\lib\httplib.py", line 945, in connect ssl = socket.ssl(realsock, self.key_file, self.cert_file) AttributeError: 'module' object has no attribute 'ssl' >>> cheers, sydneyguru From nospam at nowhere.hu Mon Mar 15 14:08:53 2004 From: nospam at nowhere.hu (Miklós) Date: Mon, 15 Mar 2004 20:08:53 +0100 Subject: INTRANET zope References: Message-ID: "Andrzej Mleczko" wrote in message news:c32rlm$akq$1 at topaz.icpnet.pl... > Hi > I'm searching for an open-source, free Intranet solutions in Zope. > > This post doesn't make any sense... Almost any "Zope solution" is open-sourced. (You components, right?) And certainly all of them are "Intranet solutions" Pm From peter at engcorp.com Sat Mar 20 17:47:38 2004 From: peter at engcorp.com (Peter Hansen) Date: Sat, 20 Mar 2004 17:47:38 -0500 Subject: [OT] Compilable Python-like language? In-Reply-To: References: Message-ID: Carl Banks wrote: > Fran?ois Pinard wrote: > >>[Ed Cogburn] >>>I'm just curious if such a beast exists out there. I've googled >>>around some and read some programming language websites but I have yet >>>to find a language similar to Python that can be compiled to binary. >>>[...] Is there such a thing? >> >>What is your real need? Why do you consider important to compile >>something to an executable binary? The goal is executing a program >>written in Python, or Python-like language, isn't it? > > I really don't think why he needs it is necessary to answer this > question: he stated what he wanted clearly enough. And I would say > questioning his need for a complied language is quite presumptuous. Presumptuous? Hardly. It's a very valid question to ask. By asking for "a compiled language like Python", Ed is making the common mistake of specifying a solution without identifying what his requirements are. We are simply trying to identify what his real needs are so that we can give him a useful answer, along the lines of, say, "use py2exe for easier packaging" if that were his goal. Also, although I don't think this is a problem Ed has, some people are confused about interpreted versus compiled and such things. It's just possible that someone asking such a question has an incorrect understanding of how programs work, and thus asked a "wrong question" innocently. -Peter From adeleinandjeremy at yahoo.com Wed Mar 31 15:17:32 2004 From: adeleinandjeremy at yahoo.com (Adelein and Jeremy) Date: Wed, 31 Mar 2004 12:17:32 -0800 (PST) Subject: ESR's fortune.pl redone in python - request for critique Message-ID: <20040331201732.86453.qmail@web40802.mail.yahoo.com> Thanks again for all of the feedback. (JH)> My second comment was that it is not necessary to explicitly (JH)> exit the program with 'sys.exit()'. I was aware of this, but it is a bad habit of mine (philosopher's disease?) to state the obvious even if it has already been stated elsewhere (when the interpreter terminates process and exits, right?). sys.exit() is only necessary for properly terminating event loops, is that correct? (JH)> I am impressed with the way you followed up on this. I am not quite sure what you mean by this (how else would I have done so?), but thank you. >> In fact, I did intend to have 0 as the first element. My thinking >> is thus: the first entry in the fortunes file is not preceded by a >> '%', and therefore will not be found by the code that follows >> unless I include 0 as one of the possible fp values. I do not know >> perl, and am not an experienced programmer, so in thinking that >> this was the reason for ESR's similar use, I may be proceeding >> from a position of ignorance. > (PO)> I think you're right again. I am right about the first element needing to be zero, xor that I am proceeding from a position of ignorance? :-) (PO)> A wrong error message may be worse than no error message. (PO)> Consider (PO)> (PO)> try: (PO)> fi = open(fortune_file) (PO)> except: (PO)> sys.exit("Cannot open fortunes file %s." % fortunes_file) (PO)> (PO)> That might mislead you to look for problems with the file while (PO)> it's just an ordinary spelling error. I see your point, I think. I am understanding that I should simply exit upon IOError exception, with no error message at all, so that an user is not led to believe that the file may be corrupt when in fact it may not exist, or the filename passed was misspelled, etc. - this point is good to keep in mind for all error messages, I will add it to my thinking. (PO)> You can think of seek() for a readonly file as positioning a (PO)> pointer to the start of the next read() operation. As no more (PO)> reads will follow, such a repositioning is useless. ...And therefore inefficient.... (JH)> Repositioning the file pointer is not necessary, this pointer (JH)> just vanishes when you close the file anyway. ...So I correctly understood the comments on this subject. Thank you. (PO)> As you can see from Mel Wilson's code, (PO)> 3) it also greatly simplifies your program, which means it will (PO)> be less errorprone and take less time to write and less time to (PO)> understand for others. Also, I expect it to be the fastest for (PO)> small files - and the size so called "small" files is still (PO)> growing fast these days. (PO)> (PO)> Yes, Mel's approach is the least scalable (it keeps the whole (PO)> file), followed by yours (keeps a list of positions for every (PO)> items). Mine is best in that regard :-), because it only keeps (PO)> two items (reducing that to one is left as an exercise...) at (PO)> any time. But if you really need performance and many entries, (PO)> I'd guess that putting the items into a database would defeat (PO)> them all. So, Mel's version for small files (which applies 99% of the time to fortune files), mine to show how Perl transforms into Python statement-by-statement, and yours (once I get a handle on it) for 'production' use. > Also, what is 'tr' in the arguments list for file()? I looked up > file() in the library reference and it doesn't mention t - only a, > b, r, w, +, and U. A typo, or something I am unaware of? (PO)> (PO)> t translates "\r\n" to "\n" on windows. I think this is (PO)> superseded by "U" these days, which guarantees "\n" as newline (PO)> on windows, unix and mac alike. I thought that the conversion of newline/carriage return sequences was automatic as long as files are not read in under binary mode. Is that not the case? I still find no mention of t in the ref (http://python.org/doc/2.3.3/lib/built-in-funcs.html#l2h-25). Is it platform dependent, or am I looking at the wrong docref? > The randomization in findfortune() is interesting and would never > have occurred to me. The problem with it (as I see it - I could be > wrong) is that it results in a sub-pseudo random choice, as I can > easily imagine that entries towards the end of a large file will be > much less likely to be chosen due to the randomizer being applied > not to a set but to each element of the set, and because a positive > for any element means that none of the following elements are > considered for randomization, the result could well be that some > entries will effectively never be chosen. (PO)> (PO)> You are getting this wrong. I hoped to evade the explanation by (PO)> providing the reference, but now I'll give it a try. You can (PO)> prove the right outcome by induction, but I'll resort to "proof (PO)> by example" for now. Let's consider a small sample (PO)> (PO)> for index, item in enumerate(["a", "b", "c", "d"]): (PO)> if random() < (1.0/(index+1)): (PO)> chosen = item (PO)> (PO)> random() yields a floating point number 0 <= n < 1.0 (PO)> (PO)> Now let's unroll the loop: (PO)> (PO)> if random() <1.0/1 : chosen = "a" #index is 0, item is "a" (PO)> if random() <1.0/2 : chosen = "b" #index is 1, item is "b" (PO)> if random() <1.0/3 : chosen = "c" #index is 2, item is "c" (PO)> if random() <1.0/4 : chosen = "d" #index is 3, item is "d" (PO)> (PO)> The probability for the if branches to be executed is thus (PO)> decreasing: 1, 0.5, 0.33, 0.25. Now look at it backwards: The (PO)> chance that d is chosen is 0.25, the total probability for a, (PO)> b, or c is then 1-0.25 = 0.75. When we now look at the first (PO)> three lines only, we see immediately that the chance for c is (PO)> one third. 1/3 of 75 percent is again 0.25. The remaining (PO)> probability for a and b is then p(a or b) = 1 - p(c) - p(d) = (PO)> 0.5. Now look at the first two lines only to distribute the (PO)> total probability of 0.5 over a and b. Do you see the pattern? Yes, and I am sorry about that - I did not understand your example as well as I thought I did, and I totally missed the link you included - lucky I didn't delete that email. What you are saying is crystal-clear to me, but I need to really go over it to comprehend it fully. In any case, I see that the probabilities do not work out as I thought. > This is a very interesting solution in light of point (b), but of > course I will always know the size of the set as long as it comes > from a file. (PO)> (PO)> Again, you have to build a list of positions, with size (PO)> proportional to the file, I only keep the last fortune item, (PO)> essentially constant size. Point noted. I had missed it, obviously. > As for point (a), in the case that the last entry of a > file is chosen, wouldn't the whole file then have been in memory at > the same time, or do values returned by generators die right after > their use? (PO)> (PO)> That is up to the garbage collection; I'm working with the (PO)> assumption that unreachable data, i. e. previously read lines (PO)> are garbage-collected in a timely manner. So in theory, they die. I am a complete newb as regards generators (and many, many other things) - I am incapable of explaining them to those who do not know what they are. Now I am one step closer to being able to do so. (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)? - Jeremy adeleinandjeremy at yahoo.com __________________________________ Do you Yahoo!? Yahoo! Finance Tax Center - File online. File on time. http://taxes.yahoo.com/filing.html From shifflett at nps.navy.mil Fri Mar 19 13:58:12 2004 From: shifflett at nps.navy.mil (D. Shifflett) Date: 19 Mar 2004 10:58:12 -0800 Subject: Select on Win XP References: Message-ID: Josiah Carlson wrote in message news:... > [snip description] > > Hoepfully I am doing something wrong on the Win system. > > Any help would be appreciated. > [snip code] > > I checked the raw socket code on my machine and didn't have any issues. > You should check: > ... > def button_cb(button): > my_sock.sendto(data, (SERVERADDR, SERVERPORT)) > ... > with a print statement to make sure that is actually getting called. > > - Josiah Hi, Thanks for your response. Yep, I have checked that. I am running tcpdump, and can see the packet go out and the response come back. The python program also dumps the packet but only after two packets have been sent does select() return and I can read the first response packet. Any other ideas why select() is hanging? David Shifflett From trevp_spam at trevp.net Wed Mar 24 01:21:03 2004 From: trevp_spam at trevp.net (Trevor Perrin) Date: Wed, 24 Mar 2004 06:21:03 GMT Subject: SHA-based subclass for random module In-Reply-To: References: <7xptbgjpk4.fsf@ruckus.brouhaha.com> <47e891f1.0403221408.27fee114@posting.google.com> <7xk71c32mp.fsf@ruckus.brouhaha.com> <0gN7c.41346$zm5.32277@newssvr25.news.prodigy.com> <7x7jxc9r9c.fsf@ruckus.brouhaha.com> <5d83790c.0403230111.1a5137e8@posting.google.com> <5d83790c.0403230857.50e3bc73@posting.google.com> Message-ID: Josiah Carlson wrote: > >> This would be easy to implement with Mersenne Twister too. Though it >> would involve some rewriting. >> >> Do you think this is worthwhile? > > > I don't know, but I'm leaning towards not really. > > def getrandstring(self, n): > out = [struct.pack('>L', self.getrandbits(32)) \ > for i in xrange(0, n, 4)] > out.extend([chr(self.getrandbits(4)) for i in xrange(n%4)]) > return ''.join(out) > > You have your getrandstring for any class that provides getrandbits, and > is relatively optimized to deal with very long output strings. If the generator is something like /dev/urandom or Win32's CryptGenRandom, you don't want the repeated system call overhead of dipping into it 32 bits at a time. (I made the mistake of getting a byte at a time out of CryptGenRandom once, for a few hundred bytes of RSA padding, and it was a big performance hit). > def getrandbits(self, n): > out = 0 > for i in xrange(0, n+16, 16): > out = out << 16 + struct.unpack('>H', self.getrandstring(2)) > return out >> (16-(n%16)) > > Now you have getrandbits for any method that provides getrandstring, But you don't need getrandbits(). Let's distinguish between the API and the SPI (service provider interface). API is what users access, and the SPI is what new generators implement. I argue that getrandstring() makes more sense than getrandbits() in both the API and SPI. In the API, getrandstring() could be used for cryptographic keys, for example. In contrast, getrandbits() is not a useful API function, since the API already offers randint(). As for the SPI, currently there is random() and getrandbits(). These require every new generator to be able to produce floats and arbitrary-sized longs. Most generators are oriented towards producing strings of bits or bytes (M-T produces a sequence of 32-bit values, for example), so it would be easier for them to implement getrandstring() and let the base class handle conversion. > On a relatively unrelated note, I'm leaning toward trying to get the > benefits of both SHA and MT with the following, though I lack the heavy > mathematical background to prove whether it is better than either. I agree with Paul, there's no need to combine them. The only benefit of MT vs. a SHA-based generator is speed. Trevor From look at www.covingtoninnovations.com.for.address Thu Mar 25 17:27:28 2004 From: look at www.covingtoninnovations.com.for.address (Michael A. Covington) Date: Thu, 25 Mar 2004 17:27:28 -0500 Subject: IDLE won't launch, and other frustrations References: Message-ID: <6ZSdneDuMJpMwf7d4p2dnA@speedfactory.net> "David MacQuigg" wrote in message news:vho3609it1bc3nnqui3e5ii8e3kupgl0c2 at 4ax.com... > On Wed, 24 Mar 2004 09:57:35 -0500, "Michael A. Covington" > wrote: > > >WN16 is WordNet 1.6, from Princeton University, basically a huge synonym > >dictionary of English. They are up to version 2.0 now and it's much better > >behaved. The open-source community is _finally_ learning something about > >how Windows works. For a while there, inept Windows configuration seemed to > >be a point of pride with some kinds of free software tools! > > I believe the problem lies with Microsoft for obfuscating the > installation process. As good as they have done with usability for > the typical office user, they seem to have a deliberate strategy of > making things more complex than they need to be at the system level. > The registry is a prime example. Another is the monolithic > integration of the desktop with the OS. There are many such examples. > It's all part of the Lock In Strategy of software development. I think the real problem here is simply that WordNet 1.6 was *old*. It smacked of Windows 3, which has much less orderly installation methods than we have nowadays. From ashot at REMOVETHISmolsoft.com Tue Mar 2 04:47:09 2004 From: ashot at REMOVETHISmolsoft.com (Ashot) Date: Tue, 02 Mar 2004 03:47:09 -0600 Subject: vim & python References: <221dd125.0403011151.504ce09d@posting.google.com> Message-ID: On 1 Mar 2004 17:48:17 -0800, poiboy wrote: > Look at taglist.vim (links below), a popular souce-browsing Vim > script. It's the only major script I'm using right now. I don't know > of any definitive Python calltips available for Vim (I assume they > would be difficult with flexible parameters and return values), but > taglist.vim provides function prototypes in the form of parameter > lists (search for 'prototype' in the taglist docs). > > I've tried a few nifty Python-specific scripts (search www.vim.org) > but always wound up forgetting the special commands and resorting to > Vim staples. For example, the following two lines in my .vimrc were > good enough to condense all the functions and classes in a file: > > set foldmethod=indent > set foldnestmax=2 > > My .vimrc also includes this "execute code and output results in new > buffer" script (which should all be on one line): > > map :w:let @a = system('`which python` ' . > bufname('%')):silent botright new output:silent normal "aP > > Normally I use GVim next to a terminal window tabbed with IPython > (ipython.scipy.org/) and a browser tabbed with whatever documentation > I may need - Python docs, RFCs, and project docs > (epydoc.sourceforge.net/). IPython helps access the nitty-gritty > aspects of Python, Epydoc allows me to browse documentation and > package structures elegantly. And though I am by no means a Python > guru, I've posted a screenshot of my "modular IDE" in action (link > below). > > I went through a do-it-all-in-Vim stage and left feeling as though I > had just spent too much time playing with my tool. Keeping a browser > and terminal open all the time anyway, I eventually dismissed the > all-in-one paradigm as some quixotic jab at Emacs. > > Happy vimmings, > poiboy > > taglist.vim > http://www.vim.org/scripts/script.php?script_id=273 > > exuberant ctags > http://ctags.sourceforge.net/ > > screenshot > http://aonalu.makahavalley.org/img/gvim_konq_ipython.png (197K, > 1600x1200) > Check out the function prototype on the bottom of GVim's window. very nice. -- Ashot Petrosian University of Texas at Austin, Computer Science From gh at ghaering.de Wed Mar 3 03:39:02 2004 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Wed, 03 Mar 2004 09:39:02 +0100 Subject: Which Python module for PostgreSQL? In-Reply-To: <30260531.0403022111.1a2928b7@posting.google.com> References: <30260531.0403022111.1a2928b7@posting.google.com> Message-ID: <404599A6.3050206@ghaering.de> simo wrote: > I'd like to know too - I had a play with psychog but couldn't get it > to connect, and couldn't find any documentation for it. > > I don't have a huge amount of PostgreSQL knowledge (more of a MySQL > person myself) so I could have it setup wrong, but I couldn't figure > anything out as the error message was useless (something about IDENT > user). It's a PostgreSQL question, really. It sounds like the user account you're trying to connect to the database from doesn't have the necessary permissions. I can hardly imagine that a copy-and-paste strategy of the exact error message into Google wouldn't have led you further ;-) -- Gerhard From jcarlson at nospam.uci.edu Fri Mar 5 02:27:26 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Thu, 04 Mar 2004 23:27:26 -0800 Subject: Some language proposals. In-Reply-To: References: Message-ID: [snip classes not behaving like class instances] I see. You are not happy with the fact that instances of some other class, with a __call__ method are not considered a bound instance method. I'm sure you have thought of it, but I would wrap it. It may take another function call, but really, what other functionality do you need that the below does not provide? Give the below a shot. - Josiah class callee: def __call__(s, self, *args): print self def instance(self, *args): print self def wrapper(self, *args): print self self._c(self, *args) class caller: pass caller.instance_method = instance caller.instance_method2 = wrapper foo = caller() caller._c = callee() foo.instance_method() foo.instance_method2() foo.instance_method foo.instance_method2 From tjreedy at udel.edu Wed Mar 17 11:33:18 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 17 Mar 2004 11:33:18 -0500 Subject: Semantics of == References: <40200384.0403161538.7407d9e2@posting.google.com><4057A2A0.CC63C070@alcyone.com> <40200384.0403170657.5c81a456@posting.google.com> Message-ID: "Axel Boldt" wrote in message news:40200384.0403170657.5c81a456 at posting.google.com... > That definition doesn't seem to fully specify equality of list values: > to determine whether s==w, I first note that they both have length 2 > and both have 1 as their first element, the second element of s is a > pointer to s, the second element of w is a two-element list, with > first element 1 and second element a pointer to w. So now I have to > determine whether s is equal to the two element list with first > element 1 and second element a pointer to w. They both have two > elements, they both share the first element 1, the second element of s > is a pointer to s, the second element of the other list is a pointer > to w. Now I'm back where I started: I have to test whether s==w. So > the definition in the language reference is circular and both > conclusions s==w and s!=w are consistent with it. I hope that the > actual result received, i.e. s==w, is not implementation dependent? You could try old versions if you have access back far enough ;-). I vaguely remember a discussion on PyDev list, some years ago, of 'equality' of infinite recursive structures. I believe there was a change in the direction of simplicity and robustness to the current algorithm from a more ambitious algorithm that might have detected s != w -- but which sometimes had problems. For dicts at least, a finite printout (instead of infinite looping requiring a keyboard interrupt) is an innovation since 1.4. Terry J. Reedy From Spam at ivonet.nl Sat Mar 13 03:47:59 2004 From: Spam at ivonet.nl (Ivo) Date: Sat, 13 Mar 2004 09:47:59 +0100 Subject: typecasting: a string object to a dictionary object References: Message-ID: <4052cab0$0$15636$3a628fcd@reader1.nntp.hccnet.nl> Here are some examples of how to sort a dictionary. Now If you first want to convert a string to a dictionary and after sorting back to a string, why do the converting. A dictionary is of the Mapping Types, which are by default unsorted. To sort a dictionary is unnatural behavior for Python. Much easier to sort a tuple or list. if you convert your string to a list or tupple you can just use mystr.sort() and you are done. If you intend to use the dictionary as a dictionary it's ok but otherwise don't do it. # the simplest approach: def sortedDictValues1(adict): items = adict.items() items.sort() return [value for key, value in items] # an alternative implementation, which # happens to run a bit faster for large # dictionaries on my machine: def sortedDictValues2(adict): keys = adict.keys() keys.sort() return [dict[key] for key in keys] # a further slight speed-up on my box # is to map a bound-method: def sortedDictValues3(adict): keys = adict.keys() keys.sort() return map(adict.get, keys) def sort_by_value(d): """ Returns the keys of dictionary d sorted by their values """ items=d.items() backitems=[ [v[1],v[0]] for v in items] backitems.sort() backitems.reverse() return [ backitems[i][1] for i in range(0,len(backitems))] -- Cherez, Ivo. http://IvoNet.nl "Life is like a nose.. You have to get out of it what's in it!" "dont bother" wrote in message news:mailman.344.1079154269.19534.python-list at python.org... > Hi, > Thanks! Just one more favour. > I want to sort the entries on this new dictionary. > (Increasing order) and convert it back to a string > where each values are not separated by , but by space. > > ie. for example: I have a string s of the form > index: value, index: value, index: value > > I converted it to a dictionary by the method you > suggested. I want to sort the entries now, with > increasing order of index. > > Once I have the sorted dictionary, I want to convert > it back to a string of the form > > 1 index:value index:value index:value > > > Note, that 1 is added because I am creating feature > vectors of the type "spam". index: value pairs are now > separated by space instead of comma and finally I want > to write this to a file. > > The whole notion of making a string to a dictionary > was because of sorting. > > Can you extend this piece of code for the above > objective. I will indeed be very grateful to you. > > > import string > > # define a test string > s1 = "" > # get rid of the < and > by taking a slice > s1 = s1[1:-1] > # split string at the commas > s2 = string.split(s1,',') > mydict = {} > for item in s2: > a,b = string.split(item,":") > mydict[a] = b > print mydict[a] > print "Dictionary is: ", mydict > > > > > > > > > > Thanks > Dont > > > --- midtoad wrote: > > dont bother wrote: > > > > > I have a string: > > > > > > feature_vector. It is of the form > > > > > > > > > I want to make this string into a dictionary so > > that I > > > can apply .keys() method > > > > okay, here's a solution, assuming that your < and > > > are part of the string. > > If not, remove the line where you take a slice. > > I'm sure that there are > > more Pythonic solutions, but this works... > > > > --- > > import string > > > > # define a test string > > s1 = "" > > # get rid of the < and > by taking a slice > > s1 = s1[1:-1] > > # split string at the commas > > s2 = string.split(s1,',') > > mydict = {} > > for item in s2: > > a,b = string.split(item,":") > > mydict[a] = b > > print mydict[a] > > print "Dictionary is: ", mydict > > --- > > > > cheers > > Stewart > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > __________________________________ > Do you Yahoo!? > Yahoo! Mail - More reliable, more storage, less spam > http://mail.yahoo.com > From faheem at email.unc.edu Mon Mar 15 12:21:41 2004 From: faheem at email.unc.edu (Faheem Mitha) Date: Mon, 15 Mar 2004 17:21:41 GMT Subject: creating array of python objects References: Message-ID: On Sun, 14 Mar 2004 13:37:36 -0600, Jeff Epler wrote: > I don't believe that numarray supports arrays of Python objects. > The list of Numarray types doesn't list them: > http://stsdas.stsci.edu/numarray/numarray-0.9.html/node21.html#tab:type-specifiers > > This is the meaning of the "not a numeric type" message. > > Using numpy, you can create an array of PyObjects where each entry is a > reference to the same cell object: > >>> class cell: > ... def setrow(self,row): > ... self.row = row > ... def setcol(self,col): > ... self.col = col > ... > >>> empcell = cell() > >>> a = Numeric.reshape([empcell]*4, (2,2)) > >>> a[0][0].setrow(10) > >>> a[1][1].row # because they are the same object > 10 Is a[0,0] equivalent to a[0][0]? It is a slightly more compact representation. > If you want distinct objects, you'll have to use > >>> a = Numeric.reshape([cell() for i in range(4)], (2,2)) Thanks. Faheem. From bogus at bogus.net Wed Mar 10 20:29:54 2004 From: bogus at bogus.net (Paul McGuire) Date: Thu, 11 Mar 2004 01:29:54 GMT Subject: Tips on calling Matlab from Python Message-ID: I've spent the past day or so working through the various complexities in calling Matlab routines from Python (please do not reply with suggestions to use Numpy/Scipy/etc. - our customer is using Matlab, and I needed to learn how to access it through COM). Matlab's COM API is actually pretty clean/simple, but there are a few wrinkles, some undocumented "magic strings", and some odd surprises. Also, the Matlab COM API was designed for lesser languages that do not have built-in support for complex data. So I captured my usage notes, a simple wrapper class, and some test code, to simplify this task. You can find my notes at http://www.geocities.com/ptmcg/python/using_matlab_from_python.html. HTH, -- Paul McGuire From tundra at tundraware.com Fri Mar 5 05:00:16 2004 From: tundra at tundraware.com (Tim Daneliuk) Date: 05 Mar 2004 05:00:16 EST Subject: OFF-TOPIC:: Why Lisp is not my favorite programming language In-Reply-To: References: <165b3efa.0403030443.4d591f04@posting.google.com> <40460dd5$0$5916$7a628cd7@news.club-internet.fr> Message-ID: Mike Nishizawa wrote: > 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. > http://www.tundraware.com/Technology/How-To-Pick-A-Programming-Language/ ---------------------------------------------------------------------------- Tim Daneliuk tundra at tundraware.com PGP Key: http://www.tundraware.com/PGP/ From jepler at unpythonic.net Sun Mar 21 16:12:04 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Sun, 21 Mar 2004 15:12:04 -0600 Subject: Invalid character in os.system call... In-Reply-To: <00ef01c40ea0$c9104760$0600a8c0@Hugh> References: <00ef01c40ea0$c9104760$0600a8c0@Hugh> Message-ID: <20040321211203.GA2797@unpythonic.net> Python's os.system() is a wrapper around the C library's system() call. If you read ANSI C, you'll learn that basically nothing about system() is specified. In the real world, Unix passes the argument to system() to sh -c, like so: def system(command): return os.spawnv(os.P_WAIT, "/bin/sh", ["sh", "-c", command]) so refer to "man sh" to learn more about how the command is interpreted, or use os.spawnv or os.execv to directly control the list of arguments in the subprogram. Personally, I recommend using spawnv or execv over using system. Jeff From skip at pobox.com Wed Mar 17 10:36:24 2004 From: skip at pobox.com (Skip Montanaro) Date: Wed, 17 Mar 2004 09:36:24 -0600 Subject: Perceived optparse shortcomings In-Reply-To: References: <6e990e29.0403162320.584328ea@posting.google.com> Message-ID: <16472.28792.900813.442017@montanaro.dyndns.org> >> Heather> How about having your plugins "register" with your main program Heather> *before* you call optparse? .... Heather> I've not used optparse, but I've used that scheme with getopt. I was thinking that with getopt I would call it once to process the generic options. That would leave the args as the list equivalent of The main program plucks from that list and then passes the remaining args to the appropriate subcommand, which calls getopt again with the list equivalent of I don't know if that's possible with optparse, but if so, that's the route I'd try first. Skip From rajorshi at fastmail.fm Mon Mar 1 05:24:11 2004 From: rajorshi at fastmail.fm (Rajorshi) Date: 1 Mar 2004 02:24:11 -0800 Subject: Determining the encoding of a text file Message-ID: <85b5e3f8.0403010224.939e8f8@posting.google.com> Hello! How do I determine the encoding of a text file ? That is, given a text file I want to know the encoding it is in UTF8 or UTF16 or Latin etc. It would be very helpful if you could tell me how to do this in python on Linux. But just the method is acceptable. Thanks in advance! From frr149 at telefonica.net Thu Mar 4 10:23:52 2004 From: frr149 at telefonica.net (Boogie El Aceitoso) Date: Thu, 04 Mar 2004 16:23:52 +0100 Subject: How to catch a generic exception? Message-ID: Hi, How can I catch a generic exception (without knowing a priori what exception it will be)? For example, something like this try: generateSomeException() except e: print e From tismer at stackless.com Sat Mar 6 22:48:59 2004 From: tismer at stackless.com (Christian Tismer) Date: Sun, 07 Mar 2004 04:48:59 +0100 Subject: ready to use python, need help with GUI decision In-Reply-To: <6Fu2c.2306$G3.18772@localhost> References: <20040303181544.GB74292@dogma.freebsd-uk.eu.org> <4046EE84.9080700@rebirthing.co.nz> <6Fu2c.2306$G3.18772@localhost> Message-ID: <404A9BAB.7030503@stackless.com> Peter Hansen wrote: > Ed Cogburn wrote: > >> David McNab wrote: >> >>> My personal favourite is Tkinter, with the 'steroids' that go by the >>> name of PMW. >> >> >> Have you also tried wxPython? I'm not advocating, just want to know >> if you've also tried "the other one". :) What does PMW do for >> Tkinter? I've seen opinions suggesting wxPython was "better" than >> (standard) Tkinter, but I've never seen PMW mentioned before when >> comparing the two. If you've used wxPython previously, how does >> Tkinter+PMW compare to it? Anyone? > > > I've used both, and didn't find PMW any more compelling than I found > Tkinter alone. I still find that wxPython fits my brain better and > gives me better results. This, however, is an area where individual > mileage definitely varies, based on past reports here that strongly > support either the one or the other approach depending on who's writing. If I may add to this: I have been using wxPython for 1.5 years, now. And I'm not completely happy, I'm just pleased. I heared that QT is smaller and more capable, should also be more elegant. Can't really judge it. The problem with QT is that it is not free for commercial products under Windows. wxPython has some subtle hurdles which can cost you days of research, annoying when you are used to the ease of Delphi for GUI development. For instance, I wanted to grab keyboard events on a wxStaticBitmap object and almost didn't get any. After a longer search, I found a note that this only works if you switch of tab processing for the enclosing wxFrame objects. For me as (in this case :) the application programmer, this is just bad, and almost unsolveable without the help of the mailing list. I also doubt that this behavior necessarily has to be implemented in this rigorous way. There is also a serious strugle with flicker. Meanwhile, I solved all these issues for me, but again, this took days and weeks of research. With Delphi, I never had this problem. Now I *have* smooth, flicker free display of little movies with wxPython, but I had to do all the drawing by myself, had to remove all implicit calls to erase the background, and it is a huge code cruft. Anyway, it works very fine. So I can't recommend wxPython wholeheartedly, it has cost me much more efforts than I wanted to invest. On the other hand, it is free, and it does it's job, in the end. As a positive add-on, there is Boa Constructor, which I happily use to create my wxPython stuff. It is still young, very ambitious but not really ready, but I like it very much. I will look into PyGame, which does not have a GUI at all, but seems to be quite simple and platform-independant, and I'm thinking to write my own GUI layer on top of it. This would of course be Stackless Python centered from the ground. I'm not sure if it will happen in this life, but I'm thinking positive. Until then, I will continue to cope with wxPython. I don't say it is perfect, but I do say it can be what you want. cheers -- 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 vxg49 at yahoo.com Tue Mar 2 11:47:09 2004 From: vxg49 at yahoo.com (Fred Murray) Date: 2 Mar 2004 08:47:09 -0800 Subject: Odd cgi.FieldStorage behavior Message-ID: Hi all, When uploading a file ("input type=file"), FieldStorage usually behaves correctly, but every once in a while (every couple days?), it will suddenly start causing internal server errors. A look at the apache (v. 2.0.44 on Linux) error log shows "premature end of script headers" with no error messages from Python. After reloading the browser about 10 times in a row, it will suddenly start working again. Recently, when a series of these errors was occuring, I removed the FieldStorage line from my program and it completed normally. When I put the line back in again, the internal server errors resumed. Thus, it seems that the bug is either in FieldStorage itself or in something FieldStorage interacts with. It seems odd that that there are no errors in the log from Python. Does this mean the program is crashing before it can output a traceback to stderr? Cheers, Fred From mjackson at alumni.caltech.edu Mon Mar 22 09:55:12 2004 From: mjackson at alumni.caltech.edu (Mark Jackson) Date: 22 Mar 2004 14:55:12 GMT Subject: [OT] Compilable Python-like language? References: <405ed061$0$10776$afc38c87@news.easynet.co.uk> <8351bb33.0403220632.5becbc0c@posting.google.com> <405efb39$0$28151$afc38c87@news.easynet.co.uk> Message-ID: Peter Hansen writes: > Peter Hickman wrote: > > > Jon Nicoll wrote: > > > >> Peter Hickman wrote: > >>> The UK English phrase would be to "put on kid gloves" kid gloves > >>> being very soft and gentle type of leather (supposedly made from > >>> juveniles). > >> > >> er, I think 'supposedly made from [the skin of] juvenile _goats_ ...' > >> > >> Regards > >> Jon N > > > > As they say, God is in the details. > > God is a young goat?! Yes. Of course, as they also say, the Devil is in the details. So if a young goat claims to be God, be careful - he might be kidding. -- Mark Jackson - http://www.alumni.caltech.edu/~mjackson The supreme misfortune is when theory outstrips performance. - Leonardo da Vinci From light at soton.ac.uk Thu Mar 25 04:34:38 2004 From: light at soton.ac.uk (Mark Light) Date: Thu, 25 Mar 2004 09:34:38 +0000 (UTC) Subject: simple py2exe import os error Message-ID: Hi, I am trying to use py2exe on a simple python program and get the error below. Any ideas? It runs fine on my laptop at home but not on my desktop at work - I think they are setup the same - but I guess there must be some subtle difference. ##standard output C:\Python_Mark\datamatetest>python setup.py py2exe C:\Python23\Lib\os.py:282: Warning: 'yield' will become a reserved keyword in th e future 'import site' failed; use -v for traceback C:\Python23\Lib\os.py:282: Warning: 'yield' will become a reserved keyword in th e future Traceback (most recent call last): File "setup.py", line 1, in ? from distutils.core import setup File "C:\Python23\Lib\distutils\core.py", line 13, in ? import sys, os File "C:\Python23\Lib\os.py", line 282 yield top, dirs, nondirs ^ SyntaxError: invalid syntax C:\Python_Mark\datamatetest> ##input setyp file C:\Python_Mark\datamatetest>more setup.py from distutils.core import setup import py2exe, os print os.getcwd() setup(name="DataMate", version="2.0", description="DownLoad Kappa CCD Data", author="Mark E Light", author_email="light at soton.ac.uk", scripts=["DataMate.pyw"], data_files=[(os.getcwd(), ["DataMate.ini"]), (os.getcwd(), ["DataMateSav.i ni"])], ) #python setup.py py2exe From fowlertrainer at anonym.hu Mon Mar 1 07:25:38 2004 From: fowlertrainer at anonym.hu (fowlertrainer at anonym.hu) Date: Mon, 1 Mar 2004 13:25:38 +0100 Subject: KinterBasDB problems in Linux In-Reply-To: References: Message-ID: <16617410454.20040301132538@anonym.hu> Hello Uwe, So: in Debian Sarge, some interesting thing happened. When I start python with: /usr/bin/python it is starting the py2.3 When I write this: import kinterbasdb the py2.3 is not say this: "import _kinterbasdb as _k" "ImportError: No module named _kinterbasdb" only do the import. So it is working. BUT ! If I write this line to a script: #!/usr/bin/python import kinterbasdb this error I get: "import _kinterbasdb as _k" "ImportError: No module named _kinterbasdb" Why ? What I do wrong ?????? Anybody know it ? Monday, March 1, 2004, 12:15:04 PM, you wrote: UG> I don't have any proplems with cross-platform issues. UG> Working on Win2000 + suse linux 8.2, 9.0 and FB 1.5, UG> kinterbasdb from http://sourceforge.net/projects/kinterbasdb/ I try with apt-get install "kidb", and do same things. UG> Try this version! UG> Uwe UG> fowlertrainer at anonym.hu wrote: >> Hello ! >> >> I have a problem. >> I create my projects in Windows, and I write a database synchronizing >> utility for copy a gdb changes to another gdb. Some of these products >> is need to run in linux. >> >> I'm very tired, because I download (apt-get install >> python2.3-kinterbasedb) the module, what working good in Windows, but >> in linux I get this message when I try to start my script: >> >> bha:/kepes# ./syncmdb2teldb.py >> Traceback (most recent call last): >> File "./syncmdb2teldb.py", line 2, in ? >> import kinterbasdb >> File "/home/fixshare/kepes/kinterbasdb/__init__.py", line 41, in ? >> import _kinterbasdb as _k >> ImportError: No module named _kinterbasdb >> bha:/kepes# >> >> >> The test file is: >> File: syncmdb2teldb.py Col 0 321 bytes 100% >> #!/usr/bin/python >> import kinterbasdb >> >> import sys >> # Base datas >> >> srcdb=kinterbasdb.connect(dsn='192.168.1.17:/mpanni/bha/database/teldata.gdb',us >> er='sysdba',password='m',charset="win1250") >> desdb=kinterbasdb.connect(dsn='192.168.1.17:/mpanni/bha/database/mpanni.gdb',use >> r='sysdba',password='m',charset="win1250") >> print "ok" >> >> 1Help 2UnWrap 3Quit 4Hex 5Line 6RxSrch 7Search 8Raw 9Unform 10Quit >> >> In the package dir: >> >> bha:/usr/lib/python2.3/site-packages/kinterbasdb# ls -l >> total 152 >> -rw-r--r-- 1 root root 29691 Jul 19 2002 __init__.py >> -rw-r--r-- 1 root root 32036 Feb 27 17:44 __init__.pyc >> -rw-r--r-- 1 root root 32036 Feb 27 17:44 __init__.pyo >> -rw-r--r-- 1 root root 56072 Sep 28 16:32 _kinterbasdb.so >> bha:/usr/lib/python2.3/site-packages/kinterbasdb# >> >> >> What I do wrong, or what is it ???? >> (The Zope with Kinterbasdb is working good in this linux, so no >> connection problem...) >> >> thanx for every help ! >> -- Best regards, fowlertrainer mailto:fowlertrainer at anonym.hu From sross at connectmail.carleton.ca Sat Mar 6 11:45:32 2004 From: sross at connectmail.carleton.ca (Sean Ross) Date: Sat, 6 Mar 2004 11:45:32 -0500 Subject: Introspection at the module level? References: Message-ID: "Roy Smith" wrote in message news:roy-AEE793.11085806032004 at reader2.panix.com... > I've got a module that defines a bunch of constants: > > OP_FOO = 1 > OP_BAR = 2 > OP_BAZ = 37 > > and so on. The values are all unique. I want to build, at module > import time, a reverse map of these constants, i.e. I want to end up > with: > > {1: "OP_FOO", 2: "OP_BAR", 37: "OP_BAZ"} > I'm not sure how to do this "at module import time", but if you just want to build a reverse dictionary of globals variables that start with "OP_", you can try this: rd = dict([(v,k) for k,v in globals().copy().iteritems() if k.startswith("OP_")]) >Not to mention that I don't > see how to get a handle to the module from inside the module, i.e. > there's no "self". http://groups.google.ca/groups?hl=en&lr=&ie=UTF-8&oe=UTF-8&safe=off&selm=giGhb.262770%24R32.8518969%40news2.tin.it&rnum=6 From oussoren at cistron.nl Mon Mar 22 04:32:40 2004 From: oussoren at cistron.nl (Ronald Oussoren) Date: Mon, 22 Mar 2004 10:32:40 +0100 Subject: Python bytecode compatibility between interpreter versions In-Reply-To: <8ei2j1-69c.ln1@home.rogerbinns.com> References: <0qudndSnJMpWbsfdRVn-uA@powergate.ca> <7okui1-3no.ln1@home.rogerbinns.com> <8ei2j1-69c.ln1@home.rogerbinns.com> Message-ID: >> In practice though, there is really just one implementation of Python >> (with the standard libraries... excluding Jython) That's *two* implementations of Python: CPython and Jython, one of which uses pyc files. You're conveniently ignoring the primary example of a Python interpreter that does not use pyc files. >> which works using the >> same bytecode mechanism on _all_ platforms, so as far as I can tell, >> it would be quite feasible to distribute applications in .pyc form. Yes it is feasible to distribute apps in .pyc form, as long as you target a specific version of Python. Ronald From jepler at unpythonic.net Wed Mar 17 20:32:16 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 17 Mar 2004 19:32:16 -0600 Subject: Help on Tkinter installation In-Reply-To: <105hpt53kagaj67@corp.supernews.com> References: <105hpt53kagaj67@corp.supernews.com> Message-ID: <20040318013216.GB12550@unpythonic.net> On Thu, Mar 18, 2004 at 12:04:53AM -0000, Cameron Laird wrote: > I'm curious about how you decided to start with the program you've > exhibited above. I think he's using this module: http://mcsp.wartburg.edu/zelle/python/graphics.py it looks like a canvas-based thing, and the example would probably have worked if Tkinter was installed properly on the system. Jeff From anthony at interlink.com.au Wed Mar 3 07:40:57 2004 From: anthony at interlink.com.au (Anthony Baxter) Date: Wed, 03 Mar 2004 23:40:57 +1100 Subject: capturing audio In-Reply-To: <001b01c40113$1f45efe0$b10d10ac@metasalio> References: <001b01c40113$1f45efe0$b10d10ac@metasalio> Message-ID: <4045D259.9060205@interlink.com.au> Herman Geldenhuys wrote: > has anybody tried to capture sound or audio from within python on windows? > i'm looking for an api for the lame encoder, but no luck. Look at the fastaudio wrapper for portaudio. Shtoom uses this on windows, works fine. From jcarlson at uci.edu Tue Mar 30 15:13:46 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Tue, 30 Mar 2004 12:13:46 -0800 Subject: Breakdown of approaches to PEP318 In-Reply-To: References: <7vD9c.318$1A6.114130@news20.bellglobal.com> Message-ID: > def foo(self): > this_method. spark_rule = "DOC:=HEAD BODY FOOT" > this_method.url="/cgi-bin/directory/directory" > this_method = publish_to_web(this_method) > " doc string " > very > long > body God no. - Josiah From OlafMeding at compuserve.com Thu Mar 11 10:53:18 2004 From: OlafMeding at compuserve.com (Olaf Meding) Date: 11 Mar 2004 07:53:18 -0800 Subject: backquote Message-ID: <9e5ea2c4.0403110753.5c4d437a@posting.google.com> Is `object` (using backquotes) the same as saying str(object)? Trying to understand how backquotes work. Thanks for your help. Olaf From pje at telecommunity.com Tue Mar 23 13:00:11 2004 From: pje at telecommunity.com (Phillip J. Eby) Date: 23 Mar 2004 10:00:11 -0800 Subject: import, functions, and threading References: Message-ID: <25b5433d.0403231000.4003f7fa@posting.google.com> aahz at pythoncraft.com (Aahz) wrote in message news:... > There were some posts recently discussing whether it's poor style to put > import statements inside functions. I recently got reminded that there's > one very good reason to avoid it: Python has an import lock that blocks > more than one thread from executing import statements. Putting import > statements inside functions that might be called in a threaded > environment is asking for deadlock trouble. If I understand this correctly, a deadlock could only occur if a lock was being acquired by module-level code in a newly imported module, after another thread acuired that lock, and then blocked waiting for the import lock. So, all this means is that you shouldn't acquire locks in module-level code, because if you do, you can run afoul of this problem entirely independent of whether you do any importing in functions! So, treating this as an issue with importing inside functions seems like a red herring. The import lock can only be a source of deadlocks for module-level code, and the issue applies to *any* import statement. From dmq at gain.com Wed Mar 24 14:53:30 2004 From: dmq at gain.com (David MacQuigg) Date: Wed, 24 Mar 2004 12:53:30 -0700 Subject: IDLE won't launch, and other frustrations References: Message-ID: On Wed, 24 Mar 2004 09:57:35 -0500, "Michael A. Covington" wrote: >WN16 is WordNet 1.6, from Princeton University, basically a huge synonym >dictionary of English. They are up to version 2.0 now and it's much better >behaved. The open-source community is _finally_ learning something about >how Windows works. For a while there, inept Windows configuration seemed to >be a point of pride with some kinds of free software tools! I believe the problem lies with Microsoft for obfuscating the installation process. As good as they have done with usability for the typical office user, they seem to have a deliberate strategy of making things more complex than they need to be at the system level. The registry is a prime example. Another is the monolithic integration of the desktop with the OS. There are many such examples. It's all part of the Lock In Strategy of software development. Open-source developers are often not as expert in Windows installations as a typical commercial developer targeting the Windows platform. We cannot blame them for falling into a few Microsoft traps. It's not like they don't *want* their programs to run on Windows, or that they are "proud" of the problems they cause for Windows users. A few may a have a "don't care" attitude, but most just don't realize that when they set a variable in AUTOEXEC.BAT, it can mess up another program like IDLE. Given the reality that other programs will be making blunders in their installations, we should still be able to detect a bad setup for IDLE and at least warn the user -- "Some other program has set the default TCL/TK library to version 8.2. IDLE cannot be installed unless you remove the variable TCLxxxNNN from the current environment. -- Dave From peter at semantico.com Mon Mar 15 10:26:58 2004 From: peter at semantico.com (Peter Hickman) Date: Mon, 15 Mar 2004 15:26:58 +0000 Subject: Static Typing in Python In-Reply-To: References: <4055a71e$0$28265$afc38c87@news.easynet.co.uk> Message-ID: <4055cb43$0$7558$afc38c87@news.easynet.co.uk> Jacek Generowicz wrote: > Peter Hickman writes: >>Premshree Pillai wrote: >>>Like in C, C++, etc, Python too is >>>strongly typed, i.e., variables are necessarily bound >>>to a particular type. [deletia] > Secondly, you appear to be confusing C and C++ with strongly typed > languages. A common mistake :-) No I was just taking Premshree's lead where he says 'Like in C, C++, etc, Python too is strongly typed' > Python is strongly typed because: > > - lots of type checking is done > - few implicit type conversions are done. > - No operations which are inappropriate to the object(s) in question > are allowed. Perhaps you should read the following where Guido van Rossum talks about typing in Python. Here he is contrasting strongly typed languages with Python. "In a strongly typed language, when you change to a different data structure, you will likely have to change the argument and return types of many methods that just pass these things on. You may also have to change the number of arguments, because suddenly you pass the information as two or three parts instead of one. In Python, if you change the type of something, most likely pieces of code that only pass that something around and don't use it directly don't have to change at all." It would seem to be clear that what Guido considers to be strong typing is not a feature of Python. As the following quote seems to indicate. "Weak typing is not really a fair description of what's going on in Python. It's really runtime typing because every object is labeled with a type." Here's the link http://www.artima.com/intv/strongweakP.html I would recommend reading www.artima.com to anyone interested in programming. So there we have it, Python is *NOT* strongly typed unless you know more about Python than Guido van Rossum. 1-0 From crap1234 at hotmail.com Tue Mar 30 06:52:06 2004 From: crap1234 at hotmail.com (Stefan Axelsson) Date: Tue, 30 Mar 2004 13:52:06 +0200 Subject: Orders of magnitude In-Reply-To: <66a61715.0403291539.7e1346c7@posting.google.com> References: <66a61715.0403291539.7e1346c7@posting.google.com> Message-ID: Buck Nuggets wrote: > step 1: sort the file using a separate sort utility (unix sort, cygwin > sort, etc) > > step 2: have a python program read in rows, > compare each row to the prior, > write out only one row for each set It might be worth mentioning that if your idea of 'sameness' is identical textual representation, the '-u' flag of 'sort' does step 2 for you. Won't work in the more general case, but then 'sort' might not work either. YMMV. Stefan, -- Stefan Axelsson (email at http://www.cs.chalmers.se/~sax) From claird at lairds.com Sat Mar 27 10:43:31 2004 From: claird at lairds.com (Cameron Laird) Date: Sat, 27 Mar 2004 15:43:31 -0000 Subject: Tangent on embeddability (was: Choosing Perl/Python for my particular niche) References: <40652B0D.7C313F77@doe.carleton.ca> <40657D14.3FBE7E82@doe.carleton.ca> Message-ID: <106b893s0sfut11@corp.supernews.com> In article , Roy Smith wrote: . . . >2) It's dead simple to embed in a C/C++ application. This is one place >where it really outshines Python. It's literally two lines of C to get >a Tcl interpreter up and running. It's equally trivial to extend Tcl by >providing functions in C. Compare this to the native Python/C >interface, boost.python, or swig, and you really appreciate the >difference! > >For most general purpose tasks, I reach for Python first. But if I >needed to provide a quick scripting interface to an existing C library, >or wanted to embed some easy scriptability into a large C/C++ app, Tcl >is what I would be looking at. Me, too, to a large extent. I think you overstate Tcl's advantage, though, Roy, in a couple of ways. First, I agree that Tcl is objectively easier and more reliable in embedding; Python still has blemishes in ease-of-use and portability in this role. It can be hard getting all of Python embedded correctly, especially, in my ex- perience, when working on multiple platforms. However, Tcl has historically been so easy that it hasn't bothered documenting the process. Python has a definitive (if aging) embedding manual that I regard as more inviting than what Tcl offers. Also, ctypes, Boost and Pyrex *are* successful, and appear to me progressing faster than any of their Tcl cousins. Yet another way to look at the comparison is that a sig- nificant number of people rely on SWIG, and, to them, Tcl and Python are indistinguishable. Follow-ups narrowed. Most of Perl's response to all of this is, "Wait 'til 6!" -- Cameron Laird Business: http://www.Phaseit.net From jjl at pobox.com Mon Mar 29 12:46:47 2004 From: jjl at pobox.com (John J. Lee) Date: 29 Mar 2004 18:46:47 +0100 Subject: No built-in swap function? References: Message-ID: "Andrew Koenig" writes: > I am looking for the most effective way t