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 to exchange v[i] and v[j], and > expected to find something like > > v.swap(i, j) > > but it doesn't seem to exist. Is there anything better than > > v[i], v[j] = v[j], v[i] > > (which I don't like particularly because it evaluates each of v[i] and v[j] > twice)? I don't think so. It seems an odd question in one way: Saying that it evaluates v[i] and v[j] twice may be true, but ignores the fact that v[a] is quite different from v[a] = b -- one does a lookup (whether it be a dict lookup, list indexing operation, or whatever), and the other is an assignment (whether setting a dict key/val pair, setting a list item, etc). I admit I don't like the repetition of v[i] and v[j], though of course that can be solved by writing a function. I suppose a function is best here, not a method, because you might want to apply it to any sequence. I-am-not-a-language-lawyer-ly y'rs, John From newsgroups at jhrothjr.com Thu Mar 11 16:43:14 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Thu, 11 Mar 2004 16:43:14 -0500 Subject: Deprecating reload() ??? References: Message-ID: <1051nfg3nie5060@news.supernews.com> "Ellinghaus, Lance" wrote in message news:mailman.282.1079035927.19534.python-list at python.org... > > > Other surprises: Deprecating reload() > > >Reload doesn't work the way most people think > >it does: if you've got any references to the old module, > >they stay around. They aren't replaced. > > >It was a good idea, but the implementation simply > >doesn't do what the idea promises. > > I agree that it does not really work as most people think it does, but how > would you perform the same task as reload() without the reload()? > > Would this be done by "del sys.modules['modulename']" and then perform an > 'import'? > > I use reload() for many purposes, knowing how it works/does not work. I usually figure out another way to do it - mostly reload the entire program from scratch. In any case, it's not a real issue for me - it's just enough of an irritation that the PythonWin editor does it that I keep a command line open rather than use what is (to me) a really broken implementation of run. There are a lot of things in life that I wished worked the way they are advertised. They don't, so you cope. John Roth > > Lance Ellinghaus > From peter at engcorp.com Thu Mar 18 11:40:32 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 18 Mar 2004 11:40:32 -0500 Subject: Slashes and Windows (was Re: New to Python.) In-Reply-To: References: <40593E14.EAF16BD5@alcyone.com> Message-ID: <3pSdnZHPt9CdTMTdRVn-gw@powergate.ca> Scott F wrote: > "Terry Reedy" wrote in > news:mailman.126.1079617542.742.python-list at python.org: > >>>You really want to use double backslashes (\\) here or use a raw >>>string (r'...'). If not, this will eventually bite you. >> >>Or forward slashes (/), which avoids the whole problem. > > for file() and similar, forward slashes are great, but try to spawn() > something and a raw string works better. The basic rule is that if you are passing the path through the command line (in effect, using os.system or spawn and friends), you need to use backslashes, but any other time forward slashes should be fine. Unfortunately, if you ever get into comparing path strings, and some have been made with forward slashes, while others used backslashes or were run through things like os.path.normpath(), then you'll also get into trouble. -Peter From look at www.covingtoninnovations.com.for.address Wed Mar 24 09:57:35 2004 From: look at www.covingtoninnovations.com.for.address (Michael A. Covington) Date: Wed, 24 Mar 2004 09:57:35 -0500 Subject: IDLE won't launch, and other frustrations References: Message-ID: "Dennis Lee Bieber" wrote in message news:l2a260lj050pch3sq57vfp29rsq099tgp9 at 4ax.com... > On Tue, 23 Mar 2004 20:48:19 -0500, "Michael A. Covington" > > My apologies... The name seems familiar... "Astrophotography for > the Amateur", by chance? That's me! Since I lead a double life, I'll give you both signature blocks below... By the way, the deal with WN16 was - can you believe it - an AUTOEXEC.BAT file! I didn't know such things would even still run under Windows XP, but there it was. 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! ---------------------------------------------------------------------------- --------- Michael A. Covington, Associate Director Artificial Intelligence Center, The University of Georgia http://www.ai.uga.edu/~mc -- Michael Covington -- www.covingtoninnovations.com Author, Astrophotography for the Amateur and (new) How to Use a Computerized Telescope From theller at python.net Mon Mar 8 11:17:04 2004 From: theller at python.net (Thomas Heller) Date: Mon, 08 Mar 2004 17:17:04 +0100 Subject: How to implement a union (C data type) in Python? References: <2c22d0af.0403080753.f17a7e0@posting.google.com> Message-ID: lamote1 at netscape.net (chads) writes: > How would one implement a union (C data type) in Python, given this > simple example? > > union { > struct { > int size; > float time; > } var1; > struct { > char initial; > float time; > } var2; > }; With ctypes ;-) from ctypes import * class MyUnion(Union): class struct_1(Structure): _fields_ = [("size", c_int), ("time", c_float)] class struct_2(Structure): _fields_ = [("initial", c_char), ("time", c_float)] _fields_ = [("var1", struct_1), ("var2", struct_2)] print sizeof(MyUnion) On Windows, this prints 8. Thomas From alan.gauld at btinternet.com Mon Mar 15 13:15:51 2004 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 15 Mar 2004 18:15:51 +0000 Subject: Stop code in python!! References: <4055bb8c$0$794$edfadb0f@dread11.news.tele.dk> Message-ID: On Mon, 15 Mar 2004 15:19:52 +0100, "The Radiator" wrote: > I have this code, but I shall have a pause in the end. Would you plaese > give me some idears to this, or/and write the code better! > > p = (raw_input("Password please: ")) > if p == "root": > print "" > print "Welcome" > print "to this game, hope you will enjoy!" > print "But remeber, it still under construktion!!" > print "" > m = (raw_input("Will you move on to level 2? (y/n)")) > print "" > if m == "n": > print "Goodbye!!" > else: > if m == "y": > print "Hey, this here is level 2" > print "but it is still under construction" > If you just want the program to stop so that you can see the output try adding a raw_input() line at the end: raw_input("Hit Enter to quit...") Alternatively don't double click but actually run it from inside a DOS prompt(assuming you are on Windoze) or within IDLE. BTW You might find it helpful to join the Python tutor mailing list which is geared to helping beginners. Find the sign up page under Communities->Mailing Lists on the Python web site. HTH Alan G. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld From faheem at email.unc.edu Sun Mar 14 12:12:55 2004 From: faheem at email.unc.edu (Faheem Mitha) Date: Sun, 14 Mar 2004 17:12:55 GMT Subject: creating array of python objects Message-ID: Dear People, I have the current modest goal. Given a user defined class, I want to creata an array of instances of that class. Consider the following class. class cell: def setrow(self,row): self.row = row def setcol(self,col): self.col = col ... I create an "empty" cell. empcell = cell() Now I want to create an array of objects identical to empcell, and later initialize them. I tried stuff along the lines of ****************************************************************** import string from numarray import * empcell = cell() base = [empcell] mat = fromlist(base,shape=(2,2)) ****************************************************************** But the mat = fromlist(base,shape=(2,2)) line fails with AttributeError: cell instance has no attribute '__len__' Similar things fail with the same error message. No doubt I'm doing something stupid, but would someone please enlighten me? I got the fromlist command from >>> help("numarray.objects") I was a bit disconcerted to find on trying to run the first example from the help page that I got >>> a = fromlist(["t","u","w"]) ... TypeError: Expecting a python numeric type, got something else. What am I doing wrong? I'm running ii python 2.3.3-5 An interactive high-level object-oriented language (default versio ii python-numarray 0.8.1-1 An array processing package modelled after Python-Numeric ii python-numeric 23.1-1 Numerical (matrix-oriented) Mathematics for Python on Debian sarge. Thanks in advance and sorry for the long-winded message. Faheem. From qpmez at oce.nl Fri Mar 19 09:57:09 2004 From: qpmez at oce.nl (Patrick Mezenberg) Date: Fri, 19 Mar 2004 15:57:09 +0100 Subject: Running inproc COM-components in a surrogate process using win32com Message-ID: <405B0A45.33BA4981@oce.nl> Hi all, It should be possible to let inproc COM-components live in a surrogate process (for instance in the default Dllhost.exe surrogate process, for more info see http://msdn.microsoft.com search for: "DLL Surrogates (COM)"). Somehow this "feature" does not seem to work when running inproc COM-components launched within a python environment using the win32com package (the inproc component then lives in the python.exe process). Does anyone know whether win32com supports surrogates processes and if so what could I done wrong? Or is there perhaps an alternative, I use python for testing inproc COM-components so it is not an option to let the COM-components live in the python process (if the component under test chrashes my testenvironment will crash too). Thanks in advance! Regards, Patrick From jcarlson at nospam.uci.edu Sun Mar 14 03:32:51 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Sun, 14 Mar 2004 00:32:51 -0800 Subject: A GOTO example (was question: numarray c extension...) In-Reply-To: References: Message-ID: > You have to remember to check the error variable at every step in the > function, or use else clauses and deal with heavy nesting. This is a > perfect situation for GOTO. I did slip, but it is still fairly easy to do, I just wasn't paying attention. It does show a situation where GOTO can be useful, I'll give you that. Depending on the code, it may be a case where a macro would be better suited. - Josiah From fumanchu at amor.org Thu Mar 4 12:35:52 2004 From: fumanchu at amor.org (Robert Brewer) Date: Thu, 4 Mar 2004 09:35:52 -0800 Subject: Gadfly ???? Message-ID: Fuzzyman wrote: > Gadfly looks like an interesting database system for python. I am > working on a couple of projects that may benefit from using a database > (on the other hand, these days - is there really aproblem with using > dictionaries that are a couple of meg in size and searching through > those ??). The only problem with using in-memory dictionaries will be the indexing, which is the problem which databases solve. In other words: if you always look up the objects by dictionary key, it might be feasible, but if you need to inspect each object to match it against some criterion, you should find a good DB. Robert Brewer MIS Amor Ministries fumanchu at amor.org From look at www.covingtoninnovations.com.for.address Wed Mar 24 00:23:42 2004 From: look at www.covingtoninnovations.com.for.address (Michael A. Covington) Date: Wed, 24 Mar 2004 00:23:42 -0500 Subject: IDLE won't launch, and other frustrations References: <6ZydnUx5GLGadf3dRVn-sw@speedfactory.net> Message-ID: Somehow, after reinstalling, it started working OK. And on another computer it gave no trouble. "Michael A. Covington" wrote in message news:6ZydnUx5GLGadf3dRVn-sw at speedfactory.net... > Further, Python 2.3.2 has the same problem, but with 8.3 in place of 8.4 > throughout. > > > "Michael A. Covington" wrote > in message news:PoidnWghOfqve_3dRVn_iw at speedfactory.net... > > 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 rogerb at rogerbinns.com Mon Mar 8 15:43:11 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Mon, 8 Mar 2004 12:43:11 -0800 Subject: Working around a lack of 'goto' in python References: Message-ID: > Well, say you decide that several lines of code should be executed > repeatedly. You can stick in the while...: , your editor can indent > the block, then you have to hunt for numbered `continue` and `break` and > increment some, but not all of the numbers. Unnumbered `continue` and > `break` cause similar trouble, but the trouble is guaranteed to be more > local. For non-local I much prefer the exit-by-exception. That is fine (and only solves break - continue is more of a pain, and things get real ugly if you have both break and continue). You are not forced to use every language construct. For example I never use 'else' with for loops. Similarly to your argument, multiple inheritance can also be error prone (eg call a different base class than you thought, order of inheritance matters). Some languages don't let you use multiple inheritance ever. Others (such as Python) realize that it can occassionaly be useful and allow you to use it. All general purpose languages let you have looping constructs (for and while) and usually let you nest them to arbitrary depths (ie it isn't considered a bad thing by the languages to have nested loops). They all let you break out of the loops before they would naturally terminate (break) and usually do the next iteration of the loop (continue - Modula 2 doesn't have this). Since nested loops are ok, and break/continue out of one enclosing loop is ok, why is break/continue out of more than one some sort of great evil? Your argument about introducimg more loops in the same code requiring fixing of the numbers doesn't really matter. You may have to do code surgery if you went from one enclosing loop to two (because there is no break 2/continue 2) so each loop construct has to be examined anyway. Python's indentation rules also make it VERY clear what is going on. Any code editor can trivially renumber existing code when you insert a new loop. Just like multiple-inheritance, this may be of no use to you or a construct you feel is too dangerous for your code. That doesn't mean it should be prevented from others using it. Several pieces of my code would greatly benefit from break/continue of multiple depths. They currently use extra variables and exceptions and have had a tendency to be somewhat buggy due to the extra complexity and the mismatch between my mental model and what the language allows. Roger From skip at pobox.com Wed Mar 24 11:05:58 2004 From: skip at pobox.com (Skip Montanaro) Date: Wed, 24 Mar 2004 10:05:58 -0600 Subject: Way OT [was: Re: [Slightly OT] Re: Voting (was Re: PEP 318)] In-Reply-To: References: <95aa1afa.0403230250.4c9da7a2@posting.google.com> <1060m0593q1uo0d@news.supernews.com> <10637ibo30epo6f@news.supernews.com> Message-ID: <16481.45542.61787.963592@montanaro.dyndns.org> Joe> (The crux of the flamewar is that Condorcet tends to elect Joe> "compromise candidates" who are few peoples' favourite but Joe> palatable to most, while IRV is more likely to elect people that Joe> are the first choice of a large block but hated by others. Which Joe> is preferable is a matter of philosophy.) Given the results of the last couple of presidential elections in the US I'd say our current system tends to "elect people that are the first choice of a large block but hated by others" as well. It has little to do with the voting method though, and more to do with the candidates pandering to the more extreme segments of their constituencies (*). Perhaps one or the other voting method would tend to move things back toward the middle. Skip (*) My personal opinion is that most Republican party apparatchiks try to brand as "liberal" anyone whose views are at all to the left of say, Rush Limbaugh. From rogerb at rogerbinns.com Tue Mar 23 19:50:07 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Tue, 23 Mar 2004 16:50:07 -0800 Subject: "The Python Robot" is going mad ? References: Message-ID: > Like amk said, "them ain't us". I think "Python Robot" is what Awstats uses to refer to anything with a user agent of "Python-urllib" (actually from the Awstats code, it would appear that anything with "python" in the user agent field is considered the Python Robot. There is one person on the end of a DSL line who looks at a Python file on my website at 7am PST every day. User agent is "Python-urllib/1.15" Roger From michael at foord.net Mon Mar 8 05:20:44 2004 From: michael at foord.net (Fuzzyman) Date: 8 Mar 2004 02:20:44 -0800 Subject: Need better string methods References: <0d4k40987t6d70bahqil3geth640bufgoc@4ax.com> Message-ID: <8089854e.0403080220.4622ded6@posting.google.com> [snip..] > Isn't this more readable? : > > pieces = line.split(|) # break at the bars > nodots = [ piece.strip(".") for piece in pieces ] # remove leading or > trailing dots > clean = [" ".join(words.split()) for words in nodots] # normalise spaces > > Well, there is still some complexity with the join/split mess. > But still more readable than the regex? This is much simpler and easier to read. Seems like the best solution..... no need for it all to be done on one line. Remind me of the Perl assertion that it's a better language because you can cram functions into huge, indecipherable single lines..... why on earth is that an advantage ? Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html From theller at python.net Wed Mar 3 03:08:51 2004 From: theller at python.net (Thomas Heller) Date: Wed, 03 Mar 2004 09:08:51 +0100 Subject: py2exe odbc:cannot import dbi module References: Message-ID: <65dmic8c.fsf@python.net> Thomas Heller writes: > mederis at hotmail.com (Marc Ederis) writes: > >> Hello, >> >> I'm trying to create an executable with py2exe, and it uses the odbc >> module. The script runs fine until I use py2exe on it and run the >> .exe. Then I get: >> >> -- >> Traceback (most recent call last): >> File "dbmod.py", line 2, in ? >> File "odbc.pyo", line 9, in ? >> File "odbc.pyo", line 7, in __load >> odbc: Cannot import dbi module >> -- >> >> dbi.dll is in the dist folder, and so is odbc.pyd. >> >> Does anyone know how to solve this problem? > > It seems you have to first explicitely import the dbi module before the > odbc module can be imported. > > """ > import dbi, odbc > """ > > py2exe doesn't know that dbi.dll is a python extension - it is only > found as binary dependency. You can avoid the need for 'import dbi' by patching the builtin hidden_imports dictionary, in the get_hidden_imports() method in py2exe\build_exe.py, near line 650. Add "odbc": ["dbi"] and it should work. > And you should not (must not?) distribute > odbc32.dll, which is also copied to the dist folder. > > In py2exe 0.5, you *should* be able to specify > dll_exludes = ["odbc32.dll"] > but this doesn't seem to work. I got this wrong - it does work, but you have to pass an options dict to the setup script, something like this: setup(... options = {"py2exe": {"dll_excludes": ["odbc32.dll"]}} ) Thomas From mwilson at the-wire.com Wed Mar 24 07:41:54 2004 From: mwilson at the-wire.com (Mel Wilson) Date: Wed, 24 Mar 2004 07:41:54 -0500 Subject: creating lists question? References: Message-ID: In article , Josiah Carlson wrote: >> I'm not sure this is doing what I want it to do. In the example I gave I >> want a new list call "aaa" another list called "bbb"... so I can append to >> the new list i.e., bbb.append(). It may be that your example does this but >> it appears to be (with my limited knowledge) that it's creating a list of >> lists, when all I want is a new isolated list. > >Matt already gave an answer for how to do it using exec. There is >another method: > >for name in list1: > locals()[name] = [] > >The above gets the dictionary for the local namespace, and makes the >name given point to a new list. > >This doesn't have the same security holes as exec, but may have >(non-exploitable) security holes, eg lists with builtin or module names. Modifying locals() is not entirely like creating a variable: Python 2.3 (#46, Jul 29 2003, 18:54:32) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> def f (x): ... print locals() ... locals()['b'] = x ... print locals() ... if x == 'x': ... print b ... print ... >>> f('y') {'x': 'y'} {'x': 'y', 'b': 'y'} >>> f('x') {'x': 'x'} {'x': 'x', 'b': 'x'} Traceback (most recent call last): File "", line 1, in ? File "", line 6, in f NameError: global name 'b' is not defined Regards. Mel. From rich_NOSPAM_ at _NOSPAM_holmteam.net Thu Mar 4 17:36:57 2004 From: rich_NOSPAM_ at _NOSPAM_holmteam.net (RichH) Date: Thu, 4 Mar 2004 16:36:57 -0600 Subject: Debugging Extensions using Visual Studio 7.1 References: Message-ID: In article , artifice_1 _SPAM_ME_NOT at PLEASE_hotmail.com says... > Does anyone know how to get this to work? I've done a fair bit of > searching with Google and couldn't turn up anything. I just want to get > debugging to work so I've built a DLL using VC7 and it runs fine. I set > breakpoints in some of the code. Set the command line/args to run the > program from python, and then it craps out with: "Fatal Python error: > Interpreter not initialized (version mismatch?)" > > Does anyone have any suggestions? Apart from building a debug python so > I can set break points in it? > Just turn off optimization (to make it easier to step through the code) and build a release version. You can't mix debug and release builds. Cheers, Rich From null at null.null Thu Mar 18 23:10:56 2004 From: null at null.null (SWright) Date: Fri, 19 Mar 2004 04:10:56 GMT Subject: Updating Widgets Message-ID: Please bear with a Python/Tkinter newbie here. I'm having trouble knowing when a widget will be updated on screen. I've included a program that creates a window with a single button. When that button is pressed it brings up a configuration window which lets you pick the color of 'car' and 'truck'. After the user chooses to update the color of car, the StringVar which contains the color is updated and the color chooser closes. The 'car' button still displays with its original color, but when the config window closes, it prints out a message indicating the car color was updated. When the config window is opened again, the 'car' button is the color which was picked. The truck button operates the same except the widget parameter 'fg' is updated when the StringVar is updated. In this case, the 'truck' button changes color immediately. This is fine, except it requires that the button be named so the 'fg' parameter can be changed: name['fg']=color. Is it possible to make the un-named button update without closing and reopening the window? Thanks for any insight you can give me. from Tkinter import * import tkSimpleDialog import tkColorChooser #******************************************************************************* class base: def __init__(self,parent): self.main=Frame(parent) self.main.pack() Button(self.main,text="Config",bg='light blue', width=20,height=8,command=self.conf).pack() self.info={"car":'#FF0000',"truck":'#0000FF'} def conf(self): print 'Starting with car %s and truck%s'%(self.info['car'], self.info['truck']) UNIT_config(self.main,self.info) #****************************************************************************** class UNIT_config(tkSimpleDialog.Dialog): def __init__(self,parent,db): self.paint=db tkSimpleDialog.Dialog.__init__(self,parent) def body(self,parent): self.car_color=StringVar() self.car_color.set(self.paint["car"]) self.truck_color=StringVar() self.truck_color.set(self.paint["truck"]) Button(parent,text='car',fg=self.car_color.get(), command=lambda a1=self.car_color,a2='car': self.color_config(a1,a2)).grid(row=1) self.b2=Button(parent,text="truck",fg=self.truck_color.get(), command=lambda a1=self.truck_color,a2='truck': self.color_config(a1,a2)) self.b2.grid(row=2) def apply(self): self.paint["car"]=self.car_color.get() self.paint["truck"]=self.truck_color.get() print 'Now car color', self.car_color.get() print 'Now truck color', self.truck_color.get(),'\n**********' def color_config(self,color_var,type): old_color=color_var.get() new_color=tkColorChooser.askcolor(old_color) if new_color[0]: red=hex(new_color[0][0])[2:] green=hex(new_color[0][1])[2:] blue=hex(new_color[0][2])[2:] if len(red)==1: red='0'+red if len(green)==1: green='0'+green if len(blue)==1: blue='0'+blue new_color_rgb='#'+red+green+blue else: new_color_rgb=old_color if type=='car': self.car_color.set(new_color_rgb) else: self.truck_color.set(new_color_rgb) self.b2['fg']=new_color_rgb #****************************************************************************** root = Tk() prop = base(root) root.mainloop() From gerrit at nl.linux.org Fri Mar 12 06:55:00 2004 From: gerrit at nl.linux.org (Gerrit) Date: Fri, 12 Mar 2004 12:55:00 +0100 Subject: put your money where your mouse is, or why I prefer Spanish to English: a proposal In-Reply-To: <082d01c407eb$bb8dfc10$210110ac@jsbwxp3> References: <082d01c407eb$bb8dfc10$210110ac@jsbwxp3> Message-ID: <20040312115500.GA4102@nl.linux.org> John Benson wrote: > I propose that we change the language of this board to Spanish, as long as > we're so vocally committed to using best-of-breed languages. Derived from > the Iberian dialect of vulgar Latin, Spanish has many important advantages > over English: > Thinly-veiled threat: If this board doesn't immediately cut over to Spanish > because it is obviously superior to English, I shall be forced to consider > its badmouthing of other computer languages as just so much small-minded > special pleading. How about Esperanto? Zamenhoff-forever-ly - y'rs Gerrit. -- Weather in Twenthe, Netherlands 12/03 11:25 UTC: 6.0?C haze mostly cloudy wind 5.4 m/s ESE (57 m above NAP) -- Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From peter at engcorp.com Tue Mar 16 15:53:52 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 16 Mar 2004 15:53:52 -0500 Subject: Send commads to printer In-Reply-To: References: Message-ID: free free wrote: > i'am writing a python program and now i need to print some stuff. Before > print i want to set the text to condensed text and to italic, so i have > to send some esc commads to printer. > > my code > > pp=open("/dev/lpr","w") > pp.write(chr(27)+chr(15)) > pp.write("This should be condensed\n") > pp.write(chr(27)+chr(52)) > pp.write("This should be italic too\n\f") > pp.close() > > what i get is text in normal font. I think chr(27) does not send the ESC > char to printer. chr(27) is most certainly ASCII ESCape, so the problem is elsewhere. Why not try creating a file containing exactly the characters you want to send, and copy that to the printer as a test? If that works, then you can try modifying your above program to write to a file instead, for comparison. If it doesn't work, then clearly you are not dealing with a Python problem, but with something environment- or printer-specific. -Peter From http Thu Mar 4 04:39:00 2004 From: http (Paul Rubin) Date: 04 Mar 2004 01:39:00 -0800 Subject: i'm lost in list manipulation References: <40460bb3$0$28116$636a15ce@news.free.fr> <404653cb$1_1@themost.net> <4046e6d6$0$4677$626a14ce@news.free.fr> <4046e8c1$0$4666$626a14ce@news.free.fr> Message-ID: <7xbrnd54uj.fsf@ruckus.brouhaha.com> "GrelEns" writes: > i'm not happy with this code, must be an other shorter alternative, have you > any siggestions on how to build these sets [[1], [2], [3], [1, 2], [1, 3], > [2, 3], [1, 2, 3]] from [1,2,3] ? def subsets(lst): def subgen(lst): if not lst: yield lst return for s in subsets(lst[1:]): yield s yield [lst[0]] + s return list(subgen([1,2,3]))[1:] # discard empty subset print subsets([1,2,3]) From grsNOSPAM at NO-SPAMmail.com Wed Mar 3 11:54:48 2004 From: grsNOSPAM at NO-SPAMmail.com (Guillaume) Date: Wed, 03 Mar 2004 17:54:48 +0100 Subject: OFF-TOPIC:: Why Lisp is not my favorite programming language In-Reply-To: <165b3efa.0403030443.4d591f04@posting.google.com> References: <165b3efa.0403030443.4d591f04@posting.google.com> Message-ID: <40460dd5$0$5916$7a628cd7@news.club-internet.fr> I don't know what this post has to do with comp.lang.c, but whatever. This was pretty funny nonetheless. As for me, I would say practically the same things about Java. :-p From jcarlson at nospam.uci.edu Fri Mar 12 02:06:38 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Thu, 11 Mar 2004 23:06:38 -0800 Subject: PEP 328: Imports: Multi-Line and Absolute/Relative In-Reply-To: References: Message-ID: > If people do not care for > > import -2.MODULE > from -1.MODULE import NAMES as RENAME > > Would it be possible and/or preferrable to have something like this work: > > import relative(2).MODULE > from relative(1).MODULE import NAMES as RENAME I don't know the Python semantics for mixing statements and expressions like that. Really, relative() would end up with the same magical internals, except that "relative" would probably need to be a builtin (which is generally frowned upon). Personally, I don't favor using functional notation in order to handle module loading. If we wanted a function-based import, we'd all be using __import__(). - Josiah From nish20 at netzero.net Thu Mar 4 10:35:32 2004 From: nish20 at netzero.net (Mike Nishizawa) Date: 4 Mar 2004 07:35:32 -0800 Subject: OFF-TOPIC:: Why Lisp is not my favorite programming language References: <165b3efa.0403030443.4d591f04@posting.google.com> <40460dd5$0$5916$7a628cd7@news.club-internet.fr> Message-ID: 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. Guillaume wrote in message news:<40460dd5$0$5916$7a628cd7 at news.club-internet.fr>... > I don't know what this post has to do with comp.lang.c, but whatever. > > This was pretty funny nonetheless. > > As for me, I would say practically the same things about Java. :-p From chrisks at NOSPAMudel.edu Mon Mar 22 05:02:59 2004 From: chrisks at NOSPAMudel.edu (Chris S.) Date: Mon, 22 Mar 2004 05:02:59 -0500 Subject: Slow Python - what can be done? In-Reply-To: References: <480e9240.0403180943.64bee13d@posting.google.com> Message-ID: Riccardo Galli wrote: > I can't try your prog because I have not Tkinter, Isn't Tkinter a standard module? From kamikaze at kuoi.asui.uidaho.edu Fri Mar 5 20:35:12 2004 From: kamikaze at kuoi.asui.uidaho.edu (Mark 'Kamikaze' Hughes) Date: 6 Mar 2004 01:35:12 GMT Subject: Running insecure python code References: <2004022623031275249%bob@redivicom> <2004022718575516807%bob@redivicom> <2004030511074775249%bob@redivicom> Message-ID: Bob Ippolito wrote on Fri, 5 Mar 2004 11:07:47 -0500: > On 2004-03-04 16:04:25 -0500, kamikaze at kuoi.asui.uidaho.edu (Mark > 'Kamikaze' Hughes) said: >> Bob Ippolito >> wrote on Fri, 27 Feb 2004 18:57:55 -0500: >>> You can try looking into PyPy or something. In practice, an >>> interpreter written in Python is probably going to be far too slow to >>> be used for any sort of modern game. >> You could translate your more limited scripting language into Python, >> and then eval it. This should be reasonably fast, and if you're careful >> not to pass unescaped strings from the player through to Python, it >> should be secure. >> For maximum fun, the limited scripting language should be a subset of >> Python. > You have to be awfully careful about resource consumption (long > strings, infinite loops, etc)... > It wouldn't be trivial to do correctly, let's leave it at that. There are two possibilities. The first is that resource consumption is irrelevant to your concerns, you just want something that can't 'rm -rf' your files. If the user runs you out of memory, so what? If the user eats a lot of CPU time, so what? You kill the app, and it goes away (if your OS's task switching is so primitive that you can't kill a CPU-eating app, the problem is not in the scripting language). This is very easy to provide, and in real scripting applications this is all you need 99.9% of the time. The second, which exists only in very theoretical ivory-tower discussions and will never be found in the wild, is that you do care about loops, recursion, and memory hogging. Even so, this is a little harder, but not by much. You check all the strings, you check the range of all loops, your custom list class checks maximum sizes before appending, and you don't allow any cycles in function-calling graphs. -- Mark Hughes "Doing the impossible makes us mighty." -Captain Malcolm Reynolds, Firefly From grelens at NOSPAMyahoo.NOTNEEDEDfr Wed Mar 3 11:45:52 2004 From: grelens at NOSPAMyahoo.NOTNEEDEDfr (GrelEns) Date: Wed, 3 Mar 2004 17:45:52 +0100 Subject: i'm lost in list manipulation Message-ID: <40460bb3$0$28116$636a15ce@news.free.fr> 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 :( thank a lot if you could help... From val at vtek.com Sun Mar 7 14:26:18 2004 From: val at vtek.com (Val Bykoski) Date: 7 Mar 2004 11:26:18 -0800 Subject: dynamic names Message-ID: 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 pythonw -u "sumL.py" Traceback (most recent call last): File "sumL.py", line 11, in ? sumL(1,4) File "sumL.py", line 7, in sumL tot=tot + ("L%s" % L) TypeError: unsupported operand type(s) for +: 'float' and 'str' >Exit code: 1 Any help would be life-saving. let's-make-python-a-tax-pain-killer-ly y'rs val From s.mountNOSPAM at REALLYNOSPAMcoventry.ac.uk Mon Mar 22 11:16:04 2004 From: s.mountNOSPAM at REALLYNOSPAMcoventry.ac.uk (Sarah Mount) Date: Mon, 22 Mar 2004 16:16:04 -0000 Subject: Problem using py2exe Message-ID: Hi everyone. I'm trying to create an exe for a simple pygame app on Win XP. I think I've got the latest (python, py2exe, pygame) and my setup.py file looks like this: | from distutils.core import setup | import glob | import py2exe | | setup(name='pyDemo', | windows=["pyDemo.py"], | data_files=[("data", | ["images/sensor.png", "images/start.png"])] | ) Simple, eh? Well, all runs well, except for the following error: | The following modules appear to be missing | ['AppKit', 'Foundation', 'objc'] Since pyDemo doesn't use any of these libraries, I just ignored that. When I try to run pyDemo.exe, I get the following error report from the MS Visual C++ Runtime Library: | Runtime error! | Program: C:\mypath\pyDemo.exe | This application has requestion the Runtime to terminate it in an unusual way. | Please contact the application's support team for more information. Eeek! I've no idea where to go from here, so if anyone can help that would be fantastic. Thanks, Sarah From mcfletch at rogers.com Tue Mar 16 12:05:52 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Tue, 16 Mar 2004 12:05:52 -0500 Subject: Advice needed: large OpenGL + Widgets Project for Molecular Graphics In-Reply-To: <5eb8fb88.0403160815.36d716a6@posting.google.com> References: <5eb8fb88.0403151925.4f63842b@posting.google.com> <5eb8fb88.0403160815.36d716a6@posting.google.com> Message-ID: <405733F0.2040500@rogers.com> Rick Muller wrote: >"Mike C. Fletcher" wrote in message news:... > > ... >>Togl is pretty much history. I'll likely fix the installer one last >>time for the next bug-fix release (2.0.2) and then drop the thing. I've >>been looking for someone who uses Tkinter+Togl to champion maintenance >>of the thing for years and never found anyone interested enough to >>bother. I'm not a huge fan of Tkinter either, for that matter. >> >> > >Help me out with this: is it that the togl project is history, or that >the Python bindings for Togl are history? I've poked around the Togl >website (http://togl.sf.net), and I'm not overwhelmed with new >releases. Plus, there don't seem to be many posts to the mailing list >in the last year. > > Togl the Tcl/Tk project is moribund, but then, it's very old technology that's been stable for years. Togl is just setting up a context for Tkinter and hooking it up to various event handlers. For the most part all GUI-library interfaces can be similarly static. The only problems that come up with it in an average year are configuration and installation ones. It's the Tkinter binding that's on it's way to the graveyard, precisely because of those configuration and installation headaches. For instance, the upgrade of Tkinter to 8.4 in Python 2.3.x broke the Togl install for us (it's still broken). It's possible to build and install the widget manually, but the automated installer fails due to some deep Tk or Tcl or Togl bug. Working around that is fairly trivial, but it means going back and reworking the installer's Togl code... not a big deal... but nowhere near the top of my list of priorities for the few hours I get now and then to work on the project. So, the 8 or 9 line change doesn't get done, and the Tkinter/Togl binding languishes (and eventually dies). The problems aren't huge, they just don't have anyone available who's actually using the library and willing to find/fix them. >But I'm amazed that more people don't need to put an OpenGL window in >a graphical widget -- seems like a common task. How do people do this? > > wxPython. I think there's a few with GTK, Qt and Fox as well, all of which can mix in widgets fine, but I don't hang out on those user-groups any more to hear from them and thus be able to say for sure. In all fairness, there are also lots of people who have, in the past, used Tkinter/Togl, but since they're not willing to speak up and help with the maintenance I don't feel the need to plug their platform (in either applicable sense of the word) ;) . Have fun, Mike _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From skip at pobox.com Mon Mar 22 11:53:31 2004 From: skip at pobox.com (Skip Montanaro) Date: Mon, 22 Mar 2004 10:53:31 -0600 Subject: What's missing from python? In-Reply-To: <405f148a$0$10522$afc38c87@news.easynet.co.uk> 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: <16479.6667.49725.771745@montanaro.dyndns.org> Peter> Paul Rubin wrote: >> 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. Peter> The 'batteries included' stuff is more a distribution / packaging Peter> issue than the standard library. At least coming from Tcl where Peter> we have a 'batteries included' distribution including all sorts Peter> of nice things. However this does not mean that they are part of Peter> the standard library. See: http://www.tcl.tk/cgi-bin/tct/tip/12.html and search for "Frank Stajano". My guess would be that Frank's paper got the ball rolling for the "batteries included" concept in Tcl. Skip From theller at python.net Thu Mar 25 06:13:23 2004 From: theller at python.net (Thomas Heller) Date: Thu, 25 Mar 2004 12:13:23 +0100 Subject: py2exe question References: Message-ID: Guy Robinson writes: > I want to package a program (using py2exe) that utilises a number of > python scripts so that people can't see or change the source code. But > there is one python script containing some functions I do want the > user to be able to change. Then when they run the program again these > functions are available to the main program. Is this possible? How > could I do it? Sure. Add the directory that contains this module to sys.path at runtime, and exclude it from the build process at build time. Thomas From llothar at web.de Fri Mar 5 18:29:46 2004 From: llothar at web.de (Lothar Scholz) Date: 5 Mar 2004 15:29:46 -0800 Subject: ready to use python, need help with GUI decision References: <30260531.0403032108.3bfc4312@posting.google.com> Message-ID: <6ee58e07.0403051529.3f05f865@posting.google.com> simoninusa2001 at yahoo.co.uk (simo) wrote in message news:<30260531.0403032108.3bfc4312 at posting.google.com>... > If you've got some money to buy a Windows commercial license, or just > want to program for Linux/GPL, then I'd say go with PyQt. The only > thing that puts me off is the stupid licensing issues which even the > PyQt/Qt/BlackAdder folks don't seem to grasp. > Why ? >From there website it seems to be clear: "Includes the rights to distribute the run-time elements (except mxODBC) with your application." So why do you think that this is unclear. Did you found any comments from QT ? From skip at pobox.com Sun Mar 21 12:16:32 2004 From: skip at pobox.com (Skip Montanaro) Date: Sun, 21 Mar 2004 11:16:32 -0600 Subject: PEP 318 In-Reply-To: References: Message-ID: <16477.52720.622370.755878@montanaro.dyndns.org> Marco> def foo(x, y)[staticmethode]: pass ... vs ... Marco> def foo(x, y) as staticmethode: pass Marco> Define foo with arguments x and y as staticmethode. Marco> Is Python now C++? Mabe I miss something why this syntax is wrong. I believe the "as wrap1, wrap2, ..." form is one of the alternatives under consideration, though current sentiment seems to be in favor of the list-like syntax. Python has a long history of borrowing good ideas from other languages. I'm not aware that any of this is being borrowed from C++, no matter that it has some syntactic similarities to stuff C++ does. Note in particular that the construct is much more general than applying the currently available staticmethod and classmethod builtins. The end result need not even be a function or class (there has been some discussion about applying this construct to classes, but it's not as obviously valuable). See recent discussion in the python-dev archives for some other ideas. Skip From crap1234 at hotmail.com Mon Mar 22 10:33:45 2004 From: crap1234 at hotmail.com (Stefan Axelsson) Date: Mon, 22 Mar 2004 16:33:45 +0100 Subject: What's missing from python? In-Reply-To: <405f065c$1@nntp0.pdx.net> References: <405ee0d0$0$63627$5a6aecb4@news.aaisp.net.uk> <405f065c$1@nntp0.pdx.net> Message-ID: Scott David Daniels wrote: > This almost certainly not go in. You can get into a big legal hassle > when you ship encryption binaries around, as some governments tend to > think of them as "munitions" and regulate traffic in them. Python > just wants to avoid that hassle, and so leaves it up to you to put it > together. Actually with the Wassenaar agreement its not that bad anylonger, with an "open source", i.e. freely available source implementation, which would cover C Python quite nicely I think. The only countries that would be excluded would more or less be excluded (it's a gray area) from importing Python anyway, since it's 'American technology'. Google the Wassenaar agreement. And IMHO the world in this day and age actually needs more free high quality crypto implementations. I'd hate to see crypto not being made available because of some (more or less) irrational fear that one might step on someones toes. "Damn the torpedoes, full speed ahead". Other software (likewise exported from the US) contains crypto implementations these days, so I see no reason that Python couldn't. Stefan, -- Stefan Axelsson (http://www.cs.chalmers.se/~sax) From pinard at iro.umontreal.ca Tue Mar 2 10:20:17 2004 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Tue, 2 Mar 2004 10:20:17 -0500 Subject: vim & python In-Reply-To: <1078239738.8515.9.camel@dubb> References: <221dd125.0403011151.504ce09d@posting.google.com> <1078239738.8515.9.camel@dubb> Message-ID: <20040302152017.GA27401@alcyon.progiciels-bpi.ca> [gabor] > i always wanted to ask this... why people use GVIm and not the > normal-vim-in-a-terminal? what is the advantage of gvim? Mainly the ability to use the mouse for some quick operations, like positioning the cursor between two characters, moving big distances by dragging scroll bars, changing window dimensions by dragging the bars between windows, wandering in help through clicking on index items, clicking within the fold margin for opening and closing folds, etc. I'm usually not fond on the mouse, but strangely (to me at least), `gvim' is effectively taming me into using it. One thing which I often do is repeating mouse fast positioning of the cursor with `.' typed with the left hand. It is also surprising how many `vim' operations you can quickly do with the left hand alone! :-) One thing which helped me a lot is that, right from the beginning, I took the time of carefully customising `gvim' so it uses readable fonts, consistent colours, and such things. As for Python editing, of course, `vim' customisation is equally available within and outside X. -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From hungjunglu at yahoo.com Sun Mar 21 17:25:37 2004 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 21 Mar 2004 14:25:37 -0800 Subject: Package name with '.' in them: Python Bug ? References: <105mmlt1ld7jvb9@news.supernews.com> <8ef9bea6.0403192150.57dbddef@posting.google.com> <105oe5k5ovugi5e@news.supernews.com> Message-ID: <8ef9bea6.0403211425.15ca2d4d@posting.google.com> "Terry Reedy" wrote in message news:... > > In Python, that is a meaningless term to me. > ... > Python is neither C++ nor Java. It's data model is quite different. > Imported jargon is meaningless to those not familiear with is. Adding the > word 'static' to 'class attribute' or 'class variable' adds nothing since > there is no differentiation from a hypothetical 'non-static' class > attribute. > --------------- "John Roth" wrote in message news:<105oe5k5ovugi5e at news.supernews.com>... > > So what? This is Python, not C++, Java or any other language. > ... > Static generally means "something that does not change." The fact > that C++ in particular abuses the word has no relevance. --------------- No relevance, huh? (a) What is in the Python Programming FAQ, then? http://www.python.org/doc/faq/programming.html#how-do-i-create-static-class-data-and-static-class-methods Are you saying that this is a C++ Programming FAQ? (b) Search in Python mailing list for keywords "static variable" (quoted as single keyword) and "meaningless". There are exactly two entries, by authors John Roth and Terry Reedy. The fact is, historically speaking, so far there have been only two person in the Python community that have claimed "static variables" are meaningless in Python. Search again with "class static" as single (quoted) keyword, and you see plenty of people in the Python community talking about class-static issues, and none of them ever said that it is meaningless. So, how come all other people can discuss about class-static issues without problem, and only you two have to jump out with semantic issues and say it is meaningless? I don't understand. What is so special about you two? Are you guys the Real Academia de la Lengua Pythonica or something like that? :) Hung Jung From newsgroups at jhrothjr.com Wed Mar 3 16:23:20 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Wed, 3 Mar 2004 16:23:20 -0500 Subject: function arguments passed by reference References: Message-ID: <104cj8vkrqb6i20@news.supernews.com> "Marcello Pietrobon" wrote in message news:mailman.8.1078344338.736.python-list at python.org... > Hello, > > My background is C++ > > I would like to know for sure if it is possible to pass a value by > reference to a function AND having it changed by the function itself > > > def changeValue( text ): > text = 'c' > print text > return > > >>> txt = 'a' > >>>changeValue( txt ) > 'c' > >>>print txt > 'a' > > Question 1) > I guess that in Python ( differently than in C++) somehow txt is passed > by reference even if its value is not changed. > Is this true ? > > Question 2) > How can I define a function that changes the value of txt ( without > having to return the changed value ) ? > > Question 3) > Is there some documentation talking extensively about this ? The key concept is that everything is an object, and all objects are passed by reference in the sense that what's bound to the funtion's parameters is the objects that were passed in. However, you cannot affect the bindings in the calling environment. Regardless of what you do (unless you do some deep magic with the invocation stack) nothing is going to affect the bindings in the caller. So you can rebind anything you want to the parameters within the function, and it will have no effect on the calling environment. On the other hand, if you mutate a mutable object that was passed as a parameter, that change will be visible after you return. For example: def foo(bar): bar = "shazoom" a = "shazam" foo(a) The result is that a is still "shazam." However, if you do this: def foo(bar): bar.append("shazoom") a = ["shazam"] foo(a) the result is: ["shazam", "shazoom"] HTH John Roth "shazoom" ::= ["strength", "health", "aptitude", "zeal", "ox, power of", "ox, power of another", "money"] whatever the value you passed in remains. > > > Thank you, > Marcello > > > From imbosol at aerojockey.invalid Wed Mar 31 22:29:29 2004 From: imbosol at aerojockey.invalid (Carl Banks) Date: Thu, 01 Apr 2004 03:29:29 GMT Subject: proper use of braces in Python References: <338366A6D2E2CA4C9DAEAE652E12A1DE01536140@au3010avexu1.global.avaya.com> Message-ID: Paul McGuire wrote: > > > "Michael" wrote in message > news:mailman.148.1080691972.20120.python-list at python.org... >> >> >>Right. Then we can have "does the brace go on the same line or the >> >>next line" wars. >> >> >> >> >> > >> > int main (void) >> > { >> > if (true) >> > { >> > } >> > >> > return 0; >> > } >> > >> >There is no other way. >> > >> > >> No way, that wastes an entire line of code with a single brace! >> >> int main ( void ) { >> if ( true ) { >> return 1; >> } >> return 0; >> } >> >> This is clearly better. Compact yet easy to read. I try formatting my >> Python code exactly like this and it always complains about my braces.. >> clearly wrong. >> > http://c2.com/cgi/wiki/wiki?WhereDoTheBracesGo > > Not having to deal with this #$*^!!@ is just about my favorite feature of > Python! (Although I'm not excited about getting into a thread on an issue > that is so flame-prone. Honestly, though. "There is no other way."? "This > is clearly better."? I really interpret your stance as "This is the way I'm > used to." What's annoying is the added "... and therefore superior." > implication. The visual cues provided by brace placement are extremely > subjective, and what is "clearly better" to one is confusing to another.) Paul, What you're seeing here is a couple Pythonistas mocking C and Java programmers who take these sorts of arguments dead-seriously. (But not Perl programmers: they don't actually use braces. :) Here at Python, we like to think that we argue about more important things. It's part of the Zen of Python: there should only be one way to do it. Because when there's more than one way to do it, you get arguments like this. "More than one way to do it" has led to the space vs. tab arguments we have here. As far as I'm concerned, the biggest problem with spaces and tabs is that you can use either, i.e., there's *unnecessarily* more than one way to do it. And the Python Gods are rightly getting rid of that. -- 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 s.meyer at technology-network.de Wed Mar 17 04:26:45 2004 From: s.meyer at technology-network.de (Sebastian Meyer) Date: Wed, 17 Mar 2004 10:26:45 +0100 Subject: Problem with threads and signals Message-ID: Hi Newsgroup, i have some problems with using threads and signals in one program. In my program i have three threads running, one for checking a directory at a specified interval to see if new data arrived, one waiting for work and the main thread. My problem is the following: I want to shutdown the program via a signal, so i used the signal module. I know, that signal handling mus be done by the main thread, the signal handler is installed by the main thread. Now, when both threads are running and i send the signal to the main thread at my xterm via kill -SIGUSR1 PID, it seems that the main program ignores it or does not execute the signal handler. When i dont use threads, the signal handler functions properly. I ll post some code, maybe this is more explainig: --- CODE --- import threading import os,signal # *** signal handler *** def shutdown(signum, arg): global threads for th in threads: # the shutdown method sets an internal # flag in the derived thread class to # notify the thread to shutdown # (implemented using threading.Event) th.shutdown() # *** main *** # install the signal handler signal.signal(signal.SIGUSR1, shutdown) # both classes, TimedDirectoryCheck and BatchProcessor are derived from # threading.Thread threads = {} threads["dircheck"] = TimedDirectoryCheck("/tmp/dpf/notify") threads["process"] = BatchProcessor() # start the threads for th in threads: th.start() --- CODE --- thats is ... now both threads are running and doing their work. When i now want to shutdown and send the signal, nothing happens, even the signal handler will not be called? Have i missed something? I ve red a lot about threads and signals, seems that it sometimes causes strange program behavior... Anyone any idea what i did wrong?? Thanks for your help in advance.. Sebastian From Pieter.Claerhout at Creo.com Wed Mar 24 10:31:06 2004 From: Pieter.Claerhout at Creo.com (Pieter Claerhout) Date: Wed, 24 Mar 2004 16:31:06 +0100 Subject: zxJDBC driver error Message-ID: <490316A24CC5D411ACD700B0D078F7F0068A0D8F@cseexch01.cse.creoscitex.com> Are you sure the jar file with the mysql JDBC classes is in your classpath? cheers, pieter Come and visit us at Drupa! Hall 4 Stand B10 Creo EMEA S.A. 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 vincent Salaun Sent: 24 March 2004 16:15 To: python-list at python.org Subject: zxJDBC driver error hi all, i'm trying to use the zxJDBC module to work on my mySql database, but : >>> from com.ziclix.python.sql import zxJDBC >>> d, u, p, v = "jdbc:mysql://localhost/test", "user", "pass", "org.gjt.mm.mysql.Driver" >>> db = zxJDBC.connect(d, u, p, v) Traceback (innermost last): File "", line 1, in ? DatabaseError: driver not found any idea ? thx vince -- http://mail.python.org/mailman/listinfo/python-list From roy at panix.com Sun Mar 7 12:50:21 2004 From: roy at panix.com (Roy Smith) Date: Sun, 07 Mar 2004 12:50:21 -0500 Subject: Unit testing - suitable for all development? References: <153fa67.0403070839.77ae66e6@posting.google.com> Message-ID: kylotan at hotmail.com (Kylotan) wrote: > Today I tried to implement some sort of unit testing into my program > for the first time, and must admit to being a little disillusioned > with the process. Mainly, my issue is that in my program, the classes > are so tightly coupled that testing in isolation is next to > impossible. Yup, this is often a problem when you first start unit testing. Tightly coupled classes are difficult to test. Tightly coupled classes cause lots of problems too. They make it hard to understand how your system works, and they make it hard to change out components later. One of the things that unit testing does is it forces you to write classes so they are easily testable, which usually means not a lot of inter-class dependencies. > The main problem stems from the fact that I try to ensure that all my > objects are created in a working state. This often means passing > various other objects to the __init__ function. That's fine. Let's imagine you've got: class Foo: def __init__ (self, language, timeZone, hairColor): self.language = language self.timeZone = timeZone self.hairColor = hairColor def getBreakfastFood (self): do a lot of stuff involving language, etc return (food) class Bar: def __init__ (self, foo): self.foo = foo On the surface, it looks like you can't test Bar without having a working Foo. But maybe you can provide a stub implementation of Foo which does just enough to allow Bar to be tested: class FooStub: def getBreakfastFood (self): return "spam" then you can do in your TestCase class, something like: def setUp (self): foo = FooStub () self.bar = Bar (foo) and you're all set. This assumes that there's something about Bar's behavior which depends on foo having a getBreakfastFood () method which actually works. If the classes were less coupled, Bar might do nothing with the foo it was passed other than treat it as opaque data to be retrieve by a getFoo() method. In which case, your stub class could be even simplier: class FooStub: pass and you might even be able to get away with no FooStub class at all, but simply instantiating your Bar test object with a constant: def setUp (self): self.bar = Bar ("foo") This is where the dynamic nature of Python really shines. Something like C++ or Java would make you jump through a lot more hoops to make sure you instantiated your Bar with a valid Foo. But the basic principle is the same in any OOPL; the more tighly coupled your classes are, the more difficult it is to test, maintain, and understand the system. > One way out of this would be to reduce coupling. This would allow me > to test objects in relative isolation, but it would increase the > amount of explicit coupling code that I'd have to execute normally. > This extra code then becomes a potential source of new bugs. One way or another, your classes need to interact, and the code that implements those interactions needs to exist (and thus needs to be tested). The question is, where do you put that code? Do you bury it inside the classes, making it difficult to test both the underlying classes and their interactions, or do you factor it out to someplace where you can test each piece in isolation? From loic at fejoz.net Thu Mar 18 03:27:07 2004 From: loic at fejoz.net (Yermat) Date: Thu, 18 Mar 2004 09:27:07 +0100 Subject: attributes of Python classes In-Reply-To: References: <3064b51d.0403171605.75ec1ba0@posting.google.com> <4058F086.490C215B@alcyone.com> Message-ID: Roy Smith a ?crit : > 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 :-) I agree BUT there is 2 cases were I don't follow this rules : 1) I have a project that creates a lot of objects by reading a file. The time is twice as needed if I initialize first the attribute and then set them from the values given by the file... 2) When using an algorithm that need to decorate the object, it's easier to just add attribute to the object rather than create a dictionnary or something like that. But for te sake of documentation, your rules sound good to me. For the first problem, I don't know how to solve it nicely. The second is not a problem because, the algorithm know what he's doing. Yermat From aahz at pythoncraft.com Wed Mar 31 15:20:24 2004 From: aahz at pythoncraft.com (Aahz) Date: 31 Mar 2004 15:20:24 -0500 Subject: Syntax counts (was Re: Prothon Prototypes vs Python Classes) References: <8ef9bea6.0403282102.632ae427@posting.google.com> Message-ID: In article <8ef9bea6.0403282102.632ae427 at posting.google.com>, Hung Jung Lu wrote: > >I often don't know how to take it when I see people talking about OOP >by using definitions like: polymorphism, data hiding, etc. As if these >definitions were something of utmost importance. To me, OOP is just a >tool for factorizing code, just like using for-loops and using >functions to factor out repetitive code. Polymorphism, data hiding, >etc. are all secondary features: code factorization is the heart and >soul of OOP. Class-based OOP is a way of factorizing. Prototype-based >is just another way of factorizing, which seems to be more elegant: >instead of two concepts (classes and instances), you unify them and >have only one concept (objects). Moreover, in a prototype-based >language like Io, even scopes and objects are unified. Seems to me that Lisp is the counter-datapoint that disproves, not your thesis at the theoretical level, but the ways in which your thesis gets applied in practice. From my POV, Python demonstrates that syntax counts and that using different syntactical forms for different kinds of factorization makes people enormously productive. So saying "just factorization" misses the point IMO. Factorization needs to be elegantly defined and easy mechanisms for applying it created. What you call the secondary features are the user interfaces for factorization and they are a necessary component for the successful use of factorization. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "usenet imitates usenet" --Darkhawk From gerrit at nl.linux.org Sun Mar 14 09:34:17 2004 From: gerrit at nl.linux.org (Gerrit) Date: Sun, 14 Mar 2004 15:34:17 +0100 Subject: root password in a .py script In-Reply-To: References: Message-ID: <20040314143417.GA2737@nl.linux.org> Wayne Folta wrote: > import string > > unshifted = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' > shifted = 'nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM' > rot13_table = string.maketrans(unshifted, shifted) > > user = string.translate ('sjkeiulkje', rot13_table) > passwd = string.translate ('eorpoipoe', rot13_table) This is actually totally equal to: 'eorpoipoe'.encode('rot13') Gerrit. -- Weather in Amsterdam Airport Schiphol, Netherlands 14/03 13:55 UTC: 12.0?C Few clouds mostly cloudy wind 10.3 m/s SSW (-2 m above NAP) -- Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From claird at lairds.com Tue Mar 2 08:20:37 2004 From: claird at lairds.com (Cameron Laird) Date: Tue, 02 Mar 2004 13:20:37 -0000 Subject: network servers References: <930ba99a.0403020250.66d3536e@posting.google.com> Message-ID: <10492h56p0teh9e@corp.supernews.com> In article <930ba99a.0403020250.66d3536e at posting.google.com>, Sridhar R wrote: >We're planning to write a server for handling atleast 1000 and atmost >4000 clients. The connection is basically (TCP) >connect-send-disconnect type. So no client will open up its >connection forever, except for the small time duration of sending the >message. This is something like online programming contest, where >clients will submit their programs for evaluation and server will >return the results (after sometime). I though of writing the server >part in C and use Python for client. > >Is it possible to use python for that high performance serving? Note: >There is only one physical machine. Yes. It's even realistic, and advisable. -- Cameron Laird Business: http://www.Phaseit.net From jcarlson at nospam.uci.edu Mon Mar 15 18:10:14 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Mon, 15 Mar 2004 15:10:14 -0800 Subject: How to use Sockets with wxPython? In-Reply-To: References: Message-ID: > I am having this problem: > I use Python for my teaching and right now we are trying to implement some > sort of very simple graphical game the pupils can play across the > Internet. For this, we use wxPython. > > Now it has turned out that wxPython does not implement wxWidget sockets, > so we have to use Python sockets instead. Implementing a separate thread > for this would be too complicated and I am going to use the wxIdle event > to do the socket processing, as the amount of data sent from one player to > the other is very small. > > Could somebody show me, how to use Pythin socket in "polling mode" and > how to achieve this? I am not expecting a complete program, an outline of > the logic woul suffice. I would suggest you stay away from wxIdle events, if only because they only occur under certain circumstances (in Windows, they seem to only occur when the mouse is moved over the window). Start with asyncore, and get everything working properly with that. When it is working properly, do something like the following for your GUI: import asyncore import yourasyncorelibrary #in the __init__ method of your main window class #set up the server/clients/whatever #using the new namespace self.timer = wx.Timer(self, wx.NewId()) EVT_TIMER(self, self.timer.GetId(), self.SocketPoller) self.timer.Start(10, wx.TIMER_CONTINUOUS) def SocketPoller(self, event): asyncore.poll() If you properly designed your server and clients, the above should just work. If you are willing to post information about your architecture or protocol, I may be able to help you more. - Josiah From jepler at unpythonic.net Sun Mar 14 16:19:53 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Sun, 14 Mar 2004 15:19:53 -0600 Subject: Behaviour of time.sleep with negative arg In-Reply-To: <4054b472$1@news.iconz.co.nz> References: <4053a412$1@news.iconz.co.nz> <4054b472$1@news.iconz.co.nz> Message-ID: <20040314211953.GA9639@unpythonic.net> On Mon, Mar 15, 2004 at 08:43:51AM +1300, Colin Brown wrote: > "Jeff Epler" wrote in message > news:mailman.15.1079236344.745.python-list at python.org... > > I'd agree that time.sleep(interval) should do the same thing on all > > platforms when interval<0, but I'd rather see it always raise an > > exception than sleep for 0 seconds. > > I am 100% with you that time.sleep() should perform the same on all > platforms but would rather the sleep(0) for negative args because: > 1. 2**31 seconds is about 68 years so interpreting a negative integer > as unsigned is practically useless I was not arguing that it was too useful to be able to sleep for 68 years (and certainly not that the argument -1 should be interpreted to mean 68 years), but rather that sleep(-1) is a TypeError or ValueError because it's not in the range of valid arguments to sleep. > 2. A common usage of sleep is with the difference of two values. If > it raises an exception on negative numbers then when one takes the > difference of say a timestamp and current-time (real-values), to be safe you > would need to put the difference in a temporary variable, check that for > negative and only sleep for positive values - not very elegant. def unsurprising_sleep(d): if d < 0: return time.sleep(d) > Whatever is decided, the behaviour needs to be documented under time.sleep! sleep(secs) Suspend execution for the given number of seconds. The argument may be a floating point number to indicate a more precise sleep time. The actual suspension time may be less than that requested because any caught signal will terminate the sleep() following execution of that signal's catching routine. Also, the suspension time may be longer than requested by an arbitrary amount because of the scheduling of other activity in the system. + The behavior when secs is less than zero is undefined. In particular, + a future version of Python may interpret 'time.sleep(-1); other code' + to cause 'other code' to execute beginning one second before the call + to time.sleep. You can find my proposed enhancement to the documentation above. Jeff From pythongnome at hotmail.com Thu Mar 18 16:44:06 2004 From: pythongnome at hotmail.com (Lucas Raab) Date: Thu, 18 Mar 2004 21:44:06 GMT Subject: Hiding console window References: Message-ID: "Lucas Raab" wrote in message news:Xkh6c.8082$GQ3.5678 at newsread3.news.atl.earthlink.net... > I'm looking to play a joke on a friend and I'm wondering if there's a way to > not show or hide the DOS console. My friend doesn't have python so I have to > compile it to an EXE. > > TIA > > In response to Peter's question, what I meant when I said hide was to hide the console while running the program. Essentially, it would run in the background. The application would run, but you wouldn't see any sign of it. In response to Jorgen and Josef, unfortunately it didn't work. Here's the code for it. It may be a little messy, but I wasn't aiming for perfection: import pygame import time def sleep(): #Sleep for 5 minutes time.sleep(300) def play(): #Initialize pygame pygame.init() #Initialize mixer pygame.mixer.init() #Load and play sound1 pygame.mixer.music.load('C:/sound1.mp3') pygame.mixer.music.play() sleep() #Load and play hazards of retreating pygame.mixer.music.load('C:/hazards_of_retreating.mp3') pygame.mixer.music.play() sleep() #Load and play bring it on pygame.mixer.music.load('C:/bring_it_on.mp3') pygame.mixer.music.play() sleep() #Load and play freaked by flood pygame.mixer.music.load('C:/freaked_by_flood.mp3') pygame.mixer.music.play() sleep() #Load and play grunty thirst pygame.mixer.music.load('C:/grunty_thirst.mp3') pygame.mixer.music.play() sleep() #Load and play joe has lost it pygame.mixer.music.load('C:/joe_has_lost_it.mp3') pygame.mixer.music.play() sleep() #Load and play the french grunt pygame.mixer.music.load('C:\the_french_grunt.mp3') pygame.mixer.music.play() sleep() #Load and play stacker e3 outtake2 pygame.mixer.music.load('C:\stacker_e3_outtake2.mp3') pygame.mixer.music.play() sleep() #Load and play poor running anatomy pygame.mixer.music.load('C:\poor_running_anatomy.mp3') pygame.mixer.music.play() sleep() #Load and play bring it on pygame.mixer.music.load('C:\bring_it_on.mp3') pygame.mixer.music.play() #Quit playing and close pygame pygame.mixer.quit() pygame.quit() #Start the program play() You may raise your eyebrows at the filenames, but as I said its a joke I'm playing. The sound clips are based off the game Halo. Just fill in your own files instead of mine. TIA From peter at engcorp.com Wed Mar 17 13:07:45 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 17 Mar 2004 13:07:45 -0500 Subject: simple http server In-Reply-To: References: Message-ID: Gelo Ilzi wrote: > I've created a subdir 'cgi-bin' which contains a python script. Now when I > enter this directory, i.e., go to the url http://localhost:8000/cgi-bin/ my > browser shows: > > Error response > Error code 403. > Message: CGI script is not a plain file ('/cgi-bin/'). > Error code explanation: 403 = Request forbidden -- authorization will not > help. > > Plain html pages are ok. > > It seems I misunderstand something very basical. Could somebody help me > please. What did you expect to happen when you went to that URL? -Peter From hufman at cobalty.com Fri Mar 5 16:13:57 2004 From: hufman at cobalty.com (Walter Huf) Date: 5 Mar 2004 15:13:57 -0600 Subject: How to find size of file? References: Message-ID: Yermat wrote in news:c2ai0g$1t4u$1 at biggoron.nerim.net: > Walter Huf a ?crit : > def sizeOf(f): > f.seek(0,2) > return f.tell() > Thank you! -----= 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 kkto at csis.hku.hk Fri Mar 26 09:24:03 2004 From: kkto at csis.hku.hk (Isaac To) Date: Fri, 26 Mar 2004 22:24:03 +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> <40200384.0403260545.262ee105@posting.google.com> Message-ID: <7i65cr660s.fsf@enark.csis.hku.hk> >>>>> "Axel" == Axel Boldt writes: Axel> l=[] l.append(l) Is l well-founded? Both answers "yes" and "no" Axel> are consistent with the above definition. If you write a program Axel> to determine whether a given list is well-founded, it will run Axel> into an infinite loop. That depends on how you write the program. I can easily give you a program that will tell you either this is or is not, depending on whether you like it one way or the other---provided that I have a little bit of memory to play with, or I'm allowed to look at my own back-trace. Regards, Isaac. From skip at pobox.com Mon Mar 15 14:46:12 2004 From: skip at pobox.com (Skip Montanaro) Date: Mon, 15 Mar 2004 13:46:12 -0600 Subject: Timeouts with urllib2 In-Reply-To: <7b454334.0403151037.3e78dca9@posting.google.com> References: <7b454334.0403151037.3e78dca9@posting.google.com> Message-ID: <16470.2052.504519.159753@montanaro.dyndns.org> Fazer> I was wondering what's the best way of setting timeouts when Fazer> working with urllib2. Using 2.3+: >>> import socket >>> socket.setdefaulttimeout(3) >>> import urllib2 >>> urllib2.urlopen("http://www.musi-cal.com/search?performers=Greg+Brown") Traceback (most recent call last): File "", line 1, in ? File "/Users/skip/local/lib/python2.4/urllib2.py", line 130, in urlopen return _opener.open(url, data) File "/Users/skip/local/lib/python2.4/urllib2.py", line 338, in open response = self._open(req, data) File "/Users/skip/local/lib/python2.4/urllib2.py", line 356, in _open '_open', req) File "/Users/skip/local/lib/python2.4/urllib2.py", line 317, in _call_chain result = func(*args) File "/Users/skip/local/lib/python2.4/urllib2.py", line 988, in http_open return self.do_open(httplib.HTTPConnection, req) File "/Users/skip/local/lib/python2.4/urllib2.py", line 971, in do_open raise URLError(err) urllib2.URLError: Skip From dwelch91 at comcast.net Wed Mar 24 20:05:33 2004 From: dwelch91 at comcast.net (dw) Date: Thu, 25 Mar 2004 01:05:33 GMT Subject: monitoring a directory In-Reply-To: References: Message-ID: Guy Robinson wrote: > Hello, > > What would be the most efficient or 'clever' way to monitor a directory > for file additions/ modifications on windows? > > Currently I'm looping through the directory with a 1 sec delay. But > doesn't seem that clever. > > Guy This page might give you some hints: http://www.sysinternals.com/ntw2k/source/filemon.shtml -Don From steve at ninereeds.fsnet.co.uk Thu Mar 4 17:37:17 2004 From: steve at ninereeds.fsnet.co.uk (Stephen Horne) Date: Thu, 04 Mar 2004 22:37:17 +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> <4119c4e0d1dd457d3637e1316d5513ac@news.teranews.com> Message-ID: <22af40pkcecubm2o76a7g6aknj89rq1psu@4ax.com> On Thu, 04 Mar 2004 12:52:27 GMT, Dang Griffith wrote: >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. If you need >>something else, just define your own shortcut, don't deprecate a >>statement that is exactly what most users want. > >'print' is not a shortcut for 'sys.stdout.write'. >'print' is a statement. 'sys.stdout.write' is a function. >You can't define a shortcut for a statement. > --dang To the best of my knowledge, the word 'shortcut', is in common idiomatic use in English and refers to a quick and convenient means of achieving the same goal, by obvious analogy to the literal meaning of shortcut as a route to a given destination which is shorter than the normal route. The fact that in this case the means happens to be a statement as opposed to a function doesn't seem relevant to me. And the fact that programmers cannot define their own custom shortcuts in this way seems equally irrelevant. Actually, your protest seems analogous to saying 'that isn't a shortcut to the highstreet because its a back alley - the normal route is a proper road'. In literal shortcuts, the classification of roads, back alleys, dirt tracks etc is irrelevant, and I see no reason to fuss about technicalities such as the type of syntax in an idiomatic use. Similarly, I cannot build my own custom dirt tracks and back alleys, yet I can still refer to existing ones as shortcuts. If there was some specialist definition of the word 'shortcut' in Python I might agree that David had made a poor choice of words, but I'm not aware of any and even if there is that doesn't make normal English usage invalid. 'print' is a quick and convenient way of doing much the same thing as 'sys.stdout.write'. It's a shortcut. I honestly can't see any logic in claiming otherwise. Even those unwanted spaces can be seen as analogous to the muck you get all over your shoes in many literal shortcuts ;-) -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From mcfletch at rogers.com Wed Mar 17 21:05:27 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Wed, 17 Mar 2004 21:05:27 -0500 Subject: attributes of Python classes In-Reply-To: <3064b51d.0403171605.75ec1ba0@posting.google.com> References: <3064b51d.0403171605.75ec1ba0@posting.google.com> Message-ID: <405903E7.3060502@rogers.com> 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? > > I actually go a very different way. Use properties/descriptors for everything, with the properties declared directly in the class definition something like so: class SessionImporter( sessiondata.SessionData ): """Holder for importing data with an interactive session Primary purpose of this class is to provide a way to safely store partially-constructed records which may reference either database-resident records, or other partially-constructed records. """ sourceText = common.StringProperty( "sourceText", """Source of the data being imported""", defaultValue = "", ) newObjectID = common.IntegerProperty( "newObjectID", """Sequence for the newObjectID of newly created objects""", defaultValue = 0, ) newObjects = common.DictionaryProperty( "newObjects", """New objects, indexed by newObjectID""", ) rootObjects = common.ListProperty( "rootObjects", """IDs for each root-object to be stored""", ) and then use generic __init__ and the like that can take any set of specified properties. This way each attribute is fully documented, can have intelligently calculated defaults, can be initialised anywhere, etceteras, but there's not the huge collections of boilerplate initialisation, copying, etceteras code that's needed with bare attributes. The fact that it also allows for type-checking and coercian, and generic code for working with properties, is a nice side-effect :) There's still the possibility of having properties without values, but if that's undesired, just declare each with the default of None or "" or whatever you like *for that particular property*. Have fun, Mike _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From peter at engcorp.com Wed Mar 31 08:19:49 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 31 Mar 2004 08:19:49 -0500 Subject: GUI Frameworks in Python? In-Reply-To: References: <8089854e.0403300518.3a180414@posting.google.com> Message-ID: Andrew Malcolmson wrote: > GUI's seem to be more like documents than programs, so I wonder why > we're not considering more declarative type interface builders. Mitch Kapor talked about this, I believe, as being part of the Chandler project's approach, at the Birds-Of-a-Feather session on Chandler at PyCon last week. There might be notes about this somewhere, maybe in the docs on http://www.osafoundation.org/ -Peter From jzgoda at gazeta.usun.pl Sun Mar 7 02:12:37 2004 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Sun, 7 Mar 2004 07:12:37 +0000 (UTC) Subject: ready to use python, need help with GUI decision References: <20040303181544.GB74292@dogma.freebsd-uk.eu.org> <4046EE84.9080700@rebirthing.co.nz> <6Fu2c.2306$G3.18772@localhost> Message-ID: Christian Tismer pisze: > 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 have the very same opinion. Coming from Delphi, I found wxPython relatively easy and similar to some degree, but when I tried to do some less usual things with wxGrid, I've had hard time and spend many days looking for some specific answers. OTOH, I use PyQt for ~6 months and had no such problems, but the licensing restricts its use to X11 -- no big deal for me, but may be unacceptable for others. -- Jarek Zgoda http://jpa.berlios.de/ From gerrit at nl.linux.org Wed Mar 10 06:41:08 2004 From: gerrit at nl.linux.org (Gerrit) Date: Wed, 10 Mar 2004 12:41:08 +0100 Subject: PEP 328: Imports: Multi-Line and Absolute/Relative In-Reply-To: References: Message-ID: <20040310114108.GA4301@nl.linux.org> Aahz wrote: > * Long ``import`` statements can be difficult to write, requiring > various contortions to fit Pythonic style guidelines. > Instead, it should be possible to use Python's standard grouping > mechanism (parentheses) to write the ``import`` statement:: > > from Tkinter import (Tk, Frame, Button, Entry, Canvas, Text > LEFT, DISABLED, NORMAL, RIDGE, END) > > This part of the proposal already has BDFL approval. Why are the parentheses necessary? What's wrong with: from Tkinter import Tk, Frame, Button, Entry, Canvas, Text, LEFT, DISABLED, NORMAL ...where Python's normal indentation mechanism provides the grouping? Gerrit. -- Weather in Twenthe, Netherlands 10/03 11:25 UTC: 2.0?C light snow overcast wind 5.4 m/s NE (57 m above NAP) -- Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From jcarlson at nospam.uci.edu Thu Mar 18 22:35:27 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Thu, 18 Mar 2004 19:35:27 -0800 Subject: tkinter, threads and asyncore together In-Reply-To: References: Message-ID: duane voth wrote: >>#to control asyncore >>while 1: >> asyncore.loop(.1) >> if not fromgui.empty(): >> #handle messages from GUI > > The above doesn't work for me - asyncore.loop() always blocks. > The asyncore.poll(timeout=0.01) functions however works fine. Thus I have: > > while 1: > tkinter.dooneevent(tkinter.DONT_WAIT) > asyncore.poll(0.01) > Sorry about that, I meant poll, but my fingers said loop. I could have sworn that I mentioned it in my followup: http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&safe=off&frame=right&th=b2ddd726d59cdfe6&seekm=c0e4g5%24mug%241%40news.service.uci.edu#link5 - Josiah From cnoviello at hotmail.com Mon Mar 1 08:57:53 2004 From: cnoviello at hotmail.com (Carmine Noviello) Date: Mon, 1 Mar 2004 13:57:53 +0000 (UTC) Subject: [ANN]PyCrash 0.4pre1 released Message-ID: <7b3322fb289581d86ed7895c5fe3dd20.46955@mygate.mailgate.org> Hi, a new version of PyCrash is released new features and improvement.You can download it at: http://sourceforge.net/project/showfiles.php?group_id=98026&package_id=111026&release_id=220726 Changelog: * PyCrash now handles correctly new-style classes * Added onExceptionRaised() method to PyCrash class, which notifies when and how many times an uncaught exception is raised * Now all PyCrash classes inherit from "object" * Added new utils.Encrypt.py module, that contains the EncryptedPyCrash class. This class allows developers to automatically encrypt crash dumps using RSA algorithm, in order to protect sensible data * Added two scripts: keygen.py and decrypt.py that allow user to generate public/private key pair and decrypt file generated by EncryptedPyCrash class. Moreover, starting from release 0.2.1, PyCrash is distributed under the terms of LGPL software license. A next version of PyCrash Viewer will come soon, in order to support these new features. Enjoy! _______________________________________________________________________ About PyCrash Project: PyCrash is a Run-Time Exception Dumper which handles uncaught exceptions during the execution of Python programs and collects information about the program context. PyCrash can be very useful in report bug information, because the programmer can easily analyse the program execution context of the crashed application. Major information collected by PyCrash in the crash dump is: - Information about operating system, Python and Python Standard Library version and general information about the program that is crashed (e.g., program name and version, time at witch program started and ended, and so on) - Information about the uncaught exceptions, like the exception type, the context (namely method name) in which the exception occurred and the exception value - General information about variables state - Information about the stack of each thread, like the list of stack frames, the variables value in each stack frame, and so on - General information about source code, like variable and function position in source file that can be useful for the programmer to find quickly bugs in source tree The format of the crash dump file generated by PyCrash is XML, so the programmer can easily read this file to understand why the program is crashed. Now, is also available a GUI browser, named PyCrash Viewer, which allows developers to analyze quickly and easily PyCrash crash dump files in a graphical manner. Next version of PyCrash will include at least these features: * HTML dumper, that stores crash dump in HTML format rather then XML More information can be found at: http://www.pycrash.org Thanks!

PyCrash 0.4pre1 - a crash handler for Python written applications. (01-03-04)

-- Posted via Mailgate.ORG Server - http://www.Mailgate.ORG From me at privacy.net Thu Mar 11 06:34:43 2004 From: me at privacy.net (Heather Coppersmith) Date: 11 Mar 2004 06:34:43 -0500 Subject: Python style guidelines References: <3064b51d.0403101112.3449e987@posting.google.com> <405035a3$1@pfaff2.ethz.ch> Message-ID: On Thu, 11 Mar 2004 10:48:35 +0100, Josef Meile wrote: >> Is there something missing you think should be there? There's no particular >> reason a PEP needs to be continually updated. In particular, notions of >> good Python style haven't changed a lot over the past ten years. >> Skip > I agree, those are good guidelines, but I don't agree with: > - Don't compare boolean values to True or False using == (bool > types are new in Python 2.3): > No: if greeting == True: > Yes: if greeting: > What would happened if you do: >>>> 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. >>> if a.find( 'foo' ) == True: ... print 'foo was found' probably isn't what you want either. ;-) Regards, Heather -- Heather Coppersmith That's not right; that's not even wrong. -- Wolfgang Pauli From op73418 at mail.telepac.pt Wed Mar 24 20:16:23 2004 From: op73418 at mail.telepac.pt (Gonçalo Rodrigues) Date: Thu, 25 Mar 2004 01:16:23 +0000 Subject: Any way to get information from fun objects about their parameters? References: Message-ID: On Thu, 25 Mar 2004 00:49:57 GMT, Kenneth McDonald wrote: >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. > Check out the inspect module. In particular the getargspec function. With my best regards, G. Rodrigues From knight at baldmt.com Wed Mar 24 22:28:21 2004 From: knight at baldmt.com (Steven Knight) Date: 24 Mar 2004 19:28:21 -0800 Subject: Scons help! References: Message-ID: Anuj-- One of my searches turned up your message to comp.lang.python. It would have been more appropriate for you to send this message to the SCons users mailing list, users at scons.tigris.org. As to your specific problem: > opt = Options(None, ARGUMENTS) > opt.AddOptions( > EnumOption( > 'COMPILER', > 'The compiler you want to use', > 'cl', > ['cl','gcc'])) > > env = Environment(options=opt) > > CLDEBUGCPPFLAGS = r'/nologo /MDd /W3 /Gm /GR /GX /ZI /Od /D "_DEBUG" > /D "WIN32" /D "_WINDOWS" /D "BOBO_DLL_EXPORT" /D "USE_STANDARD_HEAP" > /YX /FD /c' > > env['BUILDERS']['cl'] = Builder(action = 'cl '+ CLDEBUGCPPFLAGS +' %SOURCE') > env['BUILDERS']['gcc'] = Builder(action = 'gcc -co %TARGET %SOURCE') > > > env['BUILDERS']['MyCompiler'] = env['BUILDERS'][env['COMPILER']] > > env.MyCompiler('myheap.cpp') > > > and here is the output. > > F:\work\src\mallocheap>scons > scons: Reading SConscript files ... > scons: done reading SConscript files. > scons: Building targets ... > cl /nologo /MDd /W3 /Gm /GR /GX /ZI /Od /D "_DEBUG" /D "WIN32" /D > "_WINDOWS" /D "BOBO_DLL_EXPORT" /D "USE_STANDARD_HEAP" > /YX /FD /c %SOURCE > Command line warning D4024 : unrecognized source file type '%SOURCE', > object file assumed > Command line warning D4027 : source file '%SOURCE' ignored > Command line warning D4021 : no action performed > scons: done building targets. First, it would help if you would use the correct SCons syntax for construction variable interpolation. The proper syntax is $SOURCE (note dollar sign), not %SOURCE. Second, trying to do this with custom Builders is making things much more difficult than they need to be. SCons already comes with canned tool specifications for Microsoft Visual C++ and GCC (and a host of other tools). It would be a lot easier to let SCons do the hard stuff for you. First, you need to account for the fact that the tool specification in SCons is named "msvc," not "cl". To allow your users to specify "COMPILER=cl" on the command line, you just need to add a dictionary to map "cl" to the correct SCons tool name of "msvc": opt.AddOptions( EnumOption( 'COMPILER', 'The compiler you want to use', 'msvc', ['msvc','gcc'], {'cl':'msvc'})) Then, you can let SCons initialize the Environment as follows, allowing it to expand $COMPILER to the specified value: env = Environment(options=opt, tools=['default', '$COMPILER']) After that, you can use env.Program(), env.Library(), etc. to build whatever you want. --SK From __peter__ at web.de Thu Mar 4 11:19:07 2004 From: __peter__ at web.de (Peter Otten) Date: Thu, 04 Mar 2004 17:19:07 +0100 Subject: How to catch a generic exception? References: Message-ID: Boogie El Aceitoso wrote: > How can I catch a generic exception (without knowing a priori what > exception it will be)? If you catch the generic Exception, there is a small chance that your except suite will be bypassed: >>> try: ... raise "yes, it's deprecated" ... except Exception, e: ... print "will we ever see this?" ... Traceback (most recent call last): File "", line 2, in ? yes, it's deprecated This seems to work: >>> try: ... raise KeyError ... except: ... print sys.exc_info() ... (, , ) >>> try: ... raise "so what" ... except: ... print sys.exc_info() ... ('so what', None, ) >>> Not very elegant though. But then, not knowing what to catch is something that should be avoided in the first place. Peter From mwilson at the-wire.com Fri Mar 12 10:29:18 2004 From: mwilson at the-wire.com (Mel Wilson) Date: Fri, 12 Mar 2004 10:29:18 -0500 Subject: Deprecating reload() ??? References: <2j12505t4oaniqq7607t3pekulm0e979cu@4ax.com> Message-ID: In article <2j12505t4oaniqq7607t3pekulm0e979cu at 4ax.com>, David MacQuigg wrote: >On Thu, 11 Mar 2004 15:10:59 -0500, "Ellinghaus, Lance" > wrote: > >>> > Other surprises: Deprecating reload() >> >>>Reload doesn't work the way most people think >>>it does: if you've got any references to the old module, >>>they stay around. They aren't replaced. >> >>>It was a good idea, but the implementation simply >>>doesn't do what the idea promises. >> >>I agree that it does not really work as most people think it does, but how >>would you perform the same task as reload() without the reload()? > >Seems like reload() could be *made* to work by scanning currently >loaded modules for all references to objects in the reloaded module, >and resetting them to the new objects. If an object is missing from >the new module, throw an exception. I don't quite get this. I don't see objects _in_ a module. I see objects referenced from the modules namespace, but they can be referenced from other modules' namespaces at the same time. Who is to say which module the objects are *in*? e.g. (untested) #=============================== "M1.py" f1 = file ('a') f2 = file ('b') #=============================== "main.py" import M1 a_file = M1.f1 another = file ('c') M1.f2 = another reload (M1) Regards. Mel. From jcarlson at uci.edu Mon Mar 29 23:35:41 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Mon, 29 Mar 2004 20:35:41 -0800 Subject: histogram type thingy for (unique) dict items In-Reply-To: References: <5e8bd451.0403291801.51071ca2@posting.google.com> Message-ID: John hit it on the nose. That is how I would do it. - Josiah From fumanchu at amor.org Fri Mar 26 16:25:37 2004 From: fumanchu at amor.org (Robert Brewer) Date: Fri, 26 Mar 2004 13:25:37 -0800 Subject: python & mysql probelm Message-ID: james blair wrote: > I am having a problem executing following query: > cursor.execute("select * from projects where projectid between '%s' > and '%s'"%(id1,id2)) > But say if i have projectid's from 1 to 20 in database & if i give the > project range 1 to 2 then it gives me the result 1,2,11,12,13,14..... > When I execute this query in mysql i.e > select * from projects where projectid between 1 and 2,I get the > correct result. > I also tried doing > cursor.execute("select * from projects where projectid between '%s' > and '%s'"%(int(id1),int(id2)) > but no success > What should I do?? Try dropping the single quotes around each %s cursor.execute("select * from projects where projectid " "between %s and %s" % (id1, id2)) FuManChu From bogus at bogus.net Tue Mar 2 08:36:30 2004 From: bogus at bogus.net (Paul McGuire) Date: Tue, 02 Mar 2004 13:36:30 GMT Subject: xmlrpclib timeouts References: Message-ID: "p2esp" wrote in message news:mailman.19.1078223070.12614.python-list at python.org... > 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. You are better off turning your synchronous "wait forever" client into an asynchronous "wait for callback" client. Have your client create a listener object, and pass a reference to this object as part of your long-running method call. This allows the XMLRPC call to complete, since it is a brief submission of work, instead of waiting for the work to complete. When the server is finished, it uses the callback object to send the results back to the client. This does make things more complicated - the server has to save the callback object so that it knows who to send the results to. The client is probably going to be multithreaded, so that the client isn't blocked while waiting for the response (although, given your initial design, this may not bother you). AND, the server may have to do some exception recovery (or at least logging), if the client has disconnected before it was able to send back results. Another alternative is the "job ticket" model. In this case, the client calls the server just as you have it coded now, but the return value is some form of job ticket, or job id. The client then uses this id to periodically poll the server to see if the results are ready yet. Once the server replies that results are ready, the client uses the job id as the argument to a getResults() call on the server. This solution is simpler to code, but may have implications for network loading (lots of extra polling messages, as clients repeatedly check if their results are ready), and the server has to handle the case of clients that disconnect and never pick up their laundry, um, that is, results. There are a number of good reference books about client/server programming. One that I like is "Advanced CORBA Programming with C++" by Henning and Vinoski. Although it uses CORBA and C++ as its implementation platform, so you'll have to map the examples to Python and XMLRPC, the concepts are much the same. And don't be too quick to skip the memory management discussions - even though Python does its own memory management (in place of C++'s new/delete model), it is easy to have distributed memory leaks between client and server. (I have seen a Java memory leak happen this way, even though Java uses a garbage collection memory management model too.) Another good resource is Douglas Schmidt's set of web pages at Washington Univ of St. Louis - see http://www.cs.wustl.edu/~schmidt/patterns.html for some distributed system patterns papers. Good luck - distributed systems can be nerve-wracking, but they are also some of the really cool problems to solve. -- Paul From simoninusa2001 at yahoo.co.uk Tue Mar 30 22:54:41 2004 From: simoninusa2001 at yahoo.co.uk (simo) Date: 30 Mar 2004 19:54:41 -0800 Subject: Import config into global space? Message-ID: <30260531.0403301954.7905a3b@posting.google.com> I'm writing a module, and it's getting too big to cope with as it has a lot of configuration in it - constants, dictionaries etc; it'd be nice to externalise this and keep my module down to just classes/defs etc. What I'd like to do is have myprog.py import config.py and be able to reference the configuration variables globally - i.e. I could just reference myvar instead of config.myvar So I'd have something like this: config.py ========= ID_TOOLBAR = 105 myprog.py ========= import config print ID_TOOLBAR result ====== >> 105 It doesn't seem to work though, as global is limited to modules as far as I know. Any ideas how to do this, it's basically like a require or #include in Perl/C... From gerrit at nl.linux.org Tue Mar 30 07:58:44 2004 From: gerrit at nl.linux.org (Gerrit) Date: Tue, 30 Mar 2004 14:58:44 +0200 Subject: A 'Python like' language In-Reply-To: <37S9c.58035$cx5.39835@fed1read04> References: <40645d8f$0$10775$afc38c87@news.easynet.co.uk> <1068up4kn49778@news.supernews.com> <58cb60lmovocadg9p3ghu39t4ga343gfvd@4ax.com> <37S9c.58035$cx5.39835@fed1read04> Message-ID: <20040330125844.GB27344@nl.linux.org> Mark Hahn wrote: > But everything in Prothon is subject to change until > 7/04. Is that April the 7th or July the 4th? Gerrit. -- Weather in Twenthe, Netherlands 30/03 13:25 UTC: 15.0?C wind 5.4 m/s E (57 m above NAP) -- here will soon be Gerrit Holl's very own signature From max at NcOviSsPiAoMntech.com Mon Mar 1 10:22:00 2004 From: max at NcOviSsPiAoMntech.com (max khesin) Date: Mon, 01 Mar 2004 15:22:00 GMT Subject: [ANN]PyCrash 0.4pre1 released In-Reply-To: <7b3322fb289581d86ed7895c5fe3dd20.46955@mygate.mailgate.org> References: <7b3322fb289581d86ed7895c5fe3dd20.46955@mygate.mailgate.org> Message-ID: Great! And thanks for the license update, I was waiting to use this at work! Carmine Noviello wrote: > Hi, > a new version of PyCrash is released new features and improvement.You > can download it at: > > > http://sourceforge.net/project/showfiles.php?group_id=98026&package_id=111026&release_id=220726 > > Changelog: > > * PyCrash now handles correctly new-style classes > * Added onExceptionRaised() method to PyCrash class, which notifies when > and how many times an uncaught exception is raised > * Now all PyCrash classes inherit from "object" > * Added new utils.Encrypt.py module, that contains the > EncryptedPyCrash class. This class allows developers to > automatically encrypt crash dumps using RSA algorithm, in order to > protect sensible data > * Added two scripts: keygen.py and decrypt.py that allow user to > generate public/private key pair and decrypt file generated by > EncryptedPyCrash class. > > Moreover, starting from release 0.2.1, PyCrash is distributed under the > terms > of LGPL software license. > > A next version of PyCrash Viewer will come soon, in order to support > these > new features. > > Enjoy! > _______________________________________________________________________ > About PyCrash Project: > PyCrash is a Run-Time Exception Dumper which handles uncaught exceptions > during the execution of Python programs and collects information about > the program context. PyCrash can be very useful in report bug > information, > because the programmer can easily analyse the program execution context > of the crashed application. > > Major information collected by PyCrash in the crash dump is: > > - Information about operating system, Python and Python Standard > Library version and general information about the program that is > crashed (e.g., program name and version, time at witch program > started and ended, and so on) > > - Information about the uncaught exceptions, like the exception type, > the context (namely method name) in which the exception occurred and > the exception value > > - General information about variables state > > - Information about the stack of each thread, like the list of stack > frames, the variables value in each stack frame, and so on > > - General information about source code, like variable and function > position in source file that can be useful for the programmer to find > quickly bugs in source tree > > The format of the crash dump file generated by PyCrash is XML, so the > programmer can easily read this file to understand why the program is > crashed. > > Now, is also available a GUI browser, named PyCrash Viewer, which allows > developers to analyze quickly and easily PyCrash crash dump files in a > graphical manner. > > Next version of PyCrash will include at least these features: > * HTML dumper, that stores crash dump in HTML format rather then > XML > > More information can be found at: > > http://www.pycrash.org > > Thanks! > >

PyCrash 0.4pre1 - a crash > handler for Python written applications. (01-03-04)

> > From gandalf at geochemsource.com Wed Mar 17 08:00:49 2004 From: gandalf at geochemsource.com (Gandalf) Date: Wed, 17 Mar 2004 14:00:49 +0100 Subject: popen problem Message-ID: <40584C01.6030602@geochemsource.com> Hi All! I don't know if this is a Python problem or not. Here is a snippet: import os TERM='\n\r\n\r' cmd = 'cu -l /dev/cuaa0 -s9600' pop = os.popen4(cmd,1) pop[0].write('AT'+TERM) # Ping modem def readln(): buffer = '' while True: c = pop[1].read(1) if c == '\n': return buffer elif (c != '\r') and not (c in TERM): buffer += c pop[1].readln() pop[1].readln() pop[1].readln() Here is the problem: on FreeBSD, this works fine. The last readln() calls will print this: 'Connected.' '' 'OK' But if I try to do the same on Linux (with /dev/ttyS0 instead of /dev/cuaa0) I get this: 1. The first read blocks. 2. When I do 'killall cu' in another shell, it starts to read this: '\0x7Connected.' 'cu: Got interrupt signal' It seems that the first line ('Connected.') if buffered somewhere. I guess 'OK' is also buffered but it is not read because of the interrup. Is it a problem with Linux of Python? Or is it a big difference between /dev/ttyS0 and /dev/cuaa0? Thanks in advance, G From bitbucket at safe-mail.net Mon Mar 1 20:48:17 2004 From: bitbucket at safe-mail.net (poiboy) Date: 1 Mar 2004 17:48:17 -0800 Subject: vim & python References: <221dd125.0403011151.504ce09d@posting.google.com> Message-ID: 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. From peter at engcorp.com Thu Mar 18 22:02:56 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 18 Mar 2004 22:02:56 -0500 Subject: services In-Reply-To: References: Message-ID: Laurent Vincelette wrote: > I have a python script (file start with #!/usr/bin/python) that use > xmlrpclib to lessen and respond on port:8000. The problem is when I > close the shell (bash in remote with putty) the script stop to work. I > try to start it in backgroud with & but it dosent work. Finally I copy > and I try to modify the /etc/init.d/crond to start the script in > services (with start-stop-demon but I have the same problem... When I > close putty the script stop. > > Someone have a idea? Redirect stdout and stderr to /dev/null. I'm not sure which of these -- perhaps both -- is necessary, but doing both certainly works... That is, this should work: yourscript.py >/dev/null 2>/dev/null & -Peter From danb_83 at yahoo.com Wed Mar 17 02:39:51 2004 From: danb_83 at yahoo.com (Dan Bishop) Date: 16 Mar 2004 23:39:51 -0800 Subject: Inconsistency in Python's Comparisons References: <4057B2A4.F9EC49DD@alcyone.com> Message-ID: Erik Max Francis wrote in message news:<4057B2A4.F9EC49DD at alcyone.com>... > Dietrich Epp wrote: > > > This could cause sorting functions to malfunction. > > [example of nontransitive "<"] > > Do you have an example of this that doesn't involve comparisons between > different types? # This shouldn't count, for obvious reasons. But what the heck... class ContrivedExample(object): def __init__(self, n): self.__n = n def __cmp__(self, other): if self.__n == other.__n: return 0 elif (self.__n - other.__n) % 3 == 1: return -1 else: return 1 paper = ContrivedExample(0) rock = ContrivedExample(1) scissors = ContrivedExample(2) print paper < scissors print scissors < rock print rock < paper From khawaja_shahzads at hotmail.com Wed Mar 31 10:37:05 2004 From: khawaja_shahzads at hotmail.com (Khawaja Shahzad Sadiq Butt) Date: Wed, 31 Mar 2004 10:37:05 -0500 Subject: Need Help with pymssql Message-ID: Hi, I am trying to connect to sql server 2000 on win xp. I am using a python extension called. pymssql but it is giving me this errror: Traceback (most recent call last): File "C:\Python22\Lib\site-packages\Pythonwin\pywin\framework\scriptutils.py", line 310, in RunScript exec codeObject in __main__.__dict__ File "C:\syndication\db_1.py", line 3, in ? con = pymssql.connect(host='abc',user='ag',password='ag',database='agl') File "C:\Python22\Lib\site-packages\pymssql.py", line 277, in connect con = _mssql.connect(dbhost, dbuser, dbpasswd,dbport) error: Can't Connecting MSSQL Server Everything like server username and password are correct. can someone help me . There is almost no help available on sourceforge for this. Any help would be appreciated. Please reply, Regards Khawaja Shahzad _________________________________________________________________ Free up your inbox with MSN Hotmail Extra Storage. Multiple plans available. http://join.msn.com/?pgmarket=en-us&page=hotmail/es2&ST=1/go/onm00200362ave/direct/01/ From http Sat Mar 13 03:19:13 2004 From: http (Paul Rubin) Date: 13 Mar 2004 00:19:13 -0800 Subject: Sorting Driving Crazy: URGENT: PLEASE HELP References: Message-ID: <7xn06lf9by.fsf@ruckus.brouhaha.com> dont bother writes: > When I print x and feature_vectors[x] I get some of > the entries which are not in the increasing order. (keys shown are: 22836 22840 22841 22842 22844 22846 2357 3105 3117 3675 4280) Those keys are sorted correctly. You have entered them in the dictionary as strings, not integers. '22836' comes before '4280' just like 'apple' comes before 'pear'. From mogmios at mlug.missouri.edu Tue Mar 30 14:19:21 2004 From: mogmios at mlug.missouri.edu (Michael) Date: Tue, 30 Mar 2004 11:19:21 -0800 Subject: Python Documentation Blows! In-Reply-To: <20040330161531.GA17112@vulcan.cprogrammer.org> References: <40699A31.8000708@yahoo.com> <20040330161531.GA17112@vulcan.cprogrammer.org> Message-ID: <4069C839.6020109@mlug.missouri.edu> ># It is a shame that the only limitation of a great is documentation. > >Maybe I'm misunderstanding, but if you are implying that good docs >make a great language, you're mistaken. After all, you're advocating >Java in a python forum. I do agree that java has good documentation, >but I not think Java should be considered "great" in any capacity. If >the python docs are so bad, you should be specific about how and why. >Python is great for countless other reasons which are unrelated to >documentation. I think the python docs are exceptional. > > IMO, PHP has the best documentation of basic language functionality. That certainly doesn't mean I think it is the best language. I think Python's library reference documentation is very good but the documentation of the basic language itself is sometimes lacking or confussing or just hard to find. Especially given that Python is somewhat unique in many ways and has certain gotchas that tend to confuse experienced programmers that are new to Python. Also it seems that certain popular 3rd party modules should be more closely documented with the library reference. Twisted would be a good example. Also it'd be nice to see a collection of short example programs that make use of various functionality and libraries available from Python. I'd say that good docs don't make a great language but bad docs can ruin a great language. Python's docs aren't bad but they could be a lot better. wxPython would be my example of some of the worst (non-existant) documentation available for Python while PyGame would be my example of some of the best. From deets_noospaam at web.de Mon Mar 1 17:14:53 2004 From: deets_noospaam at web.de (Diez B. Roggisch) Date: Mon, 01 Mar 2004 23:14:53 +0100 Subject: Function calling another function References: Message-ID: > My question is surely a basic one, but somehow, I am not able to figure it > out. > When I execute satish.py, main() executes. I was expecting y() to execute > first and then x() and then y() again. I wanted function x() to be capable > of calling function y(). With this form of code, seems like function x() > is not recognising function y(). Is there any sort of import or anything > else that I can do here ?? Works for me: def main(): y() x() def y(): print "y" def x(): print "x" y() main() gives me: x y x As expected. -- Regards, Diez B. Roggisch From lbates at swamisoft.com Thu Mar 4 16:03:47 2004 From: lbates at swamisoft.com (Larry Bates) Date: Thu, 4 Mar 2004 15:03:47 -0600 Subject: Python Database Driven Web Development References: Message-ID: You might want to look at Zope www.zope.org Not required, but might save you a lot of time and effort. -Larry "Maru, Mulugeta" wrote in message news:mailman.4.1078428023.679.python-list at python.org... What do I need other than Python, Apache, and MySQL to develop a database driven intranet? Do I need to use any framework or application server? If I do please kindly direct me where to go. Many thanks. MM VisionTV proudly celebrates 15 years as Canada's multi-faith television network. From http Tue Mar 30 17:49:45 2004 From: http (Paul Rubin) Date: 30 Mar 2004 14:49:45 -0800 Subject: A 'Python like' language References: <40645d8f$0$10775$afc38c87@news.easynet.co.uk> <1068up4kn49778@news.supernews.com> <58cb60lmovocadg9p3ghu39t4ga343gfvd@4ax.com> <258fd9b8.0403301151.179e9190@posting.google.com> <4kmac.74887$cx5.73453@fed1read04> Message-ID: <7xoeqegdbq.fsf@ruckus.brouhaha.com> "Mark Hahn" writes: > Any ideas on how to implement assignment expressions and not have if x = y: > ambiguity problems? > > I've considered using a different syntax for the expression version of "=", > such as ":=" or even left.replace!(right). := is the variant discussed most often around here. left.replace!(right) only works if left is already bound to an object. From glingl at aon.at Thu Mar 4 14:27:31 2004 From: glingl at aon.at (Gregor Lingl) Date: Thu, 04 Mar 2004 20:27:31 +0100 Subject: how fast is Python code - another detail In-Reply-To: <20040304190419.20224.qmail@web61004.mail.yahoo.com> References: <20040304190419.20224.qmail@web61004.mail.yahoo.com> Message-ID: <40478323.4060604@aon.at> Aloysio Figueiredo schrieb: >> if sig not in d.keys(): >> >> >> > >Have you tried > > if sig not in d.iterkeys(): > >? > Yes. It's only slightly faster that if sig not in d.keys(), i. e. still much slower than if sig in d by a factor of 180 for a 20000-item list. Gregor >Aloysio > > From skip at pobox.com Fri Mar 12 09:26:41 2004 From: skip at pobox.com (Skip Montanaro) Date: Fri, 12 Mar 2004 08:26:41 -0600 Subject: Xemacs syntax highlighting In-Reply-To: References: <1d17eeb7.0403111721.7aae9a76@posting.google.com> Message-ID: <16465.51361.967348.648145@montanaro.dyndns.org> Skip> name is a reddish color. Strings are green. Comments are blue. Skip> None of the colors are too saturated though so even though it Skip> sounds garish it's not too hard on the eyes. The Ville> Aren't the actual, physical colors more of a global emacs issue, Ville> rather than an issue w/ python-mode.el? Ah, perhaps you're right. In which case the OP probably just needs to upgrade to a recent version of XEmacs. ;-) Ville> I'm using color-theme.el myself: Ville> http://www.emacswiki.org/cgi-bin/wiki/ColorTheme Ville> I urge everyone to check it out, esp. if you spend >= 8 hours a Ville> day staring at emacs windows :). Thanks for the suggestion. Got a favorite theme for Python bufferrs or do you rotate through a small set of themes to give your eyes a break? Skip From max at alcyone.com Fri Mar 19 04:50:55 2004 From: max at alcyone.com (Erik Max Francis) Date: Fri, 19 Mar 2004 01:50:55 -0800 Subject: Best way to convert string a to utf-* References: Message-ID: <405AC27F.CCCE7527@alcyone.com> Oliver Kurz wrote: > could someone tell me the best way to convert a string to utf, for > example > to utf-8? > > The problem: I have no controll about the source where the string > comes > from. It could have any possible characterset. And I have to convert > it for > example to utf-8. If the format is not already a Unicode string, you really can't know what encoding it's in. To convert it to UTF-8 (or UTF-16 or UTF-32), you really must know what format it's in to begin with or otherwise you're stuck. -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE \__/ He who conceals his disease cannot expect to be cured. -- (an Ethiopian proverb) From pxlpluker at cfl.rr.com Thu Mar 4 09:19:44 2004 From: pxlpluker at cfl.rr.com (pxlpluker) Date: Thu, 04 Mar 2004 09:19:44 -0500 Subject: [Tutor] Sightly off topic - download file name In-Reply-To: <4041DE9C.9070201@pusspaws.net> References: <4041DE9C.9070201@pusspaws.net> Message-ID: <40473B00.2080802@cfl.rr.com> 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. Fred From mambuhl at earthlink.net Wed Mar 3 16:13:53 2004 From: mambuhl at earthlink.net (Martin Ambuhl) Date: Wed, 03 Mar 2004 21:13:53 GMT Subject: OFF-TOPIC:: Why Lisp is not my favorite programming language In-Reply-To: <165b3efa.0403030443.4d591f04@posting.google.com> References: <165b3efa.0403030443.4d591f04@posting.google.com> Message-ID: 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. I fail to see why anyone should give a rat's ass about what someone hiding behind "nobody_u_should_no at yahoo.com (nobody)" has to say about anything. "Nobody"'s opinions about LISP, C, or the color of bananas is completely worthless. When you have the cajones to stand behind your opinions, you might be paid attention to. From miki.tebeka at zoran.com Thu Mar 4 07:48:12 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Thu, 04 Mar 2004 14:48:12 +0200 Subject: Calling C programs In-Reply-To: References: Message-ID: <4047258C.9080808@zoran.com> Hello Colin, > 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? from os import popen print popen("/tmp/hello").read() See http://www.python.org/doc/current/lib/os-process.html HTH. Miki From tim.one at comcast.net Tue Mar 2 21:38:02 2004 From: tim.one at comcast.net (Tim Peters) Date: Tue, 2 Mar 2004 21:38:02 -0500 Subject: E-mail account disabling warning. In-Reply-To: Message-ID: It shouldn't need to be said, but if you get a message that looks like this: > Dear user of Python.org gateway e-mail server, > > We warn you about some attacks on your e-mail account. Your > computer may contain viruses, in order to keep your computer and > e-mail account safe, please, follow the instructions. > > For details see the attached file. > > For security reasons attached file is password protected. The > password is "28132". > > Cheers, > The Python.org team > http://www.python.org 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 From fperez528 at yahoo.com Tue Mar 9 12:57:18 2004 From: fperez528 at yahoo.com (Fernando Perez) Date: Tue, 09 Mar 2004 10:57:18 -0700 Subject: os.popen() failing under ipython+cygwin, I'm stumped. References: Message-ID: Jason Tishler wrote: > Fernando, > > On Mon, Mar 08, 2004 at 09:01:05AM -0700, Fernando Perez wrote: >> Any help would be much appreciated. > > Does rebasing your Cygwin installation help? > > http://www.tishler.net/jason/software/rebase/rebase-2.2.README Thanks again, Jason. As Thorsten reported, the 'rebasing' business (I still don't know what that means :) did help. Best, Fernando. From ville at spammers.com Tue Mar 9 13:22:29 2004 From: ville at spammers.com (Ville Vainio) Date: 09 Mar 2004 20:22:29 +0200 Subject: Python scripting for GNumeric References: Message-ID: >>>>> "Niklaus" == NWirth writes: Niklaus> Python) compared with Excel and VBA? Is it possible to Niklaus> run Gnumeric using Python extensions on Windows? Is it possible to run Gnumeric on Windows at all? ISTR that it's not possible yet. -- Ville Vainio http://tinyurl.com/2prnb From xpythonist at yahoo.com.br Wed Mar 3 14:50:20 2004 From: xpythonist at yahoo.com.br (=?iso-8859-1?q?Aloysio=20Figueiredo?=) Date: Wed, 3 Mar 2004 16:50:20 -0300 (ART) Subject: insertion in lists In-Reply-To: Message-ID: <20040303195020.59810.qmail@web61003.mail.yahoo.com> I'm not sure if I understand your question, but I think you forgot to make list[0] a list itself: >>> element = 1 ## 1 or whatever >>> list = [] >>> list.insert(0, []) >>> list[0].insert(0, element) >>> list[0][0] 1 Now, we have list[0][0] = element... Aloysio --- Lupe escreveu: > hi, > > 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. > > if I have: > element > > list [0] > and want to have list[0][0] > list[0][1] > > how can I insert the element to that list[0][0], for example? > just to put things clearer, if I wanted to insert the element in > list[0] I > could do list.insert(0,element). > > I've tried list[0].insert(0,element) but gives me an error. > > > Luis > -- > http://mail.python.org/mailman/listinfo/python-list ______________________________________________________________________ Yahoo! Mail - O melhor e-mail do Brasil! Abra sua conta agora: http://br.yahoo.com/info/mail.html From wenming_hu2002 at hotmail.com Fri Mar 5 03:48:14 2004 From: wenming_hu2002 at hotmail.com (wenming_hu) Date: Fri, 5 Mar 2004 16:48:14 +0800 Subject: how to write python server page by using mod_python? References: Message-ID: I'm sorry to bother you again. i think you must be a cool man for using mod_python. my os environment: operation system is windows 2000 server apache 2.0.48 mod_python-3.1.2b.win32-py2.3.exe python2.3.3 according to your guide, i have succeed in configuring the apache, as the following: LoadModule python_module modules/mod_python.so #----interface.conf---- Alias /web f:/psp_site AddHandler python-program .htm PythonHandler dispatch PythonDebug On DirectoryIndex welcome.htm #----end interface.conf---- And I have two files , nothing else but dispatch.py and welcome.htm, in the folder f:\pspsite, the dispathch.py has the following code: # dispatch.py from mod_python import apache def handler(req): return apache.OK the other file "welcome.htm" is: welcome to this site!

Hello, world! This is a new site!

Then i restart the apache, enter the URL "http://localhost/web" in my web browser, but get nothing. i want to access welcome.htm when entering the url http://localhost/web that is to say, welcome.htm is the default page of the site. how to get the above effect? From mf at orase.com Wed Mar 31 12:33:45 2004 From: mf at orase.com (Markus Franz) Date: Wed, 31 Mar 2004 19:33:45 +0200 Subject: Fetching websites with Python Message-ID: Hi. How can I grab websites with a command-line python script? I want to start the script like this: ./script.py ---xxx--- http://www.address1.com http://www.address2.com http://www.address3.com The script should load these 3 websites (or more if specified) in parallel (may be processes? threads?) and show their contents seperated by ---xxx---. The whole output should be print on the command-line. Each website should only have 15 seconds to return the contents (maximum) in order to avoid a never-ending script. How can I do this? Thanks. Yours sincerely Markus Franz From michele.simionato at poste.it Sat Mar 27 13:53:06 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 27 Mar 2004 10:53:06 -0800 Subject: A 'Python like' language References: <40645d8f$0$10775$afc38c87@news.easynet.co.uk> <95aa1afa.0403262049.4b2a6f78@posting.google.com> Message-ID: <95aa1afa.0403271053.5c866d75@posting.google.com> David MacQuigg wrote in message news:... > This is a small problem with a simple solution (see my earlier post), > and one that will retain the advantages of tabs. Just to be clear, the previous one was a rethorical question. Use any editor with decent Python support and pressing the tab key will insert four spaces, indenting your code just fine. Even if you are using Notepad on Windows, it is best if you use spaces, otherwise you risk to be beaten by Outlook Express the Tabs Eater. Plus, the size of a tab (8 spaces? 4 spaces?) and the output you get is totally dependent on the system you are using. Seriously, even doing an effort I cannot imagine a single advantage of tabs. Tabs are evil. They are an historical wart, they should just be banned from modern computing. Michele Simionato From mwh at python.net Tue Mar 16 07:50:56 2004 From: mwh at python.net (Michael Hudson) Date: Tue, 16 Mar 2004 12:50:56 GMT Subject: newbie question: nop statement for try/except References: Message-ID: leo writes: > 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' Cheers, mwh -- As it seems to me, in Perl you have to be an expert to correctly make a nested data structure like, say, a list of hashes of instances. In Python, you have to be an idiot not to be able to do it, because you just write it down. -- Peter Norvig, comp.lang.functional From missive at frontiernet.net Mon Mar 8 17:28:13 2004 From: missive at frontiernet.net (Lee Harr) Date: Mon, 08 Mar 2004 22:28:13 GMT Subject: curses bkgd problem References: Message-ID: <1s63c.13$GX5.8@news01.roc.ny> On 2004-03-08, Gandalf wrote: > > Hi Python Gurus! > > I read the documentation on the python curses module and I started a new > application. > So far I did this: > > stdscr = curses.initscr() # Get standard screen > curses.start_color() # Uses colors > stdscr.bkgd(' ',curses.COLOR_BLUE ) # Set background of the main window > curses.noecho() # Do not echo input > curses.cbreak() # CBreak mode: process keys immediately (no ENTER) > stdscr.keypad(1) # keypad mode: parse control sequences > stdscr.redrawwin() > stdscr.refresh() > > However, it is displaying $ characters in black instead of displaying a > blue background full of spaces. > This must be a problem with my bkgd call since this works fine: > > curses.init_pair(1, curses.COLOR_RED, curses.COLOR_WHITE) > stdscr.addstr(0, 0, curses.longname(), curses.color_pair(1) ) > stdscr.refresh() > > (writes "X11$terminal$emulator" in the top left corner in red and white). > Please help me out with a few lines of code. > I must have had some trouble setting a background color also, as my curses project has a module I called ColorFill.py ... import curses def colorFill(scr, pair): if curses.has_colors(): scr.attron(curses.color_pair(pair)) (h, w) = scr.getmaxyx() for y in range(h-1): for x in range(w-1): scr.move(y, x) scr.addch(' ') From frithiof.jensen at removethis.ted.ericsson.dk Mon Mar 8 11:25:01 2004 From: frithiof.jensen at removethis.ted.ericsson.dk (Frithiof Andreas Jensen) Date: Mon, 8 Mar 2004 17:25:01 +0100 Subject: Gadfly ???? References: <8089854e.0403040124.1c6bd929@posting.google.com> <8089854e.0403080014.4e03b516@posting.google.com> Message-ID: "Fuzzyman" wrote in message news:8089854e.0403080014.4e03b516 at posting.google.com... > Because I *won't* be allowed to install anything other than python > scripts on the server........... That sounds very odd: A Malicious Python script can do just as much evil as a C++ executable only in fewer lines of code! Maybe it would be easier to get hold of a dedicated server than to work around the idiosynchracies(?) of the IT department(?) managing the server? The ressource requirements of PSQL + Python are small - almost any junk PC could work for a Proof-of-Concept. From frnakd at aol.com Fri Mar 5 15:05:34 2004 From: frnakd at aol.com (fd) Date: 5 Mar 2004 12:05:34 -0800 Subject: file.readline() after a seek() breaking up lines Message-ID: I am a newcomer to python, and I hope someone can point out to me why my calls to file.readline() (after a seek) are returning mangled lines. Calling readline twice after each seek, eliminates the problem. Is seek(), like next(), incompatible with readline()? If so, how should I be doing do random access line reads? Thanks FD # Sample code for readline() problem # platform: windows xp # python version 2.3 # The source file is just a list of words - one word per line, # saved as ANSI from notepad from string import rstrip from random import randrange words = file('C:\\swap\\english.txt', 'r') words.seek(-1,2) endAt = words.tell() startAt = 1 for w in range(0, 50): words.seek(randrange( startAt, endAt ) , 0) #words.readline() #uncomment this and lines are intact print words.readline() words.close() From ngps at netmemetic.com Thu Mar 25 03:45:57 2004 From: ngps at netmemetic.com (Ng Pheng Siong) Date: 25 Mar 2004 08:45:57 GMT Subject: pyOpenSSL is dead or not? References: <405fe1b6$0$298$636a15ce@news.free.fr> Message-ID: According to Trevor Perrin : > Roger Binns wrote: > > 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. Cool! -- Ng Pheng Siong http://firewall.rulemaker.net -+- Firewall Change Management & Version Control http://sandbox.rulemaker.net/ngps -+- Open Source Python Crypto & SSL From jacek.generowicz at cern.ch Mon Mar 15 03:47:22 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 15 Mar 2004 09:47:22 +0100 Subject: Static Typing in Python References: Message-ID: Premshree Pillai writes: > --- srijit at yahoo.com wrote: > Hello, > > Try Traits > > (http://www.scipy.org/site_content/traits). > > > > Regards, > > Srijit > > Who says Python is not strongly typed? Too many people, who don't know what they're talking about (including the authors of the traits package, it seems). > The problem I am facing is that Python is also dynamically typed, > and I want static typing. No you don't. You really, really don't :-) From max at alcyone.com Thu Mar 18 18:25:08 2004 From: max at alcyone.com (Erik Max Francis) Date: Thu, 18 Mar 2004 15:25:08 -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> Message-ID: <405A2FD4.E8713170@alcyone.com> Axel Boldt wrote: > ...and then it can run into an infinite loop. I explained that for the > example s==w in the part you deleted. The recursion does not always > have a base case; the rule does not always give a definite truth > value. But the == operator doesn't run into an infinite loop, so this is much ado about nothing. > ... i.e. such a fun case. If there really is an implementation > dependency hidden in something as fundamental as == for lists, that'd > better be mentioned in the language reference. I don't know what you're talking about here. The behavior you saw with your s == w example is completely consistent with Python's definition of equality and Python's definition of equal sequences. You have some additional equivalence in your mind that simply does not apply to Python. > > How can you define the value of an arbitrary object without > > reference to > > its internal structure? > > Well, you claim that s and w have the same value yet different > internal structure, so you must work with some definition of "value" > that's different from internal structure. I don't know what it is, and > the language reference doesn't fully specify it. 1 and 1.0 have different internal structure, but they're equal. This is an obvious existence proof that Python simply does not follow the equivalence that you're thinking of. Equality does _not_ indicate equivalence in internal structure in Python. This is especially true in Python where users can define their own equality behavior, so you can make it whatever you want -- you can make your own instance that compares equal (or unequal) with absolutely everything. If 1 == 1.0 didn't convince you, surely this will convince you that equality and equivalence in internal structure are not related in Python. > I.e., I'm interesting in a function val : lists -> strings with the > property val(l1) == val(l2) iff l1 == l2. That would also considerably > clarify the semantics of == for lists, which I still don't understand. Why are you interested in such a function? -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE \__/ I do not promise to consider race or religion in my appointments. I promise only that I will not consider them. -- John F. Kennedy From fumanchu at amor.org Sun Mar 21 17:15:25 2004 From: fumanchu at amor.org (Robert Brewer) Date: Sun, 21 Mar 2004 14:15:25 -0800 Subject: New restrain builtin function? Message-ID: I wrote a bunch of guff about limit(), including: > If you had a dataset with many large iterables, you would probably go > ahead and incur the overhead of an inner function call, with something > like: > > def limit3(obj, lower=None, upper=None): > if upper is None: > if lower is None: > limfunc = lambda i: i > else: > def _lower(i): > if i < lower: > i = lower > return i > limfunc = _lower > else: > if lower is None: > def _upper(i): > if i > upper: > i = upper > return i > limfunc = _upper > else: > def _both(i): > if i < lower: > i = lower > if i > upper: > i = upper > return i > limfunc = _both > > if hasattr(obj, '__iter__'): > product = [] > for item in obj: > product.append(limfunc(item)) > return product > else: > return limfunc(obj) > > ...which might squeeze a bit of performance out of the partial > application: > > >>> tl = timeit.Timer("limit.limit(data, 1, 5)", "import limit; data = > (0, 3, 6) * 100") > >>> tl.timeit(10000) > 7.1556577721471513 > >>> t3l = timeit.Timer("limit.limit3(data, 1, 5)", "import > limit; data = > (0, 3, 6) * 100") > >>> t3l.timeit(10000) > 5.0156802051656086 Of course, I tested the wrong function (I should have tested "limit4" instead of "limit"). Turns out the partial application solution ("limit3") is slower after all: >>> t4l = timeit.Timer("limit.limit4(data, 1, 5)", "import limit; data = (0, 3, 6) * 100") >>> t4l.timeit(10000) 3.8564284008166396 >>> t3l.timeit(10000) 4.9950809390575159 Meh. It was fun trying. FuManChu From gandalf at geochemsource.com Wed Mar 3 07:32:29 2004 From: gandalf at geochemsource.com (Gandalf) Date: Wed, 03 Mar 2004 13:32:29 +0100 Subject: Which Python module for PostgreSQL? References: Message-ID: <4045D05D.4000109@geochemsource.com> > > >I use psycopg usually, though I try to test my progs with all of them >(except popy). It's not too hard to accomadate all of them with just a few >tweaks (usually in the way they handle booleans), since they all use >pyformat. > > Hmm, this is why I use C-style booleans (e.g. an integer where 0 means false and not 0 means true). It is totally portable (can be used with any DBMS and with any DB-API module). I can be wrong doing this but it works fine for me. G From tjreedy at udel.edu Thu Mar 18 08:56:26 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 18 Mar 2004 08:56:26 -0500 Subject: attributes of Python classes References: <3064b51d.0403171605.75ec1ba0@posting.google.com><4058F086.490C215B@alcyone.com> Message-ID: > > 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 :-) An alternative is to give attributes a default value of None as class attributes. This avoid time and space overhead of doing same on per instance basis. Instances only need instance-specific value when there is one. class C: a = None # what a is b = None # what b is Terry J. Reedy From jcarlson at nospam.uci.edu Mon Mar 15 03:58:19 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Mon, 15 Mar 2004 00:58:19 -0800 Subject: Extracting info from OS/hardware In-Reply-To: References: <1059hm7s63ebh4f@corp.supernews.com> Message-ID: > In Linux, you can get a lot of information on hardware and status by examining > files in the /proc directory. For example, from doing cat /proc/cpuinfo on my > system: [snip proc info] In Windows 2k (and perhaps XP, 2003, ...) you can some of the same information with "set" (portions removed for brevity) C:\> set NUMBER_OF_PROCESSORS=2 OS=Windows_NT PROCESSOR_ARCHITECTURE=x86 PROCESSOR_IDENTIFIER=x86 Family 6 Model 6 Stepping 5, GenuineIntel PROCESSOR_LEVEL=6 PROCESSOR_REVISION=0605 > For disk space and free space, you check /proc/diskstats, etc. > No idea about how to do it on Windows, but programs like "Treesize" tell me it > mustn't be that hard. Off the top of my head, I can't think of a method for finding out other than parsing the results of a "quick": [parse(os.popen("dir %s:\\"%chr(letter)).read()) \ for letter in xrange(ord('a'), ord('z')+1)] There is likely a better and faster way for both by using pywin32 (current name for win32 extensions). - Josiah From michael at foord.net Mon Mar 15 11:44:28 2004 From: michael at foord.net (Fuzzyman) Date: 15 Mar 2004 08:44:28 -0800 Subject: Enjoying Inheritance and operator Overloading References: <8089854e.0403150353.5f249c3f@posting.google.com> Message-ID: <8089854e.0403150844.642feb8b@posting.google.com> > > def __delitem__(self, item): # deleting a keyword > key = item.lower() > if not self.has_key(key): > raise KeyError(item) > dict.__delitem__(key) > Oops - except dict.__delitem__ ought have both self and item as arguments.... Regards, Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html > > if __name__ == '__main__': > a = lowerDict() > a['HELLO'] =3 > print a From oren-py-l at hishome.net Thu Mar 11 10:13:06 2004 From: oren-py-l at hishome.net (Oren Tirosh) Date: Thu, 11 Mar 2004 10:13:06 -0500 Subject: new python syntax: concatenation of functions In-Reply-To: References: Message-ID: <20040311151306.GA91050@hishome.net> On Thu, Mar 11, 2004 at 12:38:49PM +0100, Uwe Mayer wrote: > Hi, > > I know the python community is not very receptive towards extending the > python syntax. Nevertheless I'd like to make a suggestion and hear your pro > and cons. > > I want so suggest a concatenation operator like in mathematics: ?? > such that: > > a(b(c(d))) <=> a??b??c(d) > > Now, why do you think such an extension would be completely useless? ;) Composition of regular functions is not too useful in daily programming tasks but concatenation of stream processes is quite useful. That is what makes pipes in shell programming so effective. Oren From fumanchu at amor.org Sat Mar 20 13:30:03 2004 From: fumanchu at amor.org (Robert Brewer) Date: Sat, 20 Mar 2004 10:30:03 -0800 Subject: Regular Expression AND mach Message-ID: Fuzzyman wrote: > Jeff Epler wrote in message > news:... > > Regular expressions are not a good tool for this purpose. > > Hmm... I'm not sure if I've been helped or not :-) > Thanks anyway..... > > Odd that you can't do this easily with regular expressions - I suppose > it doesn't compile down to a neat test.... but then it's hardly a > complex search... OTOH I have *no idea* how regular expressions > actually work (and no need to find out)... >From one Fu.*man to another ;) you do have a need to find out, even if you don't recognize it. Start with A.M. Kuchling's excellent, Python-based tutorial at: http://www.amk.ca/python/howto/regex/ At the least, you should understand why a regex is not an all-in-one solution to your issue. It basically comes down to the fact that a regex is geared to do its analysis in a single pass over your text. As it finds partial matches, it may backtrack to try to find a complete match, but in general, it moves forward. Therefore, if you want to find three words in a *declared* order in your text, a single regex can do it easily. If you want to find three words in *any* order, the simplest solution using regexes is to perform three separate searches. There are ways to get around this within a regex, but they're neither as simple nor as maintainable as letting Python do the iteration: >>> import re >>> text = 'Some aa text cc with bb search terms.' >>> search_terms = ['aa', 'bb', 'cc'] >>> [re.findall(re.escape(word), text) for word in search_terms] [['aa'], ['bb'], ['cc']] or, for your case: >>> def has_all_terms(content, terms): ... for word in terms: ... if not re.search(re.escape(word), content): ... return False ... return True ... >>> has_all_terms(text, search_terms) True >>> has_all_terms('A is for aardvark.', search_terms) False HTCYTIRABM! Robert Brewer MIS Amor Ministries fumanchu at amor.org From ivoras at __geri.cc.fer.hr Tue Mar 2 14:42:17 2004 From: ivoras at __geri.cc.fer.hr (Ivan Voras) Date: Tue, 02 Mar 2004 20:42:17 +0100 Subject: Twisted/Woven threading? In-Reply-To: <2004022921404364440%bob@redivicom> References: <2004022921404364440%bob@redivicom> Message-ID: Bob Ippolito wrote: > On 2004-02-29 20:07:04 -0500, Ivan Voras said: > >> I've experimented with a simple web application made with woven and >> stated by twistd from a .tap file, on a Win32. It seems that the web >> server started that way is not multitasked/multithreaded and that one >> request that requires long processing (e.g. a factory that produces a >> long result fetched from a database) makes the server totaly >> unresponsive. >> >> Is that normal? What can I do to make it multithreaded? > > > You're probably using DBAPI stuff directly, you can't do that, it's > blocking. You need to do that work in a separate thread, the easiest > way is probably with twisted.enterprise. There are tutorials and such > about this, and a better place to ask is the Twisted mailing list(s). Actually, I don't think the problem is in the db itself, but in the formatting (the "factory" that transformed database result into xhtml). The query itself is fast and trivial. From tjreedy at udel.edu Sat Mar 20 11:06:47 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 20 Mar 2004 11:06:47 -0500 Subject: Python bytecode compatibility between interpreter versions References: <0qudndSnJMpWbsfdRVn-uA@powergate.ca> Message-ID: "Jon Perez" wrote in message news:c3gqvu$27bujr$1 at ID-180326.news.uni-berlin.de... > 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)? The CPython VM is intentionally underdocumented and intentionally not part of the language spec. It is still being developed and might radically change in the future. There will probably be minor changes in the next release as a result of experiments designed to find combinations of codes that dependably run faster on all major platforms. However, the current byte code is described in the Library Ref as part of the doc for the dis (assembly) module. Terry J. Reedy From cookedm+news at physics.mcmaster.ca Tue Mar 2 21:15:19 2004 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Tue, 02 Mar 2004 21:15:19 -0500 Subject: Speed Comparison Perl Python & C References: <3064b51d.0403011035.554e7731@posting.google.com> <3064b51d.0403020649.53866885@posting.google.com> Message-ID: At some point, beliavsky at aol.com wrote: > Python is supposed to be easy (and in general I agree that it is), but > your solution requires some knowledge of > > (1) how integer and floating point calculations are done (which many > novices do not have) > (2) when Psycho can speed things up > > and the final result is still much slower than Fortran. For the > Fortran program, the only "trick" is the use of integer*8. It's quite easy (using F2PY) to make Python wrapper around a Fortran routine. So if you're in a situation where Fortran is much faster, then use it. Wrap it in Python and slap a webserver and a GUI on that puppy, and run rings around pure Fortran code. [Heck, I'll cry if I ever have to write any serious user interface code in Fortran. More than my sanity is worth.] -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From aahz at pythoncraft.com Fri Mar 12 14:45:41 2004 From: aahz at pythoncraft.com (Aahz) Date: 12 Mar 2004 14:45:41 -0500 Subject: put your money where your mouse is, or why I prefer Spanish to English: a proposal References: <082d01c407eb$bb8dfc10$210110ac@jsbwxp3> Message-ID: In article , Python Baby wrote: > >Yes but how does Spanish compare to Ruby? Which is better? Are you an Irish Python baby? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "usenet imitates usenet" --Darkhawk From hove at bccs.no Wed Mar 31 05:42:32 2004 From: hove at bccs.no (Joakim Hove) Date: Wed, 31 Mar 2004 12:42:32 +0200 Subject: ESR's fortune.pl redone in python - request for critique References: Message-ID: <4y3c7pi9gn.fsf@skjellgran.ii.uib.no> > I know it's not necessary, but it does no harm (right?) and I think [...] That is right. > (JH)> Repositioning the ... file pointer is not necessary, this pointer just vanishes when you close the file anyway. My second comment was that it is not necessary to explicitly exit the program with 'sys.exit()'. I am impressed with the way you followed up on this. Joakim -- /--------------------------------------------------------------------\ / Joakim Hove / hove at bccs.no / (55 5) 84076 | \ | Unifob AS, Avdeling for Beregningsvitenskap (BCCS) | Stabburveien 18 | | CMU | 5231 Paradis | \ Thorm?hlensgt.55, 5020 Bergen. | 55 91 28 18 / \--------------------------------------------------------------------/ From shalen_itbhu at hotmail.com Fri Mar 12 23:25:32 2004 From: shalen_itbhu at hotmail.com (shalendra chhabra) Date: Sat, 13 Mar 2004 04:25:32 +0000 Subject: Is Python Smart Enough to do Sorting like this? Message-ID: Hey Stephen, Thanks. I got what you said and by mistake I had typed the order in Decreasing, which I needed too. However, right now I see this interesting problem here on this list of "dont bother" which seems interesting. If one has a string and can this string be assigned to a dictionary and then we can apply the sorting methods of dictionary on it. For example: the information in my itemset can be treated as a string. itemset{} itemset=str(key[i])+str(value[i]) #done over a loop and and then some how can get everything concatenated If I am not mistaken the itemset is now a string. How can I assign this itemset back to a dictionary? Is there any way? If yes! then we can apply the sort methods for increasing order and for decreasing order you have given me the function already. Please clear my doubt Thanks Shalen >From: Stephen Horne >To: python-list at python.org >Subject: Re: Is Python Smart Enough to do Sorting like this? >Date: Sat, 13 Mar 2004 04:03:30 +0000 > >On Sat, 13 Mar 2004 01:26:25 +0000, "shalendra chhabra" > wrote: > > >Is it possible to order this itemset in an increasing order of key: value > >with respect to keys. For example: if > >key4>key2>key3>key1 > >then the resulting ordering should be in such a way: > > > >key4:value4, key2: value2,key3:value3>key1: value1 > >What you seem to be describing is decreasing order of key - the >highest key value (key4) first, with progressively smaller values at >later positions. > >This is not hard. The only minor annoyance is that, unlike for >instance a C++ map, Python dictionaries don't naturally iterate in >sorted order (they use hashing rather than a tree structure, which >overall is probably neither better nor worse - just different). > >Sorting tasks are quite common, so while that are not exactly >difficult I imagine there's a good guide on the internet somewhere for >newbies (links anyone?). > >In this case, once you have the dictionary of key:value pairs you >extract a list of keys and sort it appropriately. The default sort is >in increasing order, so you reverse that to get decreasing order. >Then, if necessary, you use a list comprehension to get a list of >(key, value) tuples in the needed order. The list comprehension is >often redundant, though, as you can normally just iterate the sorted >keys and read the values from the dictionary when they're needed. > >Here is a quick function... > >def pairs_by_decreasing_key (p_Dict) : > """ > Takes a dictionary and derives a list of (key, value) tuples > in decreasing order of key. > """ > tmp = p_Dict.keys (); tmp.sort (); tmp.reverse () > > return [(i, p_Dict [i]) for i in tmp] > > >-- >Steve Horne > >steve at ninereeds dot fsnet dot co dot uk >-- >http://mail.python.org/mailman/listinfo/python-list _________________________________________________________________ Xerox Multifunction devices?that print,copy,scan and fax. http://go.msnserver.com/IN/44797.asp Get affordable printing solutions that fit your needs . From FBatista at uniFON.com.ar Mon Mar 29 14:00:55 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Mon, 29 Mar 2004 16:00:55 -0300 Subject: Threading program with issues when executing from IDLE Message-ID: People, executing the following code from command line, it works as expected (you see "th1 - 2" *always* after "th2 - 2"). But when I execute from IDLE one of two things happens: - Everything freezes up after "th1 - 1". - The program finishes but after I get an strange internal IDLE error. There's a way to avoid that? The code: ----------------- import threading def thfunc1(): print "th1 - 1" event.wait() print "th1 - 2" def thfunc2(): print "th2 - 1" print "th2 - 2" event.set() event = threading.Event() th1 = threading.Thread(target=thfunc1) th2 = threading.Thread(target=thfunc2) th2.start() th1.start() ----------------- Thank you all! . Facundo From tdelaney at avaya.com Sun Mar 7 17:41:31 2004 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Mon, 8 Mar 2004 09:41:31 +1100 Subject: New to Python; what about #include, extern and function prototypes Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE013E7161@au3010avexu1.global.avaya.com> > From: Bo Jacobsen > > I'm new to Python, and it looks as if there is no > C like "#include and extern" or function protypes. No shell like ". > ../filename" > is this correct ?. > > Is there any way to implement them ? > > PS: For me, "import module" is no replacement for include. http://www.catb.org/~esr/faqs/smart-questions.html Hint: try learning/using the language before posting. Most of the people here get along just fine without #include in Python ... Tim Delaney From news at grauer-online.de Tue Mar 2 05:26:07 2004 From: news at grauer-online.de (Uwe Grauer) Date: Tue, 02 Mar 2004 11:26:07 +0100 Subject: How to access the Oracle9i? In-Reply-To: References: Message-ID: slackgg at 163.com wrote: > HI: > above title.. Choose a oracle-module from: http://python.org/topics/database/modules.html Uwe From yaipa at yahoo.com Tue Mar 16 00:17:03 2004 From: yaipa at yahoo.com (yaipa h.) Date: 15 Mar 2004 21:17:03 -0800 Subject: Python and Microsoft Excel files References: <20040315214043.2814f549.benoit.merouze@epita.fr> Message-ID: <6e07b825.0403152117.5f557548@posting.google.com> ben- wrote in message news:<20040315214043.2814f549.benoit.merouze at epita.fr>... > I want to import and export Microsoft Excel files. > Are there libraries for this ? > > If someone have advices to give, I'm interested ! See: Python Programming on Win32 By Mark Hammond, Andy Robinson http://www.oreilly.com/catalog/pythonwin32/ Also, if you google "Excel group:comp.lang.python.*" you will get about 1500 hits. Googling "hammond Excel group:comp.lang.python.*" drops the number down to just over 100. Cheers. From steve at ninereeds.fsnet.co.uk Mon Mar 8 00:01:04 2004 From: steve at ninereeds.fsnet.co.uk (Stephen Horne) Date: Mon, 08 Mar 2004 05:01:04 +0000 Subject: Working around a lack of 'goto' in python References: Message-ID: On Sat, 06 Mar 2004 16:16:10 -0500, Roy Smith wrote: >In article , > "Brett" wrote: > >> Two areas where I've found 'goto' two be useful in other languages are in >> (untested examples in C++) > >Working around the lack of "goto" in a language is kind of like trying >to figure out how to swim without a piano strapped to your back. :-) >> (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; >> >> END: /* continue */; > >I've found two general solutions to the breaking out of a deeply nested >loop. One possibility is to factor the loop out into its own function, >and break out of it with a return: >Another is to use an exception: Another occurred to me. Turn the three nested loops into one loop. In C... i = j = k = 0; while (k < 10) { if (/* some test */) break; i++; if (i == 10) { i = 0; j++; if (j == 10) { j = 0; k++; } } } If it was needed a lot, I might try... /* Cyclic increment Increment var reference by p and test against limit. if limit reached, reset to zero and return true to indicate overflow */ int CInc (int *p, int p_Limit) { (*p)++; if (*p < p_Limit) return 0; *p = 0; return true; } ... i = j = k = done = 0; while (!done) { if (/* some test */) break; done = CInc (&i, 10) && CInc (&j, 10) && CInc (&k, 10); } though I would at least try to think of a decent name for that function. This can just about be translated to Python... class cyclicint : def __init__ (self, p) : self.value = p def inc (self, p_Limit) : self.value++ if self.value < p_Limit : return false self.value = 0 return true def __int__ (self) : return value ... i = cyclicint (0); j = cyclicint (0); k = cyclicint (0); done = 0 while not done : if some test : break done = i.inc (10) and j.inc (10) and k.inc (10) But really that's a bad idea - there's a much neater way... for (i,j,k) in [(x,y,z) for x in range(10) for y in range(10) for z in range(10) ] : if sometest : break This should, of course, get a bit more efficient in Python 2.4 when we get generator expressions :-) I can also imagine a helper function... for (i,j,k) in cross(range(10), range(10), range(10)) : if sometest : break -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From tismer at stackless.com Mon Mar 29 09:19:24 2004 From: tismer at stackless.com (Christian Tismer) Date: Mon, 29 Mar 2004 16:19:24 +0200 Subject: import a module from an archive ? In-Reply-To: <40682BF2.80407@zslide.com> References: <40682BF2.80407@zslide.com> Message-ID: <4068306C.10507@stackless.com> vincent Salaun wrote: > hi all, > > i'd like to know if it's possible to import a module from an archive > (zip, rar, tar, jar, ...) > I've tried using different formats but it still doesn't work ..... > > i make: > >>>sys.path.append('d:/myModules.zip') > >>>import aModuleFromTheArchive > > is there a way to do that ? > the problem is that i've embed a python interpreter in our java app and > our scripts need some standard modules from python and jython but the 2 > 'Lib' directories of python and jython are a bit heavy : 8Mb .... This has started with PEP 273, and was implemented after PEP 302, see http://www.python.org/peps/pep-0302.html See also the module zipfile. And here is how to do it: http://www.python.org/doc/current/whatsnew/node5.html 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 steve at ferg.org Thu Mar 4 18:29:30 2004 From: steve at ferg.org (Stephen Ferg) Date: 4 Mar 2004 15:29:30 -0800 Subject: ANN: EasyGui update - simple GUI interface for Python programs Message-ID: I've just released easygui version 0.66 It is available at http://www.ferg.org/easygui This version adds a few useful features: Multchoicebox is like choicebox (i.e. a listbox), but it allows the user to select multiple entries. Results are returned in a list. Password box is like enterbox, except that the data-entry field is masked with asterisks. Multpassword box is like multenterbox, except that the last data-entry field is masked with asterisks. The cancel (X) box in dialog titlebars has been disabled. This makes it clearer what the user chose, since a user MUST choose one of the programmed choices. For those not familiar with EasyGui, here is an excerpt from the documentation: ****************************** Experienced Pythonistas need support for quick and dirty GUI features. New Python programmers need GUI capabilities that don't require any knowledge of tkinter, frames, widgets, callbacks or lambda. This is what EasyGui provides. Using EasyGui, all GUI interactions are invoked by simple function calls. EasyGui is different from other GUIs in that it is NOT event-driven. It allows you to program in a traditional linear fashion, and to put up dialogs for simple input and output when you need to. If you are new to the event-driven paradigm for GUIs, EasyGui will allow you to be productive with very basic tasks immediately. Later, if you wish to make the transition to an event-driven GUI paradigm, you can move to an event-driven style with a more powerful GUI package such as anygui, PythonCard, Tkinter, wxPython, etc. EasyGui is there just to do very basic stuff. More elaborate stuff should be done with more powerful tools. Here is a code snippet using EasyGui. msg ="What is your favorite flavor?" title = "Ice Cream Survey" choices = ["Vanilla", "Chocolate", "Strawberry", "Rocky Road"] choice = choicebox(msg, title, choices) # note that we convert choice to string, in case # the user cancelled the choice, and we got None. msgbox("You chose: " + str(choice), "Survey Result") From premshree_python at yahoo.co.in Fri Mar 19 00:16:45 2004 From: premshree_python at yahoo.co.in (=?iso-8859-1?q?Premshree=20Pillai?=) Date: Fri, 19 Mar 2004 05:16:45 +0000 (GMT) Subject: Py Tic Tac Toe in action Message-ID: <20040319051645.11698.qmail@web8301.mail.in.yahoo.com> Hello folks, See the Py Tic Tac Toe in action at http://balajin.net/cgi-bin/pyttt.py -Premshree Pillai ===== -Premshree [http://www.qiksearch.com/] ________________________________________________________________________ Yahoo! India Insurance Special: Be informed on the best policies, services, tools and more. Go to: http://in.insurance.yahoo.com/licspecial/index.html From __peter__ at web.de Thu Mar 4 15:10:35 2004 From: __peter__ at web.de (Peter Otten) Date: Thu, 04 Mar 2004 21:10:35 +0100 Subject: how fast is Python code - another detail References: <404778E4.9090601@aon.at> Message-ID: Andrew Koenig wrote: > "Peter Otten" <__peter__ at web.de> wrote in message > news:c280b0$1g3$03$1 at news.t-online.com... > >> key in theDict.keys() > >> changes the lookup from constant time (a hash value is calculated which >> is used as an index into a list of values if all goes well) to >> proportonial > to >> len(theDict) because on average half of the list has to be searched >> before the matching entry is found. > > Worse: Evaluating theDict.keys() requires building a list from all the > keys. So even if the key is the first element of the list, the run time > is O(len(theDict)). Might be interesting to measure the impact of boths effects separately by keeping a copy of keys that will be updated in the if clause. > Moreover, there's no way for the compiler to optimize such expressions in > general, because it doesn't know the type of theDict during compilation. Conclusion: the outward similarity of the value in theList and key in theDict tests *is* dangerous if you are concerned about speed. Peter From dlee at rightnow.com Sat Mar 27 17:53:53 2004 From: dlee at rightnow.com (Lee, Dustin) Date: Sat, 27 Mar 2004 15:53:53 -0700 Subject: examples of doing syadmin activities as a web app Message-ID: I've looked at it briefly (if I recall it is written in Perl). I may go back and investigate that more thoroughly but I still wonder: - Are there any Python based examples? - Is webmin well designed? (Not trying to troll, just curious if it is well thought out or just a hack) If any of you were to design such a beast (web based system admin tool) from scratch which framework would you consider a good match? dustin -----Original Message----- From: Skip Montanaro Sent: Sat 3/27/2004 7:04 AM To: Lee, Dustin Cc: python-list at python.org Subject: Re: examples of doing syadmin activities as a web app Dustin> I'm looking for an example of a well designed web application Dustin> used to do sys-admin type functions. I think the most popular tool in this space is WebMIN . Skip -------------- next part -------------- An HTML attachment was scrubbed... URL: From jcarlson at nospam.uci.edu Mon Mar 15 20:09:56 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Mon, 15 Mar 2004 17:09:56 -0800 Subject: Newbie question on wxNotebook In-Reply-To: References: Message-ID: The sizing information is never getting passed down to the wxNotebook. Try the following in the "MyFrame" class: def OnSize(self, event): size = event.GetSize() print "size:", size.width, size.height event.Skip() - Josiah From lilyth at umich.edu Fri Mar 19 11:17:40 2004 From: lilyth at umich.edu (Lilith) Date: 19 Mar 2004 08:17:40 -0800 Subject: Graphing problems (was: Re: Is there a map or graph module?) References: <75200cbc.0403181507.350feeb7@posting.google.com> Message-ID: <75200cbc.0403190817.10ed1ef3@posting.google.com> Josiah Carlson wrote in message news:... > Lilith wrote: > > Is there a python module somewhere (been searching today, no luck) > > which has efficiently coded various graph-handling routines, such as > > finding the shortest path through a graph, or the set of all paths > > through a graph? I'm not a compsci-educated person, so coding my own > > would be less parsimonious. > > > > Thanks for any suggestions! > > Thank Guido, http://www.python.org/doc/essays/graphs.html I figured it out...I needed to use sys.setrecursionlimit. D'oh. :) Thanks for your help! From fumanchu at amor.org Wed Mar 24 17:30:52 2004 From: fumanchu at amor.org (Robert Brewer) Date: Wed, 24 Mar 2004 14:30:52 -0800 Subject: Is this the correct way to implement TestSuite? Message-ID: Lol McBride wrote: > Hi all, > I've been using unittest for a while now but only creating > test cases for > individual modules of an application e.g class foo() has a reciprocal > module called class fooTestCase() class bar() has a reciprocal module > called class barTestCase() > > Now my app has quite a few modules and I want to run a single > test that > calls all of the xxxTestCase() modules and therefore runs all > of the tests > I have created so far. I took a slightly different approach, possibly because I tend to code in packages. Most of my development assumes 1) the module you want to test is in site-packages or some other point on syspath, and 2) all your testing modules are somewhere in the same folder or subfolders of it. If you can assume those two things as well, try my testpkg module (below). It's invoked like: prompt> python testpkg.py mypackage and will then run all files in that package (and its subfolders) whose names begin with "test_" and end in ".py". ----testpkg.py---- import os import sys import imp import unittest import xray def test_module(module): test = unittest.TestLoader().loadTestsFromModule(module) result = unittest.TextTestRunner().run(test) return result.wasSuccessful() def modules(dir): for name in os.listdir(dir): fullname = os.path.join(dir, name) if os.path.isdir(fullname): for mod in modules(fullname): yield mod elif name.startswith("test_") and name.endswith(".py"): yield fullname def test_package(packageName): filename, pathname, descr = imp.find_module(packageName) # TODO: provide for subpackages (packageNames containing dots) for name in modules(pathname): name = name[len(pathname):] if name.startswith(u"\\") or name.startswith(u"/"): name = name[1:] if name.endswith(u".py"): name = name[:-3] name = name.replace("/", ".").replace(u"\\", ".") name = ".".join((packageName, name)) try: mod = xray.modules(name) except ImportError, x: x.args += (name, ) raise x print "Module: " + name test_module(mod) del mod if __name__ == '__main__': test_package(sys.argv[1]) This uses my xray module, btw, which you can find at: http://www.aminus.org/rbre/python/xray.py HTH! Robert Brewer MIS Amor Ministries fumanchu at amor.org From robin at alldunn.NOSPAM.com Wed Mar 31 12:05:00 2004 From: robin at alldunn.NOSPAM.com (Robin Dunn) Date: Wed, 31 Mar 2004 09:05:00 -0800 Subject: Number formats in wxpython In-Reply-To: <39cbe663.0403141140.34618da3@posting.google.com> References: <39cbe663.0403141140.34618da3@posting.google.com> Message-ID: <0TCac.682$JX6.82@fe07.usenetserver.com> Piet wrote: > I am developping a small Python/wxPython app to track expenses. A > bunch of information is collected in a wxGUI consisting of text > controls, comboboxes and a small grid. Some values are not put in by > the user, but are calculated (e.g. the price of 789 g apples when 1 kg > is 1.99 ? or the mean fuel consumption of a car when the user puts in > the amount of fuel and the driven distance). The values from the > calculations and from the user inputs are stored in an external file. > I would like to define the format of currency information by setting > the number of digits after the decimal point to two. THe information > displayed in the grid can be controlled by using cell renderers, but > the do not influence the output. Is there something like number > formats in wxPytghon, such as the formats known from Mic++++++'s > ex***? Take a look at the MaskedEditCtrl classes in the library. -- Robin Dunn Software Craftsman http://wxPython.org Java give you jitters? Relax with wxPython! From joe at notcharles.ca Mon Mar 29 09:50:10 2004 From: joe at notcharles.ca (Joe Mason) Date: Mon, 29 Mar 2004 14:50:10 GMT Subject: Prothon Prototypes vs Python Classes References: <569c605ld1cj8fc1emolk08ete0s1prls1@4ax.com> Message-ID: In article , Jeff Epler wrote: >> BTW, I've got three pure-python solutions now (four when this one's >> fixed) but it turns out they all suffer from a flaw: >> >> >>> class TestProto: l = [] >> ... >> >>> class Test2(TestProto): pass >> ... >> >>> TestProto.l >> [] >> >>> Test2.l >> [] >> >>> Test2.l.append(0) >> >>> Test2.l >> [0] >> >>> TestProto.l >> [0] >> >> We really need copy-on-write lists and dicts - and large objects in >> general - for this to work. > > Can't you just follow the Python rule for classes with a little > difference? > * if you want some data to be shared by reference among the Prototype > and all its children, declare it at 'prototype' ('class') scope > * if you don't, create it in __init__ Possibly. You need something, at least - full copy-on-write seems like the most transparent, but also the most work to set up. (I'm still reading up on Self and others to find out how they handle these things.) Hmm, your method sounds like it would work. In fact, I guess it would already do that as written, wouldn't it? The use case I was thinking of was something like this (I'm going to use "object" instead of "class" from now on for pseudocode): object UrlDispatcher: def __init__(self): self.handlers = { "http:" : HttpHandler, "ftp:" : FtpHandler } object SSLUrlDispatcher(UrlDispatcher): def __init__(self): UrlDispatcher.__init__(self) self.handlers["https:"] = SSLHttpHandler So each instance of URLDispatcher and descendants has its own, entirely unshared copy of handlers. One drawback of this is that if you add a handler to UrlDispatcher at runtime, it isn't inherited by clones that have already been initialized. The other approach I suggested - replacing lists and dicts in prototype-baed objects with a customized version - could make this more transparent. Say, look up the value in SSLUrlDispatcher.handlers, then UrlDispatcher.handlers only if not found, and only then throw an error if the key still isn't found. The question is whether it's useful to put this complexity in the prototype system, or just provide classes that do this in a library (which can just be done by third parties as needed) and give coders the option of saying "handlers = ProtoDict()" instead of "handlers = {}". Joe From jeremy+plusnews at jeremysanders.net Mon Mar 1 11:25:23 2004 From: jeremy+plusnews at jeremysanders.net (Jeremy Sanders) Date: Mon, 01 Mar 2004 16:25:23 +0000 Subject: Plotting modules References: <403FC608.1010008@telus.net> Message-ID: On Fri, 27 Feb 2004 17:34:48 -0500, DG wrote: > Nice output. Looks almost biggles-ish, maybe better. Thanks. I'll inform people here when it's in a workable state. Jeremy From fma at doe.carleton.ca Tue Mar 30 17:23:50 2004 From: fma at doe.carleton.ca (Fred Ma) Date: 30 Mar 2004 22:23:50 GMT Subject: Choosing Perl/Python for my particular niche References: <40652B0D.7C313F77@doe.carleton.ca> Message-ID: <4069F371.B4D08F58@doe.carleton.ca> Robin Munn wrote: > > Fred Ma wrote: > > Hello, > > > > This is not a troll posting, and I've refrained from > > asking because I've seen similar threads get all > > nitter-nattery. > [snip: poster is basically asking "Should I learn Perl or Python?"] > > While availability of libraries for your specific tasks is a major > factor to take into consideration, I'd say that even more important is > to figure out which language fits your brain. > > I first learned Perl, then Python. I now use Python almost exclusively, > because I found that Python fits my mental "map" much better than Perl > does. To me, it seemed like in Perl, everything was a string. Sure, you > could have objects and classes, but they felt strange and awkward -- how > do I translate the "bless" keyword into my mental model? Whereas > Python's object model translated perfectly into my mental map, to the > point where programming in Python gave a clarity that I never had when > using Perl. It's hard to explain why, exactly -- it just seemed like > when using Perl, I was always going back down to the level of details, > the trees in the forest. Python allows me to look at the entire forest. > I can still go down and look at trees if I need to, but I don't have to > operate in that mode all the time. > > Your mileage *will* vary. There's no substitute for experience. Set > yourself a simple task (say, writing a sieve of Eratosthenes program) > that you could do in about an hour with a language you're familiar with. > Then write the same program in Perl and in Python, and see which one > fits *your* brain better. Well, my bout with Perl took much, much more than an hour. It worked, though. It's probably not enough experience to get a good look at the strength of Perl. For example, I am a vim user (an editor), which is cryptic at first, but let's you fly when you get to know it. I'm not saying that all things cryptic are efficient in the end, just that a brief bout won't always uncover the strengths. As a "working model", I've decided to use Perl as the workhorse, and keep tabs on Python as time permits. If my mental map works better with Python, it's ease of ramping up will allow the better fit to shine through despite the lesser time I spend with it. Then it will naturally take a more prominent role. Thanks for the advice on checking out both. It seems to be the most realistic, and in line with what many have suggested. Fred -- Fred Ma Dept. of Electronics, Carleton University 1125 Colonel By Drive, Ottawa, Ontario Canada, K1S 5B6 From hufman at cobalty.com Thu Mar 4 18:07:10 2004 From: hufman at cobalty.com (Walter Huf) Date: 4 Mar 2004 17:07:10 -0600 Subject: Sending binary data over CGI References: Message-ID: Tim Roberts wrote in news:onod401p4rjbe9kuu10q6518l93ds7rks3 at 4ax.com: > > Really? This is such a common problem that most Windows Python > programmers encounter it very early in their experiments. > > The issue, of course, is that stdout is opened as a text file, not as > a binary file, and we all know that the LF to CR-LF conversion you > describe is part of the normal processing of a text file in Windows. > > If you must send binary data through stdout, do this before you start > to write: > > import os > import msvcrt > ... > msvcrt.setmode( stdout.fileno(), os.O_BINARY ) Awesome, thanks! I'm quite new at Python. I've done a lot in Visual Basic, and even written a couple cgiprogs in basic, but my server on the internet(http://hufman.cobalty.com) is a linux server, and, Micro$oft being Micro$oft, there is no visual basic compiler or interpreter for linux. I started learning Python last Sunday, so I wouldn't know anything about the conversions. Well, I knew about the newline conversions, I think, but I didn't know how to get around it. I couldn't find anything about it in the help. Thank you though! --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 giles_brown at hotmail.com Wed Mar 3 16:15:43 2004 From: giles_brown at hotmail.com (Giles Brown) Date: 3 Mar 2004 13:15:43 -0800 Subject: XML best practices (was: Python as replacement for PHP?) References: <403fa54b@news.zianet.com> <30260531.0402271901.1bbdda99@posting.google.com> <1040489b2ookafd@corp.supernews.com> <1hd240haqpbmnqdltavdt6t24ue0jvcl92@4ax.com> Message-ID: <57de9986.0403031315.1bacf2c7@posting.google.com> Andy Dingley wrote in message news:<1hd240haqpbmnqdltavdt6t24ue0jvcl92 at 4ax.com>... > On Sat, 28 Feb 2004 03:54:49 -0000, claird at lairds.com (Cameron Laird) > wrote: > > >Let me get this straight: your preferred vehicle for XML > >parsing is Perl regular expressions? That's ... well, > > Rather more restrained a comment than I'd be capable of expressing ? http://www.usingenglish.com/glossary/litotes.html maybe? From andrew-pythonlist at puzzling.org Wed Mar 24 08:51:19 2004 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Thu, 25 Mar 2004 00:51:19 +1100 Subject: PEP 318 In-Reply-To: References: <95aa1afa.0403222352.2679dde@posting.google.com> <95aa1afa.0403232104.328356ea@posting.google.com> Message-ID: <20040324135119.GB23307@frobozz> On Wed, Mar 24, 2004 at 03:25:21PM +0200, Ville Vainio wrote: > >>>>> "Andrew" == Andrew Bennetts writes: > > Andrew> Which is to say, I don't understand how that can work -- > Andrew> the first definition of foo gets clobbered. > > Yes, the name 'foo' gets clobbered every time, but the decorator > always returns the *dispatcher* that is capable of dispatching the > call to the correct definition of 'foo'. The dispatcher preserves the > references to the callables, so they don't get decreffed out of > existence. > > The dispatcher obviously needs a reference to a module global dict > object of some sort, with some magical name like > '__mm_dispatcher_registry'. > [...] > > Andrew> How is the registry not going to help distinguish between > Andrew> the foo methods from C, and the foo methods from C2? > > It's not. I'm still thinking of multimethods mostly as plain functions > with dynamic dispatching on arg types, not actual methods. To get the > functionality in methods, you just need to call the mm function > explicitly with an unique name inside the method. Ah, I see. I was thinking of methods, but you were thinking of functions. But the same problem still applies: how would the multimethod decorator distinguish between a "foo" function in moduleA, and a "foo" function in moduleB? By inspecting the function's __module__ attribute? This degree of introspection feels a bit too magical (i.e. implicit) to me... -Andrew. From tjreedy at udel.edu Mon Mar 8 23:44:07 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 8 Mar 2004 23:44:07 -0500 Subject: Unit testing - suitable for all development? References: <153fa67.0403070839.77ae66e6@posting.google.com><104mo6mjpc1lq74@news.supernews.com><153fa67.0403071515.7cf93986@posting.google.com><104nnqlq81dvj48@news.supernews.com><153fa67.0403081300.42e2d061@posting.google.com> Message-ID: "Greg Ewing (using news.cis.dfn.de)" wrote in message news:c2j9ea$1ug17d$1 at ID-169208.news.uni-berlin.de... > It sounds like you have a similar situation as I have > with Pyrex. The Pyrex compiler is made up of a large > number of parts which interact in very complex ways. > Each part on its own is fairly simple, and while it > *could* be tested on its own after a fashion, this > wouldn't really help much, because most of the > interesting things happen in the interactions between > the parts, rather than inside the parts themselves. > > I haven't bothered doing unit testing in the conventional > sense with Pyrex. What I have instead is a large collection > of very small Pyrex files, each of which exercises some > feature of the Pyrex language. Running the test consists > of compiling the file and checking that the generated code > matches previously verified output. The main test files for the Python interpreter are similar, testing that 0+1==1, 2*2==4, 'a'+'a'=='aa', [0,1][1]==1, and so on for hundreds of compile and execute cases intended to cover every syntax feature possible. Perhaps the OP can do something similar: set up minimal game world and repeatedly direct a simple action ('pick up nearest object') and check for intended change of state (inventory contains small dagger that it did not before). Terry J. Reedy From ieyf4fu02 at sneakemail.com Mon Mar 29 20:25:21 2004 From: ieyf4fu02 at sneakemail.com (Greg Ewing (using news.cis.dfn.de)) Date: Tue, 30 Mar 2004 13:25:21 +1200 Subject: Prothon, metaclasses, Zope [Was: A 'Python like' language] In-Reply-To: References: <95aa1afa.0403272243.78d60724@posting.google.com> <95aa1afa.0403280258.41dc5cd9@posting.google.com> Message-ID: Joe Mason wrote: > In article <95aa1afa.0403280258.41dc5cd9 at posting.google.com>, Michele Simionato wrote: > >>Uh? The base class __init__ method is not called when I derive a new >>class. I want to make the make the check at class level, *before* >>instantiating. > > It is if you call the inherited __init__ method, which you should be > doing because it probably does important stuff. But presumably he wants the check done only once, when a subclass is defined, *not* every time said subclass is instantiated. In Prothon it appears that both of these end up invoking the same __init__ method, so there's no way of telling them apart. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From skip at pobox.com Sun Mar 21 09:59:26 2004 From: skip at pobox.com (Skip Montanaro) Date: Sun, 21 Mar 2004 08:59:26 -0600 Subject: Python bytecode compatibility between interpreter versions In-Reply-To: References: Message-ID: <16477.44494.544581.766532@montanaro.dyndns.org> Jon> [ expand jar file - presto! instant app ] Aahz> .... I am sure that simple cases work as you describe, but I'd Aahz> like a cite for Java working as you describe in general. Jon> Yes. Java works like that ... [ mentions Batik ] The fundamental difference between Java and Python in this regard is that the JVM must absolutely be part of the defined API since it is delivered separate from the compiler. Whoever does this stuff probably has to go to great lengths to preserve compatibility. This is not the case for the Python VM, since a new version is delivered with each distribution. Skip From vedranf at riteh.hr Fri Mar 5 06:11:54 2004 From: vedranf at riteh.hr (Vedran Furac) Date: Fri, 5 Mar 2004 11:11:54 +0000 (UTC) Subject: Impersonation References: Message-ID: On 03 Mar 2004 16:19:48 -0500, David Bolen wrote: > Vedran Furac writes: > >> I would like to run a program as another user in win2k. I have runas >> utility but with this I need type password all the time. Using python and >> windows extensions it is posibile to write a program that will do this, here >> is a code: > > It's probably the fact that os.execv is bubbling down into a normal > CreateProcess call at the win32 API level. But if the calling process > is impersonating a user, CreateProcess uses the authentication token > for the calling process itself, and not the impersonation token. > > There is a CreateProcessAsUser call that works just like Yes, that was the problem, using CreateProsessAsUser() fixes the problem. Thanks! From peter at engcorp.com Tue Mar 30 02:13:16 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 30 Mar 2004 02:13:16 -0500 Subject: GUI Frameworks in Python? In-Reply-To: References: Message-ID: Hugh Macdonald wrote: > I've recently been trying out various different GUI frameworks in Python and > was wondering if I could get your input on the pros and cons of the > different ones... > > wxPython: I love the programming side of wxPython, but I find it's just so > slow to initialise in the first place. 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. I would think, given the size of the demo itself, that just about anything it does should be representative of other apps on the same machine. For the record, running WinXP AMD 2200 with adequate RAM etc. Are these reports of slow wxPython startup only coming from really old machines or something? -Peter From paul.kemp at standardbank.com Mon Mar 8 08:49:59 2004 From: paul.kemp at standardbank.com (Paul) Date: 8 Mar 2004 05:49:59 -0800 Subject: py2exe - COM Server problem Message-ID: Hi all I've been trying to build a COM Server as an executable using Py2exe. I had a few problems, so I came back to using Thomas Heller's basic example (copied below). When I build this, I still get an error. I can register Python.TestServer (testcomserver.exe --register), however, when I try to create an instance of it (e.g. using VBA), a command prompt window appears with the title: d:\...\testcomserver.exe /automate And the command prompt window just sits there! Eventually, VBA times out. I really don't understand, because I've succeeded with COM servers and Py2Exe in the past, and have never seen this before. Can anyone help? Thanks Paul --- import sys import pythoncom if hasattr(sys, 'importers'): # we are running as py2exe-packed executable pythoncom.frozen = 1 sys.frozen = 1 class HelloWorld: _reg_clsctx_ = pythoncom.CLSCTX_LOCAL_SERVER if hasattr(sys, 'importers'): # In the py2exe-packed version, specify the module.class # to use. In the python script version, python is able # to figure it out itself. _reg_class_spec_ = "__main__.HelloWorld" _reg_clsid_ = "{B83DD222-7750-413D-A9AD-01B37021B24B}" _reg_desc_ = "Python Test COM Server" _reg_progid_ = "Python.TestServer" _public_methods_ = ['Hello'] _public_attrs_ = ['softspace', 'noCalls'] _readonly_attrs_ = ['noCalls'] def __init__(self): self.softspace = 1 self.noCalls = 0 # __init__() def Hello(self, who): self.noCalls = self.noCalls + 1 # insert "softspace" number of spaces return "Hello" + " " * self.softspace + str(who) if __name__ == '__main__': if hasattr(sys, 'importers'): # running as packed executable. if '--register' in sys.argv[1:] or '--unregister' in sys.argv[1:]: # --register and --unregister work as usual import win32com.server.register win32com.server.register.UseCommandLine(HelloWorld) else: # start the server. from win32com.server import localserver localserver.main() else: import win32com.server.register win32com.server.register.UseCommandLine(HelloWorld) --------- setup.py: from distutils.core import setup import py2exe setup(name='testCOMserver', scripts=['testCOMserver.py']) vba: dim o as object set o = CreateObject("Python.TestServer") From cpl.19.ghum at spamgourmet.com Fri Mar 26 07:22:46 2004 From: cpl.19.ghum at spamgourmet.com (Harald Massa) Date: Fri, 26 Mar 2004 13:22:46 +0100 Subject: Python in the laboratory References: Message-ID: Zunbeltz Izaola > papers defending the goodness of python for such aplications. > Can s0mebody give me references about projects of this nature? http://pythonology.org/success http://python.oreilly.com/news/python_success_stories.pdf http://wingide.com/success/ http://pbf.strakt.com/success Good Luck Harald From no at sp.am Sun Mar 28 12:45:49 2004 From: no at sp.am (DH) Date: Sun, 28 Mar 2004 11:45:49 -0600 Subject: Breakdown of approaches to PEP318 In-Reply-To: <7vD9c.318$1A6.114130@news20.bellglobal.com> References: <7vD9c.318$1A6.114130@news20.bellglobal.com> Message-ID: Sean Ross wrote: > Here's a breakdown of most of the syntax discussed re: PEP318 using an > example from python-dev. There are probably several more (I've added [10]). > The example applies both function decoration and annotation. These are all ugly and unreadable. If you had to do this I'd go with #9 docstrings, but use javadoc (only the @ parts). Actually it looks like epydoc already does this: http://epydoc.sourceforge.net/ See their example: http://epydoc.sourceforge.net/epytextintro.html and list of all @tags: http://epydoc.sourceforge.net/fields.html An example with function decorators too: def addObserver(self, obs) [synchronized, classmethod]: """ Add an observer to be notified when something changes. @author: John Smith @deprecated: The reason why this is deprecated. @param obs: The observer, a class with a "notify" method or else a function or callable. """ Note though this all really is beyond the initial scope of PEP 318. From talktojamesblair at yahoo.com Thu Mar 25 06:22:35 2004 From: talktojamesblair at yahoo.com (james blair) Date: 25 Mar 2004 03:22:35 -0800 Subject: Error handling in smtp Message-ID: Hi I want to handle all the error that are thrown by smtp Do I have to handle each error seperately i.e except SMTPConnectError: except SMTPResponseException: etc Also, howe is this error handled error: (10061, 'Connection refused') I tried to handle it with except SMTPConnectError: But noluck Thanks, James From tundra at tundraware.com Tue Mar 9 19:27:28 2004 From: tundra at tundraware.com (Tim Daneliuk) Date: 09 Mar 2004 19:27:28 EST Subject: Any Python Hackers Wanna Beta Test???? Message-ID: <404E60A5.9010605@tundraware.com> One of the things I find myself needing over and over is providing an external configuration file for use by my applications. For various reasons, I have not been satisfied with other solutions to this problem I have seen so far. So ...I am about 25% done with a new Python module I've wanted to write for some time. It is intended as general purpose configuration file parser complete with conditionals, variable substitution, etc. The idea is that you hand it the name of a configuration file, and it returns a populated symbol table, ready-to-use. Anyway, I am going to be looking for people to stress test this thing when it is ready. If interested, let me know _off-list_... -- ---------------------------------------------------------------------------- Tim Daneliuk tundra at tundraware.com PGP Key: http://www.tundraware.com/PGP/ From ivoras at __geri.cc.fer.hr Wed Mar 10 16:49:47 2004 From: ivoras at __geri.cc.fer.hr (Ivan Voras) Date: Wed, 10 Mar 2004 22:49:47 +0100 Subject: Extending Python Syntax with @ In-Reply-To: References: Message-ID: 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. From prouleau at impathnetworks.com Sat Mar 20 18:25:26 2004 From: prouleau at impathnetworks.com (Pierre Rouleau) Date: Sat, 20 Mar 2004 18:25:26 -0500 Subject: New restrain builtin function? In-Reply-To: References: Message-ID: Robert Brewer wrote: > Pierre Rouleau wrote: > >>In several occasions, I found myself looking for a function >>that would take a value and restrict is within a specified >>set of boundaries... >> >>def restrain(value, theMin, theMax) : >> >> assert(theMax >= theMin) >> return min(max(value,theMin),theMax) >> > > > I'd find a limit() function more useful, where either min or max is > optional: > > def limit(value, lower=None, upper=None): > """Return value limited by lower and/or upper bounds.""" > > if upper is not None: > value = min(value, upper) > if lower is not None: > value = max(value, lower) > return value > > This allows for single-boundary limits: > > >>>>limit(3, 5) > > 5 > >>>>limit(3, upper=1) > > 1 > > And a no-op: > > >>>>limit(3) > > 3 > I was trying to make it as fast as possible but the additional flexibility is nice. The word 'limit' is probably closer to min and max and easier to read. I wonder if the word limit would clash with more existing programs though. > Also, you don't need to assert that upper >= lower; in fact, if upper is > less than lower, you can use the same function for exclusive boundaries: > > >>>>limit(3, 5, 1) > > 5 True, however, the reason for such a function, instead of the inline min(max()) was to provide for some protection in some defensive programming way. > > However, I find both restrain(3, 1, 5) and limit(3, 1, 5) difficult to > read. It would be nice to produce the same thing with some other syntax. I agree that the way it reads leaves me wishing for some Smalltalkish way of saying: limit value to min,max > If we did it in C, we could at least write: limit(lower=None, value, > upper=None). But perhaps there's some other means I'm not thinking of. > It'd be nice to have "value" look different than upper and lower. Maybe > something like: limit(value, (lower, upper)), or even value.limit(lower, > upper) using a __limit__ customizable method. Hmm. However, if upper and lower are inside a tuple, then restrain (or limit) could not be used to restrain or limit multi-dimensional values like tuple and list like in: >>> map(restrain, (10,15,20) , (11,14,19) , (12,18, 20)) [11, 15, 20] From fumanchu at amor.org Sat Mar 13 19:03:47 2004 From: fumanchu at amor.org (Robert Brewer) Date: Sat, 13 Mar 2004 16:03:47 -0800 Subject: Python & the job market Message-ID: kbass wrote: > I am starting to learn Python but I want to know how the job > market looks for programming using Python. I really don't see > many jobs (probably one or two) that require Python experience > at all. Most DBA and SA positions that I have seen require > Perl and most development position require Java or C++ so > how can learning Python benefit my career if there are little > to no chance that an employer will require the use of Python > or consider using Python over other programming languages > such as Java? Java was designed to benefit your career. Python was designed to benefit your life. Pick one. FuManChu From skip at pobox.com Sat Mar 27 14:07:51 2004 From: skip at pobox.com (Skip Montanaro) Date: Sat, 27 Mar 2004 13:07:51 -0600 Subject: A 'Python like' language In-Reply-To: <58cb60lmovocadg9p3ghu39t4ga343gfvd@4ax.com> References: <40645d8f$0$10775$afc38c87@news.easynet.co.uk> <1068up4kn49778@news.supernews.com> <58cb60lmovocadg9p3ghu39t4ga343gfvd@4ax.com> Message-ID: <16485.53511.280337.321187@montanaro.dyndns.org> Stephen> Different people have different tab sizes set up in their Stephen> editors. As long as you don't mix tabs and spaces, the Stephen> indentation itself will be clear - but having a different tab Stephen> size can break other aspects of vertical alignment, damaging Stephen> readability in other ways. It isn't as bad as the problems Stephen> that arise when mixing tabs and spaces for indentation, but IMO Stephen> it is bad enough. Tim Peters used to complain often enough that email messages I posted which contained bits of Python code I typed into them contained mixtures of tabs and spaces (which muffed the layout in his mail reader) that I finally added a little bit of code to my XEmacs setup to untabify all outgoing mail: (defun untab-buffer () (untabify (point-min) (point-max))) (add-hook 'mail-send-hook 'untab-buffer) Tim hasn't complained about that aspect of my Python since then. (Other things, yes, but not tabs). Skip From theller at python.net Mon Mar 22 15:36:00 2004 From: theller at python.net (Thomas Heller) Date: Mon, 22 Mar 2004 21:36:00 +0100 Subject: Need Help Using Py2Exe References: Message-ID: <7jxcfwlr.fsf@python.net> "upward_spiral2001" writes: > Hi. I've got a neat artificial intelligence project I want to > distribute as an EXE. I'm using Python, Pygame, and Numeric. My > problem is: When I use py2exe, I'm told "The following modules > appear to be missing: AppKit, Foundation, dotblas, objc." And then > my EXE crashes with a "segmentation fault." I tried the command: > > python setup.py py2exe --ignores [those modules] > > It then compiles w/o complaint, but the EXE still crashes. The > setup.py is very simple: > > from distutils.core import setup > import py2exe > setup(console=["NissIslandDemo.py"]) Most certainly one of the extension modules (either from pygame, or from Numeric, or even both) is importing another module from C code, and py2exe cannot find these dependencies. You have to find it yourself, and include it in the py2exe build. An interesting experiment would be to set an PY2EXEVERBOSE environment variable and run the crashing executable in this environment. The PY2EXEVERBOSE variable does the same as the PYTHONVERBOSE env var or the -v flag for the normal Python interpreter - imports are printed to the standard output. Maybe this can help to find the missing module? Thomas From ville at spammers.com Thu Mar 25 01:38:06 2004 From: ville at spammers.com (Ville Vainio) Date: 25 Mar 2004 08:38:06 +0200 Subject: Python for large projects References: <7xisgxt51r.fsf@ruckus.brouhaha.com> <105uk4987h7tm77@corp.supernews.com> <7xad28313c.fsf@ruckus.brouhaha.com> Message-ID: >>>>> "Jarek" == Jarek Zgoda writes: Jarek> Oh, dear... Jarek> I think the best way of lobbying for Python adoption is to Jarek> write good software with Python. I think the best way is to urge your friends/coworkers to try it. Esp. if you are not in Open Source business, and your work is not visible to public. Still, there are masses of people out there who never hear of anything that is not Java, C(++) or one of those Microsoft languages. It wouldn't hurt to get some good buzz going in that audience. -- Ville Vainio http://tinyurl.com/2prnb From eurleif at ecritters.biz Mon Mar 8 05:36:54 2004 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Mon, 08 Mar 2004 10:36:54 GMT Subject: "print" as function not statement In-Reply-To: References: Message-ID: Duncan Booth wrote: > You need a bit more checking to be sure nobody tried to pass in any > unexpected keyword arguments, and your output loop is a bit messy. Why check for unknown keyword arguments? It seems to me that better forward-compatibility is achieved if we ignore them. You're right about the output loop, though. I haven't really tried list comprehensions yet, so I didn't even think of using them. Thanks. From jacek.generowicz at cern.ch Wed Mar 24 03:12:11 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 24 Mar 2004 09:12:11 +0100 Subject: [OT] Compilable Python-like language? References: <6ee58e07.0403231151.36de00d5@posting.google.com> Message-ID: llothar at web.de (Lothar Scholz) writes: > Ed Cogburn wrote in message news:... > > Jacek Generowicz wrote: > > > That rather depends on what you mean by "Python-like". > > > > > > Oh dear... > > yes, oh my dear...., you posted a troll question. > > There is nothing like that what you want. It is just not there because > it is impossible. Huh ? > It simply does not work with languages like python which are > extremely dynamic - including metaprogramming. So how do you explain the existence of compilers (to-native-binary) for languages just as dynamic as Python ? > Even a full compiled LISP, that means safety settings set to lowest > priority and typedeclarations everywhere simply isn't much of the > lisp you may (not) know. What on earth are you talking about? Type declarations and safety settings in Lisp have an influence on the amount of checks (array bounds, overflows, type-checks and so on) that are performed at run-time. This is completely, totally and utterly orthogonal to "compliation to binary". Common Lisp programs, when fully compiled are fully compiled. Period. Whether the program contains any type declarations, or any optimization declarations, has no influence on whether the program is fully compiled or not. The only thing that has any influence on whether the program is fully compiled, is whether you compiled your whole program or just bits of it. You appear to be thoroughly confused about what "compliation" means. From newsgroups at jhrothjr.com Mon Mar 15 21:53:56 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 15 Mar 2004 21:53:56 -0500 Subject: Tkinter3000 References: Message-ID: <105cr4i7evg2gce@news.supernews.com> "Batista, Facundo" wrote in message news:mailman.13.1079398001.742.python-list at python.org... > Fredrik Lundh wrote: > > #- > #- > Also, at one point there was going to be an O'Reilly book on > #- > Tkinter, did that die? > #- > #- yes. > #- > > What a pitty. Is there some project to document Tkinter? "Python and Tkinter Programming" by Grayson (Manning 2000) is still availible. It's a bit long in the tooth, but it's still a very good guide. John Roth > > Thanks! > > . Facundo > From premshree_python at yahoo.co.in Mon Mar 15 21:12:34 2004 From: premshree_python at yahoo.co.in (=?iso-8859-1?q?Premshree=20Pillai?=) Date: Tue, 16 Mar 2004 02:12:34 +0000 (GMT) Subject: Static Typing in Python In-Reply-To: <4055a71e$0$28265$afc38c87@news.easynet.co.uk> Message-ID: <20040316021234.71773.qmail@web8307.mail.in.yahoo.com> --- Peter Hickman wrote: > Premshree Pillai wrote: > > Like in C, C++, etc, Python too is > > strongly typed, i.e., variables are necessarily > bound > > to a particular type. > > Python 1.5.2 (#1, Jan 31 2003, 11:01:49) [GCC 2.96 > 20000731 (Red Hat > Linux 7.2 2 on linux-i386 > Copyright 1991-1995 Stichting Mathematisch Centrum, > Amsterdam > >>> a = 1 > >>> a > 1 > >>> a = "fred" > >>> a > 'fred' > >>> a = open > >>> a > > >>> > > So here was have a variable 'a'. In the first > instance I set it to a > number. Then I set it to a string. Now in a strongly > typed language, > such as C or C++, would be screaming that "fred" was > not an integer. > Then we set it to, in effect, a pointer to a > function. Again no error. > > Could you please clarify how this consitutes Python > being 'strongly typed'? > -- > http://mail.python.org/mailman/listinfo/python-list Well, that was not what I meant. When I said that variables are bound to a particular type, I meant that variables necessarily have a specific type; I didn't say that you cannot change its type. Consider this: >>> str = 10 >>> len(str) Traceback (most recent call last): File "", line 1, in ? len(str) TypeError: len() of unsized object >>> This was what I meant. See the following: >>> foo = "x" >>> foo = foo + 2 Traceback (most recent call last): File "", line 1, in ? foo = foo + 2 TypeError: cannot concatenate 'str' and 'int' objects >>> The above returns a TypeError in Python, but not in PHP, which is weakly typed. Get it? -Premshree Pillai ===== -Premshree [http://www.qiksearch.com/] ________________________________________________________________________ Yahoo! India Insurance Special: Be informed on the best policies, services, tools and more. Go to: http://in.insurance.yahoo.com/licspecial/index.html From kvdvm at yahoo.com Sat Mar 13 00:03:42 2004 From: kvdvm at yahoo.com (kvdvm) Date: Sat, 13 Mar 2004 05:03:42 -0000 Subject: How to stop a listening socket.accept()? Message-ID: 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. From dave at pythonapocrypha.com Tue Mar 16 16:04:55 2004 From: dave at pythonapocrypha.com (Dave Brueck) Date: Tue, 16 Mar 2004 14:04:55 -0700 Subject: Can't connect Postgres to Python References: <40576A00.9090506@sstar.com> Message-ID: <038001c40b9a$5598e890$6401fea9@YODA> John wrote: > At this point, using the command > conn = psycopg.connect("dbname=personal", serialize=0) > from psycogq documentation, I get > NameError: name 'psycopg' is not defined > > What am I missing? Hi John. You need to import the module first: import psycopg You may have more errors to figure out, but this will at least get you to the next step. -Dave From cookedm+news at physics.mcmaster.ca Sun Mar 7 03:27:55 2004 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Sun, 07 Mar 2004 03:27:55 -0500 Subject: extending python References: <10895173.0403050231.35c977ef@posting.google.com> Message-ID: At some point, alain.dimier at andra.fr (dimier) wrote: > I have created a module in python based on a C program and it works > fine. I created it without using swig. > I tried to create a class to go to //isation and ran in problems. I > created the class, but calling the associated methods,as an example, I > get the following message: > > RuntimeError: Error in define_verbose > > Notice thar define_verbose has arguments. > > Can anyone tell me what I am doing wrong? Yes; you're not giving enough information to solve your problem (and I left my mind-reading hat at home). -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From grsNOSPAM at NO-SPAMmail.com Thu Mar 4 13:38:42 2004 From: grsNOSPAM at NO-SPAMmail.com (Guillaume) Date: Thu, 04 Mar 2004 19:38:42 +0100 Subject: OFF-TOPIC:: Why Lisp is not my favorite programming language In-Reply-To: <4046C71D.9060008@joncruz.org> References: <165b3efa.0403030443.4d591f04@posting.google.com> <40460dd5$0$5916$7a628cd7@news.club-internet.fr> <4046C71D.9060008@joncruz.org> Message-ID: <404777ac$0$5911$7a628cd7@news.club-internet.fr> > Well, I happen to use that "fairly useless" language daily in working > with Java. Hehe, nice. ;-) From eddie at holyrood.ed.ac.uk Tue Mar 23 10:00:22 2004 From: eddie at holyrood.ed.ac.uk (Eddie Corns) Date: Tue, 23 Mar 2004 15:00:22 +0000 (UTC) Subject: SOLVED: Re: ftplib - uploading files using transfercmd? References: <7mru509ghdlv0cfu538nfau3kcs3vtn268@4ax.com> Message-ID: Kevin Ollivier writes: >OK, I finally figured out how to fix my problems with the FTP commands >being issued in the wrong order - after I've finished uploading the >file, I have to call ftplib.voidresp(). >Is it possible to get this added as a note to the docs for >ftplib.transfercmd()? IIUC, you must always call ftp.voidresp() after >uploading a file using transfercmd(), and if that's the case, then I >think it'd be helpful to add a note about it in the ftplib docs so >that the next person to come along and try something like this doesn't >run into the same problem. It's more complicated than that. You have to be aware that FTP commands generate responses, sometimes multiple responses but I think that's so rare you can ignore it. Most of the ftplib commands hide this, when I replied to the first post, I could see that the problem was probably that you weren't eating your responses, unfortunately I didn't read your message carefully enough to notice you were calling transfercmd directly (tsk tsk) and hence my explanation was crap (sorry). In general you will often need to know what the response actually is, however neither of the response gathering methods is exposed, which is probably worth remedying. Which brings me to the observation in that in such cases it's often best just to look at the source. I had a similar problem when trying to turn an FTP call into a generator but soon noticed all those calls to voidresp. However it's probably worth trying to get the documentation augmented to remind users that transfercmd may need to handle responses and to request that at least getresp be added as a public interface. I think there's a special mail address for such requests but I'm too lazy^H^H^H^Hbusy to look it up just now. Eddie From reed at reedmedia.net Wed Mar 17 14:50:18 2004 From: reed at reedmedia.net (Jeremy C. Reed) Date: Wed, 17 Mar 2004 13:50:18 -0600 Subject: The python bindings for gconf (gnome-python2-gconf) could not be found. Message-ID: <6vKdnQ0Jt_dnNsXdRVn-sA@whidbeytel.com> Configuring gramps (genealogy software) says: checking Python bindings for gtk... ok checking Python bindings for GNOME... ok checking Python bindings for gconf... Traceback (most recent call last): File "conftest.py", line 17, in ? import gnome.gconf ImportError: No module named gconf cat: conftest.out: No such file or directory configure: error: **** The python bindings for gconf (gnome-python2-gconf) could not be found. *** Error code 1 I am able to repeat it with this simple python script (based on the configure code): -=-=-=- try: import pygtk pygtk.require('2.0') except ImportError: pass def out(str): f = open('conftest.out', 'w') f.write(str) f.close() try: import gconf out("YES") except ImportError: import gnome.gconf out("YES") except ImportError: out("NO") -=-=-=- For example: $ python gconf.test.python Traceback (most recent call last): File "gconf.test.python", line 16, in ? import gnome.gconf ImportError: No module named gconf I have gnome-python-2.0.0 installed. I installed using pkgsrc build system and it did not work. And I installed directly from source too. I assume I have the gconf module installed. How can I find out? I have: -rw-r--r-- 1 root root 296026 Mar 17 05:30 /usr/lib/python2p3/site-packages/gtk-2.0/gconf.a -rwxr-xr-x 1 root root 1114 Mar 17 06:08 /usr/lib/python2p3/site-packages/gtk-2.0/gconf.la -rwxr-xr-x 1 root root 182087 Mar 17 06:08 /usr/lib/python2p3/site-packages/gtk-2.0/gconf.so -rw-r--r-- 1 root root 29603 Mar 17 06:08 /usr/share/pygtk/2.0/defs/gconf.defs How can I get python to tell me what it is doing when it looks for and tries the module? I have built and installed this several times before. Just the past few days something has changed in my python setup or in my gnome-python. My python is: $ python -V Python 2p3.3 It is as installed using pkgsrc under Linux. (The package name is python23-pth-2.3.3nb1.) When I run python with debugging and verbose I get: # trying /usr/lib/python2p3/glob.py # /usr/lib/python2p3/glob.pyc matches /usr/lib/python2p3/glob.py import glob # precompiled from /usr/lib/python2p3/glob.pyc # trying /usr/lib/python2p3/site-packages/gtk-2.0/gconf.so import gnome # directory /usr/lib/python2p3/site-packages/gtk-2.0/gnome # trying /usr/lib/python2p3/site-packages/gtk-2.0/gnome/__init__.so # trying /usr/lib/python2p3/site-packages/gtk-2.0/gnome/__init__module.so # trying /usr/lib/python2p3/site-packages/gtk-2.0/gnome/__init__.py # /usr/lib/python2p3/site-packages/gtk-2.0/gnome/__init__.pyc matches /usr/lib/python2p3/site-packages/gtk-2.0/gnome/__init__.py import gnome # precompiled from /usr/lib/python2p3/site-packages/gtk-2.0/gnome/__init__.pyc # trying /usr/lib/python2p3/site-packages/gtk-2.0/gnome/ltihooks.so # trying /usr/lib/python2p3/site-packages/gtk-2.0/gnome/ltihooksmodule.so # trying /usr/lib/python2p3/site-packages/gtk-2.0/gnome/ltihooks.py # trying /usr/lib/python2p3/site-packages/gtk-2.0/gnome/ltihooks.pyc # trying /usr/lib/python2p3/site-packages/gtk-2.0/ltihooks.so # trying /usr/lib/python2p3/site-packages/gtk-2.0/ltihooksmodule.so # trying /usr/lib/python2p3/site-packages/gtk-2.0/ltihooks.py # trying /usr/lib/python2p3/site-packages/gtk-2.0/ltihooks.pyc # trying /usr/pkgsrc/databases/gramps/ltihooks.so # trying /usr/pkgsrc/databases/gramps/ltihooksmodule.so # trying /usr/pkgsrc/databases/gramps/ltihooks.py ... # trying /usr/lib/python2p3/site-packages/PIL/ltihooks.so # trying /usr/lib/python2p3/site-packages/PIL/ltihooksmodule.so # trying /usr/lib/python2p3/site-packages/PIL/ltihooks.py # trying /usr/lib/python2p3/site-packages/PIL/ltihooks.pyc # trying /usr/lib/python2p3/site-packages/gtk-2.0/gnome/gobject.so # trying /usr/lib/python2p3/site-packages/gtk-2.0/gnome/gobjectmodule.so # trying /usr/lib/python2p3/site-packages/gtk-2.0/gnome/gobject.py # trying /usr/lib/python2p3/site-packages/gtk-2.0/gnome/gobject.pyc # trying /usr/lib/python2p3/site-packages/gtk-2.0/gobject.so import gobject # dynamically loaded from /usr/lib/python2p3/site-packages/gtk-2.0/gobject.so # trying /usr/lib/python2p3/site-packages/gtk-2.0/gnome/_gnome.so # trying /usr/lib/python2p3/site-packages/gtk-2.0/gnome/gconf.so # trying /usr/lib/python2p3/site-packages/gtk-2.0/gnome/gconfmodule.so # trying /usr/lib/python2p3/site-packages/gtk-2.0/gnome/gconf.py # trying /usr/lib/python2p3/site-packages/gtk-2.0/gnome/gconf.pyc dlopen("/usr/lib/python2p3/lib-dynload/strop.so", 2); dlopen("/usr/lib/python2p3/site-packages/gtk-2.0/gconf.so", 2); dlopen("/usr/lib/python2p3/site-packages/gtk-2.0/gobject.so", 2); dlopen("/usr/lib/python2p3/site-packages/gtk-2.0/gnome/_gnome.so", 2); Traceback (most recent call last): File "gconf.test.python", line 16, in ? import gnome.gconf ImportError: No module named gconf # clear __builtin__._ # clear sys.path # clear sys.argv ... strace tells me: getdents64(3, /* 108 entries */, 4096) = 4096 getdents64(3, /* 96 entries */, 4096) = 3768 getdents64(3, /* 0 entries */, 4096) = 0 close(3) = 0 stat64("/usr/lib/python2p3/site-packages/gtk-2.0", {st_mode=S_IFDIR|0755, st_size=4096, ...}) = 0 stat64("/usr/lib/python2p3/site-packages/gtk-2.0/gconf", 0xbfffef40) = -1 ENOENT (No such file or directory) write(2, "# trying /usr/lib/python2p3/site-packages/gtk-2.0/gconf.so\n", 59# trying /usr/lib/python2p3/site-packages/gtk-2.0/gconf.so ) = 59 open("/usr/lib/python2p3/site-packages/gtk-2.0/gconf.so", O_RDONLY|O_LARGEFILE) = 3 fstat64(3, {st_mode=S_IFREG|0755, st_size=182087, ...}) = 0 open("/usr/lib/python2p3/site-packages/gtk-2.0/gconf.so", O_RDONLY) = 4 read(4, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\0\310;\0\0004\0\0\0\274\277\2\0\0\0\0\0004\0 \0\3\0(\0\"\0\37\0\1\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\300\207\0\0\300\207\0\0\5\0\0\0\0\20\0\0\1\0\0\0\ 300\207\0\0\300\227\0\0\300\227\0\0D\21\0\0h\21\0\0\6\0\0\0\0\20\0\0\2\0\0\0$\225\0\0$\245\0\0$\245 \0\0\20\1\0\0\20\1\0\0\6\0\0\0\4\0\0\0\305\0\0\0\313\0\0\0\0\0\0\0C\0\0\0\0\0\0\0\272\0\0\0\0\0\0\0 \0\0\0\0U\0\0\0\0\0\0\0\273\0\0\0\0\0\0\0\0\0\0\0003\0\0\0\0\0\0\0\257\0\0\0\0\0\0\0[\0\0\0\0\0\0\0 \243\0\0\0\0"..., 1024) = 1024 fstat64(4, {st_mode=S_IFREG|0755, st_size=182087, ...}) = 0 old_mmap(NULL, 43304, PROT_READ|PROT_EXEC, MAP_PRIVATE, 4, 0) = 0x4040c000 mprotect(0x40415000, 6440, PROT_NONE) = 0 old_mmap(0x40415000, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED, 4, 0x8000) = 0x40415000 close(4) = 0 open("/usr/gcc3/lib/libgconf-2.so.5", O_RDONLY) = -1 ENOENT (No such file or directory) open("/usr/lib/libgconf-2.so.5", O_RDONLY) = 4 /usr/lib/python2p3/site-packages/gtk-2.0/gconf.so does exist. How can I find out why it was skipped? $ ldd /usr/lib/python2p3/site-packages/gtk-2.0/gconf.so libgconf-2.so.5 => /usr/lib/libgconf-2.so.5 (0x4000c000) libORBit-2.so.0 => /usr/lib/libORBit-2.so.0 (0x40044000) libgobject-2.0.so.200 => /usr/lib/libgobject-2.0.so.200 (0x40080000) libgthread-2.0.so.200 => /usr/lib/libgthread-2.0.so.200 (0x400b7000) libm.so.6 => /lib/libm.so.6 (0x400c3000) libgmodule-2.0.so.200 => /usr/lib/libgmodule-2.0.so.200 (0x400e5000) libdl.so.2 => /lib/libdl.so.2 (0x400e9000) libglib-2.0.so.200 => /usr/lib/libglib-2.0.so.200 (0x400ec000) libc.so.6 => /lib/libc.so.6 (0x4015d000) libpthread.so.0 => /lib/libpthread.so.0 (0x40275000) liblinc.so.1 => /usr/lib/liblinc.so.1 (0x402c6000) libpopt.so.0 => /usr/lib/libpopt.so.0 (0x402ce000) /lib/ld-linux.so.2 => /lib/ld-linux.so.2 (0x80000000) On a NetBSD system, it works and is slightly different: # trying /usr/pkg/lib/python2p3/glob.py # /usr/pkg/lib/python2p3/glob.pyc matches /usr/pkg/lib/python2p3/glob.py import glob # precompiled from /usr/pkg/lib/python2p3/glob.pyc # trying /usr/pkg/lib/python2p3/site-packages/gtk-2.0/gconf.so # trying /usr/pkg/lib/python2p3/site-packages/gtk-2.0/gobject.so import gobject # dynamically loaded from /usr/pkg/lib/python2p3/site-packages/gt k-2.0/gobject.so import gconf # dynamically loaded from /usr/pkg/lib/python2p3/site-packages/gtk- 2.0/gconf.so # clear __builtin__._ # clear sys.path # clear sys.argv I am not sure what information is needed to troubleshoot this. The python and other packages are installed using pkgsrc system. I am pretty sure the problem is how it was configured or built, but I am trying to track down where this has changed. Any advice on this would be appreciated. Thank you, Jeremy C. Reed http://bsd.reedmedia.net/ From bram at nospam.sara.nl Mon Mar 8 08:42:03 2004 From: bram at nospam.sara.nl (Bram Stolk) Date: Mon, 8 Mar 2004 14:42:03 +0100 Subject: Calling a constructor in a default argument. Message-ID: <20040308144203.40f85891@pistache.sara.nl> Hello, I wrote a function that takes a default argument. The default arg is set to a constructor call. I expected this constructor to be called every time I call the func without the arg. However, it turns out that the constructor is called only once. Is this the desired behaviour, or a known bug? The output of the prog below is: Set([88, 89]) Set([88, 89, 100, 101]) Whereas I expected: Set([88, 89]) Set([100, 101]) Thanks, Bram #!/usr/bin/python -i import sys import sets import whrandom def foo(lst, set=sets.Set()) : for i in lst : set.add(i) return set print foo([88, 88,89]) print foo([100, 100,101]) -- ------------------------------------------------------------------------------ Bram Stolk, VR Specialist. SARA Academic Computing Services Amsterdam, PO Box 94613, 1090 GP AMSTERDAM email: bram at nospam.sara.nl Phone +31-20-5923059 Fax +31-20-6683167 "For the costs of subsidized agriculture in the EU, we can have all 56 million European cows fly around the world. First Class." - J. Norberg ------------------------------------------------------------------------------ From max at alcyone.com Tue Mar 16 21:48:38 2004 From: max at alcyone.com (Erik Max Francis) Date: Tue, 16 Mar 2004 18:48:38 -0800 Subject: Is Python type safe? References: <221d8dbe.0403161043.52406195@posting.google.com> <16471.26244.889193.809339@montanaro.dyndns.org> Message-ID: <4057BC86.BC3A897F@alcyone.com> Carl Banks wrote: > Here's my guess: > > long i = 0; > *(short*)&i = 1; > > if (i == 1) { printf("It's whatever one Intel uses.\n"); } > else { printf("It's the other one.\n"); } You meant char, not short. And none of the solutions so far acknowledge the fact that none of these types have absolute sizes as defined in the Standard. If I were conducting the interview, I'd take points off if that weren't at least acknowledged. -- __ 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 when you wake up in the morning and have a big smile. -- Anggun From edcogburn at hotpop.com Tue Mar 30 05:52:58 2004 From: edcogburn at hotpop.com (Ed Cogburn) Date: Tue, 30 Mar 2004 05:52:58 -0500 Subject: Python installing on Debian In-Reply-To: References: Message-ID: Haim Ashkenazi wrote: > Ryan Spencer wrote: > > >>On Mon, 29 Mar 2004 03:43:25 +0200, Haim Ashkenazi wrote: >> >> >>>It's a very bad idea to install self-compiled applications to the same >>>prefix as the ones from original packages. this can breake many things on >>>your computer. what you have now is a semi-broke python installation, and >>>a package that tries to install itself every time you run apt-get but >>>fails. >>> >>>I think your best chance to "clean" things would be to uninstall every >>>python2.3 package on your system (see what happenes when you run 'apt-get >>>remove --purge python2.3'). but make sure you understand what you're >>>doing (e.g. do you really want to purge your zope installaion? do you >>>have important stuff there, do you know how to restore it?). then if >>>there's still stuff in /usr/lib/python2.3 and /usr/local/lib/python2.3 >>>check that they don't belong to any package (with dpkg -S filename) and >>>remove them. also check if you have a python binary in /usr/local/bin and >>>delete it. then re-install all the python2.3 packages. this of-course >>>will make you lose all your self-compiled modules, so you'll have to >>>re-compile them. this is a long and messy job, but you got yourself into >>>this position. just make sure you understand what you're doing before >>>your doing it. >>> >>>in the future I would recommend using the source from unstable to build a >>>package if you want a version newer then the one that exist in testing. >>>also use 'stow' when you're compiling sources. this will let you >>>uninstall self-compiled application easilly. >>> >>> >>> >>>>Thanks a lot, >>> >>>good-luck (you'll need it) :( >> >>It actually needn't be that messy. dpkg --purge'ing will only remove the >>package in question, whereas using a program such as debfoster and pruning >>the selected target package will remove all it's associate dependencies >>entirely eradicating it from your system, maybe leaving behind empty >>configuration folders in your home directory, but there's no fret for >>that those won't be taking up barely any space and you can always remove >>them later. > > in my system 'apt-get remove --purge python2.3' wants to remove 401 > packages. that's what I meant messy. you have to check that you didn't > change any system configuration file for any of the packages. and as a > rule, it's a good idea to understand what's you're doing. I've seen too > many times people following instructions and then discovering that nothing > works without knowing how to restore... It seems apt has gotten so popular that everyone has forgotten about dpkg, which apt is built upon. :) Yes, apt-get follows dependencies in that way, which is why apt was created, to handle dependencies automatically. In this case however, it may not be necessary to remove everything to restore python. It makes sense to try the least painful remedy first. If it were me, I would first try rebuilding the python .deb package from my system with dpkg-repack as a backup, then using 'dpkg --force-all --purge python2.3' to delete just the python interpreter itself, not any of the packages that depend on it. Clean any python directories/files left behind (there sometimes is in places like /etc and /usr/lib, etc), then reinstall python2.3 using the .deb you created with dpkg-repack. If that fails, then try downloading a guaranteed virgin copy of the .deb package and repeating again. If that fails too, then you're forced to start purging other python-related things to figure out whats causing the problem. My point is that when apt doesn't do what you need it to do, you can always fall back on dpkg. In this case the problem is likely to be the OP partially overwrote Debian's python with his own custom compiled one, because I have seen that "import site" failure happen when I did this myself some time ago. I wasn't even installing the compiled version, I just built it and manually transferred the shared libs and executable to /usr, but that was enough to break some of the written-in-python library files. Moral of the story: don't mix standard and custom-built packages. If you want to try a custom built one, completely deinstall the standard one first. From nick.carter at roke.co.uk Tue Mar 2 06:09:00 2004 From: nick.carter at roke.co.uk (Nick Carter) Date: Tue, 2 Mar 2004 11:09:00 -0000 Subject: Binaries for Swish-E and Python 2.3 for Windows References: Message-ID: Binaries for Swish-E and Python 2.3 for WindowsPieter, Try here: http://lorrain.ca/foss/ Nick "Pieter Claerhout" wrote in message news:mailman.15.1078215556.12614.python-list at python.org... Hi all, does anyone has a precompiled version for Python 2.3 on Windows for the following library: http://jibe.freeshell.org/bits/SwishE/ I'm trying to access a Swish-E database from Python, but I don't have access to a compiler unfortunately. 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) -------------- next part -------------- An HTML attachment was scrubbed... URL: From miki.tebeka at zoran.com Mon Mar 8 11:56:49 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Mon, 08 Mar 2004 18:56:49 +0200 Subject: os.popen() failing under ipython+cygwin, I'm stumped. In-Reply-To: References: Message-ID: <404CA5D1.6080706@zoran.com> Hello Fernando, > We've narrowed it down to the following. Under ipython, here is what he gets > with a popen() call: > > ,--- > | Python 2.3.3 (#1, Dec 30 2003, 08:29:25) > | Type "copyright", "credits" or "license" for more information. > | > | IPython 0.5.0 -- An enhanced Interactive Python. > | ? -> Introduction to IPython's features. > | @magic -> Information about IPython's 'magic' @ functions. > | help -> Python's own help system. > | object? -> Details about 'object'. ?object also works, ?? prints more. > | 1% import os > | 2% xmode Verbose > | Exception reporting mode: Verbose > | 3% pipe=os.popen('less','w') > | 10 [main] python2.3 2896 sync_with_child: child 3032(0x6D4) died before > initialization with status code 0x1 > | 9375 [main] python2.3 2896 sync_with_child: *** child state child loading > dlls > | --------------------------------------------------------------------------- > | OSError Traceback (most recent call last) > | > | /home/thorsten/ > | > | OSError: [Errno 11] Resource temporarily unavailable > I've installed IPython 0.5.0 with `python setup.py install' then: --- [18:46] $ipython Python 2.3.3 (#1, Dec 22 2003, 11:56:28) Type "copyright", "credits" or "license" for more information. IPython 0.5.0 -- An enhanced Interactive Python. ? -> Introduction to IPython's features. @magic -> Information about IPython's 'magic' @ functions. help -> Python's own help system. object? -> Details about 'object'. ?object also works, ?? prints more. In [1]: import os In [2]: xmode verbose Exception reporting mode: Verbose In [3]: --- Maybe upgrade your cygwin? My dll version is 1.5.7-1 (run `cygcheck -s | egrep "^cygwin"' to find your version) HTH. Miki From miki.tebeka at zoran.com Sun Mar 14 02:22:41 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Sun, 14 Mar 2004 09:22:41 +0200 Subject: List append help In-Reply-To: <105811aq55rah53@corp.supernews.com> References: <105811aq55rah53@corp.supernews.com> Message-ID: <40540841.8070802@zoran.com> Hello Bill, > Could someone please tell me why the "hireCrew" > method in the following code leaves me with a list that contains "None"? > ... > self.myCrew = self.myCrew.append(argHire) The return value of list.append is None. However it does add the item to the list. Try: self.myCrew.append(argHire) On a side note, I find this `arg' prefix for an argument irritating :-) HTH. Miki From python at rcn.com Tue Mar 23 03:36:05 2004 From: python at rcn.com (Raymond Hettinger) Date: 23 Mar 2004 00:36:05 -0800 Subject: SHA-based subclass for random module References: <87oeqpaqih.fsf@Ronaldann.demon.co.uk> <5d83790c.0403221047.2db9a9a1@posting.google.com> <87k71cbpjd.fsf@Ronaldann.demon.co.uk> Message-ID: <5d83790c.0403230036.3e9b08dc@posting.google.com> [Holger Duerer] > >> 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? > > Raymond> genrandbits() pulls as many bits as requested out of the > Raymond> underlying generator. The Mersenne Twister carries 624 > Raymond> words of internal state (about 20000 bits) so it is > Raymond> capable of supplying all the bits needed for this > Raymond> application. > > Raymond> So, yes, the plaintext will span the 2^128 possibilities. [Holger Duerer] > Well, I am aware that the state is larger. But my understanding from > a quick glance at the code was that you seed it with only an unsigned > long (automatically done with time(NULL) for you if you don't provide > a seed -- even worse at it reduces the search space dramatically). The seed(x) method accepts longs and can have an arbitrary number of bits. If using this proposed generator cryptographically, the seed should be viewed as a key and all the usual precautions should be taken (secrecy, long length, and a pure random source). So, what ever you do, don't seed it with time! Raymond From merkosh at hadiko.de Sun Mar 21 10:11:06 2004 From: merkosh at hadiko.de (Uwe Mayer) Date: Sun, 21 Mar 2004 16:11:06 +0100 Subject: call up, notify down Message-ID: Hi, someone told me this on how layered-architectures work. It took me some time to read-up to it, but now I think its rather the other way around: The lower layers provide functionality to upper layers. Therefore it should be: call down, notify up. Qt does it the same way, as I understood it: You call the public methods of underlying objects and can install SIGNALs to be notified (notify up). This flips if I misunderstood the meaning of up and down, but to me "down" means the more fundamental components. Going up from a root-node. Ciao Uwe From jcarlson at nospam.uci.edu Fri Mar 19 18:44:45 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Fri, 19 Mar 2004 15:44:45 -0800 Subject: py2exe 0.5.0 and data_files In-Reply-To: <87fzc4h036.fsf@u-go.net> References: <87fzc4h036.fsf@u-go.net> Message-ID: Try the following... ex_name = 'myprogram.exe' if sys.path[0][-len(ex_name):] == ex_name: path = os.path.split(sys.path[0]) else: path = os.path.split(__file__) I don't know if the above works correctly when the script is not a part of an executable, but is imported with zipimport. - Josiah From aisomurs at paju.oulu.fi Fri Mar 12 16:19:44 2004 From: aisomurs at paju.oulu.fi (Antti Isomursu) Date: 12 Mar 2004 13:19:44 -0800 Subject: Newbie question, Help needed! Message-ID: Ok, this is my problem. I have a list, with several items. I can move forward in that list using iterator (for example, iter(x) and then, it.next()...) But how can I move backwards? From roy at panix.com Fri Mar 12 08:48:37 2004 From: roy at panix.com (Roy Smith) Date: Fri, 12 Mar 2004 08:48:37 -0500 Subject: Xemacs syntax highlighting References: <1d17eeb7.0403111721.7aae9a76@posting.google.com> Message-ID: In article , Skip Montanaro wrote: > What version of python-mode.el are you using? I use the latest version from > CVS (4.51). I just downloaded python-mode.el a couple of days ago from www.python.org and got version 4.6, for use with GNU Emacs 21.2.1 on my Mac OSX box. > "def" is a purplish color (as are all keywords). The function > name is a reddish color. Strings are green. Comments are blue. I'm getting keywords in teal (sort of a light blue), function names in dark blue, strings in green, and comments in red. Everything else in black. From grelens at NOSPAMyahoo.NOTNEEDEDfr Thu Mar 4 03:29:04 2004 From: grelens at NOSPAMyahoo.NOTNEEDEDfr (GrelEns) Date: Thu, 4 Mar 2004 09:29:04 +0100 Subject: i'm lost in list manipulation References: <40460bb3$0$28116$636a15ce@news.free.fr> <404653cb$1_1@themost.net> <4046e6d6$0$4677$626a14ce@news.free.fr> Message-ID: <4046e8c1$0$4666$626a14ce@news.free.fr> "GrelEns" a ?crit dans le message de news: 4046e6d6$0$4677$626a14ce at news.free.fr... > > btw please give your opinion on this one : > > def build(l, n): > result = [] > if n == 1: > for e in l: > result.append([e]) > else: > subSet = build(l, n - 1) > for n_uples in subSet: > iLast = l.index(n_uples[-1]) > if iLast < len(l) - 1: > for e in l[iLast + 1:]: > tmp = n_uples + [e] > result.append(tmp) > return result > > def allSets(l): > """from [1,2,3] will build [[1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, > 3]]""" > result = [] > for i in range(1, len(l)): > result += build(l, i) > result.append(l) > return result i'm not happy with this code, must be an other shorter alternative, have you any siggestions on how to build these sets [[1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]] from [1,2,3] ? best From skip at pobox.com Sat Mar 27 13:57:58 2004 From: skip at pobox.com (Skip Montanaro) Date: Sat, 27 Mar 2004 12:57:58 -0600 Subject: A 'Python like' language In-Reply-To: References: <40645d8f$0$10775$afc38c87@news.easynet.co.uk> <1068up4kn49778@news.supernews.com> Message-ID: <16485.52918.622130.779482@montanaro.dyndns.org> >> 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. David> I've never had this problem. Is this something MS exchange does? No. It's just that with so many virii running around attached to email that often the simplest thing to do is to strip delete all attachments passing through mailing list manager software. Skip From tjreedy at udel.edu Tue Mar 23 09:34:06 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 23 Mar 2004 09:34:06 -0500 Subject: PEP 318 References: <95aa1afa.0403222352.2679dde@posting.google.com> Message-ID: "Michele Simionato" wrote in message news:95aa1afa.0403222352.2679dde at posting.google.com... > def __mul__(self,other) as multimethod(Vector,Scalar): [et cetara] This PEP proposes somewhat implicit declarative syntax in the function heading as a substitute (but not replacement) for an explicit procedural call after the function call. This is similar to the doc string rule, and just as 'unnecessary'. However, if instead of writing def f(): 'f: a function to illustrate a point' pass we had to write def f(): pass f.__doc__ = 'f: a function to illustrate a point' (as we now can), I suspect there would be fewer doc strings written. Even if not, they would be less useful to readers. I see the point of the PEP at putting information about a function at the top so readers can more easy see it before reading the body, if indeed they need to read the implementation detail. So I suspect the result of this PEP would be more functional transformations than at present. It certainly emphasizes the point that Python functions are first-class objects which can be manipulated and wrapped just like other objects. I consider this a positive, but have no strong opinion on '(args) [deco]' versus 'as deco'. Terry J. Reedy From anand at easi.soft.net Tue Mar 16 06:35:08 2004 From: anand at easi.soft.net (Anand K Rayudu) Date: Tue, 16 Mar 2004 17:05:08 +0530 Subject: how import works Message-ID: <4056E66C.1000409@easi.soft.net> Hi all, Currently i have embedded python and extended my application for python. While invoking python intrepter I call following function so that all my exposed APIs are available for python scripting. Py_InitModule("myModule", MyModuleMethods); This is fine so far. But i have a requirement that end user can add his own extension modules, so in that case I don't want to change code to add some more intializations Py_InitModule("myModule", MyModuleMethods); Py_InitModule("myNewModule", MyNewModuleMethods); import myNewMoudle should call above function. Is there a way that i can do it, I believe disutil can do some thing, but not sure of how it works. The solution should be compatible on all UNIX and Windows machines. Can some one please help me on this subject & probably some link to documentation. Thanks in advance. Anand From newsgroups at jhrothjr.com Fri Mar 12 13:24:21 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Fri, 12 Mar 2004 13:24:21 -0500 Subject: Deprecating reload() ??? References: <40514A48.50907@domain.invalid> Message-ID: <105405ogq0t2s61@news.supernews.com> "David MacQuigg" wrote in message news:hgr3501a1qu612fvumq5ccd0vrocdoc4pf at 4ax.com... > On Fri, 12 Mar 2004 08:20:14 -0600, Skip Montanaro > wrote: > > >Given Python's current object model it would be an interesting challenge to > >write a "super reload" which could identify all the objects created as a > >side effect of importing a module and for those with multiple references, > >locate those other references by traversing the known object spaces, then > >perform the import and finally rebind the references found in the first > >step. I thought I saw something like this posted in a previous thread on > >this subject. > > I'm not familiar with the internals of Python, but I was assuming that > all objects could be easily associated with the module which created > them. If not, maybe what we need is the ability to put a selected > module in "debug" mode and keep a list of all objects created by that > module and all references to those objects. That would add a little > overhead, but avoid the difficulties of searching all object spaces > with every reload. That's actually the wrong end of the problem. Even if you could associate all the objects with the module that created them, you would still have to find all the references to those modules. That's the harder of the two tasks. It's actually relatively easy to find the objects that would have to be replaced: it's all of the objects that are bound at the module level in the module you're replacing. Since CPython uses memory addresses as IDs, it's trivially easy to stick them in a dictionary and compare them while scanning all the places they could possibly be bound. John Roth > > -- Dave > From __peter__ at web.de Thu Mar 4 11:36:41 2004 From: __peter__ at web.de (Peter Otten) Date: Thu, 04 Mar 2004 17:36:41 +0100 Subject: how fast is object-oriented Python code? References: <3064b51d.0403040759.452953ea@posting.google.com> Message-ID: beliavsky at aol.com wrote: > I know that object-oriented numerical code in C++ can be much slower > than the procedural C or Fortran equivalent, unless one is careful. To > what extent is this true with OO and non-OO Python? $ timeit.py -s"def x(): pass" "x()" 1000000 loops, best of 3: 0.437 usec per loop $ timeit.py -s"class X:" -s" def x(self): pass" -s"x=X()" "x.x()" 1000000 loops, best of 3: 0.694 usec per loop The above bogus example would suggest an extra cost of 60 percent. Let's modify it a little: $ timeit.py -s"class X:" -s" def x(self): pass" -s"x=X().x" "x()" 1000000 loops, best of 3: 0.446 usec per loop With a tiny change almost all of the overhead goes away. I think with a grain of salt the same is true on a larger scale. The speed of an application is determined by the quality of its design, not by the programming paradigm employed. Peter From wmgill at gcgroup.net Thu Mar 4 11:14:23 2004 From: wmgill at gcgroup.net (William D. Gill) Date: Thu, 4 Mar 2004 11:14:23 -0500 Subject: python classes Message-ID: I'm new to python and am probably trying too many new things at once, but here goes. I am working with a (MySQL) database and am trying to make a html /python interface for editing records. Data is broken up into several tables, and related by customer number. For example one table contains basic information about the customer, one table phone numbers (one record for published number, one for cell phone, etc, all customers will have at least one record here). I want to use python classes in my code so I have a couple of questions about python classes: 1) can a class __init__ have multiple "signatures like in C++ i.e. MyClass( int, string), . MyClass(int) ? 2) can a class attribute be an instance of another class or is multiple inheritance the proper answer? 3) Can I make instantiation fail if an invalid customer number is use, and wrap the "a=MyClass(cusid=999) in an exception? Thanks in advance, Bill From mcfletch at rogers.com Tue Mar 16 10:21:30 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Tue, 16 Mar 2004 10:21:30 -0500 Subject: embedding opengl in wxpython window [Re: Advice needed: large OpenGL + Widgets Project for Molecular] In-Reply-To: References: <5eb8fb88.0403151925.4f63842b@posting.google.com> Message-ID: <40571B7A.8080107@rogers.com> DH wrote: ... > The problem I have though is - can you have an opengl canvas in the > same window with other wxpython controls. I've done this in java, > basic and C, but the wxpython demo only showed opengl animations > running in their own window. This is my problem with vpython and sdl > too. I want something that can be embedded in a tk/wx/qt/gtk window > with other controls, even other opengl canvases. At the C level, it's > just a matter of clipping the drawing and switching the current > drawing context. This works fine. See the browser sub-package of OpenGLContext for a demo. See also much simpler demo in OpenGLContext/tests/wx_with_controls.py, which just puts a button and a wxPython Context (derived from wxGLCanvas) on a window and uses the button to start/stop the animation. PyOpenGL and wxPython are both just thin wrappers around their respective C/C++ libraries, so most of the functionality in the lower levels is available. > >> Disadvantages: The OpenGL install still crashed under Windows. A > >> widget set that not many people use? Also requires the most amount > >> of code rewrite, although if it's the best option it isn't a > >> problem. > > Yeah, it doesn't work on Windows for me either with python 2.3. It > used to work with python 2.2. Now it complains about not finding glut. If you encounter a bug like this, please submit a bug-report to the project so that it can be fixed. As a quick check though, you did install the GLUT binary package in your system32 directory, right? PyOpenGL doesn't include the GLUT library itself, only a binding for it. Have fun, Mike _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From JasonHarper at pobox.com Mon Mar 15 14:59:46 2004 From: JasonHarper at pobox.com (Jason Harper) Date: Mon, 15 Mar 2004 12:59:46 -0700 Subject: tkinter entry/text widget References: Message-ID: <405609D7.F674BE9E@pobox.com> Tk Text widgets do not support indexes in the form of single integers, since their internal representation is NOT a contiguous block of memory (which would be horribly inefficient for insertions at the top of a large document). Instead, you must use indexes of the form "line.column", where line starts at 1, and column starts at 0. To get the entire text, you'd use: .get("1.0", END) . Other allowed forms of indexes are given in the documentation. Jason Harper From joe at notcharles.ca Sun Mar 28 11:56:29 2004 From: joe at notcharles.ca (Joe Mason) Date: Sun, 28 Mar 2004 16:56:29 GMT Subject: Minor observation on the programming enterprise (was: Python for large projects) References: <1060p59d9rg9819@corp.supernews.com> <8ef9bea6.0403260837.72a8fade@posting.google.com> <106e0498vbqa611@corp.supernews.com> Message-ID: In article <106e0498vbqa611 at corp.supernews.com>, Cameron Laird wrote: Remarkable fact that I see as turning up all over: we work with > grep(1). There are visual programming and language-savvy editors > and IDEs and refactoring plugins and all sorts of other tools, > and we find our variables with text searches. 'Know how to make > a C programmer mad? Name a global variable 'i'. 'Know how to > make him happy? Change the name to 'ii'. Both Lisp's inventor > and I keep our human address collection in a plaintext file. My address collection was scattered all over various databases and phones, and I lost the phone with the most recent one. I spent a good hour searching for an important number, and realized that the one database I might still have access to was for a PDA I no longer owned, with a desktop app that I could no longer run, in a Windows partition that I couldn't boot to at the time. I could see the actual data, but knowing the Windows world I was almost positive it'd be some binary database, and I'd be out of luck. Nope, XML. Almost as good as plain text for grepping. I've never been so relieved. Joe From No.Spam.mc at No.Spam.mclaveau.No.Spam.com Fri Mar 12 08:22:41 2004 From: No.Spam.mc at No.Spam.mclaveau.No.Spam.com (Michel Claveau/Hamster) Date: Fri, 12 Mar 2004 14:22:41 +0100 Subject: Video module? References: Message-ID: Cool ! From jcarlson at nospam.uci.edu Tue Mar 9 01:34:26 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Mon, 08 Mar 2004 22:34:26 -0800 Subject: PEP 328: Imports: Multi-Line and Absolute/Relative In-Reply-To: References: Message-ID: > [-5.dirname.dirname.dirname]filename The above is relatively clear, though the brackets kind of destroy the clarity. For magical syntax, it isn't bad. I prefer the standard semantics already offered: from MODULE import NAMES as RENAME searching HOW import NAMES as RENAME from MODULE searching HOW Or for backwards compatibility: from HOW.MODULE import NAMES as RENAME import HOW.MODULE.NAMES as RENAME Where HOW is of the form: -[.PACKAGE1[.PACKAGE2[...]]] [PACKAGE1[.PACKAGE2[...]]] With the search stepping up path levels, then traversing down through the listed packages, not stepping up any path levels when the -integer is not given, and raising a SyntaxError for -0 imports. For example: for HOW: -1.sibling_package maps to ../sibling_package/MODULE.(py|pyc|pyo|pyd|so|dll) -2.uncle_package.cousin_package maps to ../../uncle_package/cousin_package/MODULE.(ext) -0.[other stuff] should raise a SyntaxError child_package.grandchild_package.great_grandchild_module maps to ./child_package/grandchild_package/great_grandchild_module.(ext) I think such behavior is clear enough magical syntax, what do others think? - Josiah From jcarlson at nospam.uci.edu Sat Mar 27 17:45:59 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Sat, 27 Mar 2004 14:45:59 -0800 Subject: A 'Python like' language In-Reply-To: References: <40645d8f$0$10775$afc38c87@news.easynet.co.uk> <95aa1afa.0403262049.4b2a6f78@posting.google.com> <95aa1afa.0403271039.5a351884@posting.google.com> Message-ID: > > 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.) > Usually contests of the sort offer the opportunity to submit a "pretty" and a "small" version of your code. One that contains proper spacing, another that contains minimal spacing. Show me a contest that doesn't allow it, and I'll show you a contest that isn't worth entering. - Josiah From aahz at pythoncraft.com Tue Mar 9 12:41:35 2004 From: aahz at pythoncraft.com (Aahz) Date: 9 Mar 2004 12:41:35 -0500 Subject: Sending bulk email from a Python script References: <2004030816344216807%cs1spw@bathacuk> Message-ID: In article <2004030816344216807%cs1spw at bathacuk>, 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. Don't use sendmail directly. Just send via SMTP and let the server handle the batching. You might consider using a better MTA (postfix or Exim) unless you've got an admin you *really* likes sendmail. -- 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 haim at babysnakes.org Mon Mar 22 12:27:04 2004 From: haim at babysnakes.org (Haim Ashkenazi) Date: Mon, 22 Mar 2004 19:27:04 +0200 Subject: py2exe icon resource on win98 References: Message-ID: Thomas Heller wrote: > Haim Ashkenazi writes: > >> Hi >> >> I'm trying to build a binary with py2exe. I've used the method suggested >> in the py2exe wiki about adding icon resources to apps. it build ok on >> win2k, but when I try to build the same on win98 I get this error: >> >> copying C:\Python23\Lib\site-packages\py2exe\run.exe -> C:\My >> Documents\NS_Backup\dist\NS_Backup.exe >> Traceback (most recent call last): >> File "Setup.py", line 13, in ? >> windows = [ >> File "C:\PYTHON23\lib\distutils\core.py", line 149, in setup >> dist.run_commands() >> File "C:\PYTHON23\lib\distutils\dist.py", line 907, in run_commands >> self.run_command(cmd) >> File "C:\PYTHON23\lib\distutils\dist.py", line 927, in run_command >> cmd_obj.run() >> File "C:\Python23\Lib\site-packages\py2exe\build_exe.py", line 197, in >> run >> self.create_binaries(py_files, extensions, dlls) >> File "C:\Python23\Lib\site-packages\py2exe\build_exe.py", line 391, in >> create_binaries >> arcname, target.script) >> File "C:\Python23\Lib\site-packages\py2exe\build_exe.py", line 577, in >> build_executable >> add_icon(unicode(exe_path), unicode(ico_filename), ico_id) >> RuntimeError: MapExistingFile: The handle is invalid >> >> ---------------------------------- >> I've attached my "setup.py". >> >> anyone has any ideas? > > I assume you have unicows.dll installed (this is required on win98), as > described in the py2exe webpage. of course :) > > The build process on win98 is not tested very good, maybe I overlooked > something. Can you build your exe when you comment out all the icon > resources? yes. without a problem. it's win98 first edition without any updates (internet explorer 4). > > Thomas > > thanx -- Haim From michele.simionato at poste.it Tue Mar 23 02:52:11 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 22 Mar 2004 23:52:11 -0800 Subject: PEP 318 References: Message-ID: <95aa1afa.0403222352.2679dde@posting.google.com> Skip Montanaro wrote in message news:... > 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. > > 1. From Fred Drake: > > As an (admittedly trivial) example, I'd be quite happy for: > > class Color [valuemap]: > red = rgb(255, 0, 0) > blue = rgb(0, 255, 0) > green = rgb(0, 0, 255) > > to cause the name Color to be bound to a non-callable object. Why must > the decorators be required to return callables? It will not make sense > in all circumstances when a decorator is being used. Ok. > 2. From Anders Munch: > > Given that the decorator expression can be an arbitrary Python > expression, it _will_ be used as such. For example: > > def foo(arg1, arg2) as release( > version="1.0", > author="me", > status="Well I wrote it so it works, m'kay?", > warning="You might want to use the Foo class instead"): Nice, > 3. From Shane Hathaway: > > Ooh, what about this: > > def singleton(klass): > return klass() > > class MyThing [singleton]: > ... > > That would be splendid IMHO. This one I don't like (not the syntax, the implementation). I want my singleton to be a class I can derive from. This can be done by using a metaclass as decorator (I posted an example months ago). > There are plenty of other examples. Browse the archives. > > think-outside-the-bun-(tm)-ly, y'rs, > > Skip And don't forget Ville Vanio's idea of using the new syntax to implement multimethods: def __mul__(self,other) as multimethod(Matrix,Matrix): ... def __mul__(self,other) as multimethod(Matrix,Vector): ... def __mul__(self,other) as multimethod(Matrix,Scalar): ... def __mul__(self,other) as multimethod(Vector,Vector): ... def __mul__(self,other) as multimethod(Vector,Scalar): ... etc. Way cool, actually :) Michele Simionato From peter at engcorp.com Mon Mar 22 09:43:59 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 22 Mar 2004 09:43:59 -0500 Subject: What's missing from python? In-Reply-To: <405ee0d0$0$63627$5a6aecb4@news.aaisp.net.uk> References: <405ee0d0$0$63627$5a6aecb4@news.aaisp.net.uk> Message-ID: John Burton wrote: > One of the reasons I like python so much is that the standard > installation comes with a whole lot of libraries to do lots of useful > things but there seem to be a few things missing from the standard > library which would be useful in many projects: > > Encryption - AES and 3DES. Possibly RSA and Certificate processing. > DNS - Something better than gethostbyaddr for looking up other record > types. > Database - Something suitable for small projects / prototypes like > pysqlite or something in pure python even. > SSL/TLS - Some useful support... > > A lot of projects seem to need some of those. It's easy enough to > install extras to do those thing but they are all things where it would > be nice to have something in the standard library that you could rely on > being there. > > Is there any reason why those things are not already in the standard > library? Yes, they aren't mature enough to be in there yet (because the work is not complete, probably because not enough people are helping). That's at least a partial answer. Were I actually one who helped with the core work on these things myself, I would doubtless add "contributions are welcome!" :-) -Peter From james.g.tanner at boeing.com Wed Mar 10 15:29:10 2004 From: james.g.tanner at boeing.com (Jim Tanner) Date: Wed, 10 Mar 2004 20:29:10 GMT Subject: Python 2.3.2 spawn problem Message-ID: I am trying to start the 2.3.3 IDL and getting an error. I think I might have a dll conflict, but the 2.2.3 IDL works fine. The 2.3.3 IDL used to work just fine. The following are the Traceback error messages: bash-2.05b$ python.exe Lib/idlelib/idle.pyw C:\cygwin\bin\python2.3.exe: *** unable to remap C:\cygwin\bin\cygssl-0.9.7.dll to same address as parent(0x720000) != 0x730000 407 [main] python 2496 sync_with_child: child 3112(0x180) died before initia lization with status code 0x1 903 [main] python 2496 sync_with_child: *** child state child loading dlls Traceback (most recent call last): File "Lib/idlelib/idle.pyw", line 4, in ? main() File "/cygdrive/c/Python23/Lib/idlelib/PyShell.py", line 1282, in main flist.pyshell = PyShell(flist) File "/cygdrive/c/Python23/Lib/idlelib/PyShell.py", line 764, in __init__ self.interp.start_subprocess() File "/cygdrive/c/Python23/Lib/idlelib/PyShell.py", line 355, in start_subproc ess self.spawn_subprocess() File "/cygdrive/c/Python23/Lib/idlelib/PyShell.py", line 321, in spawn_subproc ess self.rpcpid = os.spawnv(os.P_NOWAIT, sys.executable, args) File "/usr/lib/python2.3/os.py", line 521, in spawnv return _spawnvef(mode, file, args, None, execv) File "/usr/lib/python2.3/os.py", line 489, in _spawnvef pid = fork() OSError: [Errno 11] Resource temporarily unavailable Thanks for your assistance, Jim Tanner From cs1spw at bath.ac.uk Mon Mar 8 20:06:44 2004 From: cs1spw at bath.ac.uk (Simon Willison) Date: Mon, 8 Mar 2004 19:06:44 -0600 Subject: Sending bulk email from a Python script References: <104q5jpg86q2udf@corp.supernews.com> Message-ID: <2004030819064420092%cs1spw@bathacuk> On 2004-03-08 18:57:29 -0600, claird at lairds.com (Cameron Laird) said: > In article <2004030818081575249%cs1spw at bathacuk>, > Simon Willison wrote: > >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. > . > Give us a notion of scope. Does "large list" mean to you a thousand? > Hundred thousand? Ten million? How often are you sending out e-mail? Our largest list at the moment is 4,000 addresses. The business we are in (local online newspaper) means we are very unlikely to ever have more than 10,000. The answer certainly relates to sendmail, but I'm interested in any experience other people may have with this kind of task. At the moment I'm looking at using smtplib and just cycling through calling smtp.send() once for every address but I'm not confident that that this is a particularly efficient method. If there's a better option I'd love to hear about it. Cheers, Simon From jack at performancedrivers.com Tue Mar 30 00:06:15 2004 From: jack at performancedrivers.com (Jack Diederich) Date: Tue, 30 Mar 2004 00:06:15 -0500 Subject: Tkfont buggy for two Tk() top level windows In-Reply-To: <20040330045726.GB1313@performancedrivers.com> References: <20040330045726.GB1313@performancedrivers.com> Message-ID: <20040330050615.GC1313@performancedrivers.com> [top post] Awwww, screw me. TopLevel() does what I want. After searching groups.goole and skimming Programming Python I posted. And its right there in the docs (and TopLevel is in the index of PP). Any Tkinter folks that are listening, consider printing a warning to stdout when Tk() is called twice or preferably raising an exception instead of limping along. On Mon, Mar 29, 2004 at 11:57:26PM -0500, Jack Diederich wrote: > I'm calling Tk() twice to create two top level windows, > which works fine in every respect except fonts. > Assigning a Tkfont to widgets in the first Tk() window I create works > fine, the font looks good as it should. But if I start a another > window by calling Tk() again the second window will always use some > awful default font. Swapping the two lines that call Tk() will > change which one actually uses the font and which doesn't. > > The code looks like: > win_one = Tk() > win_two = Tk() > myfont = tkFont.Font(family="Courier", size=12) > > Entry(win_one, font=myfont).pack(fill='both',expand=1) > Entry(win_two, font=myfont).pack(fill='both',expand=1) > > Any text on the first window obeys the font, the second > one will always use some system default. switching the two lines > that call Tk() reverses which window goes font happy. > > If calling Tk() twice has undefined behavior I would rather it > raise a useful exception instead of continuing partially gimpy. > > Debian testing, python 2.3.3, tk 8.2.3-5 > This has been the behavior for 6-12 months (as long as I've been using > Tk). Until now I just assumed I had missed a call, after checking it > out it seems to be a Tk thing. > > TIA, > > -jackdied > > > > -- > http://mail.python.org/mailman/listinfo/python-list > From frnknstn at iafrica.com Sat Mar 27 08:10:11 2004 From: frnknstn at iafrica.com (Peter Finlayson) Date: Sat, 27 Mar 2004 15:10:11 +0200 Subject: SHA-based subclass for random module In-Reply-To: <_qN8c.42856$wj2.30269@newssvr25.news.prodigy.com> References: <7xu10ddxie.fsf@ruckus.brouhaha.com> Message-ID: <40659953.3349.9FD2A8@localhost> I have been following this thread with great interest. I am very new to Python, and this group (struggling to keep up with the heavy traffic.) Some of the stuff here went over my head, as I am not a gifted mathematician, but it did get me thinking. I find random number generators facinating, and I have a perfectionist streak in me that really dislikes several of the flawed generators used frequently. Still, if you are aiming for totally nondeterminant random numbers, there are better ways to do it than with SHA with its inevitable collisions. If we assume that every bit from the MT generator is roughly as 'random' as all the others, why not use the oldest cryptographic trick in the book: One-time-pads? Python is largely designed as a scripting language, so why not just pull a random file off the system and (perhaps after removing the file's header) use the raw data to offset the getrandbits() data? Wait, I suppose that may not be random enough. There are only a finite number of files on your system, and I suppose that for $250 000 the poker players could have hacked into the system and downloaded the complete contents of all the memory. Well, Python is a scripting language, so why not just use httplib to download some random file off the internet, and use that? Every morning, just get the latest files of your favorite site, and use them to offset the getrandbits() data. I can see it now, porn-powered cryptographic pseudo-random number generators! Wait, there is only a finite amount of porn in the world. I know, why not just use the latests comments posted on Slashdot? That is an *inexhaustable* supply of rubbish. Nobody would sift through all that, not ever for a MILLION dollars. :) Peter Finlayson From see_below at hazen.net Fri Mar 19 06:13:02 2004 From: see_below at hazen.net (John Hazen) Date: Fri, 19 Mar 2004 03:13:02 -0800 Subject: services In-Reply-To: References: Message-ID: <20040319111302.GC31626@gate2.hazen.net> * Laurent Vincelette [2004-03-18 19:53]: > I have a python script (file start with #!/usr/bin/python) that use > xmlrpclib to lessen and respond on port:8000. The problem is when I > close the shell (bash in remote with putty) the script stop to work. I > try to start it in backgroud with & but it dosent work. Finally I copy > and I try to modify the /etc/init.d/crond to start the script in > services (with start-stop-demon but I have the same problem... When I > close putty the script stop. > > Someone have a idea? try: % nohup file.py & It redirects the output (and stderr) to ./nohup.out, and prevents the HUP signal from being sent to the process when you log out. And if you want the service to run at startup, I'd probably create a separate startup script (if it's running as a permament service, I don't think cron has anything to do with it) which launches it and redirects the output. -John at hazen.net From SBrunning at trisystems.co.uk Wed Mar 10 12:51:17 2004 From: SBrunning at trisystems.co.uk (SBrunning at trisystems.co.uk) Date: Wed, 10 Mar 2004 17:51:17 -0000 Subject: Nice way of getting items from two lists Message-ID: <31575A892FF6D1118F5800600846864D01201055@intrepid> > From: C GIllespie [mailto:csgcsg39 at hotmail.com] > > I have two equal size lists - list1, list2. Basically, each > item in list 1 > has a partner in list2. I was wanting to do something like > So if: > list1=['x','y','z'] > list2=[1,2,3] > > then if I did this 'for loop' > for name, value in list1,list2: > print name, value > > I would get > x,1 > y,2 > z,3 for name, value in zip(list1, list2): print name, value Cheers, Simon B. simon at brunningonline.net http://www.brunningonline.net/simon/blog/ --LongSig ----------------------------------------------------------------------- The information in this email is confidential and may be legally privileged. It is intended solely for the addressee. Access to this email by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot accept liability for statements made which are clearly the senders own. From skip at pobox.com Tue Mar 2 10:23:38 2004 From: skip at pobox.com (Skip Montanaro) Date: Tue, 2 Mar 2004 09:23:38 -0600 Subject: csv bugs In-Reply-To: References: Message-ID: <16452.42746.753582.600239@montanaro.dyndns.org> (A better place for this discussion would probably be csv at mail.mojam.com. I'm adding it to the cc list.) Magnus> It seems that when a line termination is escaped (using the Magnus> current escape character), csv.reader treats it as a line Magnus> continuation, which is well an good -- but it doesn't discard Magnus> the escape character; instead, it escapes it implicitly. This Magnus> seems like a bug to me. E.g. Magnus> foo:bar:baz\ Magnus> frozz:bozz Magnus> with separator ':' and escape character '\\' is parsed into Magnus> ['foo', 'bar', 'baz\\\nfrozz', 'bozz'] Magnus> In my opinion, it *ought* to be parsed into Magnus> ['foo', 'bar', 'baz\nfrozz', 'bozz'] Magnus> As far as I know, this is the UNIX convention, as used in (e.g.) Magnus> /etc/passwd. That may be, however development of the csv module's parser was driven by how Microsoft Excel behaves. The assumption was (rightly I think) that Excel reads or writes more CSV files than anything else. I don't believe it does anything with backslashes. Magnus> Am I off target here? If the current behaviour is desirable Magnus> (although I can't see why it should be) then at least I think Magnus> there should be a way of implementing "normal" line Magnus> continuations (as in my example), which is the standard UNIX Magnus> behavior, and the behavior of Python source, for that Magnus> matter. Otherwise, csv can't be used to parse (e.g.) Magnus> /etc/passwd... You're welcome to submit a patch. I don't have time for it. Magnus> And another thing: Perhaps a 'passwd' dialect could be added Magnus> alongside 'excel'? Something like: Magnus> class passwd(Dialect): Magnus> delimiter = ':' Magnus> doublequote = False Magnus> escapechar = '\\' Magnus> lineterminator = '\n' Magnus> quotechar = '?' Magnus> quoting = QUOTE_NONE Magnus> skipinitialspace = False Magnus> register_dialect("passwd", passwd) I'll take a look at that. Magnus> For some reason you *have* to supply a quotechar, even if you Magnus> set QUOTE_NONE... I guess that's a bug too, in my book. Maybe. Maybe just a feature. Magnus> If there are no objections, I might submit some of this as a bug Magnus> report or two (or even a patch). Please do. Skip From theller at python.net Thu Mar 18 14:34:28 2004 From: theller at python.net (Thomas Heller) Date: Thu, 18 Mar 2004 20:34:28 +0100 Subject: ConfigParser and Unicode References: Message-ID: <1xnqx83f.fsf@python.net> thehaas at binary.net writes: > "Martin v. L??wis" wrote: >> thehaas at binary.net wrote: >> > Obviously, 'Gr????'!='Gr\xfc\xdf' . > >> It is not at all obvious that they are different. In fact, they >> are the same, assuming the second string is encoding in Latin-1. > >> > Any ideas on how I can get the correct value? > >> Pray tell: what is the correct value? > > The correct value is 'Gr????', or at least have it equal to that. > > Maybe I should back up -- I'm interfacing into a Windows API. In that > API, I see 'Gr????' as: > >>> plist[-1].Reference > u'Gr\xfc\xdf' > > My value in goodProcList is: > >>> goodProcRef[18] > 'Gr\xfc\xdf' Try this: >>> "Gr\xfc\xdf".decode("latin-1") u'Gr\xfc\xdf' >>> Thomas From claird at lairds.com Mon Mar 22 15:52:44 2004 From: claird at lairds.com (Cameron Laird) Date: Mon, 22 Mar 2004 20:52:44 -0000 Subject: What's missing from python? References: <405ee0d0$0$63627$5a6aecb4@news.aaisp.net.uk> <7x8yhsj3bm.fsf@ruckus.brouhaha.com> <405f148a$0$10522$afc38c87@news.easynet.co.uk> Message-ID: <105ukgstn1tb867@corp.supernews.com> In article , Skip Montanaro wrote: > > Peter> Paul Rubin wrote: > >> 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. > > Peter> The 'batteries included' stuff is more a distribution / packaging > Peter> issue than the standard library. At least coming from Tcl where > Peter> we have a 'batteries included' distribution including all sorts > Peter> of nice things. However this does not mean that they are part of > Peter> the standard library. > >See: > > http://www.tcl.tk/cgi-bin/tct/tip/12.html > >and search for "Frank Stajano". My guess would be that Frank's paper got >the ball rolling for the "batteries included" concept in Tcl. > >Skip > I confirm that. That's verifiably how it happened. I also don't see that as contradicting what Peter wrote. -- Cameron Laird Business: http://www.Phaseit.net From Scott.Daniels at Acm.Org Fri Mar 26 19:47:46 2004 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Fri, 26 Mar 2004 16:47:46 -0800 Subject: [SPAM-Bayes] - Re: Converting IBM Floats..Help.. - BayesianFilter detected spam In-Reply-To: <41A1CBC76FDECC42B67946519C6677A9A20E01@pippin.int.etrials.com> References: <41A1CBC76FDECC42B67946519C6677A9A20E01@pippin.int.etrials.com> Message-ID: <4064CF32.1080900@Acm.Org> Ian Sparks wrote: > You might find my weird little bits module helpful to take your floating > point values in python apart in order to send them around. > > http://members.dsl-only.net/~daniels/bits.html > << > > Could you demonstrate this? No, this is more for the other direction. from bits import msb, extract def asIBM(v): """Only works for positive numbers, doesn't round""" assert v >= 0 if 0 == v: return 8 * '\0' top = msb(v) expon = top // 4 + 1 data = [chr(extract(v, n-8, n)) for n in range(expon*4, expon*4 - 7*8, -8)] data.insert(0, chr((expon + 64) & 127)) return ''.join(data) I haven't really tested the above, so you'd really better check it carefully against some known values: asIBM(10.0625) or whatever else you know. or whatever you know equivalents for. -- -Scott David Daniels Scott.Daniels at Acm.Org From gherron at islandtraining.com Tue Mar 30 12:18:16 2004 From: gherron at islandtraining.com (Gary Herron) Date: Tue, 30 Mar 2004 09:18:16 -0800 Subject: GUI Frameworks in Python? In-Reply-To: <20040330143520.31dccb5e.HughMacdonald@brokenpipefilms.com> References: <8089854e.0403300518.3a180414@posting.google.com> <20040330143520.31dccb5e.HughMacdonald@brokenpipefilms.com> Message-ID: <200403300918.16128.gherron@islandtraining.com> On Tuesday 30 March 2004 05:35 am, Hugh Macdonald 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... No! GTK is most definitely cross platform. I use it on both Windows and Linux with great success. And it's very consistent in the sense that my GUI looks identical on both platforms. I have almost no need for any platform dependent code in my GUI layout. (Unlike Tkinter and wxPython where I remember having to tweek fonts and other things on a platform by platform basis.) Here's several pointers: http://www.async.com.br/faq/pygtk/index.py?req=show&file=faq21.012.htp http://www.pcpm.ucl.ac.be/~gustin/win32_ports/ Gary Herron From tim.one at comcast.net Tue Mar 23 21:18:31 2004 From: tim.one at comcast.net (Tim Peters) Date: Tue, 23 Mar 2004 21:18:31 -0500 Subject: IDLE won't launch, and other frustrations In-Reply-To: Message-ID: [Michael A. Covington] > 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???!! No, it means Python is a good citizen but WN16 was a criminal . Installing Python won't interfere with any other Tcl/Tk-using app on your system, because Python is polite and considerate. WN16 probably set an environment variable, or more than one, forcing every Tcl/Tk on the box to use the old version WN16 installed. That's anti-social of it, but not Python's doing. Do "set | sort" from a DOS box, and look for envars with names starting with TCL or TK. I'm betting you'll find at least one, pointing to a directory under C:\WIN16. If you do, get rid of it, and then Tkinter should work fine. From ken at perfect-image.com Thu Mar 25 22:38:00 2004 From: ken at perfect-image.com (Ken Godee) Date: Thu, 25 Mar 2004 20:38:00 -0700 Subject: import a modified module In-Reply-To: References: Message-ID: <4063A598.2030505@perfect-image.com> myang wrote: > I am revising a python module, and try it in python shell. Each time after > the module is modified, how can I import the new module? I remember there is > an "import" like staff to do it, but dont know its name clearly. I was not > able to google out it, and the huge bulk of python documentation is > fearsome. :( > > Regards, > Yang > > If I understand the question.... you want to reload the modified module without exiting the interpiter? if so try reload(mymod) From steve at ninereeds.fsnet.co.uk Mon Mar 22 14:13:33 2004 From: steve at ninereeds.fsnet.co.uk (Stephen Horne) Date: Mon, 22 Mar 2004 19:13:33 +0000 Subject: PEP 318 References: <4qet50hla2dna5g8gqcbbfj2tsmu3smkp7@4ax.com> Message-ID: On Mon, 22 Mar 2004 07:33:08 -0500, Peter Hansen wrote: >> Surely it *is* a list - a list of modifier functions to apply to the >> original function. > >If it's a list, then just as surely a tuple should be allowed in its >place, as in every (?) other such case in Python that I can think of. >Would that be part of the proposal? (I haven't read the full PEP, sorry.) I don't think tuples were mentioned in the PEP, though I only skimmed through it quickly. But, well... >(I know, "foolish consistency is the hobgoblin blah blah..." :-) Yes, I have to agree. The list-like syntax isn't too confusing in this context. A tuple-based context would be. With parens, it would look a lot like having too lists of arguments. Without, well, IMO it'd be even worse. Which still shouldn't be read as me expressing a preference - the 'as' syntax is roughly equally good IMO. -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From bart_nessux at hotmail.com Fri Mar 12 14:11:53 2004 From: bart_nessux at hotmail.com (Bart Nessux) Date: Fri, 12 Mar 2004 14:11:53 -0500 Subject: root password in a .py script In-Reply-To: References: Message-ID: Dave Brueck wrote: > What is it that this script is doing? How is it getting invoked? And if it's > being invoked by a non-root user, why should that user be allowed to do > something that requires root privileges? Is there any reason why you simply > don't run the script as root? The script is setting the root password. It is running as root, by root as a daily cron job. It does three things: 1. Set root password to XXXXXXXXX 2. Make certain ssh is enabled on the machine, if not enable it. 3. Email the machine's IP to the admins Root is the owner of the script... it's perms are 700 Why am I doing this? Because users turn off ssh and change the root password. Mac OSX allows "administrative" users to do this. This script undoes their changes. > P.S. If you're going to automatically run the script on 200 machines, and > you're putting the root password inside the script, does that imply that you > have a network of 200 machines that all have the same root password? Yes. From ville at spammers.com Wed Mar 24 04:45:05 2004 From: ville at spammers.com (Ville Vainio) Date: 24 Mar 2004 11:45:05 +0200 Subject: PEP 318 References: <95aa1afa.0403222352.2679dde@posting.google.com> <95aa1afa.0403232104.328356ea@posting.google.com> Message-ID: >>>>> "Andrew" == Andrew Bennetts writes: Andrew> But the decorator syntax doesn't help with this case at Andrew> all. Andrew> You *could* hack up multimethods today, though, by abusing Andrew> metaclasses: Hmm? I would have figured that once you are able to associate parameter types with a function name and a concrete callable the gets called, you can implement multimethods. The wrapper would essentially 1. Look up the function name N from func_name 2. Insert the mapping of parameter types to the callable in the data structure that holds the mappings for multimethod N 3. Return the dispatcher object that remembers it's a dispatcher for multimethod N, so, when called, it can search the data structure for its own multimethod for the concrete callable to invoke with the parameters. This would obviously be used for CLOS-style multimethods, i.e. the concrete methods would be plain functions. This wouldn't work for operator overloading, for example, unless all the dispatcable classes did a: class C: def __mul__(self, other): return mm_multiply(self,other) Where mm_multiply would be the multimethod. Perhaps a base class could be introduced that did this for all the operators... Again, I might be overlooking something, but I haven't yet figured out what :). -- Ville Vainio http://tinyurl.com/2prnb From w.ewert2002 at gmx.de Tue Mar 9 10:42:21 2004 From: w.ewert2002 at gmx.de (Wolfgang Ewert) Date: Tue, 09 Mar 2004 16:42:21 +0100 Subject: (Zope] ZserverSSL as a win32 service Message-ID: Hi, I'd installed and running Zope Zserver as a service under w2k. Now I'll migrate to ZserverSSL by NG Pheng Siong (m2crypto-0.12 as win32 binaries). I tried these steps from the ZserverSSL Howto but I need no installation (step4) and I haven't any C compiler working under w2k. I'll try to reinstall the zopeservice now with HTTPS_Server.py included. I've no plan for it. Thank you Wolfgang Ewert From ajsiegel at optonline.com Sat Mar 20 19:30:54 2004 From: ajsiegel at optonline.com (Arthur) Date: Sun, 21 Mar 2004 00:30:54 GMT Subject: [snip too-long subject] References: <7x7jxhuuex.fsf@ruckus.brouhaha.com> <1079827655.31510.0@lotis.uk.clara.net> Message-ID: On Sun, 21 Mar 2004 00:07:50 +0000, Garry Knight wrote: > >It might be useful to think of the items in each list coming together like >the teeth of a zipper. But it's better than that: you're not constrained to >two sets of teeth: > >>>> L3 = [9, 10, 11, 12] >>>> zip(L1,L2,L3) >[(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)] I have found zip quite useful. But I think it is a case of Python being for consenting adults. If the lists are of unequal length, the first 'n' items of each list, with 'n' being the number of items in the shortest list, are zipped. It is assumed that is one's intention, and there is no warning that you have attempted to zip unequal length lists. Where the lists are coming together from different sections of the code, are being built dynamically, and there are corner cases to concern oneself with - well something unexpected could be passing unless there is explicit testing somewhere along the route. Map behaves differently, matching None with the item in the longer length list when the lists are of unequal length. Which I think makes it easier to catch exceptions. I guess I am the stage of understanding some of the not fully obvious "traps". Sometimes, even, before I fall into them. Art From klapotec at chello.at Thu Mar 11 03:50:28 2004 From: klapotec at chello.at (Christopher Koppler) Date: 11 Mar 2004 00:50:28 -0800 Subject: Extending Python Syntax with @ References: Message-ID: David MacQuigg wrote, amongst other things: > > If you believe as I do that Python is not yet the ultimate language, If Python were the ultimate language, it would be a Lisp ;-) > and some syntactical changes are still to come, then it seems like > using a very distinct symbol like @ may have some merits. This is not Perhaps, but as it stands, Python syntax is the best compromise in readability I have seen in any programming language, and I for one am very comfortable with less cryptic symbols - another case for explicit is better than implicit. -- Christopher From peter at engcorp.com Mon Mar 22 19:58:03 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 22 Mar 2004 19:58:03 -0500 Subject: Neat Trick for Loading Modules with unknown Name In-Reply-To: References: Message-ID: Roger Binns wrote: >>__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* :-) True. So I guess we could say the exec() approach is the simplest way to do arbitrary *normal* imports, while __import__ can handle arbitrary "simple" imports as-is, but neither alone is sufficient for the entire possible range of (arbitrary) imports. :-) -Peter From p at trick.lu Fri Mar 19 10:06:27 2004 From: p at trick.lu (Patrick Useldinger) Date: Fri, 19 Mar 2004 16:06:27 +0100 Subject: FreeBSD or OpenBSD for Python? Message-ID: Hi All, I am looking for alternatives to my current Linux OS, and am currently evaluating both FreeBSD and OpenBSD. Has anyone got a strong point for or against one of these OSes, specifically regarding Python? I am especially interested in - the ease of compiling CPython - the thread support (both for Python and in general) - running Twisted. Regards, -pu -- http://www.homepages.lu/pu/ From __peter__ at web.de Mon Mar 8 13:37:05 2004 From: __peter__ at web.de (Peter Otten) Date: Mon, 08 Mar 2004 19:37:05 +0100 Subject: Initializing Member Variables References: Message-ID: Scott Brady Drummonds wrote: > I'm a Python novice and just diagnosed a problem that is confusing me. I > wrote a class that looks like this: > > class Keys: > __dict = {} > > def __init__(self, key): > self.__dict[key] = key > print('keys are now: %s' % self.__dict.keys()) > > > When I test this class from my Python interpreter (interactive), I see the > following strange behavior: > >>>> import keys >>>> k1 = keys.Keys('1') > keys are now: ['1'] >>>> k2 = keys.Keys('2') > keys are now: ['2', '1'] >>>> k3 = keys.Keys('4') > keys are now: ['4', '2', '1'] >>>> > > > Maybe this isn't strange for a Python developer, but it sure is for me. I > thought that the "__dict = {}" line after the class declaration was > supposed > to initialize that member variable for each object. Obviously, that's not > happening. Instead, that variable is retaining its value from one object > to > the next, like a static member variable. For what it's worth, it seems > that this static variable behavior is not observed when using scalar > variables. Just with dictionaries. You've pretty much answered it yourself, except for the last sentence. The difference is not scalars versus vectors but rebinding versus mutating. a = {} # rebind a a = b # rebind a is fundamentally different from a[key] = value # change a's value As strings and integers are immutable you are always using only the first pattern - it doesn't matter if you reuse the same object in several places, because its value can never change. > Where have I gone wrong? What is the purpose of that "initialization" in > the Keys class? What is the correct was to initialize a class's member > variable and guarantee that it is properly initialized for all objects? self.__dict used in the __init__() method is misleading in your case, because if the attribute is not found in the instance, lookup proceeds to the class. This may have funny effects: >>> class A: ... b = 1 ... >>> a = A() >>> a.b 1 >>> a.b = 2 # create an instance attribute >>> a.b # the class attribute is now shadowed... 2 >>> A.b # ...but still there 1 >>> del a.b # delete the instance attribute >>> a.b # the class atttribute is visible again 1 Putting it all together: create the dictionary in the __init__() method instead of the class body (and while we're at it - do you really need that extra privacy provided by the double underscore?): >>> class Keys: ... def __init__(self, key): ... self._dict = {} ... self._dict[key] = key ... >>> k = Keys("first") >>> k2 = Keys("second") >>> k._dict {'first': 'first'} >>> k2._dict {'second': 'second'} >>> Peter From stefano at cavallari.cjb.net Thu Mar 18 08:44:59 2004 From: stefano at cavallari.cjb.net (Stefano Cavallari) Date: Thu, 18 Mar 2004 14:44:59 +0100 Subject: Python,mysql question In-Reply-To: References: Message-ID: <1079617499.1533.32.camel@localhost.localdomain> Il gio, 2004-03-18 alle 14:09, james blair ha scritto: > Hi > I have a search page & the reults for the search are fetched from the > database. > I want that on the results page only first 25 results are shown & a > link "next 25 results" be shown.Same for the 2nd result page. > How do I do this? here is how I ( a python newbie :) ) do it, using mod_python for apache and ... sorry for the last req.write that is quite hard to read def search(req,start="0",itemsperpage="5"): req.write("" etc etc... ) start=int(start) itemsperpage=int(itemsperpage) curs1=db1.cursor() curs1.execute("""SELECT ... FROM ... WHERE ORDER BY ... LIMIT %s,%s ;""",(start,itemsperpage+1) ) for i in xrange(itemsperpage): row=curs1.fetchone() if row!=None: req.write(repr(row)) # change to something more useful row=curs1.fetchone() # any row left for next page? req.write(( 'Previous ') *(start-itemsperpage>=0) +('Next')* (row!=None)) the last req.write(..) could be rewritten as if (start-itemsperpage>=0): req.write('Previous ') if row!=None: #first line of "next page" is empty, so no "next page" is needed req.write('Next') which is far more readable. Any comment is appreciated, it's one of the first python script I wrote. HTH, HAND -- Linux User #153639 RoLug Member - http://rovigo.linux.it GnuPG id:E88F9363 keyserver.linux.it Jabber id:cava at jabber.linux.it From nathanjohns77 at hotmail.com Thu Mar 25 17:42:04 2004 From: nathanjohns77 at hotmail.com (calpolynate) Date: 25 Mar 2004 14:42:04 -0800 Subject: [Newbie]Trouble with string method Message-ID: <96fd272b.0403251442.49047ba9@posting.google.com> I'm attempting to open a file, read the lines, sort them, change any uppercase character to lowercase, and output to another file: import string unsorted = open('unsorted', 'r') L = unsorted.readlines() L.sort() L = L.lower() sorted = open('sorted', 'w') sorted.writelines(L) unsorted.close() sorted.close() when trying to run, I get this traceback: Traceback (most recent call last): File "sort_list.py", line 6, in ? L = L.lower(L) AttributeError: 'list' object has no attribute 'lower' Do I need to somehow convert the list into strings? Thanks for any help! From michele.simionato at poste.it Thu Mar 11 10:25:01 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 11 Mar 2004 07:25:01 -0800 Subject: new python syntax: concatenation of functions References: Message-ID: <95aa1afa.0403110725.2ebe1b55@posting.google.com> Uwe Mayer wrote in message news:... > Hi, > > I know the python community is not very receptive towards extending the > python syntax. Nevertheless I'd like to make a suggestion and hear your pro > and cons. > > I want so suggest a concatenation operator like in mathematics: ? > such that: > > a(b(c(d))) <=> a?b?c(d) > > Now, why do you think such an extension would be completely useless? ;) > > Ciao > Uwe This is not useless, but does not require new notations. Just use callable objects instead of functions and overload "*" to denote composition. Michele Simionato From chenet.carl at free.fr Fri Mar 19 11:57:58 2004 From: chenet.carl at free.fr (chaica) Date: Fri, 19 Mar 2004 17:57:58 +0100 Subject: FreeBSD or OpenBSD for Python? References: Message-ID: On Fri, 19 Mar 2004 16:06:27 +0100, Patrick Useldinger wrote: > Hi All, > I am looking for alternatives to my current Linux OS, and am currently > evaluating both FreeBSD and OpenBSD. > Has anyone got a strong point for or against one of these OSes, > specifically regarding Python? I am especially interested in > - the ease of compiling CPython > - the thread support (both for Python and in general) > - running Twisted. > Regards, > -pu You won't have any difference for python working under freebsd or openbsd. Just be sure about your python version, many differnces come from a version to another one. From skip at pobox.com Fri Mar 12 09:20:14 2004 From: skip at pobox.com (Skip Montanaro) Date: Fri, 12 Mar 2004 08:20:14 -0600 Subject: Deprecating reload() ??? In-Reply-To: References: <40514A48.50907@domain.invalid> Message-ID: <16465.50974.577405.950902@montanaro.dyndns.org> Regarding >> del sys.modules['modulename']; import modulename vs. >> del modulename ; import modulename Peter sez: Peter> Just to clarify, *neither* of the above solutions does anything Peter> useful, as far as I know. Only reload() will really reload a Peter> module. Certainly the del mod/import mod approach is practically Peter> a no-op... Not so. del sys.modules['mod']/import mod is effectively what reload() does. Given foo.py with this content: a = 1 print a here's a session which shows that it is outwardly the same as reload(...). That is, the module-level code gets reexecuted (precisely because there's not already a reference in sys.modules). >>> import foo 1 >>> reload(foo) 1 >>> import foo >>> import sys >>> del sys.modules['foo'] >>> import foo 1 David MacQuigg's contention that it doesn't work is missing the fact that when he executed a = testimport.a he simply created another reference to the original object which was outside the scope of the names in testimport. Reloading testimport created a new object and bound "testimport.a" to it. That has nothing to do with the object to which "a" is bound. This is the problem reload() doesn't solve. Given Python's current object model it would be an interesting challenge to write a "super reload" which could identify all the objects created as a side effect of importing a module and for those with multiple references, locate those other references by traversing the known object spaces, then perform the import and finally rebind the references found in the first step. I thought I saw something like this posted in a previous thread on this subject. In case you're interested in messing around with this, there are three object spaces to be careful of, builtins (which probably won't hold any references), all the imported module globals (which you can find in sys.modules) and all the currently active local Python functions (this is where it gets interesting ;-). There's a fourth set of references - those held by currently active functions which were defined in extension modules - but I don't think you can get to them from pure Python code. Whether or not that's a serious enough problem to derail the quest for super_reload() function is another matter. Most of the time it probably won't matter. Every once in a great while it will probably bite you in the ass. Accordingly, if super_reload() can't track down all the references which need rebinding it should probably raise a warning/exception or return a special value to indicate that. Skip From dontbotherworld at yahoo.com Fri Mar 5 22:15:17 2004 From: dontbotherworld at yahoo.com (dont bother) Date: Fri, 5 Mar 2004 19:15:17 -0800 (PST) Subject: Enumerating words and Adding integer, character and string Message-ID: <20040306031517.67563.qmail@web60809.mail.yahoo.com> 1. How do I make a vector of words in a file. Ex: File has Alpha Beta Gamma I want to have this file: 1 Alpha 2 Beta 3 Gamma I just dont want to write it/print it instead I want a mapping. A vector kind of thing whose first attribute is interger second is the 'word' 2. How to I create a string for example by adding: s=1 + ":" + "dont" this does not work if I normally try to concatenate and write to a file. Any help is appreciated Thanks Dont __________________________________ Do you Yahoo!? Yahoo! Search - Find what you?re looking for faster http://search.yahoo.com From leo at bella.local Tue Mar 16 07:47:13 2004 From: leo at bella.local (leo) Date: 16 Mar 2004 23:47:13 +1100 Subject: newbie question: nop statement for try/except Message-ID: 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? thanks, leo From hostmaster at nedit.org Sun Mar 7 08:22:06 2004 From: hostmaster at nedit.org (nedit.org) Date: Sun, 7 Mar 2004 14:22:06 +0100 (CET) Subject: Mailing lists have changed Message-ID: <20040307132206.6B6FF3B397@jebediah.calyx.nl> You are apparently trying to reach one of the NEdit mailing lists. Please note that the nedit.org mailing lists have moved, and the addresses for the list managers have changed. Amongst others, majordomo at nedit.org is no longer valid. If you are looking to subscribe to one of the NEdit mailing lists, please visit http://www.nedit.org/mail.shtml where you will find insructions on how to join one or more of the lists, or contact the list owners. With kind regards the NEdit hostmaster -- This is an autogenerated message. Replies will most likely not reach an actual person. From __peter__ at web.de Wed Mar 10 05:04:51 2004 From: __peter__ at web.de (Peter Otten) Date: Wed, 10 Mar 2004 11:04:51 +0100 Subject: trap attributeError from inside a dict ? References: <404ed174$0$307$626a14ce@news.free.fr> Message-ID: GrelEns wrote: > hello, > > i would like if this behaviour can be obtained from python : trap an > attributeError from inside a subclassing dict class... (here is a silly > examples to explain my question) > > class Test(dict): > """subclassing a dict and each key will permit access to a tuple of fized > size""" > def __init__(self): > pass > def load(self, adict): > """actually it will be done from a text file with fixed size fields, > each > tuple will have the same size""" > for k in adict: > self[k] = tuple(adict[k]) > > t = Test() > t.load({1: ('a', 'aa'), 2: ('(b', 'bb')}) > > here is what i would have : >>>> t[1].get('first') > 'a' > > without having to define tuple as an object or subclassing tuple, of > course now i had : >>>> t[1].get('first') > > Traceback (most recent call last): > File "", line 1, in -toplevel- > t['A'].get('first') > AttributeError: 'tuple' object has no attribute 'get' > > is it possible ? > > btw my question is something like is there a way from inside Test code to > say to python that when it first get t[1] it should not go further, trap > the things one ask to do on t[key] and then calling a function such as > > (inside Test) > def __get(self, key, readable): > mapping = {'first' : 1, 'second' : 2} > return self[key][mapping[readable]] > > (maybe it is a silly design...but i need this because i do want some kind > of readable object access without having to create all these objects) Here's one way to do it: >>> class Dict(dict): ... translate = {"first": 0, "second": 1} ... def __getitem__(self, key): ... value = dict.__getitem__(self, key[0]) ... return value[self.translate[key[1]]] ... >>> d = Dict([(1,("a", "aa")), (2, ("b", "bb"))]) >>> d[1, "first"] 'a' >>> d[2, "second"] 'bb' Here's another: >>> class Dict(dict): ... def __getitem__(self, key): ... return Wrap(dict.__getitem__(self, key)) ... >>> class Wrap(object): ... def __init__(self, data): self.data = data ... first = property(lambda self: self.data[0]) ... second = property(lambda self: self.data[1]) ... >>> d = Dict([(1,("a", "aa")), (2, ("b", "bb"))]) >>> d[1].first 'a' >>> d[2].second 'bb' >>> Note that you might end with *more* objects as every call to __getitem__() creates a new Wrap instance. A cache could help, but if you did it properly with a custom class for the values the problem wouldn't arise. Personally, I would put custom objects into a normal dictionary instead of playing one of these tricks. Peter From khawaja_shahzads at hotmail.com Thu Mar 18 18:26:44 2004 From: khawaja_shahzads at hotmail.com (Khawaja Shahzad Sadiq Butt) Date: Thu, 18 Mar 2004 18:26:44 -0500 Subject: Problem with a script. Message-ID: Hello, There was a script/recipe published at active state. Is a basic connection string for ODBC.Here is it. The recipe tilted: Python Database Interface for MS SQL Server http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/144183 In test file. What is the module dbcp. I can't configure what is or where can i get it . when i run the code python give me the error of: module dbcp not found. I am runing it on windows using gadfly. I have also mxODBC installed. Please tell me what should i do. Regards Khawaja Shahzad _________________________________________________________________ Check out MSN PC Safety & Security to help ensure your PC is protected and safe. http://specials.msn.com/msn/security.asp From alet at librelogiciel.com Sun Mar 21 15:15:24 2004 From: alet at librelogiciel.com (Jerome Alet) Date: Sun, 21 Mar 2004 21:15:24 +0100 Subject: Accessing MS-Access DB from Linux References: Message-ID: On Sun, 21 Mar 2004 13:21:54 -0300, Gustavo Rahal wrote: > How can I access a MS-Access DB from a linux machine? I'd suggest you try mxODBC, available from egenix.com bye Jerome Alet From tim.golden at viacom-outdoor.co.uk Thu Mar 25 10:07:50 2004 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Thu, 25 Mar 2004 15:07:50 -0000 Subject: monitoring a directory Message-ID: >[Tim Golden ] > >>The other method, which is a bit more sophisticated, uses the > >Hhm, looks like "win32file" expertise is around ;-) > >Shameless question plugin: Is there a way to find the realname of a >file on Windows? In those times of DOS there was a DOS call/interrupt >"Truename" that would return the real name of a files. This is >important if you have created additional drives via the "SUBST" >command. > >I'm still looking for a foolproof way to ensure that two files are >different on windows. There are times where I'd like to avoid deleting >the last valid copy of a file ... Well, I must thank you for starting a small voyage of discovery. I had started to write a reply saying that I'd previously looked and that it was impossible (altho' that seemed so unlikely, given that the O/S itself *must* know whether two files were the same). So I started to look around a little more, and found that you can in fact tell if two files are the same using only what's available in win32file. It's a little involved, but not too much, and nothing that a couple of functions can't encapsulate. In essence, you get a handle to each file and call win32file.GetFileInformationByHandle for each. This returns, among other things, a FileIndexHi/Lo pair which, coupled with the VolumeSerialNumber also returned gives you a unique id for a file *while it is open by a process*. This means that you must have both handles open to read the info before you close either. The following code works ok across drives SUBSTed to the same path and drives mapped to the same network share. (And -- naively -- to the same file given twice). import os, sys import win32file def get_read_handle (filename): return win32file.CreateFile ( filename, win32file.GENERIC_READ, win32file.FILE_SHARE_READ, None, win32file.OPEN_EXISTING, 0, None ) def get_unique_id (hFile): ( attributes, created_at, accessed_at, written_at, volume, file_hi, file_lo, n_links, index_hi, index_lo ) = win32file.GetFileInformationByHandle (hFile) return volume, index_hi, index_lo def files_are_equal (filename1, filename2): hFile1 = get_read_handle (filename1) hFile2 = get_read_handle (filename2) are_equal = (get_unique_id (hFile1) == get_unique_id (hFile2)) hFile2.Close () hFile1.Close () return are_equal 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 fperez528 at yahoo.com Mon Mar 8 11:01:05 2004 From: fperez528 at yahoo.com (Fernando Perez) Date: Mon, 08 Mar 2004 09:01:05 -0700 Subject: os.popen() failing under ipython+cygwin, I'm stumped. Message-ID: Hi all, I'm reaching out to the cygwin wizards out there, because I have a problem I don't know how to even begin attacking. An IPython user is having problems with the help() command under cygwin, and since I only have access to linux boxes, I have a real hard time helping him out. Brief background: ipython (http://ipython.scipy.org) is a free replacement for the standard python interpreter with a ton of added features. It is pure python code, with no C extensions at all. We've narrowed it down to the following. Under ipython, here is what he gets with a popen() call: ,--- | Python 2.3.3 (#1, Dec 30 2003, 08:29:25) | Type "copyright", "credits" or "license" for more information. | | IPython 0.5.0 -- An enhanced Interactive Python. | ? -> Introduction to IPython's features. | @magic -> Information about IPython's 'magic' @ functions. | help -> Python's own help system. | object? -> Details about 'object'. ?object also works, ?? prints more. | 1% import os | 2% xmode Verbose | Exception reporting mode: Verbose | 3% pipe=os.popen('less','w') | 10 [main] python2.3 2896 sync_with_child: child 3032(0x6D4) died before initialization with status code 0x1 | 9375 [main] python2.3 2896 sync_with_child: *** child state child loading dlls | --------------------------------------------------------------------------- | OSError Traceback (most recent call last) | | /home/thorsten/ | | OSError: [Errno 11] Resource temporarily unavailable Under a normal python shell, the popen() call goes through ok. Note that the [main] errors are _above_ the traceback, which means they are being printed straight to stdout/err by the python core, not through the normal traceback mechanisms. I've never seen the 'Resource temporarily unavailable' error before, and I don't really know what can be going on here. Any help would be much appreciated. Cheers, f. From hamilcar at never.mind Sun Mar 7 02:01:15 2004 From: hamilcar at never.mind (Hamilcar Barca) Date: Sun, 07 Mar 2004 00:01:15 -0700 Subject: New to Python; what about #include, extern and function prototypes References: Message-ID: <20040307020101.539$r9@news.newsreader.com> 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? From spisatus at coqui.net Tue Mar 23 16:13:08 2004 From: spisatus at coqui.net (spisatus) Date: Tue, 23 Mar 2004 17:13:08 -0400 Subject: creating lists question? Message-ID: I'm trying to create a series of list from a loop is this possible? Let me give you an example: list1 = ["aaa", "bbb", "ccc", "ddd", "eee"] for element in list1: a = element a = [] I want a new list created for every element in list1, how can I do this. Thanks!! Spisatus From michael at foord.net Sat Mar 20 06:03:00 2004 From: michael at foord.net (Fuzzyman) Date: 20 Mar 2004 03:03:00 -0800 Subject: Regular Expression AND mach References: <8089854e.0403190721.6bdcbfbe@posting.google.com> Message-ID: <8089854e.0403200303.5eae6726@posting.google.com> Jeff Epler wrote in message news:... > Regular expressions are not a good tool for this purpose. > > Here's one bad solution: > > def permutations: > raise NotImplementedException, "exercise for the reader" > > def rxseq(seq): # Return a RE that has seq[0] followed by seq[1] etc > return ".*".join(seq) > > def rxand(seq): # Return an RE that matches each permutation of seq > return "|".join([rxseq(p) for p in permutations(seq)]) > > This fails when one part can overlap another, for instance if > word1="aba" and word2="b", "ab" or "ba". > > You could also use a bunch of lookahead assertions, something like > (?=.*word1)(?=.*word2) > but you'll also come to regret this choice. > > Jeff > PS If you liked these regular expressions and would like to buy more, > visit e-bay where I'm selling a RE that matches multiples of 3 base 10. Hmm... I'm not sure if I've been helped or not :-) Thanks anyway..... I've ended up just doing a search in the the database for the longest word.... (which returns all songs containing that word) and then checking hte text of *each* song for all the other words............... It's not noticeably slow (only 1800 songs)... If I do this again I might try and find a useful indexer.......... Odd that you can't do this easily with regular expressions - I suppose it doesn't compile down to a neat test.... but then it's hardly a complex search... OTOH I have *no idea* how regular expressions actually work (and no need to find out)... Regards Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html From joe at notcharles.ca Mon Mar 29 06:30:43 2004 From: joe at notcharles.ca (Joe Mason) Date: Mon, 29 Mar 2004 11:30:43 GMT Subject: Prothon Prototypes vs Python Classes References: <106dukh7ncf9ad4@news.supernews.com> <106eo695a9t8820@news.supernews.com> <106ev65lpu59614@news.supernews.com> Message-ID: In article <106ev65lpu59614 at news.supernews.com>, John Roth wrote: > 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. I'm collection up implementations (I've got 4 now) and later this week (or next weekend, if I get too busy at work) I'll make a post about what's been done and what still needs to be done. Joe From ciccio at unical.it Tue Mar 9 08:25:02 2004 From: ciccio at unical.it (ciccio at unical.it) Date: Tue, 9 Mar 2004 14:25:02 +0100 Subject: problem Message-ID: <1078838702.404dc5ae50aa9@webmail.unical.it> Hi I have a big probel. I'm using a script to run sequencially 5 programs, but just one of them runs before the next. Can you help me to solve this problem? many thanks ernesto PS:I think to be registered in this mailing list with the address e.picardi at unical.it that is the same of this one (ciccio at unical.it) ------------------------------------------------- This mail sent through IMP: http://horde.org/imp/ From sean_berry at cox.net Thu Mar 25 15:54:35 2004 From: sean_berry at cox.net (Sean Berry) Date: Thu, 25 Mar 2004 14:54:35 -0600 Subject: [Newbie]Trouble with string method References: <96fd272b.0403251442.49047ba9@posting.google.com> Message-ID: Try the following unsorted = open('unsorted', 'r').readlines() -- two steps into one unsorted.sort(lambda x, y: cmp(string.lower(x), string.lower(y))) unsorted.close() sorted = open('sorted', 'w') sorted.writelines(unsorted) soretd.close() Your problem is that you are trying to use a string method on a list. calpolynate wrote in message news:96fd272b.0403251442.49047ba9 at posting.google.com... > I'm attempting to open a file, read the lines, sort them, change any > uppercase character to lowercase, and output to another file: > > import string > > unsorted = open('unsorted', 'r') > L = unsorted.readlines() > L.sort() > L = L.lower() > sorted = open('sorted', 'w') > sorted.writelines(L) > unsorted.close() > sorted.close() > > when trying to run, I get this traceback: > > Traceback (most recent call last): > File "sort_list.py", line 6, in ? > L = L.lower(L) > AttributeError: 'list' object has no attribute 'lower' > > Do I need to somehow convert the list into strings? > > Thanks for any help! From fma at doe.carleton.ca Sat Mar 27 23:55:14 2004 From: fma at doe.carleton.ca (Fred Ma) Date: 28 Mar 2004 04:55:14 GMT Subject: Sermon on technique (was: Choosing Perl/Python for my particular niche) References: <40661C14.8365E058@doe.carleton.ca> <106cdgj9nauhqcd@corp.supernews.com> Message-ID: <40665BBD.828AD1AB@doe.carleton.ca> Cameron Laird wrote: > > One of the hardest things in science (and business, > and romance, and ...) is to deal with uncertainty > and incompleteness. Yup: you have countervailing > criteria. Figuring out the true optimum is a bigger > project than the CAD engineering you claim as your > goal. At some point--probably this weekend, from > the sound of it--you need to make decisions, and > move forward. They might be wrong decisions, on > narrow technical grounds. Good scientists make > wrong decisions all the time. Don't let 'em get in > the way of your science--that's all. Sounds like the story of life, actually: making decisions based on the available info, and the residual uncertainty; making the most of the decision, as well as knowing when things have to change despite past decisions. Not a bad thing, really. Life would be dead boring otherwise. > You've done a good job thinking about what you want, > and what's available. Good luck with your combina- > torics. Glad you think so. I know many who would have thought it was too much digging to make the decision, but now I have a guiding "plan" if it can be called that. Hopefully it will optimize the use of my time going forward. Now I gotta run like the wind. Thanks for all your input. Fred Fred From michele.simionato at poste.it Mon Mar 1 02:02:02 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 29 Feb 2004 23:02:02 -0800 Subject: Feature request: subclassing FunctionType [Was: Some language proposals] References: <95aa1afa.0402262158.5b33de79@posting.google.com> <95aa1afa.0402272327.29828430@posting.google.com> Message-ID: <95aa1afa.0402292302.1283af4c@posting.google.com> Jacek Generowicz wrote in message news:... > I think that you are misleading yourself. You are comparing apples to > quinces. I thank you for the long post and the time you spent in clarifying the issue I had; however, you are speaking to a converted, since I already came to the same conclusion on my own (see my reply to Bengt Richter). > So, you see, Python's scoping rules are just like Scheme's, in this > sense. Unfortunately, I don't think that it's so easy (or even > possible?) to demonstrate it the other way around (ie show a Scheme > snippet in which add0(0) == add1(0) == 1) See my reply to Bengt. > Try the following: > > x = 3 > def show(): global x; print x > show() # => 3 > x += 1 > show() # => 4 > > def outer(): > x = 3 > def show(): print x > show() # => 3 > x += 1 > show() # => 4 > outer() > > ... which prints out the numbers 3,4,3 and 4. > > You don't really believe that the last number should be 3, do you ? No, I agree with you on every respect. It is just that Scheme hides the issue; but it hides it so well that in practice you never do the mistake. Still, I maintain that the ability to subclass FunctionType would be nice ;) Michele Simionato From afriere at yahoo.co.uk Tue Mar 16 22:53:29 2004 From: afriere at yahoo.co.uk (Asun Friere) Date: 16 Mar 2004 19:53:29 -0800 Subject: Result of ``a is b'' References: <40200384.0403151632.35496ee6@posting.google.com> <40200384.0403161255.7fca7a8c@posting.google.com> Message-ID: <38ec68a6.0403161953.19bec0ed@posting.google.com> Skip Montanaro wrote in message news:... > No, its behavior is quite well-specified. It does a pointer comparison. > Here is my "is" rule: > > Use "is" to compare two objects only if one is explicitly known to be a > singleton defined by the language (None, Ellipsis, True, False). > > and its corrolary: > > Never use "is" to compare two programmer-defined variables. > What about when it is an object explicitly known to be singleton defined by the programmer. ;) Another possible use, would be to type test, eg. 'foo.__class__ is Foo', bearing in mind that one should avoid type testing in favour of polymorphism. From steve at ninereeds.fsnet.co.uk Tue Mar 9 16:52:39 2004 From: steve at ninereeds.fsnet.co.uk (Stephen Horne) Date: Tue, 09 Mar 2004 21:52:39 +0000 Subject: Working around a lack of 'goto' in python References: Message-ID: On Tue, 09 Mar 2004 01:34:06 +0000, leeg wrote: >Y2KYZFR1 wrote: > > >> >> No stay away from computers until you understand how and why this is. > >*points at the Linux kernel source* Examples of use are not proof that such use is a good thing. More relevant here, kernal programming is not the kind of job that Python is designed for. What is justifiable in kernal programming is not necessarily justifiable for the kinds of applications that are written in Python. On similar principles, whats justifiable in the Python source code is not necessarily justifiable in, errrm, Python source code :-) Which is not to say that Y2KYZFR1s absolute decree was valid, of course. -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From jepler at unpythonic.net Thu Mar 11 11:45:02 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Thu, 11 Mar 2004 10:45:02 -0600 Subject: [PyQT] QSocketNotifier problem In-Reply-To: References: Message-ID: <20040311164502.GE14393@unpythonic.net> I suspect that QSocketNotifier is built on top of poll or select. The documentation I have for poll is too terse for me to be sure, but I suspect POLLIN behaves like the readfs set in select. The documentation for select makes it clear that "readable" means that reading will not block---so an end-of-file condition counts. I'm not sure how you're really supposed to deal with this in a way that doesn't block, doesn't spin, and doesn't involve doing something based off a timer. Here's one idea that does involve a timer: When reading the FIFO indicates an end-of-file condition, close the fifo. Then, at intervals, attempt to reopen it. When opened with O_NONBLOCK, the open fails with ENXIO if there is no writer. Ensuring that there's always a writer for the FIFO might work too, because then poll/select will not detect an end-of-file condition. Jeff From ngps at netmemetic.com Mon Mar 29 22:30:26 2004 From: ngps at netmemetic.com (Ng Pheng Siong) Date: 30 Mar 2004 03:30:26 GMT Subject: [Announce] M2Crypto 0.13 Message-ID: Hi, M2Crypto 0.13 is now available. M2Crypto is a crypto and SSL toolkit for Python featuring the following: * RSA, DSA, DH, HMACs, message digests, symmetric ciphers (including AES). * SSL functionality to implement clients and servers. * HTTPS extensions to Python's httplib, urllib, and xmlrpclib. * Unforgeable HMAC'ing AuthCookies for web session management. * FTP/TLS client and server. * S/MIME. * ZServerSSL: A HTTPS server for Zope. * ZSmime: An S/MIME messenger for Zope. Get it here: http://sandbox.rulemaker.net/ngps/m2/ Feedback is appreciated. Cheers. -- Ng Pheng Siong http://firewall.rulemaker.net -+- Firewall Change Management & Version Control http://sandbox.rulemaker.net/ngps -+- Open Source Python Crypto & SSL From NAIGIMSESRIMAIL at gims.com Tue Mar 30 18:10:16 2004 From: NAIGIMSESRIMAIL at gims.com (GroupShield for Exchange (ESRIMAIL)) Date: Wed, 31 Mar 2004 01:10:16 +0200 Subject: ALERT - GroupShield ticket number OB61_1080688200_ESRIMAIL_3 was generated Message-ID: Action Taken: The message was blocked because of its subject. To: python-list at python.org From: cookedm+news at physics.mcmaster.ca Sent: 596597504,29628076 Subject: Re: test for nan Attachment Details:- Attachment Name: N/A File: Infected.msg Infected? No Repaired? No Blocked? Yes Deleted? No Virus Name: -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/ms-tnef Size: 1813 bytes Desc: not available URL: From skip at pobox.com Mon Mar 15 14:43:51 2004 From: skip at pobox.com (Skip Montanaro) Date: Mon, 15 Mar 2004 13:43:51 -0600 Subject: random.random - Interpreter works, Script doesn't? In-Reply-To: References: <105ac9sm9lvij49@corp.supernews.com> Message-ID: <16470.1911.988624.798146@montanaro.dyndns.org> Peter> You didn't name the above script random.py, did you :-) Bill> Bingo :o) Thanks! Bad habit, huh? Very bad. Done often enough you will wind up with lots of bite marks on your butt. Skip From eurleif at ecritters.biz Mon Mar 8 02:32:00 2004 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Mon, 08 Mar 2004 07:32:00 GMT Subject: "print" as function not statement In-Reply-To: References: Message-ID: Paul Prescod wrote: > As a convenience, if the show function is passed a > single object to show, it returns that object. If > it is passed more then one, it returns them as a > tuple. This can be very convenient in debugging > contexts. That would lead to a problem with the interactive shell, though. For instance, this would happen: >>> show('foo') foo 'foo' I'm sure there would be some way around that, but it might add more oddities to the language than print does. In any case, I did a quick Python implementation of the show function. All bugs are features. :-) import sys def show(*objects, **parameters): seperator = parameters.get('seperator', ' ') trailer = parameters.get('trailer', '\n') to = parameters.get('to', sys.stdout) first = 1 for object in objects: if not first: to.write(str(seperator)) to.write(str(object)) first = 0 to.write(str(trailer)) if len(objects) == 1: return objects[0] else: return objects From anand at easi.soft.net Wed Mar 31 04:22:16 2004 From: anand at easi.soft.net (Anand K Rayudu) Date: Wed, 31 Mar 2004 14:52:16 +0530 Subject: Python & COM References: <84257D042AA7D411B3F700D0B7DB9B7C0723BD4A@PDC-DSPACE> Message-ID: <406A8DC8.3020007@easi.soft.net> Hi Stefan, Thanks for the suggestion. From little debug i found out that I am getting VARIANT of safe array. How ever I am not getting proper values from the safe array. Could you please suggest how to implement that Do you see any problem in the following code. > >SAFEARRAY *array=V_ARRAY(a); >long i,val; >for(i=0;i SafeArrayGetElement(array,&i,&val) > c_array[i]= val; >} > >I am not getting proper values in C array. >Any suggestions? > > From dmq at gain.com Mon Mar 22 12:04:26 2004 From: dmq at gain.com (David MacQuigg) Date: Mon, 22 Mar 2004 10:04:26 -0700 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> <7x8yhvnfba.fsf@ruckus.brouhaha.com> <5d83790c.0403211310.15764495@posting.google.com> <7x4qshn64t.fsf@ruckus.brouhaha.com> Message-ID: On 21 Mar 2004 15:16:02 -0800, Paul Rubin wrote: >python at rcn.com (Raymond Hettinger) writes: [ snip discussion on Pseudo Random Number Generators (PRNG) and Mersenne Twister (MT) ] >> No corners were cut. MT is a state-of-the-art psuedo random number >> generator. The problem is that you want encryption. > >This sha prng module was motivated partly by your own remark in sf bug >#901285 that MT output may not be sufficiently correlation-free if you >take pairs of 16-bit integers from it, in a context having nothing to >do with encryption. Anyway, despite how it may sound, I don't have >any desire to use the random module for encryption (I'd use different >API's for that). I just want to be able to write applications that >use random numbers without having any doubts about whether the random >numbers are good enough. Teukolsky et al in "Numerical Recipes", >which is not a cryptography book, explain that a good way to do that >is to use cryptographic primitives, so I'm proposing a module that >does it that way. > >The application in numerics could be something like: I run some >half-hour simulation using MT, and get results that subjectively seem >a bit peculiar. So I run it again using the crypto-based generator >and maybe that takes three hours, but if I still see similarly >peculiar-looking results, I now can be pretty confident that it's not >some consequence of the RNG internals. It subjectively seems to me >that the Gnome version of Freecell is easier to play than the Windows >version (i.e. it deals easier hands), so that's a semi-real-world >example of this situation. (In this instance I suspect Freecell is >using some pathetic linear PRNG or something like that, but I haven't >yet bothered to look at the code). This reminds me of a similar discussion I had with a bunch of PhD mathematicians who wanted to sell my company a better statistics tool. Their claim was that the tool we were using, which had some simple PRNG, could give us bad results because of the correlations, short cycles, etc. that were known to mathematicians. This turned into a heated debate, involving our R&D Director and other company management, with me ( a dumb engineer who only understands simple statistics ) vs a team of PhDs who could fill the a blackboard with incomprehesible math proving I was wrong. We ended up keeping the old tool *and* buying theirs, when we should have made a clean decision. I'm still curious as to the answer to my very simple and basic question: Are there any examples that show a *non-subjective* difference in a physically meaningful result between one PRNG and another? By "physically meaningful" I mean to include things like means, standard deviations, correlations between two distributions, but rule out some measure that would only mean something to a mathematician. By "non-subjective" I mean a difference that can be observed in a repeatable fashion, where the statistical significance is not always at the edge when you repeat the experiment with more trials. The only answer I got from the earlier discussion was a reference to some paper on a German website, but when I looked, the website was gone. -- Dave From theaney at cablespeed.com Fri Mar 5 09:09:17 2004 From: theaney at cablespeed.com (Tim Heaney) Date: Fri, 05 Mar 2004 09:09:17 -0500 Subject: Parsing xml file using python References: <14b36d18.0403050216.ad3a7f5@posting.google.com> Message-ID: <877jxzv10y.fsf@mrbun.watterson> antonyliu2002 at yahoo.com (chad) writes: > > I downloaded PyXML from sourceforge, but could not install it. Python already comes with stuff like xmllib, minidom, and the aforementioned sgmllib http://www.python.org/doc/current/lib/markup.html You should be able to do what you described without installing anything else. I hope this helps, Tim From bob at redivi.com Tue Mar 2 16:18:06 2004 From: bob at redivi.com (Bob Ippolito) Date: Tue, 2 Mar 2004 16:18:06 -0500 Subject: Speed Comparison Perl Python & C References: <3064b51d.0403011035.554e7731@posting.google.com> <3064b51d.0403020649.53866885@posting.google.com> Message-ID: <2004030216180675249%bob@redivicom> On 2004-03-02 15:52:55 -0500, "Neil Hodgson" said: > beliavsky at aol.com: > >> Thanks. I am going to learn about Psyco. In this case, I assume that >> doing the computations with floating point numbers and finally >> converting the result to int gives the same values as the original >> integer calculation. In other cases, integer arithmetic will need to >> be done with integers to ensure correct results. > > Yes, in this case float has enough range. That is something you get to > determine with any fixed length numeric representation. > >> Python is supposed to be easy (and in general I agree that it is), but >> your solution requires some knowledge of >> >> (1) how integer and floating point calculations are done (which many >> novices do not have) >> (2) when Psycho can speed things up >> >> and the final result is still much slower than Fortran. For the >> Fortran program, the only "trick" is the use of integer*8. > > With Fortran, you need to know how large your values are going to become. > If you increased the number of iterations in your example sufficiently, > Fortran's 64 bit integers would overflow requiring understanding of the > concept of fixed range integers. Python avoids this by using unbounded > integers. Python is oriented towards ease of use and correctness at the > expense of speed. If the speed of the Python program is inadequate then you > can take a working Python program and work on its speed. Or decide that the > speed problem needs another language. > > Python does optimize integers that can be represented in 32 bits but > larger than that and unbounded integers are used. For some applications, it > would be better if Python also optimized integers that require between 32 > and 64 bits. Especially on architectures that have 64 bit integer registers, but are running on an operating system/compiler combination that uses 32 bits for int and long (such as the PowerPC 970, on OS X). I would imagine a similar situation exists for other processor/enivronment combinations. -bob From skip at pobox.com Fri Mar 5 17:56:04 2004 From: skip at pobox.com (Skip Montanaro) Date: Fri, 5 Mar 2004 16:56:04 -0600 Subject: Split a sentence by punctuations using Python In-Reply-To: <14b36d18.0403051444.21b3937e@posting.google.com> References: <14b36d18.0403051444.21b3937e@posting.google.com> Message-ID: <16457.1412.335966.510869@montanaro.dyndns.org> chad> You know, string.split does not work for this objective. So how chad> can i achieve this? Check the re module docs. Skip From look at www.covingtoninnovations.com.for.address Tue Mar 23 20:12:53 2004 From: look at www.covingtoninnovations.com.for.address (Michael A. Covington) Date: Tue, 23 Mar 2004 20:12:53 -0500 Subject: IDLE won't launch, and other frustrations Message-ID: Greetings, I'm trying to teach Python to some linguistics students who are new to programming. The last time I did this was 2 years ago, with Python 2.1 and IDLE. (Windows environment.) At the time, everything went smoothly except installation; as I recall Python 2.1 wrote its links into Administrator's start menu instead of All Users' start menu, and I had to move them. But once moved, it worked well. Fast forward to 2004. Following Ron Zacharski's "Python for Linguists," I choose ActiveState Python. It installs very smoothly but, but the IDE, which is called Pythonwin, is frustrating in two respects: - If the program has a serious syntax error, you don't get any error messages in the interaction window. There is only a brief note in the status line at the bottom of the screen. This is *very* frustrating to my students. - In the IDE, input() and raw_input() pop up an input box. On the console, they simply wait for input. The disparity is annoying to students who are basically learning the console paradigm. It becomes excessively hard to write an interactive console program with the IDE. So on my Windows XP laptop just now, I de-installed Python 2.1 and ActiveState Python 2.3, and went and downloaded Python 2.3.3 from www.python.org. All looks good except - IDLE won't start at all!!! I try to launch it, get a few seconds of the hourglass cursor, and it's gone, with nothing on the screen and no processes running! Rebooting didn't cure this. What gives? -- Michael A. Covington - Artificial Intelligence Ctr - University of Georgia "In the core C# language it is simply not possible to have an uninitialized variable, a 'dangling' pointer, or an expression that indexes an array beyond its bounds. Whole categories of bugs that routinely plague C and C++ programs are thus eliminated." - A. Hejlsberg, The C# Programming Language From mark at prothon.org Tue Mar 30 01:39:22 2004 From: mark at prothon.org (Mark Hahn) Date: Mon, 29 Mar 2004 22:39:22 -0800 Subject: Prothon Prototypes vs Python Classes References: <106dukh7ncf9ad4@news.supernews.com> <4068D66A.7060800@sneakemail.com> Message-ID: <9C8ac.68303$cx5.4075@fed1read04> > 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. "Greg Ewing (using news.cis.dfn.de)" wrote in message news:4068D66A.7060800 at sneakemail.com... > Mark Hahn wrote: > > Prothon has announced that we are caving in and going to spaces instead of > > tabs, even though both of the Prothon authors abhor spaces. > > You don't have to choose between them if you don't > want to. Disallowing *mixed* tabs and spaces is sensible, > but you could allow either all-tabs or all-spaces in a > given file. > > -- > Greg Ewing, Computer Science Dept, > University of Canterbury, > Christchurch, New Zealand > http://www.cosc.canterbury.ac.nz/~greg > From gandalf at geochemsource.com Wed Mar 24 15:03:09 2004 From: gandalf at geochemsource.com (Gandalf) Date: Wed, 24 Mar 2004 21:03:09 +0100 Subject: wxNotebook Message-ID: <4061E97D.9090805@geochemsource.com> Hi All! I would like to hide and show pages in a notebook. Here is what I do right now: def SetVisiblePages(self,pages): for index in range(self.notebook.GetPageCount()): self.notebook.GetPage(index).Show(index in pages) But it does not work. All pages remain visible. Only their content will be invisible. I also tried this: self.notebook.Show(index in pages) but it hides the whole nootebook. How can I hide/show individual pages? Thanks in advance. Laci 2.0 p.s.: I sent this originally to the wxpython-users list but it never arrived. From mcfletch at rogers.com Wed Mar 10 08:00:54 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Wed, 10 Mar 2004 08:00:54 -0500 Subject: Zippping a directory recursively from Python script on Windows In-Reply-To: <404f0141$0$183$edfadb0f@dread12.news.tele.dk> References: <404f0141$0$183$edfadb0f@dread12.news.tele.dk> Message-ID: <404F1186.8080403@rogers.com> Max M wrote: ... > Can it really be that there is no free .zip command line tool for > Windows, or are my Googling skills just to poor? I believe InfoZip is a free command-line zip/unzip utility, but I may be wrong about that, I normally use cygwin tar & gzip. > Or is there a more Pythonic approach? 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. HTH, Mike import zipfile, os def toZip( directory, zipFile ): """Sample for storing directory to a ZipFile""" z = zipfile.ZipFile( zipFile, 'w', compression=zipfile.ZIP_DEFLATED ) def walker( zip, directory, files, root=directory ): for file in files: file = os.path.join( directory, file ) # yes, the +1 is hacky... archiveName = file[len(os.path.commonprefix( (root, file) ))+1:] zip.write( file, archiveName, zipfile.ZIP_DEFLATED ) print file os.path.walk( directory, walker, z ) z.close() return zipFile if __name__ == "__main__": toZip( 'v:\\temp', 'c:\\temp\\test.zip' ) _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From jacek.generowicz at cern.ch Mon Mar 22 05:04:30 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 22 Mar 2004 11:04:30 +0100 Subject: PEP 318 References: <105rush64n1trba@news.supernews.com> Message-ID: "John Roth" writes: > I personally think that self not only should be a keyword, > it should not be among the parameters at all. However, I > seem to be in a distinct minority about that. The existence of C++ or Java coding guidelines which advocate the universal use of this->member or the use of m_member for all member data and function names, is (to me) evidence of the necessity of self. Also, ask an average[*] C++ programmer whether the following functions have the same type: void A::foo(void); void B::foo(void); (where A and B are both classes). In my experience[+], they will, typically, be adamant that the types are identical. If they have been exposed to Python, then you have more than a fair chance that they will understand that the types are, in fact, different. Python's explicit passing of self makes people understand what is going on, much better ... and I think that is a very valuable thing. [*] And we all know just how dangerous "average" C++ programmers are. [+] You probably don't want to know why I have had ample opportunity to ask this question, in real life. From opengeometry at yahoo.ca Sat Mar 6 17:50:25 2004 From: opengeometry at yahoo.ca (William Park) Date: 6 Mar 2004 22:50:25 GMT Subject: Need better string methods References: <0d4k40987t6d70bahqil3geth640bufgoc@4ax.com> Message-ID: Christian Tismer wrote: > William Park wrote: > > 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 > > But isn't that regex expression much harder to understand > for part-time programmers than the few Python methods? But, OP's audience is not part-time programmers. My guess is that they immediately abandon shell and jump to proprietary languages. OP may have better luck if they stick with shell a bit longer, and then jump to Python as last resort. As for regex... it's usually easier to set up the data to be cut, instead of cutting first and then patching up the pieces. -- William Park, Open Geometry Consulting, Linux solution for data processing and document management. From shane at zope.com Thu Mar 25 13:13:55 2004 From: shane at zope.com (Shane Hathaway) Date: Thu, 25 Mar 2004 13:13:55 -0500 Subject: Make 'def' and 'class' usable within expressions In-Reply-To: References: <1065uf99la6if29@news.supernews.com> Message-ID: <40632163.7070405@zope.com> 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 > 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 From faheem at email.unc.edu Fri Mar 12 13:03:05 2004 From: faheem at email.unc.edu (Faheem Mitha) Date: Fri, 12 Mar 2004 18:03:05 GMT Subject: strings question Message-ID: Dear People, If I am given two strings, named foo and bar, what is the most elegant way to create a string object whose name is the value of foo and whose value is the value of bar? I have done some searching + looking in my introductory textbook "Learning Python" but have not come up with an answer yet. Thanks. Faheem. From dmq at gain.com Wed Mar 10 21:44:04 2004 From: dmq at gain.com (David MacQuigg) Date: Wed, 10 Mar 2004 19:44:04 -0700 Subject: Extending Python Syntax with @ References: <104vg6f87k7gb19@corp.supernews.com> Message-ID: On Thu, 11 Mar 2004 01:28:47 -0000, claird at lairds.com (Cameron Laird) wrote: >In article , >David MacQuigg wrote: > . > . > . >>Wouldn't it be nice, for example, if instead of special keywords like >>'lambda' and 'yield', we had used '@(args)' and '@return'. ( No, I'm >>not advocating we go back and change what has been done.) In both >>these cases, we had a well-established syntax that needed a slight >>variation. >> >>The 'lambda function' for example, was needed to cram a small block of >>code into a tight space. By saying '@x,y:' instead of 'lambda x,y:', >>we not only avoid the need for a new keyword, but we better serve the >>purpose of tightly packing some code. We would also avoid mystifying >>beginners. "It has no magic meaning. It's just a way to write a >>function without a name." > . > . > . >No, for me it would be so far from nice I first suspected you >of jesting, because, from my background, "lambda" *does* have >a magic meaning, one that long precedes its (entirely apt) use >in Python. For you, '@(args)' might indeed be more evocative; >for me, not calling a lambda "lambda" would be a big loss. > >I think APL and J (and Perl) are plenty meritorious. I prefer >Python--much. I guess this reflects our different backgrounds. I've been an electronic design engineer for many years. I never heard of lambda's or lambda calculus until learning Python, and the name still doesn't evoke much meaning for me. I've never used APL, J, or Perl. I wonder how many technical professionals who are *not* programmers would know what a lambda is? I wonder if Python is becoming more a language for programmers, and less for "everyone". My initial impression in learning Python was that 'lambda' was something tricky. Then it became clear it was just a way to cram a function into a small space like an argument list, except that there were some strange restrictions on what could be put in the function. Even now, it seems like 'lambda x,y:' is awkward if you are trying to save space. It seems like we have paid a price for the dubious assumption that most users will benefit from the magic meaning of 'lambda'. Ruby uses a notation like |x,y|, which is compact, but I don't like adding special punctuation for every little task. (The Perl problem.) If the goal is to cram a function into a tight space, we could do it compactly, and have the extra burden of the new syntax be shared by many other features. They key characteristic is that they are small departures from existing features and syntax, so the symantic burden is not carried by the @ symbol. It's just a flag to modify something already well understood. All @X says is "I'm like X, but different." You still need to learn about X. Again, my intention is not to change lambda functions, but to propose a better way of introducing new syntax to a language that already has all the basics worked out. I would rather have one special symbol than a bunch of new keywords that mean nothing to me. -- Dave From jrm at ccs.neu.edu Thu Mar 4 10:31:57 2004 From: jrm at ccs.neu.edu (Joe Marshall) Date: Thu, 04 Mar 2004 10:31:57 -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: "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 From egusenet at verizon.net Thu Mar 25 17:57:48 2004 From: egusenet at verizon.net (Eric) Date: Thu, 25 Mar 2004 17:57:48 -0500 Subject: [Way OT] Condorcet vs. IRV References: <95aa1afa.0403230250.4c9da7a2@posting.google.com> <1060m0593q1uo0d@news.supernews.com> <10637ibo30epo6f@news.supernews.com> <89feb3ba.0403241233.32ea8604@posting.google.com> <1gb7bj1.xgiqcjp3ro1iN%egusenet@verizon.net> <1gb7o9h.bppzlf33xb5sN%egusenet@verizon.net> Message-ID: <1gb7tvh.d93veg1ygf2adN%egusenet@verizon.net> Joe Mason wrote: > In article <1gb7o9h.bppzlf33xb5sN%egusenet at verizon.net>, Eric wrote: > > Off the top of my head, the only inherent problem with it that I see is > > that what happens if 'NONE' turns out to be the Condorcet Winner? > > Then the electorate has expressed its sincere opinion that no government > at all is better than any of the candidates. Government should be > immediately dissolved and anarchy instituted. > > I have friends who would be delighted. > > It just occured to me that this is the exact case we have for PEP's, but > with NONE as an explicit option. Seems reasonable to me when taking no action is a reasonable option. From luis_ at iname.com Wed Mar 3 14:28:30 2004 From: luis_ at iname.com (Lupe) Date: Wed, 03 Mar 2004 19:28:30 +0000 Subject: insertion in lists Message-ID: hi, 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. if I have: element list [0] and want to have list[0][0] list[0][1] how can I insert the element to that list[0][0], for example? just to put things clearer, if I wanted to insert the element in list[0] I could do list.insert(0,element). I've tried list[0].insert(0,element) but gives me an error. Luis From davecook at nowhere.net Sun Mar 7 09:37:25 2004 From: davecook at nowhere.net (David M. Cook) Date: Sun, 07 Mar 2004 14:37:25 GMT Subject: New to Python; what about #include, extern and function prototypes References: <20040307020101.539$r9@news.newsreader.com> <404b18ce$0$565$e4fe514c@news.xs4all.nl> Message-ID: In article , Bo Jacobsen wrote: > By the way, is there an elegant way to read shell program output > into a variable as in bash: var=$(command1 | command2) I usually use the commands module: import commands status, output = commands.getstatusoutput("command1 | command2") status would be $? in bashese. Dave Cook From max at alcyone.com Tue Mar 30 17:06:27 2004 From: max at alcyone.com (Erik Max Francis) Date: Tue, 30 Mar 2004 14:06:27 -0800 Subject: struct.pack Format String Question References: <4069E5C6.BC5274E6@vt.edu> Message-ID: <4069EF63.5BF40688@alcyone.com> Joshua Forgione wrote: > In this case, 'B' is used. What does 'B' represent? What other > characters can be used? Does a list of this exist somewhere? http://www.python.org/doc/current/lib/module-struct.html -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE \__/ But you're not going to be there tomorrow. And it's all about tomorrow. -- Montgomery Brogan From __peter__ at web.de Sun Mar 14 02:29:16 2004 From: __peter__ at web.de (Peter Otten) Date: Sun, 14 Mar 2004 08:29:16 +0100 Subject: Interpreting \ escape sequences in strings References: <40537b16$1_1@themost.net> <4053daa0_1@themost.net> Message-ID: Paul Watson wrote: > I did have not explained it clearly. I want the user to specify a string Seems it was clear enough, you only didn't recognize the answer :-) > that I will put between words in the output. The user specified string > can > have escape sequences. For example, the user wants to put a binary 1 > (\001) between each output word. > > import sys > words = ['now', 'is', 'the', 'time'] > print '\001'.join(words) #this works > print sys.argv[1].join(words) #this fails Change the above line to print sys.argv[1].decode("string_escape") s.decode("string_escape") returns a new string with all c-style escape sequences converted into the corresponding characters. This is an abuse - ahem, example of a general mechanism. Look for codecs if you want to learn more about it. Peter From jcarlson at nospam.uci.edu Tue Mar 2 18:12:03 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Tue, 02 Mar 2004 15:12:03 -0800 Subject: Group comment In-Reply-To: References: Message-ID: > thus > > Q'XXX' > i=1 > i+=1 > print i > print i+1 > 'XXX' You may as well suggest /* and */, as they are far more well known, and significantly more acceptable (in my opinion) than your syntax. Considering that /* */ has not already been added to the language, I doubt that an aribirary magical syntax for commenting code would be added. - Josiah From t-meyer at ihug.co.nz Wed Mar 17 21:48:40 2004 From: t-meyer at ihug.co.nz (Tony Meyer) Date: Thu, 18 Mar 2004 15:48:40 +1300 Subject: imaplib.IMAP4: Bug in implementation In-Reply-To: <1ED4ECF91CDED24C8D012BCF2B034F1305903A3B@its-xchg4.massey.ac.nz> Message-ID: <1ED4ECF91CDED24C8D012BCF2B034F13026F2B3A@its-xchg4.massey.ac.nz> >>> Have you tried uid("STORE", uid, "+FLAGS", "(\SEEN)")? >> >> I was bitten by this just the other day. Donn is correct, >> adding the surrounding parentheses fixes the problem. > > Actually it looks to me like there are parentheses in either > case. What I wanted to try is two separate parameters, > rather than the whole thing "+FLAGS(\SEEN)" as one parameter. > I think that will solve the problem, but am just guessing. > > As far as I know, this is different from the parenthesis > issue you allude to. I should have read it more carefully :) The solution is indeed to split up the args (tested). It's still a result of the same flaw in _checkquote(), though, because in the OP's version the whole UID STORE arg after the number is quoted, when it shouldn't be. I'd still like to see that function improved (which would fix both the problems described, the OP's and mine), although I suppose there's always Twisted. =Tony Meyer From mike at zcentric.com Mon Mar 15 11:44:55 2004 From: mike at zcentric.com (Mike Zupan) Date: Mon, 15 Mar 2004 11:44:55 -0500 (EST) Subject: py2exe and urllib(2) errors Message-ID: <45960.66.193.31.32.1079369095.squirrel@www.zcentric.com> I had some problems with urllib and py2exe under pyton2.3. I works fine until i try to use the exe file. Here is the error Error: 1 LookupError Exception in Tk callback Function: > (type: ) Args: () Traceback (innermost last): File "Pmw.pyc", line 1784, in __call__ None File "", line 270, in selectDir None File "", line 361, in grabAlbumDirs None File "", line 431, in addAlbumData None File "", line 469, in grabImage None File "urllib2.pyc", line 129, in urlopen None File "urllib2.pyc", line 326, in open None File "urllib2.pyc", line 306, in _call_chain None File "urllib2.pyc", line 901, in http_open None File "urllib2.pyc", line 884, in do_open None File "httplib.pyc", line 712, in endheaders None File "httplib.pyc", line 597, in _send_output None File "httplib.pyc", line 564, in send None File "httplib.pyc", line 532, in connect None LookupError: no codec search functions registered: can't find encoding Here is the section of code that produces the error urllib.urlretrieve(imageURL, saveFile) imageURL and saveFile are correct Here is my setup.py file # setup.py from distutils.core import setup import py2exe setup( scripts=["art.py"] ) and here is my batch file c:\python23\python setup.py py2exe -pPIL --packages=encodings Thanks Mike From dallasm at aiinet.com Fri Mar 12 12:22:53 2004 From: dallasm at aiinet.com (Mahrt, Dallas) Date: Fri, 12 Mar 2004 12:22:53 -0500 Subject: root password in a .py script Message-ID: This is not a good idea, even if it were possible. What is preventing somebody from importing this script in Python from the CLI and extracting the root password? Even if the decrypt logic is in the code, and only the .pyc is accessible, the decompile logic would still be easily accessible. What is preventing you from prompting for the password on execution? --- Dallas S. Mahrt > -----Original Message----- > From: Bart Nessux [mailto:bart_nessux at hotmail.com] > Sent: Friday, March 12, 2004 9:12 AM > To: python-list at python.org > Subject: root password in a .py script > > > 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: > > pass = "#$%^&@*#&*$^@" > instead of: > pass = "root-password" > > Thanks, > > Bart > -- > http://mail.python.org/mailman/listinfo/python-list > From peter at engcorp.com Sat Mar 6 09:30:04 2004 From: peter at engcorp.com (Peter Hansen) Date: Sat, 06 Mar 2004 09:30:04 -0500 Subject: Newby Question: Generic Database Object Interface Needed In-Reply-To: <1Rc2c.2356$u92.1037@fe3.columbus.rr.com> References: <1Rc2c.2356$u92.1037@fe3.columbus.rr.com> Message-ID: kbass wrote: > I have two databases, Postgres and Oracle, and I would like to be able to > use the same syntax to access and retrieve data in the same way. Is there a > generic database object interface (module) that will allow me to access and > retrieve data the same way? I would prefer one that is well supported. Does this help? : http://www.python.org/topics/database/ -Peter From usenet at ixokai.net Sun Mar 14 00:17:38 2004 From: usenet at ixokai.net (Ixokai) Date: Sat, 13 Mar 2004 21:17:38 -0800 Subject: Extending Python Syntax with @ References: <3g31501dfsut81gboa43qu6bj7n37ffumr@4ax.com> <5u9150peaueqmsrt5tppc08mro5q8acebu@4ax.com> Message-ID: <1057qnntt6tjb4@corp.supernews.com> > >This is all semantics, probably, but I don't believe you can make a > >strong case that yield is an ill-chosen name. > > It's not ill chosen, just arbitrary. I would be just as happy with > 'rtn' or 'tsr' or any fanciful word that doesn't convey a _wrong_ > meaning. To me, it conveys the perfect meaning. All it takes is having the right mindset. You yield in traffic; you let someone go along before you and then continue on.. that's what generators are, perfectly. Yes, only one definition of 'yield' fits Python's usage-- but that's infinately better then "Like return, but different". What happens if you have a second type of 'return-like' statement? @@return? @return@? If someone is learning a language, they'll always run into keywords and such that they do not understand. So they have to look them up. No big deal. Afterwards, when they get the mindset of how to think in them, it sticks-- they can then glance down and remember, and /know/, what's going on. It becomes again pseudocode-that-works: 'yield X' means, 'give off X and let the control continue on its way, i'll be continued later'. However, something like '@return X' wouldn't accomplish the same result, in my opinion. For some people it'll be too easy to just ignore the punctuation and think 'return', when its very important that they not think 'return' in this case. For others, it'll always catch their eyes and make them pause and think-- which variant of return is this? A new keyword in this instance is perfect: its totally different, and totally seperate from the behavior of 'return', so someone can't just pass it by with assumptions of 'return', and once they learn what it is, it sticks. --Stephen From and-google at doxdesk.com Mon Mar 15 03:55:32 2004 From: and-google at doxdesk.com (Andrew Clover) Date: 15 Mar 2004 00:55:32 -0800 Subject: Question concerning Unicode and or Shift-JIS References: <4050f410$0$40740$c3e8da3@news.astraweb.com> Message-ID: <2c60a528.0403150055.7dd24a6f@posting.google.com> Antioch wrote: > However, when getting user input, the input it natively sent to the > program in Shift-JIS encoding. You can change this by setting the encoding of the web page containing the
, either by having the server send an HTTP response header 'Content-Type: text/html;charset=utf-8', or by including a element inside the . If you don't set the charset like this, the browser will have to guess what encoding to use, which in the absence of any properly-encoded Japanese text on the form page could be anything, and may default to different encodings dependent on the user's locale. [Detour:] The browser will send the form submission in the specified encoding, *unless* the user deliberately goes to the browser's encodings menu and selects a different one. Unlikely, but possible. The 'proper' way around this is to write , which should mean that the browser should send the submission as UTF-8 regardless of the encoding of the page containing the form. Unfortunately Internet Explorer on Windows is broken and stupid, and prefers to use this as a 'backup' encoding: it will use the current page's encoding for fields which can be encoded in that, and the accept-charset encoding on fields that contain characters that can't be encoded in the current page's charset. Thus you can get a mixture of encodings with absolutely no way to determine which is which. The IE-compatible but utterly hideous workaround is to avoid accept-charset and include a hidden field with name '_charset_' in the form. IE will fill it in with the currently selected encoding when the form is submitted. Whether it is worth doing this is debateable. [end detour.] > the problem is I don't know how to "decode" the UTF and then recode > it into Shift-JIS so that I can compare the dictionary values I'd definitely recommend storing the dictionary values as Unicode strings rather than trying to compare encoded versions. > I don't know how to decode any of the codecs. I'm sure theres just > some simple function call Yep: characterString= unicode(jisString, 'shift_jis') utfString= characterString.encode('utf-8') -- Andrew Clover mailto:and at doxdesk.com http://www.doxdesk.com/ From anton at vredegoor.doge.nl Wed Mar 31 14:32:02 2004 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Wed, 31 Mar 2004 21:32:02 +0200 Subject: A 'Python like' language References: <1068up4kn49778@news.supernews.com><58cb60lmovocadg9p3ghu39t4ga343gfvd@4ax.com><37S9c.58035$cx5.39835@fed1read04><1J8ac.68390$cx5.23284@fed1read04> Message-ID: <406b1cdf$0$125$3a628fcd@reader3.nntp.hccnet.nl> Terry Reedy" wrote: >What's funny and sad about this is that I would not be surprised to >discover, after some experience, that prototypes fit my brain better than >the class model. Too bad he could not allow himself to see the satiric >humor of my hint. Look at the bright side Terry :-) Last time he got irritated by someone he wrote a completely new language and even apologized for his behavior in the end! Anton From alan.gauld at btinternet.com Tue Mar 16 04:18:13 2004 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 16 Mar 2004 09:18:13 +0000 Subject: new to programming: suggestion References: <3d5e65ea.0403152115.3df7e8c1@posting.google.com> Message-ID: On 15 Mar 2004 21:15:47 -0800, alessandro_valerio at msn.com (pius) wrote: > i'm new in programming; i'd like to find a good programming book, full > of examples guiding me step to step in the marvellous world of > programming. Best place to start is the non programmers section of the Python web site. Despite the fact that I wrote one, I don't think most folks need a book to learn the basics, there are plenty of web tutors for that. Pick one you like and work your way through it. (If you do want a beginners tutor then feel free to buy mine though! :-) More useful is to get an intermediate level book like Programming Python by Lutz. Also a concise referce like "Python in a Nutshell" or "Python Essential Reference" is handy. Also you might find some of the more general programming books useful too: The Pragmatic Programmer by Hunt & Thomas is good The Practice of Programming by Kernighan & Pike is another Finally all serious programmers should read Code Complete by McConnell. And if you really want to understand the underlying theory try Structure & Iterpretation of Computer Procrams(SICP) by Abelman and Sussman - a classic which is also online: http://mitpress.mit.edu/sicp/full-text/book/book.html That should keep you busy! :-) HTH, Alan G. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld From jaustin at post.harvard.edu Tue Mar 16 04:06:28 2004 From: jaustin at post.harvard.edu (Jess Austin) Date: 16 Mar 2004 01:06:28 -0800 Subject: mutable list iterators - a proposal References: Message-ID: aahz at pythoncraft.com (Aahz) wrote in message news:... > I'll guarantee that it won't be fixed for 2.4. This subject has come up > many times long before iterators were introduced, and the answer has > always beent the same: if you want to mutate, make a copy or make *very* > sure that your mutations don't muck the loop. If this was hashed out so completely before iterators, I wonder if iterators might make a different solution more plausible. Such a solution wouldn't have been considered since then, because, well, it has already been hashed out. > >I hope this isn't in conflict with any previous irrevocable > >pronouncements. b-) > > Your hope is in vain. ;-) It usually is; still I hope. b-) Jess From glaine at free.fr Mon Mar 8 05:29:13 2004 From: glaine at free.fr (glaine) Date: 8 Mar 2004 02:29:13 -0800 Subject: Start Message-ID: Start Hello I'm new in python. I try to make a script like a sub routine which save the win registry each morning after the win98's running. I have a lot of problems to concretize my idea about the moment when my script start. How to do to run automatically my script each morning after the win98's running I will accept any suggestions or ideas. I found some elements with win32events and handle, but I don't understand very well what handle means in python. Is there anybody to explain me ? Thank all for your help. Save Registry.py import _ winreg t=file('c:\\windows\\bureau\\toto.txt','w') p=_winreg.SaveKey(Keys x, Keys y,'t') Guillaume From claird at lairds.com Tue Mar 23 16:33:10 2004 From: claird at lairds.com (Cameron Laird) Date: Tue, 23 Mar 2004 21:33:10 -0000 Subject: Python for large projects References: <1060p59d9rg9819@corp.supernews.com> <1080074644.4365.12.camel@wintermute.atriaky.sk> Message-ID: <1061b8mkui8n922@corp.supernews.com> In article , Dave Brueck wrote: . . . >> (previously all the programs were written in java) >> "if one of our programmers changes a method in a class/interface, we >> immediately will know about it, because the next program-rebuild will >> simply fail. but if we would use python, we wouldn't find it out". > >Say "Bzzt! Wrong!" :) In C++ this is a no brainer because the compiler simply . [Dave continues with his perfectly rendered follow-up] . . >everybody should avoid. I would ask them to cite a real world example rather >than hypothetical "what-ifs" because the refactoring of an interface is almost >always accompanied by a semantic change to the interface, and again the >compiler can't really help there. > >-Dave > > Here's the part that scares me: I've seen enough to suspect that, in some shops, this line of reasoning is *not* hypo- thetical--that is, that the locals truly do conceive of refactoring as fiddling around with signatures and reacting to overt compiler messages. Brutalities are committed in the name of IT that admit no other explanation. -- Cameron Laird Business: http://www.Phaseit.net From lucat at despammed.com Tue Mar 16 13:08:52 2004 From: lucat at despammed.com (Luca T.) Date: Tue, 16 Mar 2004 19:08:52 +0100 Subject: Python & Linux, some questions (2) In-Reply-To: References: Message-ID: Thomas Guettler wrote: > Be carefull, there are a many things you need to > make it secure. Maybe suexec of apache can be > used as template. Where can i find its sources? Thanx, Luca From fouff at visitmail.com Wed Mar 31 10:41:19 2004 From: fouff at visitmail.com (Fouff) Date: 31 Mar 2004 07:41:19 -0800 Subject: Modifying Entry size Message-ID: <8b352861.0403310741.78ba64e9@posting.google.com> Hello. I'm trying to modify manually the size of a tkinter Entry . Especialy the width (in pixel for my calc), not in character as the width property of the widget. Thanks for help. From sross at connectmail.carleton.ca Sun Mar 28 12:24:36 2004 From: sross at connectmail.carleton.ca (Sean Ross) Date: Sun, 28 Mar 2004 12:24:36 -0500 Subject: Breakdown of approaches to PEP318 References: <7vD9c.318$1A6.114130@news20.bellglobal.com> Message-ID: <5TD9c.343$1A6.122185@news20.bellglobal.com> That last one had an error, here it is again: [publish_to_web] def foo(self): {spark_rule:"DOC:= HEAD BODY FOOT", url:"/cgi-bin/directory/directory" } "doc string" body From pxlpluker at cfl.rr.com Fri Mar 5 09:44:44 2004 From: pxlpluker at cfl.rr.com (pxlpluker) Date: Fri, 05 Mar 2004 09:44:44 -0500 Subject: Pushing file name to browser In-Reply-To: <4041DE9C.9070201@pusspaws.net> References: <4041DE9C.9070201@pusspaws.net> Message-ID: <4048925C.1030505@cfl.rr.com> 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 From Spam at ivonet.nl Sat Mar 6 04:56:27 2004 From: Spam at ivonet.nl (Ivo) Date: Sat, 6 Mar 2004 10:56:27 +0100 Subject: import vs from module import : any performance issue? References: <3Rc2c.20653$qA2.1452238@news20.bellglobal.com> Message-ID: <4049a051$0$3886$3a628fcd@reader1.nntp.hccnet.nl> Quote from Dive Into Pyhton """ When a line of code asks for the value of a variable x, Python will search for that variable in all the available namespaces, in order: 1. local namespace - specific to the current function or class method. If the function defines a local variable x, or has an argument x, Python will use this and stop searching. 2. global namespace - specific to the current module. If the module has defined a variable, function, or class called x, Python will use that and stop searching. 3. built-in namespace - global to all modules. As a last resort, Python will assume that x is the name of built-in function or variable. """ when you use: from x import y you import into the local namespace. so in theory it could by a speedup to use this form. if you use import x you will have to address the functions by there namespace (which equals the name of x), so no speedup will be gotten there. "Peter Otten" <__peter__ at web.de> wrote in message news:c2c2r9$p5t$03$1 at news.t-online.com... > Pierre Rouleau wrote: > > > Q1: > > I'v seen mentionned in some post that there could be performance issues > > of using: > > > > from moduleX import whatever > > > > as opposed to: > > > > import moduleX > > > > What would be the performance issues? > > You wouldn't put the import statement into an inner loop, so why bother. > Every module is imported once (there is a pathological exception) and > subsequent imports are essentially lookups in sys.modules. > However, moduleX.whatever() is one dictionary lookup slower than the bare > whatever(), and *that* might occur in an inner loop. > > > > > Q2: > > What happens when names from moduleX are imported using the first former > > syntax in some modules of an application and imported using the latter > > syntax in other modules of the same application? > > Nothing. You can even mix both forms in the same module: > > >>> import os > >>> from os import walk > >>> os.walk > > >>> walk > > >>> > > > Q3: > > It's my understanding that using the "from moduleX import whatever" > > syntax in moduleA, all of moduleX code will run and only the name > > "whatever" will be made available to moduleA. What are the benefit of > > using this syntax then, is it only the fact that you don't have to type > > the "moduleX." prefix in moduleA? > > A tiny speedup. The disadvantage being pollution of the importing module's > namespace. Not as bad as from module import *, though. > > Peter From roccomoretti at hotpop.com Wed Mar 17 14:33:29 2004 From: roccomoretti at hotpop.com (Rocco Moretti) Date: Wed, 17 Mar 2004 13:33:29 -0600 Subject: python-dev Summary for 2004-02-01 through 2004-02-29 In-Reply-To: References: Message-ID: Brett C. wrote: > --------------------------------------------------- > Do we really need mutability for exceptions groups? > --------------------------------------------------- > The question was raised as to why ``except (TypeError, ValueError):`` > is acceptable while ``except [TypeError, ValueError]:`` (in other > words why use tuples to group exceptions for an 'except' statement and > not allow lists). The question was in relation as to whether it had > something to do with a tuple's immutability. > > Guido said it all had to do with a visual way of grouping tuples and > nothing to do with what the underlying container was. If he had it to > do over again he would rather change it so that ``except TypeError, > ValueError:`` did the same thing as above. That change would > alleviate the common error of expecting the above behavior using that > syntax but instead getting the exception instance bound to ValueError. > But the change is not planned for any time in the future since Guido > has no proposal on how to change the syntax to handle the assignment > to a local variable for the exception instance. Generalizing it to any iterable would be nice, especially with situations where you have the exception types stored in a variable: catch = (TypeError, ValueError, MyValueError) ... try: #Body except catch: #Error code If you need to dynamically add exceptions, it may be easier to use a list, and using general iterables opens up all sorts of fun with generators. (Is time savings all that big of deal here?) As far as Python3000 syntax, has anyone suggested 'as' abuse? try: #Body except TypeError, ValueError as e: #Error code I'm not sure if this is compatable with the parser or not, but it looks nice ... -Rocco From jbperez808 at yahoo.com Sun Mar 21 10:53:06 2004 From: jbperez808 at yahoo.com (Jon Perez) Date: Sun, 21 Mar 2004 23:53:06 +0800 Subject: Python bytecode compatibility between interpreter versions In-Reply-To: References: Message-ID: Skip Montanaro wrote: > The fundamental difference between Java and Python in this regard is that > the JVM must absolutely be part of the defined API since it is delivered > separate from the compiler. Absolutely untrue. The JVM is part of the Java /spec/, but has nothing to do with the /API/ (e.g. Java 2 Standard Edition) that application programmers use. > Whoever does this stuff probably has to go to great lengths to preserve > compatibility. This is not the case for the Python VM, since a new version > is delivered with each distribution. I don't get what you're trying to say here. The JVM has changed very little (or not at all) over the different Java versions. Neither the incremental feature-additions to the Java compiler nor modifications to the Java platform APIs require any great effort to 'maintain compatibility' between them and the JVM. Even fairly major additions like generics (i.e. Pizza compiler) do not sound like they require ripping out great chunks of guts and replacing them with something totally new. If anything though, what you're saying might apply more to Jython. New Python language features tend to be more radical / come faster than new Java features but the Jython authors will have to implement these on a JVM that cannot morph to accomodate such new features. Still, Jython's continued development proves that it is possible implement Python's features on a fixed underlying VM. The only reason I can think of for wanting CPython's VM to remain undocumented / not-nailed-down is because we want to make it easier / give more freedom to the language designers to implement the plumbing for new Python features. From mwilson at the-wire.com Mon Mar 22 10:41:20 2004 From: mwilson at the-wire.com (Mel Wilson) Date: Mon, 22 Mar 2004 10:41:20 -0500 Subject: Reload() Confusion References: Message-ID: In article , David MacQuigg wrote: >I like this code example because it gets the student to think about >how modules are kept in memory. Showing the module's dictionary >before and after a reload is great. I'll try to integrate it into my >presentation, perhaps in place of the second example, which can now >become an exercise. Thanks. Use it in good health. Mel. From Scott.Daniels at Acm.Org Mon Mar 1 19:49:46 2004 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Mon, 01 Mar 2004 16:49:46 -0800 Subject: Using the __builtins__ module to assign new global variables In-Reply-To: <7c160399.0403011348.779cc5c8@posting.google.com> References: <7c160399.0403011348.779cc5c8@posting.google.com> Message-ID: <4043e2cf$1@nntp0.pdx.net> Opinder wrote: > Are there any side effects in assigning new variables to the > __builtins__ module for the purpose of exposing variables to imported > modules. Generally, Guido frowns at you very sternly. Also, you could cause a disaster if there is a conflict between your idea of what should be a global and some other module's idea. You will be in big trouble if a builtin is added that you over-write (actually a form of the same problem). -- -Scott David Daniels Scott.Daniels at Acm.Org From jacek.generowicz at cern.ch Tue Mar 23 09:36:57 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 23 Mar 2004 15:36:57 +0100 Subject: Python for large projects References: Message-ID: Andrew Wilkinson writes: > assaf__ at walla.com wrote: > I find the lack of static type checking to cause some bugs to hide > in my code that in other languages would be found at compile time. I feel honour-bound to point out that citing static typing (explicit static typing, in particular) as a means of creating more correct programs, to be one of the greatest contemporary myths of software engineering. Static typing makes it easier for compilers to produce more efficient code. That is the only advantage that static typing offers. I am of the opinion that (explicit) static typing contributes to the bugginess of programs. From wweston at att.net Mon Mar 29 10:46:45 2004 From: wweston at att.net (wes weston) Date: Mon, 29 Mar 2004 15:46:45 GMT Subject: Wierd problem with replace In-Reply-To: References: Message-ID: Florian Lindner wrote: > Hello, > I've this code: > > print "Login1:", login > login.replace("@","_") > print "Login2:", login > > Which produces this output: > > Login1: tester at root > Login2: tester at root > > Why is Login2 still tester at root and not tester_root? I thought that I've > replaced the @ with _?? > > Thx, > Florian > Florian, >>> x = "tester at root" >>> y = x.replace("@","_") >>> print y tester_root From danb_83 at yahoo.com Tue Mar 30 21:30:15 2004 From: danb_83 at yahoo.com (Dan Bishop) Date: 30 Mar 2004 18:30:15 -0800 Subject: Equality and identity References: <3cfvfkmi337.fsf@nelja.ifi.uio.no> Message-ID: 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 >>> x = 100 >>> x is 100 False From webmaster at keyphrene.com Tue Mar 23 02:05:28 2004 From: webmaster at keyphrene.com (webmaster at keyphrene.com) Date: Tue, 23 Mar 2004 07:05:28 GMT Subject: pyOpenSSL is dead or not? Message-ID: <405fe1b6$0$298$636a15ce@news.free.fr> The last pyOpenSSL has been released in September 2002. pyOpenSSL is dead or not? From timr at probo.com Mon Mar 15 01:52:27 2004 From: timr at probo.com (Tim Roberts) Date: Sun, 14 Mar 2004 22:52:27 -0800 Subject: random.random - Interpreter works, Script doesn't? References: <105ac9sm9lvij49@corp.supernews.com> Message-ID: "Bill" <> wrote: >Hello, >If I type the following code directly into the interpreter, it works. If I >run it from a script, it generates the following error. Can someone help? >Thanks! > >------------------------ > >import random > >for i in range(10): > x = random.random() > print x > >------------------------ > >TypeError: 'module' object is not callable I'll wager money that your script actually says this: import random for i in range(10): x = random() print x ...which IS trying to call a module. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From assaf__ at walla.com Mon Mar 22 06:11:08 2004 From: assaf__ at walla.com (assaf__ at walla.com) Date: Mon, 22 Mar 2004 13:11:08 +0200 Subject: Python for large projects Message-ID: <200403221111.i2MBB8B18186@omail3.walla.co.il> Hello, I am beginning to work on a fairly large project and I'm considering to use python for most of the coding, but I need to make sure first that it is reliable enough. I need to make sure that I won't have surprises when my program runs on different real-world systems. So far I wrote a little script with python using urllib, and on one computer it failed completely because of a problem in getting the proxies (in my opinion this is a bug). How likely are such things to happen and how often, and to what extent are they more prevalent in python in comparison to C++? If python is indeed suitable for large projects, how common is it to actually use if for such purposes? Is there perhaps a list of examples of real projects using python? Thanks, Bob ----------------------------------------------------------------------- Walla! Mail, Get Your Private, Free E-mail from Walla! at: http://mail.walla.co.il -------------- next part -------------- An HTML attachment was scrubbed... URL: From elmlish at netscape.net Wed Mar 3 15:53:18 2004 From: elmlish at netscape.net (elmlish) Date: Wed, 03 Mar 2004 20:53:18 GMT Subject: Efficiently test for positive re.match then use the result? References: Message-ID: <20040303125347291-0800@news.qwest.net> > What's wrong with: > > alist =3D ['boo','hoo','choo'] > for line in alist: > m =3D re.match('choo', line) > if m: > doSomethingWith(m.groups(0)) > > > FuManChu > > Nothing, really.. I was just hoping I could do that in even fewer steps. You know, the search for eternally overreaching brevity... Thanks though. -- ~elmlish~ From max at alcyone.com Fri Mar 12 20:45:08 2004 From: max at alcyone.com (Erik Max Francis) Date: Fri, 12 Mar 2004 17:45:08 -0800 Subject: put your money where your mouse is, or why I prefer Spanish to English: a proposal References: <082d01c407eb$bb8dfc10$210110ac@jsbwxp3> Message-ID: <405267A4.18109F72@alcyone.com> Harry George wrote: > Hmmm. How many Pythonistas have studied Esperanto? Looks like 2 of > us so far. The Esperanto headquarters is in Netherlands, so there is > a suspicious confluence of geography with Python. Sxajnas, ke la Pitonistoj kiuj povas paroli Esperanton nombrigxas almenaux kvar aux kvin. -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE \__/ When you talk to her / Talk to her -- India Arie From likwoka at yahoo.com Mon Mar 1 14:51:06 2004 From: likwoka at yahoo.com (Alex Li) Date: 1 Mar 2004 11:51:06 -0800 Subject: Multi-user quiz show game Message-ID: Hi all, I would like to create a quiz show game for play in a party. The physical setup would probably be a big screen where everyone (players and host) can see, which shows a question, and a multiple choice of answer. The player, with a client computer and keyboard in front, will press a key to pick an answer. The client program, will then send the player's choice through the wire to the server program. The server program will validate the player's answer and the one that is correct and fastest will get a point. Then we go on to the next questions...etc. Some more specific requirements: 1) the programm will probably run on some windows machines 2) need unicode support (ie. questions and answers will be shown in Chinese) 3) the display will be a full screen display (ie, no window's toolbar or taskbar shown) My current thinking is: 1) Use twisted for the networking code 2) Use wxpython for the screen display My questions are: Does anyone have any recommendation of what frameworks/libraries to use? I am kind of worry about mixing all these libraries/frameworks together for them to play nicely... Would pygame help simplify? Thanks a lot, Alex From python at apocalyptech.com Mon Mar 8 18:26:39 2004 From: python at apocalyptech.com (CJ Kucera) Date: Mon, 8 Mar 2004 17:26:39 -0600 Subject: optparse variable parsing? Message-ID: <20040308232639.GB11572@unisrv.net> Hello, list! I'm wondering if it's possible to have an option with optparse function as either a true/false option, or optionally use a supplied value when it's provided. For example, let's say that I'm writing a util to add a user to some system. By default, the program would assign a random password: > $ adduser.py > Assigned password: If the user specifies "-p", the program would prompt for a password instead: > $ adduser.py -p > Pass: > Confirm: And then it'd be great to be able to pass in a hashed value and have the program use that instead: > $ adduser.py -p\$1\$KgM/m2Ys\$.o0sbvwHddeKMCKJdfcMJ0 Is something like that possible with optparse? Thanks! -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 aahz at pythoncraft.com Thu Mar 4 06:30:28 2004 From: aahz at pythoncraft.com (Aahz) Date: 4 Mar 2004 06:30:28 -0500 Subject: Especialized generator References: Message-ID: In article , Boogie El Aceitoso wrote: > >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? You don't. You write another generator that yields appropriate results from calling os.walk(). Chaining generators is *wonderful*. -- 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 peter at engcorp.com Fri Mar 19 08:18:39 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 19 Mar 2004 08:18:39 -0500 Subject: services In-Reply-To: References: Message-ID: <0qudndWnJMqybsfdRVn-uA@powergate.ca> John Hazen wrote: > try: > > % nohup file.py & > > It redirects the output (and stderr) to ./nohup.out, and prevents the > HUP signal from being sent to the process when you log out. Interesting! Note, from "info nohup", that it reduces the process' priority (i.e. increases the priority value by 5), and can in some cases not actually run the command at all. Still, another interesting tidbit for the toolbox. -Peter From peter at engcorp.com Thu Mar 11 12:01:57 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 11 Mar 2004 12:01:57 -0500 Subject: Extending Python Syntax with @ In-Reply-To: <3g31501dfsut81gboa43qu6bj7n37ffumr@4ax.com> References: <3g31501dfsut81gboa43qu6bj7n37ffumr@4ax.com> Message-ID: David MacQuigg wrote: > 'yield' is a little closer to the intent, but again, to most new users > it probably means something more like 'give way' or 'acquiesce', the > opposite of 'resist'. If you had never seen 'yield' used as it is now > in Python, and your first encounter with generator functions was when > you saw @return, would you not think "Ah yes, a modified return.", and > would that not be closer to reality than whatever you might associate > with the word 'yield'? No! The "give way" meaning is _much_ closer to what is going on than "modified return", in my way of looking at it. Return winds up the call stack and just happens to include a result value. Yield temporarily "gives way" but leaves the stack frame in place, available for resumption at a later time. You could say that the result value is incidental, in the return case, while the permanent transfer of context is the key thing. Just the opposite in the case of yield, and therefore much different from a "modified return". This is all semantics, probably, but I don't believe you can make a strong case that yield is an ill-chosen name. -Peter From bob at redivi.com Mon Mar 8 10:58:17 2004 From: bob at redivi.com (Bob Ippolito) Date: Mon, 8 Mar 2004 10:58:17 -0500 Subject: Socket Receive Buffer References: <404c3419$0$63629$5a6aecb4@news.aaisp.net.uk> Message-ID: <2004030810581743658%bob@redivicom> On 2004-03-08 03:51:38 -0500, John Burton said: > christofer wrote: > >> I am writing a small IRC type server. I also have a small test client >> for obvious reasons. My problem is that when receiving input from the >> server, my client sometimes ends up with two messages in the same >> input buffer, which obviously causes problems. Anybody know why it is >> doing this? > > It's the way that sockets work. > They are just a stream of bytes. > You *might* read the whole message you sent in one go, or you might get > 60% of the message in one read and 40% in the next, or you might be two > messages together, or any other cominbation. > > Often you'll get each message seperately when testing on a low load > local network but get different results over the internet. > > You need to find the end of the messages yourself, and remember that a > single read might not return the whole of the messasge. > > Yes it's a pain but that's how it works. And this is exactly why you can and should use a higher level abstraction, like Twisted or at least medusa/asyncore. -bob From nospam at nowhere.hu Mon Mar 29 03:13:19 2004 From: nospam at nowhere.hu (Miklós) Date: Mon, 29 Mar 2004 10:13:19 +0200 Subject: Where to offer simple apps References: Message-ID: Sourceforge? Savannah? or c.l.p ? :) Or have a look around at www.python.org .. then decide if you like pypi or Starship, etc. Pm "Christian von Essen" wrote in message news:c46tob$bkl$1 at online.de... > Hi all > > I've written a little .ini fileeditor, neither important nor good enough > to become an own project, but for me important enough to want to get > some feedback, as it is my first more or less sensible python > application. Where is the best/a good place to offer this code and ask > for feedback. > > Well, it seems, that I already offer my code here ;) > > The application consists of 442 lines in 2 files. I use Tkinter and my > own ini-parser because I wanted to learn how to parse such a simple format. > > Christian von Essen From hufman at cobalty.com Sun Mar 7 00:26:32 2004 From: hufman at cobalty.com (Walter Huf) Date: 7 Mar 2004 00:26:32 -0500 Subject: Sending binary data over CGI References: Message-ID: > import msvcrt > ... > msvcrt.setmode( stdout.fileno(), os.O_BINARY ) Now, what would I do if I want to do the same in Unix/Linux? --Walter Huf-- From roy at panix.com Tue Mar 16 14:18:39 2004 From: roy at panix.com (Roy Smith) Date: Tue, 16 Mar 2004 14:18:39 -0500 Subject: Is Python type safe? References: <221d8dbe.0403161043.52406195@posting.google.com> Message-ID: In article <221d8dbe.0403161043.52406195 at posting.google.com>, srijit at yahoo.com wrote: > Hello, > I would like to know the definition of type safe and whether Python > can be considered as a type safe language. Similarly are Java, C# or > C++ type safe? > > Regards, > Srijit You tell me what you mean by "type safe", and I'll tell you if those languages meet that definition. C++ and Java both have the concept of declaring variables to hold a certain type of data. I don't know anything about C#, but I'll assume I can lump it into the C++/Java camp. Python on the other hand, carries the type information along with the data, not with the variable (container) that holds the data. Neither C++ nor Python will let you add the integer 3 to the string "four", but use different mechanisms to prevent it. Oddly enough, Java (in a perl-like, but admittedly convenient, stab at automagic polymorphism) will let you add them. No clue what C# does. Which is type safe and which isn't? Well, I think we're back to my first statement, otherwise we quickly get into playing three blind men and the elephant. From michael at foord.net Fri Mar 26 03:49:50 2004 From: michael at foord.net (Fuzzyman) Date: 26 Mar 2004 00:49:50 -0800 Subject: Regular Expression AND mach References: <8089854e.0403220021.db39215@posting.google.com> Message-ID: <8089854e.0403260049.454a1d4d@posting.google.com> "Greg Ewing (using news.cis.dfn.de)" wrote in message news:... > Fuzzyman wrote: > > So I'm currently just searching for > > the longest word - KirbBase then returns the full *text* of each song > > containing that word... and I'm just checking each song to see if it > > has the other words :-) > > If you need to do a lot of searches of this kind, you might > find it worthwhile to build an index indicating which songs > each word occurs in. Hmmmm...... possibly. It seems a shame to store a database with all the songs in *and* build a full index. For this project, the solution I have is fine. I may well need to look at an indexer for another one soon though. Thanks. Regards, Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html From rmunn at pobox.com Tue Mar 23 16:55:00 2004 From: rmunn at pobox.com (Robin Munn) Date: Tue, 23 Mar 2004 21:55:00 GMT Subject: Need advice on choosing skills. References: Message-ID: Randall Smith wrote: > Funny you said that. > > I chose Postgresql about a year ago to use at work for several projects > and have never looked back. > > I started working with wxPython about 2 months ago and like it for the > same reasons. > > I built a website using Webware. > > I'm looking for a solution for tying together PHP to a python backend. > xmlrpc, soap , corba maybe. Might twisted be good for this? > > Thanks. > > Randall I believe it would be. I'm only at the early learning & experimenting stage of learning Twisted, so I can't comment in depth, but here's their howto for doing XML-RPC and/or SOAP in Twisted, and the code looks nice and simple: http://www.twistedmatrix.com/documents/current/howto/xmlrpc -- Robin Munn rmunn at pobox.com From qp at al.net Sun Mar 14 22:29:08 2004 From: qp at al.net (Qp) Date: Sun, 14 Mar 2004 22:29:08 -0500 Subject: Seeking advice on GUI code architecture Message-ID: Hi, I've got a generic coding architecture question about an application I'm developing. Given that I've never developed anything quite like this before (especially not in Python), I'd appreciate any pointers that you can give me. The app is a network client written using Twisted and Tkinter. The clients will connect to a server, communicate via public & private chat, and also play simple games. My problem is this: how do you keep your GUI code seperate from as much underlying code as possible? As I begin, I find myself adding a lot of intermediate code (not Tkinter, but not Twisted either) to the GUI class, and it's beginning to clutter things up. It really seems as if I should have a GUI class, a network class, and some separate way of communicating between them... but I can't seem to visualize the structure in my mind. If anyone has tips, docs, or examples, I would greatly appreciate it. Thanks a lot. From rajarshi at presidency.com Sat Mar 6 14:42:54 2004 From: rajarshi at presidency.com (Rajarshi Guha) Date: Sat, 06 Mar 2004 14:42:54 -0500 Subject: generating points on a grid - efficiently References: <404a1c35_2@mk-nntp-1.news.uk.worldonline.com> Message-ID: On Sat, 06 Mar 2004 18:44:47 +0000, simon place wrote: > Rajarshi Guha wrote: >> Hi, >> I've written some code that takes a N lists of numbers (corresponding to >> axes) and generates a list of grid points (N dimensional grid) for the >> supplied axes. So as an example say my two axes are defined as >> >> v1 = [1,2,3] >> v2 = [1,2,3] >> >> My code will return to me a list of points: >> >> (1,1), (1,2), (1,3) ....(3,1), (3,2), (3,3) >> > > [[a,b] for a in v1 for b in v2] > > >> and so on. For 3 axes, I would obtain 27 points and so on. >> I've included the code below. > > > [[a,b,c] for a in v1 for b in v2 for c in v3] > Thanks very much - it speeded it up significantly From steve at ninereeds.fsnet.co.uk Mon Mar 22 14:40:11 2004 From: steve at ninereeds.fsnet.co.uk (Stephen Horne) Date: Mon, 22 Mar 2004 19:40:11 +0000 Subject: PEP 318 References: Message-ID: On 22 Mar 2004 11:25:01 -0800, artur_spruce at yahoo.com (AdSR) wrote: >Just done a quick check: > >$ find /lib/python2.3/ -name "*.py" -exec egrep >"(class|static)method\W" {} ';' | wc --lines > 49 > >Not all of them are calls, and all this in 773 *.py files. I guess >this says something about importance... Actually, given that support for staticmethod and classmethod is very recent, it is rather surprising that it appears in that many places. I wouldn't expect existing libraries to be updated just to make use of 'staticmethod' or whatever. New features mainly get used in new code, and even then there is the drag factor as people take time to adopt them. -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From roy at panix.com Sun Mar 7 15:49:07 2004 From: roy at panix.com (Roy Smith) Date: Sun, 07 Mar 2004 15:49:07 -0500 Subject: Working around a lack of 'goto' in python References: <9gpm405d952ooq37bmeilacks37o4on086@4ax.com> <71tm409egnua4ncic1siadnk7fi9rqnp8e@4ax.com> Message-ID: Stephen Horne wrote: >> goto allows the code for a state to be fallen into from the top. > > How is this different to the more typical switch-within-loop method? Not much. The C switch statement isn't much better than a goto, for just that reason :-) > returning a function pointer to a > function that is immediately going to call that function pointer, > you're basically just faking the effect of a goto anyway. 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. To tie this in with the current thread on unit testing, it's also a lot easier to test a bunch of little functions than a collection of gotos. You said: > In fact its basically a special case of the state variable method, > using the processors IP as the state variable. That's a very good observation. Imagine you implemented your state machine with gotos. To test each transition, you need to get the machine into the right state before each test by feeding it a sequence of inputs which navigates your state graph in the right way. That's complicated and error prone to design (the last thing you want is an error-prone test procedure). If there were many states and edges, it would be very slow. If the state machine is non-deterministic (timing dependencies, perhaps), it would be impossible. Of course, this is all assuming that the logic implemented in each state is different enough to require writing individual functions. Some state machines (like those that execute compiled regular expressions) are simple enough to be table driven. With a tabular approach, you get the same testability you do with the functional approach; you can set the machine to any random state, apply a single input, and see what happens. You can't do that with gotos because the state is stored in a place that's not exposed at the language level (unless you're writing in assembler). From fumanchu at amor.org Fri Mar 26 13:31:00 2004 From: fumanchu at amor.org (Robert Brewer) Date: Fri, 26 Mar 2004 10:31:00 -0800 Subject: [Newbie]Trouble with string method Message-ID: calpolynate wrote: > "Robert Brewer" wrote in message > news:... > > I think he wanted the output to be lowercase, not just sorted > > case-insensitively (that's how I read it anyway). Try: > > > > lines = [line.lower() for line in open('unsorted', 'r')] > > lines.sort() > > sorted = open('sorted', 'w') > > sorted.writelines(lines) > > sorted.close() > > Yes Robert, > > That's what I was looking for. Sean's worked too, but it sorted > without changing uppercase to lowercase, I should have been more > detailed in what I was trying to do. > > How should I go about creating an exception for changing from upper to > lower? I.E., if the latter part of a line has a comment (#XYZ) and I > would like to keep those uppercase, what would be a good way to > implement that in with the existing code? That depends on whether you want the entire line to keep its case, or just the comment. Either way, you need to unpack the list comprehension (the first line, above) into a normal for loop: lines = [] for line in open('unsorted', 'r'): if not has_comment(line): line = line.lower() lines.append(line) lines.sort() sorted = open('sorted', 'w') sorted.writelines(lines) sorted.close() ...the above leaves lines with a comment untouched, and lowercases all other lines. I leave the definition of has_comment() to you--if you can't figure that one out, then I'm starting to smell homework, Mr. Calpoly. ;) Robert Brewer MIS Amor Ministries fumanchu at amor.org From jmeile at hotmail.com Fri Mar 19 03:44:25 2004 From: jmeile at hotmail.com (Josef Meile) Date: Fri, 19 Mar 2004 09:44:25 +0100 Subject: Hiding console window References: Message-ID: <405ab2e8$1@pfaff2.ethz.ch> If you generate the exe with py2exe, then you could do: python setup.py py2exe -v -w Where setup.py is the setup script where you specify the python imports and your program modules. (see py2exe documentation). The "-w" option was the option I was talking before. I don't know if it produces the same effect of the proposed solution by Otto. With this option, you won't see a DOS console, however, I don't know if it will hide the icon on the task bar. Try to call the script on the "Startup" menu or with the "Scheduled Tasks" of windows or perhaps you will have to do it from the registry. > In response to Peter's question, what I meant when I said hide was to hide > the console while running the program. Essentially, it would run in the > background. The application would run, but you wouldn't see any sign of it. > In response to Jorgen and Josef, unfortunately it didn't work. Here's the > code for it. It may be a little messy, but I wasn't aiming for perfection: > > import pygame > import time > > def sleep(): > #Sleep for 5 minutes > time.sleep(300) > def play(): > #Initialize pygame > pygame.init() > #Initialize mixer > pygame.mixer.init() > #Load and play sound1 > pygame.mixer.music.load('C:/sound1.mp3') > pygame.mixer.music.play() > sleep() > #Load and play hazards of retreating > pygame.mixer.music.load('C:/hazards_of_retreating.mp3') > pygame.mixer.music.play() > sleep() > #Load and play bring it on > pygame.mixer.music.load('C:/bring_it_on.mp3') > pygame.mixer.music.play() > sleep() > #Load and play freaked by flood > pygame.mixer.music.load('C:/freaked_by_flood.mp3') > pygame.mixer.music.play() > sleep() > #Load and play grunty thirst > pygame.mixer.music.load('C:/grunty_thirst.mp3') > pygame.mixer.music.play() > sleep() > #Load and play joe has lost it > pygame.mixer.music.load('C:/joe_has_lost_it.mp3') > pygame.mixer.music.play() > sleep() > #Load and play the french grunt > pygame.mixer.music.load('C:\the_french_grunt.mp3') > pygame.mixer.music.play() > sleep() > #Load and play stacker e3 outtake2 > pygame.mixer.music.load('C:\stacker_e3_outtake2.mp3') > pygame.mixer.music.play() > sleep() > #Load and play poor running anatomy > pygame.mixer.music.load('C:\poor_running_anatomy.mp3') > pygame.mixer.music.play() > sleep() > #Load and play bring it on > pygame.mixer.music.load('C:\bring_it_on.mp3') > pygame.mixer.music.play() > #Quit playing and close pygame > pygame.mixer.quit() > pygame.quit() > > #Start the program > play() > > You may raise your eyebrows at the filenames, but as I said its a joke I'm > playing. The sound clips are based off the game Halo. Just fill in your own > files instead of mine. From crap1234 at hotmail.com Thu Mar 25 06:33:57 2004 From: crap1234 at hotmail.com (Stefan Axelsson) Date: Thu, 25 Mar 2004 12:33:57 +0100 Subject: Python for large projects In-Reply-To: References: Message-ID: Jacek Generowicz wrote: > If you happen to find it, drop me a line, please. (Don't go too far > out of your way though ... my stack of interesting things I want to > read is mostly monotonically growing :-( ) I'll have a look around. I've only skimmed it, it's probably deep in one of my monotinically growing stacks. :-) > You mean "damage limitation" and enabling "primate programming" > (http://www.newtechusa.com/ppi/main.asp) ? Yes, that's the whole > purpose of Java, as far as I can see. Well, more or less yes. > Again, difference in philosophy. I assume that I am trying to write > the best product I can. Writing bad tests is not in my interest. I > acknowledge that this is probably not the case in most real-life > situations. > > Conclusion: I'm naively, romantically optimistic about what > programming is :-) No disagreement there. :-) We'll see how that changes though, now that the bubble has burst, and fewer people are drawn into CS that don't really have an interest in it. OTOH we have the outsourcing trend, that IMHO will drive programming into a race to the bottom. May you live in interesting times and all that... >>It's interesting to note that Ericsson drew the conclusion that C++ >>was to blaim for the failed billion dollar AXEn project. Of course the >>choice of language had very little to do with that. > > > But that won't deter me from quoting it to all and sundry :-) > > (Do you have a reference to this conclusion ?) Well, no. While I could probably find an old policy document that stated it (God knows there are enough of those), it would be for internal use only. Plenty of stuff on the success of Erlang though (at http://www.erlang.org) which is dynamically typed, though it's not as effective propaganda against C++. (And indicentally, Erlang was once forbidden to use for new projects within Ericsson as well, it was *one* of the things that drove the opensourcing of Erlang. That policy has been lifted. In that case it was the old "You're too successful, we need to be able to bring people in from the street to do this, we don't need no stinking experts.") Stefan, -- Stefan Axelsson (email at http://www.cs.chalmers.se/~sax) From smallbee at rediffmail.com Wed Mar 3 08:40:43 2004 From: smallbee at rediffmail.com (Somesh Bartakkay) Date: 3 Mar 2004 05:40:43 -0800 Subject: python + Xml + GnuCash Message-ID: <8f198e47.0403030540.1ccbc9e5@posting.google.com> GnuCash -- popular accounting s/w is developed with c+Gtk+XML. if i wanna develope application like gnuCash which handles flat file database :: 1.weather it is wise decision to develope in python ? which is prefered GUI from wxPython, PyGTK ? and Why ? Shall i code wxPython in FUNCTIONAL programming way(nON Object oriented) ? 2.weather i should go with XML or python's flatDB module which handles flat file databse from python for storing data. 3.how i shold encrypt/decrypt my data which is going to store in datafiles-- thru pythons..keep in mind that application performance should b fast6.. From crap1234 at hotmail.com Wed Mar 24 10:34:36 2004 From: crap1234 at hotmail.com (Stefan Axelsson) Date: Wed, 24 Mar 2004 16:34:36 +0100 Subject: sorting the list by inner elements In-Reply-To: References: Message-ID: John Hunter wrote: > The usual way is to simply reverse the tuple, sort, and then reverse > back > > tmp = [ (city, name) for name, city in name_city_list] > tmp.sort() > name_city_list = [ (name, city) for city, name in tmp] > > This is usually faster than writing a custom comparison func for sort. The notable exception being when Psyco is applied. I've actually had e.g. significantly *faster* runs when applying a custom sort function to do a 'reverse' than calling it separately after sorting. Do a run on your own data/platform to check what's faster if speed matters. If it doesn't I'd do the comparison function as I find that clearer. Stefan, -- Stefan Axelsson (email at http://www.cs.chalmers.se/~sax) From jacek.generowicz at cern.ch Tue Mar 23 09:31:47 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 23 Mar 2004 15:31:47 +0100 Subject: [OT] Compilable Python-like language? References: Message-ID: Ed Cogburn writes: > Jacek Generowicz wrote: > > That rather depends on what you mean by "Python-like". > > > Oh dear... > > It was not my intention to start this kind of debate, Debate? I think a number of us wanted to point out that your question can be interpreted in many very different ways. We also wanted you to explain a bit more about what _you_ meant by the words you used, in order to enable us to give you answers which are more useful to _you_, rather than writing pages in an attempt to answer a question which you didn't really meant to ask. (Or were you referring to the "debate" about whether such requests for clarification are appropriate? I hope that it is self-evident that they are.) > I'm not a troll, I don't think anyone suggested that you are. _I_ certainly did _not_ mean to imply that you are a troll. > I actually consider GvR to be something of a minor deity. :) Quite an unhealthy attitude, IMHO. If more people realized that GvR is just a guy who happens to have designed and implemented a rather nice language, then a some discussions around here would be more constructive that they are :-) > I was merely curious if any of you may have known about some > language currently in development, or some still-young and > little-known language that was like Python and aiming for something > like C/C++-ish performance. Great, so you've identified performance issues as a motivation for your question ... but we're still a bit hazy on the "like Python" part :-) > By compile-to-binary, I meant create a binary executable in native > machine code that does not involve an interpreter process (source or > byte-code), and any substantial run-time overhead. In other words my > concern, is as always, about speed. Are you aware that you are slighly contradicting yourself, or at least unnecessarily constraining your definition of "compile-to-binary"? (I don't mean to be condescending here, in the slightest.) My point is, if your concern really is "as always, about speed", why should you care whether you "create a binary executable"? For example, if the PyPy project is wildly successful, then the day will come (I'm optimistically hoping for this to happen before the next C++ standard comes out :-) when Python itself will compile to native binary, run faster than C ... all that, I suspect, without creating an "executable binary". And you couldn't ask for a more Python-like language than Python itself ... or could you ? > Concerning Perl/Lisp. I'm using Python because it is *nothing* like > those two. :) Funny. Here's someone who thinks that Python is rather similar to Lisp: In http://paulgraham.com/lispfaq1.html Paul Graham writes: PG> I like Lisp but my company won't let me use it. What should I do? PG> PG> Try to get them to let you use Python. [...] semantically PG> [Python] has a lot in common with Lisp, and has been getting PG> closer to Lisp over time. (Cue PP: "No it isn't", etc. etc.) Are you sure that you are using Python because it is *nothing* like Lisp? I bet that if you removed all Python's similarities to Lisp from the language, then you wouldn't give the language a second look. > Lisp has good performance, and is a compilable language, I'm aware > of that, but I just can't handle all the parentheses. To the > individual in the other thread who said people complaining about all > the parentheses in Lisp are being ludicrous, well, just consider > yourself lucky or superior that you can look at Lisp code for more > than 30 minutes without getting a headache. :) The point is that, if you spend more than 30 minutes looking at Lisp code without an attitude of "paretheses suck", then you will almost certainly cease to have any inclination to develop a headache. If you, subsequently, actually try to edit some Lisp code, then you will discover that the parentheses are actually help considerably. The problem most people have is to look at Lisp code without prejudice for those first 30 minutes. That's the hurdle where most people fall over. Still, you might like to take a look at Dylan. It is, essentially, a Lisp without parentheses. From lilyth at umich.edu Fri Mar 19 10:55:23 2004 From: lilyth at umich.edu (Lilith) Date: 19 Mar 2004 07:55:23 -0800 Subject: Graph Problems (was Re: Is there a map or graph module?) References: <75200cbc.0403181507.350feeb7@posting.google.com> Message-ID: <75200cbc.0403190755.5765890a@posting.google.com> Josiah Carlson wrote in message news:... > Lilith wrote: > > Is there a python module somewhere (been searching today, no luck) > > which has efficiently coded various graph-handling routines, such as > > finding the shortest path through a graph, or the set of all paths > > through a graph? I'm not a compsci-educated person, so coding my own > > would be less parsimonious. > > Thanks for any suggestions! > > Thank Guido, http://www.python.org/doc/essays/graphs.html That's not working for me. I should have mentioned I tried that, but I get a slew of these errors: > File "guidograph.py", line 40, in find_all_paths > newpaths = find_all_paths(graph, node, end, path) > RuntimeError: maximum recursion depth exceeded Guido's example works fine when I use his simple graph. When I plug in my 9000-node graph, I get those problems even if the nodes are a few steps away. I think my network is too big for that code. I imagine there's some kind of recursion limit I can set somewhere, but it's probably a problem in that the code can't handle larger graphs. Not only does find_all_paths crash, but so does find_path. From premshree_python at yahoo.co.in Sat Mar 13 09:55:08 2004 From: premshree_python at yahoo.co.in (=?iso-8859-1?q?Premshree=20Pillai?=) Date: Sat, 13 Mar 2004 14:55:08 +0000 (GMT) Subject: Static Typing in Python In-Reply-To: Message-ID: <20040313145508.28591.qmail@web8304.mail.in.yahoo.com> --- Terry Reedy wrote: > > "Premshree Pillai" > wrote in message > > Anyway, what I want is to force variable > declaration. > > In perl we have the "use strict vars" pargma...I > need > > something like that... > > For those of us who do not know Perl, and there are > many, I suspect, on > this Python newsgroup, that means nothing ;-). > > tjr > > > > > -- > http://mail.python.org/mailman/listinfo/python-list Yes. Let me explain. Perl's "strict" pragma makes sure that you have declared (initialized) a variable before using it. Nothing more to it. ===== -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 kkto at csis.hku.hk Wed Mar 10 00:16:12 2004 From: kkto at csis.hku.hk (Isaac To) Date: Wed, 10 Mar 2004 13:16:12 +0800 Subject: Working around a lack of 'goto' in python References: <5sbs40l90vpumpp3u72a4259gp83j4mfih@4ax.com> Message-ID: <7ihdwx8eoz.fsf@enark.csis.hku.hk> >>>>> "Stephen" == Stephen Horne writes: Stephen> As a rule, having a program that runs a few milliseconds slower Stephen> is preferable to having a maintenance headache. The reason why Stephen> gotos, breaks and continues are considered bad style in any Stephen> language is because when used inappropriately they routinely do Stephen> create maintenance headaches, and because the temptation is to Stephen> use them inappropriately. Everything said above is true for most programming constructs. You can put "local variables", "global variables", "dynamic scoping", "functions", "classes", "exceptions", "checked exceptions", etc., into the above paragraph, and the paragraph still "make sense". The worth of a programming construct is how *good* it is when it is used *appropriately*, not how *bad* it is when it is used *inappropriately*. Stephen> As I mentioned elsewhere, I have used gotos recently but only Stephen> once in ten years or so. I have no doubt that there are many Stephen> simpler cases where at some time I could have avoided a state Stephen> variable or an exception by using a goto, but following a Stephen> standard convention has some value in itself and these days the Stephen> standard convention is to use a state variable or an exception. One can likewise use goto in a "standard convention", and indeed that is what I always do: just like any other person, I fully acknowledge that goto is horrible when used inappropriately. But the same can be said to, say, classes. Stephen> These are relatively unusual cases, though. Certainly they pop Stephen> up from time to time, but in the mean time you've probably Stephen> written tens of loops that didn't need these tricks. Most people *fear* goto. They think that "if I use goto, my program is unclean". Or "if I use goto now, my program won't be readable tomorrow". Or simply, "my manager is going to blame me the moment I show my program to him just because I use goto". But even though we are under such climate, once in a while we find that goto actually clean up mess. I think this alone means that we should look at the construct again to see whether we are too critical to it from the beginning. Of course, this is from the user's point of view. From the implementation point of view, that can be another story: one won't want constructs that are too expensive to implement. Unconditional jump will remove some optimization opportunities. But it is "paid only by those who use it", so I think it is a fair deal. Regards, Isaac. From eric at zomething.com Mon Mar 8 03:46:30 2004 From: eric at zomething.com (Eric @ Zomething) Date: Mon, 8 Mar 2004 00:46:30 -0800 Subject: Gadfly or gadfly or Gadfly.gadfly() or _? Message-ID: <20040308004630.1096705640.eric@zomething.com> My interest was piqued enough to try Gadfly, but I find myself struggling to install it, a new problem for this newB. Not sure if any of this is the distribution's "fault" or just my lack of understanding of Python: 1) I notice there is no py file named "gadfly.py". How does Python find and define the namespace? 2) I have installed the files in this directory under a Windows XP OS: C:\Python23\Lib\site-packages\Gadfly 3) "import gadfly", as shown in the docs, returns an ImportError 4) "import Gadfly" does not return any errors. Is this because of the capitalization of the directory name? then, following the instructions in the docs: >>> connection = gadfly.gadfly() Traceback (most recent call last): File "", line 1, in ? connection = gadfly.gadfly() NameError: name 'gadfly' is not defined >>> connection=Gadfly.gadfly() Traceback (most recent call last): File "", line 1, in ? connection=Gadfly.gadfly() TypeError: 'module' object is not callable Have I somehow mucked up the namespace upon installation? Am I entering the wrong commands? Any pointers appreciated. Eric From claird at lairds.com Thu Mar 11 07:55:20 2004 From: claird at lairds.com (Cameron Laird) Date: Thu, 11 Mar 2004 12:55:20 -0000 Subject: Extending Python Syntax with @ References: <104vtblamboehab@corp.supernews.com> <2f9050pq22u53o7aqo9i8ebqj11vo9kilg@4ax.com> Message-ID: <1050odofl644aac@corp.supernews.com> In article <2f9050pq22u53o7aqo9i8ebqj11vo9kilg at 4ax.com>, David MacQuigg wrote: . . . >going to help me write some code, I won't have time to study it. My >understanding of lambda functions is simply that they are a way to >squeeze functions into a tight space: > >list_of_funcs = [(lambda x: 2**x), (lambda x: 3**x), (lambda x: 4**x)] > >If you are not concerned about space, simply use normal defs: > >def f2(x): return 2**x >def f3(x): return 3**x >def f4(x): return 4**x >list_of_funcs = [f2, f3, f4] > >Is there any other reason in Python to use lambdas? . . . In fact, *that*'s not a reason. Part of tribal lore--a true, documented part, by the way--is that Big Cheese Guido depre- cates lambdas. He says they're a mistake, and people shouldn't be using 'em. Whenever you feel like a lambda, define a named function; it forces the developer to come up with a name for the operation, and that's likely to make the code more read- able (I'm slightly abbreviating the argument here). Space, in the sense you're using it above, should NOT concern Pythoneers. Correctness and clarity of express should. It pains my sensitivities every time you claim lambdas are just a way of making functions "small". Again, I understand how natural that is from your background. Around this mathematician, 'twould be less distracting to run your finger- nails down a chalkboard. I think this ties back to your broader original propositions: the Python aesthetic assesses little merit for the brevity of @-anything, and much for the presumed evocativeness of "yield". An abundance of *good* keywords is a good thing. That's definitely not the attitude of all languages. -- Cameron Laird Business: http://www.Phaseit.net From peter at engcorp.com Sat Mar 20 17:36:55 2004 From: peter at engcorp.com (Peter Hansen) Date: Sat, 20 Mar 2004 17:36:55 -0500 Subject: Help getting the md5 module to work In-Reply-To: <8z07c.21193$Bg.9311@fed1read03> References: <7x1xnodjx2.fsf@ruckus.brouhaha.com> <405BFC92.E1C8C186@alcyone.com> <8z07c.21193$Bg.9311@fed1read03> Message-ID: <7fadnUgM0Z8VWsHd4p2dnA@powergate.ca> Amy G wrote: > "Erik Max Francis" wrote in message > news:405BFC92.E1C8C186 at alcyone.com... > >>Paul Rubin wrote: >> >> >>>Try n.update("help\n"). >> >>Right. For Amy: You can suppress the newline on echo with the -n >>option, by the way: >> > > I discovered this last night. > > But what is the true MD5 hash for help? With or without the newline? You already had the right hashes for both! Your Python attempt did not include a newline, while the shell approach with "echo" did, so you were comparing apples and oranges. Paul and Erik gave you the solutions to switch either approach to do what the other does... -Peter From raims at dot.com Wed Mar 10 04:33:50 2004 From: raims at dot.com (Lawrence Oluyede) Date: Wed, 10 Mar 2004 10:33:50 +0100 Subject: [OT] C unit testing suite References: Message-ID: <1sgcf5ztxai6k$.14jk2fldxnae8$.dlg@40tude.net> In data Wed, 10 Mar 2004 10:54:53 +0200, Miki Tebeka ha scritto: > I'm looking for a good C unit testing suite. > Any recommendations? Try to look here: http://www.xprogramming.com/software.htm -- Lawrence "ain't nothin' but fun." From jnoller at reference-info.com Tue Mar 23 12:09:24 2004 From: jnoller at reference-info.com (Jesse Noller) Date: 23 Mar 2004 09:09:24 -0800 Subject: Beginner Threaded file reading access Message-ID: <2835a96b.0403230909.35be2b7b@posting.google.com> 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 - I have a definable variable that will determine how many threads are going, but for now let's choose 5. With 5 threads - I need each of the 5 threads to read 1 line from the file (but never the same line) and perform the processing. I never want the thread count to exceed the 5 threads defined. Now, I am trying to figure how to do this, and I've been pointed in the direction of syncronization of the access to the readlines() function in between threads. Does anyone have any pointers, or good beginner tutorials on how to approach this? -jesse From halloleo at nospam.myrealbox.com Tue Mar 2 07:55:00 2004 From: halloleo at nospam.myrealbox.com (leo) Date: Tue, 02 Mar 2004 23:55:00 +1100 Subject: how to get EXIF data from a jpg Message-ID: hi there how can i get in python EXIF data (particularky the shouuting time) of a jpg? is there a special module around? thanks, leo From chris.gonnerman at newcenturycomputers.net Wed Mar 3 23:59:15 2004 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Wed, 03 Mar 2004 22:59:15 -0600 Subject: [ANN] Alternative Readline 1.6 (for Python 2.3 and higher) released Message-ID: <4046B7A3.7040400@newcenturycomputers.net> I am happy to finally announce the release of a corrected version of my Alternative Readline for Python. This new version 1.6 has the prompt bug fixed thanks to Andre Alves. WHAT IS IT? The Alternative Readline for Python provides basic command-line recall and editing for Python on Win32 platforms. While Python 2.3 contains this functionality for newer platforms, making my "alternative" version obsolete, older platforms such as Windows 98 and Me may still need this module. WHERE IS IT? You can get the source archive and/or the Python 2.3 installer from my website: http://newcenturycomputers.net/projects/readline.html Thanks again to Andre Alves for taking the time to find this bug! -- Chris. From Kyler at news.Lairds.org Sat Mar 27 14:08:00 2004 From: Kyler at news.Lairds.org (Kyler Laird) Date: Sat, 27 Mar 2004 19:08:00 GMT Subject: Python for email? References: <106b6ivetpf0bc0@corp.supernews.com> Message-ID: claird at lairds.com (Cameron Laird) writes: >smtplib presents a few other, even more marginal issues. If an >installed MTA enforces institutional standards (disclaimers, archi- >ving, ...), smtplib is likely to subvert those. How so? The example for smtplib given here http://www.python.org/doc/current/lib/SMTP-example.html appears to relay mail through "localhost". That will typically be equivalent to using the "installed MTA", right? --kyler From ruud.de.jong at consunet.nl Fri Mar 19 07:47:26 2004 From: ruud.de.jong at consunet.nl (Ruud de Jong) Date: Fri, 19 Mar 2004 13:47:26 +0100 Subject: Basic Inheritance Question In-Reply-To: References: Message-ID: <405aeb3c$0$41757$5fc3050@dreader2.news.tiscali.nl> Matthew Bell schreef: > I've got a conceptual problem to do with inheritance. > I'd be grateful if someone could help to clear up my > confusion. > > An example. Say I need a class that's basically a > list, with all the normal list methods, but I want a > custom __init__ so that the list that is created is > [1,2,3] rather than [] (yes, it's a bogus example, > but it does to make the point). Without bothering > with inheritance, I could do: > > class mysimplelistclass: > def __init__(self): > self.internallist = [1, 2, 3] > > This would work but I would, of course, need to define > methods in "mysimpleclass" to deal with all the various > methods that the original list class provides. > > Obviously, the thing to do is to inherit from the list > class, override the __init__ method and leave the rest > of the normal list class's methods untouched. So I'd > write something like: > > class myinheritedlistclass(list): > def __init__(self): > > > It's at this point I get confused. Obviously, I don't > use the "self.internallist = [1, 2, 3]" bit as before > because I'd then need to override all of the rest of > the normal list methods to get them to act on > self.internallist. > > Conceptually, I suppose I need something like: > > = superclass.self.__init__([1, 2, 3)] > > but that is, of course, totally ridiculous. > > Essentially, then, if I've inherited another class, how > do I create an instance of the class I've inherited such > that methods I haven't overrriden will still work, and > how can I then refer to that instance from my subclass? > I can guess it's something to do with "self" but exactly > what, I'm really at a loss. > > Any assistance in my confusion would be gratefully received! > > Regards, > Matthew. > > You were nearly there. You don't need a ; __init__ does not return anything. Just initialize the baseclass with the things you want: >>> class myList(list): def __init__(self): list.__init__(self, [1,2,3]) >>> m = myList() >>> m [1, 2, 3] >>> Regards, Ruud From slackgg at 163.com Wed Mar 3 21:30:23 2004 From: slackgg at 163.com (slackgg at 163.com) Date: 3 Mar 2004 18:30:23 -0800 Subject: I can't use cx_Oracle..help me. Message-ID: hello all: i import cx_Oracle modules will show "Traceback (most recent call l File "", line 1, in ImportError: DLL load failed: can't find ..." From michael at foord.net Fri Mar 5 07:32:37 2004 From: michael at foord.net (Fuzzyman) Date: 5 Mar 2004 04:32:37 -0800 Subject: Gadfly ???? References: <8089854e.0403040124.1c6bd929@posting.google.com> Message-ID: <8089854e.0403050432.6cedbe99@posting.google.com> Gerhard H?ring wrote in message news:... > Fuzzyman wrote: > > [problems finding Gadfly binaries] > > Alternatively, you could try PySQLite. It's also an embedded database engine in a > Python module. And it offers binaries for win32. > > -- Gerhard (PySQLite developer) Thanks. In actual fact I'm looking for a pure python solution. I want to be able to upload python modules to our server without having to worry about installing/compiling binaries on our Linux server. I also need to be able to test on my Windoze desktop. In various references to Gadfly it was refferred to as a 'pure python' solution... and then the distribution comes with a C file and pre-built binaries for python up to version 2.2... but not 2.3. Odd that no-one seems to know anything about Gadfly - which was even touted for inclusion in the main python distribution. Regards, Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html From Roberto at lupi.an.it Tue Mar 30 04:17:29 2004 From: Roberto at lupi.an.it (Roberto Lupi) Date: Tue, 30 Mar 2004 09:17:29 GMT Subject: Prothon, metaclasses, Zope [Was: A 'Python like' language] References: <95aa1afa.0403272243.78d60724@posting.google.com> Message-ID: In article <95aa1afa.0403272243.78d60724 at posting.google.com>, > So, I reverted my mind to the pre-metaclass functioning mode (which required > a certain effort) and I wrote a function that takes a class, looks at > its dictionary, and raises an error if the class overrides an attribute > which is already defined in the parent classes. The solution works, > but it is kind of ugly compared to the metaclass solution: > > 1. The metaclass can raise the error *before* the metaclass is created, > whereas the function works a posteriori, *after* the overriding is done; > if find it to be conceptually unsatisfactory, I don't want to create > a class just to throw it away. The alternative is to use a class factory, > but then I have just re-invented a metaclass with an ugly call syntax. I would add the check to a test case for the class. class XYZTestCase(ZopeTestCase): tested_class = XYZ def testOverriddenMethods(self): check_if_we_are_overriding_names_in(self.tested_class) > 2. The metaclass can be inherited, so the check is automatic for all children; > on the contrary, I have to call the function by hand each time I define > a new class. This means writing twice the class name, which is error > prone if I later rename the class and I forget to update the function > call. Test cases can be inherited. class XYZ2TestCase(XYZTestCase): tested_class = XYZ2 -- Roberto Lupi From jason at tishler.net Wed Mar 10 16:44:08 2004 From: jason at tishler.net (Jason Tishler) Date: Wed, 10 Mar 2004 16:44:08 -0500 Subject: os.popen() failing under ipython+cygwin, I'm stumped. In-Reply-To: <73iopmskzdhx$.dlg@thorstenkampe.de> References: <12dq1z2aca4l2.dlg@thorstenkampe.de> <73iopmskzdhx$.dlg@thorstenkampe.de> Message-ID: <20040310214407.GB1904@tishler.net> Thorsten, On Tue, Mar 09, 2004 at 11:30:48PM +0100, Thorsten Kampe wrote: > * Jason Tishler (2004-03-09 21:18 +0100) > > Can you be more specific? We cannot address issues if we do not > > know what they are. > > I wasn't specific on purpose because this is a Cygwin issue and might > not interest the Python folks. Understood, so I will try to answer briefly -- please move this to the Cygwin list if you would like to continue this discussion. BTW, hanging innuendos are not good for archive searchers... > The readme written by this JT guy states: Who is this JT guy? Oh, that's me! :.) > ,--- > | > | Note it is *strongly* recommended that users only use rebaseall > | unless they *really* know what they are doing or are instructed by > | one of the Cygwin developers. > | > `--- The above warning is about rebase *not* rebaseall. > I tried 'rebaseall' and it broke at least zsh The zsh rebase issue has been resolved (i.e., at least worked around): http://cygwin.com/ml/cygwin-announce/2004-02/msg00021.html > and sshd I rebase my system *and* run sshd all the time. I have never noticed any sshd rebase problems. > - and these were just the two I noticed immediately. Reemerging zsh > helped and reemerging openssh would have helped probably, too. But the > whole rebase might have broken dozens of other Cygwin apps and when I > use those in a few days and they segfault I might not guess that it > was the rebaseall and that I just have to reemerge them. Since I have contributed Cygwin rebase, there have been relatively few problems: Windows Me support (due to MS's broken imagehlp.dll on that platform) stripped executable support (only under certain conditions) zsh AFAICT, all of them have been addressed. IMO, implying rebase can break dozens of apps seems unwarranted. > So I modified the script that just the file list was written to a file > and I deleted all the non Python dlls in the list. It helped with > IPython but not with idle. Probably because idle uses Tcl DLLs too. > On the other hand I still have a working Cygwin installation (because > I tried the "rebaseall" on a copy) - and this is more worth than a > working idle but a broken Cygwin environment. Like I said before, we can't address problems that we don't know exist. BTW, you can always save a copy of your DLLs (e.g., tar up) before rebasing... Jason -- PGP/GPG Key: http://www.tishler.net/jason/pubkey.asc or key servers Fingerprint: 7A73 1405 7F2B E669 C19D 8784 1AFD E4CC ECF4 8EF6 From rtrocca at inwind.it Mon Mar 15 08:30:40 2004 From: rtrocca at inwind.it (Riccardo) Date: 15 Mar 2004 05:30:40 -0800 Subject: Problems wrapping FreeImage with SWIG on win32 Message-ID: <8b4118ee.0403150530.3b0df08e@posting.google.com> Hello, I'm trying to wrap FreeImage (freeimage.sf.net) through SWIG in Python on Win32. I'm using VC6sp5. I've tried both using the static library and the dynamic one, having the same kind of problems: missing symbols. I describe you the sequence: I create a swig file like this one: %module freeimage %{ #include "FreeImage.h" %} const char *FreeImage_GetVersion(); const char *FreeImage_GetCopyrightMessage(); then I create the source file with: swig -python -c++ -o pyFreeImage.cpp FreeImage.i The setup.py file is: setup(name="pyFreeImage", version="0.0", description="wrapper to FreeImage", #packages=[''], ext_modules=[Extension("_freeimage", ["pyFreeImage.cpp"], libraries=["FreeImage"])] ) So far so good. When I launch the build the file compiles well but I've problems during the link phase: C:\Programmi\Microsoft Visual Studio\VC98\BIN\link.exe /DLL /nologo /INCREMENTAL:NO /LIBPATH:C:\Python23\libs /LIBPATH:C:\Python23\PCBuild FreeImage.lib /EXPORT:init_freeimage build\temp.win32-2.3\Release\pyFreeImage.obj /OUT:build\lib.win32-2.3\_freeimage.pyd /IMPLIB:build\temp.win32-2.3\Release\_freeimage.lib Creating library build\temp.win32-2.3\Release\_freeimage.lib and object build\temp.win32-2.3\Release\_freeimage.exp pyFreeImage.obj : error LNK2001: unresolved external symbol _FreeImage_GetVersion pyFreeImage.obj : error LNK2001: unresolved external symbol _FreeImage_GetCopyrightMessage build\lib.win32-2.3\_freeimage.pyd : fatal error LNK1120: 2 unresolved externals error: command '"C:\Programmi\Microsoft Visual Studio\VC98\BIN\link.exe"' failed with exit status 1120 Given that VC finds the library (I use it in an application of mine and it compiles well), and that the lib is the latest one, pre-compiled, as found on sf.net, what am I missing? THanks for the help. Riccardo From tismer at stackless.com Mon Mar 29 20:52:19 2004 From: tismer at stackless.com (Christian Tismer) Date: Tue, 30 Mar 2004 03:52:19 +0200 Subject: Orders of magnitude In-Reply-To: <66a61715.0403291539.7e1346c7@posting.google.com> References: <66a61715.0403291539.7e1346c7@posting.google.com> Message-ID: <4068D2D3.4020009@stackless.com> Buck Nuggets wrote: > "Robert Brewer" wrote in message news:... > >>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? > > > In case you are interested in alternatives approaches...here's how I > typically do this: > > 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 Good solution, but wayyyy too much effort. You probably know it: If you are seeking for duplicates, and doing it by complete ordering, then you are thwowing lots of information away, since you are not seeking for neighborship, right? That clearly means: it must be inefficient. No offense, just trying to get you on the right track! 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 patois at calvix.org Fri Mar 19 17:26:33 2004 From: patois at calvix.org (Yannick Patois) Date: Fri, 19 Mar 2004 23:26:33 +0100 Subject: Package name with '.' in them: Python Bug ? In-Reply-To: References: Message-ID: Terry Reedy wrote: > "Yannick Patois" wrote in message > To restate: if I were to investigate further, I would add prints > statements, since that has so far worked well for me with Python. What you > do is up to you. 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. 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 cookedm+news at physics.mcmaster.ca Thu Mar 11 16:58:31 2004 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Thu, 11 Mar 2004 16:58:31 -0500 Subject: Python database References: <4050647e$1@puffinus.its.uu.se> Message-ID: At some point, "@(none)" <""daniel\"@(none)"> wrote: > Facts: > > (1) I don't know anything about data bases > > (2) I don't have much time to learn about them (but I do have SOME time) > > (3) I need to store (and retrieve) thousands of pages for a wiki, and > need to be able to perform simple searches in the data base (but > nothing else) > > (4) I want to have open source free of charge programs The original Wiki at http://c2.com/cgi/wiki uses the filesystem as its database (see http://c2.com/cgi/wiki?MoreAboutTheDatabase). You can get ideas by looking at what other people have done at http://c2.com/cgi/wiki?WikiWikiClones There's a small Wiki clone in Python at http://sourcefrog.net/projects/piki/ which MoinMoin is based on. It's filesystem based also. I use a custom version of this for my personal use. You don't need much of a database. You can probably get away with one-page-per-file, maybe with an external indexer (like Lupy?). Have a look at the speed of the original wiki; a full-text search of 26738 pages takes a few seconds -- and it's a cgi script. > Can someone recommend a simple, easy-to-program data base? As far as I > have understood there is no standard data base in Python. Why is this > so? Do people have too different needs? There are database modules in the standard Python distribution, just not relational databases. Look at the anydbm, gdbm, and shelve modules. Also look at the bsddb module, which is a wrapper around the Berkeley DB library. The TCL wiki (http://wiki.tcl.tk/) uses Metakit, which is another non-relational database (although not included with Python), for which there are Python wrappers. -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From paxcalpt at sapo.pt Mon Mar 1 01:50:42 2004 From: paxcalpt at sapo.pt (Paxcal) Date: Mon, 1 Mar 2004 06:50:42 -0000 Subject: IDLE on Windows; save files as UNIX? References: Message-ID: <4042dc05$0$28143$a729d347@news.telepac.pt> You can use the UNIX (also in cygwin) command dos2unix and unix2dos command to do the convertion... Regards Paxcal "Jay O'Connor" escreveu na mensagem news:lvo0c.15119$aT1.1581 at newsread1.news.pas.earthlink.net... > I'm doing some Python CGI programming under Windows (Win95) but my CGIs need to > run on Linux. If I try to write and save the files in IDLE, they get saved in > DOS format and won't run on the Linux server. If I load the files into another > text editor and explictely "Save As" in UNIX format, they work fine, but the > other editor is not Python aware so I'd rather not have to use if for main > development, and having to load and resave my scripts before uploading to the > server is a bit obnoxious. > > Is there any way to for IDLE in Windows to save files in UNIX format? > > Note: Pythonwin does not work on my machine so I can't use it as an alternative > > Thanks > From charleshixsn at earthlink.net Mon Mar 29 22:55:22 2004 From: charleshixsn at earthlink.net (Charles Hixson) Date: Mon, 29 Mar 2004 19:55:22 -0800 Subject: Prothon Prototypes vs Python Classes In-Reply-To: <40675F08.9070402@mlug.missouri.edu> 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> Message-ID: <4068EFAA.8060309@earthlink.net> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Michael wrote: | They're planning to remove tab indention support in 3.0? I for one | would be pissed off at such a change. I don't mind people using | spaces if they like but I see no reason I shouldn't be able to use | tabs if I like. I can't see how it should make any difference to | Python which you use so why not allow for personal preference? | |> I'll just mention that there are ***very good***, that is |> ***extremely good*** reasons why the Python standard is to use |> spaces for indentation, and why the option of using tabs will be |> removed in 3.0. |> They can't possibly be good enough (for my needs). That said, where can I check this. I don't want to make important decisions on incomplete information. -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.4 (GNU/Linux) Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org iD8DBQFAaO9xE1guSVL8NK8RAuZCAJ9k2jZSLxwG6Ql3rHqV8u5APcuPJgCghjjo AW0ROHktFKNbSKSWYn1q9BM= =AR/9 -----END PGP SIGNATURE----- From no at sp.am Fri Mar 26 14:41:24 2004 From: no at sp.am (DH) Date: Fri, 26 Mar 2004 13:41:24 -0600 Subject: A 'Python like' language In-Reply-To: References: <40645d8f$0$10775$afc38c87@news.easynet.co.uk> <1068up4kn49778@news.supernews.com> Message-ID: <9dCdnezNbpH4GvndRVn-hw@comcast.com> > Anyway GvR just posted on the python-dev saying this: > > == > No, I want to reserve the leading dot for attribute assignment to a > special object specified by a 'with' statement, e.g. > > with self: > .foo = [1, 2, 3] > .bar(4, .foo) brilliant! > this is in VB so neither of us can claim to have invented it. :-) oh wait, this sucks :) > (And "with" was in Pascal 30+ years ago, without the leading dot.) lemme ask my grandfather for his opinion From theller at python.net Mon Mar 8 15:03:39 2004 From: theller at python.net (Thomas Heller) Date: Mon, 08 Mar 2004 21:03:39 +0100 Subject: wrapping C++, how to wrap an object? References: <404aff25$0$3954$afc38c87@news.optusnet.com.au> Message-ID: >> AFAIK, you have 2 mainstream choices for wrapping C++: >> 1. Boost.Python - http://www.boost.org/libs/python/doc/ >> 2. SWIG - http://www.swig.org/ >> >> I'm also aware of: >> 3. SIP - http://www.riverbankcomputing.co.uk/sip/docs/sipref.html >> >> I use Boost.Python and have found it to be excellent. >> > Hi, > > thanks for that hint. > > But is there no way to do this in plain python? > > I don't really want to use any additional libraries, > as i want to use this code in the office and license > problems are always a big problem there. > > Can i somehow wrap a C++ object in a python data type > just without any additional libraries? Is PyCObject what you need? Depends on what you mean by 'wrap'... Thomas From deetsNOSPAM at web.de Mon Mar 22 19:18:09 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Tue, 23 Mar 2004 01:18:09 +0100 Subject: Python for large projects References: <7xisgxt51r.fsf@ruckus.brouhaha.com> <105uk4987h7tm77@corp.supernews.com> <7xad28313c.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > 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 Which, if any, would you write in JAVA or C#? I think for a project in "userland" thats not on the number crunching or machine architecture side like a kernel2, python often would be a viable alternative. And the spaceshuttle runs on a 68K processor - I bet a modern 3GHz processor running python can beat that :) -- Regards, Diez B. Roggisch From __peter__ at web.de Fri Mar 12 16:15:08 2004 From: __peter__ at web.de (Peter Otten) Date: Fri, 12 Mar 2004 22:15:08 +0100 Subject: Optparse: Detecting if option or option-arg is specified or not References: Message-ID: Sam Smith wrote: > Usage Scenario: > > I am implementing a multi-level commandline program. On windows > platform similar to "net /?" command which in turn has "net use /?", > "net computer /?" etc commandlines. > > Some of my commandlines share the same option-arg, but the default > value to be associated with each of them is different. In one of the > commandlines I was trying to detect if the user has specified the > option or not and if not assign a different value to the option. I normally don't advocate code duplication, but in this case I'd either specialcase if specialcommandline: parser.add_option(special option) else: parser.add_option(normal option) or completely separate the parsers for the two differing scenarios. > Irrespective of the usage scenario, I believe that it is important to > give the module user the ability to find out whether an option has > been specified or not by the user. Irrespective of the usage scenario - you can't be serious here. > Some suggestions: > > * Maybe a method can be added to the option class, isSpecified() > which will return True if the option is found on commandline > and optparse has read it or False if the option is not found > on the commandline. > > * Add ability to query the Values instance which is returned by > parse_args My doubts not withstanding, here's how to achieve the desired (I think) behaviour in a few lines - not tested beyond what you see as I will hardly ever use it myself: import sets import optparse as op class Values(op.Values): def __init__(self, defaults): op.Values.__init__(self, defaults) self.specified = sets.Set([]) def __setattr__(self, name, value): self.__dict__[name] = value if hasattr(self, "specified"): self.specified.add(name) def test(args): p = op.OptionParser() p.add_option("-f", dest="filename", default="tmp.txt") v = Values(p.defaults) p.parse_args(args, v) if "filename" in v.specified: info = "specified:" else: info = "using default:" print info, v.filename test(["-f", "other.txt"]) test(["-f", "tmp.txt"]) test([]) Peter From max at alcyone.com Fri Mar 19 15:54:56 2004 From: max at alcyone.com (Erik Max Francis) Date: Fri, 19 Mar 2004 12:54:56 -0800 Subject: Result of ``a is b'' References: <38ec68a6.0403171642.7199763c@posting.google.com> <405A5EC9.6010503@yahoo.com.au> <2eu6c.25407$P45.19517@fe1.columbus.rr.com> Message-ID: <405B5E20.AD0EAB6D@alcyone.com> Andrew Koenig wrote: > I'm pretty sure that IEEE floating point requires NaN to be defined in > such > a way that if x is NaN, then x == x must yield False. That's correct. Python itself doesn't do this, though: Python 2.3.3 (#1, Dec 22 2003, 23:44:26) [GCC 3.2.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> a = 1e3000 >>> a inf >>> a/a nan >>> n = a/a >>> n == n True >>> [Similar things are shown for Python on Solaris 8.] But the following C program: #include int main(void) { double a = 1e3000; double n = a/a; printf("%f, %f, %d\n", a, n, a == n); return 0; } prints inf, nan, 0 on Intel Linux. -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE \__/ Chance favors the trained mind. -- Louis Pasteur From HughMacdonald at brokenpipefilms.com Tue Mar 30 01:45:49 2004 From: HughMacdonald at brokenpipefilms.com (Hugh Macdonald) Date: Tue, 30 Mar 2004 07:45:49 +0100 Subject: Getting both PID and output from a command References: <3cc4824d.0403190259.1e06a578@posting.google.com> <002901c40e66$cabaa860$0600a8c0@Hugh> Message-ID: <004f01c41622$a30ca2f0$0600a8c0@Hugh> Fair enough - thanks for the suggestion.... I have actually already gone the other way, which works perfectly, thanks. If I find problems with the method I'm using, then I will certainly take a look at this one... Hugh Macdonald ----- Original Message ----- From: "Cameron Laird" To: Sent: Tuesday, March 30, 2004 2:14 AM Subject: Re: Getting both PID and output from a command > In article , > Hugh Macdonald wrote: > >I suspect I'll probably use Donn Cave's suggestion when I give it a go on > >monday - I'd rather not use any external modules if I can help it, and I > >know that stderr gives me output in a format that I can read (I know exactly > >which command I want to run here, and I have the program working properly > >except for not being able to stop if before it finishes on its own.....) > . > . > . > Please understand that, as external modules go, Pexpect > is easy to like, because it's "pure Python". It's just > some Python source code. You can choose to put it all > inside *your* program, then there's nothing "external". > If you wish, just think of it as a particularly long > Usenet reply that has already been tested. > -- > > Cameron Laird > Business: http://www.Phaseit.net > > From SBrunning at trisystems.co.uk Thu Mar 18 06:51:22 2004 From: SBrunning at trisystems.co.uk (SBrunning at trisystems.co.uk) Date: Thu, 18 Mar 2004 11:51:22 -0000 Subject: asking for python community opinion about groovy Message-ID: <31575A892FF6D1118F5800600846864D012010C0@intrepid> > From: menceur at hotmail.com [mailto:menceur at hotmail.com] > The Java community is working on the adoption of Groovy as a JCP > standard (http://www.jcp.org/en/jsr/detail?id=241). > Groovy is a dynamic/agile language for Java > (http://groovy.codehaus.org/). > > IMO, it will be better to support the Jython project. Because Jython > exists, it's very useful and powerful. In fact, I think java community > want to have its own "scripting" language because java community is > not open-minded enough and will not accept to use something for the > outside. I raised this with James Strachan and a London Java meetup when he first dreamt up Groovy. Thing is, he likes Java syntax, and doesn't really like Python that much: AFAIC, I don't see anything in Groovy to tempt me away from Python (and Jython). But some people want to stick to something that looks as close to Java as possible, and Jython may not be for them. Anthony Eden has pointed out that even for these people, there is a more established solution than Groovy: All that said, James is a lovely bloke, so good luck to him. May the best dynamic language win! Cheers, Simon B. simon at brunningonline.net http://www.brunningonline.net/simon/blog/ --LongSig ----------------------------------------------------------------------- The information in this email is confidential and may be legally privileged. It is intended solely for the addressee. Access to this email by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot accept liability for statements made which are clearly the senders own. From skip at pobox.com Tue Mar 16 16:23:03 2004 From: skip at pobox.com (Skip Montanaro) Date: Tue, 16 Mar 2004 15:23:03 -0600 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: <16471.28727.338538.151300@montanaro.dyndns.org> >>>>> "Axel" == Axel Boldt writes: Axel> David MacQuigg wrote >> >>> x = 'akdijfkdienlskfi' >> >>> y = 'akdijfkdienlskfi' >> >>> x is y >> True >> >>> x = 'a b' >> >>> y = 'a b' >> >>> x is y >> False Axel> Wow. So it seems that the action of "is" on immutables is Axel> unspecified and implementation dependent, thus useless to the Axel> programmer. No, its behavior is quite well-specified. It does a pointer comparison. Here is my "is" rule: Use "is" to compare two objects only if one is explicitly known to be a singleton defined by the language (None, Ellipsis, True, False). and its corrolary: Never use "is" to compare two programmer-defined variables. Note that even though I "know" that small integers, identifier-like strings and the null tuple are all shared objects, the language implementation is free to change. Those are simply optimizations which you can't rely on. Use "==" when comparing integers, strings and tuples. Trying to use "is" when you want a performance improvement is generally unwise. There is a performance hit going from "is" to "==", but it's probably going be down in the noise compared to all the other things a significant program needs to do. Ordered from fastest to slowest, timing a pass statement, "a is b", "a == b" and a call to a function that only executes a pass statement: % timeit.py -s "a = b = 'frankie and johnny'" "pass" 10000000 loops, best of 3: 0.132 usec per loop % timeit.py -s "a = b = 'frankie and johnny'" "a is b" 1000000 loops, best of 3: 0.372 usec per loop % timeit.py -s "a = b = 'frankie and johnny'" "a == b" 1000000 loops, best of 3: 0.491 usec per loop % timeit.py -s "def f(): pass" "f()" 1000000 loops, best of 3: 1.1 usec per loop "a == b" is still twice as fast as a null function call. Moral of the story: stop writing code that contains so many functions. Skip From python at rcn.com Thu Mar 11 17:15:57 2004 From: python at rcn.com (Raymond Hettinger) Date: 11 Mar 2004 14:15:57 -0800 Subject: Extending Python Syntax with @ References: Message-ID: <5d83790c.0403111415.6485048@posting.google.com> [David MacQuigg] > print @(separator = None) x, y, z For this particular example, you might get farther by proposing a builtin print function that takes optional keyword arguments: def newprint(*args, separator=' ', destination=sys.stdout): print >> destination, separator.join(args) Guido at one time wished that print was a function instead of a statement. Here's your chance to push that idea forward. Using a function instead of a statement is inherently more flexible, easier to extend, and helps address a couple of micro-warts (i.e. a handful of people hate the automatic spacing, and more than a handful hate the >> notation). Raymond Hettinger From magnus at thinkware.se Tue Mar 30 14:51:56 2004 From: magnus at thinkware.se (Magnus Lyck?) Date: 30 Mar 2004 11:51:56 -0800 Subject: A 'Python like' language References: <40645d8f$0$10775$afc38c87@news.easynet.co.uk> <1068up4kn49778@news.supernews.com> <58cb60lmovocadg9p3ghu39t4ga343gfvd@4ax.com> Message-ID: <258fd9b8.0403301151.179e9190@posting.google.com> "Greg Ewing (using news.cis.dfn.de)" wrote in message news:... > * A bit of syntactic sugar for defining prototype objects > wouldn't go amiss. Having to say > > Thing = Base() > with Thing: > ... > > every time I want to define a class (oops, sorry, prototype) > would drive me batty. What about just combining it to this? with Thing = Base(): ... From tjreedy at udel.edu Fri Mar 12 14:46:21 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 12 Mar 2004 14:46:21 -0500 Subject: loop scope References: Message-ID: "David MacQuigg" wrote in message news:utn350d54pjtrsi1a6sd4ckg82mnq2uf4b at 4ax.com... > 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. Please see other post. In the future, the consisitency will be with generator comprehensions, where the loop variable is clearly encapsulated inside the induced generator function. Terry J. Reedy From wilkSPAM at OUTflibuste.net Tue Mar 30 06:26:14 2004 From: wilkSPAM at OUTflibuste.net (Wilk) Date: Tue, 30 Mar 2004 13:26:14 +0200 Subject: GUI Frameworks in Python? References: Message-ID: <87zn9yk23t.fsf@blakie.riol> "Hugh Macdonald" writes: > I've recently been trying out various different GUI frameworks in Python and > was wondering if I could get your input on the pros and cons of the > different ones... > > wxPython: I love the programming side of wxPython, but I find it's just so > slow to initialise in the first place. > > Tkinter: While it's fast to load up, the syntax has never really appealed to > me > > GTK: Unknown - I'm looking into it today > > Qt: I have yet to manage to install it on my system > > Anything else? I'm very happy with web interface :-) -- Wilk - http://flibuste.net From mstenner at ece.arizona.edu Mon Mar 15 11:07:45 2004 From: mstenner at ece.arizona.edu (Michael Stenner) Date: Mon, 15 Mar 2004 09:07:45 -0700 Subject: pre-processing source from distutils In-Reply-To: References: Message-ID: Michael Stenner wrote: > Is it possible to pre-process source code from distutils? I don't want > to do anything too fancy. I just want to put the VERSION from setup.py > (and maybe a date) into the module at sdist or build time (I haven't > decided which of those would be cleaner). Anybody know of a clean way > to do this? After some hunting around, I found that the preferred way to handle this specific problem is to put __version__ = 'x.x.x' in the module itself (or in __init__.py for a package) and then have setup.py import the module and slurp the version in from there. That works for me. -Michael From miki.tebeka at zoran.com Thu Mar 11 19:52:30 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Fri, 12 Mar 2004 02:52:30 +0200 Subject: Python database In-Reply-To: <4050647e$1@puffinus.its.uu.se> References: <4050647e$1@puffinus.its.uu.se> Message-ID: <405109CE.503@zoran.com> Hello None, > Can someone recommend a simple, easy-to-program data base? IIRC `metakit' is very simple to use. > As far as I have understood there is no standard data base in Python. > Why is this so? Do people have too different needs? I think the `anydbm' module is what you're looking for. HTH. Miki From jepler at unpythonic.net Mon Mar 15 16:38:13 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 15 Mar 2004 15:38:13 -0600 Subject: Deprecating reload() ??? In-Reply-To: References: <6kk6501shlve52ds2rjdopa73jhpchprg3@4ax.com> Message-ID: <20040315213813.GD2446@unpythonic.net> On Mon, Mar 15, 2004 at 01:18:34PM -0700, David MacQuigg wrote: > Maybe you can save a significant amount of memory by having all the > *system* modules share a common 'None' object, but when a user > explicitly says 'M1.x = None', surely we can afford a 8 bytes to > provide a special None for that reference. Not only is there a lot of Python code written that says if x is None: ... but there are dozens of pointer comparisons to Py_None in the C source code for Python. In this somewhat stale CVS tree, grep found 263 lines with both "==" and "Py_None" on the same line, and 86 more with "!=" and "Py_None" on the same line. Py_True and Py_False appear with == and != an additional 45 times. Perhaps you'd like to fix all the third-party extension modules once you're done inspecting something like 300 sites in the Python core. For Py_None, at least, the pointer equality rule is enshrined in the API documentation: Since None is a singleton, testing for object identity (using "==" in C) is sufficient. http://www.python.org/doc/api/noneObject.html Jeff From avagent-bounce at beauty.oscar-gmbh.com Wed Mar 31 16:39:43 2004 From: avagent-bounce at beauty.oscar-gmbh.com (Anti-Virus Agent) Date: Wed, 31 Mar 2004 23:39:43 +0200 Subject: WARNING! Virus or unsafe content was found in message from python-list@python.org Message-ID: The message sent from to the following recipient(s): andreas.brodowski at oscar-gmbh.com with subject line 'Delivered Message (andreas.brodowski at oscar-gmbh.com)', contains a virus or similar harmful content, therefore it was NOT delivered. --- Eicar_test_file in f-eicar.com WORM_NETSKY.D in f-your_details.pif WORM_NETSKY.D in f-mp3music.pif WORM_NETSKY.D in f-your_document.pif WORM_NETSKY.D in f-document_excel.pif WORM_NETSKY.D in f-document_excel.pif WORM_NETSKY.D in f-yours.pif WORM_NETSKY.D in f-yours.pif WORM_NETSKY.D in f-your_bill.pif WORM_NETSKY.D in f-your_file.pif WORM_NETSKY.D in f-your_product.pif WORM_NETSKY.D in f-application.pif WORM_NETSKY.D in f-your_archive.pif WORM_NETSKY.D in f-your_document.pif WORM_NETSKY.D in f-your_details.pif WORM_NETSKY.D in f-your_text.pif WORM_NETSKY.D in f-yours.pif WORM_NETSKY.D in f-document_word.pif WORM_NETSKY.D in f-my_details.pif WORM_NETSKY.D in f-message_part2.pif WORM_NETSKY.D in f-your_text.pif WORM_NETSKY.D in f-your_document.pif WORM_NETSKY.D in f-your_archive.pif WORM_NETSKY.D in f-mp3music.pif WORM_NETSKY.D in f-your_picture.pif WORM_NETSKY.D in f-my_details.pif WORM_NETSKY.D in f-document_word.pif WORM_NETSKY.D in f-your_archive.pif WORM_NETSKY.D in f-your_picture.pif WORM_NETSKY.D in f-document.pif WORM_NETSKY.C in f-sexual_paypal.pif WORM_NETSKY.C in f-response_description.doc.scr WORM_NETSKY.C in f-naked2.exe WORM_NETSKY.D in f-your_archive.pif WORM_NETSKY.D in f-my_details.pif WORM_NETSKY.D in f-application.pif WORM_NETSKY.C in f-yours.zip WORM_BAGLE.E in f-ddbeeecaab.zip WORM_NETSKY.D in f-your_picture.pif WORM_NETSKY.D in f-your_text.pif WORM_NETSKY.D in f-document_word.pif WORM_NETSKY.D in f-your_picture.pif WORM_NETSKY.J in f-yours.pif WORM_NETSKY.J in f-document_full.pif WORM_NETSKY.D in f-your_text.pif WORM_NETSKY.D in f-your_details.pif WORM_NETSKY.J in f-document_4351.pif WORM_NETSKY.D in f-your_bill.pif WORM_NETSKY.D in f-message_details.pif WORM_NETSKY.D in f-your_picture.pif WORM_NETSKY.D in f-your_letter.pif WORM_NETSKY.D in f-message_part2.pif WORM_NETSKY.D in f-your_document.pif WORM_NETSKY.D in f-document_4351.pif WORM_NETSKY.D in f-your_text.pif WORM_NETSKY.D in f-your_bill.pif WORM_NETSKY.D in f-your_file.pif WORM_NETSKY.D in f-document_full.pif WORM_NETSKY.D in f-your_document.pif WORM_NETSKY.D in f-document.pif WORM_NETSKY.D in f-your_text.pif WORM_NETSKY.D in f-document_4351.pif WORM_NETSKY.D in f-your_document.pif WORM_NETSKY.D in f-all_document.pif WORM_NETSKY.D in f-your_archive.pif WORM_NETSKY.D in f-all_document.pif WORM_NETSKY.D in f-your_file.pif WORM_NETSKY.D in f-document.pif WORM_NETSKY.D in f-document_word.pif WORM_NETSKY.D in f-your_document.pif WORM_NETSKY.D in f-document_4351.pif WORM_NETSKY.D in f-application.pif WORM_NETSKY.D in f-your_file.pif WORM_NETSKY.D in f-document_word.pif WORM_NETSKY.D in f-your_letter.pif WORM_NETSKY.D in f-message_part2.pif WORM_NETSKY.D in f-all_document.pif WORM_NETSKY.D in f-your_picture.pif WORM_NETSKY.D in f-document_4351.pif WORM_NETSKY.D in f-your_picture.pif WORM_NETSKY.D in f-your_document.pif WORM_NETSKY.D in f-document_full.pif WORM_NETSKY.D in f-your_bill.pif WORM_NETSKY.D in f-your_archive.pif WORM_NETSKY.D in f-your_picture.pif WORM_NETSKY.D in f-your_bill.pif WORM_NETSKY.D in f-your_archive.pif WORM_NETSKY.D in f-your_archive.pif WORM_NETSKY.D in f-all_document.pif WORM_NETSKY.D in f-your_text.pif WORM_NETSKY.D in f-your_product.pif WORM_NETSKY.D in f-your_document.pif WORM_NETSKY.D in f-message_details.pif WORM_NETSKY.D in f-your_document.pif WORM_NETSKY.D in f-your_archive.pif WORM_NETSKY.D in f-your_document.pif WORM_NETSKY.D in f-your_picture.pif WORM_BAGLE.GEN-1 in f-Document.zip WORM_NETSKY.D in f-my_details.pif WORM_NETSKY.D in f-your_website.pif WORM_NETSKY.D in f-your_picture.pif WORM_NETSKY.D in f-your_file.pif WORM_NETSKY.P in f-message.scr WORM_NETSKY.P in f-message.scr WORM_NETSKY.D in f-your_document.pif WORM_NETSKY.D in f-all_document.pif WORM_NETSKY.P in f-confirm.zip WORM_NETSKY.P in f-archive_.jung.zip WORM_NETSKY.P in f-message.scr WORM_NETSKY.P in f-message.scr WORM_NETSKY.P in f-document.zip WORM_NETSKY.D in f-your_text.pif WORM_NETSKY.D in f-your_picture.pif WORM_NETSKY.P in f-details_postmaster.zip WORM_NETSKY.P in f-message.scr WORM_NETSKY.P in f-details_info.doc.exe WORM_NETSKY.P in f-message.scr WORM_NETSKY.D in f-your_product.pif WORM_NETSKY.P in f-datfiles.zip WORM_NETSKY.P in f-old_photos_.jung.zip WORM_NETSKY.P in f-message.scr WORM_NETSKY.P in f-message.scr WORM_NETSKY.P in f-message.scr WORM_NETSKY.P in f-message.scr WORM_NETSKY.D in f-your_website.pif WORM_NETSKY.D in f-document_word.pif WORM_NETSKY.P in f-information.zip WORM_NETSKY.P in f-message.scr WORM_NETSKY.P in f-msg.doc.scr WORM_NETSKY.P in f-message_.jung.doc.pif WORM_NETSKY.D in f-document_4351.pif WORM_NETSKY.P in f-message.scr WORM_NETSKY.P in f-message.scr WORM_NETSKY.P in f-document.txt.scr WORM_NETSKY.P in f-message.scr WORM_NETSKY.P in f-document05.zip WORM_NETSKY.P in f-game.txt.scr WORM_NETSKY.P in f-doc01.zip WORM_NETSKY.P in f-readme.pif WORM_NETSKY.P in f-.scr WORM_NETSKY.P in f-.pif WORM_NETSKY.P in f-document_all02c.zip WORM_NETSKY.P in f-.pif WORM_NETSKY.P in f-document.pif WORM_NETSKY.P in f-account.zip WORM_NETSKY.P in f-details.scr WORM_NETSKY.P in f-letter32.zip WORM_NETSKY.P in f-my_numbers_g.man.zip WORM_NETSKY.P in f-document_all.zip WORM_NETSKY.P in f-document09.zip WORM_NETSKY.D in f-message_part2.pif WORM_NETSKY.D in f-your_details.pif WORM_NETSKY.P in f-message.scr WORM_NETSKY.P in f-.scr WORM_NETSKY.P in f-message.scr WORM_NETSKY.P in f-document_g.man.zip WORM_NETSKY.P in f-message.pif WORM_NETSKY.P in f-readme.doc.pif WORM_NETSKY.P in f-message.scr WORM_NETSKY.P in f-message.scr WORM_NETSKY.P in f-text.zip WORM_NETSKY.D in f-your_product.pif WORM_NETSKY.P in f-game_xxo.pif WORM_NETSKY.P in f-data02.zip WORM_NETSKY.P in f-message.scr WORM_NETSKY.P in f-message.scr WORM_NETSKY.P in f-message.scr WORM_NETSKY.P in f-.scr WORM_NETSKY.P in f-document.exe WORM_NETSKY.P in f-message.scr WORM_NETSKY.P in f-message.scr WORM_NETSKY.D in f-application.pif WORM_NETSKY.D in f-your_archive.pif WORM_NETSKY.D in f-your_archive.pif WORM_NETSKY.D in f-your_details.pif WORM_NETSKY.D in f-your_archive.pif WORM_NETSKY.P in f-details.exe WORM_NETSKY.P in f-message.scr WORM_NETSKY.P in f-signature.pif WORM_NETSKY.P in f-details.zip WORM_NETSKY.P in f-document342.zip WORM_NETSKY.P in f-part_01.pif WORM_NETSKY.P in f-photo.zip WORM_NETSKY.P in f-doc01.zip WORM_NETSKY.P in f-message_g.man.zip WORM_NETSKY.D in f-your_document.pif WORM_NETSKY.D in f-my_details.pif WORM_NETSKY.P in f-message.scr WORM_NETSKY.D in f-your_document.pif WORM_NETSKY.P in f-.pif WORM_NETSKY.P in f-.pif WORM_NETSKY.D in f-your_picture.pif WORM_NETSKY.D in f-your_document.pif WORM_NETSKY.D in f-my_details.pif WORM_NETSKY.P in f-message.scr WORM_NETSKY.D in f-your_document.pif WORM_NETSKY.D in f-your_document.pif WORM_NETSKY.P in f-document07_g.man.scr WORM_NETSKY.P in f-message.scr WORM_NETSKY.D in f-your_text.pif WORM_NETSKY.D in f-document.pif WORM_NETSKY.D in f-your_archive.pif WORM_NETSKY.D in f-your_picture.pif WORM_NETSKY.P in f-message.scr WORM_NETSKY.P in f-message.scr WORM_NETSKY.P in f-.exe WORM_NETSKY.P in f-readme.zip WORM_NETSKY.P in f-pgp_sess01.pif WORM_NETSKY.P in f-message.scr WORM_NETSKY.P in f-product.zip WORM_NETSKY.P in f-message.scr WORM_NETSKY.P in f-message.scr WORM_NETSKY.D in f-your_archive.pif WORM_NETSKY.D in f-your_text.pif WORM_NETSKY.P in f-message.scr WORM_NETSKY.P in f-part6_g.man.zip WORM_NETSKY.P in f-part_01.zip WORM_NETSKY.P in f-sample01.zip WORM_NETSKY.D in f-your_bill.pif WORM_NETSKY.Q in f-message3094.pif WORM_NETSKY.Q in f-message.pif WORM_NETSKY.P in f-data.pif WORM_NETSKY.P in f-summary2004.zip WORM_NETSKY.P in f-www.myx4free.exe WORM_NETSKY.P in f-message.scr WORM_NETSKY.P in f-message.scr WORM_NETSKY.P in f-message.scr WORM_NETSKY.P in f-letter.zip WORM_NETSKY.D in f-document.pif WORM_NETSKY.Q in f-message11176.pif WORM_NETSKY.P in f-about_you.scr WORM_NETSKY.Q in f-message.pif WORM_NETSKY.P in f-message.scr WORM_NETSKY.D in f-your_document.pif WORM_NETSKY.D in f-document_word.pif WORM_NETSKY.P in f-letter43.zip WORM_NETSKY.P in f-important.zip WORM_NETSKY.P in f-.scr WORM_NETSKY.D in f-document_4351.pif WORM_NETSKY.D in f-document_4351.pif WORM_NETSKY.D in f-mp3music.pif WORM_NETSKY.Q in f-message13918.zip WORM_NETSKY.Q in f-message.pif WORM_NETSKY.Q in f-data9213.pif WORM_NETSKY.Q in f-message.pif WORM_NETSKY.Q in f-message.pif WORM_NETSKY.Q in f-message.pif WORM_NETSKY.Q in f-data2674.pif WORM_NETSKY.Q in f-mail16007.zip WORM_NETSKY.Q in f-data3539.zip WORM_NETSKY.Q in f-data25189.zip --- From o_gloom at mail.com Thu Mar 11 07:16:35 2004 From: o_gloom at mail.com (gloom) Date: 11 Mar 2004 04:16:35 -0800 Subject: pythoncom, CoUninitialize & references Message-ID: <9f115c52.0403110416.4c29e7ca@posting.google.com> Hey, I'm programming something with NeroSDK COM module, and I bumped into a problem: why doesn't python releases and uninitializes COM objects that are no longer referenced? Here is a sample code: # start of sample code from win32com.client import * nero = None def find_backpack_cd(): drives = nero.GetDrives(constants.NERO_MEDIA_CD) rc = None for d in drives: if d.DeviceName.find("BACKPACK") != -1: rc = d break del(drives) print rc return rc def main(): global nero nero = Dispatch("Nero.Nero") cd = find_backpack_cd() del(cd) del(nero) if __name__ == "__main__": main() print pythoncom._GetInterfaceCount() pythoncom.CoFreeUnusedLibraries() pythoncom.CoUninitialize() # end of sample code the problem is as follows, if for example, I remove the line 'del(nero)' in function main(), the _GetInterfaceCount() is 1 and CoUninitialize() fails. And if I remove the explicit call to CoUninitialize() (and the interface count is greater than 0) the next time I run the program it fails with exception that the neroAPI is already initialized (deducing that it is somehow still in memory). Doesn't python should get rid of all instances of the COM objects through its garbage collector? Thanks, Omer. From matt.gerrans at hp.com Tue Mar 23 19:13:59 2004 From: matt.gerrans at hp.com (Matt Gerrans) Date: Wed, 24 Mar 2004 00:13:59 GMT Subject: creating lists question? References: Message-ID: "spisatus" wrote: > I'm not sure this is doing what I want it to do. In the example I gave I > want a new list call "aaa" another list called "bbb"... so I can append to > the new list i.e., bbb.append(). It may be that your example does this but > it appears to be (with my limited knowledge) that it's creating a list of > lists, when all I want is a new isolated list. This would do the trick: for item in list1: exec( item + ' = []' ) Of course, there are the usual cautions about using exec() and error handling... From phil_nospam_schmidt at yahoo.com Mon Mar 1 11:49:51 2004 From: phil_nospam_schmidt at yahoo.com (Phil Schmidt) Date: 1 Mar 2004 08:49:51 -0800 Subject: Tkinter default bindings Message-ID: <221e7b06.0403010849.e78448@posting.google.com> I have an Entry widget inside a Frame. The Frame contains other widgets as well. I have bound the event to the Frame, but I don't want the Frame to receive the event when the Entry widget has focus. So, I bound the event to the Entry widget (bound to method a_key()). This works, except that both the Entry and Frame widgets get the event. This also forces me to implement event handlers, which is fine for the Frame since that's what I want to do. But I want the Entry to use its default handler, not my own handler. Rather than duplicate all that functionality, I found I could accomplish this by temporarily unbinding the events, re-generating the event, and then re-binding the events, as follows: def a_key(self, e): self.top.unbind('') self.entry.unbind('') self.entry.event_generate('', keycode=e.keycode, keysym=e.keysym, ) self.entry.bind('', self.a_key) self.top.bind('', self._parent_class__keypress) return 'break' This works, but it's kludgy. Is there a better way to do this? I just want the Entry widget to receive the event when it has focus, behave in its default manner, and not have the event propagate upward to containing widgets. From user at domain.invalid Fri Mar 12 00:21:15 2004 From: user at domain.invalid (user at domain.invalid) Date: Fri, 12 Mar 2004 16:21:15 +1100 Subject: loop scope References: Message-ID: <405148CB.1030103@domain.invalid> Terry Reedy wrote: > For loops with a break statement, the value of the loop index when the > break occurs may be the answer sought or needed to calculate it. For list > comps which cannot have break, it is an artifact which may disappear in > 2.4. If I understand you, I don't think I like this idea. It adds complexity to the mental model of a loop. "The loop variable disappears when the loop ends unless the loop contains a break". In my opinion, Python should pick a model and stick to it. Loop variables are either ordinary variables that exist until you explicitly delete them, or they are special variables that automagically disappear at the end of the loop. I vote for the first one. -- Steven D'Aprano From op73418 at mail.telepac.pt Mon Mar 15 09:14:33 2004 From: op73418 at mail.telepac.pt (Gonçalo Rodrigues) Date: Mon, 15 Mar 2004 14:14:33 +0000 Subject: loop scope References: Message-ID: <0vdb505qigqvp8eahhp5qubnuh1v7n7k61@4ax.com> On 15 Mar 2004 12:52:14 +0100, Jacek Generowicz wrote: >Jacek Generowicz writes: > >> 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?) > >Hmm, this is starting to intrigue me. > >What are the situations that need disambiguating? > >What situations do (or might) create inner scopes? > >"def" and "class" are currently the two ways of creating an inner >scope (have I overlooked any others?) ... and we are considering the >possibility of "for" doing the same (in two different flavours: loops >and comprehensions). > Is it (entirely) correct to say that class opens a new scope? I don't think so, 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. >Current rules can be summarized as: > > In a scope creating block (def, class), assignment introduces a > local binding, unless the name is declared global. > >It looks like what's missing (because originally there were no other >scopes between local and global) is some way of declaring a name to >refer to an enclosing scope which may or may not be the global scope. > >For example: > > >>> def make(): > ... x = 0 > ... def show(): print x > ... def inc(n): x = x+n > ... return show,inc > ... > >>> show,inc = make() > >>> show() > 0 > >>> inc(3) > Traceback (most recent call last): > File "", line 1, in ? > File "", line 4, in inc > UnboundLocalError: local variable 'x' referenced before assignment > >The problem is that the "x =" inside "def inc():" tells the compiler >to treat "x" as local to the scope of "inc", and then the reference to >"x" or the RHS of the same line refers to an unbound variable ("x" in >the _local_ scope). "global" is there for exactly this sort of >situation, except that it originates from a time when there were no >nested scopes, so it offers no help if you want to refer to some scope >other than the global or local. > 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 The scope of a name is determined at compile time, so it seems unavoidable that a declaration is needed. But I wished that there were no declarations in Python and some OO form of treating scopes like objects with the local names being its attributes were available -- but I am also well aware that this is a very idiosincratic preference :-) With my best regards, G. Rodrigues From peter at engcorp.com Wed Mar 17 13:12:07 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 17 Mar 2004 13:12:07 -0500 Subject: Inconsistency in Python's Comparisons In-Reply-To: References: <4057B2A4.F9EC49DD@alcyone.com> Message-ID: Andrew Koenig wrote: > "Erik Max Francis" wrote in message > news:4057B2A4.F9EC49DD at alcyone.com... > > >>Do you have an example of this that doesn't involve comparisons between >>different types? > > > Do long and float count as different types? Was this a trick question? >>> float >>> long >>> issubclass(long, long) True >>> issubclass(long, float) False >>> issubclass(float, long) False Python says the answer to your question is "yes"... -Peter From tjreedy at udel.edu Sat Mar 6 12:07:29 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 6 Mar 2004 12:07:29 -0500 Subject: Introspection at the module level? References: Message-ID: "Roy Smith" wrote in message news:roy-AEE793.11085806032004 at reader2.panix.com... > But I don't see how to get the values. Getattr() is sort of what I > want, but it works on objects, not modules. Yes it does >>> m = __import__(__name__) >>> setattr(m, 'a', 3) >>> dir(m) ['__builtins__', '__doc__', '__name__', 'a', 'm'] >>> getattr(m, 'a') 3 > I don't see how to get a handle to the module from inside the module, i.e. > there's no "self". You have to define it yourself. See above. > What am I missing? d={} # then, inside your loop: d[getattr(m,name)] = name #should do what you said you want Terry J. Reedy From guettli at thomas-guettler.de Tue Mar 16 08:30:26 2004 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Tue, 16 Mar 2004 14:30:26 +0100 Subject: Python & Linux, some questions (2) References: Message-ID: Am Mon, 15 Mar 2004 21:28:47 +0100 schrieb Luca T.: > So it seems that "su" refuses to work if it is run like this. > Now, beside "sudo" that i CANNOT use because i don't want to change the > configuration of the user's comp... any idea about how i could run a > program as root from inside my python program? Hi, write a little C programm and make it setuid root. Scripts cannot be setuid. Be carefull, there are a many things you need to make it secure. Maybe suexec of apache can be used as template. HTH, Thomas From dmq at gain.com Thu Mar 18 14:50:17 2004 From: dmq at gain.com (David MacQuigg) Date: Thu, 18 Mar 2004 12:50:17 -0700 Subject: Result of ``a is b'' References: <40200384.0403151632.35496ee6@posting.google.com> <40200384.0403161255.7fca7a8c@posting.google.com> Message-ID: <5bvj50tp0qc4j0kibo7q8ul86t5t8k2901@4ax.com> >At some point, David MacQuigg wrote: >> I can't see where the 'is' test would *ever* be needed for the above >> comparisons. > On Thu, 18 Mar 2004 01:17:53 -0500, cookedm+news at physics.mcmaster.ca (David M. Cooke) wrote: >I do a lot of stuff with arrays in Numeric, which override __eq__ to >elementwise comparision: > >Python 2.3.3 (#2, Feb 24 2004, 09:29:20) >[GCC 3.3.3 (Debian)] on linux2 >Type "help", "copyright", "credits" or "license" for more information. >>>> import Numeric >>>> x = Numeric.array([0,1,2,3]) >>>> x == None >array([0,0,0,0]) >>>> bool(x == None) >False >>>> x is None >False >>>> x == False >array([1,0,0,0]) >>>> bool(x == False) >True >>>> x is False >False >>>> bool(x == True) >True >>>> bool(x == True and x == False) >True > >[Ok, so bool(x == None) returns False, which is good, but imagine the >overhead if x was an array of several million elements. x == None >would allocate a new array of the same size.] For the rare case where storage of None elements is an issue, could you define your own 'none' object, and simply point all references to it. That would allow you to use 'is', avoiding the overhead of '==', and not mess with the normal definition of '=='. Most importantly, it would allow you to use 'is' with confidence that a Python implementation change, or a move to a new platform, won't trash your program. >>> class none: def __repr__(self): return 'none' ... whatever other attributes you need for 'none' >>> n0 = none() >>> n1 = n2 = n0 >>> n1 == n2 True >>> n1 is n2 True >>> n1 none >>> -- Dave From donn at u.washington.edu Wed Mar 17 11:51:51 2004 From: donn at u.washington.edu (Donn Cave) Date: Wed, 17 Mar 2004 08:51:51 -0800 Subject: imaplib.IMAP4: Bug in implementation References: Message-ID: In article , "Oliver Kurz" wrote: > I call the uid like this > > uid("STORE",uid,"+FLAGS(\SEEN)") Have you tried uid("STORE", uid, "+FLAGS", "(\SEEN)")? Donn Cave, donn at u.washington.edu From tjreedy at udel.edu Mon Mar 8 23:48:42 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 8 Mar 2004 23:48:42 -0500 Subject: How to send event to another window in wxPython? References: Message-ID: "J.R." wrote in message news:c2jfd7$hbu$1 at newshost.mot.com... > A parent window (wxFrame object), which has the reference to its child > window(also wxFrame object). > I want to send event or message to the child window from the parent window, > just like simulating the mouse > or keyboard activities on child window. How to implement it? wxPython is an application written in Python, not Python itself. You may or may not have better luck asking your question on the wxPython mailing list. From peter at engcorp.com Fri Mar 12 13:34:36 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 12 Mar 2004 13:34:36 -0500 Subject: Deprecating reload() ??? In-Reply-To: <8ok3505b3b3g22bk8ci6iagptqav2cfi6r@4ax.com> References: <40514A48.50907@domain.invalid> <09b350henbtk9vnai0v7fhtbsqbmubl7vn@4ax.com> <7cj4c.2733$G3.21896@localhost> <8ok3505b3b3g22bk8ci6iagptqav2cfi6r@4ax.com> Message-ID: David MacQuigg wrote: > On Fri, 12 Mar 2004 08:45:24 -0500, Peter Hansen > wrote: >>Reload is not broken, and certainly shouldn't be deprecated at least >>until there's a better solution that won't suffer from reload's one >>problem, IMHO, which is that it surprises some people by its behaviour. > > It's worse than just a surprise. It's a serious problem when what you > need to do is what most people are expecting -- replace every > reference to objects in the old module with references to the new > objects. The problem becomes a near impossibility when those > references are scattered throughout a multi-module program. I don't consider this a problem with reload, I consider it a design defect. If there's a need for such a thing, it should be designed in to the application, and certainly one would remove the "scattering" of objects such as these which are about to be replaced en masse. I think many applications would be inherently broken if a programmer thought a simple "reload" of the style you envision would work without serious but possibly quite subtle side effects. >>I think that when you consider Python's namespace mechanism, you can't >>avoid the possibility of situations like the ones reload can now lead to. > > I don't understand. My assumption is you would normally update all > references to the selected objects in all namespaces. I guess we're coming at this from different viewpoints. My comments above should probably explain why I said that. Basically, it seems to me very unlikely there are good use cases for wanting to update the classes behind the backs of objects regardless of where references to them are bound. I'm open to suggestions though. -Peter From ed-no at spam-eepatents.com Sat Mar 27 18:14:15 2004 From: ed-no at spam-eepatents.com (Ed Suominen) Date: Sat, 27 Mar 2004 15:14:15 -0800 Subject: Regular Expressions References: <76adnc77cvMUl_vdRVn-jA@centurytel.net> Message-ID: <76adncn7cvNZl_vdRVn-jA@centurytel.net> 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)) > > - Ed Suominen > > achaljalan at yahoo.com wrote: > >> Hey, >> >> I have a string >> >> s =740446505 "O'HANLON, Benjamin" >> >> i need to use one RE to convert it into >> >> (740446505, "O'HANLN", "Benjamin"), >> >> I am using python 2.3 and have been stuydin the various tutotrials and >> the howto websites for the past 3 days and haven't managed to find a >> solution. >> >> Any help to get to the solution will be very very helpful. >> >> Thanks in advance for all the help. >> >> Achal Jalan >> >> >> --------------------------------- >> Do you Yahoo!? >> Yahoo! Finance Tax Center - File online. File on time. From steve at ninereeds.fsnet.co.uk Mon Mar 22 06:12:34 2004 From: steve at ninereeds.fsnet.co.uk (Stephen Horne) Date: Mon, 22 Mar 2004 11:12:34 +0000 Subject: PEP 318 References: <99dce321.0403211817.3704fe2@posting.google.com> <7x1xnlqs77.fsf@ruckus.brouhaha.com> <7xisgxuoti.fsf@ruckus.brouhaha.com> Message-ID: On 22 Mar 2004 03:02:49 -0800, Paul Rubin wrote: >Stephen Horne writes: >> Good point. Though to me, it isn't that it's a pain for the compiler >> to search for the 'yield' - I don't care about the compilers pain. The >> problem is that *I* have to look for the yield and might not notice it. > >Well, yes. It wouldn't have occurred to me to care about the >compiler's pain ;-). We're such an unfeeling bunch, aren't we ;-) -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From python at hitmedia.com Fri Mar 12 01:44:56 2004 From: python at hitmedia.com (Python Baby) Date: Thu, 11 Mar 2004 22:44:56 -0800 Subject: put your money where your mouse is, or why I prefer Spanish to English: a proposal In-Reply-To: <082d01c407eb$bb8dfc10$210110ac@jsbwxp3> References: <082d01c407eb$bb8dfc10$210110ac@jsbwxp3> Message-ID: <20040312064456.GA1898@mail.hitmedia.com> Yes but how does Spanish compare to Ruby? Which is better? ;-) From dj00302003 at yahoo.com Sun Mar 21 19:49:26 2004 From: dj00302003 at yahoo.com (Jay Davis) Date: 21 Mar 2004 16:49:26 -0800 Subject: Xemacs terminal output Message-ID: <1d17eeb7.0403211649.4683bd4f@posting.google.com> What is the best way to run python in Xemacs (with C-c C-c) with real time standard output? Right now, the python output window fills up when the program is finished running, but if the program runs for hours it would be nice to see the output as it is written. I know that I can switch to a python interpreter window and paste the code in etc but I don't care about the interpreter, just about the (printed) output after C-c C-c. From __peter__ at web.de Tue Mar 9 05:37:25 2004 From: __peter__ at web.de (Peter Otten) Date: Tue, 09 Mar 2004 11:37:25 +0100 Subject: URGENT: REALLY NEED HELP: Feel Helpless References: Message-ID: dont bother wrote: > # python code for creating dictionary of words from an > input file > import string, StringIO > import mailbox, email, re > import os > import sys > import re > import mailbox > import email.Parser > import email.Message > import getopt > > > fp=open(sys.argv[1], 'r') > > msg=email.message_from_file(fp) > > msg=msg.get_payload() > > dictpos={} > wordcount={} > #get rid of anything that isn't a letter, and make it > all lowercase: > lower = ''.join(map(chr, range(97, 123))) > fixed_body = msg.translate(65*' '+lower+6*' > '+lower+133*' ') > > #words_in_body = fixed_body.split() > > msg = fixed_body.split() Throw in a print msg sys.exit("debug") here and see if it's what you expected. If yes, comment out and proceed. > for i, w in enumerate(file('dictionary_index')): > dictpos[w.strip()]=i > #print i > #print w Throw in a print dictpos sys.exit("debug") here and see if it's what you expected. If yes, comment out and proceed. > for w in msg: > try: > wordcount[w]+=1 > #print wordcount > except KeyError: > wordcount[w]=1 > #print wordcount Throw in a print wordcount sys.exit("debug") here and see if it's what you expected. If yes, comment out and proceed. > for w, c in wordcount.iteritems(): > try: > print dictpos[w],':',c > except KeyError: > pass Throw in a print [dictpos.get(w, "") for (w,c) in wordcount.iteritems()] sys.exit("debug") here and see if it's what you expected. If yes, comment out and you've fixed your first python program. If one step fails, you're at least able to make a more focused post. But before, please fix your capslock key. This is urgent, too. Peter From miki.tebeka at zoran.com Mon Mar 29 07:17:32 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Mon, 29 Mar 2004 14:17:32 +0200 Subject: How to run another .py file w/o exec command? In-Reply-To: References: Message-ID: <406813DC.3010807@zoran.com> Hello CaptainN, > I'm sure there's a way to do this, but I can't find it. How can I execute > another .py file from my first .py file without using an exec* command? > They're both in the same directory, and it would be nice to have some > run("another.py") type statement as opposed to a big exec with absolute > pathnames and garbage like that. http://www.python.org/doc/current/lib/built-in-funcs.html#built-in-funcs Search for execfile HTH. Miki From fumanchu at amor.org Sat Mar 6 15:22:14 2004 From: fumanchu at amor.org (Robert Brewer) Date: Sat, 6 Mar 2004 12:22:14 -0800 Subject: Need better string methods Message-ID: David MacQuigg wrote: > I'm considering Python as a replacement for the highly specialized > scripting languages used in the electronics design industry. >8 > 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'] > > # Current best Python: > clean = [' '.join(t.split()).strip('.') for t in line.split('|')] > > This is too much to expect of a non-programmer, even one who > undestands the methods. The usability problems are 1) the three > variations in syntax ( methods, a list comprehension, and what *looks > like* a join function prefixed by some odd punctuation), and 2) The > order in which each step is entered at the keyboard. ( I can show > this in step-by-step detail if anyone doesn't understand what I mean.) > 3) Proper placement of parens can be confusing. > > What we need is a syntax that flows in the same order you have to > think about the problem, stopping at each step to visualize an > intermendiate result, then typing the next operation, not mousing back > to insert a function or the start of a comprehension, and not screwing > up the parentheses. ( My inititial version had the closing paren of > the join method *after* the following strip, which lucky-for-me popped > an attribute error ... not-so-lucky could work OK on this example, but > mess up in subtle ways on future data. ) > > # Subclassing a list: > clean = [MyList(t.split()).join().strip('.') for t in line.split('|')] > > The MyList.join method works as expected. I havent' figured out yet > how to add a map method to MyList, but already I can guess this is not > leading to a clean syntax. Having to insert 'MyList' everywhere is as > bad as the original syntax. Maybe someone can help me with the > Python. I would love it if there was a simple solution not requiring > changes to Python. > > # Possible future Python: > # clean = line.split('|').map().split().join().strip('.') > > The map method takes a list in the "front door" and feeds items from > the list one-at-a-time to the method waiting at its "back door". The > join method expects a list of strings at its front door and delivers a > single string at its back door. If something other than a space is > needed to join the strings, that can be provided via the (side-door) > of the join method. The answer depends quite a bit on the deployment environment. If you have a limited (knowable) set of commands which you wish to chain in this manner, you can simply write each one and package them up into a "listtools" package (or "mycompanytools" if they end up being more diverse in the problems they solve). Usage would then be, for example: >>> import listtools >>> line = "..../bgref/stats.stf| SPICE | 3.2.7 | John Anderson \n" >>> listtools.List(line).split("|").squeeze().strip(".") ['/bgref/stats.stf', 'SPICE', '3.2.7', 'John Anderson'] ...the idea being that, once you have "line" wrapped in a listtools.List object, that object can have whatever methods you see fit. In this case, I'd envision most of the methods above returning another listtools.List (this is the actual module I used to produce the above): class List(list): def __init__(self, value=[]): if isinstance(value, (tuple, list)): list.__init__(self, value) else: list.__init__(self, [value]) def split(self, separator): product = List() for atom in self: product.extend(atom.split(separator)) return product def squeeze(self): product = List() for atom in self: atom = ' '.join(atom.split()) product.append(atom) return product def strip(self, chars=None): product = List() for atom in self: product.append(atom.strip(chars)) return product Hope that helps! Robert Brewer MIS Amor Ministries fumanchu at amor.org From hungjunglu at yahoo.com Mon Mar 15 02:01:09 2004 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 14 Mar 2004 23:01:09 -0800 Subject: Deprecating reload() ??? References: <40514A48.50907@domain.invalid> <09b350henbtk9vnai0v7fhtbsqbmubl7vn@4ax.com> <7cj4c.2733$G3.21896@localhost> <8ok3505b3b3g22bk8ci6iagptqav2cfi6r@4ax.com> Message-ID: <8ef9bea6.0403142301.5ee6bad7@posting.google.com> > >> On Fri, 12 Mar 2004 08:45:24 -0500, Peter Hansen > >> wrote: > >> > >> It's worse than just a surprise. It's a serious problem when what you > >> need to do is what most people are expecting -- replace every > >> reference to objects in the old module with references to the new > >> objects. The problem becomes a near impossibility when those > >> references are scattered throughout a multi-module program. You could use a class instead of a module. I have done that kind of thing with classes and weakrefs. By the way, it kind of surprises me that no one has mentioned weakref in this thread. It's not too hard to keep a list of weakrefs, and everytime an object is created, you register it with that list. Now, when the new class comes in (e.g. via reload(),) you get the list of weakrefs of the existing objects, and re-assign their __class__, and voila, dynamic change of class behavior. Of course, if you spend some time and push this feature into the metaclass, everytime becomes even easier. But it is true that in Python you have to implement dynamic refreshing of behavior (module or class) explicitly, whereas in Ruby, as I understand, class behavior refreshing is automatic. David MacQuigg wrote in message news:... > > I agree, most programs should not have 'reload()' designed in, and > those that do, should be well aware of its limitations. I'm concerned > more about interactive use, specifically of programs which cannot be > conveniently restarted from the beginning. I guess I'm spoiled by HP > BASIC, where you can change the program statements while the program > is running! (half wink) Edit-and-continue. Which is kind of important. For instance, I often have to load in tons of data from the database, do some initial processing, and then do the actual calculations. Or in game programming, where you have to load up a lot of things, play quite a few initial steps, before you arrive at the point of your interest. Now, in these kinds of programs, where the initial state preparation takes a long time, you really would like some "edit-and-continue" feature while developing the program. For GUI programs, edit-and-continue is also very helpful during development. And for Web applications, actually most CGI-like programs (EJB in Java jargon, or external methods in Zope) are all reloadable while the web/app server is running. Very often you can do open-heart surgery on web/app servers, while the website is running live. > Here is a use-case for classes. I've got hundreds of variables in a > huge hierarchy of "statefiles". In my program, that hierarchy is > handled as a hierarchy of classes. If I want to access a particular > variable, I say something like: > wavescan.window1.plot2.xaxis.label.font.size = 12 > These classes have no methods, just names and values and other > classes. "State file" reminds me of a programming paradigm based on REQUEST and RESPONSE. (Sometimes REQUEST alone.) Basically, your program's information is stored in a single "workspace" object. The advantage of this approach is: (1) All function/method calls at higher level have unique "header", something like f(REQUEST, RESPONSE), or f(REQUEST), and you will never need to worry about header changes. (2) The REQUEST and/or RESPONSE object could be serialized and stored on disk, or passed via remote calls to other computers. Since they can be serialized, you can also intercept/modify the content and do unit testing. This is very important in programs that take long time to build up initial states. Basically, once you are able to serialize and cache the state on disk (and even modify the states offline), then you can unit test various parts of your program WITHOUT having to start from scratch. Some people use XML for serialization to make state modification even easier, but any other serialization format is just as fine. This approach is also good when you want/need some parallel/distributed computing down the future, since the serialized states could be potentially be dispatched independently. Today's file access time is so fast that disk operations are often being sub-utilized. In heavy numerical crunching, having a "workspace" serialization can make development and debugging a lot less painful. > If I reload a module that changes some of those variables, I would > like to not have to hunt down every reference in the running program > and change it manually. In Python the appropriate tool is weakref. Per each class that matters, keep a weakref list of the instances. This way you can automate the refresing. I've done that before. regards, Hung Jung From bignose-hates-spam at and-benfinney-does-too.id.au Thu Mar 18 07:52:37 2004 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 18 Mar 2004 23:42:37 +1050 Subject: dictionary wart References: <6b17fa95.0403180441.a747b15@posting.google.com> Message-ID: On 18 Mar 2004 04:41:38 -0800, Jesper Olsen wrote: > Does python have a way of defining a dictionary default? > I think not, but are there any plans to incorporate it? > > But surprisingly, in python set_default is a dictionary method used > for looking up a key... (Probably you mean setdefault(), since there's no set_default attribute in any default Python object.) A dict, by design, has a defined set of keys, like all mapping types. Your "dictionary default" would change a dictionary so that it effectively had an infinite set of keys. It sounds like you want an iterator, rather than a dict. But without knowing the problem you're trying to solve, we can only guess at the solution. -- \ "I got a postcard from my best friend, it was a satellite | `\ picture of the entire Earth. On the back he wrote, 'Wish you | _o__) were here'." -- Steven Wright | Ben Finney From Mike at DeleteThis.Geary.com Fri Mar 26 12:25:30 2004 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Fri, 26 Mar 2004 09:25:30 -0800 Subject: monitoring a directory References: Message-ID: <1068psb86ujku63@corp.supernews.com> Tim Golden wrote: > There are two methods that I know of (apart from the simple > approach you describe). One is described in this recipe: > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/156178 > > This is simple to use, but falls down a bit if you have more than a few > files in the directory, since it doesn't know what's changed. It's fine if > you're just happy to rescan, say for a file-manager app. > > The other method, which is a bit more sophisticated, uses the > recently-added-to-pywin32 win32file.ReadDirectoryChangesW > functionality. > The other method, which is a bit more sophisticated, uses the > recently-added-to-pywin32 win32file.ReadDirectoryChangesW > functionality. Note that ReadDirectoryChangesW is available only on the NT platforms (XP, 2000, NT4, NT3.51 SP3). If you need portability to Win95/98/Me, you'll need to fall back to FindFirstChangeNotification as the cookbook recipe uses. Does win32file.ReadDirectoryChangesW provide a way to tell if it's available or not? I'd hope that win32file would simply not define ReadDirectoryChangesW on Win9x systems, so you could code like this: if win32file.ReadDirectoryChangesW: useReadDirectoryChangesW() else: useFindFirstChangeNotification() I don't see any mention of that in the docs, so you probably have to do a version check instead: import win32api, win32con def isWindowsNT(): return( win32api.GetVersionEx()[3] == win32con.VER_PLATFORM_WIN32_NT ) if isWindowsNT(): useReadDirectoryChangesW() else: useFindFirstChangeNotification() (To really do that right, you'd need to check the GetVersionEx return value more thoroughly to test for NT versions prior to 3.51 SP3, which don't have ReadDirectoryChangesW.) -Mike From claird at lairds.com Tue Mar 16 09:29:45 2004 From: claird at lairds.com (Cameron Laird) Date: Tue, 16 Mar 2004 14:29:45 -0000 Subject: Python and Microsoft Excel files References: Message-ID: <105e3qposs0h781@corp.supernews.com> In article , Eric @ Zomething wrote: > >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... > > All true--and in fact there are at least a few other approaches I know have been successful. benoit, do write back if you're still having difficulties. What currently interests me about this topic is the rumors I've been hearing that OpenOffice is exposing Python scriptability more and more. The target is not just that it work in a way we developers can figure out, but so easily as to entice end-users. I don't "get" OpenOffice culture yet, but I'm moving in that direction. -- Cameron Laird Business: http://www.Phaseit.net From look at www.covingtoninnovations.com.for.address Tue Mar 23 20:48:19 2004 From: look at www.covingtoninnovations.com.for.address (Michael A. Covington) Date: Tue, 23 Mar 2004 20:48:19 -0500 Subject: IDLE won't launch, and other frustrations References: Message-ID: My other curiosity is how it remembers that Tcl/Tk used to be in \WN16, which no longer exists. That information is not in the Registry. "Michael A. Covington" wrote in message news:PoidnWghOfqve_3dRVn_iw at speedfactory.net... > 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 qp at al.net Wed Mar 31 20:07:00 2004 From: qp at al.net (Qp) Date: Wed, 31 Mar 2004 20:07:00 -0500 Subject: How to connect multiple class instances to 1 Twisted factory? Message-ID: Is this even possible? I'm designing a simple chat and game client/server as an intro to Python, and it would be nice to represent the different interfaces (public chat room, private chat rooms, game instances) as totally seperate classes and show them in totally seperate windows. Given my basic understanding of Twisted, I see no way of doing this, and my whole GUI is contained in one class. The project is doable this way, it would just be much better with multiple class and multiple window seperation. If anyone can give me any direction, I would appreciate it very much. Thanks, Qp From and-google at doxdesk.com Tue Mar 9 05:12:43 2004 From: and-google at doxdesk.com (Andrew Clover) Date: 9 Mar 2004 02:12:43 -0800 Subject: PEP 328: Imports: Multi-Line and Absolute/Relative References: Message-ID: <2c60a528.0403090212.13d30795@posting.google.com> aahz at pythoncraft.com (Aahz) wrote: > from Tkinter import (Tk, Frame, Button, Entry, Canvas, Text > LEFT, DISABLED, NORMAL, RIDGE, END) +0. I don't see this as a particularly pressing problem, but the solution is logical and readable. > Because this represents a change in semantics, absolute imports will > be optional in Python 2.4 through the use of :: > from __future__ import absolute_import +1. (Can I have +2?) Accidental relative imports are an annoying stumbling point for new users, and a marginal security issue for everyone else. I'd like to see absolute_import introduced and made default as quickly as possible. > from .foo import > from ...foo import -1. Agree on the 'explicit is better...' criticism. This is just unclear. > from __pkg__.__pkg__ import +1. I don't think it's *that* ugly, or no more ugly than what it's trying to express. Nested parent-package-references should in any case not be that common. I assume you can also do a simple: import __pkg__.localmodule or just: import __pkg__ to get the package itself (__init__ module). I *much* prefer this to the existing implicit syntax. I'm not convinced I prefer the shortness of __pkg__ over __parent__ or __package__, but I don't really care much either way. > * Finally, some people dislike the way you have to change ``import`` > to ``from ... import`` when you want to dig inside a package. They > suggest completely rewriting the ``import`` syntax -0. Seems of extremely marginal benefit. -- Andrew Clover mailto:and at doxdesk.com http://www.doxdesk.com/ From roy at panix.com Tue Mar 9 12:25:50 2004 From: roy at panix.com (Roy Smith) Date: Tue, 09 Mar 2004 12:25:50 -0500 Subject: Working around a lack of 'goto' in python References: Message-ID: In article , Joe Mason wrote: > In article , Y2KYZFR1 wrote: > >> > Step away from the computer slowly . . . > >> > > >> > There is absolutely NO LEGITIMATE REASON to use GOTO in any modern > >> > language, ESPECIALLY Python, EVER! > >> > > >> > No stay away from computers until you understand how and why this is. > >> > >> > >> Bull. I've used goto's in similar cases as those presented. I have > >> found that in the right cases they are quite readable. Never had a > >> problem with them when used like this. > >> > >> So you didn't answer the question, how would you do this clearly in > >> Python? > >> > > > > same way you would do it in any other OBJECT ORIENTED language. Use > > the appropriate pattern. > > Which would be what? (No, it's not exceptions. Stay away from this > thread until you understand why it's not.) > > Joe OK, I'll bite. What's wrong with exceptions for breaking out of deeply nested loops? From ajsiegel at optonline.com Thu Mar 18 08:32:27 2004 From: ajsiegel at optonline.com (Arthur) Date: Thu, 18 Mar 2004 13:32:27 GMT Subject: asking for python community opinion about groovy References: Message-ID: On Wed, 17 Mar 2004 20:21:52 -0800, "Eric @ Zomething" wrote: > >Groovy is a pretty good name, I think. Python is pretty groovy. Maybe Groovy will be pretty Java? > The *.groovy file extensions I think are less then groovy. The Microsoft marketing folks are no doubt working on the C# response. .paisley? Art From max at alcyone.com Fri Mar 26 18:47:53 2004 From: max at alcyone.com (Erik Max Francis) Date: Fri, 26 Mar 2004 15:47:53 -0800 Subject: A 'Python like' language References: <40645d8f$0$10775$afc38c87@news.easynet.co.uk> <1068up4kn49778@news.supernews.com> Message-ID: <4064C129.1B8C937C@alcyone.com> Valentino Volonghi aka Dialtone wrote: > Anyway GvR just posted on the python-dev saying this: > > == > No, I want to reserve the leading dot for attribute assignment to a > special object specified by a 'with' statement, e.g. > > with self: > .foo = [1, 2, 3] > .bar(4, .foo) > == > > So another feature of this prothon (and a major one) is going to be a > python one > too. Not quite the same, as with Prothon it looks like it always relates to the self object, whereas in a `with' clause you can make it relates to any object you wish. -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE \__/ Drifting from woman-who-tries misconstrued / Shifting to woman-wise -- Lamya From andrew-pythonlist at puzzling.org Sat Mar 6 18:40:44 2004 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Sun, 7 Mar 2004 10:40:44 +1100 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: <20040306234044.GF1878@frobozz> On Sat, Mar 06, 2004 at 10:57:27AM -0800, Josiah Carlson wrote: > >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. That, and I suspect that reading strings in chunks, rather than 1 byte at a time, would be much faster also. -Andrew. From dieter at handshake.de Thu Mar 11 17:29:16 2004 From: dieter at handshake.de (Dieter Maurer) Date: 11 Mar 2004 23:29:16 +0100 Subject: PEP 328: Imports: Multi-Line and Absolute/Relative References: Message-ID: aahz at pythoncraft.com (Aahz) writes on 8 Mar 2004 15:24:56 -0500: > ... > Rationale for Parentheses > ========================= > > Currently, if you want to import a lot of names from a module or > package, you have to choose one of several unpalatable options: > > * Write a long line with backslash continuations:: > > from Tkinter import Tk, Frame, Button, Entry, Canvas, Text \ > LEFT, DISABLED, NORMAL, RIDGE, END Why is this bad? > * Write multiple ``import`` statements:: > > from Tkinter import Tk, Frame, Button, Entry, Canvas, Text > from Tkinter import LEFT, DISABLED, NORMAL, RIDGE, END > > (``import *`` is *not* an option ;-) > > Instead, it should be possible to use Python's standard grouping > mechanism (parentheses) to write the ``import`` statement:: Do do not explain why. > ... > Rationale for Absolute Imports > ============================== > > In current Python, if you're reading a module located inside a > package, it is not clear whether :: > > import foo > > refers to a top-level module or to another module inside the package. > To resolve the ambiguity, it is proposed that ``foo`` will always be a > module or package reachable from ``sys.path``. This will break lots of code... I do not like it at all. 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. Relative imports are essential to enhance locality. A package/module should in general not need to know where it is located inside the package hierarchy to access its subpackages. We make extensive use of this locality: We have myriads of Python packages which are essentially self contained (apart from references to the standard library). To avoid pollution of the Python path and name clashes, we often organize them for concrete projects into folders. To do this, the packages should not know where they are located. From sross at connectmail.carleton.ca Thu Mar 18 00:10:52 2004 From: sross at connectmail.carleton.ca (Sean Ross) Date: Thu, 18 Mar 2004 00:10:52 -0500 Subject: New to Python. References: Message-ID: "Sean Ross" wrote in message news:m3a6c.19554$E71.1405188 at news20.bellglobal.com... [snip] > # otherwise, you can go line by line > source = file('C:\Python23\Samples\Bob.txt') > tally = 0 > for line in source: > if "customer" in line: > tally += 1 > source.close() > [snip] # sorry, that should be source = file('C:\Python23\Samples\Bob.txt') tally = 0 for line in source: tally += line.count("customer") source.close() From xml-bindings-admin at gnome.org Mon Mar 8 06:50:06 2004 From: xml-bindings-admin at gnome.org (xml-bindings-admin at gnome.org) Date: Mon, 08 Mar 2004 06:50:06 -0500 Subject: Your message to xml-bindings awaits moderator approval Message-ID: <20040308115006.1134.29304.Mailman@moniker.gnome.org> Your mail to 'xml-bindings' with the subject Re: Your bill Is being held until the list moderator can review it for approval. The reason it is being held: Post by non-member to a members-only list Either the message will get posted to the list, or you will receive notification of the moderator's decision. From david at rebirthing.co.nz Thu Mar 25 06:14:17 2004 From: david at rebirthing.co.nz (David McNab) Date: Thu, 25 Mar 2004 23:14:17 +1200 Subject: Split a string by length In-Reply-To: References: Message-ID: <4062BF09.1070906@rebirthing.co.nz> Yermat wrote: >>> 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'] >> [...] > >>> import re > >>> re.findall(".{2}","aabbccdd") > ['aa', 'bb', 'cc', 'dd'] > >>> re.findall(".{2}","aabbccdde") > ['aa', 'bb', 'cc', 'dd'] Now, who's gonna benchmark these n different approaches? From nospam at freeworld.fr Fri Mar 5 09:15:34 2004 From: nospam at freeworld.fr (Lucas Branca) Date: Fri, 05 Mar 2004 14:15:34 GMT Subject: reg exp and octal notation Message-ID: Could someone explain me the difference between the results below? ## $cat octals.txt ## \006\034abc import re a= "\006\034abc" preg= re.compile(r'([\0-\377]*)') res = preg.search(a) print res.groups() loader = open('./octals.txt', 'r') b = loader.readline() preg= re.compile(r'([\0-\377]*)') res = preg.search(b) print res.groups() RESULTS ('\x06\x1cabc',) ('\\006\\034abc\n',) Many thanks Lucas From wmwd2zz02 at sneakemail.com Mon Mar 1 19:45:01 2004 From: wmwd2zz02 at sneakemail.com (Greg Ewing (using news.cis.dfn.de)) Date: Tue, 02 Mar 2004 13:45:01 +1300 Subject: How does Ruby compare to Python?? How good is DESIGN of Rubycompared to Python? In-Reply-To: References: Message-ID: Joe Mason wrote: > I didn't think Pascals and Basics supported function pointers at all, > but I haven't used them since high school, so maybe I just didn't > encounter them at the time. Some Basics would let you use the result of an expression as a line number in a GOTO or GOSUB, just in case there weren't already enough ways to turn your code into spaghetti. Those that didn't usually had ON...GOTO and ON...GOSUB statements that could be used to achieve much the same effect. Pascal lets you pass a procedure as a parameter to another procedure (but not store it in a variable, due to scope issues). It's likely this wouldn't have been mentioned in an introductory Pascal course, however, as it would have been considered a somewhat esoteric feature. Later Wirth languages (Modula, Oberon) do let you have procedure variables. But they can only point to top-level procedures, not nested ones. One step forward, one back... -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From jcarlson at uci.edu Wed Mar 31 15:06:15 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Wed, 31 Mar 2004 12:06:15 -0800 Subject: GUI Frameworks in Python? In-Reply-To: References: <8089854e.0403300518.3a180414@posting.google.com> Message-ID: > GUI's seem to be more like documents than programs, so I wonder why > we're not considering more declarative type interface builders. Is > there such a thing, maybe that writes out a standard specification > file instead of code? If it were XML, you could write a XSL filter to > make the all the modifications you needed to accomodate a different > platform. Dude, you should really check out the wxXMLResource and wxXMLResourceHandler. I don't use XML to write GUIs, but if I did, those would be my savior. Download the wxPython demo and give it a look. - Josiah From tismer at stackless.com Mon Mar 29 07:58:05 2004 From: tismer at stackless.com (Christian Tismer) Date: Mon, 29 Mar 2004 14:58:05 +0200 Subject: Prothon Prototypes vs Python Classes In-Reply-To: <106ev65lpu59614@news.supernews.com> References: <106dukh7ncf9ad4@news.supernews.com> <106eo695a9t8820@news.supernews.com> <106ev65lpu59614@news.supernews.com> Message-ID: <40681D5D.70604@stackless.com> John Roth wrote: ... > 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. Yeah. And I have even no clue how to get multiple inheritance right with prototypes. -- 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 atulkshirsagar at yahoo.com Mon Mar 15 02:54:39 2004 From: atulkshirsagar at yahoo.com (Atul Kshirsagar) Date: Sun, 14 Mar 2004 23:54:39 -0800 (PST) Subject: TypeError: 'NoneType' object is not callable Message-ID: <20040315075439.16435.qmail@web40010.mail.yahoo.com> Hello, I am using Python 2.3.2 with a C++ extention DLL in muti-threaded environment. 1. For each new thread I create a separate sub-interpreter. 2. Each thread executes multiple python statements calling the class objects in my extention DLL. 3. Before each execution I import my extention module using; import myModule 4. I destoy each sub-interpreter at the end of that particular thread. 5. Python initialization and finalization happens in the main thread. I am observing that; As explained above when multiple threads are running. And as one of these threads finishes, in other running threads I start getting "TypeError: 'NoneType' object is not callable" error on the methods called on class objects in extention module. Does anyone know why this might be happening ? Is there any specific way I should be using Python and Extention modules in multi-threaded environment ? Any help is appreciated !!! Thanks, Atul Kshirsagar __________________________________ Do you Yahoo!? Yahoo! Search - Find what you?re looking for faster http://search.yahoo.com From egusenet at verizon.net Thu Mar 25 16:18:21 2004 From: egusenet at verizon.net (Eric) Date: Thu, 25 Mar 2004 16:18:21 -0500 Subject: [Way OT] Condorcet vs. IRV References: <95aa1afa.0403230250.4c9da7a2@posting.google.com> <1060m0593q1uo0d@news.supernews.com> <10637ibo30epo6f@news.supernews.com> <89feb3ba.0403241233.32ea8604@posting.google.com> <1gb7bj1.xgiqcjp3ro1iN%egusenet@verizon.net> Message-ID: <1gb7o9h.bppzlf33xb5sN%egusenet@verizon.net> Joe Mason wrote: > One interesting approach was brought up on the elections list just > before I stopped reading it. (Wait, don't I recognize your name from > there? You'd be more familiar with it than I, but I'll bring it up > anyway, on the assumption that there are other interested readers out > there.) > > Add an implicit "none" candidate to separate rankings of actual > preferences from least of the evils. Your first case becomes "A > C > > none > B", and the second (probably) "A > none > C > B". So in the > latter case, the voter is saying that they prefer C to B, but only if > forced to choose between them due to overwhelming preference by the rest > of the electorate. > > I'd be grateful if you can point me to a thorough analysis of this idea, > since it sounds reasonable to me but I don't really have the background > to evaluate it. You can find the full archives at: http://lists.electorama.com/pipermail/election-methods-electorama.com/ I used the grep expression: >[\s]*none[\s]*> to find various messages related to it. It does seem to be an interesting idea and one that I was unfamiliar with...I have not investigated it fully. Off the top of my head, the only inherent problem with it that I see is that what happens if 'NONE' turns out to be the Condorcet Winner? An election is about finding a winner, providing for a result where this would not occur seems problematic unless one is using a Condorcet method where a strict (but not necessarily unique) ordering of the candidates can be found, in which case one can just select the #2 person. One such method that I am aware of is MAM (http://www.alumni.caltech.edu/~seppley/). From anton at vredegoor.doge.nl Thu Mar 25 11:00:19 2004 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Thu, 25 Mar 2004 17:00:19 +0100 Subject: Split a string by length References: <4062BF09.1070906@rebirthing.co.nz> Message-ID: <40630318$0$147$3a628fcd@reader2.nntp.hccnet.nl> Yermat wrote: >Make it simple... Finally the chunklist or chunks are my favorite for >general chunk function. For string I would have use the regexp anyway... Functions can be arguments too. Combining that with making them optional and having a default: from itertools import islice def groupby(seq,n,exhaust = list): it = iter(seq) res = exhaust(islice(it,n)) while res: yield res res = exhaust(islice(it,n)) def test(): seq = [[],[],[],[],[]] print list(groupby(seq,2)) s = 'aabbccdde' print list(groupby(s,2,''.join)) if __name__=='__main__': test() output: [[[], []], [[], []], [[]]] ['aa', 'bb', 'cc', 'dd', 'e'] Anton From jcarlson at nospam.uci.edu Fri Mar 12 12:49:03 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Fri, 12 Mar 2004 09:49:03 -0800 Subject: Speed up loading and free memory... In-Reply-To: <40509cc2$0$289$626a14ce@news.free.fr> References: <4050244d$0$305$636a15ce@news.free.fr> <110320040725438317%bscholln@mac.com> <40509cc2$0$289$626a14ce@news.free.fr> Message-ID: > files must not be modified, index file contains on one line a key and an > offset which can be use to go directly to data file. Keep the index in memory. When you need to access a location that has an index in your data file: data = open('data_file', 'rb') data.seek() data.read() For most tasks, that should be fast enough. If you want to cache some recently read data, check this cookbook entry: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/252524 - Josiah From buzzard at urubu.freeserve.co.uk Fri Mar 19 22:58:03 2004 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Sat, 20 Mar 2004 03:58:03 -0000 Subject: Python / COM / Word Message-ID: Hello, I'm having a little trouble trying to automate Word (2002). I'm hoping to be able to create and process documents relatively independently of any existing open word documents. e.g. When I have an existing document open and I enter the following at the command line any documents I create are visible, until setting wordApp.Visible to False, when all the documents are hidden. >>> import win32com.client >>> wordApp = win32com.client.Dispatch('Word.Application') >>> wordApp.Visible True >>> wordApp.Visible = False Ideally I'd like to have independent 'Word instances', so I can hack around to my heart's content without jeopardising documents opened and created by some hapless user (which would also be me). At the very least I need to keep the documents I'm creating hidden, whilst leaving existing documents visible. Any ideas? Cheers. Duncan From fredrik at pythonware.com Sun Mar 14 12:32:38 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 14 Mar 2004 18:32:38 +0100 Subject: Scaling an ImageTk.PhotoImage References: Message-ID: James Anderson wrote: > I'm have a bitmap which I can display as an ImageTk.PhotoImage and would > like to display it and double or quadruple size. The bitmap itself is > generated inside my program, so converting it to another format isn't > really practical. Does anyone know an easy way to do this? did you mean Tkinter.PhotoImage? if you really mean ImageTk.PhotoImage, is there any reason you cannot just resize the original Image object, and wrap it in a new ImageTk.PhotoImage object? From piet at cs.uu.nl Thu Mar 11 09:56:41 2004 From: piet at cs.uu.nl (Piet van Oostrum) Date: 11 Mar 2004 15:56:41 +0100 Subject: Cgi: Print Text files with wordwrap! References: Message-ID: >>>>> "Dale Strickland-Clak" (DS) wrote: DS> If you send plain text, it will be presented exactly how you send it, line DS> breaks and all. DS> If you want it to wrap to the browser window, you have to make it look DS> like HTML. The bare minimum you can get away with is

tags where you DS> want new paragraphs - plus a head and a tail. And you should replace < > and & by < > and & -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP] Private email: P.van.Oostrum at hccnet.nl From steve at ninereeds.fsnet.co.uk Sat Mar 27 20:08:50 2004 From: steve at ninereeds.fsnet.co.uk (Stephen Horne) Date: Sun, 28 Mar 2004 02:08:50 +0100 Subject: A 'Python like' language References: <40645d8f$0$10775$afc38c87@news.easynet.co.uk> <1068up4kn49778@news.supernews.com> <58cb60lmovocadg9p3ghu39t4ga343gfvd@4ax.com> Message-ID: On Sat, 27 Mar 2004 13:07:51 -0600, Skip Montanaro wrote: >Tim Peters used to complain often enough that email messages I posted which >contained bits of Python code I typed into them contained mixtures of tabs >and spaces GET THEE BEHIND ME, SATAN!!! >Tim hasn't complained about that aspect of my Python since then. (Other >things, yes, but not tabs). When reading other peoples code, there is *always* something to complain about ;-) -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From peter at engcorp.com Tue Mar 16 15:34:10 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 16 Mar 2004 15:34:10 -0500 Subject: fox 1.2.x and FXPy In-Reply-To: <4e1cc86c.0403151008.669e2e45@posting.google.com> References: <4e1cc86c.0403151008.669e2e45@posting.google.com> Message-ID: Asier wrote: > Is there any plan to make bindings of the future fox toolkit 1.2.x for > python? New widgets, antialiased fonts and so on is a "Good Thing". > > GTK is a pain, wxpython is horribly slow, and tkinter doesn't have ^^^^^^^^^^^^^^^^^^^^^^^^^ Your experience is clearly at odds with what most other people report about wxPython. (And, I might add, about GTK, as far as I can tell, though I haven't used it myself.) -Peter From alexander.dejanovski at laposte.net Fri Mar 5 07:34:16 2004 From: alexander.dejanovski at laposte.net (Alexander DEJANOVSKI) Date: Fri, 05 Mar 2004 13:34:16 +0100 Subject: Retic EAI server : looking for contributors Message-ID: <5.1.0.14.2.20040305131817.01f331e8@127.0.0.1> For those who don't know Retic, it is an EAI solution that was formerly developed in Python, and now moved to Jython. (http://retic.sourceforge.net) The python releases of Retic came in the early days of the project and were pretty buggy. The Jython version has now a nice set of features and is gaining, step-by-step, fame over the internet (type "eai server" in google and you'll get it on the first pages). I've had to stop developing the Python version of Retic because of my inexperience in what the Python world offers as frameworks or communication modules (Twisted, Zope, and for sure many others I don't know). Two people recently offered me their contribution to restart Python Retic development. I think the Python community should have such software (call it EAI or ETL, the difference isn't always clear), which is heavily required in the enterprise world. Anyone willing to participate, at any level of contribution, is welcome and should contact me : alexander.dejanovski at laposte.net (please include Retic in the subject to get past my spam filter). The plan is to re-design PyRetic (the python version of Retic), basing it on mature Python frameworks (twisted) and to grow both PyRetic and JyRetic, thus, providing enterprise-class open source EAI to the Python community and the Java community at the same time. Hoping to ear from some of you real soon. Alexander PS : people thinking this is not a good initiative should feel free to tell me so (and explain why). From sross at connectmail.carleton.ca Sun Mar 28 12:21:15 2004 From: sross at connectmail.carleton.ca (Sean Ross) Date: Sun, 28 Mar 2004 12:21:15 -0500 Subject: Breakdown of approaches to PEP318 References: <7vD9c.318$1A6.114130@news20.bellglobal.com> Message-ID: One more: # [12] based on http://mail.python.org/pipermail/python-dev/2004-March/043613.html [publish_to_web] def foo(self): {spark_rule:"DOC:= HEAD BODY FOOT", url="/cgi-bin/directory/directory"} "doc string" body From alx5962NOSPAN at yahoo.com Tue Mar 2 14:32:51 2004 From: alx5962NOSPAN at yahoo.com (Alex) Date: Tue, 2 Mar 2004 20:32:51 +0100 Subject: variable name using a for References: <4044d7f3$0$4664$626a14ce@news.free.fr> <1049mi9ktod7o35@corp.supernews.com> Message-ID: <4044e177$0$24960$626a14ce@news.free.fr> Thank you very much for the reply! In fact I created a list in a variable and I have to create x numbers of butons, depending on how many values there's in the list. so in my code: for x in range(nbSujets): self.button1 = xbmcgui.ControlButton(50, 100, 40, 30, "B"+str(x) ) self.addControl(self.button1) But in fact I need self.buttonX as I need different actions on each button. And the dictionnary here doesn't help I think... I may find tricks to cheat, but it would make dirty code or bad results on screen... So any hint to make this work ? Thanks again Alex From littlejohn.75 at news.noos.fr Tue Mar 2 14:26:13 2004 From: littlejohn.75 at news.noos.fr (F. Petitjean) Date: 02 Mar 2004 19:26:13 GMT Subject: NT Services and EventLog problems References: Message-ID: <4044dfd5$0$28142$636a15ce@news.free.fr> On Mon, 1 Mar 2004 17:20:10 -0600, Larry Bates wrote: > 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 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') Second parameter seems too be a filepath, try to use raw strings : r'C:\Python22\Lib\site-Packages\win32\PythonService.exe' and launch regedit to check registry entries. > > Thanks in advance for any assistance. > Regards, From sean_berry at cox.net Thu Mar 25 21:12:22 2004 From: sean_berry at cox.net (sean) Date: Thu, 25 Mar 2004 18:12:22 -0800 Subject: How do i cast a string to be used as a module? Message-ID: <9kM8c.46388$Bg.39277@fed1read03> In article , sean at sands.beach.net (Sean Berry) writes: > I don't know that this partilarily bad programming, > but I was interested in doing the following. > > def functionname( module, var1, var2 ): > import module > > I would like to be able to pass the module name > as an argument and have the module imported as a result. > > For instance... functionname( os, "1", 234) > > Thanks for any help. Thanks for the help, and exec("import "+modname) does indeed import the module. But, what if I want to call a function from within this module that takes as an argument the name of a module. For example if I was making a module like the following import inspect def functionname( modname ): exec("import "+modname) s = inspect.getsource( modname ) return s How do I cast modname as a module name and not as a string? Thanks. From Pieter.Claerhout at Creo.com Tue Mar 2 11:20:03 2004 From: Pieter.Claerhout at Creo.com (Pieter Claerhout) Date: Tue, 2 Mar 2004 17:20:03 +0100 Subject: NT Services and EventLog problems Message-ID: <490316A24CC5D411ACD700B0D078F7F006603DCC@cseexch01.cse.creoscitex.com> Would you mind sharing the complete source code for this service? I guess there must be something wrong in there. 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 17:11 To: python-list at python.org Subject: Re: NT Services and EventLog problems I made the change, but get the exact same error message. I went back and checked the book again and it reads (on page 359): "The files PythonService.exe, win32evtlog.pyd, and win32service.pyd each have a set of generic messages. Each file has nine messages for each of the classes Error, Informational, Warning, and Success." I tried all three of these AND servicemanager.pyd and I can't make any of them work. Mark Hammond, are you out there anywhere? Regards, Larry "Pieter Claerhout" wrote in message news:mailman.14.1078214898.12614.python-list at python.org... > 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 > -- http://mail.python.org/mailman/listinfo/python-list From robichon at esrf.fr Mon Mar 22 05:02:51 2004 From: robichon at esrf.fr (MarieR) Date: 22 Mar 2004 02:02:51 -0800 Subject: Syntax of 'in' : searching a list for a string Message-ID: <6d6b80e0.0403220202.356f62fc@posting.google.com> Hi, Sorry for my newbie question: I want to check whether the string 'Remove' is present in a list 'supportList', but if I do if ('Remove') in supportList: or if 'Remove' in supportList: I get the error message 'in ' requires character as left operand. Thanks in advance for your help, Marie From geloilzi at hotmail.com Wed Mar 17 10:43:32 2004 From: geloilzi at hotmail.com (Gelo Ilzi) Date: Wed, 17 Mar 2004 17:43:32 +0200 Subject: simple http server Message-ID: I'm trying to implement a very simple http server with cgi functionality. The code is simple: import CGIHTTPServer, BaseHTTPServer httpd = BaseHTTPServer.HTTPServer(('',8000), CGIHTTPServer.CGIHTTPRequestHandler) httpd.serve_forever() I've created a subdir 'cgi-bin' which contains a python script. Now when I enter this directory, i.e., go to the url http://localhost:8000/cgi-bin/ my browser shows: Error response Error code 403. Message: CGI script is not a plain file ('/cgi-bin/'). Error code explanation: 403 = Request forbidden -- authorization will not help. Plain html pages are ok. It seems I misunderstand something very basical. Could somebody help me please. Thank you in advance. From http Thu Mar 11 07:31:03 2004 From: http (Paul Rubin) Date: 11 Mar 2004 04:31:03 -0800 Subject: Speed up loading and free memory... References: <4050244d$0$305$636a15ce@news.free.fr> Message-ID: <7x65db4lbs.fsf@ruckus.brouhaha.com> Look at the mmap and array modules. Mmap lets you directly access the disk files by mapping them into memory. The array module lets you read those big files into memory without the overhead of tuple or list structure (but of course your application must then interpret the contents). Beyond that, we need more specific info to make more concrete suggestions. From wmwd2zz02 at sneakemail.com Thu Mar 11 22:41:47 2004 From: wmwd2zz02 at sneakemail.com (Greg Ewing (using news.cis.dfn.de)) Date: Fri, 12 Mar 2004 16:41:47 +1300 Subject: Xemacs syntax highlighting In-Reply-To: <1d17eeb7.0403111721.7aae9a76@posting.google.com> References: <1d17eeb7.0403111721.7aae9a76@posting.google.com> Message-ID: Jay Davis wrote: > I use xemacs and syntax highlighting for my IDE, but I'm not a big > fan of the default syntax highlighting colors. For instance, > in 'def fun():' both 'def' and 'fun' are the same color. Funny you should mention this -- just today I set up some custom colours for xemacs. I have my keywords set to blue and function names to red (which is what it used to be like in an earlier version of xemacs, and I liked it better that way.) My .emacs file currently contains: (require 'font-lock) (set-face-foreground 'font-lock-function-name-face "red3") (set-face-foreground 'font-lock-keyword-face "blue3") (set-face-foreground 'font-lock-comment-face "dark green") (set-face-foreground 'font-lock-type-face "blue3") -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From vincent.salaun at zslide.com Wed Mar 24 10:15:12 2004 From: vincent.salaun at zslide.com (vincent Salaun) Date: Wed, 24 Mar 2004 16:15:12 +0100 Subject: zxJDBC driver error Message-ID: <4061A600.40001@zslide.com> hi all, i'm trying to use the zxJDBC module to work on my mySql database, but : >>> from com.ziclix.python.sql import zxJDBC >>> d, u, p, v = "jdbc:mysql://localhost/test", "user", "pass", "org.gjt.mm.mysql.Driver" >>> db = zxJDBC.connect(d, u, p, v) Traceback (innermost last): File "", line 1, in ? DatabaseError: driver not found any idea ? thx vince From edreamleo at charter.net Wed Mar 24 07:03:13 2004 From: edreamleo at charter.net (Edward K. Ream) Date: Wed, 24 Mar 2004 06:03:13 -0600 Subject: Decent way to trace resource leaks? References: <87r7vk7dnc.fsf@strauser.com> Message-ID: <1062u833j68aie6@corp.supernews.com> While you are waiting for the book to be written, here is a simple hack that can be useful: # WARNING: the id trick is flawed: newly allocated objects can have the same address as old objects. global lastObjectsDict objects = gc.get_objects() newObjects = [o for o in objects if not lastObjectsDict.has_key(id(o))] lastObjectsDict = {} for o in objects: lastObjectsDict[id(o)]=o As noted in the comment, this has a flaw, but so what? It will show you most of what has been allocated since the last time the code was executed. Naturally, you will put this code in a function of some kind... I think you will find that relatively simple traces, if called in judicious places, will be highly effective in finding out most of what is going on in even a complex app. You know more about your app than any general tool possibly can: use that knowledge! The easiest way to increase the signal-to-noise ratio in traces is to use strategies that are unique to your app. For example, rather than trying to "perfect" the code above in general, you can specialize the code to trace your app's most important data in a format that is most useful to you. Edward -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: Literate Editor with Outlines Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From richardshea at fastmail.fm Wed Mar 10 05:05:10 2004 From: richardshea at fastmail.fm (Richard Shea) Date: 10 Mar 2004 02:05:10 -0800 Subject: How to downgrade/remove ZODB (or any other module)? Message-ID: <282f826a.0403100205.5d6070e4@posting.google.com> Hi - I have just installed ZODB for the first time. However after I'd finished I realised that I'd installed a development release and not a stable release so I'd like to downgrade or remove the current installation and start again. I installed via a Windows installer from which I could extract a list of files and then manually remove (there are 290 files) but is there some less labourious way of removing a module ? Thanks Richard Shea. From skip at pobox.com Wed Mar 31 09:11:36 2004 From: skip at pobox.com (Skip Montanaro) Date: Wed, 31 Mar 2004 08:11:36 -0600 Subject: CSV to Browser Bookmark file In-Reply-To: References: Message-ID: <16490.53656.592454.606714@montanaro.dyndns.org> >>>>> "Bill" == Bill writes: Bill> I currently have all of my Bookmarks under WinXP in a PIM, which Bill> will allow me to export them as a CSV file ( fields are Bill> "Category,Page-Title,URL,Comments - all fields of no fixed Bill> length). Bill> Is there a program/script that will output the info from csv to a Bill> browser bookmark file - Any browser as I want to move the Bill> bookmarks from Windows to Linux - unfortunately the PIM wont run Bill> under Wine in Linux and I am not a programmer so I have no idea Bill> how to convert the file. I don't know what your output format is supposed to look like, but reading the input CSV file is trivial. Assuming it's named "mybookmarks.csv", you can read it and emit some HTML fragments using something like this: import csv rdr = csv.DictReader(file("mybookmarks.csv")) for row in rdr: print '%(Page-Title)s' % row There's going to be more to the output side of things than that. Save your browser's bookmarks as an HTML file and look at it for hints of what other print statements you need. Skip From jdhunter at ace.bsd.uchicago.edu Sat Mar 20 12:07:13 2004 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Sat, 20 Mar 2004 11:07:13 -0600 Subject: PyGTK: creating a pixbuf from image data In-Reply-To: (Edwin Young's message of "20 Mar 2004 07:51:55 -0800") References: Message-ID: >>>>> "Edwin" == Edwin Young writes: Edwin> That looks fine, but ideally I want to avoid having Edwin> complicated dependencies- I don't want my program to be one Edwin> of the ones that require you to download ten others just to Edwin> run them. Pygtk itself seems to be pretty widely Edwin> distributed in popular distributions, but Edwin> PyGTK-with-Numeric isn't. I brought this up with Cedric Gustin, the pygtk win32 installer distributer, because I need Numeric support for matplotlib, and he immediately built and uploaded pygtk for windows with Numeric (and will do likewise for future builds). http://www.async.com.br/faq/pygtk/index.py?req=show&file=faq21.012.htp JDH From antonyliu2002 at yahoo.com Fri Mar 5 05:16:05 2004 From: antonyliu2002 at yahoo.com (chad) Date: 5 Mar 2004 02:16:05 -0800 Subject: Parsing xml file using python References: Message-ID: <14b36d18.0403050216.ad3a7f5@posting.google.com> Hi, Thanks. I downloaded PyXML from sourceforge, but could not install it. When I double click the install file, it asks me to go next and choose the folder to install it, but then it gives me no choice to choose from. It seems the installer cannot get my file system info. I am using Python on Win2K. "David LeBlanc" wrote in message news:... > > 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 rdjdvd at inwind.it Mon Mar 29 01:24:09 2004 From: rdjdvd at inwind.it (RDJ) Date: 28 Mar 2004 22:24:09 -0800 Subject: FreeMindLicense - Used with Pyples (Interactive Python Examples) Message-ID: /\/\ /\ /\ / \/ \ | \ | \ \ -----------/ O \------- ----------/_ /------- -----------/_/ /-------- ===========\____/========= ========================== *** FreeMindLicense *** *********************** 1. The free mind create the free product. 2. The product is any human creation: the text, the program, the image, the music, the video, the...(other). 3. My product is your product. You can do any action with my product: to copy, to change, to publish, to distribute, to sell, to...(other), but you must use this license. 4. Your product is my product. I can do any action with your product: to copy, to change, to publish, to distribute, to sell, to...(other), but I must use this license. 5. From free source to free product, to...(other). --- FreeProductsList --- Any field is optional: Date: [yyyy/dd/mm] Type: [image,music,program,text,video,...] Name: [product name] Description: [short description] Author: [name or nick-name] Site: [www.first.org,www.second.org,...] E-mail: [first at email.org,second at email.org,...] Other: [short text] -------------------------------------------------- Date: 2004/03/27 Type: image,program,text Name: pyples Description: Interactive Python Examples Author: RDJ Site: spazioinwind.libero.it/rdjhome E-mail: rdjdvd at inwind.it -------------------------------------------------- From mcfletch at rogers.com Wed Mar 31 17:24:12 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Wed, 31 Mar 2004 17:24:12 -0500 Subject: Metaclass presentation + code samples online Message-ID: <406B450C.3090509@rogers.com> For the 99.999% of you not reading my blog, I have posted my metaclass presentation from PyCon 2004 along with code samples for the same on my site. You can get them here: http://members.rogers.com/mcfletch/programming/ Have fun all, Mike _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From bart3rNOSPAM at clinicdesignNOSPAM.com.au Thu Mar 25 22:58:50 2004 From: bart3rNOSPAM at clinicdesignNOSPAM.com.au (bart3rNOSPAM at clinicdesignNOSPAM.com.au) Date: Fri, 26 Mar 2004 14:28:50 +1030 Subject: http request doesn't work! Message-ID: Could someone please let me know what i'm doing wrong here: #!/usr/bin/python import httplib WEB_SITE = 'adsl.internode.on.net' #WEB_SITE = 'www.google.com' #PAGE_PATH = '/about.html' PAGE_PATH = '/htm/un-metered-sites-ip-list.htm' http = httplib.HTTP(WEB_SITE) http.putrequest('GET', PAGE_PATH) http.putheader('Accept', 'text/html') http.putheader('Accept', 'text/plan') http.endheaders() httpcode, httpmsg, headers = http.getreply() print 'msg: ' + httpmsg print httpcode doc = http.getfile() data = doc.read() doc.close() print data The output of the above is different if you go to the following in your browser: http://adsl.internode.on.net/htm/un-metered-sites-ip-list.htm Whats my problem?!?!??! From ed-no at spam-eepatents.com Wed Mar 24 19:24:23 2004 From: ed-no at spam-eepatents.com (Ed Suominen) Date: Wed, 24 Mar 2004 16:24:23 -0800 Subject: Globbing in List Search? References: <4LGdndsGmLrdv__dRVn-tw@centurytel.net> Message-ID: To answer my own post, k = x.index(filter(lambda x: x.startswith(term), x)[0]) where "term" acts like it has an implicit "*" at the end. Any better ideas? Ed Suominen wrote: > Does Python have a globbing-type list search capability, like "lsearch > -glob $list" in TCL? From smallbee at rediffmail.com Mon Mar 8 07:51:47 2004 From: smallbee at rediffmail.com (Somesh Bartakkay) Date: 8 Mar 2004 04:51:47 -0800 Subject: Python distribution as secondary language ..??? Message-ID: <8f198e47.0403080451.541d6ef2@posting.google.com> i have developed a small exe prgram with VC++ 6 on win32 platform, in which i used python as SECOndary language.(IT IS EMBEDED). Now i want to know how to distribute my exe application to machine on which Python in installed.plz let me know WHICH dlls,pyd files required to distribut ? Here plz note that i embeded python with vc++ i used py2exe for pure python distribution..but confused with vc++ 6.0 thanX in +vance From paddy3118 at netscape.net Tue Mar 2 14:00:25 2004 From: paddy3118 at netscape.net (Paddy McCarthy) Date: 2 Mar 2004 11:00:25 -0800 Subject: Is Eric S Raymond still a "Pythoneer" References: <2ae25c6b.0403020006.6b99e590@posting.google.com> Message-ID: <2ae25c6b.0403021100.400af290@posting.google.com> paddy3118 at netscape.net (Paddy McCarthy) wrote in message news:<2ae25c6b.0403020006.6b99e590 at posting.google.com>... > I just re-read "Why Python?" at > http://www.linuxjournal.com/article.php?sid=3882 > The article is from 2000 and shows how a programmer who programmed in > many programming languages, and who wrote compilers and interpreters, > was introduced to Python and came to like it. > > 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? > > I'm going to add the article to my bookmarks for ammo in trying to > change my strictly Perl workplace to at least consider Python. > > (I should add that I do know of most of the good advocacy resources > available, I've collected them from answers to other peoples posts, > thanks). > > Thanks again, Paddy. 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. Thanks for the other replies, Ill follow them up to. From NAVMSE-SERVER2 at computery.ru Tue Mar 2 05:37:18 2004 From: NAVMSE-SERVER2 at computery.ru (NAVMSE-SERVER2) Date: Tue, 2 Mar 2004 13:37:18 +0300 Subject: Norton AntiVirus detected a virus in a message you sent. The infected attachment was deleted. Message-ID: Recipient of the infected attachment: SERVER2, First Storage Group\Mailbox Store (SERVER2), bladerunner/???????? Subject of the message: Your order was registered One or more attachments were deleted Attachment ps.scr was Deleted for the following reasons: Virus W32.Mydoom.F at mm was found. From jdhunter at ace.bsd.uchicago.edu Tue Mar 30 15:24:57 2004 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Tue, 30 Mar 2004 14:24:57 -0600 Subject: test for nan Message-ID: I have a C extension module that is returning some doubles. When the doubles get out of range, the numbers print as 'nan'. Is there a better way to test for NaN than str(p1)=='nan' where p1 is a float? python2.3 Thanks, John Hunter From jdhunter at ace.bsd.uchicago.edu Wed Mar 3 14:01:57 2004 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Wed, 03 Mar 2004 13:01:57 -0600 Subject: building portable win32 extensions Message-ID: I'm using mingw to build python extensions. To ensure maximum portability across windows platforms (98, ME, NT, XP) is it a good idea to build on a lowest common denominator system, eg, 98, or should it not matter? I'm worried, for example, that windows ME might have a funny system library that end up in the pyd and other systems will fail to link. John Hunter From mogmios at mlug.missouri.edu Mon Mar 29 08:38:18 2004 From: mogmios at mlug.missouri.edu (Michael) Date: Mon, 29 Mar 2004 05:38:18 -0800 Subject: Prothon Prototypes vs Python Classes In-Reply-To: <40681B2B.2080106@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> Message-ID: <406826CA.6070107@mlug.missouri.edu> > 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. > Becuase there are editors which default to tab==4 spaces > and some with tab==8 spaces. I have this problem still all > over the place in the C code of the Python implementation. > I like tab==4 spaces quite much, and it is the default for > Visual Studio. But sources which are edited in Linux most of > the time, seem to default to tab==8 spaces. > It is very convenient, I agree. But I would like to teach > my editor to convert to tabs for editing only, and then > change them back to spaces on saving. :-) Who cares how an editor displays code as long as it's smart enough not to assume things and change that code. Save a tab as a tab and you can display the tab anyway you want and it shouldn't matter. The whole idea of having to make your editor imagine tabs when editing and save as spaces seems to be an example of needless checking and repair as you mentioned before. Why not just use tabs? Whatever is more convient for editing should be the standard. Anyone that wants a 1 space tab is free to configure their editor to make tabs take one space. It'd be incorrect to set your editor to make a space take four or eight spaces if actting as indention. If I enter a tab in my editing of code then it is saved to the file as a tab and not as any number of spaces at all. How is that undesirable? I'd be just as annoyed if I typed a given number of spaces and found it saved as a tab in my file. Either behavior would indicate a poorly designed editor. > Well, I don't think it is about removing a feature, but > about removing a problem. Which basically cannot be completely > solved, as long as tabs and different editors exist... 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. From joe at notcharles.ca Sun Mar 28 01:53:25 2004 From: joe at notcharles.ca (Joe Mason) Date: Sun, 28 Mar 2004 06:53:25 GMT Subject: Prothon, metaclasses, Zope [Was: A 'Python like' language] References: <95aa1afa.0403272243.78d60724@posting.google.com> Message-ID: In article <95aa1afa.0403272243.78d60724 at posting.google.com>, Michele Simionato wrote: > 1. The metaclass can raise the error *before* the metaclass is created, > whereas the function works a posteriori, *after* the overriding is done; > if find it to be conceptually unsatisfactory, I don't want to create > a class just to throw it away. The alternative is to use a class factory, > but then I have just re-invented a metaclass with an ugly call syntax. In this case, you shouldn't worry about that, since presumably you're just using it during development so it'll never be called anyway in the release version. > 2. The metaclass can be inherited, so the check is automatic for all children; > on the contrary, I have to call the function by hand each time I define > a new class. This means writing twice the class name, which is error > prone if I later rename the class and I forget to update the function > call. You could just put the function call in your base class's __init__ method. (Or, in fact, put the code from that call directly there, if you only care when you inherit from the one Zope class.) > BTW, I wonder how Prothon would solve this problem, i.e. selectively > forbidding the overriding of names, with an easy of use/elegance > comparable to the Python metaclass solution. __init__ method, I believe. But I just realized something - how does Prothon (or prototyped languages in general) handle multiple inheritance or mixins? > [*] I would be curious to know if Guido decided to expose metaclasses in > Python since he noticed that they were already being used in real applications > such as Zope (in some hidden form), or if there was some other reason. http://www.python.org/2.2/descrintro.html#metaclasses has some references you might find interesting. Joe From wmwd2zz02 at sneakemail.com Tue Mar 16 20:10:42 2004 From: wmwd2zz02 at sneakemail.com (Greg Ewing (using news.cis.dfn.de)) Date: Wed, 17 Mar 2004 14:10:42 +1300 Subject: Is Python type safe? In-Reply-To: References: <221d8dbe.0403161043.52406195@posting.google.com> Message-ID: Roy Smith wrote: > Neither C++ nor Python will let you add the integer 3 to the string > "four", Actually, C++ (and C) will: cosc353% cat foo.c #include main() { const char *s = "four" + 3; printf("%s\n", s); } cosc353% g++ foo.c -o foo cosc353% foo r -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From smallbee at rediffmail.com Tue Mar 23 08:30:23 2004 From: smallbee at rediffmail.com (Somesh Bartakkay) Date: 23 Mar 2004 05:30:23 -0800 Subject: py2exe,cx-freez and pyGTK on win32 !!! Message-ID: <8f198e47.0403230530.46b6b90a@posting.google.com> hello , i developed a small app with pygtk 2.2 python 2.3. while Running standalone exe its giving ERROR ... ''''''''''''''''' D:\Somesh\pycad-sep\dist>demo Traceback (most recent call last): File "demo.py", line 4, in ? File "C:\Python23\lib\site-packages\gtk-2.0\gtk\glade.pyd", line 4, in ? ImportError: cannot import name Widget from gtk._gtk ''''''''''''''' this error is in both cases of exe generated with Py2exe and cx-freeze plz try to get me out of this problem !! ThyaX in +vance ! somesh From buzzard at urubu.freeserve.co.uk Thu Mar 4 14:38:57 2004 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Thu, 4 Mar 2004 19:38:57 -0000 Subject: [Numeric] why is Float32 incorrect for ufuncs? References: <404757b9$1@maser.urz.unibas.ch> Message-ID: "Curzio Basso" wrote in message news:404757b9$1 at maser.urz.unibas.ch... > Hello everyone, > > I am a beginner with Numerical Python, and there is a thing I do not > understand in the behaviour of the ufuncs. Maybe someone can enlighten me. > > Why is the following not working? > > >>> import Numeric > >>> a=Numeric.ones((2,2),Numeric.Float32) > >>> a > array([[ 1., 1.], > [ 1., 1.]],'f') > >>> a/=2 > Traceback (most recent call last): > File "", line 1, in ? > TypeError: return array has incorrect type > > If I use Numeric.Float64 as typecode everything works fine, but I do not > understand why is this needed. > > thanks for your help. curzio. > What *I think* is happening is that Numeric is converting the integer to a rank-0 array of type Int64 before division. The consequence is an upcast to Float64 for the return array. Look for 'Coercion and Casting' in the Numeric documentation. Cheers. Duncan From fpetermaas at netscape.net Thu Mar 18 14:46:04 2004 From: fpetermaas at netscape.net (Peter Maas) Date: Thu, 18 Mar 2004 20:46:04 +0100 Subject: '1' + 1 ==> True ??? In-Reply-To: <7ifzc62ovr.fsf@enark.csis.hku.hk> References: <7ifzc62ovr.fsf@enark.csis.hku.hk> Message-ID: Isaac To schrieb: > Peter> That's not really a conversion. '1' is 0x31 in memory and 0x31 > > Peter> 1. > > That's really not a conversion, but not because '1' is 0x31 in memory. It > is because C defines '1' to be equivalent to (in every respect, including > type) the integer to represent it---which is 49 (0x31) in most computers we > use today. The mapping of '1' to 0x31 is defined by ASCII which is used by C. If a C instruction retrieves a char it reads data from an adress and if there is a 0x31 stored at the adress C treats it as '1'. My short form of this is "'1' is 0x31 in memory". > Peter> Unlike C, Python's comparison results for different types are > Peter> defined in a strange but archicture independent way, see Python > Peter> Library Reference 2.3.3. > > Also untrue. Python's comparison result is dependent on implementation, so > even in the same computer, two different Python implementation can give you > different results; and you cannot make any assumption in different > platforms. I didn't talk about different programs but different machines (architecture). Python Standard Library (Comparison) has this Implementation note: Objects of different types except numbers are ordered by their type names; Mit freundlichen Gruessen, Peter Maas > Regards, > Isaac. -- 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 alet at librelogiciel.com Sun Mar 21 12:34:30 2004 From: alet at librelogiciel.com (Jerome Alet) Date: Sun, 21 Mar 2004 18:34:30 +0100 Subject: ANN: PyKota v1.18 is out ! Message-ID: Hi there I'm pleased to announce that PyKota v1.18 Final is out. PyKota is an entirely Python written, GNU GPLed, centralized, full featured, internationalized, and easily extensible, print quota and accounting solution for CUPS and LPRng under Unix like systems like GNU/Linux. PyKota can store its datas either in PostgreSQL or in OpenLDAP, and integrating PyKota with an existing LDAP directory is really easy thanks to PyKota's unprecedented flexibility. Summary of Changes : - Many bug fixes, especially wrt users and printers groups, which seem to work fine now, even with deeply nested printers groups. - New command line tools : - pkprinters : use this to add/delete/manage printers or printers groups. It is much more faster than edpykota to manage printers. - pkhint : preliminary work on installation automation. It is a configuration helper (CUPS only for now) - Several speed and CPU load improvements by suppression of unneeded database queries wherever possible - Improved documentation - Italian translation added - Preliminary work on relationnal database independance - Sample reports made with OpenOffice are included - Better Debian integration, and preliminary work on Debian packaging - New directives in pykota.conf : - maildomain : sets the mail domain to use when email address for user is not set and username at smtpserver is not allowed. - prehook : allows to launch any command at the beginning of the job. - posthook : same, but at the end of the job. - PyKota now exports much of its internal state through environment variables accessible from any external command (mailers, accounters, requesters, pre and post hooks, ...) The complete list of changes is available from : http://www.librelogiciel.com/software/PyKota/action_News IMPORTANT : Before upgrading from an older version, please : - Double check the toplevel README and the FAQ. - Double check the sample configuration files for new options and features. Learn more about PyKota, see live reports or screenshots, download the CVS version or buy yearly Official Packages subscription from : http://www.librelogiciel.com/software/PyKota/action_Presentation Thank you for reading. Jerome Alet -- "A non-free program is a predatory social system that keeps people in a state of domination and division, and uses the spoils to dominate more." - RMS From john.burton at jbmail.com Sun Mar 21 07:58:09 2004 From: john.burton at jbmail.com (John Burton) Date: Sun, 21 Mar 2004 12:58:09 +0000 Subject: Socket access to low numbered ports? In-Reply-To: References: <405c22fd$0$63627$5a6aecb4@news.aaisp.net.uk> <105os7t5ve30i73@corp.supernews.com> <405c772e$0$63620$5a6aecb4@news.aaisp.net.uk> Message-ID: <405d9161$0$63621$5a6aecb4@news.aaisp.net.uk> Tuure Laurinolli wrote: > John Burton wrote: > >> Dan Boitnott wrote: >> > John Burton wrote: >> > Well it does - thanks for that - except that setting the set uid >> bit on >> the script doesn't seem to actually work. This is on gentoo linux. > > > Indeed it doesn't. You have to use a wrapper of some sort. Google should > help you on finding one. Ok, I'm now using sudo to launch the application which just opens the listening sockets and then calls os.setuid to set the uid back to an unprivilaged account. It seems to work fine. Thanks for the help. From jgrahn-nntq at algonet.se Fri Mar 12 14:29:25 2004 From: jgrahn-nntq at algonet.se (Jorgen Grahn) Date: Fri, 12 Mar 2004 19:29:25 +0000 (UTC) Subject: Python style guidelines References: <3064b51d.0403101112.3449e987@posting.google.com> <4050EAA3.9010807@wberry.org.x> Message-ID: On Thu, 11 Mar 2004 17:39:31 -0500, Will Berry wrote: > Style guidelines and coding standards are the devil! I would enjoy > nothing more than reading an ACM paper entitled "Coding Standards > Considered Harmful". I've never seen a single real-life case where the Not an ACM paper, but ... http://www.algonet.se/~jgrahn/anticodingrules.pdf Disclaimer: it's an unfinished draft, and it was written in anger during a period when I was ruled by a really stupid standard. > argument for coding standards for that reason. Or, for large projects > and open source projects, have an auto-styler run on all checked-in > code. That would at least do away with the spaces-or-tabs problem. Argh! An auto-styler is the only thing I would hate more than a coding standard... Coding style is style. People have style, programs do not. /Jorgen PS. I just read that PEP for the first time, and it's one of the most reasonable style guides I've seen (meaning I already did most of that ;-). -- // Jorgen Grahn Would You Let One Marry Your Sister?'' From jcarlson at nospam.uci.edu Sun Mar 28 21:17:07 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Sun, 28 Mar 2004 18:17:07 -0800 Subject: How To capture an id into an array.. In-Reply-To: References: Message-ID: BALAJI RAMAN wrote: > 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... The poor way of doing it is... class V(E): check = [] def __init__(self): print id(self) self.check.append(id(self)) self.val = None The reason it is poor is because if an object is deleted, its id could be reused. Instead, you should use weak references. I've found the following to be useful on occasion... import weakref class V(E): check = {} def __init__(self): #create a weak reference to yourself #place it in the __olist self.check[id(self)] = weakref.ref(self) def __del__(self): del self.check[id(self)] def __repr__(self): return str(id(self)) def get_olist(self): #this creates a hard reference to every object return [o() for o in self.check.values() if o() is not None] - Josiah From godoy at ieee.org Wed Mar 24 07:13:13 2004 From: godoy at ieee.org (Jorge Godoy) Date: Wed, 24 Mar 2004 09:13:13 -0300 Subject: Suitability of python to specific project References: Message-ID: On Ter 23 Mar 2004 14:22, hyperbob at walla.co.il wrote: > Regarding the small bugs such as the ones that I found in urllib (that the > proxies were ill retrieved and the whole operation failed on a seemengly > non-related problem at a specific computer): what worries me more than the > existence of small bugs, is their tendecy to appear on one computer and > not on another, as in my example. How common is that in the python library > in comparison to coherent bugs? Also, how fast are such small bugs usually > fixed in the official release (both in case that I fix them myself and in > case that I only complain)? I'm not sure those are Python failures or bugs. We have a client here that has a network of Win98 machines (more or less 20 machines), all with the latest updates, installed from their respective installation CDs. And some machines can't use passive FTP while other can. We even tried installing one of those machines that can't use FTP with a CD of one that can and... it didn't worked. Funny, isn't it? So if I was writing something that relied on Internet FTP access, and if my program used standard Win98 resources, my application would fail. Would it be my fault? How could I solve it without too much work? So, repeating my initial phrase, I don't know whose fault it is. -- Godoy. From claird at lairds.com Sun Mar 14 14:03:08 2004 From: claird at lairds.com (Cameron Laird) Date: Sun, 14 Mar 2004 19:03:08 -0000 Subject: How to read between xml tags? References: Message-ID: <1059b3cg50f0b4f@corp.supernews.com> In article , Anthony Liu wrote: >Yes, Miki, your code works great to strip the XML tags >and return a clean text file. > >But the thing is, I want to process the part between >tags each time it is read in. > >For example if I have a tagged XML doc like so: > >Something here >something else here > >I want to get "Something here" in one read operation >and process it before I move on to get "Something else >here". > >So any way to go about this? . . . >> I think the xml.sax module is what you're looking >> for. >> A small, briefly tested something might be: >> --- >> #!/usr/bin/env python >> >> from xml.sax.handler import ContentHandler >> from xml.sax import parse >> >> class ArticleHandler(ContentHandler): . . . If I understand you, that's *exactly* what Miki has provided you. His code reads up until the first tag is closed, then hands over control to the "callback" he's provided as an example. If you want something different to happen, just substitute in your own action. -- Cameron Laird Business: http://www.Phaseit.net From ville at spammers.com Tue Mar 23 01:43:26 2004 From: ville at spammers.com (Ville Vainio) Date: 23 Mar 2004 08:43:26 +0200 Subject: Python for large projects References: <7xisgxt51r.fsf@ruckus.brouhaha.com> <105uk4987h7tm77@corp.supernews.com> <7xad28313c.fsf@ruckus.brouhaha.com> Message-ID: >>>>> "Peter" == Peter Hansen writes: Peter> (Hmm... maybe a BOF for "serious s/w engineering with Peter> Python" or something like that?) We're living in interesting times, what with all the noise created by Havoc Pennington in http://ometer.com/desktop-language.html I think Python might have a great shot as a more "official" strategic direction for Linux desktop app development, since it's quite possible their neither Mono or Java gets picked because they are encumbered. Some lobbying is needed, of course. Getting something like IBM or Novell (well, Novell is probably stuck w/ Mono... IronPython, anyone?) officially endorsing and sponsoring Python would be oh-so-cool. -- Ville Vainio http://tinyurl.com/2prnb From dippyd at yahoo.com.au Tue Mar 30 00:57:52 2004 From: dippyd at yahoo.com.au (Steve) Date: Tue, 30 Mar 2004 15:57:52 +1000 Subject: easy verbose in functions References: Message-ID: <40690C60.20509@yahoo.com.au> Hello Pascal, Pascal wrote: > Hello, > > I've a function like this: > def myfunction(data, verbose = False): > dothis... > if verbose: print 'I do this' > dothisother > if verbose: print 'I do this other' > ... > > How can I do to exclude eachtime the `if verbose` statement? > > I tried `print verbose and 'I do this'` but it's printing `False`. > So I tried with `verbose = None` in the definition, but it's printing None! I'm not sure exactly what you are doing because I can't duplicate your results. But I am guessing that what you are doing is passing a string "False" instead of the boolean constant False. The constant False is only defined in Python 2.2 and higher. You can put something like this at the beginning of your program to make sure that False and True are defined no matter what version of Python you are using: try: if False: pass except: False = 0 True = not False Notice the difference between a string and a boolean value: >>> print False; print "False" 0 False >>> type(False); type("False") Likewise None is not the same as "None". The way I would handle verbose printing in functions is to factor out the "verbosity" from the function logic: def verboseprint(s, verbose): if verbose: print s def myfunction(arg, verbose=False): dothis verboseprint("Do this", verbose) dothat verboseprint("Do that", verbose) That way, if there is a bug in your handling of verbose printing, you only need to fix it in one place. If you decide to change verbose printing to (say) using a log file, you only need to change one place. The statement: print verbose and "Do this" will not work. If verbose is True, then the term (verbose and "Do this") will evaluate to "Do this", and Python will print what you expect, namely "Do this". But if verbose is False, then the term (verbose and "Do this") will evaluate to False, and Python will then print False, which is not what you want. -- Steven D'Aprano From jaustin at post.harvard.edu Mon Mar 22 18:40:38 2004 From: jaustin at post.harvard.edu (Jess Austin) Date: 22 Mar 2004 15:40:38 -0800 Subject: mutable list iterators - a proposal References: <5d83790c.0403170242.759ac8d9@posting.google.com> <5d83790c.0403211210.703991c2@posting.google.com> Message-ID: I hope I'm not belaboring the point. b-) python at rcn.com (Raymond Hettinger) wrote in message news:<5d83790c.0403211210.703991c2 at posting.google.com>... > 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. This seems like good advice, but the current implementation of lists in Python doesn't follow it wrt modifying while iterating. People who remember all the footnotes to the docs expect one thing, and the rest of us expect something else. Maybe it would be better if list iterators puked in the same fashion that dict iterators do immediately after the dict instance is modified. Then users wouldn't start by appending to lists over which they are iterating (which works, although I'm not sure it will with the new reversed iterators), and go on to expect to be able to modify lists in a general fashion. > The code is an improvement, but still suffers from the definitional > ambiguity mentioned above. I believe this is inescapable. Consider a Thanks. I feel that in allowing an operation that was previously implicitly forbidden, one can be forgiven if there is some subtlety to the semantics of the operation. But that's debatable. > 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. My original use case was 3 classes in 30 lines, not including the subclassing of list. I thought the subclassing of list was fairly componentized, and it would be unnecessary if the list implementation were modified as I've suggested. That doesn't look too likely. b-) I'll certainly be using collections.deque after I install 2.4! > > import itertools > > Hey, hey, I love to see people using my module ;-) I love to use it. Iterators and list comprehensions were good, but coupled with itertools they are great. Thanks, Raymond, for all you've done for Python. later, Jess From has.temp2 at virgin.net Mon Mar 29 05:10:41 2004 From: has.temp2 at virgin.net (has) Date: 29 Mar 2004 02:10:41 -0800 Subject: Prothon Prototypes vs Python Classes References: <106dukh7ncf9ad4@news.supernews.com> Message-ID: <69cbbef2.0403290210.4b55cfff@posting.google.com> Harald Massa wrote in message news:... > 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? Anything's possible, but would you want to? Aside from increasing language complexity, introducing a second OO programming model would violate Python's core "one way to do it" philosophy. Adding features is easy. It's leaving them out that's hard. ;) From droog at orange.gov Wed Mar 17 21:53:48 2004 From: droog at orange.gov (droog) Date: Thu, 18 Mar 2004 02:53:48 GMT Subject: New to Python. Message-ID: 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 peter at engcorp.com Tue Mar 16 15:50:34 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 16 Mar 2004 15:50:34 -0500 Subject: wxPython "Frames within Frames" In-Reply-To: References: Message-ID: Simon Erikson wrote: > I would like to build an app consisting of a "root" frame that can > contain an arbitrary number of child frames (the user will click to > create them). Each of these child frames needs the full functionality > of a frame (title,menu,status bars, min,max,close icons, scroll bars, > sizing, moving). In addition, the user must be able to create > grandchild frames within these child frames, to an arbitrary depth (in > practice limited to 10 or so). > > As I understand it, MDI provides the means of creating the root and > first generation frames, but not the further generations. I'm afraid I can't help with the task as described, but I wanted to draw your attention to the fact that many people consider MDI to be 'evil', and it occurs to me that a massively nested MDI could only magnify the problems many times over. In case you're interested, I found a couple of links to start you off: http://discuss.fogcreek.com/joelonsoftware/default.asp?cmd=show&ixPost=2748 http://mail.gnome.org/archives/usability/2002-August/msg00228.html (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 From zapazap at yahoo.com Mon Mar 1 23:07:43 2004 From: zapazap at yahoo.com (zapazap) Date: 1 Mar 2004 20:07:43 -0800 Subject: Pythonic control of VMware -- ctypes does not provide access to 'menu' gui-control. References: <4b3b1124.0403010024.7d044ac1@posting.google.com> <10470sbrjkdh1b2@corp.supernews.com> Message-ID: <4b3b1124.0403012007.6dc1b20b@posting.google.com> Thanks Mike. "Michael Geary" wrote in message news:<10470sbrjkdh1b2 at corp.supernews.com>... > If you are trying to close an application, I wouldn't access its menu at > all. The normal way to close a Windows app is to send or post a WM_CLOSE > message to its main window. Noted, and my intent is to bypass the menu as much as possible when driving the app. But without documentation of the app's API, I have no obvious (to me) recourse but using the menu. In the unittest, I closed the app with the menu in order to exercise the menu. The app closing is just a convenient side effect :-) > If you need to find out more about how an application is structured, > Winspector Spy may be useful: http://www.windows-spy.com/ And this may be just the thing I am looking for, maybe even to bypass the menu altogether. You are keeping my hope alive, thanks! > Won't the user still be able to press Ctrl+Alt (or whatever you set the > hotkey to) to break out of full screen mode and get back to the host system? Probably. My concern is less over determined crakers than over teachers freaking out when the VM leaves full screen mode -every time- the host does something to it. (I have hopes of deploying this in a school setting, with teachers modifying and snapshoting the students' VM, without the teacher having to know that it is a VM at all.) Disabling the Ctrl+Alt would indeed be nice, but bulletproofing is not a priority at this stage. Indeed, at this stage, I want this to be automated for my own purposes, because I am both lazy and careless in routine tasks on my own machine! Here I do not mind the VM leaving full screen mode. I am disciplined enough to "sit on my hands" while it does it's thing. Students may not though! > Don't use os.system to run a program in Windows.... > You can use os.startfile to run a program using the ShellExecute function... > Or use win32api.ShellExecute... Noted. > If you were coding in C, I would recommend using ShellExecuteEx instead of > ShellExecute. ShellExecuteEx gives you the process and thread handles to the > application, so you can use the WaitForInputIdle() function instead of an > unreliable time delay. > > I don't see a wrapper for ShellExecuteEx in win32api, but you could probably > do it with ctypes. That is new to me, and does sound interesting. > The difference between PostMessage and SendMessage is that SendMessage waits > until the target window function returns, so you wouldn't need the delay. Ditto. > > > 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) ] > > This doesn't seem like a good idea. Some unrelated window could have the > same text in its title. > > Instead of GetWindowText, I'd use win32gui.GetClassName and look for the > window class name you want. You can use Winspector Spy to find the class > name for any window. > ... > > There's no guarantee that class names will be unique either, but it's a lot > better than using window titles. You could check both. > > A general comment about closing applications: As you know, many apps will > put up a confirmation dialog box when you close them. In your Notepad test, > what if the user had edited the text? Notepad would put up a "do you want to > save" dialog and your code would take the assert. VMware always puts up a > confirmation message box if the VM is running. SendMessage(WM_CLOSE) would > avoid this problem by waiting for the WM_CLOSE message to return. Yup, I agree - for my project, but not this particular unittest. Which is also why I do not bother to deal with closing dialog boxes. My test should never cause a dialog to appear, and I wanted to trim it to the bare minimum that shows the problem. (Perhaps I need not have had the test exercise both Notepad and Freecell? One working example may have been enough?) I will check windows-spy and hope that I do not face too steep a learning curve regarding windows innards (which the menu route would have avoided!) Thank you Mike. Your comments are appreciated, and > -Mike From dj00302003 at yahoo.com Sat Mar 6 16:52:06 2004 From: dj00302003 at yahoo.com (Jay Davis) Date: 6 Mar 2004 13:52:06 -0800 Subject: How to flush print Message-ID: <1d17eeb7.0403061352.15aa1acc@posting.google.com> If you open a file the usual way, you can flush the output buffer with .flush(). How do you flush the output buffer of a print command, either 'print string' or 'print >>ofile, string' ? From mwh at python.net Tue Mar 2 06:26:21 2004 From: mwh at python.net (Michael Hudson) Date: Tue, 2 Mar 2004 11:26:21 GMT Subject: Speed Comparison Perl Python & C References: <3064b51d.0403011035.554e7731@posting.google.com> <7xllmkrzry.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin writes: > Nothing stops Python from optimizing the loop. It just doesn't do so. > Again, it's an implementation vs implementation comparison, with > Fortran winning. I haven't read the rest of this thread, but my curiosity is almost (but not quite) piqued enough by this statement to go back and find out why it's being said :-) Cheers, mwh -- TRSDOS: Friendly old lizard. Or, at least, content to sit there eating flies. -- Jim's pedigree of operating systems, asr From rschroev_nospam_ml at fastmail.fm Wed Mar 31 14:27:25 2004 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Wed, 31 Mar 2004 19:27:25 GMT Subject: test for nan In-Reply-To: References: Message-ID: Skip Montanaro wrote: > 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 >>> a = inf-inf >>> a == nan False Seems to return False always, that doesn't really help... -- "Codito ergo sum" Roel Schroeven From sc0rp at hot.pl Thu Mar 25 02:15:55 2004 From: sc0rp at hot.pl (Jacek Trzmiel) Date: Thu, 25 Mar 2004 08:15:55 +0100 Subject: Mod_python References: Message-ID: <4062872B.90FC5F33@hot.pl> Amy G wrote: > So I can now restart apache and everything seems to work. Except my python > files still show up as text in the browser window. > > I am using Apache 1.3.7. > I downloaded both mod_pyton-2.7.10 and 2.7.9. Below is configuraton that does work with Apache 2.0.49 and mod_python 3.0.3. Maybe it will work with older version as well. Make sure that similar entires are in http.conf (paths on your system may be different): ----- LoadModule python_module libexec/apache2/mod_python.so DocumentRoot "/usr/local/www/data" AllowOverride None Order allow,deny Allow from all SetHandler python-program PythonHandler Handlers PythonDebug On ----- Place your script as: /usr/local/www/data/Handlers.py Something like this should work: Make should that your Python version is old enough to be suppor Best regards, Jacek. From aahz at pythoncraft.com Wed Mar 31 15:30:56 2004 From: aahz at pythoncraft.com (Aahz) Date: 31 Mar 2004 15:30:56 -0500 Subject: wxPython book (was Re: Python Documentation Blows!) References: <40699A31.8000708@yahoo.com> <406a753b$0$12020$79c14f64@nan-newsreader-02.noos.net> <9TCac.683$JX6.99@fe07.usenetserver.com> Message-ID: In article <9TCac.683$JX6.99 at fe07.usenetserver.com>, Robin Dunn wrote: >Aahz wrote: >> In article <406a753b$0$12020$79c14f64 at nan-newsreader-02.noos.net>, >> francois lepoutre wrote: >>> >>>Possibly a smart (and not necessarily big) wxpython book could prove a >>>decisive argument for wxpython and python as well specifically for the >>>"MS visual *" and delphi user communities. >> >> There's one in the pipeline. Don't know how much more than that I >> should say; > >We've just had our 1/3 review, with lots of positive and constructive >feedback from the reviewers. There's still lots to do but it is moving >ahead at a steady pace. Cool! Still using reST to write it? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "usenet imitates usenet" --Darkhawk From katximan at gmx.net Wed Mar 24 17:10:00 2004 From: katximan at gmx.net (Asier) Date: 24 Mar 2004 14:10:00 -0800 Subject: fox 1.2.x and FXPy References: <4e1cc86c.0403151008.669e2e45@posting.google.com> Message-ID: <4e1cc86c.0403241410.28d969b3@posting.google.com> Josiah Carlson wrote in message news:... > Well, if you checked date stamps, Asier's message about "startup times" > being critical was roughly 20 hours after my my message. > > Asier originally said, "wxpython is horribly slow" with no pointer as to > the startup time being slow. Both Peter and I believed he meant 'slow > while running', which neither of us have experienced, which is why we > commented. Please, excuse me if the reasons showed in my first message were not very technical but I'm a bit tired of the "eternal war" of GUIs in Python. I'm programming with Python for one year and I haven't found a portable, free and 'batteries full' GUI toolkit -perhaps now pygtk-. Please, don't think I'm a troll or something like. I like a lot the message system used in FOX and the quality/quantity of its widgets, but the lack of maintenance of fxpy makes me cry. I'm thinking about learning SWIG to maintain the package because often this toolkit is forgetted. I see wxpython more like a framework than a GUI toolkit. If I'd want a GUI I would use GTK which also is multiplatform and also has lots of widgets. But this is caused by my customer's hardware: it's very old. -- Asier. From http Fri Mar 12 23:39:25 2004 From: http (Paul Rubin) Date: 12 Mar 2004 20:39:25 -0800 Subject: root password in a .py script References: <87y8q5g8sg.fsf@strauser.com> <7x8yi5wfyd.fsf@ruckus.brouhaha.com> Message-ID: <7x3c8d9x8i.fsf@ruckus.brouhaha.com> Ben Finney writes: > 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. The OP isn't asking about how to do it on "many systems", he's asking how to do it on a specific system (Mac OS X). If he can find a way that works on that system, he doesn't have to worry about other systems. From jacek.generowicz at cern.ch Fri Mar 5 04:20:14 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 05 Mar 2004 10:20:14 +0100 Subject: OFF-TOPIC:: Why Lisp is not my favorite programming language References: <165b3efa.0403030443.4d591f04@posting.google.com> <40460dd5$0$5916$7a628cd7@news.club-internet.fr> Message-ID: nish20 at netzero.net (Mike Nishizawa) writes: > These posts are like big huge neon signs that say, "I'm IGNORANT." He then goes on to say. > LISP is a parsing language. Thereby creating a self referential articrle. From franck.lepoutre at caramail.com Wed Mar 31 02:50:29 2004 From: franck.lepoutre at caramail.com (francois lepoutre) Date: Wed, 31 Mar 2004 09:50:29 +0200 Subject: Python Documentation Blows! References: <40699A31.8000708@yahoo.com> <20040330161531.GA17112@vulcan.cprogrammer.org> <4069C839.6020109@mlug.missouri.edu> Message-ID: <406a753b$0$12020$79c14f64@nan-newsreader-02.noos.net> > ... wxPython still is horribly documented. Documentation of > the C version of something is really not very friendly especially to new > Python programmers. I for one would be glad to buy a book about wxPython > if someone a lot more experienced than myself cared to write such a > book. I do know C but I still find working from the wxWindows docs > frustrating with a lot of trial and error required. As was mentioned in a recent thread python is definitively the tool for applications with complex code and no or little UI. For UI-intense apps, win32 C# and delphi are still hard to beat Possibly a smart (and not necessarily big) wxpython book could prove a decisive argument for wxpython and python as well specifically for the "MS visual *" and delphi user communities. Is it time for the python community to commit a bit more to the wxwidgets/wxpython environment? I feel so Fran?ois From ieyf4fu02 at sneakemail.com Mon Mar 29 21:32:31 2004 From: ieyf4fu02 at sneakemail.com (Greg Ewing (using news.cis.dfn.de)) Date: Tue, 30 Mar 2004 14:32:31 +1200 Subject: A 'Python like' language In-Reply-To: References: <40645d8f$0$10775$afc38c87@news.easynet.co.uk> <95aa1afa.0403262049.4b2a6f78@posting.google.com> Message-ID: 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? A running Python program creates and discards certain kinds of objects (e.g. integers, tuples, stack frames) at a very high rate. Due to reference counting, the fact that these objects have been discarded is discovered very quickly, and their memory released. Subsequent allocations are likely to re-use the same memory, which is likely to be in cache. A pure mark-and-sweep system, on the other hand, tends to keep on allocating fresh memory and letting the garbage objects pile up until there is no more fresh memory, only then pausing to reclaim the garbage. This is a very bad access pattern for cache purposes. Back when the addition of a mark-and-sweep collector to Python was being debated, this argument was put forward as a reason why replacing reference counting with mark-and-sweep wouldn't obviously be an improvement, and could make things worse. Python currently has both reference counting *and* mark and sweep, which sounds redundant, but the combination seems to work very well. > The interpreter supports C code calling Prothon code and vice versa. I don't doubt that it's possible, I was just wondering how easy it is. Stackless-type systems tend to make this rather more convoluted than just making a C function call. I'll take a look at the code some time and find out. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From bob at redivi.com Fri Mar 5 17:42:55 2004 From: bob at redivi.com (Bob Ippolito) Date: Fri, 5 Mar 2004 17:42:55 -0500 Subject: securely overwrite files with Python References: Message-ID: <2004030517425550073%bob@redivicom> On 2004-03-05 16:28:55 -0500, Mathias Waack said: > Bart Nessux wrote: > >> Is there a shred module in Python? You know, the kind that >> overwrites files that one doesn't want others to see? I can call >> the unix program like this: >> >> x = os.popen("/usr/bin/shred -uvz NAME_OF_FILE") >> x.read() >> x.close() >> >> But, I'd like a platform independant (portable) way of doing this >> if possible. > > 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. Somewhat OT, Mac OS X 10.3 is one of the operating systems where this assumption is false. Files smaller than a certain size get automatically moved around on the disk when it makes sense to do so in order to reduce fragmentation. -bob From a_salnikov at yahoo.com Mon Mar 15 16:34:58 2004 From: a_salnikov at yahoo.com (Andy Salnikov) Date: Mon, 15 Mar 2004 13:34:58 -0800 Subject: Python style guidelines References: <3064b51d.0403101112.3449e987@posting.google.com> <4050EAA3.9010807@wberry.org.x> <92c59a2c.0403122308.35513650@posting.google.com> <92c59a2c.0403131328.54210c30@posting.google.com> Message-ID: "MetalOne" wrote in message news:92c59a2c.0403131328.54210c30 at posting.google.com... > Good points. > With resource acquistion, I was mainly thinking along the lines of > > int file_compare(const char *filename1, const char *filename2) > { > FILE *infile1 = fopen(filename1, "r"); > FILE *infile2 = fopen(filename2, "r"); > if (!infile1 || !infile2) > { > // error > if (infile2) > fclose(infile2); > if (infile1) > fclose(infile1); > return FAILURE; > } > > // compare files > return SUCCESS > } > > as opposed to > > int file_compare(const char *filename1, const char *filename2) > { > int result = SUCCESS; > FILE *infile1 = fopen(filename1, "r"); > if (infile1) > { > FILE *infile2 = fopen(filename2, "r"); > if (infile2) > { > // compare files > } > else > { > result = FAILURE; > } > } > else > { > result = FAILURE; > } > if (infile2) > fclose(infile2); > if (infile1) > fclose(infile1); > return result; > } Latter version has an error - scope of infile2 is the first if _only_. Write it like this (and this is my preferred style too :) int file_compare(const char *filename1, const char *filename2) { int result = FAILURE; FILE *infile1 = fopen(filename1, "r"); if (infile1) { FILE *infile2 = fopen(filename2, "r"); if (infile2) { // compare files result = SUCCESS ; // maybe fclose(infile2); } fclose(infile1); } return result; } // Andy. From ark at acm.org Sat Mar 6 13:29:33 2004 From: ark at acm.org (Andrew Koenig) Date: Sat, 06 Mar 2004 18:29:33 GMT Subject: Question please References: Message-ID: > I have a new HP computer that seems to have come with Python 2.2 > with win32 extensions software. > I'm not a programmer or tech and would like to know if > I can just remove this software without affecting anything > in my system as it is taking up space if I'm not going to use it? The question is whether anything else on your machine depends on it. As we don't know what else is on your machine, we can't answer that question. Out of curiosity, what fraction of the total space on your machine does Python occupy? On mine, it's about 1/20 of a percent. From theller at python.net Mon Mar 22 15:38:19 2004 From: theller at python.net (Thomas Heller) Date: Mon, 22 Mar 2004 21:38:19 +0100 Subject: py2exe icon resource on win98 References: Message-ID: <1xnkfwhw.fsf@python.net> Haim Ashkenazi writes: > Thomas Heller wrote: > >> Haim Ashkenazi writes: >> >>> Hi >>> >>> I'm trying to build a binary with py2exe. I've used the method suggested >>> in the py2exe wiki about adding icon resources to apps. it build ok on >>> win2k, but when I try to build the same on win98 I get this error: >>> [...] >>> File "C:\Python23\Lib\site-packages\py2exe\build_exe.py", line 577, in >>> build_executable >>> add_icon(unicode(exe_path), unicode(ico_filename), ico_id) >>> RuntimeError: MapExistingFile: The handle is invalid >>> >>> ---------------------------------- >>> I've attached my "setup.py". >>> >>> anyone has any ideas? >> >> I assume you have unicows.dll installed (this is required on win98), as >> described in the py2exe webpage. > of course :) Well, its better to ask - some people don't read instructions ;-) >> The build process on win98 is not tested very good, maybe I overlooked >> something. Can you build your exe when you comment out all the icon >> resources? > yes. without a problem. it's win98 first edition without any updates > (internet explorer 4). It's a bug. I hope I can fix it before the next release. Thomas From dietrich at zdome.net Tue Mar 16 19:21:58 2004 From: dietrich at zdome.net (Dietrich Epp) Date: Tue, 16 Mar 2004 16:21:58 -0800 Subject: Inconsistency in Python's Comparisons Message-ID: <1A509EE5-77A9-11D8-8AC1-0003934ACDEC@zdome.net> Without invoking double-underscore black magic, it is possible to choose a, b, and c in Python such that: a < b b < c c < a This could cause sorting functions to malfunction. >>> class t(object): ... pass ... >>> a = t() >>> b = u'0' >>> c = '1' >>> a < b True >>> b < c True >>> c < a True Possible kludge fix: Change default_3way_compare() to use "basestring" as the typename for both built-in string types. Possible elegant fix: Any class whose members may either be less than or greater than members of a different class, which often share a common superclass, use the name of the superclass for comparisons with objects of incompatible types. This parallels the comparison of numeric types because they compare as if their type name were empty. From steve at ninereeds.fsnet.co.uk Sun Mar 7 14:57:22 2004 From: steve at ninereeds.fsnet.co.uk (Stephen Horne) Date: Sun, 07 Mar 2004 19:57:22 +0000 Subject: Working around a lack of 'goto' in python References: <9gpm405d952ooq37bmeilacks37o4on086@4ax.com> Message-ID: <71tm409egnua4ncic1siadnk7fi9rqnp8e@4ax.com> On Sun, 07 Mar 2004 13:54:33 -0500, Roy Smith wrote: >Stephen Horne wrote: > >> a goto is the natural representation of a transition between states. > >Except that a goto allows the code for a state to be fallen into from >the top. How is this different to the more typical switch-within-loop method? Or have you never forgotten to include a 'break'? ;-) >The best way I know to implement a state machine in Python is one >function for each state, and have each function return the next state, >or perhaps an (output, nextState) tuple. Your main loop then becomes >something like: > > state = start > while state != end: > nextState, output = state (input) > print output > state = nextState I've done similar in C++. In some extreme cases, I have used a class heirarchy with a class for each state, using a virtual method to get essentially the same effect. Having different members depending on the state can be useful at times, though of course there is a price to pay. The same can of course be done in Python, and probably without all the classes because of the dynamic nature of Python objects. The point with my 'short running' example, though, is that it didn't have input as such to worry about. Everything it needed to work on was available at the time it was invoked. If it had needed to wait for input sometimes I'd have needed a way to resume from a given state anyway, implying the switch-for-the-state method or whatever. Using functions or objects for the states would have meant making a bunch of local variables accessible by those functions/objects, and would have meant taking the states code out of context. Often this would be a good thing, but not in this case - keeping the code in context makes it much clearer. The other consideration was that this was an inner loop in a function that needed to run quickly. Adding function call overheads (especially with lots of parameters) wasn't an option. >I've implemented state machines in Perl with a huge multi-way >if/elif/elif/else statement. It's pretty ugly, but it beats gotos. If you say so. But in reality, but returning a function pointer to a function that is immediately going to call that function pointer, you're basically just faking the effect of a goto anyway. Implementing a state machine using gotos (in those extremely rare cases where it is an option) does not damage readability or maintainability. Implementing a transition as 'return statefn;' or as 'statevar = stateid;' is really no different than implementing it as 'goto statelabel;'. All are a potential cause of spaghetti code if abused, because all are just means of branching to a different piece of code - its just that the goto does exactly what it says, while the other methods achieve it indirectly. In fact its basically a special case of the state variable method, using the processors IP as the state variable. That said, I did try to avoid using gotos anyway - using a goto is basically begging to be harassed. I didn't use the loop-and-switch method, but instead tried to pretent it wasn't really a state machine by using a birdsnest of loops and conditionals. Never let anyone tell you that structured code is inherently clean and simple - there's always a special case where it all goes horribly wrong. After three fatally buggy attempts using structured code, which I realised I couldn't understand and thus couldn't debug, I gave up and used gotos. The result worked first time, and other people have also been able to understand it easily. -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From david at rebirthing.co.nz Sat Mar 13 19:30:04 2004 From: david at rebirthing.co.nz (David McNab) Date: Sun, 14 Mar 2004 13:30:04 +1300 Subject: Python & the job market In-Reply-To: References: Message-ID: <4053A78C.1060303@rebirthing.co.nz> Robert Brewer wrote: > kbass wrote: > >>I am starting to learn Python but I want to know how the job >>market looks for programming using Python. I really don't see >>many jobs (probably one or two) that require Python experience >>at all. The same thing was once said about C, Perl, even COBOL. The suits have always gone through a period of resistance before finally seeing the benefits of each new technology. One option would be to sell oneself into a job on the back of another language like Java or Perl, then at first opportunity write something in Python and demonstrate how much quicker and easier it is to write stuff. You could even use some dirty tricks like writing stuff in Jython. >>Most DBA and SA positions that I have seen require >>Perl and most development position require Java or C++ so >>how can learning Python benefit my career if there are little >>to no chance that an employer will require the use of Python >>or consider using Python over other programming languages >>such as Java? I'm glad not everyone lets themselves get intimidated by thinking like that. Take a walk around the Google labs - now that place is Python City. > Java was designed to benefit your career. Python was designed to benefit > your life. Pick one. Why not both? Get your butt into a Java site, deliver some stuff on time, get some credibility, then start selling them on Python. David > > > FuManChu > -- Kind regards David -- leave this line intact so your email gets through my junk mail filter From u at g0ertz.de Sat Mar 20 04:05:57 2004 From: u at g0ertz.de (Ulrich Goertz) Date: 20 Mar 2004 10:05:57 +0100 Subject: py2exe 0.5.0 and data_files References: <87fzc4h036.fsf@u-go.net> Message-ID: <87d67799ca.fsf@u-go.net> Josiah Carlson writes: > Try the following [...] Thanks for your suggestion. I see that I can get around this problem by analyzing sys.path[0] and proceeding case by case. However, my understanding is that it should not be necessary for the application to "know" that it will be packaged by py2exe later. In other words, why does py2exe "change" sys.path[0]? Or, if this change is justified (and it may well be), maybe my application shpuld not use sys.path[0] but a different way to find out the path where it resides? In addition, since this change in the behavior of py2exe forces me to change the Python application which I want to package itself, I am asking myself whether there are other changes that have to be made but which are not as obvious as this one. (All this is not meant as criticism towards py2exe; it is a great program. But I would like to improve my understanding of its behavior, and of what is the right thing to do in my application.) Ulrich From mwh at python.net Tue Mar 2 06:46:29 2004 From: mwh at python.net (Michael Hudson) Date: Tue, 2 Mar 2004 11:46:29 GMT Subject: A 'raw' codec for binary "strings" in Python? References: Message-ID: Bill Janssen writes: > I've encountered an issue dealing with strings read from files. I > read a line from a file, then try to print it out as an ASCII string: > > line = fp.readline() > print line.encode('US-ASCII', 'replace') > > and of course I get an error like: > > Traceback (most recent call last): > File "", line 1, in ? > UnicodeDecodeError: 'ascii' codec can't decode byte 0xd5 in position 1: ordinal not in range(128) > > because the file contained some binary character. You'll notice that > the problem is in *decoding* the string, not in re-encoding it, > because I'm using the default "C" locale, and "US-ASCII" is presumed > for strings. Actually, the "C" locale has precisely nothing to do with it. > But these strings are *not* US-ASCII, they are raw bytes. How do I > format a string of raw bytes for conversion to a recognized charset > encoding for printing? You don't? Wouldn't def m(c): if c in string.printable: return c else: return '?' t = ''.join([m(chr(o)) for o in range(m)]) line.translate(t) make more sense? Cheers, mwh -- I like silliness in a MP skit, but not in my APIs. :-) -- Guido van Rossum, python-dev From Kuser-admin at kde.gr.jp Wed Mar 3 10:07:51 2004 From: Kuser-admin at kde.gr.jp (Kuser-admin at kde.gr.jp) Date: Thu, 4 Mar 2004 00:07:51 +0900 Subject: Fml status report (Kuser ML) References: <20040303150731.E68B01F83DE@mail.kde.gr.jp> Message-ID: <200403040007.FMLAAB25714.Kuser@kde.gr.jp> ATTENTION! Your mail is too big, so not processed!!! This ML restricts the maximum mail size, so pay attention to the mail with e.g. attachments. --Kuser at kde.gr.jp, Be Seeing You! ************************************************************ Help: Unsubscribe: If you have any questions or problems, please contact Kuser-admin at kde.gr.jp or send e-mail with the body "help"(without quotes) to Kuser-ctl at kde.gr.jp (here is the automatic reply, so more preferable) e.g. on a Unix Machine (shell prompt)% echo "help" |Mail Kuser-ctl at kde.gr.jp ************************************************************ From jcarlson at nospam.uci.edu Fri Mar 19 12:43:15 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Fri, 19 Mar 2004 09:43:15 -0800 Subject: Graphing problems In-Reply-To: <75200cbc.0403190817.10ed1ef3@posting.google.com> References: <75200cbc.0403181507.350feeb7@posting.google.com> <75200cbc.0403190817.10ed1ef3@posting.google.com> Message-ID: >>Thank Guido, http://www.python.org/doc/essays/graphs.html > > I figured it out...I needed to use sys.setrecursionlimit. D'oh. :) You may eventually run into a case where setting the recursion limit still doesn't help you (you start getting C stack overflows). At this point, a non-recursive version of the shortest paths algorithm would probably help you. - Josiah From martin at v.loewis.de Thu Mar 18 12:48:02 2004 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Thu, 18 Mar 2004 18:48:02 +0100 Subject: ConfigParser and Unicode In-Reply-To: References: Message-ID: thehaas at binary.net wrote: > Obviously, 'Gr??'!='Gr\xfc\xdf' . It is not at all obvious that they are different. In fact, they are the same, assuming the second string is encoding in Latin-1. > Any ideas on how I can get the correct value? Pray tell: what is the correct value? Regards, Martin From altis at semi-retired.com Fri Mar 5 14:08:18 2004 From: altis at semi-retired.com (Kevin Altis) Date: Fri, 5 Mar 2004 11:08:18 -0800 Subject: ready to use python, need help with GUI decision References: Message-ID: Well I have to make the obligatory PythonCard plug... http://pythoncard.sourceforge.net/ PythonCard uses wxPython and you can mix "raw" wxPython code into your app if needed. Since it is based on wxPython, your apps will work on Windows, Linux/GTK, and Mac OS X. ka "Jonathon McKitrick" wrote in message news:mailman.0.1078340778.736.python-list at python.org... > > Hi all, > > I am totally hooked on what I have learned about python. I am going to use > it to develop a simple data entry app I need for some financial record > keeping. > > I understand tkinter is official and simple to use, but many who use > wxPython swear by it, and it is gaining ground. > > I would like to run on any platform, but that's not critical. What I want > to do is support an app that will grow over time, and should look clean. I > don't want to spend lots of time maintaining GUI code rather than app logic. > > Can anyone offer any advice? > > jm > -- > My other computer is your Windows box. > > From jcm at FreeBSD-uk.eu.org Thu Mar 4 12:44:16 2004 From: jcm at FreeBSD-uk.eu.org (Jonathon McKitrick) Date: Thu, 4 Mar 2004 17:44:16 +0000 Subject: ready to use python, need help with GUI decision In-Reply-To: <4046EE84.9080700@rebirthing.co.nz> References: <20040303181544.GB74292@dogma.freebsd-uk.eu.org> <4046EE84.9080700@rebirthing.co.nz> Message-ID: <20040304174416.GA83243@dogma.freebsd-uk.eu.org> On Thu, Mar 04, 2004 at 09:53:24PM +1300, David McNab wrote: : My personal favourite is Tkinter, with the 'steroids' that go by the : name of PMW. I think I am leaning this way as well. But why can't I find any screenshots of PMW? : leave this line intact so your email gets through my junk mail filter jm -- My other computer is your Windows box. From miki.tebeka at zoran.com Thu Mar 4 06:18:25 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Thu, 04 Mar 2004 13:18:25 +0200 Subject: Especialized generator In-Reply-To: References: Message-ID: <40471081.9030403@zoran.com> Hell Boogie, > 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? Using os.walk :-) HTH. Miki From chrish at cryptocard.com Thu Mar 11 13:28:58 2004 From: chrish at cryptocard.com (Chris Herborth) Date: Thu, 11 Mar 2004 13:28:58 -0500 Subject: Python vs Perl (an example) In-Reply-To: <40509bdf$0$28718$afc38c87@news.easynet.co.uk> References: <40509bdf$0$28718$afc38c87@news.easynet.co.uk> Message-ID: <3824c.45105$6y1.1372868@news20.bellglobal.com> Peter Hickman wrote: [...] > You might find Python easier than Perl but you are not a particulary > good Perl programmer. So, only good Perl programmers find Perl easier than Python? ;-) *hides* -- Chris Herborth chrish at cryptocard.com Documentation Overlord, CRYPTOCard Corp. http://www.cryptocard.com/ Never send a monster to do the work of an evil scientist. Postatem obscuri lateris nescitis. From google0 at lazytwinacres.net Mon Mar 15 08:12:07 2004 From: google0 at lazytwinacres.net (Dang Griffith) Date: Mon, 15 Mar 2004 13:12:07 GMT Subject: Static Typing in Python References: <67efcd4ccaf87ddf3c640aad5517017a@news.teranews.com> <7de2e74a623ae9f3ff3fe9ae4e1ec2b4@news.teranews.com> Message-ID: On 15 Mar 2004 09:44:50 +0100, Jacek Generowicz wrote: >Dang Griffith writes: > >> >Not forcing variable initialization does have its problems. Here's >> >what I mean: >> >http://www.livejournal.com/users/premshree/10624.html?thread=53376#t53376 >> >> Yes, I agree. That is one reason I like Python. >> It has forced variable *initialization*. You cannot use a variable >> that has not been initialized. > >But there is nothing to prevent you from assigning to a previously >non-existing variable, which is what Premshree is concerned about. > >> In fact, the act of initializing a variable is what makes the >> variable exist. > >Exactly, make a typo, and the compiler won't notice. > >This can indeed be a minor annoyance in interactive >exploration. However, the development of a real program, backed by a >test suite, will catch the problem in no time. Ironically, the error in the code that Premshree referenced, once fixed for Python syntax, get in an infinite loop. So, a test suite will not catch the problem, because the test will never finish. But obviously, if one is using test-driven development, it should be pretty clear which code has a problem. --dang From david at rebirthing.co.nz Sat Mar 13 18:13:20 2004 From: david at rebirthing.co.nz (David McNab) Date: Sun, 14 Mar 2004 12:13:20 +1300 Subject: ANN: pyshaper - for easy traffic-shaping In-Reply-To: References: Message-ID: <40539590.5060807@rebirthing.co.nz> allena29 at elsol.zwan wrote: > [allena29 at elsol bin]$ pyshaper.orig > File "/usr/bin/pyshaper.orig", line 1253 > main() > ^ > IndentationError: expected an indented block Fixed - is a bug in the Leo editor. -- Kind regards David -- leave this line intact so your email gets through my junk mail filter From matthias at ccs.neu.edu Wed Mar 3 08:41:19 2004 From: matthias at ccs.neu.edu (Matthias Felleisen) Date: Wed, 03 Mar 2004 08:41:19 -0500 Subject: OFF-TOPIC:: Why Lisp is not my favorite programming language In-Reply-To: <165b3efa.0403030443.4d591f04@posting.google.com> References: <165b3efa.0403030443.4d591f04@posting.google.com> Message-ID: nobody wrote: > 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. somebody answers: Lisp has been declared dead for the past N years. Unlike Algol, Simula 67, PL/I, Pascal, ... and many more languages that came and went, it is still alife and kicking. It will be alive and fun to program in for many years to come, because it still has many advantages over C#, Java, Perl, Python, Ruby, and many other languages that *will* come and go before Lisp is truly retired. Long live Scheme And now it's time to go back and strengthen Scheme even more. -- Matthias Felleisen, PLT From noemail at noemail4u.com Thu Mar 4 07:52:27 2004 From: noemail at noemail4u.com (Dang Griffith) Date: Thu, 04 Mar 2004 12:52:27 GMT 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> Message-ID: <4119c4e0d1dd457d3637e1316d5513ac@news.teranews.com> 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. If you need >something else, just define your own shortcut, don't deprecate a >statement that is exactly what most users want. 'print' is not a shortcut for 'sys.stdout.write'. 'print' is a statement. 'sys.stdout.write' is a function. You can't define a shortcut for a statement. --dang From mikrosofty at hotmail.com Fri Mar 5 07:14:49 2004 From: mikrosofty at hotmail.com (Yuri Schaeffer) Date: Fri, 05 Mar 2004 12:14:49 GMT Subject: OFF-TOPIC:: Why Lisp is not my favorite programming language In-Reply-To: References: <165b3efa.0403030443.4d591f04@posting.google.com> Message-ID: I goofed! I'm trying to write a news server and did some test with a random header I found in this group. But I forgot to set newsgroups to a test group... So the above is not a repost, just my garbage. It also was a crosspost, that does make me realy bad doesn't it? ;) (sorry) yuri From ivoras at __geri.cc.fer.hr Fri Mar 5 18:38:54 2004 From: ivoras at __geri.cc.fer.hr (Ivan Voras) Date: Sat, 06 Mar 2004 00:38:54 +0100 Subject: wxpython appearance differs after py2exe In-Reply-To: References: Message-ID: Chad Haynes wrote: > http://linkage.rockefeller.edu/chaynes/dos.jpg > http://linkage.rockefeller.edu/chaynes/py2exe.jpg > > I'm runnin winXP, any ideas? You need the so-called 'XP manifest' - a resource segment in the executable file that enables the 'XP skinned look'. Try searching the Google. From vincent.salaun at zslide.com Fri Mar 19 05:17:58 2004 From: vincent.salaun at zslide.com (vincent Salaun) Date: Fri, 19 Mar 2004 11:17:58 +0100 Subject: [(J)Python] embedding python Message-ID: <405AC8D6.2080204@zslide.com> hi all, here's my problem : I've embedded a python interpreter in our java application (based on the NetBeans palteforrm) using the Jython API : http://www.jython.org/docs/javadoc/index.html So, i've used the PythonInterpreter class to instanciate an interpreter and to integrate it but the its environnement doesn't seem to be the same as the standard jython interpreter (the one that is gived when you install jython on your machine and that you can use in a DOS shell for example). So i've encountered some problems using this embed interpreter : i test/import/script some stuff in the 'standard' interpreter but it doesn't always work using my 'embed' interpreter. For example : ---------------------------------------------------------------- C:\jython-2.1\jython >>> import urllib >>>print urllib.urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl').read() ---------------------------------------------------------------- #it displays : What time is it?

US Naval Observatory Master Clock Time


Mar. 19, 08:56:01 UTC
Mar. 19, 03:56:01 AM EST
Mar. 19, 02:56:01 AM CST
Mar. 19, 01:56:01 AM MST
Mar. 19, 12:56:01 AM PST
Mar. 18, 11:56:01 PM YST
Mar. 18, 10:56:01 PM AST

;>Time Service Department, US Nav Now, doing the same thing in my 'embed' : interpreter : ---------------------------------------------------------- >>>import urllib Traceback (innermost last): File "", line 1, in ? File "c:\jython-2.1\Lib\urllib.py", line 44, in ? File "c:\jython-2.1\Lib\javaos.py", line 32, in ? File "c:\jython-2.1\Lib\re.py", line 7, in ? File "c:\jython-2.1\Lib\sre.py", line 17, in ? File "c:\jython-2.1\Lib\sre_compile.py", line 15, in ? AttributeError: class 'org.python.modules._sre' has no attribute 'MAGIC' ---------------------------------------------------------- It is strange because if i do import again : -------------------------------- >>>import urllib >>> -------------------------------- #it doesn't tell me anything anymore but ... ------------------------------------------------------------------------- >>>print urllib.urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl').read() Traceback (innermost last): File "", line 1, in ? AttributeError: module 'urllib' has no attribute 'urlopen' #it still doesn't work ... -------------------------------------------------------------------------- I have set 2 environnement values : DOS> echo %PYTHONPATH% --> .;C:\jython-2.1;C:\jython-2.1\Lib;c:\python21;c:\python21\Lib;D:\jython\Lib;d:\jython\Lib\test (my modules live in 'd:\jython\Lib ') DOS> echo %PYTHON_HOME% --> c:\jython-2.1 In my embed interpreter, i couldnt import my own modules from 'd:\jython\Lib', but i solved the problem using the PythonInterpreter.initialize(...) function : ------------------------------------------------------------------------------------------------------------------------------- //in my java app : import java.io.Writer; import org.python.util.PythonInterpreter; import org.openide.nodes.Node; import java.util.Properties; /** * This class is used to interpret command lines in python/jython * It always goes with a Python console class */ public class ZJythonInterpreter { /** * Default Constructor * creates a new interpreter and redirects its standard output and error output on the console's output * @param out - console's output * */ public ZJythonInterpreter(Writer out) { Properties props = new Properties(); props.setProperty("python.home", "c:\\jython-2.1"); props.setProperty("python.path", "c:\\jython-2.1;c:\\jython-2.1\\Lib;c:\\python21;c:\\python21\\Lib;d:\\jython\\Lib;d:\\jython\\Lib\\test"); PythonInterpreter.initialize(System.getProperties(),props,new String[0]); this.interpreter = new PythonInterpreter(); this.interpreter.setOut(out); this.interpreter.setErr(out); // .... } //... } -------------------------------------------------------------------------------------------------------------------------------------- For information, i'm using jython 2.1 with python 2.1.3 and jdk1.4.2 on window$ 2000 Any idea will be welcomed... i'm so bored with this problem thx vince From __peter__ at web.de Tue Mar 2 09:48:19 2004 From: __peter__ at web.de (Peter Otten) Date: Tue, 02 Mar 2004 15:48:19 +0100 Subject: Thoughts on new vs traditional idioms References: Message-ID: Delaney, Timothy C (Timothy) wrote: [unrelated code snipped] >> Assuming all immutable classes are "smart enough": [... to reuse an instance of the exact class passed to their copy constructor - to use C++ terminology for lack of any better] > That's a *very* big assumption - one I would never make. Do you have a class with immutable instances handy where the following assertion fails? assert immutableObj.__class__(immutableObj) is immutableObj Peter From tjreedy at udel.edu Tue Mar 16 21:33:24 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 16 Mar 2004 21:33:24 -0500 Subject: Semantics of == References: <40200384.0403161538.7407d9e2@posting.google.com> Message-ID: "Axel Boldt" wrote in message news:40200384.0403161538.7407d9e2 at posting.google.com... > Still trying to understand "=="... means equal in value as defined be Python and user code > 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) > >>> 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. This is routine: >>> print 0, 0.0, 0==0.0 0 0.0 1 >>> 1.0 == .999999999999999999999999999999999999 1 Equal in value != equal in internal structure. > >>> s[0]=2 > >>> w[0]=2 > >>> s==w > False > > All of a sudden they have become unequal. 1 == 1.0 but type(1) != type(1.0). Okay, that's cheating, so >>> 1|1 1 >>> 1.0|1 Traceback (most recent call last): File "", line 1, in ? TypeError: unsupported operand type(s) for |: 'float' and 'int' Doing same thing to equals has different results. Or >>> a=12345678909876 >>> b=float(a) >>> a*a, b*b (152415787745757059730335376L, 1.5241578774575706e+026) now unequal to human eye, but >>> a*a == b*b 1 due to conversion of a*a to float(a*a) for comparison. Terry J. Reedy From mcfletch at rogers.com Tue Mar 2 19:07:41 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Tue, 02 Mar 2004 19:07:41 -0500 Subject: Which Python module for PostgreSQL? In-Reply-To: <20040302233008.GA4960@knorke> References: <20040302233008.GA4960@knorke> Message-ID: <404521CD.2040709@rogers.com> W. Borgert wrote: >Hi, > >I'm not new to Python, but new to databases and PostgreSQL. >I like to write a PostgreSQL client application (not code >running inside of the RDBMS), and Debian has four modules: > >python2.3-pgsql - A Python DB-API 2.0 interface to PostgreSQL v7.x > > Also known as pyPgSQL, my personal choice, mostly because it is BSD licensed, compiles easily on Win32 and is fairly DB-API compliant. Authors have been fairly responsive to my bug reports over the months. >python2.3-popy - module providing access to PostgreSQL from Python2.3 > > One of the more popular ones. Last I heard it was still GPL licensed, though apparently there's some plans to make it BSD licensed as it merges with pygresql. IIRC it has a very strong Zope DA. >python2.3-psycopg - Python 2.3 module for PostgreSQL > > GPL-licensed AFAIK, apparently designed to be more thread-safe and efficient than "the others". Again, popular. Again, I seem to recall that it has a strong Zope DA. >python2.3-pygresql - PostgreSQL module for Python > > Ancient code (maintained by my business partner incidentally) which predates the DB-API (though is still maintained), intention is to merge the project with PoPy. BSD-style License (it's part of the postgresql tree). This is *not* a DB-API module, and I personally would *not* suggest using it in new code unless you desperately need the special features of the "classic" API it provides... and even then... >Now I'm confused: Which one should I use? I'm going to try >python2.3-psycopg, but maybe the other variants are "easier >to use"? Or faster? Or more complete? Thread-safe? > > Mostly licensing issues, thread safety and efficiency are the differentiators AFAICS. Good luck, Mike _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From haim at babysnakes.org Mon Mar 29 04:21:57 2004 From: haim at babysnakes.org (Haim Ashkenazi) Date: Mon, 29 Mar 2004 11:21:57 +0200 Subject: Python installing on Debian References: Message-ID: Ryan Spencer wrote: > On Mon, 29 Mar 2004 03:43:25 +0200, Haim Ashkenazi wrote: > >> It's a very bad idea to install self-compiled applications to the same >> prefix as the ones from original packages. this can breake many things on >> your computer. what you have now is a semi-broke python installation, and >> a package that tries to install itself every time you run apt-get but >> fails. >> >> I think your best chance to "clean" things would be to uninstall every >> python2.3 package on your system (see what happenes when you run 'apt-get >> remove --purge python2.3'). but make sure you understand what you're >> doing (e.g. do you really want to purge your zope installaion? do you >> have important stuff there, do you know how to restore it?). then if >> there's still stuff in /usr/lib/python2.3 and /usr/local/lib/python2.3 >> check that they don't belong to any package (with dpkg -S filename) and >> remove them. also check if you have a python binary in /usr/local/bin and >> delete it. then re-install all the python2.3 packages. this of-course >> will make you lose all your self-compiled modules, so you'll have to >> re-compile them. this is a long and messy job, but you got yourself into >> this position. just make sure you understand what you're doing before >> your doing it. >> >> in the future I would recommend using the source from unstable to build a >> package if you want a version newer then the one that exist in testing. >> also use 'stow' when you're compiling sources. this will let you >> uninstall self-compiled application easilly. >> >> >>> >>> Thanks a lot, >> >> good-luck (you'll need it) :( > > It actually needn't be that messy. dpkg --purge'ing will only remove the > package in question, whereas using a program such as debfoster and pruning > the selected target package will remove all it's associate dependencies > entirely eradicating it from your system, maybe leaving behind empty > configuration folders in your home directory, but there's no fret for > that those won't be taking up barely any space and you can always remove > them later. in my system 'apt-get remove --purge python2.3' wants to remove 401 packages. that's what I meant messy. you have to check that you didn't change any system configuration file for any of the packages. and as a rule, it's a good idea to understand what's you're doing. I've seen too many times people following instructions and then discovering that nothing works without knowing how to restore... > And also, I wouldn't say installing certain packages would break > much - although I wouldn't mark out the possibility of it happening in > unstable and testing, I sometimes forget constant recorrection I had to > go through. Possible replacement of certain library > files for applications, but that's also an issue of whether or not the > actual library file or application itself has issues, and that's a risk > you take in using unstable and testing. For example, I have an Nvidia > Geforce four and I would constantly have problems with glibc conflicting > with my video card. If you wander through the debian newsgroups you'll > notice many others have experienced the same problem, it's merely a > question of the glibc's lack of testing - which is why it's in the testing > phase of debian. the problem happenes when you install self-compiled applications (with configure, make, make install) under the same prefix. it may work without a problem, but what if the package gets updated and deletes some of the self-compiled files but not all of them. think of installing mysql4 under '/usr' on woody, and then updating the mysql3 package. wouldn't you say it will break things... :) Bye -- Haim From jepler at unpythonic.net Mon Mar 1 09:48:47 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 1 Mar 2004 08:48:47 -0600 Subject: Regular Expressions in Python In-Reply-To: References: Message-ID: <20040301144846.GA3843@unpythonic.net> opt_spaces = " *" identifier = "[A-Za-z_][A-Za-z0-9_]+" comment = "\*.*" opt_comment = "(%s)?" % comment pat = re.compile(opt_spaces + identifier + opt_spaces + opt_comment + "$") for test in ( " END *This is a comment", " END e * This is a line with an error (e)"): print test, pat.match(test) Jeff From bouil at bouil.org.invalid Tue Mar 23 19:42:23 2004 From: bouil at bouil.org.invalid (Nicolas Bouillon) Date: Wed, 24 Mar 2004 01:42:23 +0100 Subject: py files includings each others Message-ID: Hi I have a big problem while including file. I have more that twenty classes, with one py file per class (more clear & clean), and the following test case illustrate well my problem. I facts, files including each other before the name of the classes seems to be defined, so python fails... Can you help me to resolve that ? a.py: ==== from b import Man class Person: def __init__(self): pass def set_father(self): self.father = Father() ==== b.py ==== from a import Person class Father(Person): def __init__(self): Person.__init__(self) p = Father() ==== Runing: ==== bouil at lisa:/tmp$ python b.py Traceback (most recent call last): File "b.py", line 1, in ? from a import Person File "/tmp/a.py", line 1, in ? from b import Man File "/tmp/b.py", line 1, in ? from a import Person ImportError: cannot import name Person bouil at lisa:/tmp$ ==== Thanks you. From littlejohn.75 at news.noos.fr Thu Mar 11 17:36:44 2004 From: littlejohn.75 at news.noos.fr (F. Petitjean) Date: 11 Mar 2004 22:36:44 GMT Subject: new python syntax: concatenation of functions References: Message-ID: <4050e9fc$0$306$626a14ce@news.free.fr> On 11 Mar 2004 10:24:14 -0800, Bob Lancaster wrote: > Uwe Mayer wrote in message news:... >> > > (4) For my personal style, I don't like to use constructs that are too > esoteric. I tend to avoid the tertiary operator in C++, and I tend > not to get fancy with the 'and' and 'or' operators in Python. It > makes code more readable and maintainable, IMO. Any programmer who > writes code without any thought to code maintainance is doing the > employer or client a disservice. > Like this ? (extract from a direct translation of C code into python Nore also this snippet is nested into three while conditions of a method) while charNo < self._cols: charNo += 1 ch = self._ifs.read(1) cond = ((ch != '\n') and not(ch==FF and self._doFFs) and (ch != '')) if not cond: break if ord(ch) >= 32 and ord(ch) <= 127: if ch == '(' or ch == ')' or ch == '\\': ws("\\") ws(ch) How to understand the deep nested, mostly negative parts of condition cond ? and the test is if not cond: which will be equivalent to ... So, hmmm,.. I need some sleep... Regards -- Ce qui se con?oit bien s'?nonce clairement, Et les mots pour le dire viennent ais?ment. Boileau Despr?aux (l'Art Po?tique) From __peter__ at web.de Fri Mar 5 09:54:44 2004 From: __peter__ at web.de (Peter Otten) Date: Fri, 05 Mar 2004 15:54:44 +0100 Subject: reg exp and octal notation References: Message-ID: Lucas Branca wrote: > Could someone explain me the difference between the results below? > > ## $cat octals.txt > ## \006\034abc > > import re > > a= "\006\034abc" > preg= re.compile(r'([\0-\377]*)') > res = preg.search(a) > print res.groups() > > loader = open('./octals.txt', 'r') > b = loader.readline() > preg= re.compile(r'([\0-\377]*)') > res = preg.search(b) > print res.groups() > > > RESULTS > > ('\x06\x1cabc',) > > ('\\006\\034abc\n',) a and b are two entirely different strings. Whatever similarity there appears to be is an artifact of Python's treatment of escape sequences - only in source code not in an arbitrary file. Your literal string: >>> s = "\006\034\n" >>> s '\x06\x1c\n' What you read from the text file: >>> t = "\\006\\034\n" >>> t '\\006\\034\n' Maybe it helps to learn what's really inside these two strings, so let's have a look at the ascii codes: >>> map(ord, s) [6, 28, 10] >>> map(ord, t) [92, 48, 48, 54, 92, 48, 51, 52, 10] Another example: in source code you can write the newline as >>> a = """ ... """ >>> b = "\n" >>> c = "\x0a" >>> d = "\012" >>> a,b,c,d ('\n', '\n', '\n', '\n') But if read from a file \n, \x0a, \012 would just be sequences of two or four characters. Only when you have understood the above you should return to regular expressions. Your regexp always matches the whole string - i. e. is redundant (and probably not what you want, but that you would need to explain in another post). [\0-\377] is just a fancy way of writing "match any character" * means "repeat the preceding as often as you want" (including zero times) Peter From boblancaster at zxmail.com Thu Mar 11 13:24:14 2004 From: boblancaster at zxmail.com (Bob Lancaster) Date: 11 Mar 2004 10:24:14 -0800 Subject: new python syntax: concatenation of functions References: Message-ID: Uwe Mayer wrote in message news:... > Hi, > > I know the python community is not very receptive towards extending the > python syntax. Nevertheless I'd like to make a suggestion and hear your pro > and cons. > > I want so suggest a concatenation operator like in mathematics: ? > such that: > > a(b(c(d))) <=> a?b?c(d) > > Now, why do you think such an extension would be completely useless? ;) > > Ciao > Uwe One of the things I like best about Python is the ease of use. This method would hurt, rather than help the cause, IMO. Here are the arguments against it: (1) Where is the ? key on the keyboard? I do chemistry related programing, and getting the ? into my GUIs (when I need to show degrees) takes a bit of time and effort. The old way is easier to type, ergo easier to use. (2) The precedence and ordering of the operation would have to be more clearly defined. This seems similar to the Unix pipe | operator. However, in your proposal the result of c(d) is piped into b, and that result is piped into a. This could lead to confusion. Should we have a pipe-style ?, in which case the syntax would be: c(d)?b?a, or do the way you suggest: a?b?c(d). Either way would be confusing to somebody. (As far as using | to get around the problems with point (1), (3) How would this operator play with other operators? (4) For my personal style, I don't like to use constructs that are too esoteric. I tend to avoid the tertiary operator in C++, and I tend not to get fancy with the 'and' and 'or' operators in Python. It makes code more readable and maintainable, IMO. Any programmer who writes code without any thought to code maintainance is doing the employer or client a disservice. (5) One of the best aspects of Python is how easy it is to learn in the first place. Someone with a background in C/C++, Java, Pascal, Perl, etc. can learn python in a few hours. Adding weird operators would make the process more difficult. Anyone who has been though language Holy Wars knows that ease of use and learning is about the only way to convince anyone to even consider Python. Just my opinions. -Bob From skip at pobox.com Fri Mar 12 10:45:40 2004 From: skip at pobox.com (Skip Montanaro) Date: Fri, 12 Mar 2004 09:45:40 -0600 Subject: Xemacs syntax highlighting In-Reply-To: References: <1d17eeb7.0403111721.7aae9a76@posting.google.com> <16465.52956.35691.13784@montanaro.dyndns.org> Message-ID: <16465.56100.473809.512232@montanaro.dyndns.org> Roy> BTW, although Apple ships OSX with both emacs and python Roy> pre-installed, they don't include the python-mode.el. Any idea Roy> what the best way is to suggest to Apple that they include it? Nope. You might ask on pythonmac-sig at python.org. I don't know if Jack Jansen channels Steve Jobs or not, but I think Chuq von Rospach keeps an eye on that list. I would think if anyone could squeeze python-mode.el into a future release he could. Roy> They also ship python without gnu readline enabled :-( That's the joy of being able to build from source. :-) turn-that-frown-upside-down-ly, y'rs, Skip From newsgroups at jhrothjr.com Mon Mar 1 20:20:35 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 1 Mar 2004 20:20:35 -0500 Subject: Novice [].append Help References: Message-ID: <1047oejec1h8hcf@news.supernews.com> "waters" wrote in message news:c20iig08ip at enews1.newsguy.com... > I seem to have hit a snag. > > I am trying to add the list (l_local) as an item in the output list > (l_output). "l_local" is a modified copy of the format-list "l_format", > which will be updated by index position within the function. The problem > occurs in the following statement block: > > def create_apid_list(l_format,l_values): > l_output = [] > for t_curr_line in l_values: # ...for each list in the values list > l_local = l_format # ...assign blank format to local list > l_local[0] = t_curr_line[0] # ...modify with vendor number > l_local[1] = t_curr_line[1] # ...modify with invoice number > # print l_local # ... for testing > l_output.append(l_local) # ...add list as item to output list > return l_output > > ...the "l_output.append(l_local)" line is not returning the expected > result. It is correctly producing a list of lists, but they all contain > the the same values from the last t_curr_line[0] & t_curr_line[1] > records in the l_values list. The preceding print statement displays the > proper values containing data from all of the lists in l_values, so I'm > not sure what the problem is. You've fallen into one of the little traps. There's only *one* copy of the l_format list, and it's being bound to l_local each time through the loop. Assignment is *not* creating a copy of the l_format list; it's reusing it, so each slot in the l_output list is pointing to the *same* list, which of course contains the last value you put into it. If you change the 4th line to: l_local = list(l_format) it will work because the list type will produce a copy. John Roth From antonyliu2002 at yahoo.com Wed Mar 17 12:03:11 2004 From: antonyliu2002 at yahoo.com (Anthony Liu) Date: Wed, 17 Mar 2004 09:03:11 -0800 (PST) Subject: problem with cjkcodecs on Mandrake linux +++ In-Reply-To: <16472.26602.428386.396876@montanaro.dyndns.org> Message-ID: <20040317170311.17243.qmail@web13008.mail.yahoo.com> Dear Skip, Thank you so much. It is exactly the problem. And it works by issuing print s.encode('gbk'). I got a good lecture from you about unicode and encoding. The other people probably assumed that I knew. :) I appreciate it. --- Skip Montanaro wrote: > > Anthony> s = 'abc' > Anthony> unicode(s, 'gbk') > Anthony> print s # prints 'abc' > > [fails] > > Anthony, > > The above is a bit nonsensical, since you didn't > actually modify s. I > assume you really meant: > > s = 'abc' > s = unicode(s, 'gbk') > print s > > Remember the basic rule of Unicode? If you don't > know the encoding, you > don't know nuthin'. Unicode objects themselves are > encoding-neutral. The > print statement has to encode s somehow (Unicode > objects aren't displayed > directly), so it uses the system's default encoding, > which from your earlier > messages appears to be "latin-1". > > Perhaps you're confused by > > s = unicode(s, 'gbk') > > This says, "Convert the string s to a Unicode object > assuming the string is > encoded using the 'gbk' charset, then bind the > resulting object to s." Note > the 'gbk' doesn't become an attribute of the Unicode > object, so later on > when you try to print it > > print s > > it needs to decide how to encode the object and for > that it used the current > default encoding, typically "ascii". In the case of > "abc" that's no > problem. For other code points in other character > sets (I'm not sure I'm > using the terminology quite right there) you need to > be explicit: > > print s.encode('gbk') > > or use an appropriate system-wide default encoding. > > Skip > __________________________________ Do you Yahoo!? Yahoo! Mail - More reliable, more storage, less spam http://mail.yahoo.com From ml at dynkin.com Thu Mar 11 08:22:41 2004 From: ml at dynkin.com (George Yoshida) Date: Thu, 11 Mar 2004 22:22:41 +0900 Subject: Iterating over tuple entries in a list In-Reply-To: References: Message-ID: Peter Otten wrote: > If you are really lazy: > > >>>>myList = [(1.1, "file1"), (1.2, "file2"), (1.9, "file3")] >>>>zip(*myList)[0] > > (1.1000000000000001, 1.2, 1.8999999999999999) Or you could do it: >>> myList = [(1.1, "file1"), (1.2, "file2"), (1.9, "file3")] >>> map(lambda x:x[0], myList) [1.1000000000000001, 1.2, 1.8999999999999999] -- George From steve at ninereeds.fsnet.co.uk Tue Mar 23 04:02:40 2004 From: steve at ninereeds.fsnet.co.uk (Stephen Horne) Date: Tue, 23 Mar 2004 09:02:40 +0000 Subject: PEP 318 References: <99dce321.0403211817.3704fe2@posting.google.com> <7x1xnlqs77.fsf@ruckus.brouhaha.com> <7iptb4ckea.fsf@enark.csis.hku.hk> Message-ID: <12vv50lkebgvq9fjcdpcukekpbd14m4i72@4ax.com> On Tue, 23 Mar 2004 11:27:57 +0800, Isaac To wrote: >>>>>> "Stephen" == Stephen Horne writes: > > >> 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. > > Stephen> Good point. Though to me, it isn't that it's a pain for the > Stephen> compiler to search for the 'yield' - I don't care about the > Stephen> compilers pain. The problem is that *I* have to look for the > Stephen> yield and might not notice it. > >I disagree. It's not just the compile which has to search for that yield >keyword, we human being reading other's uncommented code (or mis-commented >code) also has to do the same. It would do much good if the completely >different call convention of generator is made much more explicit in the >definition of the function. Why say "I disagree" if you actually agree with me? As I said... """ The problem is that *I* have to look for the yield and might not notice it. """ -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From usenet at spling.plus.com Fri Mar 19 06:06:47 2004 From: usenet at spling.plus.com (Matthew Bell) Date: Fri, 19 Mar 2004 11:06:47 GMT Subject: Basic Inheritance Question Message-ID: I've got a conceptual problem to do with inheritance. I'd be grateful if someone could help to clear up my confusion. An example. Say I need a class that's basically a list, with all the normal list methods, but I want a custom __init__ so that the list that is created is [1,2,3] rather than [] (yes, it's a bogus example, but it does to make the point). Without bothering with inheritance, I could do: class mysimplelistclass: def __init__(self): self.internallist = [1, 2, 3] This would work but I would, of course, need to define methods in "mysimpleclass" to deal with all the various methods that the original list class provides. Obviously, the thing to do is to inherit from the list class, override the __init__ method and leave the rest of the normal list class's methods untouched. So I'd write something like: class myinheritedlistclass(list): def __init__(self): It's at this point I get confused. Obviously, I don't use the "self.internallist = [1, 2, 3]" bit as before because I'd then need to override all of the rest of the normal list methods to get them to act on self.internallist. Conceptually, I suppose I need something like: = superclass.self.__init__([1, 2, 3)] but that is, of course, totally ridiculous. Essentially, then, if I've inherited another class, how do I create an instance of the class I've inherited such that methods I haven't overrriden will still work, and how can I then refer to that instance from my subclass? I can guess it's something to do with "self" but exactly what, I'm really at a loss. Any assistance in my confusion would be gratefully received! Regards, Matthew. From nid_oizo at yahoo.com_remove_the_ Mon Mar 1 11:36:19 2004 From: nid_oizo at yahoo.com_remove_the_ (Nicolas Fleury) Date: Mon, 01 Mar 2004 11:36:19 -0500 Subject: Garbage collector and threads In-Reply-To: References: Message-ID: <1EJ0c.4334$mx4.105438@nnrp1.uunet.ca> Aahz wrote: > Yes, Don't Do That. Do not rely on finalizers for external resources > (such as threads). Why? Isn't a kind of RAII applied to Python? > Note that your understanding of Python's memory management could use some > improvement: GC *never* runs on objects containing __del__ Well, I guess you're right. What I mean is the reasons behind the call to __del__, whatever it is ref-counting or something else. Wouldn't a class like CancellableThread, with a sub-class implemented cancel method called when the object is not referred in any other thread be useful? Regards, Nicolas From bmorgan at usa.net Sat Mar 13 01:39:02 2004 From: bmorgan at usa.net (Byron Morgan) Date: 12 Mar 2004 22:39:02 -0800 Subject: Fatal Python error: Inconsistent interned string state Message-ID: <85c78d18.0403122239.4be5ad04@posting.google.com> Anyone run into this before? I have a python app that has been reliable, running for days on end without a crash. Suddenly, It repeatedly crashes with the following message: "Fatal Python error: Inconsistent interned string state. abnormal program termination" Some background: Platform is W2K. My app receives data (short strings, 25 - 40 character in length) from a telnet connection, using telnetlib. The strings are placed in a queue (I am using Queue.Queue(). The telnet session runs in a thread. A second thread gets strings from the queue and does stuff with the contents, involving queries to a mysql database. The main thread just watches for keyboard input for a shutdown command. Other than that, it prints to console and logs to a file. I cannot find any place in my code that overtly uses the concept of an interned string (I had never before heard of an interned string). The crashes began after I started using the following simple construct, to trap a particular value in the data: if line[0] == '2': (do something) Naturally, I assume that the problem may have something to do with this change, but I cannot fathom how it could cause this problem Byron Morgan From skip at pobox.com Mon Mar 22 22:08:27 2004 From: skip at pobox.com (Skip Montanaro) Date: Mon, 22 Mar 2004 21:08:27 -0600 Subject: The problem with "as" [was "Re: PEP 318"] In-Reply-To: <1M-dnXrds_WKG8LdRVn-jw@comcast.com> 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: <16479.43563.454892.110945@montanaro.dyndns.org> DH> Possible future Python example that uses "as" differently: DH> def foo(x as int, y as float) as int: DH> "this function returns an integer, and takes an int & float params" With no extension beyond the current PEP 318 proposal, you might postulate returns() and accepts() decorators: def foo(x, y) [accepts(int, float), returns(int)]: ... which extend foo() with code to enforce input and output types. Further, function attributes could be added which could be used by tools like pychecker for intermodule type checking. Skip From tismer at stackless.com Mon Mar 29 21:01:48 2004 From: tismer at stackless.com (Christian Tismer) Date: Tue, 30 Mar 2004 04:01:48 +0200 Subject: Orders of magnitude In-Reply-To: References: Message-ID: <4068D50C.80202@stackless.com> Robert Brewer wrote: > Christian Tismer wrote: > >>Robert Brewer wrote: >> >>>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? >> >>So, here we go. >>The attached script processes a gigabyte of data, one >>million records, in about a minute on my machine, and >>finds the single duplicate. > > > Thanks, Christian! Looks like someone's been having fun. ;) > > But I don't see how your solution avoids the problem, however (some code > snipped): > > def process_duplicates(self): > for i in range(len(self.files)): > seen = {} > has = seen.has_key > for k in range(self.flushes): > bin = pickle.load(self.files[i]) > for key, value in bin: > if has(key): > self.duplicates += 1 > else: > seen[key] = value > > ...that is, the 'seen' dictionary is what is growing too large on my > dataset; it ends up being about 7 million items. Actually, I have three > such dictionaries (3 different fields which I'm checking for dupes for > each record). The hashing might cut these sizes down a bit, but I think > I'm still going to end up having to cache 'seen' (which I call 'indices' > in my Directory.produce() method) somehow. Once again going over it, to make things crystal clear: You don't keep three dicts for whatever reason. What you pass my algortihm is a complete representation of your complete record, as simple-minded as possible, as long as it covers the full contents in a unique way. Then I will swallow that into a 20 byte hash key and a record number. This is all what you ever will need, regardless how complicated your records may be. Be able to do a complete string representation, and you are done. The algorithm will then partition this set into 256 bins, which are unrelated by construction, and examining each of them individually will solve your problem, as said in prior email. In a sense of patterns, this is simple "divide and conquer". Simple and effective, with very few competitors. Yes I do take contracts. 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 solution88pro at hotmail.com Sat Mar 20 17:45:31 2004 From: solution88pro at hotmail.com (Senthoorkumaran Punniamoorthy) Date: Sun, 21 Mar 2004 04:45:31 +0600 Subject: Any module which can act as a BitSet? Message-ID: I wanted to know in Python are there any module available which can perform the same funtionality as a BitSet classs in Java. Here is the Java Doc for that. http://java.sun.com/j2se/1.4.2/docs/api/java/util/BitSet.html Senthoor _________________________________________________________________ Add photos to your e-mail with MSN 8. Get 2 months FREE*. http://join.msn.com/?page=features/featuredemail From angoyal at siebel.com Wed Mar 24 14:29:18 2004 From: angoyal at siebel.com (Anuj Goyal) Date: 24 Mar 2004 11:29:18 -0800 Subject: Scons help! Message-ID: Does anyone have a scons file that make use of multiple compilers on win32 and linux? I am trying to get my scons script to work on win32 (using cl.exe) and linux (using gcc) . it is a nightmare! I need a builder (or set of builders) that is flexible enough for both platforms. I tried to find projects that make use of this on the net, but could not find any :( opt = Options(None, ARGUMENTS) opt.AddOptions( EnumOption( 'COMPILER', 'The compiler you want to use', 'cl', ['cl','gcc'])) env = Environment(options=opt) CLDEBUGCPPFLAGS = r'/nologo /MDd /W3 /Gm /GR /GX /ZI /Od /D "_DEBUG" /D "WIN32" /D "_WINDOWS" /D "BOBO_DLL_EXPORT" /D "USE_STANDARD_HEAP" /YX /FD /c' env['BUILDERS']['cl'] = Builder(action = 'cl '+ CLDEBUGCPPFLAGS +' %SOURCE') env['BUILDERS']['gcc'] = Builder(action = 'gcc -co %TARGET %SOURCE') env['BUILDERS']['MyCompiler'] = env['BUILDERS'][env['COMPILER']] env.MyCompiler('myheap.cpp') and here is the output. F:\work\src\mallocheap>scons scons: Reading SConscript files ... scons: done reading SConscript files. scons: Building targets ... cl /nologo /MDd /W3 /Gm /GR /GX /ZI /Od /D "_DEBUG" /D "WIN32" /D "_WINDOWS" /D "BOBO_DLL_EXPORT" /D "USE_STANDARD_HEAP" /YX /FD /c %SOURCE Command line warning D4024 : unrecognized source file type '%SOURCE', object file assumed Command line warning D4027 : source file '%SOURCE' ignored Command line warning D4021 : no action performed scons: done building targets. From niurka.perez at cimex.com.cu Tue Mar 23 18:02:00 2004 From: niurka.perez at cimex.com.cu (niurka.perez at cimex.com.cu) Date: Tue, 23 Mar 2004 18:02:00 -0500 Subject: new style classes Message-ID: <0403241080.AA1080145343@ws3.cimex.com.cu> I've seen every where this term of new style classes that inherits from a base class Object, but I haven't realize the advantage that this approach offers. Any one has some link where I can read about it? Thanks in advance Niurka From jaustin at post.harvard.edu Sun Mar 21 09:27:36 2004 From: jaustin at post.harvard.edu (Jess Austin) Date: 21 Mar 2004 06:27:36 -0800 Subject: mutable list iterators - a proposal References: <5d83790c.0403170242.759ac8d9@posting.google.com> Message-ID: Sorry I didn't respond in a timely fashion; I've been out of town. python at rcn.com (Raymond Hettinger) wrote in message news:<5d83790c.0403170242.759ac8d9 at posting.google.com>... > List iterators likely won't change because > * it does not encourage an error prone programming style > * it is documented to perform as it currently does > * there is likely existing code that relies on the current behavior > * there are performance issues which changing it > * there do not seem to be compelling, general use cases to warrant a > change These are all reasonable objections. > 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, the iterator should go to the beginning of the replacement slice, EXCEPT in the case where the new slice is the same length as the old slice, in which case the iterator should stay where it is. The exception is for backwards compatibility with current uses. > 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): > > >>> from collections import deque > >>> d = deque('abcdefg') > >>> it = iter(d) > >>> it.next() > 'a' > >>> it.next() > 'b' > >>> d.extend('hijk') > >>> d.appendleft('z') > >>> d.appendleft('y') > >>> list(it) # this picks up right where it left off > ['c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k'] > >>> d > deque(['y', 'z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', > 'k']) 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?" I know, see above for the reasons. The current list iteration stills seems ugly, and I know it's jarring to new users because I've been jarred by it, have forgotten it, and then been jarred again. As for performance, I think that it could be coded so that all performance penalties would be within the iterator, and there only after the list has been changed. There follows a revision of the code I posted originally, which attempts to demonstrate that. cheers, Jess import itertools class muterable_list(list): """just like a list except it iterates gracefully under mutation""" Insertion = object() Deletion = object() def __init__(self, object_): list.__init__(self, object_) self._mutations = [] self._iterators = {} self._iterators_keys = itertools.count() def __iter__(self): key = self._iterators_keys.next() self._iterators[key] = [] i = 0 try: while True: for position, direction in self._iterators[key]: if isinstance(position, int): if position < i: if direction is self.Deletion: i += -1 else: i += 1 elif direction is self.Deletion: # slice deletion start, stop, step = position.indices(i) i += (start - stop)/step elif position.start < i: # slice insertion i += position.stop - position.start self._iterators[key] = [] yield self[i] i += 1 for iterator in self._iterators: self._iterators[iterator].extend(self._mutations) self._mutations = [] except IndexError: del self._iterators[key] def __delslice__(self, i, j): list.__delslice__(self, i, j) if self._iterators: self._mutations.append((slice(i, j), self.Deletion)) def __setslice__(self, i, j, object_): list.__setslice__(self, i, j, object_) if self._iterators: length = len(object_) if length != (j - i): self._mutations.append((slice(i, j), self.Deletion)) self._mutations.append((slice(i, i + length), self.Insertion)) def __delitem__(self, index): list.__delitem__(self, index) if self._iterators: self._mutations.append((index, self.Deletion)) def __setitem__(self, index, object_): list.__setitem__(self, index, object_) if self._iterators: length = len(object_) if (isinstance(index, slice) and (index.step == 1 or index.step is None) and length != (index.start - index.stop)): self._mutations.append((index, self.Deletion)) self._mutations.append((slice(index.start, index.start+length), self.Insertion)) def insert(self, index, object_): list.insert(self, index, object_) if self._iterators: self._mutations.append((index, self.Insertion)) def pop(self, index): r = list.pop(self, index) if self._iterators: self._mutations.append((index, self.Deletion)) return r def remove(self, object_): if self._iterators: mutation = self.index(object_), self.Deletion list.remove(self, object_) self._mutations.append(mutation) else: list.remove(self, object_) From miki.tebeka at zoran.com Mon Mar 29 06:49:01 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Mon, 29 Mar 2004 13:49:01 +0200 Subject: easy verbose in functions In-Reply-To: References: Message-ID: <40680D2D.9060001@zoran.com> Hello Pascal, > I've a function like this: > def myfunction(data, verbose = False): > dothis... > if verbose: print 'I do this' > dothisother > if verbose: print 'I do this other' > ... > > How can I do to exclude eachtime the `if verbose` statement? > > I tried `print verbose and 'I do this'` but it's printing `False`. > So I tried with `verbose = None` in the definition, but it's printing None! Try the logging package? HTH. Miki From bscholln at mac.com Fri Mar 5 17:21:38 2004 From: bscholln at mac.com (benjamin schollnick) Date: Fri, 05 Mar 2004 22:21:38 GMT Subject: Need a Progress Bar/Meter for Tkinter References: <040320041859589376%bscholln@mac.com> Message-ID: <050320041721385005%bscholln@mac.com> > Google is your friend... > > google python Tkinter Progress Bar > > http://www.faqts.com/knowledge_base/view.phtml/aid/2718 Sorry... I forgot to mention by specifics, that I had tried that one, and it does not seem to work on my Python v2.33 install... The root TK window starts up, but disappears, and almost immediately quits... No progress bar, but the program itself works... I just found one today that works.... But I don't have it here to post.... Either way... I am very suprised that this is not a standard widget in the Tkinter module... - Ben From kbass at midsouth.rr.com Fri Mar 12 01:25:03 2004 From: kbass at midsouth.rr.com (kbass) Date: Fri, 12 Mar 2004 06:25:03 GMT Subject: Newby Question: Python and A Nested Dictionary References: <_G84c.1393$P45.950@fe1.columbus.rr.com> Message-ID: <3Jc4c.4710$fg7.3800@fe2.columbus.rr.com> "Greg Ewing (using news.cis.dfn.de)" wrote in message news:c2rc2l$1vtcg7$1 at ID-169208.news.uni-berlin.de... > kbass wrote: > > I am new to Python and I am attempting to retrieve data from a database and > > I would like to place this data into a nested dictionary. After placing the > > data into a dictionary, I would like to loop through the data using for > > loops. How would I do this? > > It's hard to say exactly how to go about building the dictionary > without knowing more about the format of the data and how you > want to structure it. Posting some sample data together with > the dict you want to build from it would help. > > As for looping over the dictionaries, some general facts you > might find useful are: > > for key in dictionary: > ... > > will loop over all the keys in the dictionary. > > for value in dictionary.values(): > ... > > will loop over the values (but you won't know what > their keys were). > > for key, value in dictionary.items(): > ... > > will loop over all the key/value pairs in the dictionary. > > -- > Greg Ewing, Computer Science Dept, > University of Canterbury, > Christchurch, New Zealand > http://www.cosc.canterbury.ac.nz/~greg > An extra would be: Data Source: Select region, source from accounts; I want to be able to store the data from the select statement into something like: revenue [source][region = return data from the select statement To loop over the data, I would like to perform something like: for src in revenue: for reg in revenue[source]: for value in revenue[source][region] print something Hope this makes sense. Thanks! kbass From jamesl at appliedminds.com Sat Mar 13 16:45:06 2004 From: jamesl at appliedminds.com (James Laamnna) Date: 13 Mar 2004 13:45:06 -0800 Subject: Problems with unicode Message-ID: I'm trying to write out a XML document using a StringIO class, however I always run into the following error: UnicodeDecodeError: 'ascii' codec can't decode byte 0x92 in position 4: ordinal not in range(128) Apparently in the batch that I'm encoding there is one string with non-ascii characters in it. Is there any way to just have it encode everything as unicode and not ascii? Or should I just strip out non-ascii characters (a last resort which I do not want to do) Thanks. From spam_bait101 at yahoo.com Thu Mar 4 02:32:05 2004 From: spam_bait101 at yahoo.com (sb) Date: 3 Mar 2004 23:32:05 -0800 Subject: vim & python References: <221dd125.0403011151.504ce09d@posting.google.com> Message-ID: <221dd125.0403032332.d4282f4@posting.google.com> spam_bait101 at yahoo.com (sb) wrote in message news:<221dd125.0403011151.504ce09d at posting.google.com>... > I have a bunch of questions about using python scripting in vim and > about editing python with vim. Thanks for all of the answers to the second question, but what about vim scripting with python? I can not find *anything* about it (no docs, books or tutorials) From artur_spruce at yahoo.com Thu Mar 18 04:38:04 2004 From: artur_spruce at yahoo.com (AdSR) Date: 18 Mar 2004 01:38:04 -0800 Subject: Replace accented chars with unaccented ones References: Message-ID: Nicolas Bouillon wrote: > Hi > > I would like to replace accentuel chars (like "????", "????" or "????") with non > accetued ones ("????" -> "e", "????" -> "e", "????" -> "a"). > > I have tried string.replace method, but it seems dislike non ascii chars... > > Can you help me please ? > Thanks. You could try experimenting with the 'unicodedata' module: >>> import unicodedata >>> [unicodedata.name(x) for x in u'123 abc @#$ \u00ff'] ['DIGIT ONE', 'DIGIT TWO', 'DIGIT THREE', 'SPACE', 'LATIN SMALL LETTER A', 'LATIN SMALL LETTER B', 'LATIN SMALL LETTER C', 'SPACE', 'COMMERCIAL AT', 'NUMBER SIGN', 'DOLLAR SIGN', 'SPACE', 'LATIN SMALL LETTER Y WITH DIAERESIS'] >>> unicodedata.lookup('latin capital letter a with grave') u'\xc0' You could strip the ' WITH...' part when applicable and convert names back to string. You would only need to process characters with ord >= 160. HTH, AdSR From harry.g.george at boeing.com Fri Mar 12 13:54:49 2004 From: harry.g.george at boeing.com (Harry George) Date: Fri, 12 Mar 2004 18:54:49 GMT Subject: put your money where your mouse is, or why I prefer Spanish to English: a proposal References: <082d01c407eb$bb8dfc10$210110ac@jsbwxp3> Message-ID: Gerrit writes: > John Benson wrote: > > I propose that we change the language of this board to Spanish, as long as > > we're so vocally committed to using best-of-breed languages. Derived from > > the Iberian dialect of vulgar Latin, Spanish has many important advantages > > over English: > > > Thinly-veiled threat: If this board doesn't immediately cut over to Spanish > > because it is obviously superior to English, I shall be forced to consider > > its badmouthing of other computer languages as just so much small-minded > > special pleading. > > How about Esperanto? > > Zamenhoff-forever-ly - y'rs Gerrit. > > -- > Weather in Twenthe, Netherlands 12/03 11:25 UTC: > 6.0?C haze mostly cloudy wind 5.4 m/s ESE (57 m above NAP) > -- > Asperger's Syndrome - a personal approach: > http://people.nl.linux.org/~gerrit/english/ > Hmmm. How many Pythonistas have studied Esperanto? Looks like 2 of us so far. The Esperanto headquarters is in Netherlands, so there is a suspicious confluence of geography with Python. -- harry.g.george at boeing.com 6-6M21 BCA CompArch Design Engineering Phone: (425) 342-0007 From kkto at csis.hku.hk Fri Mar 26 01:26:18 2004 From: kkto at csis.hku.hk (Isaac To) Date: Fri, 26 Mar 2004 14:26:18 +0800 Subject: Semantics of == References: <40200384.0403161538.7407d9e2@posting.google.com> <105f5pqh0jhs3cd@news.supernews.com> <5d83790c.0403251936.2734dbee@posting.google.com> Message-ID: <7iad24m8dx.fsf@enark.csis.hku.hk> >>>>> "Raymond" == Raymond Hettinger writes: Raymond> [Axel Boldt] >> > >>> l=[1] > >>> s=l > >>> l.append(s) > >>> 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. >> > >> > >>> s[0]=2 > >>> w[0]=2 > >>> s==w > False >> > >> > All of a sudden they have become unequal. Raymond> [John Roth] >> You've got a recursive structure! I originally thought that the [...] >> was something you'd done to the printout, but it isn't. >> >> I think the original True is a bug. It's getting confused by the >> recursion. Raymond> Armin Rigo found and fixed this for Py2.4: Raymond> Python 2.4a0 (#46, Mar 23 2004, 01:55:44) [MSC v.1200 32 bit Raymond> (Intel)] on win32 >>>> s Raymond> [1, [...]] >>>> w Raymond> [1, [1, [...]]] >>>> s==w Raymond> Traceback (most recent call last): File "", line 1, Raymond> in -toplevel- s==w RuntimeError: maximum recursion depth Raymond> exceeded in cmp I'm confused... what makes the new behaviour more "correct" than the original? Regards, Isaac. From catcher at linuxmail.org Sat Mar 27 12:22:44 2004 From: catcher at linuxmail.org (zatoichi) Date: Sat, 27 Mar 2004 12:22:44 -0500 Subject: Choosing Perl/Python for my particular niche In-Reply-To: <106b7k2s8af5c3c@corp.supernews.com> References: <40652B0D.7C313F77@doe.carleton.ca> <40657D14.3FBE7E82@doe.carleton.ca> <106b7k2s8af5c3c@corp.supernews.com> Message-ID: Cameron Laird wrote: > In article <40657D14.3FBE7E82 at doe.carleton.ca>, > My current instinct is that you'll be happiest with Perl-- > but it's a close choice, all around. I'm most accomplished > in Tcl, and would happily use it, or Perl, or Python. It > seems to me, though, that it's crucial that you be able > to exploit libraries that pertain to your domain, and, in > particular, optimized engines for linear algebra, graph > theory, and linear and mathematical programming. Tcl > lacks the weight that Perl and, to an increasing extent, > Python can boast in their libraries. Since you happily use Perl, Python or Tcl, I have a question. How do you decided which one to use? :-) Robert From mgr3 at aber.ac.uk Wed Mar 24 17:50:49 2004 From: mgr3 at aber.ac.uk (Matt) Date: 24 Mar 2004 14:50:49 -0800 Subject: sorting times Message-ID: <4af8e6c7.0403241450.74350e21@posting.google.com> X-No-archive: yes Hi, I'm a cs student, and working on an assignment using python. uber cool except... I have an assignment that requires me to analyse the time complexities of bubble sort and quick sort. I don't want any help - but would like to know if people consider the following times to be 'normal': I have extensively tested both algorithms on smaller sets of data, as well as the parser class i created - quite a few test cases for such a small app. (all tests pass) Environment: Running on linux 2.4 / pentium 4.2 Ghz / 1GB RAM Results: File: two columns, \t, pow(10, 5) lines in file. Bubble Sort takes 32 - 35 minutes Quick Sort takes 8 seconds My quick sort implementation uses random pivot selection and is recursive, the bubble sort is adaptive, uses a "flipped" flag to exit early if data is already sorted. I implemented both algorithms in C , as bubble sort used to take 8 hours. Any comments much appriciated. Matt NB. I haven't posted the code in case of plagerism. From john.abel at pa.press.net Mon Mar 8 03:47:48 2004 From: john.abel at pa.press.net (John Abel) Date: Mon, 08 Mar 2004 08:47:48 +0000 Subject: Gadfly or gadfly or Gadfly.gadfly() or _? In-Reply-To: <20040308004630.1096705640.eric@zomething.com> References: <20040308004630.1096705640.eric@zomething.com> Message-ID: <404C3334.8010804@pa.press.net> On my Linux machine: Python 2.3.3 (#1, Dec 28 2003, 12:13:48) [GCC 3.3 20030226 (prerelease) (SuSE Linux)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import gadfly >>> It looks like your install didn't work properly. You could try running "python setup.py install" again. HTH John Eric @ Zomething wrote: >My interest was piqued enough to try Gadfly, but I find myself struggling to install it, a new problem for this newB. Not sure if any of this is the distribution's "fault" or just my lack of understanding of Python: > >1) I notice there is no py file named "gadfly.py". How does Python find and define the namespace? >2) I have installed the files in this directory under a Windows XP OS: C:\Python23\Lib\site-packages\Gadfly >3) "import gadfly", as shown in the docs, returns an ImportError >4) "import Gadfly" does not return any errors. Is this because of the capitalization of the directory name? > >then, following the instructions in the docs: > > > >>>>connection = gadfly.gadfly() >>>> >>>> >Traceback (most recent call last): > File "", line 1, in ? > connection = gadfly.gadfly() >NameError: name 'gadfly' is not defined > > > >>>>connection=Gadfly.gadfly() >>>> >>>> >Traceback (most recent call last): > File "", line 1, in ? > connection=Gadfly.gadfly() >TypeError: 'module' object is not callable > >Have I somehow mucked up the namespace upon installation? Am I entering the wrong commands? > >Any pointers appreciated. > > >Eric > > > From otto_kruse at hotmail.com Thu Mar 11 05:26:12 2004 From: otto_kruse at hotmail.com (=?ISO-8859-1?Q?Otto_Kr=FCse?=) Date: Thu, 11 Mar 2004 11:26:12 +0100 Subject: py2exe distribution wants internet access (DNS) Message-ID: <40503ec2$0$77271$abc4f4c3@news.wanadoo.nl> Hello, I've made a small GUI program that connects with a MySQL database to collect information which is put on the screen. The database and the program are used for testing purposes so I installed them locally and only use them locally (so on my own computer). When I run the script from a system (WinXP) shell through the python interpreter all goes well. However when I make an executable program of it through py2exe there's a problem. When I start the .exe file the program wants to 'talk' to my DNS on the internet. My firewall sees this and asks me if this all right. Now if say 'yes' to the firewall the program runs as expected. But if I say 'no' my program won't connect to the MySQL server. Now this isn't quite right, I run MySQL locally so DNS access should not be necessary. This firewall stuff also makes distributing the program harder: not all users have access to firewall choices, on some machines programs are blocked by default. Why does the original python script run normally but does the py2exe 'conversion' of it want DNS access? How can I change this? Thanks in advance, Otto Kr?se From llothar at web.de Fri Mar 5 19:20:44 2004 From: llothar at web.de (Lothar Scholz) Date: 5 Mar 2004 16:20:44 -0800 Subject: "Virtual" file system mock object - replacing stuff in __builtins__ References: <404844e3$1@epflnews.epfl.ch> Message-ID: <6ee58e07.0403051620.40d3b42@posting.google.com> Remy Blank wrote in message news:<404844e3$1 at epflnews.epfl.ch>... > As a fan of TDD (test-driven development), I use the unittest module to > write the test cases for these tools. However, to make the test cases > independent of the file system environment, I simulate a file system > tree with a mock object using the following technique (sorry for the > long posting): 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. This is the simplest case to avoid strange effects. From skip at pobox.com Fri Mar 12 22:56:24 2004 From: skip at pobox.com (Skip Montanaro) Date: Fri, 12 Mar 2004 21:56:24 -0600 Subject: Deprecating reload() ??? In-Reply-To: <7ln4501mfe70sgrrk25fn0sj80f6cn8vt7@4ax.com> References: <40514A48.50907@domain.invalid> <09b350henbtk9vnai0v7fhtbsqbmubl7vn@4ax.com> <7cj4c.2733$G3.21896@localhost> <8ok3505b3b3g22bk8ci6iagptqav2cfi6r@4ax.com> <7ln4501mfe70sgrrk25fn0sj80f6cn8vt7@4ax.com> Message-ID: <16466.34408.708759.310700@montanaro.dyndns.org> Just an FYI, I didn't write this statement: Dave> On Fri, 12 Mar 2004 11:42:06 -0600, Skip Montanaro Dave> wrote: >> >> Reload is not broken, and certainly shouldn't be deprecated at least >> >> until there's a better solution that won't suffer from reload's one >> >> problem, IMHO, which is that it surprises some people by its >> >> behaviour. Dave> I've written a short description of what reload() does to try and Dave> help reduce the confusion. This is intended for EEs who are new Dave> to Python. I'm not sure why you're planning to teach them reload(). I've used it rarely in about ten years of Python programming. Its basic semantics are straightforward, but as we've seen from the discussions in this thread things can go subtly awry. Just tell people to either not create references which refer to globals in other modules (e.g. "quote = urllib.quote") if they intend to use reload() or tell them to just exit and restart their application, at least until they understand the limitations of trying to modify a running Python program. Skip From noah at noah.org Tue Mar 16 14:02:01 2004 From: noah at noah.org (Noah) Date: 16 Mar 2004 11:02:01 -0800 Subject: Replace accented chars with unaccented ones References: Message-ID: Nicolas Bouillon wrote in message news:... > Hi > > I would like to replace accentuel chars (like "??", "??" or "??") with non > accetued ones ("??" -> "e", "??" -> "e", "??" -> "a"). > > I have tried string.replace method, but it seems dislike non ascii chars... The following is the code that I use. This looks like what you are asking for. In case this gets corrupted you can also find it here: http://sourceforge.net/snippet/detail.php?type=snippet&id=101229 This has some improvements to readability and speed, but it is basically the same: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/251871 Yours, Noah #!/usr/bin/env python """ UNICODE Hammer -- The Stupid American I needed something that would take a UNICODE string and smack it into ASCII. This function doesn't just strip out the characters. It tries to convert Latin-1 characters into ASCII equivalents where possible. We get customer mailing address data from Europe, but most of our systems cannot handle the Latin-1 characters. All I needed was to prepare addresses for a few different shipping systems that we use. None of these systems support anything but ASCII. After getting headaches trying to deal with this problem using Python's built-in UNICODE support I gave up and decided to write something that would solve the problem the American way -- with brute force. I convert all european accented letters to their unaccented equivalents. I realize this isn't perfect, but for my purposes the packages get delivered. Noah Spurrier noah at noah.org License free and public domain """ def latin1_to_ascii (unicrap): """This replaces UNICODE Latin-1 characters with something equivalent in 7-bit ASCII. All characters in the standard 7-bit ASCII range are preserved. In the 8th bit range all the Latin-1 accented letters are stripped of their accents. Most symbol characters are converted to something meaninful. Anything not converted is deleted. """ xlate={0xc0:'A', 0xc1:'A', 0xc2:'A', 0xc3:'A', 0xc4:'A', 0xc5:'A', 0xc6:'Ae', 0xc7:'C', 0xc8:'E', 0xc9:'E', 0xca:'E', 0xcb:'E', 0xcc:'I', 0xcd:'I', 0xce:'I', 0xcf:'I', 0xd0:'Th', 0xd1:'N', 0xd2:'O', 0xd3:'O', 0xd4:'O', 0xd5:'O', 0xd6:'O', 0xd8:'O', 0xd9:'U', 0xda:'U', 0xdb:'U', 0xdc:'U', 0xdd:'Y', 0xde:'th', 0xdf:'ss', 0xe0:'a', 0xe1:'a', 0xe2:'a', 0xe3:'a', 0xe4:'a', 0xe5:'a', 0xe6:'ae', 0xe7:'c', 0xe8:'e', 0xe9:'e', 0xea:'e', 0xeb:'e', 0xec:'i', 0xed:'i', 0xee:'i', 0xef:'i', 0xf0:'th', 0xf1:'n', 0xf2:'o', 0xf3:'o', 0xf4:'o', 0xf5:'o', 0xf6:'o', 0xf8:'o', 0xf9:'u', 0xfa:'u', 0xfb:'u', 0xfc:'u', 0xfd:'y', 0xfe:'th', 0xff:'y', 0xa1:'!', 0xa2:'{cent}', 0xa3:'{pound}', 0xa4:'{currency}', 0xa5:'{yen}', 0xa6:'|', 0xa7:'{section}', 0xa8:'{umlaut}', 0xa9:'{C}', 0xaa:'{^a}', 0xab:'<<', 0xac:'{not}', 0xad:'-', 0xae:'{R}', 0xaf:'_', 0xb0:'{degrees}', 0xb1:'{+/-}', 0xb2:'{^2}', 0xb3:'{^3}', 0xb4:"'", 0xb5:'{micro}', 0xb6:'{paragraph}', 0xb7:'*', 0xb8:'{cedilla}', 0xb9:'{^1}', 0xba:'{^o}', 0xbb:'>>', 0xbc:'{1/4}', 0xbd:'{1/2}', 0xbe:'{3/4}', 0xbf:'?', 0xd7:'*', 0xf7:'/' } r = '' for i in unicrap: if xlate.has_key(ord(i)): r += xlate[ord(i)] elif ord(i) >= 0x80: pass else: r += i return r # This gives an example of how to use latin1_to_ascii(). # This creates a string will all the characters in the latin-1 character set # then it converts the string to plain 7-bit ASCII. if __name__ == '__main__': s = unicode('','latin-1') for c in range(32,256): if c != 0x7f: s = s + unicode(chr(c),'latin-1') print 'INPUT:' print s.encode('latin-1') print print 'OUTPUT:' print latin1_to_ascii(s) From dmq at gain.com Fri Mar 5 14:30:35 2004 From: dmq at gain.com (David MacQuigg) Date: Fri, 05 Mar 2004 12:30:35 -0700 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> <22af40pkcecubm2o76a7g6aknj89rq1psu@4ax.com> <0370d5ccac8adfc1054d7802ef3e0ba0@news.teranews.com> Message-ID: On Fri, 05 Mar 2004 12:35:01 GMT, Dang Griffith wrote: >In any case, I think the one-liner posted satisfies nearly all of the >requirements. > >import sys >def pr(*args): sys.stdout.write(''.join([str(i) for i in args])) > >Where it fails is the difference between a function and a statement. >The OP said [one of] the advantages of a statement is that there is no >need for parenthesis. This is the reason I brought up the point that >a function and a statement are semantically different, and why none of >the function-based suggestions will satisfy the OP's plea. The inconvenience of typing a single set of parens seems trivial to me in comparison to the extra burden of an additional syntax. In reading someone else's code, I rely on the *syntactic* difference between functions and statements to convey possibly different *symantics*. If it says print a,b,c I know exactly what that statement means. If it says prn(a,b,c) I know to look for a definition of 'prn'. Note that in this case, there are *two* syntactic differences, the parens and the keyword. The keyword difference is essential, because you *can* say print(a,b,c) and still be using the built-in print statement (although with a slightly different result.) So, do what you like with the parens, but leave the keywords alone. Beyond this one statement, the idea might work as a general enhancement. If the first token in a statement is not a keyword, and the second is not an assignment operator, then look for a function definition, and don't require parens. This would allow you to say 'printF a,b,c' or 'importR module' and have these functions/statements do whatever you want. At this point my vote for adding more syntax to Python would be -1. I prefer the added readability of a more consistent use of parens over the convenience of leaving them off. I see the parens as having much the same role as the unnecessary ':' at the end of some statements. It clues beginners as to the structure of a statement, and it enhances readability for experts. Now if we want to talk about getting rid of 'self.' ... :>) -- Dave From newsgroups at jhrothjr.com Mon Mar 29 14:52:34 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 29 Mar 2004 14:52:34 -0500 Subject: Integer, 64 Bit, signed and unsigned References: Message-ID: <106gvmljo0q1m83@news.supernews.com> "Torsten Mohr" wrote in message news:c49t6n$4mh$1 at schleim.qwe.de... > 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? Yes and no. Python has unlimited precision long integers, so it should work without any special effort for most things. If you're trying to exploit truncation at the 64 bit mark, though, you'll have to do it yourself with tests. John Roth > > > Thanks for hints, > Torsten. > From rzantow at ntelos.net Mon Mar 29 11:26:37 2004 From: rzantow at ntelos.net (rzed) Date: Mon, 29 Mar 2004 16:26:37 GMT Subject: tabbing probs (was: Prothon Prototypes vs Python Classes) References: <106gg1jifa2n9c2@news.supernews.com> <406848CD.5070100@mlug.missouri.edu> Message-ID: Michael wrote in news:406848CD.5070100 at mlug.missouri.edu: > >>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. >> >> > No, I just fail to see why it matters. A tab could be 4 columns, > 8 columns, 15 columns, or whatever on a particular editor and > code blocks will still line up. > >>It matters. 8 columns is much too wide for indents in readable >>code. People do differ on that, but that seems to be the >>concensus. >> >> > So rather than switch editors or change your editors settings > you'd rather everyone be forced to use spaces? I presume four > spaces? If someone uses eight spaces to indent will that also > break the code? It seems to me that it'd be easier to configure > an editor to show tabs as four columns, if you so desire, than > to configure an editor to show eight spaces as four columns. > Eight spaces is no easier to read than a tab that takes eight > columns. It's just more typing to correct the problem. > > By my own preference, if I'm forced to use spaces to indent > rather than tabs, then I'll most likely use a single space to > indent because I don't want to deal with pressing the space and > backspace keys multiple times (trying to keep count) to make > blocks line up correctly. I also don't find it acceptable to use > an editor which kludges together such space using behavior for > me to do what tabs would have done in the first place. Overall, > I think I find code that uses a single tab, rather than a single > space, to be easier to read. > As long as you are the only one to work on your code, your viewpoint may not cause you any problems. I and others are telling you that tabs can cause problems with some software, and you can rightly avoid using that software as long as you don't share your code. Once that happens, though, things get more complicated. One aspect of the tab/spaces issue involves working on other people's code. You like tabs, I like spaces. Supposing that I prefer to show a single level of indention as five spaces (for some reason), what happens when I have to make a change to your code? If I am aware that you use tabs, then I can adjust to it, but how do I become aware? To me, it looks like you're putting five spaces in for each level of indention. The chances are that I won't know otherwise until I've made some changes, saved the file and tried to run it. If some of those changes involve changing an indention level, I may insert spaces before or after your tabs, so now such a change leaves a line with mixed tabs and spaces, but no visible indication of which is where. Now when someone else grabs the code and displays it with tabs set to four spaces instead, what happens? No sympathy there, either, I would bet, but you do see how things like that can happen even using only your tools, don't you? -- rzed From michele.simionato at poste.it Tue Mar 30 23:49:02 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 30 Mar 2004 20:49:02 -0800 Subject: Prothon Prototypes vs Python Classes References: <569c605ld1cj8fc1emolk08ete0s1prls1@4ax.com> <106di86neu1qh4d@news.supernews.com> <4069a001$0$4237$afc38c87@news.easynet.co.uk> Message-ID: <95aa1afa.0403302049.4d5d4c91@posting.google.com> Peter Hickman wrote in message news:<4069a001$0$4237$afc38c87 at news.easynet.co.uk>... > I have never left a group because of the trolls. > I have never left a group because of the noobies. > I have left a group because of the constant whining about top posting. Then maybe you should consider leaving c.l.py ? Michele Simionato From jeder at earthlink.net Mon Mar 29 02:59:36 2004 From: jeder at earthlink.net (Ryan Spencer) Date: Mon, 29 Mar 2004 07:59:36 GMT Subject: Python installing on Debian References: Message-ID: > It actually needn't be that messy. dpkg --purge'ing will only remove the > package in question, whereas using a program such as debfoster and pruning > the selected target package will remove all it's associate dependencies > entirely eradicating it from your system, maybe leaving behind empty > configuration folders in your home directory, but there's no fret for > that those won't be taking up barely any space and you can always remove > them later. > > So, I'd say use debfoster and prune the python2.3 package. It won't be a > messy process at all. Just remember, when it prompts the package > python2.3, remember to push 'p' for prune, not 'n' for that 'n' (standing > for 'no') will do the same thing as dpkg --purge and simply remove the > package in question. > > There is the beginning concern of when using debfoster it will inquire > about every single dpkg on your system (If I am correct, it should read > something alike the apt-cache which, even with manual installation of > dpkg's, still is written to, keeping a meticulous record of all dpkg's > on your system. If not the apt-cache, I know it's another file.) But once > you get past all the programs you want and don't want, it keeps the > remaining information in the /var/lib/debfoster/keepers file, which you > can always edit if you accidentilly kept something. > > And also, I wouldn't say installing certain packages would break > much - although I wouldn't mark out the possibility of it happening in > unstable and testing, I sometimes forget constant recorrection I had to > go through. Possible replacement of certain library > files for applications, but that's also an issue of whether or not the > actual library file or application itself has issues, and that's a risk > you take in using unstable and testing. For example, I have an Nvidia > Geforce four and I would constantly have problems with glibc conflicting > with my video card. If you wander through the debian newsgroups you'll > notice many others have experienced the same problem, it's merely a > question of the glibc's lack of testing - which is why it's in the testing > phase of debian. > > The underline is that testing and unstable are more for those that A) > Don't mind having sometimes broken packages in exchange for bleeding edge > software and B) Developers helping in the aid of testing out applications > and hopefully moving testing into it's 'stable' state if tested vigorously > enough. > > Take Care, > ~Ryan Also, though, Reading back through, He is right about the possible self-compiled modules, which then I would also advise using stow for keeping things neat. ~Ryan From werner.merkl at fujitsu-siemens.com Thu Mar 11 07:26:25 2004 From: werner.merkl at fujitsu-siemens.com (Werner Merkl) Date: Thu, 11 Mar 2004 13:26:25 +0100 Subject: py2exe win32all: Can write, but not read FileVersion ... Message-ID: 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. BTW: I found the same behavior for (most/all?) .pyd from win32all and for PythonWin.exe. Any idea? Thanks in advance Werner Merkl Versions I use: - Python 2.3.3 - win32all 163 - py2exe 0.5.0 Source code: ------------ getfileversion.py ---------------------------------- import os, win32api, sys ver_strings=('Comments','InternalName','ProductName', 'CompanyName','LegalCopyright','ProductVersion', 'FileDescription','LegalTrademarks','PrivateBuild', 'FileVersion','OriginalFilename','SpecialBuild') ##fname = os.environ["comspec"] fname = sys.argv[0] d=win32api.GetFileVersionInfo(fname, '\\') ## backslash as parm returns dictionary of numeric info corresponding to VS_FIXEDFILEINFO struc for n, v in d.items(): print n, v print "%s: %d.%d.%d.%d" % (fname,d['FileVersionMS'] / (256*256), d['FileVersionMS'] % (256*256), d['FileVersionLS'] / (256*256), d['FileVersionLS'] % (256*256)) pairs=win32api.GetFileVersionInfo(fname, '\\VarFileInfo\\Translation') ## \VarFileInfo\Translation returns list of available (language, codepage) pairs that can be used to retreive string info ## any other must be of the form \StringfileInfo\%04X%04X\parm_name, middle two are language/codepage pair returned from above for lang, codepage in pairs: print 'lang: ', lang, 'codepage:', codepage for ver_string in ver_strings: str_info=u'\\StringFileInfo\\%04X%04X\\%s' %(lang,codepage,ver_strin g) ## print str_info print ver_string, win32api.GetFileVersionInfo(fname, str_info) ------------ setup.py ---------------------------------- # A setup script showing advanced features. # # Note that for the NT service to build correctly, you need at least # win32all build 161, for the COM samples, you need build 163. # Requires wxPython, and Tim Golden's WMI module. from distutils.core import setup import py2exe import sys # If run without args, build executables, in quiet mode. if len(sys.argv) == 1: sys.argv.append("py2exe") sys.argv.append("-q") class Target: def __init__(self, **kw): self.__dict__.update(kw) # for the versioninfo resources self.version = "0.5.0" self.company_name = "No Company" self.copyright = "no copyright" self.name = "py2exe sample files" ################################################################ # A program using wxPython # The manifest will be inserted as resource into test_wx.exe. This # gives the controls the Windows XP appearance (if run on XP ;-) # # Another option would be to store it in a file named # test_wx.exe.manifest, and copy it with the data_files option into # the dist-dir. # manifest_template = ''' %(prog)s Program ''' RT_MANIFEST = 24 test_wx = Target( # used for the versioninfo resource description = "A sample GUI app", # what to build script = "test_wx.py", other_resources = [(RT_MANIFEST, 1, manifest_template % dict(prog="test_wx"))], ## icon_resources = [(1, "icon.ico")], dest_base = "test_wx") test_wx_console = Target( # used for the versioninfo resource description = "A sample GUI app with console", # what to build script = "test_wx.py", other_resources = [(RT_MANIFEST, 1, manifest_template % dict(prog="test_wx"))], dest_base = "test_wx_console") getfilever = Target( # used for the versioninfo resource description = "test version", # what to build script = "getfilever.py", other_resources = [(RT_MANIFEST, 1, manifest_template % dict(prog="getfilever"))], dest_base = "getfilever") ################################################################ # A program using early bound COM, needs the typelibs option below test_wmi = Target( description = "Early bound COM client example", script = "test_wmi.py", ) ################################################################ # a NT service, modules is required myservice = Target( # used for the versioninfo resource description = "A sample Windows NT service", # what to build. For a service, the module name (not the # filename) must be specified! modules = ["MyService"] ) ################################################################ # a COM server (exe and dll), modules is required # # If you only want a dll or an exe, comment out one of the create_xxx # lines below. interp = Target( description = "Python Interpreter as COM server module", # what to build. For COM servers, the module name (not the # filename) must be specified! modules = ["win32com.servers.interp"], ## create_exe = False, ## create_dll = False, ) ################################################################ # COM pulls in a lot of stuff which we don't want or need. excludes = ["pywin", "pywin.debugger", "pywin.debugger.dbgcon", "pywin.dialogs", "pywin.dialogs.list"] setup( options = {"py2exe": {"typelibs": # typelib for WMI [('{565783C6-CB41-11D1-8B02-00600806D9B6}', 0, 1, 2)], # create a compressed zip archive "compressed": 1, "optimize": 2, "packages": ["encodings"], "excludes": excludes}}, # The lib directory contains everything except the executables and the python dll. # Can include a subdirectory name. zipfile = "lib/shared.zip", console = [getfilever] ## service = [myservice], ## com_server = [interp], ## console = [test_wx_console, test_wmi], ## windows = [test_wx], ) From steve at ninereeds.fsnet.co.uk Sun Mar 7 22:30:00 2004 From: steve at ninereeds.fsnet.co.uk (Stephen Horne) Date: Mon, 08 Mar 2004 03:30:00 +0000 Subject: Working around a lack of 'goto' in python References: Message-ID: On Sun, 7 Mar 2004 14:33:38 -0800, "Roger Binns" wrote: >Brett wrote: >> Two areas where I've found 'goto' two be useful in other languages are in >> (untested examples in C++) > >What you have is what many other languages allow with integers after break or >continue statements. For example you can do 'break 2' or 'continue 3' to >break or continue out of the respective number of enclosing for loops. Which languages? The nearest I've seen is in Ada, where it is possible (but not normal practice) to name loops. The equivalent of 'break' can then name which loop it is referring to. IIRC, an example might be... outer: loop inner: loop ... exit when ...; -- by default, exit only the inner loop exit inner when ...; -- explicitly exit the inner loop exit outer when ...; -- explicitly exit both the inner and outer -- loops end loop; end loop; I can't remember ever needing this, but then it's nearly 6 years since I last used Ada in anger. 'break 2' is not something that I've seen, though it wouldn't surprise me as a vendor specific extension in C or C++, or maybe as a Perl thing. My first impression of it is that it is probably a maintenance nightmare. If you are using break to exit several nested loops, then the break statement is likely obscured by other code. It isn't likely to stand out to maintainers. When a new level of nesting gets added, or a level of nesting gets taken out, during maintenance the maintainer could easily miss the need to change the number on the break statement. Of course this can be an issue with any break/continue from a loop, but these statements can been used relatively safely in small loops where they will be seen. The programmer is responsible for using language features appropriately and not otherwise. The thing is, I'm not convinced there can be an appropriate case for breaking several nested loops that way. In Ada, at least the loops are explicitly named - adding or removing a layer of nesting will not change which loop the exit statement actually exits. Though even then, I don't remember ever seeing it used for real. Also, the thought of someone specifying the integer using a variable or expression is somehow making me think of gothic castles, dark stormy nights, thunder and lightening, and the distant howling of wolves. I'm thinking 'I'd much rather be there than debugging a mess like that' ;-) >I don't like the rewriting as it greatly complicates the code, and you are >having to write something different than what you mean in your head. >Maybe someone wants to take this on as a PEP? We need a real use case. I can't imagine needing the feature you describe. Sometimes, people get into coding habits using what they know just because it is there and not realising that there are better ways to handle it. Often, even 'what you mean in your head' gets imagined that way purely as result of a bad habit. Sometimes you need to make what amounts to a paradigm shift. I've been there and done that too many times. Maybe I'm wrong, but I'm very suspicious about this right now. If I am wrong (perhaps it's me that needs to do the paradigm shift thing after all) then I'd much rather Python went with the Ada route of naming loops rather than adding gotos or allowing a number-of-levels parameter for break and continue. -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From theller at python.net Mon Mar 8 16:04:39 2004 From: theller at python.net (Thomas Heller) Date: Mon, 08 Mar 2004 22:04:39 +0100 Subject: py2exe - omitting DLLs (not Python extensions!) from the distribution References: <1xo3yt01.fsf@yahoo.co.uk> Message-ID: Paul Moore writes: > I have a Python application, which uses cx_Oracle for database access. > I am wrapping it up into an EXE using py2exe - the result is very > nice, and easy to distribute. However, the dependency tracking picks > up OCI.dll as a dependency of cx_Oracle. Now, OCI.dll is actually an > Oracle-supplied DLL, part of the Oracle client. I definitely *don't* > want to include this in my built distribution, as it depends on the > version of the Oracle client installed, and this may differ between > the build machine and the target machine. > There's a dll_excludes option, which you can use in this way: setup(... options = {"py2exe": { "dll_excludes": ["oci.dll"]}}) It would also be possible to add this to a setup.cfg file, but I prefer to have everything in the setup script only. That is also the reason that there are only very few command-line options left. > I'd rather not have to remember to delete OCI.dll as part of the build > process. > > I've searched the py2exe documentation, but I can't see a way of doing > this. Can anyone suggest a way? For now, the documentation for advanced features is supplied by the users and maintained in the py2exe wiki (hint, hint): http://starship.python.net/crew/theller/moin.cgi/Py2Exe This seems to work pretty nice (and I'd like to thank again any contributors). Once you have understood all the features, a short reference is included in the py2exe docstring, which you can display by entering help("py2exe") at the python prompt, or hit C-c C-h py-help-at-point in a python-mode (x)emacs buffer on the 'py2exe' symbol. Thomas From donn at u.washington.edu Mon Mar 8 17:46:49 2004 From: donn at u.washington.edu (Donn Cave) Date: Mon, 08 Mar 2004 14:46:49 -0800 Subject: Working around a lack of 'goto' in python References: Message-ID: In article , "Roger Binns" wrote: ... > Just like multiple-inheritance, this may be of no use to you or > a construct you feel is too dangerous for your code. That doesn't > mean it should be prevented from others using it. > > Several pieces of my code would greatly benefit from break/continue > of multiple depths. They currently use extra variables and exceptions > and have had a tendency to be somewhat buggy due to the extra complexity > and the mismatch between my mental model and what the language allows. I believe you'd be able to get the same benefit from goto - nearly identical solution, really. Of course it can be used a lot of other ways, but you couldn't really argue that's a bad thing, given your position stated above. I mean, either Python should incorporate all features that someone finds useful, and leave taste and judgement to the user, or it shouldn't. So it seems like goto is the ticket, following your line of reasoning. Donn Cave, donn at u.washington.edu From tassilo.parseval at rwth-aachen.de Sat Mar 27 03:28:36 2004 From: tassilo.parseval at rwth-aachen.de (Tassilo v. Parseval) Date: 27 Mar 2004 08:28:36 GMT Subject: Choosing Perl/Python for my particular niche References: <40652B0D.7C313F77@doe.carleton.ca> Message-ID: Also sprach Fred Ma: > This is not a troll posting, and I've refrained from > asking because I've seen similar threads get all > nitter-nattery. But I really want to make a decision > on how best to invest my time. I'm not interested on > which language is better in *general*, just for my > purpose. My area of research is in CAD algorithms, > and I'm sensing the need to resort to something more > expedient than C++, bash scripting, or sed scripting. > What I hope to do is a bit multifaceted. What I don't > do dabble in is web apps (though I'm not sure of the > similarities). No XML processing or database > interaction in what I do. Who knows, though. The desire to do certain things grows with the skills one acquired. > 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. In the > past, I've eeked out sed scripts for such tasks, but > would appreciate a more traditional language. Since > Perl is used alot in digital IC design, I took a stab > at that, motivated by the simple need to convert my > mail aliases from one mail reader to the other. It > took a while to do, and I'm concerned at the difficulty > level. If I did this kind of thing constantly, I > would probably get proficient and use the power behind > it, but it's not my main area. That sounds like a text-processing task. Perl's strengths in this area are well-known, so there's no need to go into that deeper. Most scripting languages (and that includes Python) can be used here. > The alternative is Python, which is easier to read > from what I've read. My concern there is that I cut > myself off from large availability of stuff that's > out there. For example, I use a PC-to-solaris > viewer called VNC, and I've banged my head against the > startup script to change it a bit for my situation. > Likewise, the above translator uses Perl extensively > in its operation, as well as it's building and > installation. If I wasn't passingly familiar with > Perl, I would have had a much harder time installing > it. Being in the approximate area digit circuits, > I'm concerned about being on the band wagon, if only > to avoid reinventing things, or impediments to sharing > things. This is a strong reason to use Perl. While it may not always be desirable to toe the line, here it is. The availability of tools that can easily be integrated into one's own work will save you a lot of work on the long run. I didn't know that Perl was particularly strong in the field of IC design. If so, good then. Apart from this particular case, it's generally a good thing when pre-written code exists that can be used. The amount of such code for Perl is immense (several thousand libraries) and gathered all in one place (the CPAN) with a unified interface to access and install them and a vast infrastructure built around it. I don't know how much or whether at all the situation for Python has significantly improved over the recent past. A while ago at least there was no such thing. > An additional usage scenario is to (if reasonable) > replace my shell scripting e.g. I just converted to > bash from tcsh to write scripts that push a document > through a series of filters, or simply as a wrapper > around a tough-to-use utility e.g. pstops. A final > example is to take a file of design information and > do more than tweak it e.g. extract all the information > about interconnections between circuit building blocks, > including which is the source block, and which are the > destination blocks. Typically, this information will > be read by matlab scripts and passed to my C++ code > (I've managed to avoid writing code to parse the > input file from C++). As with text processing, both Python and Perl offer all the essential things needed for that. On a cursory glance, the score of them is tied. > Whichever way I go, I would like to avoid the overhead > of learning both Perl and Python. I will sculpt out some > time in a miserly fashion to slowly get to know one. Since > I spend most of my time exploring the algorithm in Matlab or > C++/STL, there's only so much time to pick up higher level > languages (it took years before I shelled out the time > to switch from tcsh to bash). One of the things that > makes the decision not clear is that despite Python's > claim to a gentler learning curve and clearer code, I > often like the expedience of sed e.g. a terse one-liner > that can be pipelined with other shell commands. I > also note that Perl's unweldiness only comes for big > projects, and I don't expect to using Perl quite that > way. Perl wins when it comes to one-liners and maybe replacing shell scripts. As I tend to forget the syntax of bash's scripting language easily, I've replaced it entirely with Perl. Perl's bad reputation for big projects is probably due to the variance of those people using Perl. One large group is sys-admins who use Perl in an entirely different way as compared to someone building larger systems. However, there are enough very large Perl projects that show that it can be used for that just as easily (at least as long as one keeps the sys-admins away from the source;-). > I've seen mention of parrot and perl6, which is quite a > ways off. I'm not sure how much that should weigh into > my decision, since it isn't real yet. It shouldn't. Perl6 is mostly yet another leap towards fitness for large projects. I don't think it will gain much for those more hackish tasks. Also, no one quite knows when Perl6 will be due. Tassilo -- $_=q#",}])!JAPH!qq(tsuJ[{@"tnirp}3..0}_$;//::niam/s~=)]3[))_$-3(rellac(=_$({ pam{rekcahbus})(rekcah{lrePbus})(lreP{rehtonabus})!JAPH!qq(rehtona{tsuJbus#; $_=reverse,s+(?<=sub).+q#q!'"qq.\t$&."'!#+sexisexiixesixeseg;y~\n~~dddd;eval From duncan-news at grisby.org Mon Mar 29 04:42:45 2004 From: duncan-news at grisby.org (Duncan Grisby) Date: Mon, 29 Mar 2004 11:42:45 +0200 Subject: odd behaviour with embedded python and omniorb References: <6c5f2ab0.0403250846.6e773bb0@posting.google.com> Message-ID: <6746b$4067ef95$51604868$13336@nf3.news-service-com> In article , Paul wrote: >> How does it fail? >y", line 4, in ? > from omniORB import CORBA > File "./__init__.py", line 357, in ? >ImportError: No module named omni_func That's fixed in CVS. Get the CVS contents or the latest nightly snapshot and the problem should go away. Cheers, Duncan. -- -- Duncan Grisby -- -- duncan at grisby.org -- -- http://www.grisby.org -- From Pieter.Claerhout at Creo.com Thu Mar 4 03:08:17 2004 From: Pieter.Claerhout at Creo.com (Pieter Claerhout) Date: Thu, 4 Mar 2004 09:08:17 +0100 Subject: I can't use cx_Oracle..help me. Message-ID: <490316A24CC5D411ACD700B0D078F7F00660411A@cseexch01.cse.creoscitex.com> Unfortunately, the name of the DLLs is not included in your email, but I presume it's looking for the oci.dll file. Do you have the Oracle client tools installed on your system? If not, cx_Oracle will not work as it requires you to have the Oracle client tools installed. 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 slackgg at 163.com Sent: 04 March 2004 03:30 To: python-list at python.org Subject: I can't use cx_Oracle..help me. hello all: i import cx_Oracle modules will show "Traceback (most recent call l File "", line 1, in ImportError: DLL load failed: can't find ..." -- http://mail.python.org/mailman/listinfo/python-list From peter at engcorp.com Mon Mar 22 07:26:16 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 22 Mar 2004 07:26:16 -0500 Subject: [OT] Compilable Python-like language? In-Reply-To: <405ed061$0$10776$afc38c87@news.easynet.co.uk> References: <405ed061$0$10776$afc38c87@news.easynet.co.uk> Message-ID: Peter Hickman wrote: > 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). Heh heh... here's the smiley you missed: :-) -P From axel.koehler at tu-berlin.de Thu Mar 11 13:23:23 2004 From: axel.koehler at tu-berlin.de (Axel Koehler) Date: Thu, 11 Mar 2004 19:23:23 +0100 Subject: Start and control an extern program Message-ID: Hallo, I want to start an extern program and simple stop it, after a given time, if not succesfull finished. OS is Linux Axel -- ___________________________________________________________________________ Axel K"ohler, axel.koehler at tu-berlin.de Tel: 030-314 73141 From junkmail at solumslekt.org Mon Mar 22 02:30:18 2004 From: junkmail at solumslekt.org (Leif B. Kristensen) Date: Mon, 22 Mar 2004 08:30:18 +0100 Subject: PyQt database example Message-ID: Can somebody point me to a quick example on how to display the result of an SQL query in a PyQt QListBox? I've googled in vain for this. regards, -- Leif Biberg Kristensen http://solumslekt.org/ Validare necesse est From xholcik1 at fi.muni.cz Fri Mar 26 08:45:59 2004 From: xholcik1 at fi.muni.cz (Lukas Holcik) Date: Fri, 26 Mar 2004 13:45:59 GMT Subject: store tag content with SGMLParser ... ? Message-ID: Hi Python people! I'd like to ask you a question about parsing html with SGMLParser class from module sgmllib. Is there a way I could get contents of a tag with certain properties? For example: I'd like to get a list of all contents and hrefs of tags, which have certain value of "class" property: BLABLABLA I'd like to get stored the "http://example.com" and the "BLABLABLA", while class="section". Probably with the use of SGMLParser method handle_data. Or better use different approach? Thanks for answers!:) #Luk From jcarlson at nospam.uci.edu Thu Mar 18 16:32:53 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Thu, 18 Mar 2004 13:32:53 -0800 Subject: python-dev Summary for 2004-02-01 through 2004-02-29 In-Reply-To: References: <105hf8biugij2d2@news.supernews.com> Message-ID: > I do it. I have some code that talks to pySerial. On Windows > it can throw an exception type that is part of win32all and > hence not present on other platforms. > > modeignoreerrortypes=[ commport.CommTimeout, > common.CommsDeviceNeedsAttention ] > try: > import pywintypes > modeignoreerrortypes.append(pywintypes.error) > except: > pass > > # has to be tuple or it doesn't work > modeignoreerrortypes=tuple(modeignoreerrortypes) > > Later on in my code I detect a broken driver (most of the > time I am actually talking to USB to serial connections). > When that happens it starts giving dud exceptions which > I add to the above list (I only want to do it for the > broken driver, not all cases). There is nothing wrong with adding tuples. I would expect that normally the number of exceptions is somewhat small, so the overhead of tuple addition is not that bad... modeignoreerrortypes=(commport.CommTimeout, common.CommsDeviceNeedsAttention) try: import pywintypes modeignoreerrortypes += (pywintypes.error,) except: pass - Josiah From stewart at midwinter.ca Mon Mar 29 21:36:08 2004 From: stewart at midwinter.ca (Stewart Midwinter) Date: 29 Mar 2004 18:36:08 -0800 Subject: Socket Help References: Message-ID: <9396ba6f.0403291836.77573da1@posting.google.com> Lindstrom Greg - glinds wrote in message news:... > I'd ask if there is a simple way to verify my socket is still communicating. how about this, taken from a non-blocking socket class's Connect method: class NBSocket: def __init__(self): self.__host = 'localhost' self.__port = 177 self.__myconnection = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) self.__myconnection.setsockopt(0,socket.SO_KEEPALIVE,1) self.__connected = 0 return def connect(self, host = 'localhost', port = 177, applicationName = 'NBSocket'): """ ======================================================================c+ NBSocket.connect(self,host,port,applicationName) This procedure opens the connection to the socket defined in __init__ it takes the host name, prot number and application name as aruguments host defaults to localhost port defaults to 177 application name defaults to None It tries to connect once and if it doesn't get a response after 5 seconds or if it can't connect right away it raises a socket.error exception ======================================================================c- """ # Test to see if we are already connected if self.__connected: print "This socket is already connected" return 1 self.__host = host self.__port = int(port) self.__applicationName = applicationName counter = 0 try: failed = 1 while failed: try: self.__myconnection.recv(1024) self.__connected = 1 self.__myconnection.setblocking(1) failed = 0 print 'connected' except socket.error: print 'unable to connect' counter = counter + 1 time.sleep(1) if counter > 5: raise except socket.error: raise then continue on with your communication with the server... cheers, S From rogerb at rogerbinns.com Mon Mar 8 01:24:43 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Sun, 7 Mar 2004 22:24:43 -0800 Subject: Working around a lack of 'goto' in python References: Message-ID: <36gth1-42c.ln1@home.rogerbinns.com> > This has to be the worst idea I've seen in a long time. Well, it is popular enough to be in shell scripting (digit form), several forms of Basic (either form), another poster mentioned ADA, and I have seen it in other languages which I have forgotten. Note that your mental model is one of "I want to continue/break *that* loop". When *that* is the enclosing loop, break/continue is easy. When it is outside the enclosing loop, you then have to figure out how to transfer control to the appropriate location using exceptions, state variables and who knows what else. > Breaking out of multiple nested loops of various depths is actually very > simple. Raise an exception, and catch it outside the loop. That works in the trivial case. It gets way more complicated if there are multiple locations you want to do the 'break 2' and 'continue 2' from (and exceptions pretty much only cover the 'break' case anyway without even more work). Here is an example of code using break/continue with numbers. Try it using exceptions. Note that this form of code is fairly common when doing parsing/interpretting of files and building up data structures (ie same place you tend to see gotos in C) for l1 in loop1: do stuff while loop2: do other stuff for l3 in loop3: do more stuff if blah blah: break 2 if foo bar: continue 3 do stuff harder if orange: continue 2 do stuff hardest Roger From tdelaney at avaya.com Tue Mar 2 16:03:44 2004 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Wed, 3 Mar 2004 08:03:44 +1100 Subject: Thoughts on new vs traditional idioms Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE013E6975@au3010avexu1.global.avaya.com> > From: Peter Otten > > Do you have a class with immutable instances handy where the following > assertion fails? > > assert immutableObj.__class__(immutableObj) is immutableObj Jeff's already replied with ImmutableSet, but in any case, user-defined immutable classes are very likely to not have this property. class Point: def __init__(self, point): self.x, self.y = point.x, point.y Most user-defined classes do not implement __new__. Tim Delaney From peter at semantico.com Fri Mar 12 09:00:34 2004 From: peter at semantico.com (Peter Hickman) Date: Fri, 12 Mar 2004 14:00:34 +0000 Subject: put your money where your mouse is, or why I prefer Spanish to English: a proposal In-Reply-To: References: Message-ID: <4051c282$0$14973$afc38c87@news.easynet.co.uk> John Benson wrote: How about hawian(?), it only uses 11 characters and would by much more usable on a PDA as you would need less keys. From littlejohn.75 at news.noos.fr Mon Mar 8 14:31:36 2004 From: littlejohn.75 at news.noos.fr (F. Petitjean) Date: 08 Mar 2004 19:31:36 GMT Subject: Can python read up to where a certain pattern is matched? References: <404ba3cb$0$279$626a14ce@news.free.fr> Message-ID: <404cca18$0$277$626a14ce@news.free.fr> On 07 Mar 2004 22:35:55 GMT, F. Petitjean wrote: >> >> Please give a hint. Thank you! >> > the hint : > import itertools > help(itertool.takewhile) > > # not tested (no python 2.3 on Debian gateway at home) > > import itertools < snip a piece of code full of bugs > > > text = """\ > Some words here, and some other words. Then another > segment follows, and more. This is a question, a junk > question, followed by a question mark?""" > > for sentence in readsentence(text): > print sentence A lightly tested version : def readsentence(iterable, ends = (".", "!", "?"), yield_fn=''.join): """generator function which yields sentences terminated by ends""" end_pred = ends if not callable(ends): end_pred = lambda c : c in ends it = iter(iterable) sentence = [] add = sentence.append while True: c = it.next() if not end_pred(c): add(c) else: # Now add the item terminating the sentence add(c) t = tuple(sentence) if callable(yield_fn): t = yield_fn(t) yield t sentence[:] = [] # add = sentence.append if sentence: t = tuple(sentence) if callable(yield_fn): t = yield_fn(t) yield t Regards From curzio.basso at unibas.ch Mon Mar 8 12:48:19 2004 From: curzio.basso at unibas.ch (Curzio Basso) Date: Mon, 08 Mar 2004 18:48:19 +0100 Subject: [Numeric] why is Float32 incorrect for ufuncs? In-Reply-To: <404757b9$1@maser.urz.unibas.ch> References: <404757b9$1@maser.urz.unibas.ch> Message-ID: <404cb1e3$1@maser.urz.unibas.ch> Thanks to everyone! Sorry if I did not answer before but on the we I did not check the group. I think I understand now the mechanism, what I did not understand was why it was upcasting the 2 to Float64 if the matrix was Float32. But probably I'll give numarray a try. thanks again. curzio From http Tue Mar 9 08:11:04 2004 From: http (Paul Rubin) Date: 09 Mar 2004 05:11:04 -0800 Subject: Fast way to send message between 2 child processes? (using a file is too slow?) References: <20040309032505.GA18682@unpythonic.net> Message-ID: <7xoer6i2s7.fsf@ruckus.brouhaha.com> seberino at spawar.navy.mil writes: > Thanks. What about sockets?? If we > hardwire child processes to have a fixed ip address > and port then I can communicate with a socket right? If the processes are on the same machine, ip sockets are overkill. What is the application, if I can ask? How much speed do you need? The absolute fastest method will be to use a module like this: http://gigue.peabody.jhu.edu/~mdboom/omi/source/shm_source/shm.html But you will have to know what you're doing. From piet at cs.uu.nl Tue Mar 16 04:09:38 2004 From: piet at cs.uu.nl (Piet van Oostrum) Date: 16 Mar 2004 10:09:38 +0100 Subject: Any known bitmap/resource/image collection for a Spanish card deck? References: Message-ID: >>>>> Josiah Carlson (JC) wrote: >> 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. JC> Aside from you using Python to prototype the initial "new cardgame", images JC> of Spanish playing cards are very off-topic. JC> Search at google.com for the three terms: spanish playing cards JC> The second link will be for a site that sells decks of cards for $3.50 + JC> shipping each. Scan them. That is how I would get images of Spanish JC> playing cards. And you would have a copyright problem. -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP] Private email: P.van.Oostrum at hccnet.nl From peter.schwalm at epost.de Wed Mar 24 22:36:03 2004 From: peter.schwalm at epost.de (Peter Schwalm) Date: 24 Mar 2004 19:36:03 -0800 Subject: Python / COM / Word References: Message-ID: <5cf809e9.0403241936.5fe98316@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? Thank you Peter Schwalm From paddy3118 at netscape.net Tue Mar 2 03:26:25 2004 From: paddy3118 at netscape.net (Paddy McCarthy) Date: 2 Mar 2004 00:26:25 -0800 Subject: Is Eric S Raymond still a "Pythoneer" Message-ID: <2ae25c6b.0403020006.6b99e590@posting.google.com> I just re-read "Why Python?" at http://www.linuxjournal.com/article.php?sid=3882 The article is from 2000 and shows how a programmer who programmed in many programming languages, and who wrote compilers and interpreters, was introduced to Python and came to like it. 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? I'm going to add the article to my bookmarks for ammo in trying to change my strictly Perl workplace to at least consider Python. (I should add that I do know of most of the good advocacy resources available, I've collected them from answers to other peoples posts, thanks). Thanks again, Paddy. From NAIGIMSESRIMAIL at gims.com Thu Mar 4 11:14:35 2004 From: NAIGIMSESRIMAIL at gims.com (GroupShield for Exchange (ESRIMAIL)) Date: Thu, 4 Mar 2004 18:14:35 +0200 Subject: ALERT - GroupShield ticket number OB24_1078416868_ESRIMAIL_3 was generated Message-ID: Action Taken: The message was blocked because of its subject. To: python-list at python.org From: Nobody Sent: -996341248,29622787 Subject: Re: testing - please ignore Attachment Details:- Attachment Name: N/A File: Infected.msg Infected? No Repaired? No Blocked? Yes Deleted? No Virus Name: -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/ms-tnef Size: 1817 bytes Desc: not available URL: From bignose-hates-spam at and-benfinney-does-too.id.au Tue Mar 2 20:40:36 2004 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 3 Mar 2004 12:30:36 +1050 Subject: Group comment References: Message-ID: 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. -- \ "Truth would quickly cease to become stranger than fiction, | `\ once we got as used to it." -- Henry L. Mencken | _o__) | Ben Finney From jacek.generowicz at cern.ch Wed Mar 24 11:38:53 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 24 Mar 2004 17:38:53 +0100 Subject: Python for large projects References: Message-ID: Jacek Generowicz writes: > Stefan Axelsson writes: > > While the first statement is true on the face of it. The second is > > also true on the face of it, but probably not what you meant. It's > > that if the unit tests have been designed to find deviations from > > the 'expected' behaviour they will. Whether the 'expected' behaviour > > was actually the 'specified' behaviour is another question entirely. > > Programmers/designers misunderstanding the specification is all to > > common an occurrence. Which is what my "90% of the real problem vs 100% of the wrong problem" comments, in the post you replied to, were all about. > No argument there. However, static type systems' misunderstanding of > the problem is an even more common occurence ... basically because > static type systems don't even attempt to understand the problem. They > interfere with the developer regardless. And here I omitted to stress something important. Static type systems reject programs: they forbid you to even try running them. Test suites merely advise. Sometimes I want to run a program that I _know_ full well is full of bugs, dammit! During the whole of the development process, the program is full of bugs, by definition ... I still want to be able to see how it behaves, in order to investigate what to do about it. Static type systems all too often forbid me to do this. (Even Hindley Milner type systems.) From marklists at mceahern.com Thu Mar 25 15:46:42 2004 From: marklists at mceahern.com (Mark McEahern) Date: Thu, 25 Mar 2004 15:46:42 -0500 Subject: execute shell command pipeline In-Reply-To: <8757b529.0403251215.29333930@posting.google.com> References: <8757b529.0403251215.29333930@posting.google.com> Message-ID: <40634532.8050506@mceahern.com> Paul wrote: >Hi, > >I'm a Python newbie and I'm wondering how I can do the following Perl thing: > >open(F, 'grep -b 2004 logfile | head -1 | cut -d: -f1 |') or die "blah, blah"; >$offset = ; >( or $offset = `grep -b 2004 logfile | head -1 | cut -d: -f1`; ) > >in Python. When I tried: > You don't have to do it this verbosely, but it works: import os text = '2004' filename = 'logfile' delim = ':' matches = os.popen('grep -b %s %s' % (text, filename)).readlines() if matches: first = matches[0] offset = first.split(delim)[0] # note: offset is now a string // m From kingd Mon Mar 8 12:13:51 2004 From: kingd (Dale King) Date: Mon, 8 Mar 2004 12:13:51 -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: <404cb2e7@news.tce.com> "Joe Marshall" wrote in message news:smgoljbm.fsf at ccs.neu.edu... > "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. > FX I forgot to qualify this statement like I did another in my post. It only applies to languages that actually were successful languages. Many languages have been invented that never actually really "lived" in that they were not widely known. FX seems to fall in this category. It appears to only be an MIT research project. > Focal Can't testify to its use, but I find information about it on the web. > Lakota I can't speak to this one as there is almost no information on the web. Not sure if it ever was successful. > REBOL 1.x And the fact that a language involves from one version to another does not qualify as the language being dead. REBOL seems to be far from dead: http://www.rebol.com From __peter__ at web.de Wed Mar 31 08:14:44 2004 From: __peter__ at web.de (Peter Otten) Date: Wed, 31 Mar 2004 15:14:44 +0200 Subject: ESR's fortune.pl redone in python - request for critique References: Message-ID: Peter Otten wrote: A wrong comment being as bad as a wrong error message, change the unrolled loop to: if random() < 1.0/1: chosen = "a" # index is 0, item is "a" if random() < 1.0/2: chosen = "b" # index is 1, item is "b" if random() < 1.0/3: chosen = "c" # index is 2, item is "c" if random() < 1.0/4: chosen = "d" # index is 3, item is "d" From miki.tebeka at zoran.com Thu Mar 4 01:59:48 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Thu, 04 Mar 2004 08:59:48 +0200 Subject: ready to use python, need help with GUI decision In-Reply-To: References: Message-ID: <4046D3E4.9040007@zoran.com> Hello Jonathon, > Can anyone offer any advice? I use wxPython here at work and I'm very pleased with it. Native look and feel, a lot of widgets ... There are some nice UI designers as well (Boa, wxGlade ...). The UI in my projects is not that complicated to I write all the GUI in VIm, the *Sizer are wonderful. HTH. Miki From newsgroups at jhrothjr.com Sun Mar 14 06:26:55 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Sun, 14 Mar 2004 06:26:55 -0500 Subject: Performance penalty for using properties? References: Message-ID: <1058gebqdikgl38@news.supernews.com> "Peter Otten" <__peter__ at web.de> wrote in message news:c3150l$hua$02$1 at news.t-online.com... > I think finding a way for properties to access attributes without wrapping > them into a function call would be worth the effort. The penalty for clean > interfaces should be as low as possible. I suspect you're right. If the only reason for using a property is to hide a simple getter or setter from the client, and provide for (possible) future more complex processing, then it shouldn't be necessary to do a function call at all. Unfortunately, that would require a significant redefinition of the descriptor interface. If that's done, then I'd strongly suggest looking at a couple of other issues at the same time. >From a performance standpoint, keyword (that is, optional) parameters require a lot more processing than positional (that is, non-optional) parameters. I know there's been some talk of trying to optimize function call processing, and property access should be able to take advantage of any fast paths through that morass that are created. > Peter From eric at zomething.com Wed Mar 17 23:21:52 2004 From: eric at zomething.com (Eric @ Zomething) Date: Wed, 17 Mar 2004 20:21:52 -0800 Subject: asking for python community opinion about groovy Message-ID: <20040317202152.624502206.eric@zomething.com> Mouloud wrote: > > IMO, it will be better to support the Jython project. Because Jython > > exists, it's very useful and powerful. In fact, I think java community > > want to have its own "scripting" language because java community is > > not open-minded enough and will not accept to use something for the > > outside. A Pythonista trying to convince a world of Java heads to do it another way? Your cries for sanity will be lost in the "public static void". In other news, Bill Gates announced today that next month Linux, also, will be Windows. Ironically, Jython's name hinders it: folks, this _is_ marketing we're talking about. These are brand names. Groovy is a pretty good name, I think. Python is pretty groovy. Maybe Groovy will be pretty Java? Anyone got any "Groovy" code examples? I suddenly feel like I need a hot cup of coffee and some quiet time - cuddling a reptile? Eric Pederson "I love Python, but the current funky green snake may not help with mass acceptance" From simon Sat Mar 6 11:05:57 2004 From: simon (simon) Date: Sat, 06 Mar 2004 16:05:57 GMT Subject: machine control script ( parameterless method? ) Message-ID: <340a6b1b6f65b385490e5d818b2b6c9e@news.scbiz.com> I'm thinking of rewriting some vb code in python, its a machine control program currently using a simple script to define an action sequence. but if i directly use python for the action sequence ( the most flexible approach.) means each action ( method ) having brackets, which is a bit redundant and confusing to the user, since i'm separating the parameters all actions are calls to parameterless methods, so the question is, is there any way to call a method when a name is referenced ( like __repr__ in interactive mode.) why do i separate the parameters? well a parameter can be changed often, can occur in several actions and is unlikely to cause major problems if wrongly entered, whilst the actions have more serious consequences if wrongly arranged , so they are differently accessed. This arrangement seems to me to be quite common, like a washing machine, dial to select a predefined sequence and then buttons or dials to tailor it to more refined requirements. thanks in advance. From dmq at gain.com Tue Mar 16 06:48:49 2004 From: dmq at gain.com (David MacQuigg) Date: Tue, 16 Mar 2004 04:48:49 -0700 Subject: Deprecating reload() ??? References: <6kk6501shlve52ds2rjdopa73jhpchprg3@4ax.com> Message-ID: On Tue, 16 Mar 2004 04:43:01 GMT, Carl Banks wrote: >What if one of your users does something like 'y = M1.x + 1'; then >what are you going to do? The goal is *not* to put the program into the state it "would have been" had the changes in M1 been done earlier. That is impossible. We simply want to have all *direct* references to objects in M1 be updated. A direct reference, like 'y = M1.x', sets 'y' to the same object as 'M1.x' The 'y' in the above example points to a new object, with an identity different than anything in the M1 module. It should not get updated. >It seems to me that your noble effort to make reload() completely >foolproof is ultimately in vain: there's just too many opportunities >for a module's variables to affect things far away. It all depends on your goals for reload(). To me, updating all direct references is a worthy goal, would add a lot of utility, and is easy to explain. Going further than that, updating objects that are "only one operation away from a direct reference" for example, gets into a grey area where I see no clear line we can draw. There might be some benefit, but the cost in user confusion would be too great. Reload() will always be a function that needs to be used cautiously. Changes in a running program can propagate in strange ways. "Train wreck" was the term another poster used. -- Dave From npat at efault.net Tue Mar 9 10:58:01 2004 From: npat at efault.net (Nick Patavalis) Date: Tue, 9 Mar 2004 15:58:01 +0000 (UTC) Subject: Package importing question Message-ID: Assume this package: p0/ __init.py__ <-- empty m0.py m1.py $ cat p0/m0.py import sys import m1 def f0(i): pass $ cat p0/m1.py def f0(i): pass Now let's see what happens when importing the package: $ python2.3 ........ >>> import p0 >>> dir(p0) ['__builtins__', '__doc__', '__file__', '__name__', '__path__'] so far, so good. Now try: >>> import p0.m0 dir(p0.m0) ['__builtins__', '__doc__', '__file__', '__name__', 'f0', 'm1', 'sys'] fine also! But: >>> dir(p0) ['__builtins__', '__doc__', '__file__', '__name__', '__path__', 'm0', 'm1'] Why on earth does 'm1' show-up there?? And since it does, why doesn't 'sys'?? Thanks in advance /npat From sleap at pennswoods.net Tue Mar 2 10:41:47 2004 From: sleap at pennswoods.net (43fan) Date: Tue, 2 Mar 2004 10:41:47 -0500 Subject: Extreme Newbie, HELP! :) Message-ID: <7dqdnck-z6KnNtnd4p2dnA@hereintown.net> Not only a newbie, but an extreme newbie here, and at this point, really only have one application that I need to use Python for. This is in Paintshop Pro, version 8. Where I work, we regularly take photos of material as we're progressing through a job. These photos are named(and stored) according to a specific naming process. What happens now is, one person takes the photos and downloads the images to a folder, usually having to rotate the image 90deg one way or the other. Then, another person renames the files and moves them to the appropriate folder. Since the name of the file(and actually the folder it's to be located in) follows a strict set of rules, the person that's doing the dowloading could save them in the proper place, with the proper name. However, this could be one of several people, and I'd like to be able to automate the process. If there's a way that I can ask the user a series of approx. 4 questions, I can determine the location the file should be in, and the name it should be, based on the answers to those questions. That's basically all I want to do. :) Have them open the downloaded file in PSP 8(or an earlier version if it supports it), run the script which would ask the series of questions, then save the file in the appropriate folder, with the appropriate name. Any help???? Thanks! Shawn PS - please excuse the nick, I post in a racing ng as well. :) -- Join the newest in Fantasy Sports. http://www.6FantasySports.com (this site supports the Victory Junction Gang Camp with a portion of all proceeds) From jcarlson at nospam.uci.edu Fri Mar 26 14:34:07 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Fri, 26 Mar 2004 11:34:07 -0800 Subject: PyProtocols question In-Reply-To: References: Message-ID: > I'm not sure if this is the best forum to place this question, but > haven't found a better one, so here goes. > > I have Python 2.3 in my machine (Windows 2000) and downloading > PyProtocols 0.9.2 the installer complains that python 2.2 isn't found > in the registry. If it complains that you don't have Python 2.2, then you should have installed 2.2 instead of 2.3. Python 2.3 is not Python 2.2. > I've also tried to download the source and follow the instructions, > but since there's no compiler the setup complains. Since I cannot find > the latest 0.9.3 version I can't use the --without-speedups to bypass > the compilation phase... You say you have cygwin. You can get a version of GCC for cygwin. > I also have cygwin and could try the rpm's, but I have (yet) very > little experience on it, so I don't wanna go that route. Cygwin has RPM support? Cool. If Pyprotocols as a src RPM and Cygwin has RPM support, get the source distribution and try to go from there. From steve at ninereeds.fsnet.co.uk Mon Mar 22 06:10:18 2004 From: steve at ninereeds.fsnet.co.uk (Stephen Horne) Date: Mon, 22 Mar 2004 11:10:18 +0000 Subject: PEP 318 References: <99dce321.0403211817.3704fe2@posting.google.com> <7x1xnlqs77.fsf@ruckus.brouhaha.com> Message-ID: On 22 Mar 2004 11:11:26 +0100, Jacek Generowicz wrote: >My only slight reservation is the increased "keyword overloading". For >example ... "static" has something like 7 distinct meanings in C++ (at >last count), and I find that this has a detremental effect on >discussions with colleagues. I hope that Python will be able to avoid >such problems. Which is worse? Keyword overloading, or wierd pattern-of-symbols overloading? Personally, I'd hate to see nouns or verbs 'overloaded'. But why shouldn't prepositions be used in a wide variety of contexts in Python? They are in spoken languages, after all. -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From noah at noah.org Mon Mar 22 03:24:50 2004 From: noah at noah.org (Noah) Date: 22 Mar 2004 00:24:50 -0800 Subject: Need recommendations for installer setup tool References: Message-ID: Robin Munn wrote in message news:... > Noah wrote: > > I would like something that could put a GUI on this process. > > Not that this would make it any easier to use, but it would make it > > easier to market :-P Ideally the installer would allow for both GUI and > > text based interfaces. > > > > Are there any Python based products that would help me build these installers? > > I'm trying to move away from the bash scripts and go with 100% pure Python. > > Have you looked at SCons? Between SCons and anygui, you might be able to > put together a good solution pretty easily. SCons looks great! At first glance it seem to be exactly what I was looking for. I thought that AnyGUI was a dead project. No? Yours, Noah From peter at engcorp.com Tue Mar 16 15:29:20 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 16 Mar 2004 15:29:20 -0500 Subject: Is Python type safe? In-Reply-To: References: <221d8dbe.0403161043.52406195@posting.google.com> Message-ID: Roy Smith wrote: > Neither C++ nor Python will let you add the integer 3 to the string > "four", but use different mechanisms to prevent it. Oddly enough, Java > (in a perl-like, but admittedly convenient, stab at automagic > polymorphism) will let you add them. No clue what C# does. It's been a while since I Java-ed, but doesn't it "append" them, as in convert the integer to a string and then join the two strings, rather than "add" them (which I take to mean "calculate the sum of")? (That's probably what you meant, but I'm just checking. I'd be surprised to find that Java actually performed the string-to-value conversion implicitly.) -Peter From kbk at shore.net Mon Mar 1 12:23:23 2004 From: kbk at shore.net (Kurt B. Kaiser) Date: Mon, 01 Mar 2004 17:23:23 GMT Subject: comp.lang.python References: Message-ID: <87smgs4h2s.fsf@hydra.localdomain> Marcello Pietrobon writes: > Is the server comp.lang.python working or not ? > > If yes, > what settings do I need in order to see this mailing list in newsgroup > form ? You would need to install newsreader software, and point it at your ISP's news server. Most decent browsers have this capability these days. Or you could use Google Groups: http://www.google.com/groups?safe=images&ie=UTF-8&oe=UTF-8&as_ugroup=comp.lang.python&lr=&hl=en -- KBK From jforgion at vt.edu Tue Mar 30 16:25:27 2004 From: jforgion at vt.edu (Joshua Forgione) Date: Tue, 30 Mar 2004 16:25:27 -0500 Subject: struct.pack Format String Question Message-ID: <4069E5C6.BC5274E6@vt.edu> Hello. I am reverse engineering some Python Code. I am using the book "The Quick Python Book" as an aide. The following line exists in the code: msg = struct.pack('BBBB',word0, word1, word2, word3, word4) In this struct.pack command, the format string is 'BBBB.' In the book, it gives the following examples for characters that are meaningful to struct: 'h' - short integer 'd' - double-precision floating point 's' - string In this case, 'B' is used. What does 'B' represent? What other characters can be used? Does a list of this exist somewhere? Thank you for your help. Josh From t-meyer at ihug.co.nz Sat Mar 6 23:16:03 2004 From: t-meyer at ihug.co.nz (Tony Meyer) Date: Sun, 7 Mar 2004 17:16:03 +1300 Subject: Parsing xml file using python In-Reply-To: <1ED4ECF91CDED24C8D012BCF2B034F13054AFFEC@its-xchg4.massey.ac.nz> Message-ID: <1ED4ECF91CDED24C8D012BCF2B034F13026F2B00@its-xchg4.massey.ac.nz> > 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? Apart from the XML parsing solutions that have already been posted, if you really don't care about the tags, then you don't actually need to parse the XML. Just dump anything between < and > (assumes that the XML is valid, and so doesn't have < or > except for as a tag). For example (this is pretty basic): >>> import re >>> s = "This\nis\na\ntest" >>> re.sub(r"<.*?>", "", s) 'This\nis\na\ntest' You'd still have to deal with entities, but IIRC, you'll have to with most parsers, too. It's certainly simpler. =Tony Meyer From newsgroups at jhrothjr.com Mon Mar 22 18:25:09 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 22 Mar 2004 18:25:09 -0500 Subject: static information... References: Message-ID: <105utgt2ql2e0e1@news.supernews.com> wrote in message news:mailman.253.1079991337.742.python-list at python.org... > I've been looking for a way of have static variables in a python class and all I > have found is this: > > class A: > static =[] > > def f(self): > A.static = [1,2,3] > > > That seems to be pretty static since that variable can be used either on the > class (such as A.static) or on an instance (such as A().static). > Now my problem is that every time some create a new instance of this class the > variable static is reset to its original value [] and the real value that it > took is lost. What I want is someplace to store class's information and not > instance's information. > Any idea? It doesn't exist. The class level variable is a default for an instance level variable. If you want a class level variable, there are two ways of going about it. One is to declare a getter and setter and make them class methods; the other is the one you have discovered, and that Larry Bates references. for example: class Foo(object): var = "bar" def setVar(klas, value): klas.var = value setVar = classmethod(setVar) def getVar(klas): return klas.var getVar = classmethod(getVar) def bar(self): self.setVar([1,2,3]) ------------------------------- Note that classmethod requires a new style class, which is why the subclass from object. HTH John Roth > > From jacek.generowicz at cern.ch Fri Mar 12 11:38:28 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 12 Mar 2004 17:38:28 +0100 Subject: Static Typing in Python References: Message-ID: 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 ? From paul at prescod.net Sun Mar 28 15:03:39 2004 From: paul at prescod.net (Paul Prescod) Date: Sun, 28 Mar 2004 12:03:39 -0800 Subject: Prothon Prototypes vs Python Classes In-Reply-To: <106dukh7ncf9ad4@news.supernews.com> References: <569c605ld1cj8fc1emolk08ete0s1prls1@4ax.com> <106cc1f2rsnaoe2@news.supernews.com> <406635AB.9050803@mlug.missouri.edu> <106ceeeqc8ph126@news.supernews.com> <106dukh7ncf9ad4@news.supernews.com> Message-ID: <40672F9B.1040505@prescod.net> I'm totally confused. There was a statement of fact about how compilers work which I refuted. Now it's shifting to a question of programming style. Let's recap: John Roth wrote: > "Paul Prescod" wrote in message > news:mailman.10.1080485351.20120.python-list at python.org... > >>John Roth wrote: >> >> >>>It's certainly true that in a prototype based language all objects >>>exist: there are no objects that the compiler deals with but does >>>not put into the resulting program. And it's quite true that it does >>>open up the floodgates for a lot of messiness. >> I responded: >>Ummm. This is also true for Python. Python classes exist at runtime. Given class A: pass a = A() Both "a" and "A" are put in the "resulting program" (bytecodes) just as they would in a prototype-based language. A() is a completely first-class object, just like a prototype in a prototype-based language. Paul Prescod From http Fri Mar 12 05:01:02 2004 From: http (Paul Rubin) Date: 12 Mar 2004 02:01:02 -0800 Subject: How to add pairs to a dict, typo corrected in this one. References: Message-ID: <7x1xny9yg1.fsf@ruckus.brouhaha.com> Avik Ghose writes: > if 'tom' in phone_book.keys(): > #duplicate entry; Don't do it that way! That builds up a whole list from scratch containing all the keys, and then searches the list for 'tom'!!! There was just a thread about this :). Instead, use: if 'tom' in phone_book: ... or if phone_book.has_key('tom'): ... From __peter__ at web.de Tue Mar 2 15:10:48 2004 From: __peter__ at web.de (Peter Otten) Date: Tue, 02 Mar 2004 21:10:48 +0100 Subject: variable name using a for References: <4044d7f3$0$4664$626a14ce@news.free.fr> <1049mi9ktod7o35@corp.supernews.com> <4044e177$0$24960$626a14ce@news.free.fr> Message-ID: Alex wrote: > Thank you very much for the reply! > > In fact I created a list in a variable and I have to create x numbers of > butons, depending on how many values there's in the list. > > so in my code: > for x in range(nbSujets): > self.button1 = xbmcgui.ControlButton(50, 100, 40, 30, "B"+str(x) ) > self.addControl(self.button1) > You have several options: (1) for x in range(nbSujets): button = xbmcgui.ControlButton(...) self.addControl(button) I don't know that particular gui, but access to the button should be possible by something like self.getControl(buttonname) or self.controls[buttonindex] - just look it up in the docs. (2) self.buttons = [] for x in range(nbSujets): button = xbmcgui.ControlButton(...) self.addControl(button) self.buttons.append(button) Refer to the button later as self.buttons[buttonindex] (3) for x in range(nbSujets): button = xbmcgui.ControlButton(...) self.addControl(button) setattr(self, "button" + str(x), button) Refer to the button later as self.button0, self.button1, ... > But in fact I need self.buttonX as I need different actions on each > button. And the dictionnary here doesn't help I think... Perhaps you can find a way to connect buttons and actions directly in the for loop and need not refer to them later at all? (4) for x, action in enumerate([self.killMonster, self.saveTheWorld]): button = xbmcgui.ControlButton(...) button.onClick = action # speculating again here self.addControl(button) killMonster() and saveTheWorld() are the methods that shall be triggered when the associated button is pressed. Incidentally, the last one is my personal favourite. Peter From michele.simionato at poste.it Tue Mar 23 13:44:02 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 23 Mar 2004 10:44:02 -0800 Subject: PEP318 yet an alternate syntax idea References: Message-ID: <95aa1afa.0403231044.2f3d139d@posting.google.com> Marco Aschwanden wrote in message news:... > Python has the concept that names with a preceding underscores (__) will > be mangled in some way. I suppose the "compiler"/interpreter does this > name-mangling. Why not use the same concept: > > def __static__theRealFunctionName(self, var1, var2): > pass > > The compiler will do some name mangling. The function is called without > the __static__ part: > > --> theRealFunctionName(3,4) > > > The advantages: > > - Old code won't break (except if someone has functions starting with > __static__). > - It is an already used concept for "private" variables --> they might be > migrated to __private__ > - well they even might be joined: > __static____privat__theRealFunctionName(...) > - don't use it if you don't need it (this probably defaults to a > __public__) > - The definition tells us what kind of method (class?) this is > > The disadavantage: > - long names > > Stupid idea? I guess so, but I am too stupid to see why? > > Bye, > > Marco Three reasons: 1. it is ugly; 2. you don't need to change the core language for that. Implementing this idea in Python 2.2+ is just an exercise in metaclasses. It does not deserve a PEP. 3. How do you pass parameters to the decorator? Michele Simionato From uche at ogbuji.net Sun Mar 14 23:09:45 2004 From: uche at ogbuji.net (Uche Ogbuji) Date: 14 Mar 2004 20:09:45 -0800 Subject: Does python's minidom support Chinese? References: Message-ID: Anthony Liu wrote in message news:... > The following 4 lines of code parses an XML document > very well if the XML document contains only English > words. > > But when I insert one Chinese character into the XML > document, then Python starts to complain when it hits > the Chinese character, saying that it is an invalid > token and thus it is not well-formed. > > This is the complaint of Python: > > ExpatError: not well-formed (invalid token): line 3, > column 7 > > line 3 and column 7 exactly pinpoints the 1st Chinese > character in the XML document. This is an XML problem on your end, not a minidom problem. That error probably means that you are either omitting the XML declaration (and thus defaulting to UTF-8 or UTF-16) or declaring a bogus encoding. > The problem remains even if I try encoding="UTF-16" or > encoding="GB2312" or encoding="GBK" in the xml > document. Well, you can't just go shopping about for oare it accordingly. Back to minidom: even after you fix your XML problems you may still have trouble with minidom because the expat reader has to understand the encoding you're using. I think that it may use the Python codecs model to find the encoding you declared, so you may just need to install a Python Chinese codecs package, and you'll be all set. I'm not entirely sure this si the case, though. --Uche http://uche.ogbuji.net From peter at engcorp.com Sat Mar 6 20:06:54 2004 From: peter at engcorp.com (Peter Hansen) Date: Sat, 06 Mar 2004 20:06:54 -0500 Subject: Question please In-Reply-To: References: Message-ID: Abe and Barb K. wrote: > I have a new HP computer that seems to have come with Python 2.2 with > win32 extensions software. > > I'm not a programmer or tech and would like to know if I can just remove > this software without affecting anything in my system as it is taking up > space if I'm not going to use it? It's probably part of some system maintenance utilities that HP includes, and you're best off leaving it alone. There's a note in the Python FAQ at www.python.org that mentions this sort of thing in case you're interested. Besides, as this is a new computer, it's very likely that the disk space being taken up by Python is a small fraction of one percent of the total, and you're really not gaining anything significant by doing this. It ain't broke, so don't "fix" it. -Peter From ville at spammers.com Fri Mar 12 07:58:09 2004 From: ville at spammers.com (Ville Vainio) Date: 12 Mar 2004 14:58:09 +0200 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> <40515E92.3080201@nospam.uci.edu> <405185f5$0$16368$afc38c87@news.easynet.co.uk> <4051936c$0$2136$afc38c87@news.easynet.co.uk> Message-ID: >>>>> "Peter" == Peter Hickman writes: Peter> If all you want her to be is a Python zealot then go ahead, Peter> but you would be doing her a greater service by allowing Peter> her to become a good programmer. It's just that I don't think Python and Ruby are different enough as languages to really provide much perspective from pedagogical viewpoint. -- Ville Vainio http://tinyurl.com/2prnb From martin at v.loewis.de Wed Mar 17 02:01:02 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 17 Mar 2004 08:01:02 +0100 Subject: problem with cjkcodecs on Mandrake linux In-Reply-To: References: Message-ID: Anthony Liu wrote: > OK, gotcha. By the way, do you know how to set the > default language of Mandrake or any linux system, so > that I can probably mimic. You need to set the LANG environment variable. This is best done on a per-user basis, e.g. in the .login file of the user. Setting LANG to zh_CN should give you a (simplified) Chinese environment. Python 2.3 will automatically pick up that setting when printing Unicode strings. Regards, Martin From srovner at us.ibm.com Thu Mar 4 20:49:47 2004 From: srovner at us.ibm.com (Sonia Rovner) Date: 4 Mar 2004 17:49:47 -0800 Subject: tkFileDialog.askopenfilename References: <8a5a6d82.0403041057.30d4c773@posting.google.com> Message-ID: <8a5a6d82.0403041749.245f350d@posting.google.com> Peter Otten <__peter__ at web.de> wrote in message news:... > Sonia Rovner wrote: > > > 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? > > Seems you are out of luck: > > "The procedures tk_getOpenFile and tk_getSaveFile pop up a dialog box for > the user to select a file to open or save. The tk_getOpenFile command is > usually associated with the Open command in the File menu. Its purpose is > for the user to select an existing file only. If the user enters an > non-existent file, the dialog box gives the user an error prompt and > requires the user to give an alternative selection. If an application > allows the user to create new files, it should do so by providing a > separate New menu command. " > > Quoted from http://www.tcl.tk/man/tcl8.5/TkCmd/getOpenFile.htm > > Peter Thank you very much. Sonia From eurleif at ecritters.biz Thu Mar 11 21:29:09 2004 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Fri, 12 Mar 2004 02:29:09 GMT Subject: Create static method dynamically In-Reply-To: References: Message-ID: Salvatore wrote: > class myClass: > def addmethod(name,method): > maClasse.__dict__[name] = method > addmethod = staticmethod(addmethod) > > def hello(): > print "hello" > > myClasse.addmethod('hello',hello) > I would like to make this call: > myClass.hello() Change line 3 to: myClass.__dict__[name] = staticmethod(method) From jepler at unpythonic.net Tue Mar 9 09:29:25 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Tue, 9 Mar 2004 08:29:25 -0600 Subject: Working around a lack of 'goto' in python In-Reply-To: <003c01c405a9$b4483720$3501a8c0@rogersqyvr14d3> References: <20040309035213.GB18682@unpythonic.net> <003c01c405a9$b4483720$3501a8c0@rogersqyvr14d3> Message-ID: <20040309142924.GI12662@unpythonic.net> On Mon, Mar 08, 2004 at 11:39:50PM -0800, Roger Binns wrote: > Jeff Epler wrote: > > [Mr. Binns helpfully deleted the attribution, so I didn't even realize > > right away he was replying to my post] > > I was posting in the newsgroup where everything is well threaded. > Apologies if you feel slighted. Maybe I'm out of step, but I thought it was standard practice on Usenet to name the person whose text is quoted. The program I'm using displays threads properly, but already-read messages are not shown in the index, meaning that I don't always see the message being replied to. > I think some of that could be alleviated through the use of 'else' > with 'for/while' although it looks like I need the opposite of its > semantics (a 'not else'). Quite frankly the existence of 'else' > in this context as a language feature baffles me and I don't use it. The same goes for me. I can never remember when the "else" clause will execute, and for that reason I'm very unlikely to use it. > > > I have seen one call > > for [g(x) for x in l while f(x)]. > > I didn't even know you could do that (the while). I wasn't clear. You *can't* use "while" in listcomps, and I've only seen it requested once. Jeff From premshree_python at yahoo.co.in Thu Mar 4 05:12:13 2004 From: premshree_python at yahoo.co.in (=?iso-8859-1?q?Premshree=20Pillai?=) Date: Thu, 4 Mar 2004 10:12:13 +0000 (GMT) Subject: Python for Beginners In-Reply-To: Message-ID: <20040304101213.81691.qmail@web8302.mail.in.yahoo.com> --- Josiah Carlson wrote: > > > http://premshree.resource-locator.com/python-seminar-210204/slides/pySlide1.jpg.htm > > I notice that you took our advice on the errors with > your original > presentation, but still doesn't distinguish between > mutable sequences > (lists), immutable sequences(strings, tuples), and > the fact that they > are really able to do the same things. > > The Python Tutorial is a much better introduction to > the language. > http://www.python.org/doc/current/tut/tut.html > > - Josiah > -- > http://mail.python.org/mailman/listinfo/python-list Maybe the slides on their own weren't enough for a good "introduction". These were slides that I prepared for an introductory seminar on the language at college. -Premshree ===== -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 bogus at bogus.net Tue Mar 9 04:16:59 2004 From: bogus at bogus.net (Paul McGuire) Date: Tue, 09 Mar 2004 09:16:59 GMT Subject: How to convert string to list without eval or exec References: Message-ID: "Oliver Kurz" wrote in message news:mailman.158.1078818680.19534.python-list at python.org... > 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. > > -- > -- > Oliver Kurz > > # get pyparsing at http://pyparsing.sourceforge.net from pyparsing import quotedString, Forward, Literal,delimitedList,Group quotedString.setParseAction(lambda s,l,t: t[0].strip("'\"")) testdata = '[["abc","abc",["abc","abc"],"abc"],["abc","abc",["abc","abc"],["abc",["abc" ,"abc"]],"abc"],"abc"]' lbrack = Literal("[").suppress() rbrack = Literal("]").suppress() listDef = Forward() # add more things to listItem, such as integers, etc. if your list has other than quoted strings listItem = quotedString | listDef listDef << lbrack + Group( delimitedList(listItem) ) + rbrack print listDef.parseString(testdata)[0].asList() From jcarlson at nospam.uci.edu Tue Mar 9 01:53:54 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Mon, 08 Mar 2004 22:53:54 -0800 Subject: a desired python editor In-Reply-To: References: Message-ID: > 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) Idle; 1-4 are easy. For 5, check the "class browser" functionality, and is included with Python. As already mentioned, DrPython has them all (http://drpython.sourceforge.net), requires wxPython. If you would like an attached "class browser", and don't mind having tabbed editing functionality, PyPE may suit you (http://pype.sourceforge.net), also requires wxPython. If you would prefer MDI (rather than tabs), don't mind the "class browser" being slow, SPE may suit you (http://spe.pycs.net), also requires wxPython. On the other hand, Eric3 looks to be pretty sweet: http://www.die-offenbachs.de/detlev/eric3.html (requires PyQT and QScintilla). I'd probably be using it, if I could get it working in Windows. - Josiah From moranar at daleclick.com Sat Mar 20 17:36:54 2004 From: moranar at daleclick.com (Adriano Varoli Piazza) Date: Sat, 20 Mar 2004 19:36:54 -0300 Subject: problem with a css cycler In-Reply-To: <200403201929.12518.moranar@daleclick.com> References: <200403201929.12518.moranar@daleclick.com> Message-ID: <200403201936.54845.moranar@daleclick.com> El S?b 20 Mar 2004 19:29, Adriano Varoli Piazza escribi?: ... > today = int(raw_input("today's date: ")) ... Of course, this variable would be obtained by using a date function, not by using raw_input(). I did it this way to be able to test easily. -- Adriano Varoli Piazza The Inside Out: http://moranar.com.ar ICQ: 4410132 MSN: adrianomd at hotmail.com Claves gpg / pgp en hkp://subkeys.pgp.net From Scott.Daniels at Acm.Org Fri Mar 26 15:38:43 2004 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Fri, 26 Mar 2004 12:38:43 -0800 Subject: [SPAM-Bayes] - Re: Converting IBM Floats..Help.. - BayesianFilter detected spam In-Reply-To: References: <41A1CBC76FDECC42B67946519C6677A9A20DFE@pippin.int.etrials.com> Message-ID: <40649c5e$1@nntp0.pdx.net> Jeff Epler wrote: > Here's one page I found with an explanation of how more standard > floating-point numbers are stored: > http://ccrma-www.stanford.edu/~jos/mdft/Floating_Point_Numbers.html > The most important difference between the IEEE formats and the IBM > format is that the radix is 16 instead of 2. I think there's also a > terminlogy error--the page says that the significand (mantissa) is > stored in "two's compliment binary", but this isn't true. It's > unsigned. The sign is stored separately. Actually, a common trick is to use "two's complement binary" on the entire word, not simply the mantissa. Then the same hardware can be used to negate integer and floating values. The way you take apart negative numbers is (1) record the sign, and (2) take the absolute value of the whole thing (3) breaking exponent and mantissa out. You might find my weird little bits module helpful to take your floating point values in python apart in order to send them around. http://members.dsl-only.net/~daniels/bits.html -- -Scott David Daniels Scott.Daniels at Acm.Org From PIVOTSINET-MESS-SA at grenoble.sema.slb.com Tue Mar 16 05:17:49 2004 From: PIVOTSINET-MESS-SA at grenoble.sema.slb.com (=?iso-8859-1?Q?Surveillance_du_syst=E8me?=) Date: Tue, 16 Mar 2004 11:17:49 +0100 Subject: [MailServer Notification] To External Sender: a virus was found a nd action taken. Message-ID: <0D6751E6159DD711BA6F00D0B7C9E6A101FC941D@pivotsinet.croissy.eur.slb.com> ScanMail for Microsoft Exchange took action on the message. The message details were: Sender = python-list at python.org Recipient(s) = emeunier at mtr.sema.slb.com; Subject = Re: My details Scanning time = 03/16/2004 11:17:38 Engine/Pattern = 6.860-1001/1.822.00 Action taken on message: The attachment my_details.pif contained WORM_NETSKY.D virus. ScanMail took the action: Deleted. Alerte virale. Scanmail a d?tect? un virus. 03/16/2004 emeunier at mtr.sema.slb.com; Re: My details From bdesth.quelquechose at free.quelquepart.fr Tue Mar 30 17:11:17 2004 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 31 Mar 2004 00:11:17 +0200 Subject: Prothon Prototypes vs Python Classes In-Reply-To: References: <569c605ld1cj8fc1emolk08ete0s1prls1@4ax.com> <106cc1f2rsnaoe2@news.supernews.com> <406635AB.9050803@mlug.missouri.edu> <106ceeeqc8ph126@news.supernews.com> <106di86neu1qh4d@news.supernews.com> Message-ID: <4069ea7d$0$8915$636a15ce@news.free.fr> Carl Banks wrote: > William Park wrote: > (snip) >>This space-vs-tab war is just insane. I wish Prothon/Python would use >>block terminator, if only to kill this silly trollings. > > > Right. Then we can have "does the brace go on the same line or the > next line" wars. > lol ! From yaipa at yahoo.com Tue Mar 16 00:11:08 2004 From: yaipa at yahoo.com (yaipa h.) Date: 15 Mar 2004 21:11:08 -0800 Subject: Stop code in python!! References: <4055bb8c$0$794$edfadb0f@dread11.news.tele.dk> <1079390825.37545.1@demeter.uk.clara.net> Message-ID: <6e07b825.0403152111.2c6f96eb@posting.google.com> Garry Knight wrote in message news:<1079390825.37545.1 at demeter.uk.clara.net>... > In message , Alan Gauld wrote: > > > raw_input("Hit Enter to quit...") > > And remember that you can do raw_input() without any message. ...and sleep() as well. From vinay_sajip at yahoo.co.uk Wed Mar 17 16:51:15 2004 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: 17 Mar 2004 13:51:15 -0800 Subject: logging messages in imported modules not showing up References: <8de75d53.0403091141.e488ec@posting.google.com> Message-ID: <2e37dc1.0403171351.47425e90@posting.google.com> erick_bodine at comcast.net (Erick Bodine) wrote in message news:<8de75d53.0403091141.e488ec at posting.google.com>... > I have a script that sets up logging at startup, imports a module > (module1) which itself imports another module (module2). > > The problem is that if I run script.py, I see the following. I never > see the 'MyClass2 initialized' log message from module2?? > > 2004-03-09 12:15:18,348 DEBUG [script:15] logging enabled > 2004-03-09 12:15:18,348 DEBUG [module1:12] MyClass initialized > 2004-03-09 12:15:18,348 DEBUG [module2:14] MyClass2 do_something > > -------------- > script.py > ------------- > import logging, module1 > > def main(): > # setup logging > log = logging.getLogger('myapp') > handler = logging.StreamHandler() > log.setLevel(logging.DEBUG) > format = logging.Formatter("%(asctime)s %(levelname)-3s " \ > "[%(module)s:%(lineno)d] %(message)s") > handler.setFormatter(format) > log.addHandler(handler) > > log.debug("logging enabled") > > my = module1.MyClass() > > if __name__ == '__main__': > main() > > -------------- > module1.py > -------------- > import logging, module2 > log = logging.getLogger('myapp') > > class MyClass: > def __init__(self): > log.debug("MyClass initialized") > > def something(self): > my = module2.MyClass2() > my.do_something() > > ------------- > module2.py > ------------- > import logging > log = logging.getLogger('myapp') > class MyClass2: > def __init__(self): > log.debug("MyClass2 initialized") > > def do_something(self): > log.debug("In MyClass2 do_something") Perhaps your script is not working as you expect because you forgot to call my.something() from main(). Hence a MyClass2 instance was never instantiated and do_something() was never called on it. Vinay Sajip From newsgroups at jhrothjr.com Mon Mar 29 10:25:28 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 29 Mar 2004 10:25:28 -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> Message-ID: <106gg1jifa2n9c2@news.supernews.com> "Michael" wrote in message news:406829FF.5060304 at mlug.missouri.edu... > > > > What difference does it make what the standard length of a tab is as > long as it remains the same throughout the program? As long as the size > is uniform it should render just fine. 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. > >There is, of course, no standard at all for how to change > >the default tabbing in programs, which means that one > >has to deal with each and every one on an individual > >basis - if it's even possible. > > > > > Again, as long as it's uniform does it matter? It won't change the logic > of the code as long as it opens a tab as a tab and saves a tab as a tab. > If you can't trust your editor to do something that basic then trash it. It matters. 8 columns is much too wide for indents in readable code. People do differ on that, but that seems to be the concensus. John Roth From __peter__ at web.de Thu Mar 11 17:48:01 2004 From: __peter__ at web.de (Peter Otten) Date: Thu, 11 Mar 2004 23:48:01 +0100 Subject: Optparse: Detecting if option or option-arg is specified or not References: Message-ID: Sam Smith wrote: > I am using optparse for the commandline parsing for my programs. I > was wondering if it is possible to detect if an option or option-arg > has been specified on the commandline by the user or not. Please do > not suggest default value solutions. What's wrong with default values? Anyway, here's the hasattr() approach: >>> p = optparse.OptionParser() >>> p.add_option("-x", action="store_true") >>> class NS: pass ... >>> values = NS() >>> p.parse_args([], values) (<__main__.NS instance at 0x402c3f6c>, []) >>> hasattr(values, "x") False >>> p.parse_args(["-x"], values) (<__main__.NS instance at 0x402c3f6c>, []) >>> hasattr(values, "x") True >>> Peter From csgcsg39 at hotmail.com Thu Mar 4 09:35:27 2004 From: csgcsg39 at hotmail.com (C GIllespie) Date: Thu, 4 Mar 2004 14:35:27 -0000 Subject: Calling C programs References: <4047258C.9080808@zoran.com> Message-ID: > from os import popen > print popen("/tmp/hello").read() What about if I want to pass an argument? I've tried input,output=popen2('/tmp/hello') input.write("Some string") input.close() # I get an error here. Thanks Colin From mark at prothon.org Sat Mar 27 21:47:04 2004 From: mark at prothon.org (Mark Hahn) Date: Sat, 27 Mar 2004 18:47:04 -0800 Subject: Prothon Prototypes vs Python Classes References: <569c605ld1cj8fc1emolk08ete0s1prls1@4ax.com> <106cc1f2rsnaoe2@news.supernews.com> <406635AB.9050803@mlug.missouri.edu> <106ceeeqc8ph126@news.supernews.com> Message-ID: > although for reasons I've mentioned elsewhere, I won't use Prothon. Can you please point me to those reasons? "John Roth" wrote in message news:106ceeeqc8ph126 at news.supernews.com... > > "Michael" wrote in message > news:406635AB.9050803 at mlug.missouri.edu... > > I'm not terribly familiar with the concept of prototypes although I > > believe I understand the basic meaning and I have worked in languages > > which do use prototypes (although not called that). > > > > Aren't there many times when it is usefult to work with classes where > > you do not want an instance to exist? Such as multiple level of > > subclasses where code is kept easily readable by putting it on a the > > appropiate class for that function alone. Often useful when you'll be > > using many similar but not identical objects? I can see how it'd be > > useful to be able to define new methods on an object, or edit the > > methods on an object but I can not see the purpose to removing classes > > altogether. Am I correct in my impression that with prototyping you must > > instantate an object to define it's structure? That would seem wasteful > > and cluttering of the namespace. Also he way your prototypes read appear > > less clear to me than a class definition. I fear that you'd wind up with > > people creating an object.. coding random stuff.. adding a method to > > that object.. coding more random stuff.. and then adding more to the > > object. > > It's certainly true that in a prototype based language all objects > exist: there are no objects that the compiler deals with but does > not put into the resulting program. And it's quite true that it does > open up the floodgates for a lot of messiness. > > On the other hand, there are application areas where that is > exactly what you need: I've already mentioned interactive fiction, > and there are undoubtedly others. > > I'd like to play around with a prototype based language to see how it > works, although for reasons I've mentioned elsewhere, I won't use > Prothon. I'd be using IO if they had a windows executable installer, > rather than requiring me to compile the silly thing. > > John Roth > > From andrew-pythonlist at puzzling.org Wed Mar 3 17:28:17 2004 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Thu, 4 Mar 2004 09:28:17 +1100 Subject: XML-RPC server framework In-Reply-To: <20040303155616.GA28132@carbon.redbrick.dcu.ie> References: <20040303155616.GA28132@carbon.redbrick.dcu.ie> Message-ID: <20040303222817.GA23030@frobozz> On Wed, Mar 03, 2004 at 03:56:16PM +0000, Cillian Sharkey wrote: > Hi, > > I'm trying to find any existing frameworks for writing an XML-RPC server > that has the following features: > > - HTTPS > - connection oriented (HTTP/1.1 persistent connections) > - multiple concurrent connections > - hooks for custom handling of HTTP basic authentication > - dynamic documentation on GET requests a la DocXMLRPCServer > > I'm aware of xmlrpclib, M2Crypto, py-xmlrpc, Twisted but haven't found > an existing implementation that does all of the above. I'd prefer not to > have to write it myself :-) Which of these does Twisted lack? > Any tips appreciated (please CC me on replies). Done. -Andrew. From kmmcdonald at wisc.edu Sun Mar 14 15:03:29 2004 From: kmmcdonald at wisc.edu (Kenneth McDonald) Date: Sun, 14 Mar 2004 20:03:29 GMT Subject: Question on making names visible in packages Message-ID: This will have an easy answer, no doubt, unfortunately I can't think of it... I'm writing a package which will have a number of classes. I'd like to split them amongst different files within the package. However, I'd also like the package user to be able to say: import Package and then to use the classes as Package.Class1, Package.Class2, etc. However, I'm only able to get this behavior when I leave the class definitions in the __init__.py file. When in other files, they of course have to be referenced as : Package.filename.Class1 Is there some way of making the names visible at the top level of the module, to mask the fact that they are split amongst different files within the package? The split reflects a logical organization of the code from the point of view of the designer of the package, but not from the user, and so I don't want the user to necessarily be aware of the file organization. (If they want to be, hey, that's fine...) Thanks, Ken McDonald From jacek at lxplus057.cern.ch Mon Mar 15 15:30:33 2004 From: jacek at lxplus057.cern.ch (Jacek Generowicz) Date: 15 Mar 2004 21:30:33 +0100 Subject: Static Typing in Python References: <4055a71e$0$28265$afc38c87@news.easynet.co.uk> Message-ID: JCM writes: > 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. I don't disagree with you :-) As I keep saying, weak typing is a wishy-washy concept, and your working definition has a lot of merit. Could you cite anything that uses your definition? (I'm not asking for these to argue with you, but to have something to cite in situations when I might want to back up your working definition.) From Juha.Autero at iki.fi Mon Mar 22 15:24:44 2004 From: Juha.Autero at iki.fi (Juha Autero) Date: Mon, 22 Mar 2004 22:24:44 +0200 Subject: galagASCII References: <1079966982.1784.183098800@webmail.messagingengine.com> Message-ID: <87isgwwrxv.fsf@jautero.no-ip.org> "Lincoln Rutledge" writes: > Lots of bugs so when it dies, you may have to re-login b/c the terminal > is in a wierd mode thanks to curses.endwin() not getting run... There is a command called "reset" that resets the terminal. -- Juha Autero http://www.iki.fi/jautero/ Eschew obscurity! From no.mail at available.net Sun Mar 14 13:17:53 2004 From: no.mail at available.net (Georgy) Date: Sun, 14 Mar 2004 18:17:53 GMT Subject: Is reverse reading possible? References: Message-ID: "Anthony Liu" wrote in message news:mailman.29.1079282915.745.python-list at python.org... | In terms of file input, can we read from the end of | the file till the beginning of a file? reversed_text = file( filename, "r" ).read()[::-1] From steve at ninereeds.fsnet.co.uk Wed Mar 10 11:44:31 2004 From: steve at ninereeds.fsnet.co.uk (Stephen Horne) Date: Wed, 10 Mar 2004 16:44:31 +0000 Subject: PEP 328: Imports: Multi-Line and Absolute/Relative References: <104q64b2uf3nl0b@news.supernews.com> <104u4ktn5hoc9db@news.supernews.com> Message-ID: On Wed, 10 Mar 2004 08:04:22 -0500, "John Roth" wrote: >> While that makes some sense, what about "uncle" references within the >> current package? > >I'm not sure what you mean by "Uncle." The term usually >means "parent's brother" or "some son of your grandparents >other than your father" so I'd assume it would go up one >directory and then sideways, which would require going up >another directory. > >If you are refering to another module in the same directory >that this one came from, then I'd code that as: > >import *.foo > >However, possibly you meant "cousin?" That doesn't sound right either. A cousin is an uncles son. Maybe he meant sibling or brother. sibling = sideways ref uncle = up then sideways ref cousin = up then sideways ref then down OTOH, it depends where you consider the start point to be. It seems pointless to have the start point as 'self', so maybe the start point is 'father'. A simple reference would then be to a sibling (implicit up then down) and a sideways reference to an uncle. I'm probably just confused, though I'd love to know exactly how. -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From ville at spammers.com Wed Mar 24 08:25:21 2004 From: ville at spammers.com (Ville Vainio) Date: 24 Mar 2004 15:25:21 +0200 Subject: PEP 318 References: <95aa1afa.0403222352.2679dde@posting.google.com> <95aa1afa.0403232104.328356ea@posting.google.com> Message-ID: >>>>> "Andrew" == Andrew Bennetts writes: Andrew> Decorators don't add any new capabilities to python, just Andrew> a more convenient spelling for existing features. I know, the decorator syntax just makes these look so much nicer. Andrew> Which is to say, I don't understand how that can work -- Andrew> the first definition of foo gets clobbered. Yes, the name 'foo' gets clobbered every time, but the decorator always returns the *dispatcher* that is capable of dispatching the call to the correct definition of 'foo'. The dispatcher preserves the references to the callables, so they don't get decreffed out of existence. The dispatcher obviously needs a reference to a module global dict object of some sort, with some magical name like '__mm_dispatcher_registry'. Andrew> You *could* have a global registry that's keyed off Andrew> func_name, as you suggest, but that doesn't work in Andrew> general... what if I later have: Andrew> class C2: Andrew> def foo(self, other): Andrew> ... Andrew> foo = multimethod(Long, String)(foo) Andrew> How is the registry not going to help distinguish between Andrew> the foo methods from C, and the foo methods from C2? It's not. I'm still thinking of multimethods mostly as plain functions with dynamic dispatching on arg types, not actual methods. To get the functionality in methods, you just need to call the mm function explicitly with an unique name inside the method. I'm not sure whether methods could be dispatched more automatically, someone might have some ideas? Andrew> I don't understand why __mul__ is any different to foo here. Well, it's just that __mul__ absolutely needs to be a method in order to be called on seeing an * operator. 'foo' can be taken out of the class. -- Ville Vainio http://tinyurl.com/2prnb From piet at cs.uu.nl Thu Mar 25 09:13:47 2004 From: piet at cs.uu.nl (Piet van Oostrum) Date: 25 Mar 2004 15:13:47 +0100 Subject: Python for large projects References: <1060p59d9rg9819@corp.supernews.com> <36wzna6qzur.fsf@hundertwasser.ti.uni-mannheim.de> Message-ID: >>>>> Jacek Generowicz (JG) wrote: JG> Matthias writes: >> Ville Vainio writes: >> >> > >>>>> "Jacek" == Jacek Trzmiel writes: >> > >> > Jacek> Jacek Generowicz wrote: >> > >> ... and one thing that makes unit testing very difficult, is >> > >> static typing ... >> > >> > Jacek> Care to provide some examples to back this opinion up? JG> Your supercite references to "Jacek" are rather ambiguous, in this JG> case (unlikely though it may seem, in general :-) Tat is because supercite used `statically typed' citing, whereas traditional citing is untyped. In this specific case it seems that static typing is less confusing :=) -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP] Private email: P.van.Oostrum at hccnet.nl From michael at foord.net Fri Mar 12 08:50:34 2004 From: michael at foord.net (Fuzzyman) Date: 12 Mar 2004 05:50:34 -0800 Subject: Gadfly ???? References: <8089854e.0403040124.1c6bd929@posting.google.com> <8089854e.0403080014.4e03b516@posting.google.com> <8089854e.0403100004.4c49cd3c@posting.google.com> Message-ID: <8089854e.0403120550.258e7601@posting.google.com> Gerhard H?ring wrote in message news:... > Fuzzyman wrote: > > I can do a proof of concept on my own computer with a personal server. > > If you're writing a CGI script, putting the PySQLite files into the cgi-bin > directory will work fine. Just copy them from a PC where you've installed PySQLite > locally: > > cgi-bin directory: > > myscript.py <----- your CGI script > _sqlite.pyd > sqlite/ > sqlite/main.py > sqlite/__init__.py > > HTH, > > -- Gerhard Hmmm.... that's looking good. All I need is a prebuilt verson of _sqlite.pyd for our *Linux* server..... and to learn SQL.... (or at least SQLite syntax) Regards, Fuzzy From cbrown at metservice.com Sat Mar 13 19:21:39 2004 From: cbrown at metservice.com (Colin Brown) Date: Sun, 14 Mar 2004 13:21:39 +1300 Subject: Behaviour of time.sleep with negative arg Message-ID: <4053a412$1@news.iconz.co.nz> Python 2.3.3 Under Windows NT: Negative Int or Real -> sleeps for a long time Under Linux: Returns IOError: [Errno 22] Invalid argument I consider both of these unfriendly results and expected the preferable silent time.sleep(0) in much the same way that slicing a string beyond the ends returns an empty string. Colin Brown PyNZ From tkablackdeath at hotmail.com Mon Mar 8 01:32:06 2004 From: tkablackdeath at hotmail.com (Ben Drayton) Date: Mon, 08 Mar 2004 19:32:06 +1300 Subject: help Message-ID: hey i was wondering if there was any easy was to make txt documents end lines. I have a very basic password program which needs to pick a line out from the others in the document to use as the password. However the document is just comming out in one long line. Also any sugestions for imporement on my password program would be appreciated. thnaks. (here is the program if it helps. it sucks i kno but hey im new) count = 0 password = "" password1 = "" username = "" username1 = "" pword = open ('hddl.txt') while password1 != pword.readline (26) and username1 != pword.readline (4) and password != pword.readline(28) and username != pword.readline(5) and count < 3: username = raw_input("username:") password = raw_input("password:") count = count +1 if username == pword.readline(4) and password == pword.readline (26): password = password1 username = username1 password = pword.readline(28) username = pword.readline(5) if username == pword.readline(5) and password == pword.readline(28): password1 = pword.readline (26) username1 = pword.readline (4) else: print if (password1 == pword.readline(26) and username1 == pword.readline(4) and count < 3 and password == pword.readline(28) and username == pword.readline(5) and count < 3): #there is a program here else: print "sorry authorised access onl" _________________________________________________________________ Surf the net and talk on the phone with Xtra JetStream @ http://xtra.co.nz/jetstream From NAIGIMSESRIMAIL at gims.com Thu Mar 4 18:19:32 2004 From: NAIGIMSESRIMAIL at gims.com (GroupShield for Exchange (ESRIMAIL)) Date: Fri, 5 Mar 2004 01:19:32 +0200 Subject: ALERT - GroupShield ticket number OA108_1078442351_ESRIMAIL_1 wa s generated Message-ID: Action Taken: The attachment was quarantined from the message and replaced with a text file informing the recipient of the action taken. To: python-list at python.org From: jceasar at tmp.org Sent: 915163136,29622834 Subject: ^_^ meay-meay! Attachment Details:- Attachment Name: Message.zip File: Message.zip Infected? Yes Repaired? No Blocked? No Deleted? No Virus Name: W32/Bagle.gen!pwdzip -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/ms-tnef Size: 1878 bytes Desc: not available URL: From knight at baldmt.com Thu Mar 11 22:50:36 2004 From: knight at baldmt.com (Steven Knight) Date: Fri, 12 Mar 2004 03:50:36 +0000 (UTC) Subject: ANN: SCons 0.95 supports Visual Studio 2003, Borland tools, "D" programming language Message-ID: SCons is a software construction tool (build tool, or make tool) written in Python. It is based on the design which won the Software Carpentry build tool competition in August 2000. Version 0.95 of SCons has been released and is available for download from the SCons web site: http://www.scons.org/ Or through the download link at the SCons project page at SourceForge: http://sourceforge.net/projects/scons/ RPM and Debian packages and a Win32 installer are all available, in addition to the traditional .tar.gz and .zip files. WHAT'S NEW IN THIS RELEASE? IMPORTANT: Release 0.95 contains the following interface changes: - The default behavior of the Zip() Builder is now to create a compressed file. - The "overrides" keyword argument when creating a Builder() has been deprecated in favor of specifying the values directly with keyword arguments. - The meaning of the "mode" keyword argument values to the SCons.Util.scons_subst() and SCons.Util.scons_subst_list() functions have been changed. (These are internal functions and should have no external effect, but we list them here for completeness.) See the release notes for more information about these changes. This release adds the following features: - Microsoft Visual Studio 2003 (version 7.1) is now supported. - The bcc32, ilink32 and tlib Borland tools are now supported. - The Digital Mars "D" programming language is now supported. - A new $MSVS_USE_MFC_DIRS construction variable controls whether the Microsoft Visual Studio ATL and MFC directories are included in the default INCLUDE and LIB paths. - New AppendUnique() and PrependUnique() Environment methods add values (flags) to construction variables only if they're not already present. - New "rsrcpath" and "rsrcdir" attributes to the $TARGET, $TARGETS, $SOURCE and $SOURCES construction variables allow Builder commands to access Repository source directories when using a Builder. - A new --debug=count option displays the numbers of various types of internal objects created, when run under Python 2.1 or later. - A new --debug=objects option dumps information about SCons internal objects when run under Python 2.1 or later. - A new --debug=memory option displays memory usage statistics when run under Linux systems. - A new ZIPCOMPRESSION construction variable controls whether the internal Python action for the Zip Builder compresses the file or not. The default value is zipfile.ZIP_DEFLATED, which generates a compressed file. - A new "toolpath" Tool() and Environment keyword allows Tool modules to be searched for in specified local directories. The following bug fixes have been added: - SCons now gracefully handles non-string construction variables in all known situations. - Construction variables may now be recursively expanded (e.g. CCFLAGS = "$CCFLAGS -g") without going into an infinite loop. - Compile the moc_*.cc Qt files using the correct environment flags, not those from the environment that first had Qt Builders attached. - Expansions like ${TARGET.dir} now work properly in *PATH construction variables (like CPPPATH, F77PATH, etc.). - Qt support now works from a copied construction environment. - The M4 Builder now changes correctly to a Repository directory when the source file is in the source directory of a BuildDir. - Automatic checkout of implicit dependency files from SCCS and RCS has been fixed. - Builder-specific override values are now always used in substitutions, not just when there isn't a target-specific environment. - SCons now properly checks for whether all of the objects going into a SharedLibrary() are shared, even if the object was already built. - SCons now correctly looks up a Win32 drive letter with no path ('C:') as a directory. - Specifying .class files as input to JavaH with the .class suffix when they weren't generated using the Java Builder has been fixed. - The env.Action() method now returns the correct type of Action for its argument(s). - The Configure() function now works when called from nested subsidiary SConscript files more than one level deep. - Error message spellings have been corrected from "non-existant" to "non-existent." - The EnsureSConsVersion() function now checks against the SCons version, not the Python version, for all Python version. - SCons now properly handles command-line arguments with multiple = in them. - SCons now correctly retrieves all files from cache when multiple files would ordinarily be built by in a single Action. - Use of a custom _concat() function in the construction environment when calling _stripixes() has been fixed. - The Fortran scanner is now case-insensitive for the INCLUDE string (per the Fortan spec). - Side-effect targets are now properly removed before building their corresponding target. - BuildDir() can, once again, be called multiple times with the same target and source directory arguments. - Output lines now stay (more nearly) together when -j is used. - A bug in saving and restoring PackageOptions to a file has been fixed. - Microsoft Visual Studio type libraries are now built in the target directory, not the source directory. - Generated Microsoft Visual Studio project files now re-invoke SCons correctly regardless of whether the file was built via scons.bat or scons.py. - Evaluate $MSVSPROJECTSUFFIX and $MSVSSOLUTIONSUFFIX when the Builder is invoked, not when the tool is initialized. - A typo has been fixed in the Microsoft Visual C registry lookup ("VCComponents.dat", not "VSComponents.dat"). - When using Microsoft Visual C++, SCons now uses independently configured "include," "lib" or "path" from the registry. Previously, SCons would only use the values if all three were set in the registry. - SCons now ignore any "6.1" version of Microsoft Visual C++ found in the registry; this is apparently a phony version number (created by later service packs?) that throws off the logic if the user had any non-default paths configured. - SCons now uses the Microsoft Visual C++ 6.0 paths by default if the "msvc" Tool is specified but no version of MSVC is detected on disk. The following miscellaneous improvements have been added: - All *FLAGS variables now "do the right thing" (as much as possible) when appending flags with either strings or lists of flags. - The -H help text now lists the legal --debug values. - SCons now supplies an error message if you try to configure a BuildDir for a directory that already has one. - The error message when a source file can't be found has been reworded to make it more clear. - SCons now supplies a useful error message, not a stack trace, if a construction variable expansion contains a syntax error. - SCons now supplies meaningful error messages, not stack traces, if a non-Node is added as a source, dependency, or ignored dependency of a Node. - The $LIBS construction variable can now contain File nodes, and can now be a single string or File node, not a list, when only one library is needed. - When scanning for libraries to link with, SCons no longer appends $LIBPREFIXES or $LIBSUFFIXES values to the $LIBS values if they're already present. - SCons now allows a target that can have its Builder called multiple times to be called through multiple environments without error, so long as the Builder calls all use the same action. - The message about ignoring a missing SConscript file is now a suppressable Warning, not a hard-coded sys.stderr.write(). - On POSIX systems with the "env" command, spawn commands with the more portable "env -" idiom, instead of "env -i". - Improve Cygwin support by accomodating Cygwin Python's delusion that it's running on a case-sensitive file system. - Microsoft Visual Studio .NET and Visual C 6.0/7.0 path detection has been updated and made more robust. Memory utilization has been improved as follows: - "Build" construction environments with overrides are now only generated as needed, not for every target. - Nodes now delete their build environments after they've been built. The documentation has been improved: - The User's Guide now has an appendix describing how to accomplish various common tasks in Python. - Mention of the still-unimplemented -e option has been removed. - A man page typo of "JAVACHDIR" instead of "JARCHDIR" has been fixed. - An undocumented "for_signature" argument in the __call__() example of the "Variable Substitution" section has now been documented. - An odd double-quote escape sequence in the man page has been fixed. - The dbm_module argument to the SConsignFile() function has been documented. ABOUT SCONS Distinctive features of SCons include: - a global view of all dependencies; no multiple passes to get everything built properly - configuration files are Python scripts, allowing the full use of a real scripting language to solve difficult build problems - a modular architecture allows the SCons Build Engine to be embedded in other Python software - the ability to scan files for implicit dependencies (#include files); - improved parallel build (-j) support that provides consistent build speedup regardless of source tree layout - use of MD5 signatures to decide if a file has really changed; no need to "touch" files to fool make that something is up-to-date - easily extensible through user-defined Builder and Scanner objects - build actions can be Python code, as well as external commands An scons-users mailing list is available for those interested in getting started using SCons. You can subscribe at: http://lists.sourceforge.net/lists/listinfo/scons-users Alternatively, we invite you to subscribe to the low-volume scons-announce mailing list to receive notification when new versions of SCons become available: http://lists.sourceforge.net/lists/listinfo/scons-announce ACKNOWLEDGEMENTS Special thanks to Chad Austin, Kerim Borchaev, Chris Burghart, Steve Christensen, David M. Cooke, Charles Crain, Andy Friesen, Scott Lystig Fritchie, Bob Halley, Zephaniah Hull, Vincent Risi, Anthony Roach, Greg Spencer and Christoph Wiedemann for their contributions to this release. On behalf of the SCons team, --SK From mgb at mgbeckett.com Thu Mar 25 06:18:06 2004 From: mgb at mgbeckett.com (Martin Beckett) Date: 25 Mar 2004 03:18:06 -0800 Subject: Getting username and passwd from IE References: <6b13855b.0403240446.7206703b@posting.google.com> <2c60a528.0403241250.9a8b572@posting.google.com> Message-ID: <6b13855b.0403250318.41cd928b@posting.google.com> > Don't know about BaseHTTPServer in particular, but in general 401 must be > used in conjunction with the WWW-Authenticate response header, or the browser > won't know what kind of authentication to send. > > self.send_header('WWW-Authenticate', 'basic realm="Fab site"') Thank you that works - specifically: self.send_response(401) self.send_header('WWW-Authenticate','basic') self.end_headers And to help other searches: Internet Explorer force send username password authentication AUTHORIZATION From srijit at yahoo.com Tue Mar 16 13:43:55 2004 From: srijit at yahoo.com (srijit at yahoo.com) Date: 16 Mar 2004 10:43:55 -0800 Subject: Is Python type safe? Message-ID: <221d8dbe.0403161043.52406195@posting.google.com> Hello, I would like to know the definition of type safe and whether Python can be considered as a type safe language. Similarly are Java, C# or C++ type safe? Regards, Srijit From imbosol at aerojockey.invalid Mon Mar 15 23:43:01 2004 From: imbosol at aerojockey.invalid (Carl Banks) Date: Tue, 16 Mar 2004 04:43:01 GMT Subject: Deprecating reload() ??? References: <6kk6501shlve52ds2rjdopa73jhpchprg3@4ax.com> Message-ID: David MacQuigg wrote: > On Mon, 15 Mar 2004 05:49:58 -0600, Skip Montanaro > wrote: > >> 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 > > Implementation detail. ( half wink ) > >>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. > > If you reload a module M1, and it has an attribute M1.x, which was > changed from '1' to '2', we want to change also any references that > may have been created with statements like 'x = M1.x', or 'from M1 > import *' If we don't do this, reload() will continue to baffle and > frustrate new users. What if one of your users does something like 'y = M1.x + 1'; then what are you going to do? It seems to me that your noble effort to make reload() completely foolproof is ultimately in vain: there's just too many opportunities for a module's variables to affect things far away. -- 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 myang at clarku.edu Sat Mar 13 21:22:11 2004 From: myang at clarku.edu (myang) Date: Sat, 13 Mar 2004 21:22:11 -0500 Subject: execute script everywhere Message-ID: After we compile a C program, we can put the executable file under a directory (like /bin) so that we can run it everywhere, and don't have to type the full path. Can we do the same thing to a python script? For example, I have a script.py under "/home/john/". Can I just type "python script.py" to run it under another directory "/home/tom/"? Thanks! Yang From mfranklin1 at gatwick.westerngeco.slb.com Mon Mar 15 14:58:24 2004 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Mon, 15 Mar 2004 19:58:24 +0000 Subject: tkinter entry/text widget In-Reply-To: References: Message-ID: <40560AE0.3070107@gatwick.westerngeco.slb.com> bigbinc wrote: > I have used the 'entry' tk widget to get text values, I am now using > 'Text' but I cant seem to use 'get' method. The TK docs say use > get(index1, index2), I tried numbers and get an error > > > print self.textMain.get(1,255) > > ceback (most recent call last): > ile "C:\Python23\lib\lib-tk\Tkinter.py", line 1345, in __call > return self.func(*args) > ile "blog.py", line 60, in saveFile > print self.textMain.get("1","255") > ile "C:\Python23\lib\lib-tk\Tkinter.py", line 2868, in get > return self.tk.call(self._w, 'get', index1, index2) > Error: bad text index "1" You should go get the Tk command reference OK it's not written in 'Python' but it's still easy to translate. Download a HTML version from here:-- http://www.tcl.tk/man/ The Exact reference for this problem would be :- http://www.tcl.tk/man/tcl8.4/TkCmd/text.htm#M18 'Text widget INDICES' It boils down to passing strings to the .get() method like so:- myTextWidget.get("0.0", "end") will get all the text in the Text widget. HTH Martin From amk at amk.ca Mon Mar 8 08:29:14 2004 From: amk at amk.ca (A.M. Kuchling) Date: Mon, 08 Mar 2004 07:29:14 -0600 Subject: "print" as function not statement References: Message-ID: On Mon, 08 Mar 2004 10:36:54 GMT, Leif K-Brooks wrote: > Why check for unknown keyword arguments? It seems to me that better > forward-compatibility is achieved if we ignore them. Typo-catching, probably; otherwise if someone wrote show(a,b,c, seperator=':') they'll get output without colons and wonder why. --amk From prouleau at impathnetworks.com Sun Mar 21 10:49:49 2004 From: prouleau at impathnetworks.com (Pierre Rouleau) Date: Sun, 21 Mar 2004 10:49:49 -0500 Subject: New restrain builtin function? In-Reply-To: References: Message-ID: Robert Brewer wrote: > I think if I were to write my own version today in pure Python, > it'd be invoked as: limit(object, lower, upper), where could be > an iterable. I see that as a much more common use case; that is, mapping > the same pair of boundaries to multiple items. > > Interesting. I had a simple one written in pure Python that was just checking the type of object to determine if it was a sequence Agreed. I had writte a pure Python one where I was looking for the object type with type(object). def restrain(theObject, lowerBound, upperBound): if type(theObject) in [types.ListType, types.TupleType]: return map(lambda val,theMin,theMax: min(max(val,theMin),theMax) , theObject, lowerBound, upperBound) else: return min(max(theObject, lowerBound), upperBound) However, 1) I don't like using type(theObject) to check if it is a sequence because that does not allow iterable objects. 2) It does not allow the use case you just mentionned where the same boundary is applied to every member set. So I wonder: 1) what's the easiest way to find if an object is iterable? There is no 'isiterable()' built in. Would it be to try iterate over it and cath the potential exception or is there a better way? Pierre Rouleau From piet at cs.uu.nl Wed Mar 10 07:50:15 2004 From: piet at cs.uu.nl (Piet van Oostrum) Date: 10 Mar 2004 13:50:15 +0100 Subject: Gadfly ???? References: <8089854e.0403040124.1c6bd929@posting.google.com> <8089854e.0403080014.4e03b516@posting.google.com> Message-ID: >>>>> michael at foord.net (Fuzzyman) (F) wrote: F> Because I *won't* be allowed to install anything other than python F> scripts on the server........... F> So I am looking for a database implementation in python........ I suppose your python script is allowed to write some file(s), otherwise you wouldn't be able to implement a database. You could import a special _sqlite.py module that has _sqlite.pyd encoded in a big string, and on the first call writes it out to _sqlite.pyd and wouldn't be called on subsequent times. -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP] Private email: P.van.Oostrum at hccnet.nl From No.Spam.mc at No.Spam.mclaveau.No.Spam.com Tue Mar 30 01:33:08 2004 From: No.Spam.mc at No.Spam.mclaveau.No.Spam.com (Michel Claveau/Hamster) Date: Tue, 30 Mar 2004 08:33:08 +0200 Subject: Britney Spears nude References: <1080607371.97814.0@iris.uk.clara.net> Message-ID: Hi ! Is "BOOB = Britney Oriented Object Breast" correct ? *sorry for my bad english* @-salutations -- Michel Claveau From tjreedy at udel.edu Fri Mar 5 14:17:14 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 5 Mar 2004 14:17:14 -0500 Subject: is perl better? References: Message-ID: "jon c" wrote in message news:Law11-F108dhVtRRM4c0002bf6d at hotmail.com... > the error is coming from windows! > > the error message is as I wrote it. > > if you try and execute the command directly from bat you get the error input > line too long! As I expected... > can perl be somehow bypassing the windows terminal and running the command > directly (does this make sense?) It must be. Given that it (reportedly) bypasses the C stdio library (on Windows), it would not surprise me. With more users, probably had one hit length limit sooner, and with greater willingness than Python developers to bypass Ansi C, might have done so. 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 ;-) 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). 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. Trying to be helpful, Terry J. Reedy From pcaffrey at iel.ie Fri Mar 26 10:40:45 2004 From: pcaffrey at iel.ie (Paul) Date: 26 Mar 2004 07:40:45 -0800 Subject: odd behaviour with embedded python and omniorb References: <6c5f2ab0.0403250846.6e773bb0@posting.google.com> Message-ID: Hi Duncan Duncan Grisby wrote in message news:... > In article <6c5f2ab0.0403250846.6e773bb0 at posting.google.com>, > denginere wrote: > > >I have a situation where I am embedding python in c++ and > >calling omniorb within python. > > You're better off asking this kind of question on the omniORB mailing > list. > > >c++ -> python -> c++ -> python > > > >The python is called using the following > > // Import the module/script > > pTmpModule = PyImport_Import(pName); > > PyObject_CallObject(pFunc, pArgs); > > > >If we call python once it's fine > >If we call python a second time (as above) it fine *mostly* > > > >However if we call python a second time, *and* import omniORB > >the PyImport_Import fails! > > How does it fail? y", line 4, in ? from omniORB import CORBA File "./__init__.py", line 357, in ? ImportError: No module named omni_func > > Are you reinitialising the Python interpreter between calls into it? > If so, you might want to try the CVS version of omniORBpy since it has > some fixes for that situation. I think the answer it no: The second time we use a different Python context > > Cheers, > > Duncan. From fumanchu at amor.org Thu Mar 25 17:56:38 2004 From: fumanchu at amor.org (Robert Brewer) Date: Thu, 25 Mar 2004 14:56:38 -0800 Subject: [Newbie]Trouble with string method Message-ID: Sean Berry wrote: > Try the following > > unsorted = open('unsorted', 'r').readlines() -- two steps into one > unsorted.sort(lambda x, y: cmp(string.lower(x), string.lower(y))) > unsorted.close() > sorted = open('sorted', 'w') > sorted.writelines(unsorted) > soretd.close() > > Your problem is that you are trying to use a string method on a list. > > > calpolynate wrote in message > news:96fd272b.0403251442.49047ba9 at posting.google.com... > > I'm attempting to open a file, read the lines, sort them, change any > > uppercase character to lowercase, and output to another file: > > > > import string > > > > unsorted = open('unsorted', 'r') > > L = unsorted.readlines() > > L.sort() > > L = L.lower() > > sorted = open('sorted', 'w') > > sorted.writelines(L) > > unsorted.close() > > sorted.close() > > > > when trying to run, I get this traceback: > > > > Traceback (most recent call last): > > File "sort_list.py", line 6, in ? > > L = L.lower(L) > > AttributeError: 'list' object has no attribute 'lower' > > > > Do I need to somehow convert the list into strings? > > > > Thanks for any help! I think he wanted the output to be lowercase, not just sorted case-insensitively (that's how I read it anyway). Try: lines = [line.lower() for line in open('unsorted', 'r')] lines.sort() sorted = open('sorted', 'w') sorted.writelines(lines) sorted.close() Robert Brewer MIS Amor Ministries fumanchu at amor.org From jcarlson at nospam.uci.edu Tue Mar 23 17:30:24 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Tue, 23 Mar 2004 14:30:24 -0800 Subject: PEP 328: Imports: Multi-Line and Absolute/Relative In-Reply-To: References: Message-ID: >>from HOW.MODULE import NAMES as RENAME >>import HOW.MODULE.NAMES as RENAME >> >>Where HOW is of the form: >>-[.PACKAGE1[.PACKAGE2[...]]] >>[PACKAGE1[.PACKAGE2[...]]] > +1. (I know I'm late :) Glad you like it. > Very readable, doesn't use any new magical names - and numbers have no > other use in import statements anyway. There is something different in > it, in a positive sense. > > I'll miss the current behavior of import, though. Somehow it feels > more intuitive to me. Oh, well, practicality beats purity - or > personal taste... You can still use classic import semantics, - is optional. - Josiah From peter at engcorp.com Fri Mar 5 10:19:37 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 05 Mar 2004 10:19:37 -0500 Subject: "Virtual" file system mock object - replacing stuff in __builtins__ In-Reply-To: <404844e3$1@epflnews.epfl.ch> References: <404844e3$1@epflnews.epfl.ch> Message-ID: <9oSdnRHo7cgXB9XdRVn-sQ@powergate.ca> Remy Blank wrote: > As a fan of TDD (test-driven development), I use the unittest module to > write the test cases for these tools. However, to make the test cases > independent of the file system environment, I simulate a file system > tree with a mock object using the following technique (sorry for the > long posting): > [snip code] > Now my questions: > - Am I doing something fundamentally forbidden (replacing stuff in > existing modules like __builtins__ or os)? > - Is there a better way of achieving the same result? > - If the technique is generally useful, would there be interest in > having a full-featured "virtual" file system mock object? I couldn't > find anything similar on Google. It's not fundamentally forbidden to stick things in __builtins__, or even other standard modules, but it's rarely necessary and might be subject to a future ban if those people who periodically discuss disallow assignments to __builtins__ have their way and forget about those of us who need the technique for testing. Nevertheless, if you are really doing things in a test-driven fashion, it should not be necessary to use __builtins__, if the open() calls and such are in your own code. In that case just create a reference to your mock file system methods in the module under test, using the names "open" and "stat" and so forth, and they will shadow the __builtin__ names. (Locals are found first, then globals, then builtins.) I don't know of a better way of doing this, and in fact we've built our own mock file system in several different projects, in a limited fashion. The idea of a standardized or at least widely used "full-featured" virtual file system is an excellent one! Writing tests that rely on the real filesystem can be awkward and is probably one of the many small things stopping/slowing some people from adopting TDD more. -Peter From oussoren at cistron.nl Thu Mar 18 15:22:02 2004 From: oussoren at cistron.nl (Ronald Oussoren) Date: Thu, 18 Mar 2004 21:22:02 +0100 Subject: Result of ``a is b'' In-Reply-To: <40200384.0403180514.341fe3b0@posting.google.com> 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: On 18-mrt-04, at 14:14, Axel Boldt wrote: > afriere at yahoo.co.uk (Asun Friere) wrote >> axelboldt at yahoo.com (Axel Boldt) wrote > >>> 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? > > Indeed I have not. Probably because basic built-in strings form a type > that's not a class and you can't inherit from it. Yes you can: Python 2.3 (#1, Sep 13 2003, 00:49:11) [GCC 3.3 20030304 (Apple Computer, Inc. build 1495)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> class MyStr(str): pass ... >>> x = MyStr("hello") >>> type(x) >>> From daniel at syrinx.net Fri Mar 26 17:00:06 2004 From: daniel at syrinx.net (Daniel Ellison) Date: Fri, 26 Mar 2004 17:00:06 -0500 Subject: A 'Python like' language References: <40645d8f$0$10775$afc38c87@news.easynet.co.uk> <1068up4kn49778@news.supernews.com> <106959g6i63cv77@news.supernews.com> Message-ID: "Robin Becker" wrote in message news:MezCgcAebKZAFwzi at jessikat.fsnet.co.uk... > It's getting near to April 1 so is prothon http://www.prothon.org/ real? > -- > Robin Becker If so, it's a pretty elaborate hoax: the interpreter is downloadable and even works! :) There are also three active mailing lists. Daniel Ellison From duncan-news at grisby.org Fri Mar 26 06:43:43 2004 From: duncan-news at grisby.org (Duncan Grisby) Date: Fri, 26 Mar 2004 11:43:43 +0000 Subject: odd behaviour with embedded python and omniorb References: <6c5f2ab0.0403250846.6e773bb0@posting.google.com> Message-ID: In article <6c5f2ab0.0403250846.6e773bb0 at posting.google.com>, denginere wrote: >I have a situation where I am embedding python in c++ and >calling omniorb within python. You're better off asking this kind of question on the omniORB mailing list. >c++ -> python -> c++ -> python > >The python is called using the following > // Import the module/script > pTmpModule = PyImport_Import(pName); > PyObject_CallObject(pFunc, pArgs); > >If we call python once it's fine >If we call python a second time (as above) it fine *mostly* > >However if we call python a second time, *and* import omniORB >the PyImport_Import fails! How does it fail? Are you reinitialising the Python interpreter between calls into it? If so, you might want to try the CVS version of omniORBpy since it has some fixes for that situation. Cheers, Duncan. -- -- Duncan Grisby -- -- duncan at grisby.org -- -- http://www.grisby.org -- From google at neilson.sent.com Mon Mar 8 09:40:15 2004 From: google at neilson.sent.com (Daniel H Neilson) Date: 8 Mar 2004 06:40:15 -0800 Subject: Question on loops References: Message-ID: "Delaney, Timothy C (Timothy)" wrote in message news:... > > From: Daniel H Neilson > > > > i = 0 > > for line in file: > > if i == 100: > > action > > i = 0 > > else: > > i += 1 > > process(line) > If you're using Python 2.3.x > > for i, line in enumerate(file): > if i % 100 == 0: > action > > process(line) > > Tim Delaney Beautiful. Thanks to those who responded. DHN From mcfletch at rogers.com Sat Mar 13 15:47:36 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Sat, 13 Mar 2004 15:47:36 -0500 Subject: Performance penalty for using properties? In-Reply-To: References: Message-ID: <40537368.2060205@rogers.com> Joe Mason wrote: >In article , Mike C. Fletcher wrote: > > >>Kenneth McDonald wrote: >>... >> >> >>>Can anyone comment on the performance >>>costs associated with properties vs. simple attribute lookup? >>> >>> ... >>OpenGLContext gets around this by >>defining an accelerator for the __get__ method of the field properties. >> >> > >What does "accelerator" mean in this context? Obviously, it's something >that speeds up __get__ calls, but ihow is that accomplished? > > Accelerator in this context is a small C-coded Python extension with two functions. One is a utility to retrieve a given key from an object's __dict__. The other implements the __get__ operation (including lookup of default method on the property on value lookup failure failure). All told about 100 lines of C code. http://cvs.sourceforge.net/viewcvs.py/pyopengl/vrml/accellerate/fieldaccel.c?view=markup (and yes, I know accelerate is mis-spelled in the module names :) ). >If it's a simple wrapper, that means you can blissfully ignore property >costs until profiling shows it's a problem, which is a big win. > > That's been my experience. I coded the entire VRML97 scenegraph engine without the accelerator module and only added it when profiling showed that the __get__ method was a hot-spot for performance. The non-accelerated code is still there in case the C module isn't available, of course. As I said, haven't gotten to the accelerator-writing stage yet with BasicProperty, but I expect to soon. Have fun, Mike _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From tismer at stackless.com Sat Mar 20 12:51:40 2004 From: tismer at stackless.com (Christian Tismer) Date: Sat, 20 Mar 2004 18:51:40 +0100 Subject: Package name with '.' in them: Python Bug ? In-Reply-To: References: <105mmlt1ld7jvb9@news.supernews.com> <8ef9bea6.0403192150.57dbddef@posting.google.com> <105oe5k5ovugi5e@news.supernews.com> Message-ID: <405C84AC.5040706@stackless.com> Yannick Patois wrote: > Hi, > > It's always very funny to read commented on onself at the third person;) > > I'm sorry to lost reader's time on this message, which is off-topic, > but, I couldnt resist to respond, being directly involved in this post. > > John Roth wrote: > >> The reason he's getting the flack he's getting > >> His response to Terry's >> original attempt to help him see what was going on was >> both rude and sarcastic; that kind of behavior simply isn't >> acceptable on this newsgroup. > > > Then, the behavior of Terry should also have been quoted as rude and > sarcastic. Most readers understood what I meant with my (incorrect) > qualification of "static". Sure, I had no problem to understand, and my first reaction on Terry's reply was like "why is this needed". Maybe this is perceived differently by different people, as I can understand John's POV well as well. And it happens quite often if you are answering many questions, that you get bored since you see the same stuff again and again. At least for my part, I sometimes react less friendly to newbie questions than I should. When I'm lucky, I read it again before sending and start over :-) > I hope persons should be able to post here > even if they dont master python vocabulary from a to z. This should be no problem, and I think this was misreadings/ misunderstandings, and I hope that you all bury the hatchet and be constructive, again. a nice weekend to all -- 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 andrew-pythonlist at puzzling.org Fri Mar 5 21:56:48 2004 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Sat, 6 Mar 2004 13:56:48 +1100 Subject: Can python read up to where a certain pattern is matched? In-Reply-To: <20040306021634.77057.qmail@web13004.mail.yahoo.com> References: <20040306021634.77057.qmail@web13004.mail.yahoo.com> Message-ID: <20040306025648.GC1878@frobozz> On Fri, Mar 05, 2004 at 06:16:34PM -0800, Anthony Liu wrote: [...] > read(), readline(), readlines() is what I want. I want > to read a text file sentence by sentence. > > A sentence by definition is roughly the part between a > full stop and another full stop or !, ? > > So, for example, for the following text: > > "Some words here, and some other words. Then another > segment follows, and more. This is a question, a junk > question, followed by a question mark?" > > It has 3 sentences (2 full stops and 1 question mark), > and therefore I want to read it in 3 lumps and each > lump gives me one complete sentence as follows: > > lump 1: Some words here, and some other words. > > lump 2: Then another segment follows, and more. > > lump 3: This is a question, a junk question, followed > by a question mark? > > How can I achieve this? Do we have a readsentence() > function? You can easily write iterators yourself using generators: ---- from StringIO import StringIO def bytes(f): for byte in iter(lambda: f.read(1), ''): yield byte def sentences(iterable): sentence = '' for char in iterable: sentence += char if char in ('.', '!', '?'): yield sentence.strip() sentence = '' sentence = sentence.strip() if sentence: yield sentence testFile = StringIO( """Some words here, and some other words. Then another segment follows, and more. This is a question, a junk question, followed by a question mark?""") for count, s in enumerate(sentences(bytes(testFile))): print 'lump %d: %r' % (count+1, s) ---- This gives the following output: lump 1: 'Some words here, and some other words.' lump 2: 'Then another\nsegment follows, and more.' lump 3: 'This is a question, a junk\nquestion, followed by a question mark?' Unfortunately (but not surprisingly), the re module only accepts strings, not iterables, otherwise you could use re.finditer, rather than writing your own less general function. Note that I've only lightly tested that code, and it's probably very inefficient. -Andrew. From kahanpaa at gstar.astro.helsinki.fi Sat Mar 27 04:46:38 2004 From: kahanpaa at gstar.astro.helsinki.fi (Jere Kahanpaa) Date: 27 Mar 2004 09:46:38 GMT Subject: creating lists question? References: Message-ID: Hi. spisatus wrote: > Josiah, > Now I know I have a long way to go:O) > I'm not sure this is doing what I want it to do. In the example I gave I > want a new list call "aaa" another list called "bbb"... so I can append to > the new list i.e., bbb.append(). It may be that your example does this but > it appears to be (with my limited knowledge) that it's creating a list of > lists, when all I want is a new isolated list. OK, now I understand what you are trying to do. Personally I'd store the lists in a dictionary: names = ['aaa','bbb','ccc'] lists = {} for name in names: lists[name] = [] lists['aaa'].append('foo') print lists['aaa'][0] print lists.items() This has the added benefit that you can operate on all lists by iterating over namedlists.values(). Jere -- Lord, make my words as sweet as honey, for one day I may have to eat them - Daryl Benson From me at privacy.net Fri Mar 12 06:21:03 2004 From: me at privacy.net (Heather Coppersmith) Date: 12 Mar 2004 06:21:03 -0500 Subject: Concatenating numerical and string attributes References: Message-ID: On Fri, 12 Mar 2004 01:26:14 -0800 (PST), dont bother wrote: > featurevector = string(1)+ " " + string(index[i]) + > ":" +string(vector[i]) > However, when I run my program I get this error: > $Traceback (most recent call last): > File "try.py", line 70, in ? > featurevector=string(index[i])+string(vector[i]) > TypeError: 'module' object is not callable "string" is a module. "str" is a type. HTH, Heather -- Heather Coppersmith That's not right; that's not even wrong. -- Wolfgang Pauli From perky at i18n.org Sun Mar 21 14:00:54 2004 From: perky at i18n.org (Hye-Shik Chang) Date: Mon, 22 Mar 2004 04:00:54 +0900 Subject: FreeBSD or OpenBSD for Python? In-Reply-To: References: Message-ID: <20040321190054.GA48617@i18n.org> On Fri, Mar 19, 2004 at 01:06:27AM +0000, Patrick Useldinger wrote: > Hi All, > I am looking for alternatives to my current Linux OS, and am currently > evaluating both FreeBSD and OpenBSD. > Has anyone got a strong point for or against one of these OSes, > specifically regarding Python? I am especially interested in > - the ease of compiling CPython > - the thread support (both for Python and in general) > - running Twisted. Maybe not many differences on these points. But I can introduce difference of features between FreeBSD and OpenBSD ports. (I'm slightly biased. sorry :) FreeBSD ports OpenBSD ports Versions 1.5.2, 2.0.1, 2.1.3, 1.5.2, 2.1.3, 2.2.3, 2.2.3, 2.3.3, 2.4 (040311) 2.3.3 Backported - email.Charset fix for cjkcodecs none patches (2.3) - intobject.c 2.105 allocation fix - weakrefobject.c 1.13.6.1 gc fix Unicode UCS4 UCS2 IPv6 enabled enabled Threads enabled enabled Shared lib. both (PIC shared, non-PIC static) non-PIC static only # of ports 197 50 starting with py- FreeBSD's port tweaked many options from the original. So if you prefer the vanilla python, you'd better to install from the source tarball. But you can use a port as it is if you do it in OpenBSD then. Regards, Hye-Shik From dmq at gain.com Wed Mar 3 13:33:36 2004 From: dmq at gain.com (David MacQuigg) Date: Wed, 03 Mar 2004 11:33:36 -0700 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> Message-ID: On Wed, 03 Mar 2004 10:32:34 GMT, m.bless at gmx.de (Martin Bless) wrote: >["Rainer Deyke" ] > >>but only because 'sys.stdout.write' is too long to type all >>the time, and never with more than one argument. If the only remaining issue is multiple arguments: >>> import sys >>> def wrt(*args): for arg in args: sys.stdout.write(arg) >>> wrt('abc','xyz\n','abc',1,2,3) abcxyz abc123 >>> -- Dave >Yes, I feel it's a pity that the standard write method of file objects >doesn't take multiple arguments. Would take some of the pressure. > >One thing I can do since Python-2.2 is to inherit from 'file' and add >for example a 'writem' (write many, write multiple) method. This does >work. > >Unfortunately it seems I can't add that 'writem' method to sys.stdout, >as the following shows. > >Anybody any ideas? > > >#!/usr/bin/env python ># -*- coding: iso-8859-1 -*- >"""Test file object.""" > >__author__ = "Martin Bless, 2004-03-03" > >if 1 and "this does work": > class MyFile(file): > > def writem(self,*args): > "Method to write many arguments." > for arg in args: > self.write(str(arg)) > > f2name = 'xxxtempfile' > f2 = MyFile(f2name,'w') > f2.writem(1,2,3,4) > f2.close() From moranar at daleclick.com Sat Mar 20 17:29:12 2004 From: moranar at daleclick.com (Adriano Varoli Piazza) Date: Sat, 20 Mar 2004 19:29:12 -0300 Subject: problem with a css cycler Message-ID: <200403201929.12518.moranar@daleclick.com> Hello all I am trying to build a css cycler in python, to change the css used in a website every X number of days, using a list of files: the first X days it'd show file1, then file2, then file3, then back to the first one. The code I came up with is the following: css = ["file1", "file2", "file3"] i = 0 max_i = 3 today = int(raw_input("today's date: ")) stored_day = 1 if 3 <= (today - stored_day): stored_day = today i += 1 if i > max_i: i = 0 print "Variable today is %s .\n" % today print "Variable stored_day is %s .\n" % stored_day print "Variable i is %s .\n" % i print "Variable css is now %s \n" % css[i] ---------- The problem with this is that it works only for the first X days. How do I make it "keep state" for the next iterations? Thanks -- Adriano Varoli Piazza The Inside Out: http://moranar.com.ar ICQ: 4410132 MSN: adrianomd at hotmail.com Claves gpg / pgp en hkp://subkeys.pgp.net From newsgroups at jhrothjr.com Sat Mar 13 12:09:34 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 13 Mar 2004 12:09:34 -0500 Subject: Static Typing in Python References: Message-ID: <1056g3f7jnt2jcc@news.supernews.com> "Premshree Pillai" wrote in message news:mailman.360.1079190339.19534.python-list at python.org... > --- srijit at yahoo.com wrote: > Hello, > > Try Traits > > (http://www.scipy.org/site_content/traits). > > > > Regards, > > Srijit > > 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#. John Roth > > -Premshree > > ===== > -Premshree > [http://www.qiksearch.com/] From skip at pobox.com Wed Mar 3 04:05:42 2004 From: skip at pobox.com (Skip Montanaro) Date: Wed, 3 Mar 2004 03:05:42 -0600 Subject: Which Python module for PostgreSQL? In-Reply-To: <30260531.0403022111.1a2928b7@posting.google.com> References: <30260531.0403022111.1a2928b7@posting.google.com> Message-ID: <16453.40934.279587.86101@montanaro.dyndns.org> simo> I'd like to know too - I had a play with psychog but couldn't get simo> it to connect, and couldn't find any documentation for it. If you're familiar with SQL programming in Python in general, it's pretty straightforward. It does adhere to v2 of the DB API, so PEP-249 is useful reading. Also, see the doc/examples directory. Here's a psycopg "hello world" (change the connect arg to suit your server): import psycopg conn = psycopg.connect('dbname=test user=test') curs = conn.cursor() curs.execute("""select 'hello world'""") print curs.fetchall() Skip From tim.one at comcast.net Sun Mar 28 20:47:17 2004 From: tim.one at comcast.net (Tim Peters) Date: Sun, 28 Mar 2004 20:47:17 -0500 Subject: Prothon Prototypes vs Python Classes In-Reply-To: Message-ID: [Mark Hahn, about immutability in Prothon] > ... > P.S. If this belongs in the Prothon list instead of Python, let us > know. Discussion of Prothon decisions is (or should be ) welcome on comp.lang.python. You're making some interesting choices that are hard to try in the CPython core anymore, and I'm keen to learn how they work out for you! From jepler at unpythonic.net Fri Mar 19 12:05:07 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Fri, 19 Mar 2004 11:05:07 -0600 Subject: SHA-based subclass for random module In-Reply-To: <5d83790c.0403190105.69ca83e7@posting.google.com> References: <7xptbgjpk4.fsf@ruckus.brouhaha.com> <5d83790c.0403190105.69ca83e7@posting.google.com> Message-ID: <20040319170506.GH1796@unpythonic.net> 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? A time-space tradeoff could be made between the number of precalculated hashes and the number of outputs from the MD5Random PRNG needed, too. A quick search on the internet indicates that about 2n bits are needed to find the initial state of an n-bit LSFR[1], so something like 40000 bits would be needed to find the internal state of MT, or 380 53-bit outputs. So let's say you can precalculate 2^30 MD5 inverses, the chance of any particular output being in the table is 2^-23. So you'd need something like 2^31 outputs from MD5Random(). I'm sure the analysis is also complicated by the fact that your 2n bits won't be consecutive outputs, but will be widely separated, but it's likely to remain possible. 2^53 is a big number, but it's well less than the 2^128 range for all MD5 signatures or the 2^64 signatures needed to find a collision. 2^30 storage and 2^31 calls to random is something many of us could at work, if not at home. IANAC, Jeff [1] http://www.ciphersbyritter.com/RES/COMBCORR.HTM "(The Berlekamp-Massey algorithm will recover the unknown state of a simple n-bit LFSR, and its feedback polynomial, with just 2n known bits.)" From nid_oizo at yahoo.com_remove_the_ Wed Mar 17 11:54:15 2004 From: nid_oizo at yahoo.com_remove_the_ (Nicolas Fleury) Date: Wed, 17 Mar 2004 11:54:15 -0500 Subject: Compare recursively objects In-Reply-To: References: Message-ID: Paul McGuire wrote: > In sum, I suspect you will get diverted to dealing with a whole bunch of > issues that are artifacts of using files, when what you really wanted to do > is compare some objects. Perhaps you could pickle to a string and compare > the strings? At least this avoids most of the file system complications. Sounds like a good idea. I am only in need of that functionality for unit testing, so I guess pickle to StringIO is a nice idea. Thx Nicolas From eppstein at ics.uci.edu Wed Mar 24 13:19:44 2004 From: eppstein at ics.uci.edu (David Eppstein) Date: Wed, 24 Mar 2004 10:19:44 -0800 Subject: PEP 318 References: Message-ID: In article , "Greg Ewing (using news.cis.dfn.de)" wrote: > Eyal Lotem wrote: > > You are not supposed to be looking for it, IMHO. > > Generators follow the Sequence protocol and are to be > > treated as sequences. Thus, you should simply make it > > clear in the > > function-name/conventions/interface-documentation that > > the function returns a sequence. Whether that > > sequence is implemented via a generator or not is an > > implementation detail. > > That may be true when you're *using* the generator, but > when looking at the implementation, it can be helpful > if you're warned ahead of time that you're wading into > generator code, to get you into the right frame of > mind. > > I had that experience just the other day -- started > reading a function, had some moments of wondering > "how does this work?", then thought "oh, I know, I > bet this is a generator"... skimmed through it, and > sure enough, there was a 'yield'. I think this can be alleviated by following a convention of using "Yields" as the first word of the docstring for all simple generators. E.g., http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/117119 Of course, that doesn't help for code not following the convention... -- David Eppstein http://www.ics.uci.edu/~eppstein/ Univ. of California, Irvine, School of Information & Computer Science From __peter__ at web.de Thu Mar 11 06:18:01 2004 From: __peter__ at web.de (Peter Otten) Date: Thu, 11 Mar 2004 12:18:01 +0100 Subject: Python style guidelines References: <3064b51d.0403101112.3449e987@posting.google.com> <405035a3$1@pfaff2.ethz.ch> Message-ID: Josef Meile wrote: >> Is there something missing you think should be there? There's no >> particular >> reason a PEP needs to be continually updated. In particular, notions of >> good Python style haven't changed a lot over the past ten years. >> >> Skip > I agree, those are good guidelines, but I don't agree with: > > - Don't compare boolean values to True or False using == (bool > types are new in Python 2.3): > > No: if greeting == True: > Yes: if greeting: > > What would happened if you do: > > >>> a='test' > >>> if a.find('foo'): > ... print "foo was found" > ... > foo was found > > I think you should never do a direct boolean comparison. Instead > one should use a more elaborate boolean expresion like: > > >>> a='test' > >>> if a.find('foo') >= 0: > ... print "foo was found" > ... > > > You will have problems specially if you come from languages where > values minor than zero are considered to be false. I think the > previous sintax is ambiguous. I think your find() example has nothing to do with if boolVal == True: versus if boolVal: though it might be a pitfall for people coming from languages with 1-based indices. If you discard the index it returns anyway, you could use the clearer if "foo" in a: instead. As to the original issue, I disagree with you and prefer the recommended style. I find it natural even for non-booleans: greeting = "Hi" if greeting: print greeting If you expect a boolean value and fear that you may erroneously encounter something else, the value == True test will not be sufficient anyway, because treating, say, "Hi" as False may be an error, too. It's if greeting == True: ... elif greeting == False: pass else: raise AssertionError, "greeting must be True or False" versus assert greeting in (True, False), "greeting must be True or False" if greeting: ... then, and again the last wins at in my eyes. Peter From __peter__ at web.de Thu Mar 4 14:45:41 2004 From: __peter__ at web.de (Peter Otten) Date: Thu, 04 Mar 2004 20:45:41 +0100 Subject: tkFileDialog.askopenfilename References: <8a5a6d82.0403041057.30d4c773@posting.google.com> Message-ID: Sonia Rovner wrote: > 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? Seems you are out of luck: "The procedures tk_getOpenFile and tk_getSaveFile pop up a dialog box for the user to select a file to open or save. The tk_getOpenFile command is usually associated with the Open command in the File menu. Its purpose is for the user to select an existing file only. If the user enters an non-existent file, the dialog box gives the user an error prompt and requires the user to give an alternative selection. If an application allows the user to create new files, it should do so by providing a separate New menu command. " Quoted from http://www.tcl.tk/man/tcl8.5/TkCmd/getOpenFile.htm Peter From ruse at webmail.co.za Fri Mar 5 06:29:00 2004 From: ruse at webmail.co.za (goose) Date: 5 Mar 2004 03:29:00 -0800 Subject: OFF-TOPIC:: Why Lisp is not my favorite programming language References: <165b3efa.0403030443.4d591f04@posting.google.com> <40460dd5$0$5916$7a628cd7@news.club-internet.fr> Message-ID: nish20 at netzero.net (Mike Nishizawa) wrote in message news:... please dont top-post. tia. > These posts are like big huge neon signs that say, "I'm IGNORANT." So is the post I am now responding to! At the risk of offending you, are you sure that your last 3 years as a programmer have properly equipped you to make informed decisions like the ones you've made below? > 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. Pick a fairly simple application ... lets say a tic-tac-toe game. Are you certain that the game implemented in java will run on more platforms than the same game implemented in ANSI C? C has many many weaknesses; platform dependence is /not/ one of them. goose, From ptmcg at austin.rr.com Thu Mar 11 11:56:35 2004 From: ptmcg at austin.rr.com (Paul McGuire) Date: 11 Mar 2004 08:56:35 -0800 Subject: [ANN] Updated releases of pyparsing - 1.1.1 Message-ID: <740c1dd4.0403110856.5f2796c3@posting.google.com> (Sorry if this is a duplicate, my newsreader is behaving strangely. I'm trying posting thru Google Groups as an alternative.) pyparsing 1.1.1 Released ---------------------- A quick minor update, to correct a critical bug introduced in 1.1 (thanks Seo Sanghyeon for spotting this!), and add backward compatible support for Python 2.2. Also includes a simple example of extracting data from a web page's HTML source. Download pyparsing at http://sourceforge.net/projects/pyparsing/. -- Paul McGuire pyparsing 1.1 Announcement ------------------------ With the accumulation of enhancements since 1.0, a minor change in the parse action interface, and the completion of validate() (one of my last outstanding "to-do" items), it seems appropriate to finally bump the minor rev level of pyparsing. pyparsing version 1.1 has been released for download from SourceForge, at http://sourceforge.net/projects/pyparsing/ New features in 1.1: - simplified parse actions - parse action functions now only need to return modified parse tokens, not a tuple of location and tokens - the example code has been updated to reflect the new style (Old style is deprecated, but still supported for backward compatibility.) - added validate() method to parse elements, to help identify improperly recursive grammar definitions - better str() output for parse elements, more similar to traditional BNF notation Fixed bugs: - infinite loop in oneOf if the input string contains a duplicate token - quoted strings do not span newlines (bug introduced in 1.0.6) - bad matching when specifying a results name on an Optional parse element Thanks to all who have tried out this module, and have forwarded their comments and remarks! -- Paul McGuire From adharma at cs.usfca.edu Thu Mar 25 19:56:30 2004 From: adharma at cs.usfca.edu (Amol Dharmadhikari) Date: Thu, 25 Mar 2004 16:56:30 -0800 Subject: How do I get the reference of window in DOM? In-Reply-To: References: Message-ID: <40637FBE.10307@cs.usfca.edu> Hi- Sam Kong wrote: > 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. If you want to close the window from the python code, ie.quit() should do it. > > Thanks in advance. > > Sam Amol From guillermo.fernandez at epfl.ch Wed Mar 10 10:08:51 2004 From: guillermo.fernandez at epfl.ch (Guillermo Fernandez Castellanos) Date: Wed, 10 Mar 2004 16:08:51 +0100 Subject: a desired python editor In-Reply-To: References: Message-ID: <404f2f83$1@epflnews.epfl.ch> > Or use the Emacs Code Browser ( http://ecb.sourceforge.net/ ). I had a look to Emacs Code Browser, but did not find any support of python. How did you do to support it? Thanks, G. From jcarlson at nospam.uci.edu Mon Mar 15 20:37:33 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Mon, 15 Mar 2004 17:37:33 -0800 Subject: Result of ``a is b'' In-Reply-To: <40200384.0403151632.35496ee6@posting.google.com> References: <40200384.0403151632.35496ee6@posting.google.com> Message-ID: > >>> a = (1,2) > >>> b = (1,2) > >>> a is b > False > >>> a = "12" > >>> b = "12" > >>> a is b > True Unless you care whether two names point to the same object, don't use 'is'. Instead compare for equality with '=='. That should work like you want it to: >>> a = (1,2) >>> b = (1,2) >>> a == b True >>> a = "12" >>> b = "12" >>> a == b True It will also handle the cases that Andrew points out. - Josiah From jcarlson at nospam.uci.edu Mon Mar 1 16:22:04 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Mon, 01 Mar 2004 13:22:04 -0800 Subject: Again: Please hear my plea: print without softspace In-Reply-To: References: <4041796c.2181078@news.muenster.de> <1rfj4etyhlcw6$.1evn1aiuzkinp$.dlg@40tude.net> <40448d4f.8911015@news.muenster.de> Message-ID: > I've wondered, though, whether there couldn't be a different > character instead of a ',' to alter the behavior of print. Maybe a > trailing '+' to indicate that what follows is to concatenate > directly. > > And yet I've been able to work around that little annoyance; it's not > that there is no way to format output the way you want. It seems that you are saying: print "hello ", "world" + #-> "hello world" That looks like "magic syntax", and should rightfully return a syntax error, because + already has a meaning for most all data types in Python. Changing the behavior of print when a syntax error is present, is the wrong thing to do. The right thing to do (if it were to happen at all) is to make fileobject.softspace "sticky" under some condition, perhaps after a call to fileobject.SetSoftSpace(False) (which doesn't currently exist). - Josiah From ericreed at mrreed.com Thu Mar 11 23:51:11 2004 From: ericreed at mrreed.com (Eric Reed) Date: Thu, 11 Mar 2004 23:51:11 -0500 (EST) Subject: Mouse wheel? Message-ID: <4799.68.124.23.9.1079067071.squirrel@webmail1.hrnoc.net> Hello, I'm very new to python coding. I have successfully read mouse clicks using the curses library, but I'd like to read wheel movements as well. a) Is this possible using curses? b) If not, what's the next best way to do this? Thanks, Eric. From dmq at gain.com Tue Mar 9 13:26:26 2004 From: dmq at gain.com (David MacQuigg) Date: Tue, 09 Mar 2004 11:26:26 -0700 Subject: Utterly OT:[Was Re: Need better string methods] References: <0d4k40987t6d70bahqil3geth640bufgoc@4ax.com> Message-ID: <7l2s405cc6kset45domrj00imd5l4maoqh@4ax.com> On Sat, 06 Mar 2004 23:59:28 GMT, rzed wrote: >David MacQuigg wrote in >news:0d4k40987t6d70bahqil3geth640bufgoc at 4ax.com: > >> [...] 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. > >[UTTERLY OFFTOPIC QUESTION]: >This "gradoo" of which you speak ... where did you learn the word? I >only ask, because I know (and use) "gradeau", pronounced like I >imagine "gradoo" would be pronounced, to mean miscellaneous cruft or >garbage ... but I've only ever heard it used by a small group of >people who, as far as I know, originated the use of the word in Green >Bay, Wisconsin, in the mid-1970's. Actually, I didn't know it was a real word until I saw the discussion of 'gradeau' in this thread. I've never seen it in print, but I heard it used by a construction supervisor in Gainesville, Florida in the mid-eighties. How's that for memory :>) It sound like a contraction of "gratuitous doo-doo", you know, the kind of doo-doo that George Bush the First is famous for. :>) Somehow it seems to uniquely fit the kind of "cruft and garbage" I'm seeing as a challenge for our string methods. -- Dave From dmq at gain.com Wed Mar 17 13:26:07 2004 From: dmq at gain.com (David MacQuigg) Date: Wed, 17 Mar 2004 11:26:07 -0700 Subject: Deprecating reload() ??? References: Message-ID: On Thu, 11 Mar 2004 15:10:59 -0500, "Ellinghaus, Lance" wrote: > >>Reload doesn't work the way most people think >>it does: if you've got any references to the old module, >>they stay around. They aren't replaced. > >>It was a good idea, but the implementation simply >>doesn't do what the idea promises. > >I agree that it does not really work as most people think it does, but how >would you perform the same task as reload() without the reload()? >>> pzfuncs >>> exec pzfuncs >>> p3 -2 --- Edit PZfuncs.py here --- >>> pzfuncs.seek(0) >>> exec pzfuncs >>> p3 -3 >>> The disadvantage compared to reload() is that you get direct references to *all* the new objects in your current namespace. With reload() you get only a reference to the reloaded module. With the proposed super_reload (at least the version I would like) you get no new references in your current namespace, just updates on the references that are already there. Hmm. Maybe we could reload(), then loop over the available names, and replace any that exist in the current namespace. -- Dave From skip at pobox.com Mon Mar 22 17:47:26 2004 From: skip at pobox.com (Skip Montanaro) Date: Mon, 22 Mar 2004 16:47:26 -0600 Subject: PEP 318 In-Reply-To: References: Message-ID: <16479.27902.268179.900252@montanaro.dyndns.org> AdSR> On other note, regarding the initial subject of this thread: Is AdSR> there going to be any voting poll about the syntax in foreseeable AdSR> future? My preferred style would be the "standard" one proposed in AdSR> the PEP. It will probably be a BDFL pronouncement. After all, that's why he's the BDFL. I have a modified version of PEP 318 in my mailbox I need to read, edit and check in. I'll try to get to it later today. Skip From scott.b.drummonds.nospam at intel.com Mon Mar 8 18:52:31 2004 From: scott.b.drummonds.nospam at intel.com (Scott Brady Drummonds) Date: Mon, 8 Mar 2004 15:52:31 -0800 Subject: Initializing Member Variables References: <20040308143642868-0500@news.shentel.net> Message-ID: "Francis Avila" wrote in message news:20040308143642868-0500 at news.shentel.net... > This may help: > http://starship.python.net/crew/mwh/hacks/objectthink.html Four great responses to my question, and this link was the most detailed. Thank you so much for helping straighten me out! Scott From sross at connectmail.carleton.ca Sat Mar 13 12:47:43 2004 From: sross at connectmail.carleton.ca (Sean Ross) Date: Sat, 13 Mar 2004 12:47:43 -0500 Subject: Static Typing in Python References: <01b650lrd53rbab3uis6dlqv38u52pk0e8@4ax.com> Message-ID: "Gon?alo Rodrigues" wrote in message news:01b650lrd53rbab3uis6dlqv38u52pk0e8 at 4ax.com... [snip] > I don't know a thing about perl, but by your description, strict > pragma is to solve a problem *in perl that does not exist in Python*. > If you use a variable before declaring (I'm using your terminology -- > it's not the most correct in the Python world, though) Python just > raises an exception, e.g. > > >>> #No var declared... exception raised: > >>> print var [snip] There's another class of problem: # trivial example based on http://io.kicks-ass.net/LocalVariables class A: def __init__(self): self.area = None def square(self, side): self.arae = side * side # spelling mistake creates new attribute def circle(self, radius): self.area = 3.14 * radius * radius a = A() a.circle(1) print a.area # 3.14 -> ok a.square(4) print a.area # 3.14 -> unintended Having never used pychecker, I can't say for certain, but I expect it will catch problems of this sort, and, as someone else suggested, unit tests should also nip this in the bud. Still, while I don't advocate it, I would not be adverse to *optionally* letting the language impose some form of distinction between variable creation and variable update - which is what "use strict" allows. Whether you use it or not is left up to your own tastes and/or discretion - you're not forced to declare your variables if you don't want to (although you will be forcing others to read it, if you do). But, if you do want to, you can, and the language will help enforce this choice. So, hypothetically, you could introduce an optional let statement: use strict # or, from __future__ import let, or nag, or whatever class A: def __init__(self): let self.area = None # uses 'let' for variable creation def square(self, side): self.arae = side * side # Exception, undeclared variable "arae" def circle(self, radius): self.area = 3.14 * radius * radius Now the language would catch this error in your code for you - no need to run outside programs (pychecker, your test suite) to find something so trivial. You'd have a whole lot of 'let's cluttering up your code - but, hey, you asked for it ... (of course, I didn't ask to have to read it - but that's beside the point - or, is that the point?) Still, there are issues. For instance: use strict class B: def __init__(self, **kwds): self.__dict__.update(kwds) # I "know" one key/value will be "b:'B'" def baz(self): print self.b # so, I'll use it here. # Not best practice, perhaps, but whatever ... b = B(b="B") b.baz() # Exception? So, here we're adding attributes dynamically, one of which is/will be self.b. But, self.b was not explicitly created (there's no "let self.b = 'B'"). Can I use self.b? I wouldn't expect so. I imagine the answer in this case would be to not use strict. There are probably other problems besides restricting dynamism and adding clutter, but I'm sure others will be along shortly to point those out. Sean From nelson at monkey.org Mon Mar 1 12:17:46 2004 From: nelson at monkey.org (Nelson Minar) Date: Mon, 01 Mar 2004 17:17:46 GMT Subject: Image width, height. References: Message-ID: Just writes: > PIL is such a Python package. It doesn't load the entire image if all > you want to know are the dimensions. Just goes to show you - if you want the right answer on the net, post a wrong answer and then everyone will correct you :-) Sorry for the misinformation. From tjreedy at udel.edu Fri Mar 12 09:52:11 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 12 Mar 2004 09:52:11 -0500 Subject: loop scope References: <405148CB.1030103@domain.invalid> Message-ID: wrote in message news:405148CB.1030103 at domain.invalid... > Terry Reedy wrote: > >> For list comps which cannot have break, >> it is an artifact which may disappear in 2.4. > > If I understand you, I don't think you did. The 'may' only applies to list comprehensions. The discussion last fall was whether the index names(s) within a list comprehension should be bound outside (after) the list comp. It is something of an accident of the current implementation that they are. The issue arose in the development of generator comprehensions, in which it was clear that the within-generator variables would *not* be bound outside of the produced generator. Bret Cannon's summary http://www.python.org/dev/summary/2003-10-16_2003-11-15.html#generator-expressions-list-comp-s-older-brother is this: --------------- A quick example is: (x for x in range(10) if x%2) returns an iterator that returns the odd numbers from 0 to 10. This make list comprehensions just syntactic sugar for passing a generator expression to list() (note how extra parentheses are not needed): list(x for x in range(10) is x%2) Having list comprehensions defined this way also takes away the dangling item variable for the 'for' loop. Using that dangling variable is now discouraged and will be made illegal at some point. ---------------- Terry J. Reedy From menceur at hotmail.com Wed Mar 17 11:01:07 2004 From: menceur at hotmail.com (M.M.) Date: 17 Mar 2004 08:01:07 -0800 Subject: asking for python community opinion about groovy Message-ID: <6b4509ac.0403170801.79aa64b7@posting.google.com> Hi all, The Java community is working on the adoption of Groovy as a JCP standard (http://www.jcp.org/en/jsr/detail?id=241). Groovy is a dynamic/agile language for Java (http://groovy.codehaus.org/). IMO, it will be better to support the Jython project. Because Jython exists, it's very useful and powerful. In fact, I think java community want to have its own "scripting" language because java community is not open-minded enough and will not accept to use something for the outside. I have post my opinion there (author Mouloud): http://www.theserverside.com/news/thread.tss?thread_id=24525 and the replies only reverse the argument : I'm too religious and not open-minded. I think I'm not alone when I say "I use Java, Python and Jython and I think Jython is very nice for Java scripting". Thanks, Mouloud. From michael at foord.net Thu Mar 4 04:24:03 2004 From: michael at foord.net (Fuzzyman) Date: 4 Mar 2004 01:24:03 -0800 Subject: Gadfly ???? Message-ID: <8089854e.0403040124.1c6bd929@posting.google.com> Gadfly looks like an interesting database system for python. I am working on a couple of projects that may benefit from using a database (on the other hand, these days - is there really aproblem with using dictionaries that are a couple of meg in size and searching through those ??). One of these projects is a customer feedback database that will be installed on our intranet - so I was looking for a pure python solution..... I thought Gadfly was a pure python implementation - however when I download the package it looks like it's optimised to work with kjBuckets and kwParsing. *However* - there isn't a pre-built version for windows (my test platform ;-) for python 2.3 - and there are scant and confusing references to it on the web...... Is kwBuckets still being 'developed', is gadfly worthwhile without it, has anyone else compiled it for python 2.3 ?? Regards, Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html From rganesan at myrealbox.com Tue Mar 2 23:50:21 2004 From: rganesan at myrealbox.com (Ganesan R) Date: Wed, 03 Mar 2004 10:20:21 +0530 Subject: Which Python module for PostgreSQL? References: Message-ID: >>>>> "W" == W Borgert writes: > Hi, > I'm not new to Python, but new to databases and PostgreSQL. > I like to write a PostgreSQL client application (not code > running inside of the RDBMS), and Debian has four modules: > python2.3-pgsql - A Python DB-API 2.0 interface to PostgreSQL v7.x > python2.3-popy - module providing access to PostgreSQL from Python2.3 > python2.3-psycopg - Python 2.3 module for PostgreSQL > python2.3-pygresql - PostgreSQL module for Python I prefer the first one - it's BSD licensed, actively maintained and supported. It's also very compatible with the python SQLite binding which I use regularly. Ganesan -- Ganesan R From claird at lairds.com Thu Mar 11 10:35:11 2004 From: claird at lairds.com (Cameron Laird) Date: Thu, 11 Mar 2004 15:35:11 -0000 Subject: Extending Python Syntax with @ References: <2f9050pq22u53o7aqo9i8ebqj11vo9kilg@4ax.com> <1050odofl644aac@corp.supernews.com> <1050uf4afdkrje5@news.supernews.com> Message-ID: <10511pf66mv7j4d@corp.supernews.com> In article <1050uf4afdkrje5 at news.supernews.com>, John Roth wrote: . . . >I tend to agree, but for slightly different reasons. Lambdas >are a means of in-lining a function definition. However, they >are so restricted that we constantly get suggestions for >"improving" them by adding more syntax. > >Given the restrictions, I see the natural growth path as leading >to a callable instance or a bound method, not a module level >function. Module level functions are a distraction; usually you >want to interface with an object, and module level functions make >that very difficult. > >The other reason to avoid lambdas is the DRY principle: >Don't Repeat Yourself. Most uses of lambdas I've seen >lead to duplication in anything larger than a toy program. > >What I'd really like is for all of the instructional material >with lambdas to just magically vanish and be replaced by >instructional material that does whatever it is in proper >object oriented fashion, using bound methods for callbacks. >Relegate lambda to a sidebar. . . . I like what you've written, and the way you've written it, better than what I had. It's absolutely more Pythonic to emphasize clarity, expressiveness, AND instance association as better-localized binding. That sounds like a project: sanitization of introductory materials for misleading lambdas. -- Cameron Laird Business: http://www.Phaseit.net From skip at pobox.com Tue Mar 30 23:08:29 2004 From: skip at pobox.com (Skip Montanaro) Date: Tue, 30 Mar 2004 22:08:29 -0600 Subject: xmlrpc, httplib and SSL In-Reply-To: <002e01c41551$08147830$3501a8c0@rogersqyvr14d3> References: <114d01c41448$4433c1e0$0000fea9@dell8200> <000d01c4144b$67dbd760$3501a8c0@rogersqyvr14d3> <16487.23850.656173.195877@montanaro.dyndns.org> <001701c41530$747c8e70$3501a8c0@rogersqyvr14d3> <16487.36554.899992.486386@montanaro.dyndns.org> <002e01c41551$08147830$3501a8c0@rogersqyvr14d3> Message-ID: <16490.17469.616646.301341@montanaro.dyndns.org> (away from my mail...) >> Every language whose objects can form cycles has to deal with the >> issue of reclaiming those cycles in the presence of destructors. Roger> I am not denying that is an issue. The problem in this case is Roger> that because there *could* be cycles, file/socket handles have to Roger> be manually closed. The currently library goes out of its way to Roger> do so, together with a makefile method (a kind of dup) to deal Roger> with ownership issues. Much of that code was written before HTTP/1.1 persistence was available, so it's not all that odd to find close() calls after each request. Perhaps a little analysis would convince people that the chance for cycles is either low enough or nonexistent so that explicity close() calls could be dispensed with. If cycles are indeed possible (or likely), perhaps weak references could be used to mitigate the problem. (I suspect much of that code was also written before the presence of weak refs in the library.) Skip From kaz at ashi.footprints.net Wed Mar 3 15:01:25 2004 From: kaz at ashi.footprints.net (Kaz Kylheku) Date: 3 Mar 2004 12:01:25 -0800 Subject: OFF-TOPIC:: Why Lisp is not my favorite programming language References: <165b3efa.0403030443.4d591f04@posting.google.com> Message-ID: nobody_u_should_no at yahoo.com (nobody) wrote in message news:<165b3efa.0403030443.4d591f04 at posting.google.com>... > 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. But nobody is more fervent than lunatics whose membership applications were *rejected* by imaginary little fanatic cliques. Their cause, in fact, usually has just one follower. From gandreas at no.reply Mon Mar 29 10:16:29 2004 From: gandreas at no.reply (Glenn Andreas) Date: Mon, 29 Mar 2004 09:16:29 -0600 Subject: A 'Python like' language References: <40645d8f$0$10775$afc38c87@news.easynet.co.uk> <1068up4kn49778@news.supernews.com> <4064C129.1B8C937C@alcyone.com> Message-ID: In article , "Mark Hahn" wrote: > > Not quite the same, as with Prothon it looks like it always relates to > > the self object, whereas in a `with' clause you can make it relates to > > any object you wish. > > Just to confuse the issue, I'd like to point out that in Prothon, the > leading dot does always relate to the self object, but the 'with' clause > sets the self object to any object you want at any time. So both statements > above are true at once. The concept of changing the self object on the fly > is somewhat bizzare, much like changing the protoype on the fly, which you > can also do. > Out of curiousity (and on a somewhat related topic), how do you handle "class variables" - i.e., variables that exist in the "super" object, and should be accessable by all "sub objects"? Accessing them is straightforward - for "foo.bar" if foo doesn't have bar, but it inherits from an object that does have bar, you get that, but what about foo.bar on the LHS of an expression? So does "foo.bar = 5" add a "bar" slot to "foo" or does it change bar in the parent object? Self had a full blown system for variable access & setting, combined with its multiple inheritance for some pretty interesting abilities (essentially, all "getters" and "setters" were functions, so you could have something be a constant by only providing a getter, etc...) NewtonScript actually had two different assignment operators "=" and ":=" which determined how it behaved (though it got complex because it sort of had multiple inheritance - everything inherited from _two_ parents, the "real" parent and a "_proto", which seems strange, but it made sense in the runtime of the Newton, but that's a bit off topic). From newsgroups at jhrothjr.com Sun Mar 14 15:06:16 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Sun, 14 Mar 2004 15:06:16 -0500 Subject: converting %20 to spaces References: Message-ID: <1059esblsa2u59@news.supernews.com> wrote in message news:f046efac.0403141156.3135c1d9 at posting.google.com... > Hi > I am storing the attachments in files on the server.User can see all > the attachments & view any of them. > My application shows the attachment correctly for file which have no > spaces in their name. > But it doesnt works for file names with spaces.As the spaces are > converted to %20.It gives an error:No such file or directory. > How do I avoid converting of spaces to %20?? > Also one more problem creeped up. > I am using method for uploading attachmnets..Then I > create a file on the server & copy the contents to that file.When I > display the attachments the text files & html files are displayed > correctly but the image files are distorted. > Do I need to escape sequences or do something else? > Please help Look at the quote() and unquote() functions in the urllib module. John Roth From ketulp_baroda at yahoo.com Mon Mar 8 04:36:46 2004 From: ketulp_baroda at yahoo.com (ketulp_baroda at yahoo.com) Date: 8 Mar 2004 01:36:46 -0800 Subject: attachment References: <4049ad99$0$564$e4fe514c@news.xs4all.nl> <404b2680$0$564$e4fe514c@news.xs4all.nl> Message-ID: Irmen de Jong wrote in message news:<404b2680$0$564$e4fe514c at 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 Hi Sorry for the little information I provided. In the application the user can't edit or remove his or any other user's attachment.What he can do is only add new attachments or view the attachments present.I already have a databse where I have stored the information about the users present.So it will be no problem to store info about attachment.Is it a good idea to store attachments in database?? But by hearing the problems I have to face with files like you said I think database is a godd option From miki.tebeka at zoran.com Tue Mar 16 04:18:13 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Tue, 16 Mar 2004 11:18:13 +0200 Subject: new to programming: suggestion In-Reply-To: <3d5e65ea.0403152115.3df7e8c1@posting.google.com> References: <3d5e65ea.0403152115.3df7e8c1@posting.google.com> Message-ID: <4056C655.4000409@zoran.com> Hello Pus, > i'm new in programming; i'd like to find a good programming book, full > of examples guiding me step to step in the marvellous world of > programming. > Is there anybody who can suggest me where to find what i'm searching? http://www.ibiblio.org/obp/thinkCSpy/ http://www.python.org/topics/learn/ HTH. Miki From dmq at gain.com Mon Mar 22 15:18:31 2004 From: dmq at gain.com (David MacQuigg) Date: Mon, 22 Mar 2004 13:18:31 -0700 Subject: SHA-based subclass for random module References: Message-ID: <3ghu50hj5bnq79ro73gk6fbr2llevjvlk0@4ax.com> On Mon, 22 Mar 2004 13:41:46 -0500, "Tim Peters" wrote: >[David MacQuigg] >> ... >> I'm still curious as to the answer to my very simple and basic >> question: > >It is basic, but there's nothing simple about it. > >> Are there any examples that show a *non-subjective* difference in a >> physically meaningful result between one PRNG and another? > >Yes, but different RNGs have different weaknesses, and whether the >weaknesses of a specific RNG *matter* to you depend on detailed analysis of >the specific app you have in mind. > >The primary weakness of linear congruential generators (still the most >common kind) is dramatically illustrated all over the web; e.g., look at the >3D plot at: > > http://www.unf.edu/ccec/cis/CIShtml/RANDUinfo.html > >If you need to generate "random" points in 3D space, does it matter that the >particular LCG plotted there systematically generates points that fall on >one of 15 planes, no matter how many points you generate? There's no answer >to that short of analyzing the specifics of what you're trying to accomplish >by generating those points. For example, if your app relies on the triples >generated being approximately equally distributed throughout a 3D cube, that >particular LCG is an obvious disaster for that particular application. But >if your app only cares that the projection of the points onto the x axis is >approximately equally distributed, probably no problem, despite that it's >obvious "by eyeball" that there's nothing even remotely "random" about their >distribution in 3D space. > >You're not going to get an easy answer. Well, here's one: the Mersenne >Twister in Python 2.3 is probably the best and most widely tested fast PRNG >in existence now, and has provably good equidistribution properties in high >dimensions (a plot like the one above would have no visible patterns if the >Twister had been used instead). This is the first good answer I have heard, and it has changed my thinking on this question. I understand now that the problem is not just something that might be found in the tenth decimal place. The clustering of random points into very thin planes could radically affect a simulation depending on the distances between those points. The problem I am working on (statistical simulation of electronic circuits) involves a large number of 1D distributions, but with carefully controlled correlations between these distributions. We are probably just lucky that the PRNG we are using has not caused a noticable problem, but seeing just one clear example like the above has made me decide to be much more cautious in selecting a PRNG. Thanks for the enlightenment. -- Dave From Spam at ivonet.nl Sat Mar 13 18:26:14 2004 From: Spam at ivonet.nl (Ivo) Date: Sun, 14 Mar 2004 00:26:14 +0100 Subject: Spyce Users out there? Message-ID: <40539882$0$15631$3a628fcd@reader1.nntp.hccnet.nl> I use a lot of Spice code to tailor my site. Are there others? and what is your experience? Is there a better alternative and why??? -- Cheerz, Ivo. http://IvoNet.nl ============================ From rogerb at rogerbinns.com Wed Mar 10 20:08:39 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Wed, 10 Mar 2004 17:08:39 -0800 Subject: Extending Python Syntax with @ References: Message-ID: David MacQuigg wrote: > @x @y @z -- short for instance variables in a method definition The explicit self in front of accesses is what bugged me the most when I first started with Python. (I liked the indentation. All my C/C++/Java code is appropriately indented anyway, so the Python rules didn't change my indentation style, and only removed now superfluous punctuation). But now when I go back to C++ code, the lack of self/this bugs me. I often expect to not compile since I am not to sure where it is resolving a name to. (Try writing MFC code on PocketPC sometime - the layers of abstractions and inheritance get to be fun). Of course I could use this->x in the code, but that is non-standard and not something I would want to inflict on someone who has to maintain the code. explicit is better than implicit! Roger From marco at bubke.de Sun Mar 21 11:53:11 2004 From: marco at bubke.de (Marco Bubke) Date: Sun, 21 Mar 2004 17:53:11 +0100 Subject: PEP 318 Message-ID: Hi I have read some mail on the dev mailing list about PEP 318 and find the new Syntax really ugly. def foo[staticmethode](x, y): pass I call this foo(1, 2), this isn't really intuitive to me! Also I don't like the brackets. def foo(x, y)[staticmethode]: pass are better but still I used to see [] as list or access operator and the don't? The original Syntax looks much cleaner to me. def foo(x, y) as staticmethode: pass Define foo with arguments x and y as staticmethode. Is Python now C++? Mabe I miss something why this syntax is wrong. regards Marco From qp at al.net Sun Mar 14 23:14:31 2004 From: qp at al.net (Qp) Date: Sun, 14 Mar 2004 23:14:31 -0500 Subject: Seeking advice on GUI code architecture References: Message-ID: OK, I've heard briefly about MVC. I'll take a look and see if I can find any examples of that, particularily in network client development. Thanks, Qp "Ben Finney" wrote in message news:slrnc5a9on.4ib.bignose-hates-spam at iris.polar.local... > 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 google0 at lazytwinacres.net Sun Mar 14 14:43:15 2004 From: google0 at lazytwinacres.net (Dang Griffith) Date: Sun, 14 Mar 2004 19:43:15 GMT Subject: Static Typing in Python References: <67efcd4ccaf87ddf3c640aad5517017a@news.teranews.com> Message-ID: <7de2e74a623ae9f3ff3fe9ae4e1ec2b4@news.teranews.com> On Sat, 13 Mar 2004 14:59:42 +0000 (GMT), Premshree Pillai wrote: > --- Dang Griffith wrote: >> On Sat, 13 Mar 2004 07:07:50 +0000 (GMT), Premshree >> Pillai >> wrote: >> >> > --- Jacek Generowicz >> >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, but you can use pychecker to get similar >> results. >> >> >Don't you think forced variable declaration is an >> >important requirement in a language? >> >> Not really. Forced variable initialization is >> what's important. >> Unlike C, et al, and Perl, variables don't have a >> default >> initial value. If you try reference a variable that >> hasn't been >> initialized ("bound to a value", in python lingo), >> python raises a >> NameError exception. >> >> --dang >> p.s. >> I know technically Perl initializes to 'undef', but >> it's magically >> treated as 0 or an empty string, depending on >> context, so the >> effect is much the same. >> -- >> http://mail.python.org/mailman/listinfo/python-list > >Not forcing variable initialization does have its >problems. Here's what I mean: http://www.livejournal.com/users/premshree/10624.html?thread=53376#t53376 Yes, I agree. That is one reason I like Python. It has forced variable *initialization*. You cannot use a variable that has not been initialized. In fact, the act of initializing a variable is what makes the variable exist. I do not think forced *declaration* is important, except perhaps in C/++/#/Java, Pascal, Ada, etc. I see the typo in the pseudo-code example. PyChecker will catch that. I typed in your code, converted it to Python, and ran pychecker on it: Warnings... bluesmoon.py:12: Local variable (my_varaible) not used --dang From mwilson at the-wire.com Fri Mar 26 21:54:02 2004 From: mwilson at the-wire.com (Mel Wilson) Date: Fri, 26 Mar 2004 21:54:02 -0500 Subject: A 'Python like' language References: <40645d8f$0$10775$afc38c87@news.easynet.co.uk> <1068up4kn49778@news.supernews.com> <4064C129.1B8C937C@alcyone.com> Message-ID: In article <4064C129.1B8C937C at alcyone.com>, Erik Max Francis wrote: >Valentino Volonghi aka Dialtone wrote: > >> Anyway GvR just posted on the python-dev saying this: >> >> == >> No, I want to reserve the leading dot for attribute assignment to a >> special object specified by a 'with' statement, e.g. >> >> with self: >> .foo = [1, 2, 3] >> .bar(4, .foo) >> == >> >> So another feature of this prothon (and a major one) is going to be a >> python one >> too. > >Not quite the same, as with Prothon it looks like it always relates to >the self object, whereas in a `with' clause you can make it relates to >any object you wish. Prothon seems to have a `with' clause, which overrides the default thus: .name # refers to the name attribute of the self object ... with other: .name # refers to other.name though I won't know for sure until I've found a copy of MSVCR70.DLL Regards. Mel. -----= 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 kosh at aesaeion.com Wed Mar 10 16:25:29 2004 From: kosh at aesaeion.com (kosh) Date: Wed, 10 Mar 2004 14:25:29 -0700 Subject: Iterating over tuple entries in a list In-Reply-To: <20040310210922.GA477@tyrone.slothrop.xx> References: <20040310210922.GA477@tyrone.slothrop.xx> Message-ID: <200403101425.29270.kosh@aesaeion.com> On Wednesday 10 March 2004 02:09 pm, Dirk Zimmermann wrote: > Hi, > > I have the following problem: > > I have a list with tuples in it, looking like this: > > myList = [(1.1, "file1"), (1.2,"file2), (1.9, "file3")] > > (I want to store a number calculated from a file together with the > file.) Than I want to use functions expecting a list of floats. Is there > an easy way to slice myList? I know, that: floats = [number for number,filename in myList] From dmq at gain.com Thu Mar 11 03:42:00 2004 From: dmq at gain.com (David MacQuigg) Date: Thu, 11 Mar 2004 01:42:00 -0700 Subject: Extending Python Syntax with @ References: <104vg6f87k7gb19@corp.supernews.com> <104vtblamboehab@corp.supernews.com> Message-ID: <2f9050pq22u53o7aqo9i8ebqj11vo9kilg@4ax.com> On Thu, 11 Mar 2004 05:13:25 -0000, claird at lairds.com (Cameron Laird) wrote: >Pierre Rouleau wrote: . >>I was trained as an EE myself and started programming in assembler on >>microprocessors, then in C , then in C++, reading, reading, reading,.... >>Just the mere fact that you are talking about lambda shows that you know >>what it is, as I do now and as people learning Python will know when >>they use it. They'll learn, that why they are technical professionals, no? I agree. Lamdas are no big deal once you get past some obfuscation and understand they perform a very simple function. Of course, both of us could be missing something important. There is a lot of deep theory behind the lambda calculus. While drawing a tentative conclusion, we have to always keep an open mind to something new. On Thu, 11 Mar 2004 05:13:25 -0000, claird at lairds.com (Cameron Laird) wrote: > For more on what lambda means to me, and others, see > > or > > or > or ... This is an impressive body of knowledge, but unless I see how it is going to help me write some code, I won't have time to study it. My understanding of lambda functions is simply that they are a way to squeeze functions into a tight space: list_of_funcs = [(lambda x: 2**x), (lambda x: 3**x), (lambda x: 4**x)] If you are not concerned about space, simply use normal defs: def f2(x): return 2**x def f3(x): return 3**x def f4(x): return 4**x list_of_funcs = [f2, f3, f4] Is there any other reason in Python to use lambdas? -- Dave From http Sun Mar 14 01:42:00 2004 From: http (Paul Rubin) Date: 13 Mar 2004 22:42:00 -0800 Subject: SHA-based subclass for Random module References: <7xhdwsjpib.fsf@ruckus.brouhaha.com> Message-ID: <7x7jxo0w1z.fsf@ruckus.brouhaha.com> David Lees writes: > NameError: global name 'newrand' is not defined > > Is this a problem with my Python installation or something defining > newrand that you forgot to include? Oops, editing error on my part. Sorry. I originally called the class "newrand" and then changed it to sharandom, but missed updating that spot and it still worked when I tested it because the old newrand class was still in the interpreter :(. Anyway, it's fixed now, you can re-download, or just edit newrand to say sharandom. Thanks. From __peter__ at web.de Tue Mar 9 18:21:20 2004 From: __peter__ at web.de (Peter Otten) Date: Wed, 10 Mar 2004 00:21:20 +0100 Subject: Is this a bug? References: <4cc8f8db.0403091415.e606e29@posting.google.com> Message-ID: Carolina Feher wrote: >>>> def f(a): > ... return 5 > ... >>>> class A(list): > ... g = f > ... def __new__(cls): > ... c = list.__new__(cls, [1, 2]) > ... c.g() > ... return c > ... >>>> a = A() >>>> a > [] > > Why is an empty list returned? Because for lists the __init__ method does the initialization: >>> class A(list): ... def __init__(self): ... list.__init__(self, [1,2]) ... >>> A() [1, 2] whereas for tuples that woould be too late because they're immutable. Therefore: >>> class B(tuple): ... def __new__(cls): ... return tuple.__new__(cls, [1,2]) ... >>> B() (1, 2) >>> Peter From aahz at pythoncraft.com Sun Mar 28 21:49:07 2004 From: aahz at pythoncraft.com (Aahz) Date: 28 Mar 2004 21:49:07 -0500 Subject: A 'Python like' language References: <40645d8f$0$10775$afc38c87@news.easynet.co.uk> <1f9c60dtvj2alu8lk522l29nerqrv0trv3@4ax.com> Message-ID: In article <1f9c60dtvj2alu8lk522l29nerqrv0trv3 at 4ax.com>, Stephen Horne wrote: > >I missed that. There's good precedent - it's the Pascal 'with' block, >but better (the leading dot tells you that you're dealing with a >'with' item rather than normal scoping rules). But - well - just >recently, people keep telling me that indented blocks are purely about >control flow. I keep disagreeing, but no-one has bothered agreeing >with me so I was feeling rather lonely and miserable in this crusade >:-( Huh? Where were they telling you that? (I don't read all of c.l.py by a long shot, 'specially when I've just gotten back from PyCon.) From my POV, indented blocks are about program structure and namespaces. Saying that ``class`` refers purely to control flow definitely misses the point. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "usenet imitates usenet" --Darkhawk From ville at spammers.com Sat Mar 13 04:08:01 2004 From: ville at spammers.com (Ville Vainio) Date: 13 Mar 2004 11:08:01 +0200 Subject: OT(Slightly): Thanks to Python. References: <104emss6ca09l45@news.supernews.com> Message-ID: >>>>> "Josiah" == Josiah Carlson writes: Josiah> Certainly the above can be streamlined with a wrapper function: Josiah> def foo1_2(a,b): Josiah> print "type 1 & 2" Josiah> def foo3_4(a,b): Josiah> print "type 3 & 4" Josiah> def foo(a,b): Josiah> dct = {(type1, type2):foo1_2, Josiah> (type3, type4):foo3_4} Josiah> return dct[type(a), type(b)](a,b) Or in Python 2.4 (strict_type is hypothetical for now): def foo(a,b) [typecheck(type1, type2): pass def foo(a,b) [typecheck(type3, type4): pass which is even nicer :-). -- Ville Vainio http://tinyurl.com/2prnb From david at rebirthing.co.nz Thu Mar 4 03:53:24 2004 From: david at rebirthing.co.nz (David McNab) Date: Thu, 04 Mar 2004 21:53:24 +1300 Subject: ready to use python, need help with GUI decision In-Reply-To: <20040303181544.GB74292@dogma.freebsd-uk.eu.org> References: <20040303181544.GB74292@dogma.freebsd-uk.eu.org> Message-ID: <4046EE84.9080700@rebirthing.co.nz> My personal favourite is Tkinter, with the 'steroids' that go by the name of PMW. Good Tkinter reference: http://www.pythonware.com/library/tkinter/introduction/index.htm PMW Homepage: http://pmw.sf.net Advantages: * Easily deployed on Windows, Linux and *BSD (other GUIs often drag the user into a sometimes difficult compilation of 3rd party libraries, whereas Tkinter comes standard with most distros, and PMW is a snack * An extensible OO interface that quickly becomes very natural * Reasonable footprint * Reasonable startup time * 100% portability - you quickly get the 'feel' for writing os-independent apps * Fast learning * Easy to make readable/intuitive code * Well supported by Windwos EXE builders like Py2EXE and McMillan Disadvantages: * Slightly less advanced features - for instance, you sometimes have to cook up custom widgets Cheers David Jonathon McKitrick wrote: > Hi all, > > I am totally hooked on what I have learned about python. I am going to use > it to develop a simple data entry app I need for some financial record > keeping. > > I understand tkinter is official and simple to use, but many who use > wxPython swear by it, and it is gaining ground. > > I would like to run on any platform, but that's not critical. What I want > to do is support an app that will grow over time, and should look clean. I > don't want to spend lots of time maintaining GUI code rather than app logic. > > Can anyone offer any advice? > > jm -- Kind regards David -- leave this line intact so your email gets through my junk mail filter From jgrahn-nntq at algonet.se Sat Mar 6 04:51:46 2004 From: jgrahn-nntq at algonet.se (Jorgen Grahn) Date: Sat, 6 Mar 2004 09:51:46 +0000 (UTC) Subject: Executing a system call References: Message-ID: On Sat, 6 Mar 2004 00:06:14 +0530 (IST), Jagarlamudi Jagadeesh wrote: > > > Hi All, > > There are so many ways to execute a system call like, > getstatusoutput() > > os.system() > > fork() > os.execvp() > > using popen And also os.spawnv*(), which unlike fork/exec work on some non-Unixes. > Of all these, which is the best to use ( interms of speed and > resources) ? It depends ;-) Some of these go through the shell (which may give you features you want, or features you *don't* want). I'd say the resources wasted on executing a shell are almost always negligable; you should probably make a decision based on functionality instead. /Jorgen -- // Jorgen Grahn Would You Let One Marry Your Sister?'' From user_77 at hotmail.com Mon Mar 1 10:14:06 2004 From: user_77 at hotmail.com (Nobody) Date: Mon, 01 Mar 2004 15:14:06 GMT Subject: Why Python? References: Message-ID: <2rI0c.175350$Po1.95713@twister.tampabay.rr.com> "Todd7" wrote in message news:Xns949ECD7289AD6Todd7Nospampleasecom at 68.12.19.6... > I am looking at learning Python, but I would like to know what its > strengths and weaknesses are before I invest much time in learning it. My > first thought is what is it good for programming, however I expect an > answer from the python newsgroup to be something like "everything". So > maybe a better question is what type of programming projects is Python a > bad choice? > > What makes it better or worse than languages like perl, php, delphi, or > c++? > > Thanks for your opinions. > > Todd. > Why NOT Python? I'm a noob at it, but so far I love it. It's easy to put together a program pretty quickly using it. Also, even when I have to code something up in, say C++, I can still put together a prototype in Python first to get a better understanding of the problem space. (Ya have to "...throw one away..." anyway, so why not use Python first?) I know this doesn't _directly_ answer your question, but it does in a way. WR From No.Spam.mc at No.Spam.mclaveau.No.Spam.com Mon Mar 29 14:10:46 2004 From: No.Spam.mc at No.Spam.mclaveau.No.Spam.com (Michel Claveau/Hamster) Date: Mon, 29 Mar 2004 21:10:46 +0200 Subject: Britney Spears nude References: Message-ID: LOL (MDR) From drconrad at metaplay.com.au Sun Mar 7 22:52:45 2004 From: drconrad at metaplay.com.au (Simon Wittber) Date: Mon, 8 Mar 2004 11:52:45 +0800 Subject: Working around a lack of 'goto' in python In-Reply-To: Message-ID: <000001c404c0$d0ec3730$0000fea9@simonxp> This has to be the worst idea I've seen in a long time. Breaking out of multiple nested loops of various depths is actually very simple. Raise an exception, and catch it outside the loop. Roger wrote: ----------------------- What you have is what many other languages allow with integers after break or continue statements. For example you can do 'break 2' or 'continue 3' to break or continue out of the respective number of enclosing for loops. (Some other languages allow you to label the loops and then you can name the level in the break/continue statements which is kind of what you end up doing in C) Sadly Python doesn't allow numbers. You can write it yourself using variables to track the looping or throwing exceptions as other posters have shown, but it can get REALLY complicated if you want to break/continue out of differing numbers of layers at different points. It is also quite easy to have bugs due to oversights (been there, done that :-) I don't like the rewriting as it greatly complicates the code, and you are having to write something different than what you mean in your head. Maybe someone wants to take this on as a PEP? ----------------------- From info at outer-court.com Mon Mar 15 05:30:57 2004 From: info at outer-court.com (Philipp Lenssen) Date: 15 Mar 2004 10:30:57 GMT Subject: where can I find Paris Hilton video? References: Message-ID: montezum wrote: > where can I find Paris Hilton video? Where you find everything. In Google. -- Google Blogoscoped http://blog.outer-court.com From bad_addy at no_domain.com Wed Mar 17 17:04:32 2004 From: bad_addy at no_domain.com (Tina) Date: Wed, 17 Mar 2004 22:04:32 GMT Subject: Newbie Python (Game) Programming Question References: Message-ID: Thanks to both of you. I'm very much a Python newbie and the ability to make things callable wasn't addressed too well/at all in either of the Python books I'm learning from. 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. From mike at nospam.com Thu Mar 4 16:48:39 2004 From: mike at nospam.com (Mike Rovner) Date: Thu, 4 Mar 2004 13:48:39 -0800 Subject: Debugging Python extensions References: Message-ID: Gus Tabares wrote: > So far I have compiled a debug version of the 'pythoncore' project > that is located in the Python sources. This has produced the > python23_d.dll which I will use to link with my pyd. You don't have to. > I have a few questions after this step: > > 1. Do I need to compile my own version of Python2.3 to debug my pyd? no > 2. Do I have to name my debug pyd as filename_d.pyd? no > 3. Does the init function need to be named initfilename_d? no > I understand that .NET 2003 is not "supported" (I believe only VS6 is) no. support code is already in cvs > but I would think using .NET 2003 would not be much different aside > from converting the projects to the new format. It's straightforward: 1. use stock python.exe 2. compile (debug version) of your extension module as DLL project and name output mymodule.dll (make sure you use initmymodule() inside. 3. in project properties set debugging /command > i.e. c:\python23\python.exe debugging /command arguments > also usefull: debugging /working directory > Make sure you have mymodule.dll in the same place as test script and you are all set. Put breakpoints, hit run, do as usual in VS.NET. HTH, Mike From myang at clarku.edu Sat Mar 27 18:43:24 2004 From: myang at clarku.edu (myang) Date: Sat, 27 Mar 2004 18:43:24 -0500 Subject: initialize a class Message-ID: Hi, I am trying to construct a 'point' instance with two different methods (see the following codes). Why the second one can't work? It's strange, since 'self' refers to the newly created object, and the '=' assign a initialized instance to it. >>> class Point: ... x = 0.0 ... y = 0.0 ... >>> def initializePoint(a,b): ... p = Point() ... p.x = a ... p.y = b ... return p ... >>> class Ppoint(Point): ... def __init__(self,a,b): ... self = initializePoint(a,b) ... >>> p = initializePoint(1.0,2.0) >>> p.x 1.0 >>> p.y 2.0 >>> p = Ppoint(1.0,2.0) >>> p.x 0.0 >>> p.y 0.0 Acutally, what I want to do is like the code above: I have a huge class in a module, and a function to initialize instances of this class. But I want the instance of the class to be initialized when it's created. How can I fulfill such a task? Thanks! Regards, Yang From oussoren at cistron.nl Fri Mar 26 02:01:40 2004 From: oussoren at cistron.nl (Ronald Oussoren) Date: Fri, 26 Mar 2004 08:01:40 +0100 Subject: Make 'def' and 'class' usable within expressions In-Reply-To: <40634B15.1090006@zope.com> References: <1065uf99la6if29@news.supernews.com> <40634B15.1090006@zope.com> Message-ID: <6E57243C-7EF3-11D8-8D1D-0003931CFE24@cistron.nl> On 25-mrt-04, at 22:11, Shane Hathaway wrote: > Glenn Andreas wrote: >> 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" >> } > > I just thought of a better way to write this. > > myHandlers = {} > myHandlers["click"] = def(x,y): > print "click at x,y" > myHandlers["enter"] = def(): > print "mouse entered" > myHandlers["exit"] = def(): > print "mouse exited" > > I think that's pretty nice. And how would you write in-line callbacks for functions that take multiple callbacks (such as an on-success and on-error handler)? Ronald From antonyliu2002 at yahoo.com Wed Mar 17 00:23:54 2004 From: antonyliu2002 at yahoo.com (Anthony Liu) Date: Tue, 16 Mar 2004 21:23:54 -0800 (PST) Subject: problem with cjkcodecs on Mandrake linux +++ In-Reply-To: <20040317050108.71682.qmail@web13006.mail.yahoo.com> Message-ID: <20040317052354.92068.qmail@web13011.mail.yahoo.com> Nobody knows what the problem is? It seems that the cjkcodecs package is correctly installed by the super user. At this point of time, cjkcodecs is only installed on one Mandrake host in the lab. And on this host, it is ok to do s = 'abc' unicode(s, 'gbk') print s # prints 'abc' On the other Mandrake host, where cjkcodecs is not installed, the script above won't work, python complains that it does not know what 'gbk' is. But then why can't I encode a Chinese string on the host which has cjkcodecs? --- Anthony Liu wrote: > But I am using gbcxterm, which displays Chinese very > well, plus, I think I can also input Chinese using > this terminal. Then why do I still have this > problem? > > --- Erik Max Francis wrote: > > Anthony Liu wrote: > > > > > I get the following error message. > > > > > > [antony at ancho tmp]$ python snake.py > > > Traceback (most recent call last): > > > File "snake.py", line 6, in ? > > > print a > > > UnicodeEncodeError: 'latin-1' codec can't encode > > > characters in position 0-1: ordinal not in > > range(256) > > > [antony at ancho tmp]$ > > > > > > What is the problem please? > > > > The problem is the default encoding is Latin-1, > > presumably because > > that's the only thing your xterm/virtual console > > understands. So Python > > is rightly complaining that it can't print the > > Chinese characters for > > you. > > > > -- > > __ Erik Max Francis && max at alcyone.com && > > http://www.alcyone.com/max/ > > / \ San Jose, CA, USA && 37 20 N 121 53 W && > > &tSftDotIotE > > \__/ In this world, nothing is certain but death > and > > taxes. > > -- Benjamin Franklin > > -- > > > http://mail.python.org/mailman/listinfo/python-list > > > __________________________________ > Do you Yahoo!? > Yahoo! Mail - More reliable, more storage, less spam > http://mail.yahoo.com > > -- > http://mail.python.org/mailman/listinfo/python-list __________________________________ Do you Yahoo!? Yahoo! Mail - More reliable, more storage, less spam http://mail.yahoo.com From scummer at 3squares.com Tue Mar 9 16:53:26 2004 From: scummer at 3squares.com (scummer) Date: 9 Mar 2004 13:53:26 -0800 Subject: Python Equivalent?? Message-ID: <1a378204.0403091353.c06c62b@posting.google.com> Hi, I am trying to rewrite the following java method: public static long convertDateTime(String d, String pattern) throws Exception { SimpleDateFormat sdf = new SimpleDateFormat(pattern); sdf.setTimeZone(new SimpleTimeZone(0,"")); java.util.Date date = sdf.parse(d); return date.getTime(); } into Python and not having a great amount of luck. Simply put, I need to pass the method a datetime string, with a given pattern, and have the timezone set on it to UTC--without changing the time value. For example, if I pass these values: d = "2001-01-01 13:00:00" pattern = "%Y-%m-%d %H:%M:%S" to the python function: def convertDateTime(self, d, pattern): and I am doing so from timezone "Europe/Berlin" for example, I do not want the "13" to be changed to "12" before this value is compared to the Unix Epoch (which is at 01 January, 1970 @ 00:00:00 UTC if I understand correctly). I want it to remain 13:00:00 UTC. The return value has to be milliseconds from the Unix epoch (like the Java's getTime()). I have fooled around with the default python modules datetime and time and looked at mx.DateTime but still have not decyphered it yet. Anyone care to lend me some assistance? Thanks in advance, Scum From axelboldt at yahoo.com Wed Mar 17 18:27:04 2004 From: axelboldt at yahoo.com (Axel Boldt) Date: 17 Mar 2004 15:27:04 -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: <40200384.0403171527.4f433174@posting.google.com> "Terry Reedy" wrote > "Axel Boldt" wrote > > "is" on immutables would be useful. 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? > > Deducing details of the implementation *is*, for people with a certain > curiosity, a legitimate usage, in spite of your distain for such. No disdain whatsoever, I do it all the time myself. However, even after my proposed redefinition of "is" for immutables, the function id() would remain available for the curious. > Explaining the bahavior of > > a=[1] > b=a > a[0]=2 > print b > > is another use for 'is'. Certainly, and there are many other real world use cases for "is", just not for "is" on immutables. Axel From peter at engcorp.com Tue Mar 30 10:58:58 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 30 Mar 2004 10:58:58 -0500 Subject: GUI Frameworks in Python? In-Reply-To: References: Message-ID: Richie Hindle wrote: > [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. Something's wrong with your box then. :-) Rebooted. No wxPython apps run first. Clicked on Demo icon and said "one thousand and wuh--" and the splash banner appeared. Run it again and I get as far as "one thou--", so clearly there is some difference between the two and it's not pilot error. (Barring the possibility, which always exists, that it still _is_ pilot error. :-) Go figure. (And as I said this is an AMD 2200 with 512MB RAM, XP Pro.) -Peter From jeff at spamisnotmything.alanne.com Fri Mar 5 12:36:34 2004 From: jeff at spamisnotmything.alanne.com (Jeff Duffy) Date: Fri, 05 Mar 2004 12:36:34 -0500 Subject: Intro to concurrent programming with python In-Reply-To: References: Message-ID: Boogie El Aceitoso wrote: > Hi, > > is there any good intro to threads with Python? Here's one: http://heather.cs.ucdavis.edu/~matloff/Python/PyThreads.pdf I've found that depending on what you're trying to accomplish writing an explicitly threaded implementation may not be the best way to go. Having come from a C and Java background, threading was pretty much the only way I knew how to do multiple execution paths, but I found that for things like writing network servers in Python I was better off using asynchronous I/O. Look into the asyncore module and the Twisted framework (http://www.twistedmatrix.com/) if that's what you need. From jacek.generowicz at cern.ch Wed Mar 17 16:54:40 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 17 Mar 2004 22:54:40 +0100 Subject: Static Typing in Python References: <4056c64d$0$3473$afc38c87@news.easynet.co.uk> Message-ID: Peter Hickman writes: > So just how is Python strongly typed 'like in C, C++, etc'? It isn't. It's _more_ strongly typed that C and C++ :-) If you are really interested in the answer, I've already explained it to you elsewhere in this thread, and you can Google for it. Happy trolling. From dlee at rightnow.com Fri Mar 26 18:05:54 2004 From: dlee at rightnow.com (Lee, Dustin) Date: Fri, 26 Mar 2004 16:05:54 -0700 Subject: examples of doing syadmin activities as a web app Message-ID: I'm looking for an example of a well designed web application used to do sys-admin type functions. Our company has a fairly large internal python web-app that we use for managing DNS, adding/removing pop accounts, installing/upgrading/removing instances of our (c/PHP based) customer product, etc. Our home grown web app works very well and has been around and growing for 2+ years. In my mind things are getting large enough that we could stand to think long and hard about the overall architecture and where we are going long term. (Not that we've never thought about it, but you know how things keep growing and growing.....) So basically I want to see well designed applications that are in the same space (sysadmin oriented). I know of and have played a little with some of the big names in infrastructure (Zope, quixote, etc) but it's hard to really commit to one of those unless I see that it's really a good match for what we are doing. For instance Zope seems more suited to content management type activities, though this may be naivety on my part. And going through the tutorials doesn't give me a great sense of how it matches our needs. Seeing something in action that is similar to what we already have would be more compelling. Anyway our environment is basically your classic LAMP set up with lots of oracle thrown in as well. I'm especially interested in uses of sudo called from web pages, authentication techniques and remote procedure calls. We've got our own solutions to these problems but I'm interested in seeing other ways of doing it. I'd even be willing to wade through non-python code if I'd learn something general about how to design such a system. thanks, dustin -------------- next part -------------- An HTML attachment was scrubbed... URL: From jorgencederberg at hotmail.com Thu Mar 18 11:13:27 2004 From: jorgencederberg at hotmail.com (=?ISO-8859-1?Q?J=F8rgen_Cederberg?=) Date: Thu, 18 Mar 2004 17:13:27 +0100 Subject: Hiding console window In-Reply-To: <4059c0bd$0$47227$cd19a363@news.wanadoo.nl> References: <4059b239$1@pfaff2.ethz.ch> <4059c0bd$0$47227$cd19a363@news.wanadoo.nl> Message-ID: Otto Kr?se wrote: > You can tell py2exe to make a windows exe by putting the line windows = > ["yourscript.py"] in your setup.py script. > > > Example: > """ > # A setup script > > from distutils.core import setup > import py2exe > > setup(windows = ["yourScript.py"]) > """ > > > What I'm wondering about now if there's a way to achieve the same for a > python script (instead of the .exe version of that script). --> I want > to double-click on a python Tkinter script and only see the GUI, not the > console window behind it. Does anyone know how to do this? > The extension should pyw instead of py! Regards Jorgen From lucat at despammed.com Tue Mar 16 15:49:23 2004 From: lucat at despammed.com (Luca T.) Date: Tue, 16 Mar 2004 21:49:23 +0100 Subject: Python & Linux, some questions (2) In-Reply-To: References: Message-ID: Peter Hansen wrote: > Bug: you are referencing r.close and friends, but not actually calling > them. Python is not VB (or Pascal, etc), so you *must* include the > parentheses to make a method call: > > r.close() > w.close() > e.close() Thank you > PyChecker can warn about such things, and many others. I'll search for it Thanx again, Luca From wmgill at gcgroup.net Thu Mar 4 12:48:07 2004 From: wmgill at gcgroup.net (William D. Gill) Date: Thu, 4 Mar 2004 12:48:07 -0500 Subject: python classes References: Message-ID: <9f1bd$40476c26$42a655ea$13320@msgid.meganewsservers.com> "Peter Otten" <__peter__ at web.de> wrote in message news:c27mrt$kge$03$1 at news.t-online.com... > William D. Gill wrote: > > > I'm new to python and am probably trying too many new things at once, but > > here goes. > > Welcome! > > > I am working with a (MySQL) database and am trying to make a html /python > > interface for editing records. > > Data is broken up into several tables, and related by customer number. > > For example one table contains basic information about the customer, one > > table phone numbers (one record for published number, one for cell phone, > > etc, all customers will have at least one record here). > > > > I want to use python classes in my code so I have a couple of questions > > about python classes: > > > > 1) can a class __init__ have multiple "signatures like in C++ i.e. > > MyClass( int, string), . MyClass(int) ? > > No, but you can provide defaults: > > >>> class MyClass: > ... def __init__(self, mandatory, value=99, name="unknown"): pass > ... > >>> MyClass(1) > <__main__.MyClass instance at 0x40290aec> > >>> MyClass(1,2) > <__main__.MyClass instance at 0x40290a6c> > >>> MyClass(1, name="whoever") > <__main__.MyClass instance at 0x40290a4c> > > and so on ad infinitum. I'm not sure defaults do what I want. In C++ I could create an instance passing customer id , or the name, have the constructor interrogat the db and create the same resulting object. I could use default id = None, name = None, and have the constructor either name, id , or a "no info given" to determine how to create the object. > > 2) can a class attribute be an instance of another class ... > > Yes, it can. > > > or is multiple inheritance the proper answer? > > If the _question_ is 42?, then I would say so :-) the _question_ is: which of the following is correct? class MyClass: def __init__(self, id=0000): self.data = MyOtherClass(id) # data is an object with name, id and other properties or class MyClass(MyOtherClass) def __init__(self, id=0000): #self.data.id, self.data.name, and other properties are defined in MyOtherClass and inherited in MyClass > > 3) Can I make instantiation fail if an invalid customer number is use, and > > wrap the "a=MyClass(cusid=999) in an exception? > > You _should_ raise a custom exception (just derive from Exception) which can > be loaded with arbitrary information - in your example that would rather be > the bad customer id than the inconsistant MyClass instance. I'm not sure I understand? I don't want python to create an instance if given invalid data (i.e given an invalid id the db lookup will fail), and I want to raise an exception when this happens. From python at rcn.com Sat Mar 20 01:07:51 2004 From: python at rcn.com (Raymond Hettinger) Date: 19 Mar 2004 22:07:51 -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> Message-ID: <5d83790c.0403192207.1389f4bb@posting.google.com> > Why md5 instead of sha? You could go either way. Make the decision based on how many bits you need (128 should be plenty) for generating a single 53-bit float and then take into account speed considerations (MD5 vs SHA-1) and the time to generate the bits going into the message digest (it takes longer to generate 160 bits than 128). > What's Random.random(self) supposed to do? It's called subclassing ;-) In this case, it inherits all the other random functionality (being sure to include my corrected method name from newrandom() to random()). > > ciphertxt = md5.new(plaintxt).digest() > > I think you mean update. Nope, I meant digest(), but it could be done with update as well. > But doesn't support all the operations specified in the Random API. > What's up with that? Sure it does. That is what the subclassing is for. Again be sure to incorporate the two submitted revisions resulting in: from random import Random from struct import unpack import md5 class MD5Random(Random): def random(self, tofloat = 1.0 / 2 ** 53): plaintxt = str(Random.getrandbits(self, 128)) ciphertxt = md5.new(plaintxt).digest() randint = unpack('> 11 # grab 53 bits return randint * tofloat > > * Takes advantage of MT's proven equidistribution, of its passing > > known tests for randomness, and of its known period (in contrast, > > SHA-1 was designed as a digest that makes it computationally > > intractable to find a different message giving the same signature -- > > that does *not* imply the non-existence of short cycles for some > > keys). > > I'm missing something here--if you're just trying to avoid possible > cycles, why do you want to use MT instead of a sequential counter? Either my version or your original requires something that generates a sequence of randoms from a seed (mine does it with MT and yours with s0=sha1(s0)). The advantages of MT are proven properties, and it can more efficiently generate an arbitrary number of bits (thanks to genrandbits()) without the messy pure python code for extracting a byte at a time. It was also nice to not have to override jumpahead(), getstate(), setstate(), etc. For the base generator, MT or s0-sha1(s0), no cryptography is necessary; you're getting that from the second application of sha1 or md5. If you use sha1 for the base generator, you gain cryptographic strength to the left which is useless for your application (lottery numbers are selected in a way that is strong to the left and right, but no one cares about inferring last weeks numbers from this weeks, you make money only if you can predict the following week). It is doubly useless, because the second application of SHA1 gives you what you need. > > * It uses both MD5 and the Mersenne Twister as they were designed (in > > contrast, my google searches show *no* research on using SHA-1 in OFB > > and reapplying SHA-1 again to conceal the output). > > Applying a collision resistant hash function to itself is a standard > construction for making a PRF and is the basis of HMAC. Re-reading your sentence carefully, does it say that SHA-1 is collision resistant. The design goal for SHA-1, of necessity, produces collisions for messages over 160 bits in length and AFAICT there are no citations showing collision resistance at 160 bits. > I believe > the relevant paper is > > Bellare, M., Canetti, R., and Krawczyk, H., "Pseudorandom Functions > Revisited: The Cascade Construction". Proc. of the 37th IEEE Symp. on > Foundation of Computer Science, 1996, webbed (PostScript) at: > > http://www.research.ibm.com/security/bck1.ps Good paper, but read it carefully. Basically what it starts out saying is that not all trapdoor functions make good PRFs, and then it sets about how to construct functions that are both trapdoor and collision resistant (with positive implications for the minimum period). > My guess is the reason you haven't found any publications specific to > SHA1 with this construction is that nobody has found any results > against SHA1. As far as anyone can tell, the output is > undistinguishable from random. I wish you would abandond this line of reasoning. In security applications, proofs rule and the absence of published flaws means nothing (consider the case of Engima where the designers relied on "nobody has found any results against" their cipher). In this particular case, the finding a short cycle would not really be a major flaw; the function still meets its design goal of producing a message digest for a given message such that it is difficult to produce another message with the same digest. A few known 160-bit collisions would not be an issue except for those exact 160 bit messages. IOW, even if some collisions are known, don't expect to find a paper on it. All of that is moot, MT is fast, subclasses nicely, is threadsafe, has proven distribution properties, and has a known (large) period. Why not digest it and produce your shielded random numbers? Or is is just a matter of being glued to your originally published code (which would be correct if collision resistance is known)? Raymond Hettinger From ienaga at vvl.co.uk Mon Mar 29 02:39:44 2004 From: ienaga at vvl.co.uk (ienaga at vvl.co.uk) Date: Mon, 29 Mar 2004 07:39:44 +0000 Subject: The best antedepressfant In-Reply-To: <52L1EAJABK50K7GB@python.org> References: <52L1EAJABK50K7GB@python.org> Message-ID: <23L3B24H99DE8J5B@vvl.co.uk> Take it easier! Prozahlc - the most popular antidepkressant in the world for the lowesgt price here http://trustdoctors.com/pr/index.php?pid=eph9058 hby w gmpy r vdgm g lc From bnetNOSPAM at ifrance.com Mon Mar 15 15:18:16 2004 From: bnetNOSPAM at ifrance.com (=?iso-8859-1?q?Beno=EEt_Dejean?=) Date: Mon, 15 Mar 2004 21:18:16 +0100 Subject: swig and docstring Message-ID: does swig handle docstring ? i have written a C module using siwg, and i want to add some documentation using docstring. how can i do ? From fidtz at clara#spam#.co.uk Tue Mar 16 07:55:29 2004 From: fidtz at clara#spam#.co.uk (DomF) Date: Tue, 16 Mar 2004 12:55:29 -0000 Subject: new to programming: suggestion References: <3d5e65ea.0403152115.3df7e8c1@posting.google.com> Message-ID: <1079441651.67066.0@demeter.uk.clara.net> In addition to the great programming books suggested by by others, I would recommend "Code" by Charles Petzold, Microsoft press. This is a great book about how computers work at a fundamental level, from switches with lightbulbs and batteries to assembly language! "pius" wrote in message news:3d5e65ea.0403152115.3df7e8c1 at posting.google.com... > i'm new in programming; i'd like to find a good programming book, full > of examples guiding me step to step in the marvellous world of > programming. > Is there anybody who can suggest me where to find what i'm searching? > Thanks a lot. > pus From dmq at gain.com Thu Mar 11 15:13:34 2004 From: dmq at gain.com (David MacQuigg) Date: Thu, 11 Mar 2004 13:13:34 -0700 Subject: backquote References: <9e5ea2c4.0403110753.5c4d437a@posting.google.com> Message-ID: <50i150d9646ms48regnbqgf64bodrsicni@4ax.com> On Thu, 11 Mar 2004 18:08:46 GMT, "Paul McGuire" wrote: >"Skip Montanaro" wrote in message >news:mailman.277.1079020800.19534.python-list at python.org... >> >> Olaf> Is `object` (using backquotes) the same as saying str(object)? >> Olaf> Trying to understand how backquotes work. Thanks for your help. >> >> `object` is equivalent to repr(object). >> >> Skip >> >Is this syntax one of those vestigial short-cuts that is on somebody's hit >list for future deprecation? To my eyes, `object` is more arcane than >repr(object) - why else would we be having this thread in the first place? see GvR's comments at: http://python.org/doc/essays/ppt/regrets/5 He is recommending we drop `x` in favor of repr(x) -- Dave From max at ucmg.com.ua.remove.it Wed Mar 10 04:39:29 2004 From: max at ucmg.com.ua.remove.it (Max Ischenko) Date: Wed, 10 Mar 2004 11:39:29 +0200 Subject: the need for J2EE-like standards for Python Message-ID: Hi, all. I think many would agree that the community-agreed standards could boost the development of the [python] applications in a defined areas. In particular, the lack of J2EE-like standards about servlets or transactions impedes development of web/enterpise applications. It shoudn't be overly complex and elaborate like J2EE but it could be much simple, like, say, DB-API. As it is now, when developing non-trivial Python application we have to face the substantial risk of "lock-in" to particular framework/vendor. The fact that the framework is open source and not proprietary doesn't help much. It is usually too much work to abstract from a particular framework used and it looks like a wrong answer anyway. It is IMO better to invent/publish such an abstraction beforehand so that different frameworks could implement it. There is many topics that could be addressed: servlet containers, component architecture, naming service, etc, etc. What do the community think? Is there an interest to this direction of "maturing" among the Python developers? May be there is already something going on which I'm not aware of? Seems to me that the current diversity of offering for basic infrastructure things like web interaction is caused by uncertainty about how it should be done and range of options on the subject. Hopefully this would sorted out finally, but why not to hurry it a bit. ;) From axelboldt at yahoo.com Thu Mar 18 08:44:28 2004 From: axelboldt at yahoo.com (Axel Boldt) Date: 18 Mar 2004 05:44:28 -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> Message-ID: <40200384.0403180544.337681f1@posting.google.com> Erik Max Francis > Axel Boldt wrote: > > > I couldn't find that algorithm in the language reference, only in 5.9: > > "Tuples and lists are compared lexicographically using comparison of > > corresponding elements. This means that to compare equal, each element > > must compare equal and the two sequences must be of the same type and > > have the same length." > > > > That definition doesn't seem to fully specify equality of list values: > > ... > > Sure it does; the rule can be used recursively. ...and then it can run into an infinite loop. I explained that for the example s==w in the part you deleted. The recursion does not always have a base case; the rule does not always give a definite truth value. > > I hope that the > > actual result received, i.e. s==w, is not implementation dependent? > > They're also equal in Jython. It wouldn't surprise me if you could find > an implementation where they might not compare equal, because this is > such a pathological case. ... i.e. such a fun case. If there really is an implementation dependency hidden in something as fundamental as == for lists, that'd better be mentioned in the language reference. > > Is there a string > > function analogous to pickle.dumps or repr which only takes values > > into account, not internal structure? > > How can you define the value of an arbitrary object without reference to > its internal structure? Well, you claim that s and w have the same value yet different internal structure, so you must work with some definition of "value" that's different from internal structure. I don't know what it is, and the language reference doesn't fully specify it. I.e., I'm interesting in a function val : lists -> strings with the property val(l1) == val(l2) iff l1 == l2. That would also considerably clarify the semantics of == for lists, which I still don't understand. Axel From riccardo_cut.me at cut.me_sideralis.net Tue Mar 2 18:11:47 2004 From: riccardo_cut.me at cut.me_sideralis.net (Riccardo Galli) Date: Wed, 03 Mar 2004 00:11:47 +0100 Subject: Ruby like syntactic sugar References: <5349af3f.0403021326.ed19d8c@posting.google.com> Message-ID: On Tue, 02 Mar 2004 13:26:17 -0800, F Jamitzky wrote: [snip] > In python these fragments can be written as: > > 5 *times(lambda: printf("Hello World!") ) [...] printf ? a bit c-style, isn't it? may be did you want to write sys.stdout.write instead? Ciao, Riccardo -- Riccardo Galli Sideralis Programs http://www.sideralis.net From gnupeaker at yahoo.com Mon Mar 22 06:19:46 2004 From: gnupeaker at yahoo.com (Eyal Lotem) Date: Mon, 22 Mar 2004 03:19:46 -0800 (PST) Subject: explicit variable scoping In-Reply-To: Message-ID: <20040322111946.93866.qmail@web61104.mail.yahoo.com> Python has a few issues many consider problems with regard to its variable namespacing. It seems that the local/global/builtins namespacing rules are ancient remnants of a different Python. While function-level, module-level and "builtin-level" variables are still needed, I suggest a few different lookup schemes, with different levels of extremity: A) Only get rid of the assignment-makes-local heuristic, by changing the meaning of the "global" keyword: def f(): global.a = 1 # Assigns to the module.a a = 2 # Assigns to a local variable This allows accessing globals, and IMO serves for better explicitness about variables which is very desirable and consistent with instance variable access. This is not backwards compatible, however this seems to be entirely statically-convertible (A simple script can convert old-global notation to the new). This has a side-effect of "global" now meaning the "current module" (*1). B) Create a hierarchy of "locals" for nested scopes, which are accessible via an overloaded or new keyword thus: I) b = 1 def f(): a = 2 def g(): global.a = 3 global.global.b = 4 II) b = 1 def f(): a = 2 def g(): parent.a = 3 global.b = 4 C) For consistency and name-lookup simplicity, also make the builtin-namespace explicit: import __builtins__ as builtins builtins.zip(...) or the backwards compatible: from __builtins__ import * I personally don't like C, but think A and B are almost crucial to the "cleanup" of Python's historic lookup semantics. Please don't rule out all suggestions (A, B and C) because of a flaw in one of them. Awaiting your replies. *1: For consistency, "class" could be made to mean the current class without any ambiguity [but perhaps complicating the parser], dissolving the need to re-specify the current class name in calls to super, for example. __________________________________ Do you Yahoo!? Yahoo! Finance Tax Center - File online. File on time. http://taxes.yahoo.com/filing.html From dw-google.com at botanicus.net Sat Mar 27 22:28:35 2004 From: dw-google.com at botanicus.net (David M. Wilson) Date: 27 Mar 2004 19:28:35 -0800 Subject: asyncore deficiencies Message-ID: <99dce321.0403271928.69ef6eeb@posting.google.com> Hi peeps, I finally got around recently to doing something serious using Python for serving network clients asynchronously, deciding on asyncore as my starting point. After 2 days or so of fiddling about, I have decided, as many before me have, that the current asyncore module is the most inflexible, brain-dead, and useless module to be found on the face of the earth! It appears that my next stop for well-engineered event-driven progamming is Twisted, but that is quite a hop from the 500 lines that is asyncore. I have decided in the meantime to stick with asyncore, despite it's failings. It has got me thinking though, shouldn't there be a standard module that does this sort of thing correctly, on a scale comparable to asyncore? ie. asyncore2 My biggests gripes with asyncore so far have been: - Exception handling: namely, it's fairly braindead. As an example, if you are using a private map for loop(), when an Exception is caught it is dumped to stderr, then the dispatcher causing it is destroyed. However, the dead dispatcher is not removed from your private map, resulting in the loop iterating again, and your dead dispatcher causing an "invalid file descriptor" error. - API wasted on less than useful features: of the few configurable parts of asyncore, one of them is the choice between select() and poll(), which I find to be completely useless, as larger projects (those that may wish to use poll()) would in my books already have migrated away from asyncore, and the smaller projects are more interested in getting code written, rather than worrying about some low level events strategy. It also makes the API rather tied to implementation. - Poor __getattr__ use: this has caused numerous "recursion limit exceeded" type exceptions, formatted using asyncore's less-than-ideal so called "compact exception formatter". This results in errors that are practically uncomprehendable, even as an experienced programmer you know to look at the top for the true source. The __getattr__ hack causes behaviour that is far from less than obvious. - Unclear API: asyncore.loop(timeout = ...) is a parameter passed on to the underlying poll() or select(). I can see no circumstance for ever needing to change this. However, I did manage to mistake it for a "maximum execution time" of the poll function, assuming that after this time it would return control to the caller. Again, it's unclear. - Lack of flexibility. I have to use SIGALRM or an external process connected via a socket to get asyncore to change execution path based on non-socket events. The only other way of accomplishing this, is to temporarily empty your map to break out of loop(), then repopulate it, probably using a couple of global variables while you're at it. - Unclear interfaces: you must override all methods inherited from a dispatcher even if you don't use all of them - this makes for verbose code when it is not necessary. - Incorrect interfaces: (this is assumed) for a UDP socket, handle_connect() gets called on first read, despite the fact that UDP is connectionless, and it doesn't make sense to make an exception of the first received packet. The idea of taking the strange semantics detected from select() or poll() and turning them into nice meaningful names is a good one, however it could be improved. So far, I'd like to see: - Less stuffy API: move select() and poll() choice to either an internal decision based on the number of active dispatchers (bad), system call availability (better), a module-level configuration value (ish), or simply use one or the other. Polling objects translate quite well into how asyncore works internally (but they're not available everywhere). - A 'process_once' to allow you to write your own loop()s. - Non braindead exception handling: if an exception occurs, I want to see it propagated back up to the parent, as happens everywhere else, not passed to a handle_error() method or "verbosely ignored". - Decoupling from socket objects: removal of the __getitem__ magic which causes screenfuls of abuse for a simple typo at the wrong stage in execution. - Possibly combined with the above, a more abstract way of watching for events from elsewhere? Doing this might ruin the overall simplicity of the module. Does anyone have any other ideas? I'm sure there are at least a few I have forgotten. If there was support for an improved 'asyncore2', I would very much like to see an improvement on the existing module, not a silly overcomplication with needless feature adding and overabstraction (let's not name names here ;). David. From maxm at mxm.dk Wed Mar 31 05:09:55 2004 From: maxm at mxm.dk (Max M) Date: Wed, 31 Mar 2004 12:09:55 +0200 Subject: [OT] Top posting is a PITA [was : Prothon Prototypes vs Python Classes] In-Reply-To: <4069e9d9$0$8915$636a15ce@news.free.fr> References: <569c605ld1cj8fc1emolk08ete0s1prls1@4ax.com> <106di86neu1qh4d@news.supernews.com> <4069a001$0$4237$afc38c87@news.easynet.co.uk> <4069e9d9$0$8915$636a15ce@news.free.fr> Message-ID: <406a98ee$0$290$edfadb0f@dread12.news.tele.dk> Bruno Desthuilliers wrote: > Peter Hickman wrote: > >> People who whine on about 'top posting' are the sort of people who >> draft 'clean desk' policies. If you want to whine about top posting >> then start alt.whine.top.posting and have fun. That is not quite right. Using top posting forces every reader to unlearn a lifetime of knowledge about narrative flow in content. Left-right - top-down That's how we are reading and writing in most western cultures. For me that's about 40 years of habbit. And it takes a lot of mental effort to read. You could just as well expect that we start reading from right to left. Exactly the same thing. .too confusing pretty is that And regards Max M From haim at babysnakes.org Tue Mar 30 12:21:49 2004 From: haim at babysnakes.org (Haim Ashkenazi) Date: Tue, 30 Mar 2004 19:21:49 +0200 Subject: Python installing on Debian References: Message-ID: Ed Cogburn wrote: > Haim Ashkenazi wrote: >> Ryan Spencer wrote: >> >> >>>On Mon, 29 Mar 2004 03:43:25 +0200, Haim Ashkenazi wrote: >>> >>> >>>>It's a very bad idea to install self-compiled applications to the same >>>>prefix as the ones from original packages. this can breake many things >>>>on your computer. what you have now is a semi-broke python installation, >>>>and a package that tries to install itself every time you run apt-get >>>>but fails. >>>> >>>>I think your best chance to "clean" things would be to uninstall every >>>>python2.3 package on your system (see what happenes when you run >>>>'apt-get remove --purge python2.3'). but make sure you understand what >>>>you're doing (e.g. do you really want to purge your zope installaion? do >>>>you have important stuff there, do you know how to restore it?). then if >>>>there's still stuff in /usr/lib/python2.3 and /usr/local/lib/python2.3 >>>>check that they don't belong to any package (with dpkg -S filename) and >>>>remove them. also check if you have a python binary in /usr/local/bin >>>>and delete it. then re-install all the python2.3 packages. this >>>>of-course will make you lose all your self-compiled modules, so you'll >>>>have to re-compile them. this is a long and messy job, but you got >>>>yourself into this position. just make sure you understand what you're >>>>doing before your doing it. >>>> >>>>in the future I would recommend using the source from unstable to build >>>>a package if you want a version newer then the one that exist in >>>>testing. also use 'stow' when you're compiling sources. this will let >>>>you uninstall self-compiled application easilly. >>>> >>>> >>>> >>>>>Thanks a lot, >>>> >>>>good-luck (you'll need it) :( >>> >>>It actually needn't be that messy. dpkg --purge'ing will only remove the >>>package in question, whereas using a program such as debfoster and >>>pruning the selected target package will remove all it's associate >>>dependencies entirely eradicating it from your system, maybe leaving >>>behind empty configuration folders in your home directory, but there's no >>>fret for that those won't be taking up barely any space and you can >>>always remove them later. >> >> in my system 'apt-get remove --purge python2.3' wants to remove 401 >> packages. that's what I meant messy. you have to check that you didn't >> change any system configuration file for any of the packages. and as a >> rule, it's a good idea to understand what's you're doing. I've seen too >> many times people following instructions and then discovering that >> nothing works without knowing how to restore... > > > It seems apt has gotten so popular that everyone has forgotten about dpkg, > which apt is built upon. :) Yes, apt-get follows dependencies in that > way, > which is why apt was created, to handle dependencies automatically. In > this case however, it may not be necessary to remove everything to restore > python. > It makes sense to try the least painful remedy first. If it were me, I > would first try rebuilding the python .deb package from my system with > dpkg-repack as a backup, then using 'dpkg --force-all --purge python2.3' > to delete just the python interpreter itself, not any of the packages that > depend > on it. Clean any python directories/files left behind (there sometimes is > in places like /etc and /usr/lib, etc), then reinstall python2.3 using the > .deb > you created with dpkg-repack. If that fails, then try downloading a > guaranteed virgin copy of the .deb package and repeating again. If that > fails too, then you're forced to start purging other python-related things > to figure > out whats causing the problem. My point is that when apt doesn't do what > you need it to do, you can always fall back on dpkg. this can work, but he should not only remove python2.3 package, but all the packages that have files there. that's the only way he can really clean this directory. I think (like most applications) that the python2.3 deb is only a part of the whole python 2.3 distribution (which, I think, installs also idle for example, which is in another package). also, the files on '/usr/local/lib/python2.3' can also be from a self-compiled source... > > In this case the problem is likely to be the OP partially overwrote > Debian's python with his own custom compiled one, because I have seen that > "import > site" failure happen when I did this myself some time ago. I wasn't even > installing the compiled version, I just built it and manually transferred > the shared libs and executable to /usr, but that was enough to break some > of the > written-in-python library files. Moral of the story: don't mix standard > and > custom-built packages. If you want to try a custom built one, completely > deinstall the standard one first. Bye -- Haim From antonyliu2002 at yahoo.com Tue Mar 16 21:15:19 2004 From: antonyliu2002 at yahoo.com (Anthony Liu) Date: Tue, 16 Mar 2004 18:15:19 -0800 (PST) Subject: problem with cjkcodecs on Mandrake linux Message-ID: <20040317021519.83996.qmail@web13007.mail.yahoo.com> The superuser of the Mandrake system in my lab installed cjkcodecs for python. But there is a problem. I can encode english alphabets like 'a', 'b', 'c' or 'abc' like so: s = 'abc' s = unicode(s, 'gbk') print s # prints 'abc' but when I tried to encode Chinese strings, I have a problem. For example, to run the following script: s = "蟒蛇" # 2 Chinese characters for python s = unicode(s, 'gbk') print s I get the following error message. [antony at ancho tmp]$ python snake.py Traceback (most recent call last): File "snake.py", line 6, in ? print a UnicodeEncodeError: 'latin-1' codec can't encode characters in position 0-1: ordinal not in range(256) [antony at ancho tmp]$ What is the problem please? __________________________________ Do you Yahoo!? Yahoo! Mail - More reliable, more storage, less spam http://mail.yahoo.com From patois at calvix.org Fri Mar 19 09:49:49 2004 From: patois at calvix.org (Yannick Patois) Date: Fri, 19 Mar 2004 15:49:49 +0100 Subject: Package name with '.' in them: Python Bug ? Message-ID: Hi, Under some naming conditions of module files, it seems that python lost class static variables values. It seems only to append when importing a "badly" named module that itself import a module with a static variable in it (looks complex, but see the example below, pretty simple): First a working example: <<<< file: aTest.py #! /usr/bin/env python import imp import A name='B' fp, pathname, description = imp.find_module(name) B=imp.load_module(name, fp, pathname, description) a=A.A(1) b=B.B() >>>> <<<< file: A.py class A: a=None def __init__(self,a=None): if (a): A.a=a def __str__(self): return str(A.a) >>>> <<<< file: B.py import A class B: def __init__(self): a=A.A() print a >>>> Execution: $ ./aTest.py 1 The value 1 obtained as expected (A.a is a static value and keept as such). 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: $ ./aTest.py None Renaming B.py to B.1.py made A unable to keeps the value of it's static variable. Bug tested with: Python 1.5.2 Python 2.2.2 Python 2.3.3 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. Thanks. 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 dbrown2 at yahoo.com Tue Mar 23 11:03:59 2004 From: dbrown2 at yahoo.com (dbrown2 at yahoo.com) Date: 23 Mar 2004 08:03:59 -0800 Subject: IDLE and turtle References: <405F2941.8070807@aon.at> Message-ID: Gregor Lingl wrote in message news:<405F2941.8070807 at aon.at> ... > With Python 2.2 and IDLE 0.8 it was no problem to use turtle.py (and > Tkinter in general) interactively, because tha application and IDLE > itself ran in the same process (using the same mainloop()). ... > *Fortunately* there is a way to use the new IDLE 1.0 exactly the > same way as the old IDLE 0.8: to use it with the -n option. > > Under Windows e. g. you have to change the link which calls IDLE as > follows (or similar): > > C:\Python23\pythonw.exe "C:\Python23\Lib\idlelib\idle.pyw " -n > > This makes IDLE starting up without subprocesses, which is indicated > by the message > > IDLE 1.0.2 ==== No Subprocess ==== .... > I use to use two versions of IDLE (and I have two coresponding icons > on my desktop). The one with the -n - option for interactive explorations, > the other one, configured like it comes out of the box, for developing > more complex programs. > > HTH, Gregor Thanks very much for your advice Gregor. This work-around works reasonably well for me. I actually was getting quite used to the process behavior in the new IDLE version and trying to forget reload(). Now though I started using the "if __name__ == '__main__' trick at the bottom of my module to load the code for testing and it seems to do the job. I'm not sure if there are any implications for memory leaks with Tkinter this way (I'm repeatedly creating turtle graphics canvases for the display and then just closing the Tkinter window later to rerun the code) but for my limited needs it works. Still, I hope someone can find a good long-term solution to these kinds of window system problems. David From brett at python.org Thu Mar 11 00:19:18 2004 From: brett at python.org (Brett C.) Date: 10 Mar 2004 21:19:18 -0800 Subject: python-dev Summary for 2004-02-01 through 2004-02-29 Message-ID: Title: python-dev Summary for 2004-02-01 through 2004-02-29 Content-type: text/x-rst python-dev Summary for 2004-02-01 through 2004-02-29 ++++++++++++++++++++++++++++++++++++++++++++++++++++ This is a summary of traffic on the `python-dev mailing list`_ from February 1, 2004 through February 29, 2004. It is intended to inform the wider Python community of on-going developments on the list. To comment on anything mentioned here, just post to `comp.lang.python`_ (or email python-list at python.org which is a gateway to the newsgroup) with a subject line mentioning what you are discussing. All python-dev members are interested in seeing ideas discussed by the community, so don't hesitate to take a stance on something. And if all of this really interests you then get involved and join `python-dev`_! This is the thirty-fifth and -sixth summaries written by Brett Cannon (who can't wait to be at PyCon). To contact me, please send email to brett at python.org ; I do not have the time to keep up on comp.lang.python and thus do not always catch follow-ups posted there. All summaries are archived at http://www.python.org/dev/summary/ . Please note that this summary is written using reStructuredText_ which can be found at http://docutils.sf.net/rst.html . Any unfamiliar punctuation is probably markup for reST_ (otherwise it is probably regular expression syntax or a typo =); you can safely ignore it, although I suggest learning reST; it's simple and is accepted for `PEP markup`_ and gives some perks for the HTML output. Also, because of the wonders of programs that like to reformat text, I cannot guarantee you will be able to run the text version of this summary through Docutils_ as-is unless it is from the `original text file`_. .. _PEP Markup: http://www.python.org/peps/pep-0012.html The in-development version of the documentation for Python can be found at http://www.python.org/dev/doc/devel/ and should be used when looking up any documentation on something mentioned here. PEPs (Python Enhancement Proposals) are located at http://www.python.org/peps/ . To view files in the Python CVS online, go to http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/python/ . Reported bugs and suggested patches can be found at the SourceForge_ project page. The `Python Software Foundation`_ is the non-profit organization that holds the intellectual property for Python. It also tries to forward the development and use of Python. But the PSF_ cannot do this without donations. You can make a donation at http://python.org/psf/donations.html . Every penny helps so even a small donation (you can donate through PayPal or by check) helps. .. _python-dev: http://www.python.org/dev/ .. _SourceForge: http://sourceforge.net/tracker/?group_id=5470 .. _python-dev mailing list: http://mail.python.org/mailman/listinfo/python-dev .. _comp.lang.python: http://groups.google.com/groups?q=comp.lang.python .. _Docutils: http://docutils.sf.net/ .. _reST: .. _reStructuredText: http://docutils.sf.net/rst.html .. _PSF: .. _Python Software Foundation: http://python.org/psf/ .. contents:: .. _last summary: http://www.python.org/dev/summary/2004-01-01_2004-01-31.html .. _original text file: http://www.python.org/dev/summary/2004-02-01_2004-02-29.ht ===================== Summary Announcements ===================== To continue my slight abuse of this space: I am still looking for a summer job or internship programming somewhere (does not have to be Python). If you happen to have something at your company or know of something somewhere that you think might work for me please email me at brett at python.org . Thanks. OK, on from pimping myself out for the summer to pimping PyCon_ (or at least I think that is how the youngsters these days would phrase that sentence =). You can still register for the conference. The talks have been chosen and scheduled; more info at http://pycon.org/dc2004/talks/ . Talks look really great and cover a huge gamut of areas; bigger variety than last year in my opinion. There is going to be a Stackless sprint in Berlin March 10-14. See the announcement email at http://mail.python.org/pipermail/python-dev/2004-February/042829.html . .. _PyCon: http://www.pycon.org/ ========= Summaries ========= --------------------------------- Python 2.3 branch open for fixin' --------------------------------- Anthony Baxter, perpetual release manager for the 2.3 branch, announced that CVS commits for 2.3 were open again. He mentioned he thought another release around May or June would probably happen unless a severe bug came up the required immediate patching and release. But Jim Fulton discovered a critical bug. =) It has been fixed in CVS, but no word on if the bug's severity has been judged by Anthony to warrant another release now. Contributing threads: - `release23-maint is reopened for business. `__ -------------------------------------------------------- Early Spring cleaning for what platforms Python supports -------------------------------------------------------- Skip Montanaro cleaned up the configure.in script for Python and in the process removed old support for unneeded OSs as stated in `PEP 11`_. So SunOS 4 support is gone. There was discussion of making Python 2.4 not support libc 5 since Python does not compile with it. The suggestion was made of having configure.in detect libc 5 and if it found it then refuse to continue. Skip also removed optional universal newline support and antiquated pthread variants from 1997 and before. .. _PEP 11: http://python.org/peps/pep-0011.html Contributing threads: - ` zapped several unsupported bits... `__ - `PEP-0011 up-to-date `__ -------------------------------------------------- Compiling in profiling support for the interpreter -------------------------------------------------- Jeremy Hylton discovered his old way of turning on gprof_ profiling support when compiling Python no longer worked. Hye-SHik Chang said he got it working by compiling using ``CC="cc -pg" LDFLAGS="-pg" ./configure``. Martin v. L??wis suggested running configure with `` --without-cxx`` to get around the problem. .. _gprof: http://www.cs.utah.edu/dept/old/texinfo/as/gprof_toc.html Contributing threads: - `building python with profiling support `__ ----------------------------------- Python and C89 play nicely together ----------------------------------- The question of what version of C Python is required to work with came up. The answer is that C89 is the version of Standard C Python requires. Neither C89 with Amendment 1 (also called C95) nor C99 are required for Python to run (which, in this case, meant wchar.h is not required). Contributing threads: - `*grumble* wchar.h `__ - `Another big ANSI-fication change... `__ --------------------------------------- Growing lists just got that much faster --------------------------------------- Raymond Hettinger (along with the help of various other people on his initial patch) managed to come up with a way to speed up allocating space for list items (either from growth of an exisiting list or creation of a new list). While this was being discussed, though, the possibility of 3rd party code messing with the internal values of list items came up. While no specific use-case was found, it was agreed upon that code outside of the Python core should not break the API; there is no guarantee the internals won't change. Raymond has also subsequently done a major clean-up of the entire PyList API that has netted wonderful speed-ups across the board. And in case you are a big fan of list.pop(0) and list.insert(0, x), the collections module's deque object now handles your needs in a much faster fashion. Kudos to him for doing all of this and helping to make sure Guido doesn't get a pie at OSCON 2004 (if you don't catch that reference about the pie, read http://python.org/dev/summary/2003-12-01_2003-12-31.html#pie-thon-competition-work-ramps-up ) Contributing threads: - `Optimization of the Year `__ --------------------------------------------------- Do we really need mutability for exceptions groups? --------------------------------------------------- The question was raised as to why ``except (TypeError, ValueError):`` is acceptable while ``except [TypeError, ValueError]:`` (in other words why use tuples to group exceptions for an 'except' statement and not allow lists). The question was in relation as to whether it had something to do with a tuple's immutability. Guido said it all had to do with a visual way of grouping tuples and nothing to do with what the underlying container was. If he had it to do over again he would rather change it so that ``except TypeError, ValueError:`` did the same thing as above. That change would alleviate the common error of expecting the above behavior using that syntax but instead getting the exception instance bound to ValueError. But the change is not planned for any time in the future since Guido has no proposal on how to change the syntax to handle the assignment to a local variable for the exception instance. Contributing threads: - `Syntax for "except" `__ --------------------------- No, you can't subclass Bool --------------------------- Francois Pinard discovered that you can't subclass the Bool type. This led to the question of "why?" To this he received the answer that since Bool only has two instance, True and False, it shouldn't be allowed to be a superclass of anything since that would suggest more instances of Bool could exist. Contributing threads: - `bool does not want to be subclassed? `__ ------------------------------------- Function decoration and all that jazz ------------------------------------- Bob Ippolito brought up Michael Hudson's function/method syntactic sugar to essentially implement `PEP 318`_ (Michael's patch can be found at http://starship.python.net/crew/mwh/hacks/meth-syntax-sugar-3.diff) as something he **really** wanted for PyObjC_. In case you don't know what the syntax is ``def fxn() [fun, stuff, here]: pass``, which ends up being the same as:: def fxn(): pass fxn = here(stuff(fun(fxn))) Common use cases are for defining class The discussion then drifted in discussing how this syntax could even be used with classes and whether it could somehow supplant some metaclass uses. Talking seemed to lead to it not really being that great of a use case. The order or application also came up. It was suggested that the order be the reversed of that shown above so that it reads the way it would be written by hand instead of in application order. Using 'as' instead of brackets was brought up again; ``def fxn() as fun`` instead of ``def fxn() [fun]``. An argument for this or any other syntax is that using brackets for this overloads the usage of them in Python itself and some feel that is unpythonic. An explicit argument for the brackets, though, is that it is cleaner for multi-line use. There was also the issue with using 'as' in terms of how would one look up its use in the docs? Would someone look up under 'as' or under 'def' naturally? .. _PEP 318: http://python.org/peps/pep-0318.html .. _PyObjC: http://pyobjc.sourceforge.net/ Contributing threads: - `Plea for function/method syntax sugar `__ - `new syntax for wrapping `__ - `PEP 318: What Java does `__ - `other uses for "as" `__ - `new syntax for wrapping (PEP 318) - Timothy's summary `__ - `[UPDATED] PEP 318 - Function/Method Decorator Syntax `__ -------------------------------------- Building Python with the free .NET SDK -------------------------------------- Go to the email to see Garth's latest tool and instructions on building Python using Microsoft's free .NET SDK. Contributing threads: - `Compiling python with the free .NET SDK `__ ------------------------------------- PEP 326 finished (but still rejected) ------------------------------------- `PEP 326`_ ("A Case for Top and Bottom Values") has its final implementation linked from the PEP. It has been rejected (as with all PEPs that have been pronounced upon, read the PEP for the reasons why), but the PEP's authors will nice enough to go ahead and finish the code for anyone who might want to use it anyway. .. _PEP 326: http://python.org/peps/pep-0326.html Contributing threads: - `PEP 326 `__ ------------------------------------------------ time.strftime() now checks its argument's bounds ------------------------------------------------ Because of a possible crash from using negative values in the time tuple when passed to time.strftime(), it was decided to bound checks on all values in the time tuple. This will break existing code that naively set all fields to 0 in a passed-in time tuple and thus did not set the values within the proper bounds (year, month, day, and day of year should not be 0). Contributing threads: - `Boundary checks on arguments to time.strftime() `__ -------------------------------------------- OpenVMS throws a fit over universal newlines -------------------------------------------- For Python 2.4 the option to compile without universal newline support was removed. Well, it turns out that OpenVMS_ doesn't like this. Apparently the OS is not stream-oriented for its filesystem but is records-based and this leads to there being no newlines in a text file unless it is opened as a plain file. Bug #903339 has been opened to deal with this. .. _Bug #903339: http://python.org/sf/903339 .. _OpenVMS: http://www.openvms.org/ -------------------------------------------- Forth-style argument passing for C functions -------------------------------------------- Raymond Hettinger came up with the idea of adding a new function flag called METH_STACK that would call a C function to be called with a pointer to the execution stack and the number of arguments it is being passed. This would allow the function to pop off its arguments on its own and bypass the expense of putting them into a tuple. The overall idea did not seem to win out. But it does turn out that Michael Hudson has a patch that implements a similar idea at http://python.org/sf/876193 . A discussion of whether more specific argument passing like METH_O should be considered. Contributing threads: - `Idea for a fast calling convention `__ From joshway_without_spam at myway.com Mon Mar 15 13:01:17 2004 From: joshway_without_spam at myway.com (JCM) Date: Mon, 15 Mar 2004 18:01:17 +0000 (UTC) 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: Peter Hickman wrote: > Jacek Generowicz wrote: >> Peter Hickman writes: >> I have read it before. I still disagree with the implication that >> Python is weakly typed just much as I did when I first read it. >> >> But you are ignoring my explanation of how Python is strongly typed, >> and of the distinction between strong-vs-weak and dynamic-vs-static >> typing, and are instead resorting to argument from authority: > Right. I should listen to you because you are an authority on Typing but > ignore Guido van Rossum. There's some disagreement, but most often I hear these terms used as Jacek describes. Weak typing generally refers to the ability to reinterpret the data representation at runtime. For example, in C: double x = 10.3; int i = *(int*)&x; Most would call Python strongly, dynamically typed. From jgentil at sebistar.net Tue Mar 30 01:50:36 2004 From: jgentil at sebistar.net (Jon-Pierre Gentil) Date: Tue, 30 Mar 2004 00:50:36 -0600 Subject: marshalling python data structures in php In-Reply-To: <930ba99a.0403292243.2d5d3997@posting.google.com> References: <930ba99a.0403292243.2d5d3997@posting.google.com> Message-ID: <106i65to50v6v31@corp.supernews.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Sridhar R wrote: | Hi, | | I have written in network project in python. the client sends a | dictionary by pickling it over the socket and the server unpickles it. | I also need a webclient for this. So I am wondering how to create | python dictionary in PHP and pickle it and send it to the server | running in python. | | any thoughts? Sounds utterly hard. You'd have to implement the Pickle module in PHP and devise a way to convert a PHP associative array into a pickled Python dictionary. Instead what I would suggest that you do is to write your webclient in Python using mod_python/Zope/Twisted.Web/etc... - -- :: Jon-Pierre Gentil :: PGP Key ID 0xA21BC30E :: Jabber: jgentil at jabber.org -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.4 (GNU/Linux) Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org iEYEARECAAYFAkBpGLoACgkQOrVFmaIbww5k7ACgkpQ+TcbKQXoqo2JtAWW6dN4U cokAn2hppk37ilKcM1hAu7J9X4N2Q48r =8OAg -----END PGP SIGNATURE----- From PeterAbel at gmx.net Wed Mar 10 16:35:45 2004 From: PeterAbel at gmx.net (Peter Abel) Date: 10 Mar 2004 13:35:45 -0800 Subject: What is wrong? The minidom or the XML file? References: Message-ID: <21064255.0403101335.41b328f7@posting.google.com> Anthony Liu wrote in message news:... > I copy-pasted the following sample xml document from > http://slis-two.lis.fsu.edu/~xml/sample.html and saved > it as samplexml.xml. Please note that I removed the > following line > > > > from the original xml sample. > > > > Sample Document > Brandon > Voss > The XML Pages > This is element text and an entity > follows:&Description; > > > > Then, I attempted to parse this xml document with the > following python code, which is saved as xmltest.py. > > from xml.dom import minidom > xmldoc = minidom.parse('sample.xml') > print xmldoc.toxml() > > I got the following error message: > > >>> > > Traceback (most recent call last): > File "C:\Python23\codes\xmltest.py", line 4, in > -toplevel- > xmldoc = minidom.parse('samplexml.xml') > File "C:\Python23\lib\xml\dom\minidom.py", line > 1919, in parse > return expatbuilder.parse(file) > File "C:\Python23\lib\xml\dom\expatbuilder.py", line > 924, in parse > result = builder.parseFile(fp) > File "C:\Python23\lib\xml\dom\expatbuilder.py", line > 207, in parseFile > parser.Parse(buffer, 0) > ExpatError: not well-formed (invalid token): line 1, > column 5 > >>> > > I have no clue why that xml document is not > well-formed. > > Any hint please? > > > __________________________________ > Do you Yahoo!? > Yahoo! Search - Find what you?re looking for faster > http://search.yahoo.com One additional possibility to get another quick help about errors in the xml-document is - when working under MS-Windows - to open the document with the Internet Explorer up from version 5.xx or so. In your case it tells me exactly what Erik Max Francis told you. Regards Peter From markus_wankusGETRIDOFALLCAPS at hotmail.com Wed Mar 10 23:37:14 2004 From: markus_wankusGETRIDOFALLCAPS at hotmail.com (Markus Wankus) Date: Wed, 10 Mar 2004 23:37:14 -0500 Subject: PythonCOM - How to get (LPDISPATCH) of myself? In-Reply-To: References: <_MS2c.1888$6y1.257780@news20.bellglobal.com> Message-ID: <%1S3c.38846$lT6.197192@news20.bellglobal.com> Getting clooooseeerr...... OK, apparently what I want is: win32com.server.util.wrap(self) This seems to work fine. All I have left to do is to get my callbacks to work. They are intermittent, but I think it is not Python's fault... Markus. Markus Wankus wrote: > In the spirit of trial and error.. ;o) ..I tried the following to get a > Dispatch object to myself from within my Python COM server: > > pythoncom.UnwrapObject(pythoncom.GetActiveObject(self._reg_progid_)) > > But got the following exception: > > Traceback (most recent call last): > File "C:\PYTHON23\lib\site-packages\win32com\universal.py", line 173, > in dispatch > retVal = ob._InvokeEx_(meth.dispid, 0, meth.invkind, args, None, None) > File "C:\PYTHON23\lib\site-packages\win32com\server\policy.py", line > 322, in _InvokeEx_ > return self._invokeex_(dispid, lcid, wFlags, args, kwargs, > serviceProvider) > File "C:\PYTHON23\lib\site-packages\win32com\server\policy.py", line > 541, in _invokeex_ > return func(*args) > File "E:\_DEV\python\solidworks\PropertyPageUtils.py", line 53, in > ConnectToSW > obj = > pythoncom.UnwrapObject(pythoncom.GetActiveObject(self._reg_progid_)) > pywintypes.com_error: (-2147221021, 'Operation unavailable', None, None) > > Can anyone tell me what 'Operation unavailable' might be hinting at? > > Markus. > > Markus Wankus wrote: > >> I have a Python COM server which supports callbacks for a large CAD >> program. It adds menu items and then listens to events - however, I >> have a problem (obviously)... I'm a COM idiot - so please expect dumb >> questions. >> >> There are a bunch of functions that require a pointer to the event >> handler, or a pointer to my COM server. Prolem is - it is looking for >> a pointer to a Dispatch object - but I have already been dispatched. >> Maybe an example will clear things up. One of the functions is as >> follows: >> >> Status = SldWorks.SetAddinCallbackInfo ( ModuleHandle, AddinCallbacks, >> Cookie ) >> >> Input: >> (long) ModuleHandle >> Instance handle of the add-in >> >> Input: >> (LPDISPATCH) AddinCallbacks >> Pointer to the object that includes the add-in callback methods >> >> Input: >> (long) Cookie >> Add-in ID; this is the same Cookie you specified in SwAddin::ConnectToSW >> >> Output: >> (VARIANT_BOOL) Status >> TRUE if successful, FALSE if unsuccessful >> >> What I *want* to do is essentially: >> >> SetAddinCallbackInfo(id(self), self, self.ICookie) >> >> ...however - this fails because "self" (my COM server) is not a >> Pointer to a Dispatch object. >> >> I can get it to work if I do the following: >> >> SetAddinCallbackInfo(id(self), Dispatch(self._reg_progid_), self.ICookie) >> >> ...however this dipatches a new instance of my COM server, losing any >> attributes that may have been set since instantiation - thus is useless. >> >> Is there a way to get a pointer to a Dispatch object of yourself? >> >> Thanks, >> Mark. From gerrit at nl.linux.org Mon Mar 15 04:16:36 2004 From: gerrit at nl.linux.org (Gerrit) Date: Mon, 15 Mar 2004 10:16:36 +0100 Subject: put your money where your mouse is, or why I prefer Spanish to English: a proposal In-Reply-To: References: <082d01c407eb$bb8dfc10$210110ac@jsbwxp3> Message-ID: <20040315091636.GA3736@nl.linux.org> Greg Ewing (using news.cis.dfn.de) wrote: > Harry George wrote: > >Hmmm. How many Pythonistas have studied Esperanto? Looks like 2 of > >us so far. The Esperanto headquarters is in Netherlands, so there is > >a suspicious confluence of geography with Python. > > I'm astounded that nobody has suggested Dutch yet... I guess the Dutch among us know that Dutch is certainly not an easy language - zwakke/sterke werkwoorden are often problems while studying NT2 (Nederlands als Tweede Taal, Dutch as second language) (or NTn n>1). I think it has been proposed at some time in the past, though - maarja, de Nederlandse mailing list heeft 2 jaar geleefd en 4 berichten gehad, dus erg veel animo is/was er niet (er is trouwens wel een Nederlandstalig Python boek zag ik, Programming Python has been translated). getjampoerde groetjes, Gerrit (who knows only Nederlands, Deutch, English, et un petit peu Fran?ais) (Indonesian? ;-) -- Weather in Twenthe, Netherlands 15/03 08:25 UTC: 10.0?C light drizzle overcast wind 6.3 m/s SW (57 m above NAP) -- Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From robhboyd at yahoo.com Tue Mar 9 10:41:39 2004 From: robhboyd at yahoo.com (Robert Boyd) Date: Tue, 9 Mar 2004 07:41:39 -0800 (PST) Subject: a desired python editor In-Reply-To: Message-ID: <20040309154139.86874.qmail@web14106.mail.yahoo.com> --- 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) > I use jEdit (jedit.org). It's written in Java and the available plugins tend to be oriented towards Java development, but it does Python syntax highlighting, code browsing with ctags, can open separate windows for each file or put them in tabs, etc, etc. Lots of additional plugins like task lists, CVS, remote editing through FTP or SFTP... you can even dock a Jython interpreter into it, or a Python debugger. No code completion for Python, though. I tried Eclipse for Python development for about a week then went back to jEdit. Rob __________________________________ Do you Yahoo!? Yahoo! Search - Find what you?re looking for faster http://search.yahoo.com From lbates at swamisoft.com Mon Mar 22 17:32:05 2004 From: lbates at swamisoft.com (Larry Bates) Date: Mon, 22 Mar 2004 16:32:05 -0600 Subject: Any reportlab user here?? References: Message-ID: Ketul, You use .barLabels.fontSize, .barLabels.fontName, .barLabels.Nudge, and .barLabelFormat to control what prints at the top of each bar. You use the legend object to create a legend for a barchart that shows a "swatch" of the color/pattern for the bar along with a description for that series. You should probably print out and review all the examples that come with ReportLab/Graphics. I know they helped me a lot. Larry Bates Syscon, Inc. wrote in message news:f046efac.0403220742.12943b9c at posting.google.com... > 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 python at gerber.mailshell.com Thu Mar 4 16:19:24 2004 From: python at gerber.mailshell.com (Shmuel Gerber) Date: Thu, 04 Mar 2004 21:19:24 GMT Subject: language version data in source Message-ID: Hi, all. Is there any convention for including metadata in a source file? Specifically, is there a convention for indicating which version or versions of Python the source was designed for and/or tested on? --Shmuel Gerber From elainejackson7355 at home.com Mon Mar 22 13:18:30 2004 From: elainejackson7355 at home.com (Elaine Jackson) Date: Mon, 22 Mar 2004 18:18:30 GMT Subject: name of 'name' Message-ID: Is there a built-in name for the function that returns an object's name? That is, for " lambda x: [y for y in globals().keys() if globals()[y]==x][0] " ? Muchas gracias. Peace From mark at hahnca.com Mon Mar 29 16:42:25 2004 From: mark at hahnca.com (Mark Hahn) Date: Mon, 29 Mar 2004 13:42:25 -0800 Subject: Prothon Prototypes vs Python Classes References: <569c605ld1cj8fc1emolk08ete0s1prls1@4ax.com><106cc1f2rsnaoe2@news.supernews.com><406635AB.9050803@mlug.missouri.edu><106ceeeqc8ph126@news.supernews.com> <106dukh7ncf9ad4@news.supernews.com> <40681CAD.6050303@stackless.com> Message-ID: <00f201c415d6$b974f110$d701a8c0@MarkVaio> I would greatly appreciate it if you could take a peek at my stackless implementation and give me a grade :) I don't know if you remember me, but I pissed you off in a rude posting I made in a reply to you months ago (I apologize once again). I was trying to pickle a complicated graph of objects and getting recursions limit errors in Python. You were very helpfully telling me how to get around the problem in a long message and I replied curtly and rudely that Python was broken and I'd rather write something from scratch than try to use broken tools (it was a bad day). To make a long story short, that was the straw that broke the camel's back and caused me to start work on Prothon. I had been daydreaming about an extrememly simple but powerful language with just a pile of lockable objects for some time. The fact that is uses Python syntax is secondary and only because I like the syntax. My real love is the internal object structure, threading, and interpreter. ----- Original Message ----- From: "Christian Tismer" To: "Mark Hahn" Cc: Sent: Monday, March 29, 2004 4:55 AM Subject: Re: Prothon Prototypes vs Python Classes > Mark Hahn wrote: > > > Mutability is an interesting area. I just added an unmutable bit in the > > Prothon internal object which makes the read_lock call a no-op and causes a > > write_lock call to throw an exception. This makes the object > > write-protected and makes the lock code run much faster. > > > > I did this for internal performance reasons, but after doing it I realize > > that extending it to the Ruby freeze() level would be really good. Tying > > the freezing in somehow to the bang! methods is also in interesting area of > > research. > > Mark Hahn (Prothon Author) > > > > P.S. If this belongs in the Prothon list instead of Python, let us know. > > Allthough I'm a known Python-addict, I find this very interesting. > Being prototyped instead of class based was one of the features > of JavaScript, which were concidered "deficiencies". Well, I didn't > share this so much, there are many other much worse problems. > > I'm eager to learn how a real language develops if it consequently > builds upon prototypes. Especially this one, since it is stackless > by nature. :-) > > 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 mfranklin1 at gatwick.westerngeco.slb.com Tue Mar 9 04:44:33 2004 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Tue, 09 Mar 2004 09:44:33 +0000 Subject: Scaling an ImageTk.PhotoImage In-Reply-To: References: Message-ID: <404D9201.8040803@gatwick.westerngeco.slb.com> James Anderson wrote: > I'm have a bitmap which I can display as an ImageTk.PhotoImage and would > like to display it and double or quadruple size. The bitmap itself is > generated inside my program, so converting it to another format isn't > really practical. Does anyone know an easy way to do this? > > Thanks, > James Anderson > A standard Tkinter.PhotoImage has a zoom method, a PIL ImageTK is AFAIK the same thing. from pydoc Tkinter.PhotoImage:- | zoom(self, x, y='') | Return a new PhotoImage with the same image as this widget | but zoom it with X and Y. HTH Martin From tseaver at zope.com Tue Mar 2 13:32:03 2004 From: tseaver at zope.com (Tres Seaver) Date: Tue, 02 Mar 2004 13:32:03 -0500 Subject: python.exe vs pythonw.exe difference? In-Reply-To: References: Message-ID: <4044D323.1060506@zope.com> Thomas Heller wrote: > "Tim Peters" writes: > > >>[moving this from comp.lang.python to zope-dev; it really belongs on a >> Zope list, although schemes to change what pythonw does probably belong >> on python-dev] > > > [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] Heh, yep. That is where I saw yours. Tres. -- =============================================================== Tres Seaver tseaver at zope.com Zope Corporation "Zope Dealers" http://www.zope.com From sross at connectmail.carleton.ca Tue Mar 23 10:37:40 2004 From: sross at connectmail.carleton.ca (Sean Ross) Date: Tue, 23 Mar 2004 10:37:40 -0500 Subject: explicit variable scoping References: Message-ID: <6QY7c.11335$A_2.687877@news20.bellglobal.com> "Jacek Generowicz" wrote in message news:tyfk71b66ko.fsf at pcepsft001.cern.ch... > In Python, both "let" and "setq" are spelt "=". However, in the case > of a global binding "(setq x y)" can be spelt "global x; x = y". > > "let" and "setq" give us a way to express whether we want to rebind an > existing binding, or to create a new one. Io makes a similar distinction, though "let" and "setq" are spelled differently (":=" and "=", respectively). Their rationale can be found here [1]. They don't appear to have considered 'let', e.g., "let a = 1". On a somewhat related note, there's atleast one long debate [2] on c.l.py regarding adding ":=" to the language (there are others if anyone wants to sift through the archives). Although, that argument was about adding an assignment expression, not a second assignment statement. [1] http://io.kicks-ass.net/LocalVariables http://io.kicks-ass.net/LocalVariablesSolutions [2] http://groups.google.ca/groups?hl=en&lr=&ie=UTF-8&oe=UTF-8&safe=off&selm=Pine.SUN.3.95-heb-2.07.990511232428.3549B-100000%40sunset.ma.huji.ac.il From max at alcyone.com Wed Mar 10 22:24:46 2004 From: max at alcyone.com (Erik Max Francis) Date: Wed, 10 Mar 2004 19:24:46 -0800 Subject: What is wrong? The minidom or the XML file? References: Message-ID: <404FDBFE.4710C204@alcyone.com> Anthony Liu wrote: > What do you mean by "where these Chinese characters > come from"? I think I got lost. You said you pasted Chinese characters into the XML document. That doesn't have much meaning unless you know what encoding those characters were in when you pasted them. They need to be in the same encoding as the document you're pasting them in, which with XML you can set using the "encoding" processing instruction. -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE \__/ All the gods are dead except the god of war. -- Leroy Eldridge Cleaver From gabor at z10n.net Wed Mar 10 11:26:54 2004 From: gabor at z10n.net (gabor) Date: Wed, 10 Mar 2004 17:26:54 +0100 Subject: Unicode (Japanese) fonts in Images In-Reply-To: <20040309173804.GK12662@unpythonic.net> References: <20040309173804.GK12662@unpythonic.net> Message-ID: <1078936014.8701.52.camel@dubb> On Tue, 2004-03-09 at 18:38, Jeff Epler wrote: > > > On Mon, 2004-03-08 at 23:12, Rich wrote: > > >> kanji = u'\ufffe\ua295\uc07b > On Tue, Mar 09, 2004 at 05:21:11PM +0000, Rich wrote: > > I thought that saving them in notepad as unicode, then opening that in a > > hex editor and using the values was the way forward but obviously not :( > > The file which looked like > FF FE A2 95 C0 7B > is a probably utf-16 encoded with a BOM (byte-order mark) at the beginning. > > You can convert this into a Python unicode string like so: > >>> "\xff\xfe\xa2\x95\xc0\x7b".decode('utf-16') > u'\u95a2\u7bc0' > On my system, printing this to my terminal shows a pair of japanese-looking > symbols. when windows talks about unicode, he always means UTF-16. when linux talks about unicode, he usually means UTF-8. you have to be very careful which encodings you use. for example if you save the stuff in notepad as 'unicode', imho it will save them as UTF-16. gabor From dmq at gain.com Tue Mar 9 18:26:22 2004 From: dmq at gain.com (David MacQuigg) Date: Tue, 09 Mar 2004 16:26:22 -0700 Subject: Working around a lack of 'goto' in python References: Message-ID: On Sat, 06 Mar 2004 18:18:28 GMT, "Brett" wrote: >Two areas where I've found 'goto' two be useful in other languages are in I agree there are situations where GOTO is appropriate, but the real question is - Do we want it in Python, given that *most*, even moderately skilled users, will abuse this tempting statement, and the effort in dealing with the consequences of this abuse will far exceed the effort of working around the few cases where it would be nice. Python, more than C++, is intended to be the *best* language for users who are not full-time programmers. I once had a boss who wrote a 70-page program in BASIC. After a few weeks, he gave up and expected me to fix it. After seeing that the whole thing was one module, laced with GOTO's, I told him that I could re-write the whole thing in less time than it would take to debug his program. He did not want to hear that. He also thought it would take too much time to explain to me what the program was supposed to do! -- Dave From artur_spruce at yahoo.com Wed Mar 24 03:19:19 2004 From: artur_spruce at yahoo.com (AdSR) Date: 24 Mar 2004 00:19:19 -0800 Subject: PEP 328: Imports: Multi-Line and Absolute/Relative References: Message-ID: Josiah Carlson wrote: > > I'll miss the current behavior of import, though. Somehow it feels > > more intuitive to me. Oh, well, practicality beats purity - or > > personal taste... > > You can still use classic import semantics, - is optional. By "current" I meant search in current package first. Anyway, I thought it over and concluded that the behavior proposed in the PEP, whether it makes more sense than what is now or not, is at least closer to what is practiced on POSIX systems for search path: Current directory is not in the search path, you have to say explicitly that you're running the program from current dir (like "./script"). So, "pkg.inpkg.mod" is always absolute, ".mod" is similar to "./script", and "-2.outpkg.mod" reads better than ".....outpkg.mod" (analogous to "../../outdir/script"). Of other proposals, ".__parent__" is logical but introduces yet another (long) name, and ".__pkg__" just doesn't say clearly that you go upwards, so you might prefer ".__up__" instead. I still like "-." better though. Just some morning wake-up thinking, AdSR From michele.simionato at poste.it Wed Mar 3 08:26:02 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 3 Mar 2004 05:26:02 -0800 Subject: E-mail account disabling warning. References: Message-ID: <95aa1afa.0403030526.728de57b@posting.google.com> "Tim Peters" wrote in message news:... > It shouldn't need to be said, but if you get a message that looks like this: > > > Dear user of Python.org gateway e-mail server, > > > > We warn you about some attacks on your e-mail account. Your > > computer may contain viruses, in order to keep your computer and > > e-mail account safe, please, follow the instructions. > > > > For details see the attached file. > > > > For security reasons attached file is password protected. The > > password is "28132". > > > > Cheers, > > The Python.org team > > http://www.python.org > > 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. Notice that I had just asked the University support team about filtering my spam and the message seemed to refer to my request (the header was smart enough). Fortunately, I got suspicious when I was asked to run an executable and I asked to the University before. It is a very subtle virus! 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 .... A frightening perspective! :-/ Michele From oussoren at cistron.nl Tue Mar 23 01:41:03 2004 From: oussoren at cistron.nl (Ronald Oussoren) Date: Tue, 23 Mar 2004 07:41:03 +0100 Subject: PEP 318 In-Reply-To: References: Message-ID: <0DE0F193-7C95-11D8-8375-0003931CFE24@cistron.nl> On 23-mrt-04, at 1:15, Jess Austin wrote: > I'll preface by saying that I haven't fully grokked all the possible > uses of decorators. Also, I can sympathize with the complaints about > seeing a function definition and then seeing a classmethod call on > that function 50 lines later (actually that seems like a case for > refactoring but never mind). b-) > > The brackets and the 'as' both seem awkward to me. Also, introducing > a requirement that definition and decoration take place on the same > line seems to limit the the possibilities of decoration. Perhaps my > class wants to offer several faces of the same method: > > 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. Ronald From christian at mvonessen.de Sun Mar 28 11:16:11 2004 From: christian at mvonessen.de (Christian von Essen) Date: Sun, 28 Mar 2004 18:16:11 +0200 Subject: Where to offer simple apps Message-ID: Hi all I've written a little .ini fileeditor, neither important nor good enough to become an own project, but for me important enough to want to get some feedback, as it is my first more or less sensible python application. Where is the best/a good place to offer this code and ask for feedback. Well, it seems, that I already offer my code here ;) The application consists of 442 lines in 2 files. I use Tkinter and my own ini-parser because I wanted to learn how to parse such a simple format. Christian von Essen From NAIGIMSESRIMAIL at gims.com Wed Mar 31 15:01:57 2004 From: NAIGIMSESRIMAIL at gims.com (GroupShield for Exchange (ESRIMAIL)) Date: Wed, 31 Mar 2004 22:01:57 +0200 Subject: ALERT - GroupShield ticket number OB65_1080763313_ESRIMAIL_3 was generated Message-ID: Action Taken: The message was blocked because of its subject. To: python-list at python.org From: Roel Schroeven Sent: 57320704,29628251 Subject: Re: test for nan Attachment Details:- Attachment Name: N/A File: Infected.msg Infected? No Repaired? No Blocked? Yes Deleted? No Virus Name: -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/ms-tnef Size: 1817 bytes Desc: not available URL: From jcarlson at nospam.uci.edu Wed Mar 17 22:12:57 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Wed, 17 Mar 2004 19:12:57 -0800 Subject: Replace accented chars with unaccented ones In-Reply-To: References: Message-ID: Noah wrote: > Josiah Carlson wrote in message news:... > >>> r += xlate[ord(i)] >>> r += i >> >>Perhaps I'm going to have to create a signature and drop information >>about this in every post to c.l.py, but repeated string additions are >>slow as hell for any reasonably large lengthed string. It is much >>faster to place characters into a list and ''.join() them. > > > True. Is this better? > > ... body of latin1_to_ascii() ... > r = [] > for i in unicrap: > if xlate.has_key(ord(i)): > r.append (xlate[ord(i)]) > elif ord(i) >= 0x80: > pass > else: > r.append (i) > return ''.join(r) I'd use: ''.join([xlate.get(ord(i), i) for i in unicrap \ if ord(i) in xlate or ord(i) < 0x80] Using r.append(), in general, while being faster than string addition, is significantly slower than using list comprehensions. - Josiah From o_gloom at mail.com Tue Mar 9 05:54:13 2004 From: o_gloom at mail.com (gloom) Date: 9 Mar 2004 02:54:13 -0800 Subject: DispatchWithEvents when have internal COM interfaces Message-ID: <9f115c52.0403090254.3ec6c567@posting.google.com> Hey, I'm trying to interface NeroSDK COM for burning CDRs. Everything works fine, but I have problems figuring out how to handle events which are not in the main COM object. What I mean is that in the makepy generated source I see: 'class _INeroEvents' which correspond to DispatchWithEvents("Nero.Nero", MyEventClass) But I also have class _INeroDriveEvents which is part of: class NeroDrive(CoClassBaseClass): # A CoClass # NeroDrive Class CLSID = IID('{F3FBC8E7-93A3-11D4-8217-A85459000000}') coclass_sources = [ _INeroDriveEvents, ] default_source = _INeroDriveEvents coclass_interfaces = [ INeroDrive2, INeroDrive, ] default_interface = INeroDrive2 Now, usually I would do something like this: nero = DispatchWithEvents("Nero.Nero", MyEventClass) drives = nero.GetDrives(NERO_MEDIA_CD) drive[0].DoSomethingThatGenerateAnEvent() But I don't know how to pass an event handle to handle drive events. This is what I get with GetDrives: >>> a.GetDrives(constants.NERO_MEDIA_CD) Further, in VB, the event functions of the drive are named: drive_OnXXXX() while event functions for nero main objects are named: nero_OnXXXX() I would gladly appreciate any suggestions. Thanks a lot, Omer. From kbk at shore.net Tue Mar 16 01:53:43 2004 From: kbk at shore.net (Kurt B. Kaiser) Date: Tue, 16 Mar 2004 06:53:43 GMT Subject: Exiting Tkinter when using IDLE References: Message-ID: <8765d51dvs.fsf@hydra.localdomain> "Batista, Facundo" writes: > At the end, and taking care of all that considerations, what is the > recommended method to quit? root.destroy() -- KBK From srijit at yahoo.com Thu Mar 18 07:28:23 2004 From: srijit at yahoo.com (srijit at yahoo.com) Date: 18 Mar 2004 04:28:23 -0800 Subject: Statistical Techniques References: <20040316223213.7981.qmail@web60805.mail.yahoo.com> Message-ID: <221d8dbe.0403180428.35bac013@posting.google.com> Hello, Scientific Python (http://dirac.cnrs-orleans.fr/ScientificPython/) has a few statistical utilities. It may not be useful for the requirements stated in the first post. With regards, Srijit fedor wrote in message news:... > Two libraries which will interest can be found at: > > http://rpy.sourceforge.net/ #use r from within python. > http://www.scipy.org/ #scientific libraries. > > Fedor > > > > dont bother wrote: > > > Hey, > > I was just wondering if python has any support modules > > for statistical techniques as Bayesian, Markovian > > Style Models etc. From jacek.generowicz at cern.ch Tue Mar 9 04:55:33 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 09 Mar 2004 10:55:33 +0100 Subject: distutils: non-module compliation products Message-ID: I have a Python package which uses some other shared libraries (written in C++). These shared libraries should be placed somewhere other than in the Python package itself. So far, I am pretending that the shared libraries in question are extension modules, which means that distutils compile them as if they were Python extension modules and place them in the location specified by --install-lib (or options similar to --install-lib). Does distutils provide be any means of a) placing the auxiliary shared libraries outside --install-lib b) compiling the libraries without all the Python extension-module gubbins ? IOW, does distutils have a concept of a compliation product which is not an extension module ? From anthony at interlink.com.au Sat Mar 6 21:01:51 2004 From: anthony at interlink.com.au (Anthony Baxter) Date: Sun, 07 Mar 2004 13:01:51 +1100 Subject: twisted.protocols.sip In-Reply-To: References: Message-ID: <404A828F.5010308@interlink.com.au> SPD wrote: > > Hello: > > I'm new to Python and Twisted but not new to > programming. I need to create a test tools to > send and receive Session Initiation Protocol (SIP) > messages. I understand twisted.protocols.sip > offers this capability but I cannot get a demo > program to work. Does anyone have a basic > example program they can share? Look at shtoom - http://shtoom.sf.net/. It's hardly a 'basic example program', but it's instead a framework for SIP. Anthony -- Anthony Baxter It's never too late to have a happy childhood. From fma at doe.carleton.ca Sat Mar 27 19:54:08 2004 From: fma at doe.carleton.ca (Fred Ma) Date: 28 Mar 2004 00:54:08 GMT Subject: Choosing Perl/Python for my particular niche References: <40652B0D.7C313F77@doe.carleton.ca> Message-ID: <4066233C.56E5D3DD@doe.carleton.ca> "Tassilo v. Parseval" wrote: > > Also sprach Fred Ma: > > > No XML processing or database interaction in what I do. > > Who knows, though. The desire to do certain things grows with the skills one > acquired. You might be right. Some digital CAD data is stored in XML. > This is a strong reason to use Perl. While it may not always be desirable to > toe the line, here it is. The availability of tools that can easily be > integrated into one's own work will save you a lot of work on the long run. I > didn't know that Perl was particularly strong in the field of IC design. If > so, good then. > > Apart from this particular case, it's generally a good thing when pre-written > code exists that can be used. The amount of such code for Perl is immense > (several thousand libraries) and gathered all in one place (the CPAN) with a > unified interface to access and install them and a vast infrastructure built > around it. > > I don't know how much or whether at all the situation for Python has > significantly improved over the recent past. A while ago at least there was no > such thing. SNIP > As with text processing, both Python and Perl offer all the essential things > needed for that. On a cursory glance, the score of them is tied. > > Perl wins when it comes to one-liners and maybe replacing shell scripts. As I > tend to forget the syntax of bash's scripting language easily, I've replaced > it entirely with Perl. > > Perl's bad reputation for big projects is probably due to the variance of > those people using Perl. One large group is sys-admins who use Perl in an > entirely different way as compared to someone building larger systems. > However, there are enough very large Perl projects that show that it can be > used for that just as easily (at least as long as one keeps the sys-admins > away from the source;-). > > > I've seen mention of parrot and perl6, which is quite a ways off. I'm not > > sure how much that should weigh into my decision, since it isn't real yet. > > It shouldn't. Perl6 is mostly yet another leap towards fitness for large > projects. I don't think it will gain much for those more hackish tasks. Also, > no one quite knows when Perl6 will be due. Thanks for the commentary on Perl, for clarifying the source of unweldiness in big Perl projects, as well as its nonuniversality. Fred From mwilson at the-wire.com Fri Mar 5 15:49:00 2004 From: mwilson at the-wire.com (Mel Wilson) Date: Fri, 05 Mar 2004 15:49:00 -0500 Subject: is perl better? References: Message-ID: <8eOSAls/KLhU089yn@the-wire.com> In article , "jon c" wrote: >>>well the cammand is >>> >>>java -hotspot -showversion ...... -classpath loads of entries >>>application-name >>> >>>the total string is 6809 characters long. >>> >>>I do not know the allowed character length (I am using windows 2000) >>> >>>but perl just runs the command fine, whereas python results in >>> >>>The following character string is too long: > >>Is that coming from Windows or Python? If the latter, give us the full >>exception message, which will say from where in Python. Also, try putting >>the long string in a .bat file and running the .bat file by itself and then >>from Python. > >>Terry J. Reedy > > >the error is coming from windows! > >the error message is as I wrote it. > >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?) Avoiding the command line might help. This runs in WinNT 4: #======================================= """test_huge_command.py """ import os command = r'e:\bin\python23\python.exe' pid = os.spawnv (os.P_WAIT, command , [command, 'number_args.py'] + ['arg-%d'%(i,) for i in xrange (1000)] ) #======================================= """number_args.py """ import sys argc = len (sys.argv) print "Called with %d arguments" % (argc,) for i in xrange (min (3, argc)): print "%d\t%s" % (i, sys.argv[i]) for i in xrange (max (3, argc-3), argc): print "%d\t%s" % (i, sys.argv[i]) print #======================================= f:\home\mwilson\projects\python>python test_huge_command.py Called with 1001 arguments 0 number_args.py 1 arg-0 2 arg-1 998 arg-997 999 arg-998 1000 arg-999 Regards. Mel. From hmessinger.removethis at comcast.net Sun Mar 14 15:43:07 2004 From: hmessinger.removethis at comcast.net (Harlan Messinger) Date: Sun, 14 Mar 2004 15:43:07 -0500 Subject: where can I find Paris Hilton video? References: Message-ID: line_guibert-wolff at hc-sc.gc.ca (montezum) wrote: >where can I find Paris Hilton video? Why not ask in a more pertinent newsgroup like, say, rec.knitting? -- Harlan Messinger Remove the first dot from my e-mail address. Veuillez ?ter le premier point de mon adresse de courriel. From fma at doe.carleton.ca Sat Mar 27 22:52:25 2004 From: fma at doe.carleton.ca (Fred Ma) Date: 28 Mar 2004 03:52:25 GMT Subject: Choosing Perl/Python for my particular niche References: <40652B0D.7C313F77@doe.carleton.ca> <406532F7.D56DC671@doe.carleton.ca> <2ae25c6b.0403271814.5d789e9e@posting.google.com> Message-ID: <40664D05.9BB91F46@doe.carleton.ca> Hi, Paddy, Wow, there's more information coming in than I expected. Having a bit of a nonengineering day (at least not at the ground level) keeping up. I did ask for it. Paddy McCarthy wrote: > > Hi Fred, > If there are particular C/C++ packages of algorithms that you use then > you might try searching for the package name +python on the web. You > might find someone who has already turned the library into aPython > module. Actually, verilator (does verilog to SystemC, which is a C++ library that provides HDL simulation capability) is a Perl-based module. As for the glue functionality I need to modify the my original verilog source, there's no specific functionality. I'm still trying to think of ways in which to modify to code to work around the translation limitations of verilator. So the filter will be very much ad-hoc. > There are several Scientific libraries for Python that have good > graphing capabilities as well as speed advantages for certain > operations. - Try installing the Enthought Python distribution for > windows at: http://www.enthought.com/python/ > > Another good page is ScriptEDA: > http://www-cad.eecs.berkeley.edu/~pinhong/scriptEDA/ - I was using the > gate-level verilog parser a month ago. Wow. The screen shots on for enthought are impressive. The software at scriptEDA reminds me that I'm an a newbie in this area. The level to which interfacing environments and languages have been brought boggles the mind. I think that I need to take a bite of Perl and/or Python before I even consider looking at the offerings there with any degree of appreciation. For the computation engine and post-process/graphing, I'll stick with C++/matlab for now, due to lack of thesis time, and because I've got a familiar system (or "idiom"?) setup to use them together. As I mentioned in another post, I'll start with Perl as the starting point, and keep tabs on Python, something that is feasible because of its readability. > On Scripting language choice, I find TCL to be in many EDA tools, but > its datastructures and syntax make it a language I use when I have > to, rather than a language of choice. > > Perl IS used a lot in EDA but I like to think of it as being dangerous > in a lot of hands as great Engineers start scripting larger and larger > applications in Perl and usually end up with something that is hard to > maintain and hard to write. Perl does have its sweet spot - I do like > the `perl -p -i -e` mewthod of making sed like alterations to files > in-place, butthe languages support for subroutine arguments - compared > to Pythons; and the need to compute and pass around references to > lists and hashes for simple nested datastructures - things like that > shout small programs only to me. I got the same impression, but there have been other explanations given in this thread for the unweldiness of big projects, as well as the fact that this is not universal. Myself, I will be using "P..." for glue functionality, so I won't run the risk of creating dangerously unmaintainable code (finger crossed here). Besides, it's for the thesis, which has to be finished soon, so I won't have the problem of looking back a ways to figure out code written long ago. By the time I get to an industrial situation (fingers crossed, since jobs are leaving North America), I hope to have a bit for breathing time to ramp up on Python. > Python is my language of choice for a large amount of programming in > the EDA field (when given the choince :-). > > Perl has a large library, Python has a large library - what you need > to do is do some web searches for libraries in your field to see which > is more appropriate - Well...I did it...verilog to SystemC boils down to verilator unless one has money to shell out. Despite its professed limitations, I am still astounded to read even the help pages. That degree of sophistication, for free. Kind of makes the thesis look like small time, though of course, the challenges are of a different nature. > When I have to write an algorithm from scratch then I do it in Python. > It does get out of the way and allow me to concentrate on the > algorithm most of the time. (Although I wish it had constrained random > generation of integers like Vera or Specman :-). > > I hope I've helped, Paddy. A great deal. Thanks. Fred From tbettio at transnorm.ch Wed Mar 10 18:02:29 2004 From: tbettio at transnorm.ch (Tiziano Bettio) Date: Thu, 11 Mar 2004 00:02:29 +0100 Subject: How to simulate a TTY with popen2? Message-ID: Hi Everybody, I'm stuck trying to write a python module for the vlc videoplayer on linux (http://www.videolan.org). I'm using the popen2 module to open a pipe to the program. If I open the vlc player in a shell it recognizes that I'm running it from a TTY. Same command with popen2-4 and the vlc doesn't seem to find a TTY so it tries to open a gui and fails resulting in ending itself. So here's my question: Is there a way to open a pipe in python imitating a TTY or am I doing something completely wrong? Greetz TC From llothar at web.de Fri Mar 5 19:04:43 2004 From: llothar at web.de (Lothar Scholz) Date: 5 Mar 2004 16:04:43 -0800 Subject: Python Database Driven Web Development References: Message-ID: <6ee58e07.0403051604.3ae4e57a@posting.google.com> "Maru, Mulugeta" wrote in message news:... > What do I need other than Python, Apache, and MySQL to develop a database > driven intranet? Do I need to use any framework or application server? I > f I do please kindly direct me where to go. > Many thanks. > MM > Look at the "webware" project at "www.sourceforge.net" If your application has a lot of logic or cacheable data this should be preferred over Quixote and Zope. From dave at pythonapocrypha.com Thu Mar 11 09:32:55 2004 From: dave at pythonapocrypha.com (Dave Brueck) Date: Thu, 11 Mar 2004 07:32:55 -0700 Subject: Can't connect Postgres to Python References: <404FE8DD.5090202@sstar.com> Message-ID: <04ba01c40775$bfb69ac0$6401fea9@YODA> John wrote: > >> I have tried PostGreSQL, PyGreSQL, pypgsql, psycopg, and PDO and have > >> yet to connect to PostgreSQL 7.4 (.1 in one box, .2 in the other). > >> > >> With PostGreSQL-3.4 and pypgsql-2.4, using setup.py build results in > >> "error: command 'gcc' failed with exit status 1." > >> > >> I couldn't install psycopg-1.1.11 because it asks for PgSql header > >> files; the only one I can identify is postgres.h. > > > > > Dave Brueck wrote: > I've been using pyscopg-1.1.11 with PostgreSQL 7.4 and Python 2.3 on Mandrake > 9.2 and have found it to work really well for my needs. To get it to build I > had to do > > cp -r postgres-7.4/src/include/catalog /usr/local/pgsql/include/ > > to get the headers in the right place. Also had to install mxDateTime first. > > HTH, > -Dave > ******************************************************************************* ***** > This looked like exactly what I need. But after I copied the header files as you instructed, I still got "configure: error: > missing PostgreSQL headers." I tried with and without the trailing /, with and without /catalog, all to no avail. Here's the configure command I used, don't know if it will help you at all: ./configure --with-postgres-libraries=/usr/local/pgsql/lib --with-postgres-includes=/usr/local/pgsql/include --with-zope=/home/dave/Zope261 --with-mxdatetime-includes=/usr/lib/python2.3/site-packages/mx/DateTime/mxDateT ime -Dave From andrew-pythonlist at puzzling.org Tue Mar 9 03:21:19 2004 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Tue, 9 Mar 2004 19:21:19 +1100 Subject: a desired python editor In-Reply-To: <404D5E06.7000303@zoran.com> References: <404D5E06.7000303@zoran.com> Message-ID: <20040309082119.GA6896@frobozz> On Tue, Mar 09, 2004 at 08:02:46AM +0200, Miki Tebeka wrote: > 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. taglist.vim (which requires ctags) can also help with browsing and navigating methods. Even without ctags, 5 is somewhat available thanks to folding. -Andrew. From michele.simionato at poste.it Sun Mar 28 02:42:39 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 27 Mar 2004 23:42:39 -0800 Subject: Appreciation for the importance of readability (was: Choosing Perl/Python for my particular niche) References: <40652B0D.7C313F77@doe.carleton.ca> <40657D14.3FBE7E82@doe.carleton.ca> <106ce9eaed1sk61@corp.supernews.com> Message-ID: <95aa1afa.0403272342.242bae89@posting.google.com> claird at lairds.com (Cameron Laird) wrote in message news:<106ce9eaed1sk61 at corp.supernews.com>... > Some scientists are very successful with "slash-and-burn" > techniques. That manifests itself in this area as "con- > science-free" coding: they write whatever programs get > them the results they're after, and don't care that no > one else can reproduce their results, nor can they them- > selves, six months later. A LOT of that goes on. > > It makes me uncomfortable. A lesson I've learned over > and over is that computer programs live far longer than > you expect. It pays to do 'em better at the beginning, > 'cause you're likely to live with them quite a while. > > I'm not a successful scientist, though; odds are long > against me ever being one. > The relation between programming and science is rather complex. There are still lots of sciences where the programming part is very minor and the "slash-and-burn" technique is the right thing to do. For instance, I have worked with very successful scientists using "slash-and-burn". Their requirements were the following: 1. we want to spend at most 5% of our time doing coding and 95% doing science; 2. our group is composed by two persons and our code will never be released; 3. if a Ph. D. student reach the group and has to study the code, we will explain it to him in person; 4. the largest program we will ever write is a thousand lines long; for the rest we will use standard routines and write as little code as possible; 5. we don't care at all about fancy graphics: the output will be a list of numbers write on a file and displayed by gnuplot; 6. all we care is numerical performance in floating point computations; the logic of the program will be trivial. They actually used old fashioned Fortran 77 and I think they made the perfect choice given their requirements; they essentially had to do numerical integrations and solving differential equations, tasks were Fortran is incredibly strong. Other persons I know doing particle Physics and doing a good deal of programming (good deal means something like 50% of their time spent on programming; spending more than 50% means that you are actually a programmer, and scientists don't want to do that) were using a mixture of Fortran and C. Here I am referring to people doing numerically intensive tasks; I have seen a trend to switch to C++ for large projects, since there is a perception than C++ scales better than Fortran. In any case, the core routines are still in Fortran and always will be. For scripting tasks, scripting languages are used; I know a few astronomers who were using Perl to control the telescope movement. Many physicists/astronomers use Python too. Specialized languages and tools (Mathematica, Maple, Matlab, Octave, Yorick, etc. etc.) have their place. Finally, it may be weird in XXI century, but there are still scientists not doing programming. For instance, the only programming language I used for my scientific research was Latex, to write the papers; my reseach tools were paper and pencil and blackboard, which are still as effective as ever. Michele Simionato From skip at pobox.com Fri Mar 12 12:42:06 2004 From: skip at pobox.com (Skip Montanaro) Date: Fri, 12 Mar 2004 11:42:06 -0600 Subject: Deprecating reload() ??? In-Reply-To: <8ok3505b3b3g22bk8ci6iagptqav2cfi6r@4ax.com> References: <40514A48.50907@domain.invalid> <09b350henbtk9vnai0v7fhtbsqbmubl7vn@4ax.com> <7cj4c.2733$G3.21896@localhost> <8ok3505b3b3g22bk8ci6iagptqav2cfi6r@4ax.com> Message-ID: <16465.63086.218976.55570@montanaro.dyndns.org> >> Reload is not broken, and certainly shouldn't be deprecated at least >> until there's a better solution that won't suffer from reload's one >> problem, IMHO, which is that it surprises some people by its >> behaviour. David> It's worse than just a surprise. It's a serious problem when David> what you need to do is what most people are expecting -- replace David> every reference to objects in the old module with references to David> the new objects. The problem becomes a near impossibility when David> those references are scattered throughout a multi-module program. This is where I think your model of how Python works has broken down. Objects don't live within modules. References to objects do. All objects inhabit a space not directly associated with any particular Python namespace. If I execute import urllib quote = urllib.quote reload(urllib) quote and urllib.quote refer to different objects and compare False. (I suppose the cmp() routine for functions could compare code objects and other attributes which might change.) The object referred to by urllib.quote is not bound in any other way to the urllib module other than the reference named "quote" in the urllib module's dict. reload() simply decrements the reference count to urllib, which decrements the reference count to its dict, which causes it to clean up and decrement the reference count for all its key/value pairs. David> For the *exceptional* case where we want to pick and chose which David> objects to update, seems like the best solution would be to add David> some options to the reload function. David> def reload(, objects = '*'): David> The default second argument '*' updates all references. '?' David> prompts for each object. A list of objects updates references to David> just those objects automatically. 'None' would replicate the David> current behavior, updating only the name of the module itself. If you want to implement this and all you're interested in are class, function and method definitions and don't care about local variables I think you can make a reasonable stab at this. I wouldn't recommend you overload reload() with this code, at least not initially. Write a super_reload() in Python. If/when you get that working, then rewrite it in C, then get that working, then you're free to recommend that the builtin reload() function be modified. David> I don't understand. My assumption is you would normally update David> all references to the selected objects in all namespaces. As Denis Otkidach pointed out in response to an earlier post of mine, objects on shared free lists can't be rebound using this mechanism. I think it's safe initially to restrict super_reload() to classes, functions and methods. Skip From dmq at gain.com Mon Mar 15 15:18:34 2004 From: dmq at gain.com (David MacQuigg) Date: Mon, 15 Mar 2004 13:18:34 -0700 Subject: Deprecating reload() ??? References: <6kk6501shlve52ds2rjdopa73jhpchprg3@4ax.com> Message-ID: On Mon, 15 Mar 2004 12:28:50 -0600, Skip Montanaro wrote: > >> 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. > > Dave> If you reload a module M1, and it has an attribute M1.x, which was > Dave> changed from '1' to '2', we want to change also any references > Dave> that may have been created with statements like 'x = M1.x', or > Dave> 'from M1 import *' If we don't do this, reload() will continue to > Dave> baffle and frustrate new users. Typically, they think they have > Dave> just one variable 'x' > >Like I said, I think that sort of change will be relatively rare. I think wanting to change numbers in a reloaded module is very common. >Just tell your users, "don't do that". The problem is the complexity of "that" which they can and cannot do. Even renouned text authors don't seem to explain it clearly. I'm opting now for "don't do anything" to try and make it simple. By that I mean - Don't expect reloads to update anything but the reference to the reloaded module itself. This is simple, just not very convenient. > Dave> I'm having trouble understanding the benefit of using shared > Dave> objects for simple numbers and strings. > >Can you say "space and time savings"? Ints are 12 bytes, strings are 24 >bytes (plus the storage for the string), None is 8 bytes. It adds up. Maybe you can save a significant amount of memory by having all the *system* modules share a common 'None' object, but when a user explicitly says 'M1.x = None', surely we can afford a 8 bytes to provide a special None for that reference. I'm no expert on these implementation issues, but these numbers seem small compared to the 512MB in a typical modern PC. I suppose there are some rare cases where you need to create an array of millions of references to a single constant. In those cases the debug mode may be too much of a burden. In general, we ought to favor simplicity over efficiency. >More importantly, small ints, interned strings and None would constantly be >created and freed. The performance savings of sharing them are probably >much more important. Again, as a non-expert, this seems strange. The burden of comparing a new object to what is already in memory, using an '==' type of comparison, must be comparable to simply creating a new object. >Finally, from a semantic viewpoint, knowing that None is defined by the >language to be a singleton object allows the more efficient "is" operator to >be used when testing objects against None for equality. If you allowed many >copies of that object that wouldn't work. We would lose some, assuming '==' for these small obects is slower than 'is', but then you would not have to test '==' on a large number of objects already in memory each time you define a new integer or small string. > Dave> We should at least have a special 'debug' mode in which the hidden > Dave> sharing of objects is disabled for selected modules. > >It might help with your problem but would change the semantics of the >language. I assume you are referring to the symantics of 'is' when working with small objects like None, 2, 'abc'. I agree, that is a problem for the proposed debug mode. I don't see a way around it, other than warning users not to expect modules imported in the debug mode to optimize the sharing of small objects in memory. Use 'x == 2' rather than 'x is 2' if you intend to use the debug mode. -- Dave From skip at pobox.com Thu Mar 18 10:15:58 2004 From: skip at pobox.com (Skip Montanaro) Date: Thu, 18 Mar 2004 09:15:58 -0600 Subject: dictionary wart In-Reply-To: References: <6b17fa95.0403180441.a747b15@posting.google.com> <7xr7vquwpo.fsf@ruckus.brouhaha.com> Message-ID: <16473.48430.533574.268507@montanaro.dyndns.org> Jesper> For instance in a dictionary which is mapping strings to Jesper> integers (or lists), I would like to do Jesper> a[my_key]+=5 Jesper> expressing that with get() would be awkward. Though not *terribly* awkward: a[my_key] = a.get(my_key, 0) + 5 I agree it's a bit clumsy, but I think it's the best you can do if you don't want to subclass dict (I don't really like {}.setdefault()): class ddict(dict): def __init__(self, default=None, init=True): self.default = default self.init = init def __getitem__(self, key): if key in self: return self.get(key) else: if self.init: self[key] = self.default return self.default d = ddict(default="Jesper", init=False) print "abc" in d print d["abc"] d = ddict(default=0) d["abc"] += 5 print d["abc"] I suspect there's more to it than I've implemented, but that should get you pointed in the right direction. Skip From loic at fejoz.net Fri Mar 26 03:02:43 2004 From: loic at fejoz.net (Yermat) Date: Fri, 26 Mar 2004 09:02:43 +0100 Subject: How do i cast a string to be used as a module? In-Reply-To: <9kM8c.46388$Bg.39277@fed1read03> References: <9kM8c.46388$Bg.39277@fed1read03> Message-ID: sean a ?crit : > In article , > sean at sands.beach.net (Sean Berry) writes: > >>I don't know that this partilarily bad programming, >>but I was interested in doing the following. >> >>def functionname( module, var1, var2 ): >>import module >> >>I would like to be able to pass the module name >>as an argument and have the module imported as a result. >> >>For instance... functionname( os, "1", 234) >> >>Thanks for any help. > > > Thanks for the help, and exec("import "+modname) > does indeed import the module. > > But, what if I want to call a function from within this > module that takes as an argument the name of a module. > > For example if I was making a module like the following > > import inspect > > def functionname( modname ): > exec("import "+modname) > s = inspect.getsource( modname ) > return s > > How do I cast modname as a module name and not as a string? > > Thanks. > > >>> exec("import chunk") >>> globals()["chunk"] or even simplier : >>> __import__("chunk") Yermat From jdhunter at ace.bsd.uchicago.edu Wed Mar 24 15:41:52 2004 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Wed, 24 Mar 2004 14:41:52 -0600 Subject: Simple raster graphics ? How do I ... In-Reply-To: (Ray Molacha's message of "Wed, 24 Mar 2004 18:02:25 GMT") References: Message-ID: >>>>> "Ray" == Ray Molacha writes: Ray> Hi Everybody. I'm learning Python on a Windows computer, Ray> using PythonWin. Ray> I'd like to be able to do some simple raster graphics, like Ray> clearing the screen and plotting a point of some color. I Ray> want to plot some fractals and math functions just for fun. I Ray> understand the math ok -- I don't know how to do simple Ray> raster graphics. matplotlib may do what you want - http://matplotlib.sourceforge.net. If you take fractal data and load it into an MxN Numeric array, you can display it with a colormap with the plotting command imshow (image show). To plot simple math functions, you can do things like t = arange(0.0, 1.0, 0.01) plot(t, sin(2*pi*t)) It's not a low level drawing program, but it is a high level plotting program that may do what you need. You can use it to create simple images to view in the viewer of your choice, or use of the GUI interfaces (GTK, WX, Tk) and to view your figure with navigation controls. Check the screenshots section for samples plots and the scripts that produced them http://matplotlib.sourceforge.net/screenshots.html If you want low level control over raster graphics, you have lots of choices. pygtk with gtk.gdk.Drawable and gtk.DrawingArea is one that is fast and cross platform; it also comes with nice widgets. A wx canvas is another alternative, or PIL, or ..... JDH From ketulp_baroda at yahoo.com Thu Mar 25 07:59:55 2004 From: ketulp_baroda at yahoo.com (ketulp_baroda at yahoo.com) Date: 25 Mar 2004 04:59:55 -0800 Subject: sorting the list by inner elements References: Message-ID: John Hunter wrote in message news:... > >>>>> "ketulp" == ketulp baroda writes: > > ketulp> Hi, all I want to sort the list,the form of my list is > > ketulp> name_city_list=[['jack','new > ketulp> york'],['mac','london'],['alice','paris']] > > ketulp> all inner list has same format i.e first is name and > ketulp> second is city. now I want to sort it by the second > ketulp> element of the inner list(by city name). > > ketulp> i.e after sorting my list should be like this > > The usual way is to simply reverse the tuple, sort, and then reverse > back > > tmp = [ (city, name) for name, city in name_city_list] > tmp.sort() > name_city_list = [ (name, city) for city, name in tmp] > > This is usually faster than writing a custom comparison func for sort. > > JDH Hi, John I like ur idea but this will work for only when inner list has only two elements. if inner list has five elements and i want to sort the whole list by 3rd element then how can i do this ? need ur help, regards From oleksik at galaxy.uci.agh.edu.pl Tue Mar 30 11:38:11 2004 From: oleksik at galaxy.uci.agh.edu.pl (Pawel Oleksik) Date: Tue, 30 Mar 2004 16:38:11 +0000 (UTC) Subject: pyrex+Numeric Message-ID: Hi, I have no idea, how to properly declare/use Numeric functions in pyrex. For example the code below causes segmentation fault: --in pyrex-------------- [... some lines from Pyrex-0.9/Demos/numeric_demo.pyx, plus: ] cdef extern from "Numeric/arrayobject.h": object PyArray_ContiguousFromObject ( object, int, int, int ) def contiguous_tst ( ArrayType A ) : if A.nd != 1 : raise ValueError("1D array expected.") B = PyArray_ContiguousFromObject(A,A.descr.type,1,1) print '***' return B --in python-------------- >>> from Numeric import * >>> A = array((1,2,3,4,5)) >>> contiguous_tst(A) My environment is 'quite new': python 2.3.3, Numeric 23.1, pyrex 0.9. I hope you will give me some light on this problem, please. Best regards p.o. From and-google at doxdesk.com Wed Mar 24 15:50:02 2004 From: and-google at doxdesk.com (Andrew Clover) Date: 24 Mar 2004 12:50:02 -0800 Subject: Getting username and passwd from IE References: <6b13855b.0403240446.7206703b@posting.google.com> Message-ID: <2c60a528.0403241250.9a8b572@posting.google.com> mgb at mgbeckett.com (Martin Beckett) wrote: > self.send_response(401) > self.end_headers() > return Don't know about BaseHTTPServer in particular, but in general 401 must be used in conjunction with the WWW-Authenticate response header, or the browser won't know what kind of authentication to send. self.send_header('WWW-Authenticate', 'basic realm="Fab site"') -- Andrew Clover mailto:and at doxdesk.com http://www.doxdesk.com/ From sross at connectmail.carleton.ca Wed Mar 24 08:56:25 2004 From: sross at connectmail.carleton.ca (Sean Ross) Date: Wed, 24 Mar 2004 08:56:25 -0500 Subject: sorting the list by inner elements References: Message-ID: wrote in message news:f046efac.0403240543.65a49ba1 at posting.google.com... > Hi, all > > I want to sort the list,the form of my list is > > name_city_list=[['jack','new york'],['mac','london'],['alice','paris']] > > all inner list has same format i.e first is name and second is city. > now I want to sort it by the second element of the inner list(by city name). > > i.e after sorting my list should be like this > > name_city_list=[['mac','london'],['jack','new york'],['alice','paris']] > > how can I do this, > > any way out ? name_city_list.sort(lambda x, y: cmp(x[1],y[1])) From kamikaze at kuoi.asui.uidaho.edu Sun Mar 7 20:36:28 2004 From: kamikaze at kuoi.asui.uidaho.edu (Mark 'Kamikaze' Hughes) Date: 8 Mar 2004 01:36:28 GMT Subject: "print" as function not statement References: Message-ID: Paul Prescod wrote on Sun, 07 Mar 2004 16:57:29 -0800: > Problems with "print" > New users are constantly asking how to print elements without > trailing whitespace. And they are then constantly told to use formatted strings, which are the next logical step up: print "%s%s" % (a, b) If the trailing newline is the problem: sys.stdout.write("%s%s" % (a, b)) > The use of a trailing comma to disable newline has no clear > relation to any other syntax elsewhere in Python. It is familiar to BASIC programmers, but it's certainly not a pythonic idiom. > The cheveron syntax is similarly unique. (">>object", aka "chevron", for those who don't recognize that term) It is familiar to Unix programmers for redirecting output. It's not pythonic, but not entirely alien. > "print" is the one of only two statement-generating keywords > that is not a flow-control or scope-control operator. Why does this matter? > Because print is a statement, it cannot be used in contexts > like list comprehensions and lambda functions. You can use sys.stdout.write() instead, or if you like print's intelligent spaces, you write a minimal utility function: def show(s): print s, return s > 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. That will never happen, because it would break an enormous amount of code. "print" means "display on the console" in most programming languages. Printing to paper is uncommon and hopefully becoming less common. What else are you going to do in a function called "print"? > "print" is one of the first thing a Python newbie learns but > learning it teaches very little about the rest of the language. > All of the idiosyncratic syntax you learn will never be seen > again elsewhere in the language and 99.9% of non-control flow > operations are performed with functions, not statements. Newbies are not taught the entire syntax of print at once. They learn to assemble a few comma-delimited items, and it "just works" at putting spaces and newlines in the right place. The more advanced uses were probably inappropriate additions. Eliminating those so print is a simple construct again would be better than removing and replacing it, but I don't see a convincing case for it. > 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: -1 Anything print isn't suitable for at present, sys.stdout.write() and formatted strings are. -- Mark Hughes "Doing the impossible makes us mighty." -Captain Malcolm Reynolds, Firefly From kkto at csis.hku.hk Wed Mar 10 20:54:45 2004 From: kkto at csis.hku.hk (Isaac To) Date: Thu, 11 Mar 2004 09:54:45 +0800 Subject: Extending Python Syntax with @ References: Message-ID: <7iznao6tcq.fsf@enark.csis.hku.hk> >>>>> "David" == David MacQuigg writes: David> Wouldn't it be nice, for example, if instead of special keywords David> like 'lambda' and 'yield', we had used '@(args)' and '@return'. David> ( No, I'm not advocating we go back and change what has been David> done.) In both these cases, we had a well-established syntax David> that needed a slight variation. I don't think it is an improvement. If you get puzzled reading a program with lambda expressions, you remember that you conveniently skipped reading "lambda" in the docs. If you read a program with generator, you know the "yield" section at the new Python docs will help. Both is very clear mentally: you can easily recall what you've learnt. If you read a program containing silly @, where should you look? And will you still remember it after 2 years of programming solely in Perl? I think everybody trying to add language construct should remember "explicit is better than implicit". David> The 'lambda function' for example, was needed to cram a small David> block of code into a tight space. By saying '@x,y:' instead of David> 'lambda x,y:', we not only avoid the need for a new keyword, but David> we better serve the purpose of tightly packing some code. We David> would also avoid mystifying beginners. "It has no magic meaning. David> It's just a way to write a function without a name." There is no real need to "cram a small block of code into a tight space": your space is unlimited when writing programs. There are times when you should want using less space: when you are expressing a sequence of really simple things. If you are writing something as complicated as a "lambda x, y: ..." and that "..." can't be put into your program conveniently, the odds are that it really takes effort to understand that part. Then I don't think that one really should try to put it into less space. Regards, Isaac. From sross at connectmail.carleton.ca Mon Mar 22 15:22:14 2004 From: sross at connectmail.carleton.ca (Sean Ross) Date: Mon, 22 Mar 2004 15:22:14 -0500 Subject: explicit variable scoping References: Message-ID: "David MacQuigg" wrote in message news:blbu505vrj35i52ari8a0uivja0pp7a9qu at 4ax.com... > If we want to set variables in intermediate scopes, I would prefer a > syntax like: > > b = 1 > def f(): > a = 2 > def g(): > global.f.a = 3 > global.b = 4 > > Of course, this means we also have to allow functions to have > attributes. > Hi. I know what you meant but, technically, functions can and do have attributes, just not the kind you've mentioned (where the locals become attributes of their function): >>> def f(): pass ... >>> f.a = "A" >>> f.a 'A' >>> Just so things are clear for those following along ... Sean From peter at engcorp.com Thu Mar 11 10:41:09 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 11 Mar 2004 10:41:09 -0500 Subject: Python style guidelines In-Reply-To: <405087fc$1@pfaff2.ethz.ch> References: <3064b51d.0403101112.3449e987@posting.google.com> <405035a3$1@pfaff2.ethz.ch> <405087fc$1@pfaff2.ethz.ch> Message-ID: Josef Meile wrote: >>>>>> 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. I believe it's more likely they just forgot what find() did return, as they were writing the code. I've done the same, thinking it was a boolean, not thinking that it returned a negative but that negatives were considered false. -Peter From dmq at gain.com Mon Mar 15 23:17:52 2004 From: dmq at gain.com (David MacQuigg) Date: Mon, 15 Mar 2004 21:17:52 -0700 Subject: Result of ``a is b'' References: <40200384.0403151632.35496ee6@posting.google.com> Message-ID: On 15 Mar 2004 16:32:25 -0800, axelboldt at yahoo.com (Axel Boldt) wrote: >is there a rationale for the following behavior: > > >>> a = (1,2) > >>> b = (1,2) > >>> a is b > False > >>> a = "12" > >>> b = "12" > >>> a is b > True Here's another one: >>> x = 'akdijfkdienlskfi' >>> y = 'akdijfkdienlskfi' >>> x is y True >>> x = 'a b' >>> y = 'a b' >>> x is y False >>> x == y True >>> It has to do with how Python decides which strings to "internalize" and make shared objects in order to save space. This is only a problem with immutable objects. Others cannot be shared like this. My suggestion is to *never* use 'is' with these objects unless you really need the fact that it is faster than '==' and you test it thoroughly for the kind of objects you will be comparing. -- Dave From jepler at unpythonic.net Tue Mar 23 13:48:53 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Tue, 23 Mar 2004 12:48:53 -0600 Subject: Suitability of python to specific project In-Reply-To: <200403231722.i2NHMCb27223@omail2.walla.co.il> References: <200403231722.i2NHMCb27223@omail2.walla.co.il> Message-ID: <20040323184852.GJ24314@unpythonic.net> If you want to run a program on a modern computer, you'll never be free from "small bugs [that] appear on one computer and not on another". You can't choose a programming language that somehow makes the OS not flaky and prone to truly bizarre failures. Back in the days of 4K basic (or on a modern microcontroller with just a few kwords of program space), sure, but not when your OS, network stack, windowing system, widget set, and language interpreter are all at least a half a million lines big... when any major component could actually be one of a half dozen or more similar but not identical parts (CPU, video card, network interface, etc), and the performance or capacity of the components might vary 10:1 or even 100:1 across machines you'd like to support. That said, I find my Python and Python+Tkinter programs to run well on the systems I commonly use, mostly Linux but occasionally Windows. On the other hand, my worst experiences have come when I've tried to use Python with proprietary Microsoft components (MS Access)... Jeff From jepler at unpythonic.net Mon Mar 8 09:50:18 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 8 Mar 2004 08:50:18 -0600 Subject: Working around a lack of 'goto' in python In-Reply-To: References: Message-ID: <20040308145018.GC12662@unpythonic.net> [Attribution helpfully discarded by Mr. Binns] wrote: > > Yuck. Bletch. Barf. > On Sun, Mar 07, 2004 at 09:09:58PM -0800, Roger Binns wrote: > Care to expand on that? Start with this code: for x in range(10): for y in range(10): if hit(x, y): break 2 Now, add z: for x in range(10): for y in range(10): for z in range(10): if hit(x, y, z): break 2 Look, a bug! With this "feature", you have to scan the entire body of the loop looking for a numeric break/continue if you're going to change the indentation level, then increment or decrement the number. If somebody was holding a gun to my head, I'd suggest that a way to name loops was preferable to both this idiom and having my brains blown out: for x in range(10) label outermost: (other intervening control statements) break outermost I believe this abomination can even be done without actually reserving "label" as a keyword, just like "from" in "import ... from", except for the problem that the somewhat perverse for x in 1, label outermost: would be 2-tuple (1, label) followed by an illegal token "outermost". .. and in the absence of coercive force, I'd -1 this suggestion too. Jeff From lbates at swamisoft.com Mon Mar 15 18:16:23 2004 From: lbates at swamisoft.com (Larry Bates) Date: Mon, 15 Mar 2004 17:16:23 -0600 Subject: dislin / PIL / cropping EPS References: Message-ID: Take a look at imagemagick (which has python interface). http://www.imagemagick.org/ I don't know for sure about clipping EPS, but when I looked at it, I thought it was more powerful than PIL. If the ultimate destination of the output is actually .PDF instead of Word, take a look at ReportLab and ReportLab Graphics. Depending on what the graphics are like out of dislin, you might be able to do it all in ReportLab. www.reportlab.org -Larry Bates "Duncan Smith" wrote in message news:c32t8r$bc7$1 at newsg3.svr.pol.co.uk... > Hello, > Can anyone advise me how to crop an EPS image generated by dislin. > I can't figure out how to crop the image before generating it. Using PIL to > crop the generated image I get an IOError (apparently because I'm using > Windows). I could use other file formats, but I'm not too keen on the > results I'm getting from using e.g. .tif. Basically I need to copy > (publication quality) images created in dislin and paste them into word > documents (but not manually). Cropping after pasting would be an option, > but I haven't (yet) played around with COM enough to know if this is easily > done. Cheers. > > Duncan > > From rajarshi at presidency.com Sat Mar 6 12:47:06 2004 From: rajarshi at presidency.com (Rajarshi Guha) Date: Sat, 06 Mar 2004 12:47:06 -0500 Subject: generating points on a grid - efficiently Message-ID: Hi, I've written some code that takes a N lists of numbers (corresponding to axes) and generates a list of grid points (N dimensional grid) for the supplied axes. So as an example say my two axes are defined as v1 = [1,2,3] v2 = [1,2,3] My code will return to me a list of points: (1,1), (1,2), (1,3) ....(3,1), (3,2), (3,3) and so on. For 3 axes, I would obtain 27 points and so on. I've included the code below. My questions: Firstly, the code runs in exponential time. Is there any way to rewrite it to make it more efficient? It seems that this could be formulated as a recursive problem but I can't seem to get at it. Secondly, it seems that the repeated use of copy.deepcopy() is very wasteful? Is there a way I can get around it? Thanks, ########################### import copy def extendgp(g,v): newg = [] if not g: for i in v: newg.append( [i,] ) return newg for i in g: for j in v: x = copy.deepcopy(i) x.append(j) newg.append(x) return newg def gengrid(axislist): grid = [] for axes in axislist: grid = extendgp( grid, axes ) return grid if __name__ == '__main__': v1 = [1,2,3] v2 = [1,2,3] v3 = [1,2,3] grid = gengrid( (v1,v2,v3) ) print grid From ville at spammers.com Wed Mar 31 07:04:15 2004 From: ville at spammers.com (Ville Vainio) Date: 31 Mar 2004 15:04:15 +0300 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: >>>>> "Didier" == Didier Morandi writes: Didier> I do not read answers to questions I did not post, so I don't care Didier> about "unlearn a lifetime of knowledge about narrative flow in Didier> content". So essentially Usenet should be a free Q&A automaton, where people post questions and Usenet fairies go around answering them? Everybody takes, nobody gives? I believe such service should cost you money... Note that many read the newsgroup w/o having any questions of their own, perhaps wanting to learn from the questions of others or see if there is some interesting discussion going on. Top posting kills all that. It surprises me how much flammage people need before correcting the error of their ways these days. Top posting might be forgivable for a newbie/grandmother who is just trying his hand w/ Usenet for the first time, but repeat offenders should be reprimanded. -- Ville Vainio http://tinyurl.com/2prnb From skip at pobox.com Sat Mar 13 19:54:18 2004 From: skip at pobox.com (Skip Montanaro) Date: Sat, 13 Mar 2004 18:54:18 -0600 Subject: Safety of pickle? In-Reply-To: References: Message-ID: <16467.44346.562417.937397@montanaro.dyndns.org> Leif> Is it safe to unpickle data from an untrusted source? No. Leif> Is it safe to use the values returned without lots of annoying Leif> type checking? Depends upon how much validation you did before unpickling. Skip From missive at frontiernet.net Thu Mar 11 18:19:53 2004 From: missive at frontiernet.net (Lee Harr) Date: Thu, 11 Mar 2004 23:19:53 GMT Subject: psycopg problem References: <40501FA1.6030801@geochemsource.com> Message-ID: > 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? > > You may want to ask this question on a postgres list. My understanding is that this is just the way it works in postgres. Once there is an error condition in the transaction you cannot continue on and commit. You have to rollback. From benoit.merouze at epita.fr Mon Mar 15 16:40:43 2004 From: benoit.merouze at epita.fr (ben-) Date: Mon, 15 Mar 2004 21:40:43 +0000 Subject: Python and Microsoft Excel files Message-ID: <20040315214043.2814f549.benoit.merouze@epita.fr> I want to import and export Microsoft Excel files. Are there libraries for this ? If someone have advices to give, I'm interested ! -- M?rouze Beno?t EPITA SIGL Promotion 2005 benoit.merouze at epita.fr benoit.merouze at gouarec.com From bh at intevation.de Wed Mar 17 05:34:14 2004 From: bh at intevation.de (Bernhard Herzog) Date: Wed, 17 Mar 2004 11:34:14 +0100 Subject: Handling geoTIFF files References: <23ae7099.0403170210.540888cd@posting.google.com> Message-ID: ally_burnett at yahoo.co.uk (alastair) writes: > I've read about the Python Imaging Library (PIL) which seems to do > what I need with TIFF files. I was wondering if anyone knows if this > library will work with geoTIFF files or if there are any other methods > of doing what I need. You might want to have a look at GDAL, a library for handling geographic raster data which comes with Python bindings: http://gdal.maptools.org/ Bernhard -- Intevation GmbH http://intevation.de/ Skencil http://sketch.sourceforge.net/ Thuban http://thuban.intevation.org/ From abcdebl2nonspammy at verizon.net Sun Mar 7 02:09:09 2004 From: abcdebl2nonspammy at verizon.net (David Lees) Date: Sun, 07 Mar 2004 07:09:09 GMT Subject: Incompatibility between psyco 1.2 and pythonwin? In-Reply-To: References: Message-ID: David Lees wrote: > I just downloaded psyco 1.2 and it seems to work fine with IDLE. But it > crashes out of Pythonwin with a message: 'pythonwin.exe has generated > errors and will be closed by windows'. It crashes after I type the line > 'psyco.full()' and hit return. > > I am running PythonWin 2.3.3 on a Windows 2000 PC. > > david lees > Question - Is there a known incompatability between psyco release 1.2 and pythonwin? From curzio.basso at unibas.ch Fri Mar 19 07:15:34 2004 From: curzio.basso at unibas.ch (Curzio Basso) Date: Fri, 19 Mar 2004 13:15:34 +0100 Subject: Basic Inheritance Question In-Reply-To: References: Message-ID: <405ae467@maser.urz.unibas.ch> Matthew Bell wrote: > Essentially, then, if I've inherited another class, how > do I create an instance of the class I've inherited such > that methods I haven't overrriden will still work, and > how can I then refer to that instance from my subclass? > I can guess it's something to do with "self" but exactly > what, I'm really at a loss. If I got it right, you should have: class A: def __init__(self): self.data=[] class B(A): def __init__(self): A.__init__(self) self.data=[1,2,3] cheers From mjackson at alumni.caltech.edu Tue Mar 16 17:07:33 2004 From: mjackson at alumni.caltech.edu (Mark Jackson) Date: 16 Mar 2004 22:07:33 GMT Subject: Is Python type safe? References: <221d8dbe.0403161043.52406195@posting.google.com> Message-ID: Roy Smith writes: > In article , > Peter Hansen wrote: > > > Roy Smith wrote: > > > > > Neither C++ nor Python will let you add the integer 3 to the string > > > "four", but use different mechanisms to prevent it. Oddly enough, Java > > > (in a perl-like, but admittedly convenient, stab at automagic > > > polymorphism) will let you add them. No clue what C# does. > > > > It's been a while since I Java-ed, but doesn't it "append" them, as in > > convert the integer to a string and then join the two strings, rather > > than "add" them (which I take to mean "calculate the sum of")? > > > > (That's probably what you meant, but I'm just checking. I'd be > > surprised to find that Java actually performed the string-to-value > > conversion implicitly.) > > > > -Peter > > Yes, "four" + 3 ==> "four3" > > I could imagine a language where "4" + 3 ==> 7 (actually, I don't have > to imagine it, all I need do is look at perl). But, a language where > "four" + 3 ==> 7 would be pretty bizarre :-) And would the result of "quatre" + 7, say, depend on the locale setting? -- Mark Jackson - http://www.alumni.caltech.edu/~mjackson The supreme misfortune is when theory outstrips performance. - Leonardo da Vinci From eric at zomething.com Sat Mar 6 17:52:22 2004 From: eric at zomething.com (Eric @ Zomething) Date: Sat, 6 Mar 2004 14:52:22 -0800 Subject: A Byte of Python - Python Book / Tutorial Message-ID: <20040306145222.1240993028.eric@zomething.com> Oren quoted and commented: > """...Python is talked about as the 100-year language. Why? Because they say it > will be the only programming language in use a 100 years from now... > """ > > I think I am as enthusiastic about Python as anyone else on this newsgroup > but this gushing praise of Python in the preface makes me a bit uneasy. If > I were new to Python it would be a complete turnoff for me "...oh no, yet > another religious fanatic..." > > I think it may be better to tone it down a little to avoid alienating > potential new converts to our secret cult planning world domination ;-) Re: World domination and secret cults [note there is nothing sexual in my use of these words though if I wanted this post to show up in Google, I might use the word sex several times, and show kinky programming methods which dominate more submissive languages] In terms of achieving world domination it is more effective to announce that you are dominating the world than to announce that you will dominate the world. for example: 99.99% of all PCs run Microsoft Windows MySQL is the most widely used database for internet sites The world's leading search engine was built with Python Girls, girls, girls Python is the most powerful programming language with modern object orientation and a tie-in to British Humor Playboy Playmates surveyed who use objects preferred Python programmers two-to-one over all other programmers, to the best knowledge of the staff of http://www.WorldDomPy.localhost.com I think programming languages, like other things, will diverge further. What programming language will be used to program each spec of a dust cloud of mesh-networking sensors? Probably not an interpreted language. On the other hand, for platforms that interface to humans, relying on a language like Python seems to make more sense with each passing month. "Python is the dominant language for programming productivity." EP Appreciative of all decent Python docs, thanks for the effort Swaroop! A little non-linearity in thought can be good, right? Though it is likely to raise some exceptions... From python-url at phaseit.net Sun Mar 28 22:07:18 2004 From: python-url at phaseit.net (Cameron Laird) Date: Mon, 29 Mar 2004 03:07:18 -0000 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Mar 28) Message-ID: <106f4n6ahljus48@corp.supernews.com> QOTW: "I think the best way of lobbying for Python adoption is to write good software with Python." -- Jarek Zgoda "The biggest problem I have now is convincing people that just because something's not already in the standard library doesn't mean it belongs there." -- Guido van Rossum, paraphrased by John Belmonte So far, over 320 have appeared for PyCon, currently in progress. http://www.sauria.com/~twl/conferences/pycon2004/ http://www.python.org/pycon/dc2004/schedule.html Prothon justly dominated the week's discussion. It's hard to summarize all the valuable insights illuminated http://groups.google.com/groups?q=prothon+group:comp.lang.python* Note the recurring attention to whether metaclasses are a symptom of health, and the path from there back to http://www-106.ibm.com/developerworks/linux/library/l-pymeta2/ as well as Michele Simoniato's new real-life example http://groups.google.com/groups?th=ab312bd057b6e9c BitTorrent's probably the most widely-used Python program http://altis.pycs.net/2004/03/24.html#a105 How does one scale? Hung Jung Lu presents a tour de force based on a novel axiomatization of "all human intellectual activities", and proceeds through a remarkable density of apt apothegms ("focus ... on how to make your system maintainable") to the conclusion that Python's purity and metaprogrammability make it "good but still not good enough" http://groups.google.com/groups?frame=left&th=abdc11f026b3e9bd Other highlights of the same attention to programming in the large include Bill Rubinstein's testimony on deep practical testing, and Stefan Axelsson's that there's a lot more to typing systems than C++ (for example) offers. Phil Pfeiffer presents important evidence on how far from "good enough" Python is http://www.python.org/pycon/dc2004/papers/8/Twelve%20Thousand%20Test%20Cases%20and%20Counting.htm One way to enhance Pythonian engineering is with advanced tools such as PyNSource, a "UML reverse engineering and modelling" application http://www.atug.com/andypatterns/pynsource.htm PyNSource has much of the "industrial strength" PyReverse, Boa, and PyUt lack. Yet another breakthrough in scalability is doctest, most recently explained by Tim Peters and Jim Fulton in their PyCon presentation http://www.python.org/pycon/dc2004/papers/4/PyCon2004DocTestUnit/ Christian von Essen breaks down the "how do I #include?" question into recipes which threaten newcomers minimally http://groups.google.com/groups?th=5fd9f24976eb836f One step farther, and they've arrived at http://groups.google.com/groups?frame=left&th=5ac63bb4fb20cb3c ZODB for complete beginners http://www.informit.com/articles/article.asp?p=23413 We deal with texts, so it's always timely to learn from George A. Miller and colleagues http://groups.google.com/groups?selm=fc91898a.0403250748.5ceb5a41%40posting.google.com What do Python and AppleScript have to do with each other? Mathieu Fenniak, Hamish Sanderson, and others know http://groups.google.com/groups?frame=left&th=52107f826d13ccad ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Brett Cannon continues the marvelous tradition established by Andrew Kuchling and Michael Hudson of intelligently summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ The Python Business Forum "further[s] the interests of companies that base their business on ... Python." http://www.python-in-business.org The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donate.html Cetus collects Python hyperlinks. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://aspn.activestate.com/ASPN/Cookbook/Python Among several Python-oriented RSS/RDF feeds available are http://www.python.org/channews.rdf http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi http://python.de/backend.php For more, see http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://python.sourceforge.net/peps/pep-0042.html The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. *Py: the Journal of the Python Language* http://www.pyzine.com Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topics/pythonurl/ http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. From smallbee at rediffmail.com Wed Mar 10 23:25:03 2004 From: smallbee at rediffmail.com (Somesh Bartakkay) Date: 10 Mar 2004 20:25:03 -0800 Subject: python interface for indian language .... Message-ID: <8f198e47.0403102025.2ab9f31d@posting.google.com> hello friends, i went thru the webpages of chinesepython, was unable to understand data on that but gr8-ly inspired by that efforts put to make python program in local language. Now i wanna develope such type of interface/small library by which i can write py programs in my language.. should anyone guide me how it should be ..? i dont want to change the core python ...just wanna upper layer in gtk/wxpython ... plz , thanX in +vance ! From http Tue Mar 23 18:15:33 2004 From: http (Paul Rubin) Date: 23 Mar 2004 15:15:33 -0800 Subject: PEP 318 References: <99dce321.0403211817.3704fe2@posting.google.com> <7x1xnlqs77.fsf@ruckus.brouhaha.com> <7iptb4ckea.fsf@enark.csis.hku.hk> Message-ID: <7xn067cfze.fsf@ruckus.brouhaha.com> Skip Montanaro writes: > You'll be free to write your generator functions like so: > > def generator(f): > return f > > def silly_counter(n) [generator]: > for i in range(10): > yield n+i > > It will just be a convention you adopt though, not a language rule. It's a start. Next would be to add something like perl's -w flag, which checks that the conventions are followed. Finally there can be a compiler option that tells the optimizer to assume without checking that the conventions are followed (i.e. if you say that some arg is an int, then it's really an int). That should allow generating much better code which has the possibly of crashing if the convention is broken. From FBatista at uniFON.com.ar Wed Mar 24 09:45:54 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Wed, 24 Mar 2004 11:45:54 -0300 Subject: FAQs in spanish Message-ID: #- Steve> I just wondered: what *is* the Spanish for #- "www.python.org"? #- #- The domain name serpiente.org is available... ;-) Ugly! :) . Facundo From premshree_python at yahoo.co.in Tue Mar 16 07:54:46 2004 From: premshree_python at yahoo.co.in (=?iso-8859-1?q?Premshree=20Pillai?=) Date: Tue, 16 Mar 2004 12:54:46 +0000 (GMT) Subject: Static Typing in Python In-Reply-To: <4056c64d$0$3473$afc38c87@news.easynet.co.uk> Message-ID: <20040316125446.91356.qmail@web8308.mail.in.yahoo.com> --- Peter Hickman wrote: > Premshree Pillai wrote: > > --- Peter Hickman wrote: > > > Premshree Pillai wrote: > >>>Like in C, C++, etc, Python too is > >>>strongly typed, i.e., variables are necessarily > >> > >>bound > >> > >>>to a particular type. > > [deletia] > > > The above returns a TypeError in Python, but not > in > > PHP, which is weakly typed. > > > > Get it? > > The only two (or perhaps one and a half) languages > you used as reference > were C and C++. Which you said 'Like in C, C++, etc, > Python too is > strongly typed'. What has PHP got to do with it? How > does PHP's typing > have anything to do with Python's? > > Typing in C and C++ is different to Python. > > int c = 0; > c = "fred"; > > No can do in C and C++. > > c = 0 > c = "fred" > > No problem in Python. > > So just how is Python strongly typed 'like in C, > C++, etc'? > -- > http://mail.python.org/mailman/listinfo/python-list I said it in an earlier post, and I'll say again: I never said strong typing is about being able to change the type of a variable; I said that strong typing means that a variable is necessarily bound to a specific type; this is true for C and C++ too (both are strongly typed). PHP is weakly typed; variables are not bound to a specific data type. For e.g., I can do the following in PHP: // PHP snippet str = "xyz"; t = str + 0 // this is not an error in PHP On the other hand, Python will return an error when you try to add a string to an integer; PHP won't. -Premshree Pillai ===== -Premshree [http://www.qiksearch.com/] ________________________________________________________________________ Yahoo! India Insurance Special: Be informed on the best policies, services, tools and more. Go to: http://in.insurance.yahoo.com/licspecial/index.html From donn at u.washington.edu Wed Mar 17 20:07:38 2004 From: donn at u.washington.edu (Donn Cave) Date: Wed, 17 Mar 2004 17:07:38 -0800 Subject: how to do non-blocking I/O References: Message-ID: In article , "J. Xu" wrote: > I am a newbie to python. I am writing a client application, I need to > read query results from the server. Mostly I'll have a file object for > the connection to the server. So I use read() or readline() to get the > response. But since these are blocking calls, I have to use a seperate > thread for the input reading. But then I have another problem, my input > thread running in the following loop > > while not quit: > str = ins.readline() > .... process the response > > so I can't terminate the thread when it's blocking in the readline() > until the connection is closed. So looks like I need to use non-blocking > IO such as select() or poll(). But since I need this application to be > cross-platform, and these are not well supported on Windows, I don't > know what to do. Far as I know, what you want to do may not be possible with portable functions, so you may have to just implement separately for each platform. If you decide to use select or poll, note that they do not account for data buffered in a file object. This loses data, in effect, because even though it's in your process buffer, you won't read it if select says there's no new data. You can turn buffering off, but that forces readline() to read 1 byte at a time at an unreasonable cost in system calls. In my opinion it makes much more sense to use recv on the socket, and not use a file object here. Donn Cave, donn at u.washington.edu From project5 at redrival.net Fri Mar 12 13:47:11 2004 From: project5 at redrival.net (Andrei) Date: Fri, 12 Mar 2004 19:47:11 +0100 Subject: strings question References: Message-ID: Faheem Mitha wrote on Fri, 12 Mar 2004 18:03:05 GMT: > If I am given two strings, named foo and bar, what is the most elegant > way to create a string object whose name is the value of foo and whose > value is the value of bar? I have done some searching + looking in my > introductory textbook "Learning Python" but have not come up with an > answer yet. You could use exec (potentially dangerous if not all code being exec-ed is under your control): >>> f = 'foo' >>> b = 'bar' >>> exec '%s = b' % f >>> foo 'bar' You could also manipulate the globals or locals dictionary: >>> globals()[f] = b*2 >>> foo 'barbar' >>> locals()[f] = b*3 >>> foo 'barbarbar' -- 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 user_77 at hotmail.com Wed Mar 17 22:44:09 2004 From: user_77 at hotmail.com (Nobody) Date: Thu, 18 Mar 2004 03:44:09 GMT Subject: New to Python. References: <9k4i50dnfsi42gdr5rue1vnpq7gfqkanb6@4ax.com> Message-ID: How 'bout this: import string f=open ('Bob.txt','r') counter = 0 for line in f.readlines(): word = string.split(line) for x in word: if x == 'customer': counter = counter + 1 print 'Found it ' + str(counter) "droog" wrote in message news:9k4i50dnfsi42gdr5rue1vnpq7gfqkanb6 at 4ax.com... > Thanks for helping, and no this is not a homework assignment > I just like python and wanted to learn it on my own. > droog > > On Thu, 18 Mar 2004 03:07:05 GMT, droog wrote: > > >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 nospam-deets at web.de Tue Mar 2 08:25:07 2004 From: nospam-deets at web.de (Diez B. Roggisch) Date: Tue, 02 Mar 2004 14:25:07 +0100 Subject: read(): 1st argument can't be coerced to byte[] References: Message-ID: > 1 response = request.POST() # posts SOAP to the web service and waits for > 2 # response > 3 instr = response.getInputStream() > 4 reader = Sax2.Reader() > 5 doc = reader.fromStream(instr) > (...) > > Well, at line 5, I get the error: > > read(): 1st argument can't be coerced to byte[] What is that Sax2 thingy? It looks to me that the fromStream-method passes the instr to something that expects a byte-array - so you could try to read all the stuff from instr into an array and pass that. > Does not seem to be a DOM parsing problem. how could it, its SAX..... -- Regards, Diez B. Roggisch From newsgroups at jhrothjr.com Thu Mar 11 12:16:54 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Thu, 11 Mar 2004 12:16:54 -0500 Subject: Python style guidelines References: <3064b51d.0403101112.3449e987@posting.google.com> <405035a3$1@pfaff2.ethz.ch> <405087fc$1@pfaff2.ethz.ch> Message-ID: <10517r5523m4743@news.supernews.com> "Peter Hansen" wrote in message news:EO%3c.2675$G3.20988 at localhost... > Josef Meile wrote: > >>>>>> 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. > > I believe it's more likely they just forgot what find() did return, as > they were writing the code. I've done the same, thinking it was a > boolean, not thinking that it returned a negative but that negatives > were considered false. I suspect that's a rather common error. I'd much prefer that both find and index return an object that acted like a number but returned the logically correct response when queried as a boolean: true for zero and false for -1. Also, the "not found" object should throw an exception if it's used as an index or slice. John Roth > > -Peter From tundra at tundraware.com Wed Mar 10 05:00:08 2004 From: tundra at tundraware.com (Tim Daneliuk) Date: 10 Mar 2004 05:00:08 EST Subject: Any Python Hackers Wanna Beta Test???? In-Reply-To: <404ED30C.6050808@zoran.com> References: <404E60A5.9010605@tundraware.com> <3af2i1-c1i1.ln1@eskimo.tundraware.com> <404EB8DC.2010002@zoran.com> <7eu2i1-g3m1.ln1@eskimo.tundraware.com> <404ED30C.6050808@zoran.com> Message-ID: <4353i1-oao1.ln1@eskimo.tundraware.com> Miki Tebeka wrote: > Hello Tim, > >> I considred something like this, but I don't actually want a full blown >> language available to the end-user. Too easy for them to blow things >> up. > > Yes. OTOH they'll want more and more power and more and more features. > Just hand them Python and warn them. > Well, unlike utilities or systems tools, I am disposed to _limit_ what users can do with applications. Microsoft (and KDE and GNOME and ...) got themselves into trouble giving users _too much_ flexibility, IMHO. This creates a nightmare for support personnel who cannot reasonably count on a standardized applications environment.. >> I am working on something that is essentially almost entirely >> a lexical substitution (aka macro) engine. The only "logic" will be >> conditional inclusion of selected statments and simple string >> substitution. I may also add lexical namespaces since this is easy to >> do. > > Have you considerd using either the C pre processor or M4 macro language? Well, I tend to write most stuff to be cross-platform and you cannot count on these being present on non-Unix platforms. > One more option is to link to a small language that you can modify, have > a look at tiny scheme (http://tinyscheme.sourceforge.net/). It's one C > file implementation and you have a full language to give to your users. This leads to the same objection I have to using Python itself as a scripting language: A full featured language hands users lit dynamite... > >> I used a similar idea when I wrote 'twander' and now I want a more >> generic version of it: >> >> http://www.tundraware.com/Software/twander/ > > Very cool. I like it. ty :) -- ---------------------------------------------------------------------------- Tim Daneliuk tundra at tundraware.com PGP Key: http://www.tundraware.com/PGP/ From http Tue Mar 2 01:17:19 2004 From: http (Paul Rubin) Date: 01 Mar 2004 22:17:19 -0800 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> Message-ID: <7x1xob6ads.fsf@ruckus.brouhaha.com> Josiah Carlson writes: > > If a '+' is problematic, it could be some other character. If I use > > a print statement in a Python program, from my viewpoint, a trailing > > comma signals suppression of newline and adding a space. In this > > scenario, a trailing would > > suppress the newline but not add a space. There's not much > > difference there. > > The problem is that checking my keyboard, there exists exactly three > characters without syntactical meanings in Python 2.3; @, $, ?. None > of them make /any/ sort of syntactical sense to me in this context. I > hope that Guido feels the same way. How about two trailing commas: print foo now prints foo with a trailing newline. print foo, suppresses the trailing newline but adds a trailing space. print foo,, can suppress the trailing space as well. From jepler at unpythonic.net Tue Mar 16 14:22:44 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Tue, 16 Mar 2004 13:22:44 -0600 Subject: TypeError: 'NoneType' object is not callable In-Reply-To: <20040316175242.7263.qmail@web40020.mail.yahoo.com> References: <20040316175242.7263.qmail@web40020.mail.yahoo.com> Message-ID: <20040316192243.GG2446@unpythonic.net> On Tue, Mar 16, 2004 at 09:52:42AM -0800, Atul Kshirsagar wrote: > Adding extra information, > This was working fine with Python 2.2.2. > > Now desperate :) to get some help ! > Atul Nope, None is not callable in 2.2.2 either: Python 2.2.2 (#1, Feb 24 2003, 19:13:11) >>> None() TypeError: 'NoneType' object is not callable What in the world do you think None should do when called? Jeff From lbates at swamisoft.com Mon Mar 22 17:49:10 2004 From: lbates at swamisoft.com (Larry Bates) Date: Mon, 22 Mar 2004 16:49:10 -0600 Subject: static information... References: Message-ID: Try A.static.extend([1,2,3]) and see what that give you. Larry Bates wrote in message news:mailman.253.1079991337.742.python-list at python.org... > I've been looking for a way of have static variables in a python class and all I > have found is this: > > class A: > static =[] > > def f(self): > A.static = [1,2,3] > > > That seems to be pretty static since that variable can be used either on the > class (such as A.static) or on an instance (such as A().static). > Now my problem is that every time some create a new instance of this class the > variable static is reset to its original value [] and the real value that it > took is lost. What I want is someplace to store class's information and not > instance's information. > Any idea? > > From mwilson at the-wire.com Mon Mar 22 10:23:47 2004 From: mwilson at the-wire.com (Mel Wilson) Date: Mon, 22 Mar 2004 10:23:47 -0500 Subject: values within quotes References: <405ebd60$0$268$4d4ebb8e@news.nl.uu.net> Message-ID: In article <405ebd60$0$268$4d4ebb8e at news.nl.uu.net>, "Guyon Mor?e" wrote: >I give my program commands like this: GET MODLIST > >This is very easy to parse, I can just use .split() to because it has only >spaces to seperate the different parts of the command. Now I want, for >example, the following command: GET FILE C:\my docs\my file.txt. Obviously I >cannot use .split() for this one, because it uses spaces in the filename. >Common pc knowledge tells me that I should put the 'space-value' witin >quotes like: GET FILE "C:\my docs\my file.txt". > >So the big question is: What is the best way to parse such a string? Best has probably been posted, but for the record another way is >>> command = r"GET FILE C:\my docs\my file.txt" # simulate a read from the world outside >>> command.split (None, 2) ['GET', 'FILE', 'C:\\my docs\\my file.txt'] Regards. Mel. From joe at notcharles.ca Sat Mar 13 12:57:20 2004 From: joe at notcharles.ca (Joe Mason) Date: Sat, 13 Mar 2004 17:57:20 GMT Subject: Performance penalty for using properties? References: Message-ID: In article , Mike C. Fletcher wrote: > Kenneth McDonald wrote: > ... > >>Can anyone comment on the performance >>costs associated with properties vs. simple attribute lookup? >> >> > They can become a significant fraction of total run-time, and often wind > up showing as the heaviest methods in an entire application if they are > used pervasively (i.e. every attribute of every object is a property). > Even short runs of small systems so designed can give you 100s of 1000s > of calls to an individual method. OpenGLContext gets around this by > defining an accelerator for the __get__ method of the field properties. What does "accelerator" mean in this context? Obviously, it's something that speeds up __get__ calls, but ihow is that accomplished? If it's a simple wrapper, that means you can blissfully ignore property costs until profiling shows it's a problem, which is a big win. Joe From bogus at bogus.net Wed Mar 17 11:33:41 2004 From: bogus at bogus.net (Paul McGuire) Date: Wed, 17 Mar 2004 16:33:41 GMT Subject: Compare recursively objects References: Message-ID: "Nicolas Fleury" wrote in message news:gF_5c.6730$kc2.158843 at nnrp1.uunet.ca... > Do you know if the use of pickle would work? If I dump two objects and > compare the files, do I have the assurance that the files are the same > if the recursive members are the same? > > Regards, > Nicolas I am not very familiar with pickle, other than its purpose for persisting object representations for later reconstitution. Given that, I suspect your pickle-to-file-and-compare-the-files scheme would work. However, I would be wary of a scheme that routinely used files for temporary/scratch storage in this manner. There are just too many ordinary ways for this to go wrong: - disk has insufficient room to create files - insufficient user privs to create files - trying to create files in non-existent or protected directory - program exits before scratch files get cleaned up, leaving behind growing debris - concurrent users end up using each others' files by mistake; accidentally creating duplicate scratch file names Plus, file i/o is just plain agonizingly slow. In sum, I suspect you will get diverted to dealing with a whole bunch of issues that are artifacts of using files, when what you really wanted to do is compare some objects. Perhaps you could pickle to a string and compare the strings? At least this avoids most of the file system complications. -- Paul From ekoome at yahoo.com Mon Mar 15 09:37:19 2004 From: ekoome at yahoo.com (Eric) Date: 15 Mar 2004 06:37:19 -0800 Subject: wxDirDialog Message-ID: How does one use wxDirDialog to select and get a computer name from the network? Or which widget should i use to accomplish this? Eric From inigoserna at terra.es Sat Mar 6 07:28:27 2004 From: inigoserna at terra.es (=?ISO-8859-1?Q?I=F1igo?= Serna) Date: Sat, 06 Mar 2004 13:28:27 +0100 Subject: How to find size of file? In-Reply-To: References: Message-ID: <1078576106.27458.5.camel@inigo.katxi.org> Hi, Other ways: >> import os, stat >> os.stat(filename)[stat.ST_SIZE] Or better: >> import os.path >> os-path.getsize(filename) Best regards, I?igo Serna El vie, 05-03-2004 a las 22:13, Walter Huf escribi?: > Yermat wrote in > news:c2ai0g$1t4u$1 at biggoron.nerim.net: > > > Walter Huf a ?crit : > > > def sizeOf(f): > > f.seek(0,2) > > return f.tell() > > > > Thank you! > > > -----= 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! =----- -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Esta parte del mensaje est? firmada digitalmente URL: From NAIGIMSESRIMAIL at gims.com Wed Mar 31 14:45:43 2004 From: NAIGIMSESRIMAIL at gims.com (GroupShield for Exchange (ESRIMAIL)) Date: Wed, 31 Mar 2004 21:45:43 +0200 Subject: ALERT - GroupShield ticket number OB64_1080762339_ESRIMAIL_3 was generated Message-ID: Action Taken: The message was blocked because of its subject. To: python-list at python.org From: cookedm+news at physics.mcmaster.ca Sent: -1092744704,29628248 Subject: Re: test for nan Attachment Details:- Attachment Name: N/A File: Infected.msg Infected? No Repaired? No Blocked? Yes Deleted? No Virus Name: -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/ms-tnef Size: 1821 bytes Desc: not available URL: From axelboldt at yahoo.com Thu Mar 18 18:37:05 2004 From: axelboldt at yahoo.com (Axel Boldt) Date: 18 Mar 2004 15:37:05 -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> <1079629638.19728.0@lotis.uk.clara.net> Message-ID: <40200384.0403181537.145d1972@posting.google.com> "DomF" wrote in message news:<1079629638.19728.0 at lotis.uk.clara.net>... > > Indeed I have not. Probably because basic built-in strings form a type > > that's not a class and you can't inherit from it. > > > Mostly because I am interested in the counter argument: > > class mynewstr(str): > ... pass > ... > >>> s = mynewstr() > >>> dir(s) > <> I stand corrected, I don't think there is a counter argument. So then the objection of Asun Friere remains: could a redefinition of "is" for strings affect the behavior of classes derived from str? I don't know. Axel From pinard at iro.umontreal.ca Tue Mar 23 09:47:35 2004 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Tue, 23 Mar 2004 09:47:35 -0500 Subject: [OT] Compilable Python-like language? In-Reply-To: References: Message-ID: <20040323144735.GA20351@alcyon.progiciels-bpi.ca> [Ed Cogburn] > By compile-to-binary, I meant create a binary executable in native > machine code that does not involve an interpreter process (source or > byte-code), and any substantial run-time overhead. In other words my > concern, is as always, about speed. Clear enough! :-) > Lisp has good performance, and is a compilable language, I'm aware > of that, but I just can't handle all the parentheses [...] without > getting a headache. :) To each their own, I need something else. While I quite understand what you mean (my initial LISP experiences were on punched cards, so human balancing of parentheses at the time ought to be an clever efficient art), Lisp (the capitalisation changed since then!) became much more manageable. With intelligent editors, able to automatically re-indent on the fly (on Unix, Emacs is the only one I used, but there might be others able to do so), you merely look at the indentation. And for the remaining few times you still need to look at parentheses, within a single line usually, the corresponding parentheses blink while you move the cursor. All in all, in real day-to-day practice, parentheses are not an impediment anymore. Given you use a proper editor, Lisp might be even easier overall than many other languages. You should not fear it. > Pyrex is very interesting, I've looked at Pyrex code. The purpose > of Pyrex however isn't to replace Python or the interpreter process, > merely to optimize some parts of a Python program. Even with heavy > use of Pyrex, you still can't get away from the interpreter process, > ie., Python will always have to be there, right? I'm not sure. In one of my projects, I want to explore how fully one could get rid of the Python interpreter while using Pyrex, maybe through a set of added stub routines, but this project is low priority and I'm not getting there yet. One of these days hopefully. The nice thing with Pyrex is that you can use the Python interpreter, or not use it, more or less depending on your way to declare things and your way to code. So, in a way, you have full control over the compromise between speed and facility. The temptation is always strong to use Python facilities, but I guess that with enough discipline, you can displace and put the equilibrium wherever you want. If you tolerate having the Python interpreter around, I presume that you can take good advantage and be happy of its presence for the many parts of your programs where speed is not that critical. If you do not want the Python interpreter around in the long run, and if this is possible to fully get rid of it (I do not know yet), then there is no doubt to me that one needs a fairly strict discipline while using Pyrex. -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From fxj at mpe.mpg.de Tue Mar 2 16:26:17 2004 From: fxj at mpe.mpg.de (F Jamitzky) Date: 2 Mar 2004 13:26:17 -0800 Subject: Ruby like syntactic sugar Message-ID: <5349af3f.0403021326.ed19d8c@posting.google.com> It is rather easy to define functions in python that mimic the special ruby syntactic sugar like: 5.times { print "Hello World!" } or [toast, cheese, wine].each { |food| eat food } In python these fragments can be written as: 5 *times(lambda: printf("Hello World!") ) or [toast, cheese, wine] *each (lambda food: eat(food) ) by defining a Times class like that: class Times: def __rmul__(self,n): for i in range(n): self.func() def __call__(self,func): self.func=func return self times=Times() Was this intended as a language feature or is this style an "unpythonic" missuse of the syntax ? I like the way of writing loops and list comprehensions that way, but I think there will be an outcry of some people. What do you guys think about extensions like that ? cheers Ferdinand From max at alcyone.com Wed Mar 17 18:38:53 2004 From: max at alcyone.com (Erik Max Francis) Date: Wed, 17 Mar 2004 15:38:53 -0800 Subject: Semantics of == References: <40200384.0403161538.7407d9e2@posting.google.com> <4057A2A0.CC63C070@alcyone.com> <40200384.0403170657.5c81a456@posting.google.com> Message-ID: <4058E18D.15C51614@alcyone.com> Axel Boldt wrote: > I couldn't find that algorithm in the language reference, only in 5.9: > "Tuples and lists are compared lexicographically using comparison of > corresponding elements. This means that to compare equal, each element > must compare equal and the two sequences must be of the same type and > have the same length." > > That definition doesn't seem to fully specify equality of list values: > ... Sure it does; the rule can be used recursively. As I indicated, according to its definition, your s and w are clearly equal despite being infinite and having different internal representations. == has to do with value, not identity. > I hope that the > actual result received, i.e. s==w, is not implementation dependent? They're also equal in Jython. It wouldn't surprise me if you could find an implementation where they might not compare equal, because this is such a pathological case. As I indicated before, I've never seen anyone use a self-referencing list in any real-world code, ever. > It now appears to me that there are four levels of equality in Python: > > a is b => pickle.dumps(a)==pickle.dumps(b) => repr(a)==repr(b) => a==b > > and none of the arrows can be reversed in general. I suppose I had > naively assumed the last three to be equivalent. __eq__ and __repr__ can be overridden to do whatever the programmer wants, so why would you think the last three would be equivalent? repr(a) == repr(b) is certainly not equivalent to a == b. Consider the default repr of an arbitrary class, which will only be equal to another object if a is b -- that is, if they represent the same object. Beyond that, it's up to the programmer to make custom types behave how he or she would like with respect to equality and repr. > Is there a string > function analogous to pickle.dumps or repr which only takes values > into account, not internal structure? How can you define the value of an arbitrary object without reference to its internal structure? -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE \__/ Liberty is the right to do whatever the law permits. -- Charles Louis Montesquieu From sross at connectmail.carleton.ca Wed Mar 10 10:11:35 2004 From: sross at connectmail.carleton.ca (Sean Ross) Date: Wed, 10 Mar 2004 10:11:35 -0500 Subject: PEP 328: Imports: Multi-Line and Absolute/Relative References: Message-ID: If people do not care for import -2.MODULE from -1.MODULE import NAMES as RENAME Would it be possible and/or preferrable to have something like this work: import relative(2).MODULE from relative(1).MODULE import NAMES as RENAME ? From cookedm+news at physics.mcmaster.ca Wed Mar 10 14:48:22 2004 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Wed, 10 Mar 2004 14:48:22 -0500 Subject: NumPy (numarray) problem with C code References: Message-ID: 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 > } -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From nir1408 at ziaran.org Tue Mar 2 16:25:13 2004 From: nir1408 at ziaran.org (ziaran) Date: Tue, 02 Mar 2004 23:25:13 +0200 Subject: Jython Debugger? In-Reply-To: References: <4044435E.6090100@ziaran.org> Message-ID: <4044FBB9.1090105@ziaran.org> max khesin wrote: > (forgive the simpleton) > How do you envision this working in Jython environment? > > thanks, > max. > > ziaran wrote: > >> F. GEIGER wrote: >> >>> I'm looking for such a thing too. All I've found so far is an >>> announcement >>> of an Eclipse plugin. >>> >>> Regards >>> Franz GEIGER >>> >>> "max khesin" schrieb im Newsbeitrag >>> news:jkL0c.94$c73.143227 at twister.nyc.rr.com... >>> >>>> Hi all, >>>> I was takling to someone who has been using Jython for a while. Their >>>> biggest complaint is the luck of a good debugger. I was really >>>> surprised. Isn't there anything decent out there? >>>> thanks, >>>> max >>> >>> >>> >>> >>> >> >> try rpdb.py >> you can get it at: >> http://ziaran.org/rpdb.htm >> Max, I didn't hear about Jython until today, but if it runs Python code it should run the debugger, since it it written in Pythonish. From chris.gonnerman at newcenturycomputers.net Fri Mar 19 00:38:12 2004 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Thu, 18 Mar 2004 23:38:12 -0600 Subject: [snip too-long subject] In-Reply-To: References: Message-ID: <405A8744.9070107@newcenturycomputers.net> Josiah Carlson wrote: >> - all builtin functions that do not add value to the language as >> language should move into separate module (e.g. map, zip, sum etc... >> vs callable, isinstance, builtin type-constructors) and not be so >> over-emphasized. > > map, zip, sum, etc. are used in a large amount of production code. > Moving them somewhere else would break every piece of code that uses > them. This is not going to happen soon, possibly ever. I'm a bit confused, anyway. When did functional programming become outdated? map() is easily as important as iterators and generators. -- Chris. From fpetermaas at netscape.net Thu Mar 4 12:36:58 2004 From: fpetermaas at netscape.net (Peter Maas) Date: Thu, 04 Mar 2004 18:36:58 +0100 Subject: exiting Python In-Reply-To: <3064b51d.0403040858.666153a1@posting.google.com> References: <3064b51d.0403040858.666153a1@posting.google.com> Message-ID: beliavsky at aol.com schrieb: > I think exiting Python with 'Ctrl-Z plus Return' is awkward. Why not > something simpler like ':q[uit]'. Since ':q' is currently invalid > syntax, I don't think using it to quit Python would break anything. class SimpleExit: def __repr__(self): print "Python: Sssssssee you!" import sys sys.exit(0) q = SimpleExit() Include this in your PYTHONSTARTUP and you're done. Just type >>> q whenever you want to exit and avoid conflicting use of q in interactive sessions. :-) 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 riccardo_cut-me at cut.me.sideralis.net Thu Mar 18 15:29:57 2004 From: riccardo_cut-me at cut.me.sideralis.net (Riccardo Galli) Date: Thu, 18 Mar 2004 21:29:57 +0100 Subject: ConfigParser and Unicode References: Message-ID: On Thu, 18 Mar 2004 19:10:08 +0000, thehaas wrote: > "Martin v. L?wis" wrote: >> thehaas at binary.net wrote: >> > Obviously, 'Gr??'!='Gr\xfc\xdf' . > >> It is not at all obvious that they are different. In fact, they >> are the same, assuming the second string is encoding in Latin-1. > >> > Any ideas on how I can get the correct value? > >> Pray tell: what is the correct value? > > The correct value is 'Gr??', or at least have it equal to that. > > Maybe I should back up -- I'm interfacing into a Windows API. In that API, I see 'Gr??' as: > >>> plist[-1].Reference > u'Gr\xfc\xdf' > > My value in goodProcList is: > >>> goodProcRef[18] > 'Gr\xfc\xdf' > > (yeah, goodProcList isn't in Unicode -- that's probably the cause of all this) > > When I test their equality: > >>>> goodProcRef[18] == plist[-1].Reference > Traceback (most recent call last): > File "", line 1, in ? > UnicodeDecodeError: 'ascii' codec can't decode byte 0xfc in position 2: ordinal > not in range(128) > > If I try to manually encode goodProcRef[18], I get the same thing: > > >>> goodProcRef[18].encode('utf-8') > Traceback (most recent call last): > File "", line 1, in ? > UnicodeDecodeError: 'ascii' codec can't decode byte 0xfc in position 2: ordinal not in range(128) by experience, you must first decode your string to encode it so >>> goodProcRef='Gr\xfc\xdf'.decode('latin-1') >>> goodProcRef u'Gr\xfc\xdf' now you could compare goodProcRef and plist[-1].Reference and get "True" When strings are unicode strings, then you can encode them easily >>> goodProcRef.encode('UTF8') 'Gr\xc3\xbc\xc3\x9f' >>> plist[-1].Reference.encode('UTF8') 'Gr\xc3\xbc\xc3\x9f' Hope it can help, Riccardo -- -=Riccardo Galli=- _,e. s~ `` ~@. ideralis Programs . ol `**~ http://www.sideralis.net From steve at ninereeds.fsnet.co.uk Fri Mar 12 23:25:51 2004 From: steve at ninereeds.fsnet.co.uk (Stephen Horne) Date: Sat, 13 Mar 2004 04:25:51 +0000 Subject: drowning newbie References: Message-ID: <1r2550l35kftiq1c4h7b1o1dquudin4upq@4ax.com> On Sat, 13 Mar 2004 03:19:15 GMT, "elizabeth fletcher" wrote: >Actually, I have the .pyd file (which I understand is basically a dll file) >and placed it in the DLL directory in the PYTHON23 directory. In the >interactive window I type "import calldll" and I get an error (ImportError: >DLL load failed: The specified module could not be found) I shoudn't if >the dll is installed correctly.....right? The folder is called 'DLLs' rather than 'DLL', but I imagine that's just finger-trouble in your post. The 'DLLs' folder is definitely the right place. There are some problems that are not specifically related to Python, though. The most likely is a dependency on other DLLs. You should check whether your extension needs any other additional DLLs (e.g. the runtime libraries for a particular compiler version) and make sure you have them installed, either somewhere on you OS path or in the DLLs folder where you placed the .pyd file. -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From marer at videotron.ca Fri Mar 5 13:19:30 2004 From: marer at videotron.ca (Eric Martel) Date: Fri, 05 Mar 2004 18:19:30 GMT Subject: Help needed with gettext.install (solved) In-Reply-To: <0L12c.109944$2g.52298@charlie.risq.qc.ca> References: <0L12c.109944$2g.52298@charlie.risq.qc.ca> Message-ID: Eric Martel wrote: > > Hi, > > I'm using Mandrake Cooker and just upgraded Python to 2.3.3. > > A Python-based program I use often is Pybliographer; since the Python > update, I get the following error when trying to start Pybliographer: > > Traceback (most recent call last): > File "/usr/bin/pybliographer", line 40, in ? > gettext.install (progname, localedir, unicode = True) > AttributeError: 'module' object has no attribute 'install' > > I don't know much about Python, but here is a Python session from the > shell (for which I was inspired by something I found on Google): > > Python 2.3.3 (#2, Feb 17 2004, 11:45:40) > [GCC 3.3.2 (Mandrake Linux 10.0 3.3.2-6mdk)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> import gettext > >>> gettext.__dict__['textdomain'] > > >>> gettext.__dict__['install'] > Traceback (most recent call last): > File "", line 1, in ? > KeyError: 'install' > > So it really looks like the 'install' method is not available for the > object 'gettext', while the method 'textdomain' is. I talked about it on > a Cooker list, but no one was aware of what could cause this problem > (and I was apparently the only one to experience it), so I'm asking to > you guys: do you know what could be missing/wrong on my system to cause > such an error? I found out that the problem was with the new gettext.py file that was installed with the Cooker update I did: for a reason I don't know, the file was very different from the one found inside the official Python 2.3.3 sources: I just copied the latter onto the bad one and everything was fine. I alerted the Cooker community. -- Eric Martel Sainte-Foy (Qu?bec) Canada Clef publique OpenPGP: ED3F191C (http://key.ericmartel.net/) Copyleft 2004 Eric Martel (http://www.gnu.org/copyleft/) -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 264 bytes Desc: OpenPGP digital signature URL: From dmq at gain.com Mon Mar 15 21:09:20 2004 From: dmq at gain.com (David MacQuigg) Date: Mon, 15 Mar 2004 19:09:20 -0700 Subject: Deprecating reload() ??? References: <6kk6501shlve52ds2rjdopa73jhpchprg3@4ax.com> Message-ID: On Mon, 15 Mar 2004 13:50:47 -0600, Skip Montanaro wrote: > Dave> We should at least update the description of the reload function > Dave> in the Python Library Reference. See the thread "Reload > Dave> Confusion" for some suggested text. > >Please file a bug report on Sourceforge so your ideas don't get lost. Feel >free to assign it to me (sf id == "montanaro"). Will do. I would like to get a few comments from folks following this thread before submitting the proposed text to Sourceforge. Here is the summary: """ To summarize what happens with reload(M1): The module M1 must have been already imported in the current namespace. The new M1 is executed, and new objects are created in memory. The names in the M1 namespace are updated to point to the new objects. No other references are changed. References to objects removed from the new module remain unchanged. Previously created references from other modules to the old objects remain unchanged and must be updated in each namespace where they occur. The old objects remain in memory until all references to them are gone. """ To read this in context, with a nice example, background discussion, etc. see http://ece.arizona.edu/~edatools/Python/Reload.htm I think I've finally got it right, but I'm always prepared for another surprise. Once I'm confident that my understanding is correct, I'll see if I can weave this into the existing text of the Library Reference. I may try also to put in some of the "motivation" for the way things are (from the Background section of the above webpage.) -- Dave From noemail at noemail4u.com Mon Mar 29 07:21:09 2004 From: noemail at noemail4u.com (Dang Griffith) Date: Mon, 29 Mar 2004 12:21:09 GMT Subject: A 'Python like' language References: <40645d8f$0$10775$afc38c87@news.easynet.co.uk> <1068up4kn49778@news.supernews.com> <106959g6i63cv77@news.supernews.com> Message-ID: On Sat, 27 Mar 2004 02:24:29 GMT, Steve Lamb wrote: >On 2004-03-26, John Roth wrote: >> "D Martin" wrote in message >> news:ax%8c.9470$wg1.4018 at edtnps84... > >>> 3 solutions: > >>> 1. Use spaces instead of tabs. Hit the space bar yourself, or an editor >>> that replaces tabs with spaces. >>> 2. Include as a .py or text file instead of inline. >>> 3. Get a different email program. > >> All of these fail for one simple reason. Let's hit >> the chorus, guys: > >> "We're right, everybody else needs to change..." > > Hey, that's the Chorus from the Microsoft song! You're the one using >Lookout! You're the one complaining about the shortfalls in your tools >because Microsoft sings that song. *YOU* deal with it. It's not a Microsoft problem. I use a webmail interface (for email, not newsgroups), and regardless of which browser I use, tabs are eliminated. I'm not thinking it's a browser problem either. My suspicion is that some part of the back-end is removing tabs because some other part of the back-end system uses tabs for delimiters. I know it's a non-Microsoft back-end (I think it's FreeBSD). Who should *I* rant at? ;-) When sending snippets, making a separate attachment can be counterproductive since 1) it breaks the flow of any explanation, and 2) many people are (justifiably) afraid to open attachments. So attaching a file is not reader-friendly, though it does solve the problem for the writer. --dang From mark at prothon.org Mon Mar 29 04:44:16 2004 From: mark at prothon.org (Mark Hahn) Date: Mon, 29 Mar 2004 01:44:16 -0800 Subject: A 'Python like' language References: <40645d8f$0$10775$afc38c87@news.easynet.co.uk> <95aa1afa.0403262049.4b2a6f78@posting.google.com> Message-ID: > Yes, this seemed interesting to me too. But when arrived at the sentence > "Prothon only allows tabs for indentation" I couldn't continue reading ;-) It appears we will be bowing to pressure and switching to spaces. Mark Hahn (Prothon Author) "Michele Simionato" wrote in message news:95aa1afa.0403262049.4b2a6f78 at 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 paul at prescod.net Mon Mar 29 01:06:00 2004 From: paul at prescod.net (Paul Prescod) Date: Sun, 28 Mar 2004 22:06:00 -0800 Subject: Pyrex talks from Pycon Message-ID: <4067BCC8.5010209@prescod.net> PyCon 2004 Slides on "Extending Python with Pyrex" PDF: http://www.prescod.net/pyrex/ExtendingPythonWithPyrex.pdf PPT: http://www.prescod.net/pyrex/ExtendingPythonWithPyrex.ppt Pycon 2004 Slides on "Optimizing Python code with Pyrex" PDF: http://www.prescod.net/pyrex/OptimizingPythonWithPyrex.pdf PPT: http://www.prescod.net/pyrex/OptimizingPythonWithPyrex.ppt I hope this helps me. Please report any mistakes. Paul Prescod From qp at al.net Wed Mar 31 21:30:02 2004 From: qp at al.net (Qp) Date: Wed, 31 Mar 2004 21:30:02 -0500 Subject: Python conference slogan References: Message-ID: I don't know if anyone else will think it's funny... "Shane Hathaway" wrote in message news:mailman.189.1080759511.20120.python-list at python.org... > Here's a Python slogan suggestion by Ken Manheimer. > > One Nation Under Under Python > > I thought it was pretty funny. I don't know if international folks will > get it, though. :-) > > Shane > From hans at zephyrfalcon.org Fri Mar 26 23:33:55 2004 From: hans at zephyrfalcon.org (Hans Nowak) Date: Fri, 26 Mar 2004 23:33:55 -0500 Subject: PyProtocols question In-Reply-To: References: Message-ID: <40650433.5070400@zephyrfalcon.org> Gon?alo Rodrigues wrote: > Hi all, > > I'm not sure if this is the best forum to place this question, but > haven't found a better one, so here goes. > > I have Python 2.3 in my machine (Windows 2000) and downloading > PyProtocols 0.9.2 the installer complains that python 2.2 isn't found > in the registry. > > I've also tried to download the source and follow the instructions, > but since there's no compiler the setup complains. Since I cannot find > the latest 0.9.3 version I can't use the --without-speedups to bypass > the compilation phase... > > I also have cygwin and could try the rpm's, but I have (yet) very > little experience on it, so I don't wanna go that route. > > Anyone got any suggestions? This worked for me: Download the source (0.9.2) from http://peak.telecommunity.com/dist/. Edit setup.py, so that it says include_speedups = False Then, do a setup.py install. HTH, -- Hans (hans at zephyrfalcon.org) http://zephyrfalcon.org/ From max at alcyone.com Sat Mar 20 18:47:31 2004 From: max at alcyone.com (Erik Max Francis) Date: Sat, 20 Mar 2004 15:47:31 -0800 Subject: Help getting the md5 module to work References: <7x1xnodjx2.fsf@ruckus.brouhaha.com> <405BFC92.E1C8C186@alcyone.com> <8z07c.21193$Bg.9311@fed1read03> Message-ID: <405CD813.B483EA6B@alcyone.com> Amy G wrote: > I discovered this last night. > > But what is the true MD5 hash for help? With or without the newline? It's completely up to you. It's your hash, you decide what goes in it. All that's important is whoever's comparing hashes with yours (for whatever reason) is doing it consistently. -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE \__/ I'm spreading my wings and I fly / I'm still as the night -- Chante Moore From mh at dreadnok.pixar.com Wed Mar 17 20:01:38 2004 From: mh at dreadnok.pixar.com (Mark Harrison) Date: Thu, 18 Mar 2004 01:01:38 GMT Subject: how to "source" a file? References: <4g56c.11369$MC6.9352@newssvr27.news.prodigy.com> Message-ID: Specifically, I'm confused why def dfpostadd(name): """per-unit postprocessing step""" sys.path.append('/my/config/path') import dfacommon dfacommon.addm(name) works, but this doesn't: sys.path.append('/my/config/path') import dfacommon def dfpostadd(name): """per-unit postprocessing step""" dfacommon.addm(name) which gives me: msg=global name 'dfacommon' is not defined trace=[' File "", line 341, in doadd\n', ' File "/usr/anim/config/ndfd/mark.cfg", line 55, in dfpostadd\n dfacommon.addm(name)\n'] Many TIA, Mark From newsgroups at jhrothjr.com Sat Mar 20 16:14:08 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 20 Mar 2004 16:14:08 -0500 Subject: New restrain builtin function? References: Message-ID: <105pd227mcmp646@news.supernews.com> "Pierre Rouleau" wrote in message news:xK17c.26714$Eb6.852981 at news20.bellglobal.com... > Hi all, > > In several occasions, I found myself looking for a function that would > take a value and restrict is within a specified set of boundaries. For > a 1-dimension value, I could simply write > > min(max(value,theMin),theMax) > > to restrict value within the range made of theMin to theMax. > It assumes that theMax >= theMin. > > I was looking for a single call to restrict a value within bounds that > would do pretty much that, so i wrote this trivial one: > > def restrain(value, theMin, theMax) : > """Return a value that is in restricted to the [theMin, theMax] range. > > **Example** > > >>> for val in xrange(-1,7,1): > ... print "restrain(%d,1,5) = %d" % (val, restrain(val,1,5)) > ... > restrain(-1,1,5) = 1 > restrain(0,1,5) = 1 > restrain(1,1,5) = 1 > restrain(2,1,5) = 2 > restrain(3,1,5) = 3 > restrain(4,1,5) = 4 > restrain(5,1,5) = 5 > restrain(6,1,5) = 5 > >>> > """ > > assert(theMax >= theMin) > return min(max(value,theMin),theMax) > > > Without the assertion check, the restrain() named function runs > expectedly slower than the explicit min(max()) calls: > > C:\Python23\Lib>timeit "min(max(5,1),0)" > 1000000 loops, best of 3: 1.02 usec per loop > > C:\Python23\Lib>timeit -s"from ut import restrain" "restrain(5,1,6)" > 1000000 loops, best of 3: 1.53 usec per loop > > Again, I found myself writing code that has to restrain the values to > some range and prefer using the restrain() function instead of the > min(max()) one. > > Therefore, I was wondering if it would it make sense to add a function > like restrain() to the list of Python built-ins. Or is there something > like that already in the Python library? > > > Thanks > > Pierre I know I've wanted that on (infrequent) occasion. I think "minmax" makes a better name, though, and I suspect it would have to be implemented in C to make any sense, performancewise. John Roth > > > > > From max at alcyone.com Wed Mar 17 19:42:46 2004 From: max at alcyone.com (Erik Max Francis) Date: Wed, 17 Mar 2004 16:42:46 -0800 Subject: attributes of Python classes References: <3064b51d.0403171605.75ec1ba0@posting.google.com> Message-ID: <4058F086.490C215B@alcyone.com> 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. -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE \__/ Everyone wants to look good at his own funeral. -- Louis Wu From dmq at gain.com Sat Mar 13 10:19:26 2004 From: dmq at gain.com (David MacQuigg) Date: Sat, 13 Mar 2004 08:19:26 -0700 Subject: Deprecating reload() ??? References: <40514A48.50907@domain.invalid> <09b350henbtk9vnai0v7fhtbsqbmubl7vn@4ax.com> <7cj4c.2733$G3.21896@localhost> <8ok3505b3b3g22bk8ci6iagptqav2cfi6r@4ax.com> Message-ID: On Fri, 12 Mar 2004 15:17:54 -0600, Skip Montanaro wrote: > > Dave> Another "brute force" kind of solution would be to replace the old > Dave> objects with links to the new. Every refence, no matter where it > Dave> came from, would be re-routed. The inefficiency would only last > Dave> until you restart the program. > >That would require that you be able to transmogrify an object into a proxy >of some sort without changing its address. In theory I think this could be >done, but not in pure Python. It would require a helper written in C. How about if we could just show the reference counts on all of the reloaded objects? That way we could know if we've missed one in our manual search and update. Could avoid the need for transmogrification of objects. :>) -- Dave From emurphy42 at socal.rr.com Mon Mar 1 00:56:45 2004 From: emurphy42 at socal.rr.com (Ed Murphy) Date: Mon, 01 Mar 2004 05:56:45 GMT Subject: Why Python? References: Message-ID: On Mon, 01 Mar 2004 05:12:48 +0000, Rainer Deyke wrote: > Todd7 wrote: >> What makes it better or worse than languages like perl, php, delphi, >> or c++? > I'll focus on the weaknesses of Python instead of the strengths. [snip] > 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.) From peter at engcorp.com Sat Mar 13 10:01:25 2004 From: peter at engcorp.com (Peter Hansen) Date: Sat, 13 Mar 2004 10:01:25 -0500 Subject: drowning newbie In-Reply-To: References: Message-ID: elizabeth fletcher wrote: > Want to use Sam Rushing's calldll Python Module on a windows box. I don't > understand how to install it. I have several books that do not detail the > steps in installing a 3rd party module in Windows. Anybody want to throw me > life preserver? Switch to ctypes. Easier to install, and newer, and supported, and easier to use, etc. calldll is basically obsolete. -Peter From http Wed Mar 3 18:43:09 2004 From: http (Paul Rubin) Date: 03 Mar 2004 15:43:09 -0800 Subject: Python as replacement for PHP? References: <403fa54b@news.zianet.com> <99dce321.0403031518.56f61c7c@posting.google.com> Message-ID: <7xad2x5wfm.fsf@ruckus.brouhaha.com> dw-google.com at botanicus.net (David M. Wilson) writes: > Like everyone else who has replied, I seriously question how much > experience you have with the multitude of Python web environments > available. The very existence of a "multitude" of Python web environments is a serious shortcoming of Python as a PHP replacement. PHP comes with one web environment, not a multitude, so you have just one manual to read, not a multitude; one codebase to worry about keeping up with the latest releases for, not a multitude, and so forth. You don't have to check out and evaluate N different web environments and K different database interface packages, and make sure they're all in sync with each other whenever you update anything. PHP's web environment are database integration right there for you the moment you install PHP. > - PHP provides no intuitive default support for many common DB > operations. Compare the following messes: That's ok, Python has no default support at all, intuitive or otherwise, for ANY db operations, common or not. > We could bring the PHP ADODB, or many of the other numerous PHP APIs > for DB connectivity into the picture, but which of these are the > obvious choice, and officially endorsed? That's precisely the situation Python is in now! > - Python tends to be slow, but slow compared to what? The laptop I > type this message on has a 2ghz processor. It cost less than ?1000. Yes, but we're talking about server side applications, that can have to support thousands of users simultaneously. They always want more speed and rarely are found running on laptops. > - PHP is very light on CPU, memory, and so on. I earn a modest amount > for a 20 year old, even by Northern Ireland standards. I can't see how > I would ever need to resort to PHP because I couldn't afford the > hardware to run a complex Python-based site intended for viewing by > thousands. The site that I worked on spent TWO MILLION U.S. DOLLARS on its web server hardware. OK, it used Java servlets that are even slower than Python, but you have to understand that there's a point after which you can no longer pretend that hardware is free. From jjl at pobox.com Tue Mar 30 03:47:40 2004 From: jjl at pobox.com (John J. Lee) Date: 30 Mar 2004 09:47:40 +0100 Subject: ANN: Python UK Conference, 16th - 17th April 2004 Message-ID: [Sorry if this appears twice -- my first post seems to have been held up / lost] The Python UK conference is taking place on Friday and Saturday 16th and 17th of April, as part of the ACCU Spring Conference at the Randolph Hotel in the centre of Oxford. The impressive list of speakers includes David Ascher, Alex Martelli, Armin Rigo of Psyco and PyPy fame, Duncan Booth, Chris Withers, and core CPython and Jython developers Michael Hudson and Samuele Pedroni. The Python conference follows a 2-day Open Source event with well-known open-source leader and Pythonista Eric Raymond, co-founder of Zope corp Paul Everitt, and a host of other interesting speakers. http://www.accu.org/conference/ http://www.accu.org/conference/python.html http://www.accu.org/conference/opensource.html Though all the official speakers are invited, there will be considerable space during breaks and after hours for Python mini-talks, Birds of a Feather meetings and sprints (possibly including a PyPy sprint). There are also very reasonable sponsorship options (starting from ?200 for a lunchtime stand and talk) for Python companies wishing to promote themselves; see the 'sponsorship' page of the site for details. John From paul at prescod.net Sun Mar 28 09:48:52 2004 From: paul at prescod.net (Paul Prescod) Date: Sun, 28 Mar 2004 06:48:52 -0800 Subject: Prothon Prototypes vs Python Classes In-Reply-To: <106ceeeqc8ph126@news.supernews.com> References: <569c605ld1cj8fc1emolk08ete0s1prls1@4ax.com> <106cc1f2rsnaoe2@news.supernews.com> <406635AB.9050803@mlug.missouri.edu> <106ceeeqc8ph126@news.supernews.com> Message-ID: <4066E5D4.10008@prescod.net> John Roth wrote: > It's certainly true that in a prototype based language all objects > exist: there are no objects that the compiler deals with but does > not put into the resulting program. And it's quite true that it does > open up the floodgates for a lot of messiness. Ummm. This is also true for Python. Python classes exist at runtime. foo = 5 class foo: # oops. I've overwritten foo def bar(self): pass print foo print dir(foo) print type(foo) Paul Prescod From talktojamesblair at yahoo.com Sun Mar 28 03:10:13 2004 From: talktojamesblair at yahoo.com (james blair) Date: 28 Mar 2004 00:10:13 -0800 Subject: Error handling in smtp References: Message-ID: Hi Ya thats true but I also want what was the error so that i could print it. From steve at ninereeds.fsnet.co.uk Sat Mar 27 11:28:25 2004 From: steve at ninereeds.fsnet.co.uk (Stephen Horne) Date: Sat, 27 Mar 2004 16:28:25 +0000 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> <7xn068bdg9.fsf@ruckus.brouhaha.com> <2dl160t6s26gau4o4gt2ld79s35gjsd0ma@4ax.com> Message-ID: On Fri, 26 Mar 2004 13:55:04 -0600, DH wrote: >Christian wrote: > >> IMHO, if the function's name has to be right after the 'def', and 'def' >> has to be the first command in a declaration, the return type has to >> come last > >I agree. > >I think it is neat that function decorators may be used for specifying >argument types and the return types, but I don't think it should be THE >way to always do it, because it is pretty ugly. It isn't really specifying anything. It is just validating, which we can do already using normal code. Using decorators to validate arguments/return types brings them to the front, thus making them more useful as an example of self-documenting code, but while it's an interesting application for decorators I don't think it should be overemphasised. Ensuring that a parameter has a specific type is often excessive in Python - if another type supports the right methods in the right way, it often makes sense to call the function with arguments of that type. -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From jbperez808 at yahoo.com Sun Mar 21 09:46:58 2004 From: jbperez808 at yahoo.com (Jon Perez) Date: Sun, 21 Mar 2004 22:46:58 +0800 Subject: Python bytecode compatibility between interpreter versions In-Reply-To: References: <0qudndSnJMpWbsfdRVn-uA@powergate.ca> Message-ID: Andrew MacIntyre wrote: > - Python has always been specified in terms of the language, with a > portable reference interpreter implementation for that language (which > just happens to compile to bytecode, and save that bytecode to disk > as an optimisation). > > IOW, the bytecode is an implementation detail for _one_ interpreter > implementation. > > This becomes obvious when you consider the possibilities associated > with Jython, which could (already does?) compile Python source to jar > files directly. Contrary to what you seem to be implying here, Guido never expressly designed Python to be easily portable to run on top of other bytecode implementations. Jython was a very difficult feat to pull and the same goes (probably moreso) for Python.NET. From steve at ninereeds.fsnet.co.uk Tue Mar 23 04:20:34 2004 From: steve at ninereeds.fsnet.co.uk (Stephen Horne) Date: Tue, 23 Mar 2004 09:20:34 +0000 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> <7xn068bdg9.fsf@ruckus.brouhaha.com> Message-ID: On 22 Mar 2004 16:43:18 -0800, Paul Rubin wrote: >DH writes: >> 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" > >I think I'd rather use colons for that, like Pascal does, e.g. > > def foo:int (x: int, y: float) > >hmm, the foo:int doesn't look too good. In Ada, the type of a function return value is specified using an explicit keyword ('returns' IIRC). I don't see the need for a unique keyword just for that, but how about... def foo (x: int, y: float) return int [decorators] : def foo (x: int, y: float) yield int [decorators] : -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From tim.one at comcast.net Mon Mar 15 11:13:06 2004 From: tim.one at comcast.net (Tim Peters) Date: Mon, 15 Mar 2004 11:13:06 -0500 Subject: mutable list iterators - a proposal In-Reply-To: Message-ID: [Jess Austin] >> I like the way that Python does lists, and I love the way it does >> iterators. But I've decided I don't like what it does with iterators >> of lists. >> ... [Aahz] > I'll guarantee that it won't be fixed for 2.4. This subject has come > up many times long before iterators were introduced, and the answer > has always beent the same: if you want to mutate, make a copy or make > *very* sure that your mutations don't muck the loop. It's worse than just that: the Python Reference manual defines what happens when you mutate a sequence while iterating over it, even while discouraging it. So the precise behavior of, e.g., >>> r = range(10) >>> for x in r: ... print x ... r.remove(x) 0 2 4 6 8 >>> is actually advertised behavior. See the Warning block at the end of section "The 'for' statement". From smithwis at colorado.edu Fri Mar 12 15:29:12 2004 From: smithwis at colorado.edu (Steve) Date: 12 Mar 2004 12:29:12 -0800 Subject: Postgres BYTEA problems References: <27ab36b3.0403031305.3e1ed4f7@posting.google.com> Message-ID: <27ab36b3.0403121229.7c210c7f@posting.google.com> Ivan Voras wrote in message news:... > Steve wrote: > > > a character that must be escaped. > > so if I should be getting > > "\x00\x01" > > I'll get > > "\\x00\\x01" > > Are you sure that it's the dbapi driver that is doing it, or maybe the > data was written to the database in that way (e.g. not chr(00)+chr(01) > but '\' 'x' '0' '0' ...)? Thanks for responding Ivan I'm pretty sure that the table is beeing fed chr(00) + chr(01). I'm not the one generating the database(it's written in Java) however I've seen the code and it appears to be entering in the data correctly. Recently, to test the problem, I've gone through and inserted a string in python that needed escaping something like this: >>> Db.insertable("steves",[['\001'],["test"],["\\001\\002"]]) >>> y = Db.query("SELECT * FROM steves").getresult() >>> print y [('\001',), ('test',), ('\\001\\002',)] And I got the double escape problem on both y[0] and y[2]. Actually, looking at my testing I got an idea. Do you think this could have to do with the double escaping one must do while working with other postgres interfaces(namely psql). Let me clarify that question, I'm wondering if this double escape thing is actually an artifact of postgres and not a problem with the pg module. My current solution is to do this simple loop that replaces all //### with the char replacemet like so: def no_escape(x): i, ret = x.find('\\'), '' while i != -1: if x[i+1].isdigit(): //number is in octal y = x[i+1:i+4] ret += x[:i] + struct.pack('B',string.atoi(y,8)) x = x[i+4:] i = x.find('\\') return ret + x But, of course, this solution is a little less than ideal. Any thoughts? --Steve From fumanchu at amor.org Wed Mar 10 11:24:33 2004 From: fumanchu at amor.org (Robert Brewer) Date: Wed, 10 Mar 2004 08:24:33 -0800 Subject: Regex Match Problem Message-ID: bdwise wrote: > 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()" Not sure if this is the final result you wanted, but it should overcome the major hurdles (like not escaping the parentheses ;) >>> import re >>> a = "something();something();document.thisForm.textBox1.focus();something(); " >>> re.search(r';([^;]*).focus\(\);', a).groups() ('document.thisForm.textBox1',) Hope that helps. Robert Brewer MIS Amor Ministries fumanchu at amor.org From tim.one at comcast.net Fri Mar 19 18:10:12 2004 From: tim.one at comcast.net (Tim Peters) Date: Fri, 19 Mar 2004 18:10:12 -0500 Subject: Result of ``a is b'' In-Reply-To: <405B5E20.AD0EAB6D@alcyone.com> Message-ID: [Andrew Koenig] >> I'm pretty sure that IEEE floating point requires NaN to be defined >> in such a way that if x is NaN, then x == x must yield False. Yes, but ... a conforming implementation of the standard requires all sorts of comparison operators, but it's not a language standard and doesn't have anything to say about how languages spell access to any of its facilities. So, e.g., there must be *some* way to spell an equality operator that doesn't consider a NaN to "be equal" to itself, but that doesn't need to be spelled "==" (not even in a language that has an "==" comparison operator). For example, it's fine if it needs to be spelled ieee.equal_considering_nans_unequal_and_unexceptional(x, y) [Erik Max Francis] > That's correct. Python itself doesn't do this, though: All Python behavior wrt IEEE gimmicks is a platform-dependent accident -- nothing is promised. > Python 2.3.3 (#1, Dec 22 2003, 23:44:26) [GCC 3.2.3] on linux2 > >>> a = 1e3000 > >>> a > inf > >>> a/a > nan > >>> n = a/a > >>> n == n > True While on Windows 2.3.3, the output looks very different, and the final result is False. For Python 2.4, Michael Hudson has patched things so that Python's 6 float relationals deliver the same results the platform C compiler delivers for the spelled-the-same-way-in-C float relationals. There's still no cross-platform guarantee about what those will do (because C makes no guarantees here either), but at least NaN == NaN will be false on both gcc and MSVC7-based Pythons (MSVC6-based Pythons will say NaN == NaN is true then, but right now there are no plans to distribute an MSVC6-based Python 2.4). From e9526547 at stud3.tuwien.ac.at Fri Mar 26 05:45:17 2004 From: e9526547 at stud3.tuwien.ac.at (Alexander Straschil) Date: 26 Mar 2004 10:45:17 GMT Subject: Calling function keywords from a dictionary Message-ID: Hello! I'm fooling around with a class wich can map cgi-parameters to function named parameter. I have a dic like dic = { 'action': 'myfunc', 'x': 1, 'y': 2, 'z': 3 } and I have a method def myfunc(x, y, z, a=None, b=None) What I want to do ist calling the method defined in 'action' with all the named parameter, also instead of self.myfunct(x=1, y=2, z=3) I want to do f = getattr(self, dic['action']) f(named parameter from the dic) Its a little like zope does it, but i didnt find it in the Zope Sources ;-) How can do that? Thanks, AXEL. From andrew-pythonlist at puzzling.org Thu Mar 25 09:27:02 2004 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Fri, 26 Mar 2004 01:27:02 +1100 Subject: sorting the list by inner elements In-Reply-To: References: Message-ID: <20040325142702.GD29958@frobozz> On Thu, Mar 25, 2004 at 07:31:16AM -0600, John Hunter wrote: > >>>>> "ketulp" == ketulp baroda writes: > > ketulp> I like ur idea but this will work for only when inner list > ketulp> has only two elements. if inner list has five elements and > ketulp> i want to sort the whole list by 3rd element then how can > ketulp> i do this ? > > The general approach is to arrange the elements in the order you want > them sorted, sort them, and then revert to original order. So if you > have 5 elements, and you want them sorted by the 3rd, put the 3rd > first. If any two of the first elements are the same, the second > element of the list will break the tie, and so on. > > Supposing you want to sort by the 3rd element, and you don't care > about the relative order of the other fields > > # swap the first an 3rd elements > tmp = [ (e[2], e[1], e[0], e[3], e[4]) for e in seq] > tmp.sort() > # swap them back > seq = [ (e[2], e[1], e[0], e[3], e[4]) for e in tmp] That's more complicated than it needs to be for ketulp's use-case. tmp = [(e[2], e) for e in seq] tmp.sort() seq = [t[1] for t in seq] -Andrew. From skip at pobox.com Wed Mar 17 17:33:14 2004 From: skip at pobox.com (Skip Montanaro) Date: Wed, 17 Mar 2004 16:33:14 -0600 Subject: Encoded file In-Reply-To: <20040317.123415.18463.1998145@webmail24.nyc.untd.com> References: <20040317.123415.18463.1998145@webmail24.nyc.untd.com> Message-ID: <16472.53802.473161.490187@montanaro.dyndns.org> Zhi> Could I ask you, how can I know a file is encoded as 'UTF-8', Zhi> 'UTF-16' or something else? In general you can't tell. I'm not aware of any filesystems which maintain encoding information for individual files. You have to know or guess. Some encodings carry clues (BOM, etc), but in general you have to figure it out. Skip From jack at performancedrivers.com Mon Mar 29 23:57:26 2004 From: jack at performancedrivers.com (Jack Diederich) Date: Mon, 29 Mar 2004 23:57:26 -0500 Subject: Tkfont buggy for two Tk() top level windows Message-ID: <20040330045726.GB1313@performancedrivers.com> I'm calling Tk() twice to create two top level windows, which works fine in every respect except fonts. Assigning a Tkfont to widgets in the first Tk() window I create works fine, the font looks good as it should. But if I start a another window by calling Tk() again the second window will always use some awful default font. Swapping the two lines that call Tk() will change which one actually uses the font and which doesn't. The code looks like: win_one = Tk() win_two = Tk() myfont = tkFont.Font(family="Courier", size=12) Entry(win_one, font=myfont).pack(fill='both',expand=1) Entry(win_two, font=myfont).pack(fill='both',expand=1) Any text on the first window obeys the font, the second one will always use some system default. switching the two lines that call Tk() reverses which window goes font happy. If calling Tk() twice has undefined behavior I would rather it raise a useful exception instead of continuing partially gimpy. Debian testing, python 2.3.3, tk 8.2.3-5 This has been the behavior for 6-12 months (as long as I've been using Tk). Until now I just assumed I had missed a call, after checking it out it seems to be a Tk thing. TIA, -jackdied From NAIMAILVIENNA at KingdomInc.com Tue Mar 23 22:45:40 2004 From: NAIMAILVIENNA at KingdomInc.com (GroupShield for Exchange (VIENNA)) Date: Tue, 23 Mar 2004 22:45:40 -0500 Subject: ALERT - GroupShield ticket number OA485_1080099940_VIENNA_1 was generated Message-ID: <6E6210A67731AB478F4CD760B14A4B9101E8914E@mail.kingdominc.com> Action Taken: The attachment was deleted from the message and replaced with a text file informing the recipient of the action taken. To: webmaster at kingdominc.com From: python-list at python.org Sent: 1701793024,29626706 Subject: Mail Delivery (failure webmaster at kingdominc.com) Attachment Details:- Attachment Name: message.scr File: message.scr Infected? Yes Repaired? No Blocked? No Deleted? Yes Virus Name: W32/Netsky.p at MM -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/ms-tnef Size: 1852 bytes Desc: not available URL: From fpetermaas at netscape.net Tue Mar 30 10:43:23 2004 From: fpetermaas at netscape.net (Peter Maas) Date: Tue, 30 Mar 2004 17:43:23 +0200 Subject: PyPerl 1.0.1 [requires Visual Studio compiler?] In-Reply-To: References: Message-ID: Eric @ Zomething wrote: > 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. I had the same problem with Borland C++ 5.5. The cause is a different object file format for compiled C++ code: MS has COFF, Borland has OMF and a tool named COFF2OMF. I applied the tool to python23.dll and could then compile extensions with the Borland compiler. I have no idea which format Mingw32 uses. But recompiling the Python source would surely have the same effect as applying COFF2OMF to MS binaries. 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 dmq at gain.com Mon Mar 15 12:38:20 2004 From: dmq at gain.com (David MacQuigg) Date: Mon, 15 Mar 2004 10:38:20 -0700 Subject: loop scope References: Message-ID: On Mon, 15 Mar 2004 14:43:20 GMT, Arthur wrote: >> >>I think I may have misunderstood your original question. The title of >>the thread is 'loop scope', but your question seems to be specifically >>on the loop iteration variable 't'. Just think of it as a normal >>variable in the current local scope. > >I can. But it's not my first inclination. And I would speculate I am >far from alone. Having subtleties to be aware of in something as >fundamenatal as a for loop is not a great thing, IMO. On the hand >hand, it was a long time before any subtleties here had any practical >implications to me. I had been getting away with ignorance. But its >not a good feeling to know that. > >t=None #(or something) > >required prior to a loop would assure I am conscious of what I am >getting myself into. Without it, it seems it isn't safe to assume the >user understands the full implications of simply complying with >required loop syntax. > >Wouldn't something like this make sense: > >With a loop iteration variable declared explicitly in the curent scope >and prior to the loop, it survives the loop. Otherwise it is treated >as a placeholder within the loop, and goes out of scope at its >conclusion. This is a little too tricky for my taste. Often we need to 'break' from a loop, and subsequently use the value of 't'. If we forget to "declare" 't' outside the loop, then we will have a situation where you get a run-time error if the loop ends without a break. What is the benefit of keeping 't' out of the surrounding local scope?" This whole thread seems pointless unless there is a substantial benefit to changing the current behavior. -- Dave From bouil at bouil.org.invalid Tue Mar 16 02:26:08 2004 From: bouil at bouil.org.invalid (Nicolas Bouillon) Date: Tue, 16 Mar 2004 08:26:08 +0100 Subject: Replace accented chars with unaccented ones In-Reply-To: References: Message-ID: 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. Bye. From mogmios at mlug.missouri.edu Tue Mar 30 14:06:28 2004 From: mogmios at mlug.missouri.edu (Michael) Date: Tue, 30 Mar 2004 11:06:28 -0800 Subject: Prothon Prototypes vs Python Classes In-Reply-To: <20040330132021.GD27344@nl.linux.org> References: <569c605ld1cj8fc1emolk08ete0s1prls1@4ax.com> <106di86neu1qh4d@news.supernews.com> <20040330132021.GD27344@nl.linux.org> Message-ID: <4069C534.1050802@mlug.missouri.edu> >>A2. People that bitch about top-posting. >> >> > >Mark - I really find it a bit difficult to read your postings. I keep >scrolling to below to see whether there is still more to come - because you >do sometimes quote others and then answer below. When I see quoting in a >message, I automatically assume there's more to come, and I am not the >only one. I think it is the wrong answer to say that people shouldn't >bitch about top-posting - it _does_ annoy people (including me and Aahz). >There are conventions on usenet (and mailing lists), and they are there >with reason. I would like to kindly ask you to try to do more >'bottom-posting'. It makes your postings easier and prettier to read. > >Really, it does - please try it... > > The 'standard' I've seen worked out in about a decade of watching this exact argument.. when responding to individual parts of someones message then post your reply directly underneath the section you're replying to. If you're making a short response to the entire message it's okay to top post. Of course, either bottom or top posting, clip any text in the previous messages you aren't directly responding to. From antonyliu2002 at yahoo.com Wed Mar 17 02:12:16 2004 From: antonyliu2002 at yahoo.com (Anthony Liu) Date: Tue, 16 Mar 2004 23:12:16 -0800 (PST) Subject: problem with cjkcodecs on Mandrake linux In-Reply-To: Message-ID: <20040317071216.57278.qmail@web13005.mail.yahoo.com> Thank you, Martin. I am using bash, so should I add the following line to .bash_profile? export LANG=zh_CN Please let me know. Thanks a lot. --- "Martin_v._L?wis" wrote: > Anthony Liu wrote: > > OK, gotcha. By the way, do you know how to set the > > default language of Mandrake or any linux system, > so > > that I can probably mimic. > > You need to set the LANG environment variable. This > is best done on a per-user basis, e.g. in the .login > file of the user. Setting LANG to zh_CN should give > you a (simplified) Chinese environment. Python 2.3 > will automatically pick up that setting when > printing > Unicode strings. > > Regards, > Martin > > -- > http://mail.python.org/mailman/listinfo/python-list __________________________________ Do you Yahoo!? Yahoo! Mail - More reliable, more storage, less spam http://mail.yahoo.com From mwilson at the-wire.com Mon Mar 8 10:43:00 2004 From: mwilson at the-wire.com (Mel Wilson) Date: Mon, 08 Mar 2004 10:43:00 -0500 Subject: Working around a lack of 'goto' in python References: Message-ID: In article , "Roger Binns" wrote: >> > What you have is what many other languages allow with integers after break or >> > continue statements. For example you can do 'break 2' or 'continue 3' to >> > break or continue out of the respective number of enclosing for loops. >> >> Yuck. Bletch. Barf. > >Care to expand on that? It is a construct present in shell scripting Well, say you decide that several lines of code should be executed repeatedly. You can stick in the while...: , your editor can indent the block, then you have to hunt for numbered `continue` and `break` and increment some, but not all of the numbers. Unnumbered `continue` and `break` cause similar trouble, but the trouble is guaranteed to be more local. For non-local I much prefer the exit-by-exception. Regards. Mel. From wfolta at netmail.to Tue Mar 2 18:57:32 2004 From: wfolta at netmail.to (Wayne Folta) Date: Tue, 2 Mar 2004 18:57:32 -0500 Subject: Ruby like syntactic sugar In-Reply-To: <5349af3f.0403021326.ed19d8c@posting.google.com> References: <5349af3f.0403021326.ed19d8c@posting.google.com> Message-ID: <5EA73B3F-6CA5-11D8-9B35-000A959CB2EC@netmail.to> It seems your solution could be the basis for rubyesque Python. (Do you have it backwards regarding Ruby, though? Isn't 5.times the way a loop is done and the for-loop-looking construct is the syntactic sugar?) But on a personal note, I'd add that the > 5.times { print "Hello World!" } syntax is the idiom that persuaded me Ruby is not for me. In my opinion, this construct is either too clever by half or it's too Smalltalkish (everything must be classed). It makes some sense when spoken, but I fail to see how a looping method belongs to the class of numbers, so it troubles me too much to use or to enjoy a language where this is natural. From twic at urchin.earth.li Fri Mar 5 10:21:57 2004 From: twic at urchin.earth.li (Tom Anderson) Date: Fri, 5 Mar 2004 15:21:57 +0000 Subject: alternate module installation Message-ID: right, i'm trying to install Mark Pilgrim's feedparser package, and one thing it mentions is that it likes to have libxml2 and mxTidy around. i've downloaded these, and done configure/make on the C bits, but i'd now like to make them available to python. i've read the very helpful Installing Python Modules manual, and determined that (a) libxml2 and mxtidy have distutils-approved setup.py scripts (although feedparser doesn't, but i don't mind that) and (b) since i'm on a unix (debian linux) machine on which i'm a lowly luser, i probably need to do an Alternate Installation (The Home Scheme), just sticking things in my home directory. however, when i say: python setup.py install --home=~ it says: failed to find headers for libxml2: update includes_dir can anyone explain what's going wrong, and what i might do to make it go right? there's probably something really obvious i should do, or read, but i'm completely at sea with all this. thanks, tom -- Force the weird stuff down! From michele.simionato at poste.it Sun Mar 28 05:58:48 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 28 Mar 2004 02:58:48 -0800 Subject: Prothon, metaclasses, Zope [Was: A 'Python like' language] References: <95aa1afa.0403272243.78d60724@posting.google.com> Message-ID: <95aa1afa.0403280258.41dc5cd9@posting.google.com> Joe Mason wrote in message news:... > > You could just put the function call in your base class's __init__ > method. (Or, in fact, put the code from that call directly there, if > you only care when you inherit from the one Zope class.) Uh? The base class __init__ method is not called when I derive a new class. I want to make the make the check at class level, *before* instantiating. Michele Simionato From lsmithso at NOhare.SPAM.demon.co.uk Mon Mar 29 07:05:21 2004 From: lsmithso at NOhare.SPAM.demon.co.uk (Les Smithson) Date: 29 Mar 2004 13:05:21 +0100 Subject: ANNOUNCE: Pymqi 0.5 MQ Interface released Message-ID: Pymqi 0.5 is now available at http://www.hare.demon.co.uk/pymqi. This version adds support for MQ 5.3 SSL client connections and a PCF interface. Pymqi is a Python extension for IBM's Messaging & Queueing middleware, MQSeries (aka WebSphere MQ family). This allows Python scripts to make calls directly to MQI to connect queues and get/put messages on them etc. Pymqi combines the power of Python with the benefits of the messaging model. It can be used to develop test harnesses for MQ based systems, for rapid prototyping of MQ applications, for development of administrative GUI's (when combined with e.g., TkInter), and even for mainstream MQ application development! Pymqi does not replace MQI, but is layered on top of it, so you must have MQ (either client or server) installed before you can use it. From rkern at ucsd.edu Thu Mar 4 16:13:34 2004 From: rkern at ucsd.edu (Robert Kern) Date: Thu, 04 Mar 2004 13:13:34 -0800 Subject: maximum element? In-Reply-To: References: Message-ID: Ivan Voras wrote: > What is the 'most pythonic' way of searching the largest element in a > list/tuple? max(list) > My 'standard' idea is: > > max = list[0] # or -infinity, or whatever... > for i in list: > if i > max: > max = i > > While this is ok, I somehow 'feel' there could be a more concise > solution... :) Indeed. :-) -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From fletcher at worldnet.att.net Sun Mar 14 12:17:06 2004 From: fletcher at worldnet.att.net (elizabeth fletcher) Date: Sun, 14 Mar 2004 17:17:06 GMT Subject: drowning newbie References: Message-ID: Thank you all for using your powers for good. :) "Peter Hansen" wrote in message news:opF4c.2789$G3.23566 at localhost... > elizabeth fletcher wrote: > > > Want to use Sam Rushing's calldll Python Module on a windows box. I don't > > understand how to install it. I have several books that do not detail the > > steps in installing a 3rd party module in Windows. Anybody want to throw me > > life preserver? > > Switch to ctypes. Easier to install, and newer, and supported, and > easier to use, etc. calldll is basically obsolete. > > -Peter From jolsen at mail2world.com Thu Mar 18 10:12:51 2004 From: jolsen at mail2world.com (Jesper) Date: Thu, 18 Mar 2004 15:12:51 GMT Subject: dictionary wart In-Reply-To: References: <5Bi6c.11865$g4.240193@news2.nokia.com> Message-ID: Jonathan Daugherty wrote: > Python isn't ruby; so don't compare them. > No, I suppose that would be a sin. Jesper From jacek.generowicz at cern.ch Thu Mar 11 04:15:54 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 11 Mar 2004 10:15:54 +0100 Subject: Scope question References: Message-ID: Subhash Chandra writes: > How can I make counter variable in function foo reference to global > counter variable in the following code. add the line " global counter" just after "def foo():" > Generally C programmers tend to write code like that I am looking > for simple way to do it in python. Generally C programmers do horrible things. Please consider whether you really, really should be emulating C style in Python. > --- BEGIN --- > counter = 0 > > def foo(): > if counter < 10: > print "count = ", counter > counter += 1 > > foo() > --- END --- From tjreedy at udel.edu Wed Mar 31 14:32:47 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 31 Mar 2004 14:32:47 -0500 Subject: Followup: big projects, games, reload Message-ID: People fairly frequently ask about Python being used in big projects, commercial projects, commercial games, etc. There was also a recent thread on the limitations of 'reload' and what one might do to get the reload behavior one wants... One of the PyCon talks that most surprised *me* is this: http://www.python.org/pycon/dc2004/papers/29/Panda3D.htm It seems that Disney's rather successful ToonTown Online ( http://toontown.com ) is scripted in Python on top of their now open sourced Panda3D (C++) engine. ( http://www.etc.cmu.edu/panda3d ) This answers the first set of questions in the affirmative. One of their reasons for using Python is to be able to do the following: "Redefining methods: One of the truly powerful features of Panda3D is that you can stop a simulation, redefine a method, and start from that point again. This is done using Python features. Panda3D recursively digs through namespaces to find the definition of the class or methods and then swaps them for the new, thus rebinding the new version. There is also special code written to dig out all the stored function pointers, such as events and tasks, and replace those as well." I think this nicely illustrates what I saw as the conclusion of the reload thread: if one wants a reload function that does exactly what one wants in a particular application, one should write it oneself, and with effect, one can do so. Terry J. Reedy From skip at pobox.com Fri Mar 5 16:21:19 2004 From: skip at pobox.com (Skip Montanaro) Date: Fri, 5 Mar 2004 15:21:19 -0600 Subject: securely overwrite files with Python In-Reply-To: References: Message-ID: <16456.61263.327619.243980@montanaro.dyndns.org> Bart> Is there a shred module in Python? You know, the kind that Bart> overwrites files that one doesn't want others to see? I've never used shred before, but here's an essentially untested stab at the problem: #!/usr/bin/env python import os import random import sys import md5 def shred(f, npasses=5): sz = os.path.getsize(f) for n in range(npasses): dig = md5.new(file(f).read()).hexdigest() print >> sys.stderr, "pass:", n+1, print >> sys.stderr, "digest:", dig chars = [chr(i) for i in range(128)] random.shuffle(chars) chars = "".join(chars) bytesleft = sz fp = file(f, "wb") while bytesleft: nbytes = min(bytesleft, 128) fp.write(chars[:nbytes]) bytesleft -= nbytes fp.close() dig = md5.new(file(f).read()).hexdigest() print >> sys.stderr, "last digest:", dig os.unlink(f) if __name__ == "__main__": tmpf = "dummyf" file(tmpf, "wb").write(file("/etc/hosts").read()*5) shred(tmpf) Note that it does no error checking, nor does it have any force write arg. Skip From python at rcn.com Wed Mar 24 04:24:53 2004 From: python at rcn.com (Raymond Hettinger) Date: 24 Mar 2004 01:24:53 -0800 Subject: SHA-based subclass for random module 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: <5d83790c.0403240124.2a80e784@posting.google.com> [Trevor Perrin] > I'm proposing that getrandstring() (returning a string) is a better > primitive than getrandbits() (returning a long). > This would be easy to implement with Mersenne Twister too. Though it > would involve some rewriting. > > Do you think this is worthwhile? Sorry, I do not think that introducing a string method into an otherwise numeric module would make it easier to use. The is doubly true because the API also requires that new generators implement random(), returning a float, which means that you have to convert to a number at some point anyway. What might be nice is if longs had methods for converting to and from bytestrings. Currently, the knowledge for how to do that is sequestered in the pickle module. Raymond From tjreedy at udel.edu Tue Mar 30 10:22:58 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 30 Mar 2004 10:22:58 -0500 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> <1J8ac.68390$cx5.23284@fed1read04> Message-ID: What is 'this'? Who is 'you'? Where is the original suggestion? What did who say what is fragile? "Mark Hahn" wrote in message news:1J8ac.68390$cx5.23284 at 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? Trying to read cryptic top-posted comments that require me to spend minutes trying to find the most like referent in order to make any sense is too much work for me. I won't do it. Good bye. Terry J. Reedy From tjreedy at udel.edu Wed Mar 31 11:29:13 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 31 Mar 2004 11:29:13 -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: "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). SourceForge adds new comments to tracker items to the top of the comments section. If you are are the original poster, and get a new report emailed with every comment, and get and read them in order, then newest at top is, I admit, helpful. BUT if you look at an old, unresolved, bug report with several comments, perhaps to see if you can help, then the format is a major nuisance. Read the original report at the top. Then jump down to the bottom and back up to the top of the first comment and read down. Then scan up to find the top of the second comment and read down. and so on. The solution, to me, are more easily customizable information readers and managers. Then one could have, for instance, a module specifically for interacting with the SourceForge database, complete with user-preference settings. (Does one exist now? that I don't know of?) Terry J. Reedy From m.bless at gmx.de Wed Mar 3 04:47:17 2004 From: m.bless at gmx.de (Martin Bless) Date: Wed, 03 Mar 2004 09:47:17 GMT 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> Message-ID: <4045a616.8831515@news.t-online.de> [David Goodger ] >you should write a PEP. Without a PEP, the idea will be forgotten. Good advice, good encouragement, thanks. I'd really like to. But unfortunately I've discovered the weak point in my own argumentation: a new keyword could and probably would break existing code. Therefore I can't go for a PEP until I have a better idea. Ok, then let's use some wrappers or helper functions. Here's the one I currently like: #!/usr/bin/env python # -*- coding: iso-8859-1 -*- """Do some experiments on write statements.""" __author__ = "Martin Bless, 2004-03-03" class Writer: def __init__(self,writer=None): if writer is None: import sys self.writer = sys.stdout else: self.writer = writer def write(self,*args): for arg in args: self.writer.write(str(arg)) __call__ = write def to(self,writer,*args): for arg in args: writer.write(str(arg)) write = Writer() NL = '\n' import sys stderr = Writer(sys.stderr) if __name__=="__main__": import sys outfile = sys.stdout or file('demo_tempfile','w') write('#', '-->'*10, NL) write('Starting.',NL) write(__doc__,NL) write("write(1,2,3,4,NL)=>", 1,2,3,4,NL) write("write('This',' ','is',' ','a',' ','demo.',NL)=>", 'This',' ','is',' ','a',' ','demo.',NL) write.to( outfile,"write.to(outfile,5,6,7,8,NL)=>",5,6,7,8,NL) stderr("stderr('A number in parentheses: (', 77, ').', NL)=>", 'A number in parentheses: (',77,').',NL) write('Done.',NL) write('#', '<--'*10, NL) """Output should be: #-->-->-->-->-->-->-->-->-->--> Starting. Do some experiments on write statements. write(1,2,3,4,NL)=>1234 write('This',' ','is',' ','a',' ','demo.',NL)=>This is a demo. write.to(outfile,5,6,7,8,NL)=>5678 stderr('A number in parentheses: (',77,').',NL)=>A number in parentheses: (77). Done. #<--<--<--<--<--<--<--<--<--<-- """ This comes pretty close to what I was aiming at. But of course it's just my version and different people will create different solutions. mb - Martin Bless From jcarlson at nospam.uci.edu Mon Mar 15 19:02:20 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Mon, 15 Mar 2004 16:02:20 -0800 Subject: read/enter text based on cursor position In-Reply-To: References: Message-ID: > ----------------------------------- > Windows Application X > ----------------------------------- > Name: > Address: > City: > State: > Zip: > ----------------------------------- I'm curious as to why you don't use a combination of static text elements and text entry widgets. From what I've been able to see with virtually every app I've ever used, read source code of, or otherwise, that is what most people do. Is there some architectural limitation where you cannot use them? - Josiah From ptmcg at users.sourceforge.net Mon Mar 1 12:32:00 2004 From: ptmcg at users.sourceforge.net (Paul McGuire) Date: Mon, 01 Mar 2004 17:32:00 GMT Subject: Reading selected data from text files References: Message-ID: "..:: sjf ::.." wrote in message news:c1vl6l$lle$1 at atlantis.news.tpi.pl... > U?ytkownik "Paul McGuire" napisa? w wiadomo?ci > news:MVK%b.7974$lS1.1103 at fe2.texas.rr.com... > > "..:: sjf ::.." wrote in message > > news:c1njho$adr$1 at nemesis.news.tpi.pl... > > > Hello Pythoners! > > > > > > There are a lot of files containing data such as: > > > > > > file1: > > > 0950 1550 > > > > > > file22: > > > 0952 1552 > > > > > > > > -- > > > ..:: sjf ::.. > > > "Linux is like Wigwam. No gates, no windows... Apache inside ;-)" > > Try this: > > > > import sets > > import os > > > > uniqueElems = sets.Set() > > > > testdata = """ > > 0950 1550 > > 0952 1552 > > 1000 1020 1050 1130 1150 1200 1245 1600 > > 1002 1022 1052 1132 1152 1202 1247 1602 > > 1005 1025 1055 1135 1155 1205 1250 1605 > > """ > > for line in testdata.split("\n"): > > uniqueElems.update( line.split() ) > > # if running Python 2.3.1 or later, replace previous line with > > # uniqueElems |= line.split() > ^^^^^^^ > OK, but what is that? > > In 2.3.1, the Set() class defines a "|=" operator that will add all elements of a list to the set. Also, update() is deprecated in 2.3.1 in favor of union_update(), intersection_update(), and, um, some other update() that I can't recall off the top of my head, something like "negative_intersection_update" or something. -- Paul From kbass at midsouth.rr.com Sat Mar 13 22:23:00 2004 From: kbass at midsouth.rr.com (kbass) Date: Sun, 14 Mar 2004 03:23:00 GMT Subject: Python & the job market References: Message-ID: "Eric @ Zomething" wrote in message news:mailman.13.1079231349.745.python-list at python.org... >> I have experience about 4 years of Java experience (designed and developed >> numerous projects as a consultant in the past), 10+ years of Oracle >> experience, about 5 years of Perl experience so programming is not a problem >> . I guess my main point that I should have touch upon was learning Python >> and influencing management to go the Python route in a company where Java is >> the standard. > Question: in terms of these kind of objectives, how important are a world class IDE and world >class libraries? >Python: Batteries are included, but do we need 110/220v power source as part of the package for >the "next phase"? Or, from perhaps a Guido perspective, is that going beyond what Python was >intended for? >Eric Pederson >"Anything is possible" - LB I feel that a world class IDE is not important to meet my objectives. I have always taken the position that an IDE is only as good as the programmer who is using it so I like to focus on programming concepts and techniques rather than tools. Once an understanding of a language is achieved, an IDE can be used as a tool to assist a programmer or developer. A module repository like Perl's CPAN or a beefed up Python module repository with good documentation would be a plus. That would be starting point towards a rich/world class type library. The main factor would be easy of use, good documentation and a resource to review before attempting to develop a class or module. Every programming language must develop and adapt to the needs of its user-based as times goes on, so I think that having 110/200v power source could be a step in the right direction in the 'next phase'. There should be no limits on the things that a program language can do and placing restraints on a programming language could be a one way ticket to the programming language graveyard as time goes on. Each programming language, let it be COBOL, Perl, etc.,.., had been intended for a specific purpose but as time goes on, some start to realize that the language that they are using could be used for other purposes. A programming language is a limited as the person who is using it. kbass From fpetermaas at netscape.net Fri Mar 12 07:48:56 2004 From: fpetermaas at netscape.net (Peter Maas) Date: Fri, 12 Mar 2004 13:48:56 +0100 Subject: Static Typing in Python In-Reply-To: References: Message-ID: 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. This could be done e.g. within a class: class doesTypeChecking: def __init__self(): aString = "" aFloat = 0.0 def __setAttr__(self, attr, value): if type(self.__dict__[attr] != type(value): raise ValueError, "Type mismatch for attribute %s\n" % attr Similar code could be used to check parameters of a function/ method. Have looked at pychecker? It's not part of the python distribution but it could help here. 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 pclinch at internet-glue.co.uk Mon Mar 29 11:30:09 2004 From: pclinch at internet-glue.co.uk (Paul Clinch) Date: Mon, 29 Mar 2004 17:30:09 +0100 Subject: Async example of SSL in M2Crypto Message-ID: Has anyone tried the echod-async.py example in m2crypto-0.12/demo/ssl? I am only connecting one client, the echo.py example in the same directory. Although the synchronous and threading examples work ok, the async server goes into an infinite loop:- LOOP: SSL accept: before/accept initialization LOOP: SSL accept: SSLv3 read client hello A LOOP: SSL accept: SSLv3 write server hello A LOOP: SSL accept: SSLv3 write certificate A LOOP: SSL accept: SSLv3 write key exchange A LOOP: SSL accept: SSLv3 write certificate request A LOOP: SSL accept: SSLv3 flush data LOOP: SSL accept: SSLv3 read client certificate A LOOP: SSL accept: SSLv3 read client key exchange A LOOP: SSL accept: SSLv3 read certificate verify A LOOP: SSL accept: SSLv3 read finished A LOOP: SSL accept: SSLv3 write change cipher spec A LOOP: SSL accept: SSLv3 write finished A LOOP: SSL accept: SSLv3 flush data INFO: SSL accept: SSL negotiation finished successfully LOOP: SSL accept: before/accept initialization INFO: SSL accept: SSLv3 read client hello B INFO: SSL accept: SSLv3 read client hello B INFO: SSL accept: SSLv3 read client hello B etc... I'm runnung on a newish linux, kernel 2.4.21. Both python2.1 and python2.3 display the same result. Regards, Paul Clinch From ad_scriven at postmaster.co.uk Fri Mar 5 05:40:12 2004 From: ad_scriven at postmaster.co.uk (Antony Scriven) Date: 5 Mar 2004 02:40:12 -0800 Subject: vim & python References: <221dd125.0403011151.504ce09d@posting.google.com> <221dd125.0403032332.d4282f4@posting.google.com> <221dd125.0403041853.2c6eb5d6@posting.google.com> Message-ID: spam_bait101 wrote: > Fran?ois Pinard wrote [...] > > > > Thanks for all of the answers to the second question, but what about > > > vim scripting with python? I can not find *anything* about it (no > > > docs, books or tutorials) > > > > Just do: > > > > :h python > > > > Thanks, but that is more like a very abbreviated tutorial. Where can I > can the real documentation? [...] > I want the real documentation for the "vim" module accessible > from vim. What classes, functions, values are defined there, etc :let @/='The vim module'|se hls :h python Is that not it? Antony From skip at pobox.com Thu Mar 4 14:46:58 2004 From: skip at pobox.com (Skip Montanaro) Date: Thu, 4 Mar 2004 13:46:58 -0600 Subject: how fast is Python code - another detail In-Reply-To: <40478323.4060604@aon.at> References: <20040304190419.20224.qmail@web61004.mail.yahoo.com> <40478323.4060604@aon.at> Message-ID: <16455.34738.946872.823285@montanaro.dyndns.org> >>> if sig not in d.keys(): vs. >> if sig not in d.iterkeys(): vs. if sig not in d: The first must build the list of keys then search it sequentially. The second doesn't have to build the entire list, but still searches sequentially. The third effectively tries d[sig] and catches the KeyError exception of sig is not a key in d. The third is O(1) in the general case. The others are O(len(d)). Skip From adam_gautier at yahoo.com Sat Mar 27 12:15:12 2004 From: adam_gautier at yahoo.com (Adam T. Gautier) Date: Sat, 27 Mar 2004 12:15:12 -0500 Subject: httplib problem Message-ID: <4065B6A0.5010105@yahoo.com> I am unable to get the following to work with the httplib.response.read() method. It returns ''. Other URLs work fine with my code just not this one. Do I need to set a header or something? the webserver is Tux I have not tried this on a similar url to apache. http://mirror.linux.duke.edu/pub/fedora/linux/core/1/i386/os/Fedora/RPMS/ Any help would be great. From ark at acm.org Thu Mar 4 14:43:40 2004 From: ark at acm.org (Andrew Koenig) Date: Thu, 04 Mar 2004 19:43:40 GMT Subject: how fast is Python code - another detail References: <404778E4.9090601@aon.at> Message-ID: "Peter Otten" <__peter__ at web.de> wrote in message news:c280b0$1g3$03$1 at news.t-online.com... > key in theDict.keys() > changes the lookup from constant time (a hash value is calculated which is > used as an index into a list of values if all goes well) to proportonial to > len(theDict) because on average half of the list has to be searched before > the matching entry is found. Worse: Evaluating theDict.keys() requires building a list from all the keys. So even if the key is the first element of the list, the run time is O(len(theDict)). Moreover, there's no way for the compiler to optimize such expressions in general, because it doesn't know the type of theDict during compilation. From joe at notcharles.ca Wed Mar 24 08:15:53 2004 From: joe at notcharles.ca (Joe Mason) Date: Wed, 24 Mar 2004 13:15:53 GMT 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: In article , David MacQuigg wrote: > A less generic keyword will lead to odd phrases like "has int" or > "with staticmethod", or different keywords for each phrase. Sure. "has int" is perfectly legible for "this function has the 'int' property". Naming a property "int" would be stupid and confusing, but that's not the syntaxes fault. (Of course, even if we use decorators to name things that can be seen as "properties" of functions - like staticmethod - that's not how they're implemented, so "has" isn't great. "def ... with" as short for "define this with the following decorators" is perfectly legible, though. Different keywords for each phrase wouldn't work at all - there's no set list of phrases! You're supposed to be able to define your own. > 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'm not clear on what you mean by "modified syntax". If it's accepted into the language, it's a standard syntax, so marking it with a symbol makes no sense. If you mean to mark things for preprocessors, sure, a standard symbol would be a great idea, but we're not talking about preprocessors here. > 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? If you mean marking some bits of the language as being second-class, absolutely not. It may make sense to have comment character meaning "ignore the keyword after this - it's for an external, mechanical tool". Doxygen and others already have conventions for this (not to mention the #! syntax), but it would be helpful to have a common agreed-on format. I think that would arise better as something the various tool vendors evolve among themselves, though. Joe From mickel at csc.fi Wed Mar 31 00:36:00 2004 From: mickel at csc.fi (=?ISO-8859-1?Q?Mickel_Gr=F6nroos?=) Date: Wed, 31 Mar 2004 08:36:00 +0300 (EEST) Subject: using third party TCL library In-Reply-To: <20040330164401.60455.qmail@web8308.mail.in.yahoo.com> References: <20040330164401.60455.qmail@web8308.mail.in.yahoo.com> Message-ID: > My question is where can I put this file so that the > TCL invoced from the python shell gets it. On Windows, try putting your Tcl source in a directory like: C:\\Python23\tcl\ On Linux I'm not sure, but you could try something like /usr/local/lib/. Cheers, Mickel Gr?nroos -- Mickel Gr?nroos, application specialist, linguistics, Research support, CSC PL 405 (Tekniikantie 15 a D), 02101 Espoo, Finland, phone +358-9-4572237 CSC is the Finnish IT center for science, www.csc.fi From jmdeschamps at cvm.qc.ca Sat Mar 27 14:39:06 2004 From: jmdeschamps at cvm.qc.ca (jmdeschamps) Date: 27 Mar 2004 11:39:06 -0800 Subject: Python for email? References: Message-ID: <3d06fae9.0403271139.701d1a5e@posting.google.com> "sean" wrote in message news:... > Is there a good module for sending out email? > > For a website that I am working on, I am writing a program that finds out > which presenters have not yet confirmed their scheduled date and sends them > an email to confirm. > > Does python have any modules for use with mail programs like sendmail, or > should I just run everything with os.system and os.popen? > > Thanks for any help. ... and using imaplib, you could *listen* to an email account for confirmations and thus, know if the confirm info as reached the presenters brain !-) jean-marc Spring is in the air From donn at u.washington.edu Wed Mar 24 14:20:50 2004 From: donn at u.washington.edu (Donn Cave) Date: Wed, 24 Mar 2004 11:20:50 -0800 Subject: [OT] Static typing and split brains research References: <4061ca3a$0$124$3a628fcd@reader3.nntp.hccnet.nl> Message-ID: In article <4061ca3a$0$124$3a628fcd at reader3.nntp.hccnet.nl>, anton at vredegoor.doge.nl (Anton Vredegoor) wrote: ... > So after this long intro I would like to make the link to programmers > that are using some kind of programming language and getting results > consistent with their world view. Once one has decided that static > typing is necessary and accordingly uses a statically typed language > the brain just fills in the details and the programmer lives in a > consistent world. The same goes for dynamically typed languages of > course. > > Now imagine a situation where ones job is dependent on "believing" in > some kind of information technology infrastructure. Now we don't even > have the option to believe otherwise, because it would damage our > career opportunities. > > In these circumstances it is incredibly hard to gather scientific > evidence about programmer productivity as correlated to the use of > certain programming languages. But at least we now have begun to > understand *why* that is so hard. I hope someone fills in the blanks > of this theory :-) Bah. I think most of the venom with which people here reject static typing comes from experience with it - either in school or at work. Personally, my enthusiasm for it comes from using Python for approximately a decade. Experience with one may as easily lead to a preference for the other. But not necessarily - experience affects the outcome, but personality, strengths and weaknesses inherent in the individual play a role. And the terms "static typing" and "dynamic typing" are part of the problem. Better say "Java typing", "Hindley-Milner typing" (ML, Haskell), "Python typing", "Perl typing", etc. One reason there is so little agreement on these matters is that we mean different things by the same phrase. Donn Cave, donn at u.washington.edu From claird at lairds.com Sat Mar 27 14:35:45 2004 From: claird at lairds.com (Cameron Laird) Date: Sat, 27 Mar 2004 19:35:45 -0000 Subject: Python for email? References: <106b6ivetpf0bc0@corp.supernews.com> Message-ID: <106blshqp92v4dc@corp.supernews.com> In article , Kyler Laird wrote: >claird at lairds.com (Cameron Laird) writes: > >>smtplib presents a few other, even more marginal issues. If an >>installed MTA enforces institutional standards (disclaimers, archi- >>ving, ...), smtplib is likely to subvert those. > >How so? > >The example for smtplib given here > http://www.python.org/doc/current/lib/SMTP-example.html >appears to relay mail through "localhost". That will typically be >equivalent to using the "installed MTA", right? > >--kyler All true, and by neglecting to read the manual recently, I've confused things. Thanks for the correction. *I* have the habit of doing something that I now see the smtplib documentation does not recommend--'fact, I now suspect that it never did, and that it's my own memory that introduced all the problems. Here's what I should have written before: smtplib is great. If you get in the habit of using it to connect directly to the far endpoint, as I do, you risk the surprise of finding situations where a local MTA is an advantage. In any case, though, smtplib can always be configured do at least as much for you as shelling out to a local mailer. -- Cameron Laird Business: http://www.Phaseit.net From dmq at gain.com Sat Mar 6 19:54:45 2004 From: dmq at gain.com (David MacQuigg) Date: Sat, 06 Mar 2004 17:54:45 -0700 Subject: ready to use python, need help with GUI decision References: Message-ID: <8dqk409dl1ncfq77kfipe7bj7dt64p0iif@4ax.com> On 07 Mar 2004 00:05:38 +0200, Ville Vainio wrote: >>>>>> "David" == David MacQuigg writes: > > David> On Wed, 3 Mar 2004 18:15:44 +0000, Jonathon McKitrick > David> wrote: > > David> I believe the licensing issue with Qt is overblown. If > David> your work is purely non-commercial, use the GPL license. > David> If you are a typical commercial developer, it should be no > David> problem to pay $1550 per developer license (no runtime > David> royalties). I've heard there are problems for commercial > David> developers who can't afford the $1550. I would say, don't > David> worry. If your project fails to make a profit, I really > David> doubt Trolltech is going to sue you. I think they would be > David> quite happy to get the first $1550 of any successful > David> project. > >So you urge people to break copyright law until they can afford to pay >the license? I would expect such a behaviour to prove extremely >problematic and dangerous. I'm not urging anyone to break the law, not even those few commercial developers who can't afford the the license. What I'm saying is that if you are in this rare situation, can't afford the licesne, and not sure your product will ever be sold, you just have to be careful not to release the product before paying your dues. The only "danger" I can see is that code developed before you have paid for the commercial license could get loose and allow someone to claim it as GPL and avoid paying your license. Maybe I'm misunderstanding the problems and dangers you forsee. Could you be more specific? >I would suggest instead that all the "valuable", back end parts of a >program be coded UI-independently (good idea in any case), and then >finally GUI is tacked on by connecting it to the back end via CORBA >(or equivalent). That way the GUI (which is worthless w/o the back >end) can be GPL'd. This seems to me a deliberate thwarting of Trolltech's intentions. It may be legal, but to me it seems like taking advantage of their generosity in offering a GPL license at all. I also question the legality. It gets down to a question of whether "connecting via CORBA" is equivalent to "linking". There is certainly more danger in that than anything I am suggesting. There is also danger on the GPL end. It seems like what you are suggesting is no different than releasing a program under GPL, but with-holding a key piece for which you charge a license. >OTOH, I would probably just use GTK or wxPython. In fact, I wouldn't >even bother learning Qt - GPL or a crapload of Euros probably won't be >terms an average employer would approve (esp. if you have to use >Windows at work), so Qt would be restricted to home use alone. Once it is clear your project will go commercial, just pay the license and avoid the worries. Surly $1550 is no big deal at that point. I have never understood the intensity of this debate over the Qt licenses. I guess I never will. -- Dave From peter at engcorp.com Fri Mar 12 13:29:48 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 12 Mar 2004 13:29:48 -0500 Subject: Deprecating reload() ??? In-Reply-To: References: <40514A48.50907@domain.invalid> Message-ID: Skip Montanaro wrote: > Regarding > > >> del sys.modules['modulename']; import modulename > > vs. > > >> del modulename ; import modulename > > Peter sez: > > Peter> Just to clarify, *neither* of the above solutions does anything > Peter> useful, as far as I know. Only reload() will really reload a > Peter> module. Certainly the del mod/import mod approach is practically > Peter> a no-op... > > Not so. del sys.modules['mod']/import mod is effectively what reload() > does. Oops, sorry. On reflection that seems logical, but I thought there was a little more to reload() than just this. :-( -Peter From ville at spammers.com Wed Mar 24 05:26:32 2004 From: ville at spammers.com (Ville Vainio) Date: 24 Mar 2004 12:26:32 +0200 Subject: Python for large projects References: <1060p59d9rg9819@corp.supernews.com> Message-ID: >>>>> "Jacek" == Jacek Trzmiel writes: Jacek> Jacek Generowicz wrote: >> ... and one thing that makes unit testing very difficult, is >> static typing ... Jacek> Care to provide some examples to back this opinion up? Programming is just a lot of work in statically typed languages, so you need to work very hard to get even the basic functionality working. You might not have energy/time/money to make proper unit tests after/during the development. I'm not sure whether this is because of static typing in general, or just because current industry-standard statically typed languages suck. -- Ville Vainio http://tinyurl.com/2prnb From fma at doe.carleton.ca Mon Mar 29 19:28:31 2004 From: fma at doe.carleton.ca (Fred Ma) Date: 30 Mar 2004 00:28:31 GMT Subject: Choosing Perl/Python for my particular niche References: <40661C14.8365E058@doe.carleton.ca> Message-ID: <4068BF28.3821F416@doe.carleton.ca> Aahz wrote: > > 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. > > The reason people say this is because algorithmic experimentation is > cheap in Python/Perl. An O(NlogN) algorithm in Python/Perl will lose to > an O(N^2) algorithm in C/C++ with a few elements, but as the data set > grows, the O(NlogN) algorithm will pull ahead. The STL library brings in some efficiently implemented algorithms to the C++ world instead of having programmings roll their own code. The problem I saw with matlab was the overhead in between calling such algorithms. For example, all the individual built-in's work fast, but the moment you call your own function, you lose all the speed that was painfully obtained by carefully crafted code. In fact, if you rely on loops containing complex control flow, it hinders matlab's acceleration technology (which vectorizes loop operations). Same with many operators. In another response, I mentioned that to ensure that one wouldn't run into similar difficulties with Perl/Python would require a real-sized application to be implemented and tested, with all the features such as overhead between function calls -- a nontrivial task. So that's put off as a possibility until after graduation, since there's more than enough to try to achieve before then. Anectdotal accounts are welcome, of course. Meantime, I'm looking at Perl/Python for mulching design data to feed various apps (notably, my algorithms, or to adequately change verilog files to accommodate limitations in a tool like verilator, as an example). Fred -- Fred Ma Dept. of Electronics, Carleton University 1125 Colonel By Drive, Ottawa, Ontario Canada, K1S 5B6 From grelens at NOSPAMyahoo.NOTNEEDEDfr Thu Mar 4 11:08:34 2004 From: grelens at NOSPAMyahoo.NOTNEEDEDfr (GrelEns) Date: Thu, 4 Mar 2004 17:08:34 +0100 Subject: i'm lost in list manipulation References: <40460bb3$0$28116$636a15ce@news.free.fr> <404653cb$1_1@themost.net> <4046e6d6$0$4677$626a14ce@news.free.fr> <4046e8c1$0$4666$626a14ce@news.free.fr> <7xbrnd54uj.fsf@ruckus.brouhaha.com> Message-ID: <40475472$0$29947$626a14ce@news.free.fr> "Paul Rubin" a ?crit dans le message de news: 7xbrnd54uj.fsf at ruckus.brouhaha.com... > "GrelEns" writes: > > i'm not happy with this code, must be an other shorter alternative, have you > > any siggestions on how to build these sets [[1], [2], [3], [1, 2], [1, 3], > > [2, 3], [1, 2, 3]] from [1,2,3] ? > > def subsets(lst): > def subgen(lst): > if not lst: > yield lst > return > for s in subsets(lst[1:]): > yield s > yield [lst[0]] + s > return list(subgen([1,2,3]))[1:] # discard empty subset > > print subsets([1,2,3]) sorry, i miss something here probably loosing indentation as my version contain an infnite recursion, can you repost it ? thanx btw it looks like very impressive. From premshree_python at yahoo.co.in Sat Mar 6 10:57:15 2004 From: premshree_python at yahoo.co.in (=?iso-8859-1?q?Premshree=20Pillai?=) Date: Sat, 6 Mar 2004 15:57:15 +0000 (GMT) Subject: Image width, height. In-Reply-To: <2004030107172838165%bob@redivicom> Message-ID: <20040306155715.94143.qmail@web8311.mail.in.yahoo.com> --- Bob Ippolito wrote: > On 2004-03-01 06:38:11 -0500, Premshree Pillai > said: > > > Hello, > > > > Is there a Py module available using which I can > find > > the width and height of any image format? > > ANY image format is a tall order, however PIL is > pretty good at it, and > supports a large number of image formats. > > >>> import Image > >>> Image.open('testorig.jpg').size > (227, 149) > > Note that even if you don't have a JPEG decoder > available, PIL bakes in > enough support for the format to let you get the > image dimensions out > of the header. I'd imagine that this is generally > true with the rest > of PIL, too. > > -bob > > -- > http://mail.python.org/mailman/listinfo/python-list Worked like a charm. Thanks! Updated version of pyAlbum.py at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/271246 -Premshree Pillai ===== -Premshree [http://www.qiksearch.com/] ________________________________________________________________________ Yahoo! India Insurance Special: Be informed on the best policies, services, tools and more. Go to: http://in.insurance.yahoo.com/licspecial/index.html From donn at u.washington.edu Fri Mar 19 13:44:04 2004 From: donn at u.washington.edu (Donn Cave) Date: Fri, 19 Mar 2004 10:44:04 -0800 Subject: Static Typing in Python References: <4055a71e$0$28265$afc38c87@news.easynet.co.uk> Message-ID: In article , Jacek Generowicz wrote: > Donn Cave writes: > > > Speaking of which, Haskell's type system supports type classes > > like Num (number), where Int and Float are instances of Num > > that implement its "+" function. > > This is pretty much what you'd do in OCaml too, I believe. > > > I'm probably leaving out a paragraph or two of the interesting > > parts, but the end result is that 1.5 + 1 works. Haskell is not > > weakly typed. > > But the point is that the programmer conrols whether the automatic > conversion is done or not. In weakly typed languages you get the > conversion whether you want it or not. I don't know, the mechanism I alluded to above doesn't really involve the programmer. 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. It doesn't just do it any time a value oppears in a context that requires a specific type - the awk/perl weak typing - but 1.5 + 1 does work, without any programmer intervention and without weak typing. Donn Cave, donn at u.washington.edu From michele.simionato at poste.it Tue Mar 23 05:50:38 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 23 Mar 2004 02:50:38 -0800 Subject: Voting (was Re: PEP 318 References: Message-ID: <95aa1afa.0403230250.4c9da7a2@posting.google.com> Ville Vainio wrote in message news:... > >>>>> "Skip" == Skip Montanaro writes: > > Skip> It will probably be a BDFL pronouncement. After all, that's > Skip> why he's the > > Of course it will - still, that didn't stop us from voting before :-). Ick! Having passed through PEP 308, I just prefer directly agree with Guido's decision without any votation at all ;) Michele Simionato From tjreedy at udel.edu Sat Mar 6 23:40:06 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 6 Mar 2004 23:40:06 -0500 Subject: ready to use python, need help with GUI decision References: <20040303181544.GB74292@dogma.freebsd-uk.eu.org> <4046EE84.9080700@rebirthing.co.nz> <6Fu2c.2306$G3.18772@localhost> <404A9BAB.7030503@stackless.com> Message-ID: "Christian Tismer" wrote in message news:404A9BAB.7030503 at stackless.com... > I will look into PyGame, which does not have a GUI at all, There is a gui-sort-of-package 'associated' in some sense with PyGame. Forget name. Main difference from 'imitate native look and feel' packages is that one can define own renderer to give quite different look and feel, as most games do. tjr From guettli at thomas-guettler.de Wed Mar 31 02:23:50 2004 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Wed, 31 Mar 2004 09:23:50 +0200 Subject: Creating Charts Message-ID: Hi! I need to create some simple charts with python. A list contains integers between 0 and mymax. I want to see how the values are distributed (How many are 0, how many are mymax, ...). The result should be a small (200x200) png file. I searched a bit: - gnuplot: Too big, too complicated - matplotlib: Too much gtk binding (I only need a png) - reportlib: Needs PIL. First try failed (_renderPM missing) Any hints on how to create charts? There need not to be a python-binding. I can call the external application with os.system(). Operating System: Linux 2.4.20 Thanks, Thomas From __peter__ at web.de Sun Mar 28 07:54:49 2004 From: __peter__ at web.de (Peter Otten) Date: Sun, 28 Mar 2004 14:54:49 +0200 Subject: Newbie Class Questions References: <94CdnVqi7o8rn_vdRVn-vg@centurytel.net> Message-ID: 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__()), {}) (assuming the subclasses are not subclassed themselves). 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. Peter From jon at joncruz.org Thu Mar 4 01:05:17 2004 From: jon at joncruz.org (Jon A. Cruz) Date: Wed, 03 Mar 2004 22:05:17 -0800 Subject: OFF-TOPIC:: Why Lisp is not my favorite programming language References: <165b3efa.0403030443.4d591f04@posting.google.com> <40460dd5$0$5916$7a628cd7@news.club-internet.fr> Message-ID: <4046C71D.9060008@joncruz.org> Jorge Rivera wrote: >> >> As for me, I would say practically the same things about Java. :-p >> > > Wow, you are comparing a fairly useless language (Lisp) with a powerful > and flexible languange (Java), and would come up with the same arguments > as to why it sucks? Well, I happen to use that "fairly useless" language daily in working with Java. :-) http://jdee.sunsite.dk/ (Sorry, guys. Couldn't resist) From pxlpluker at cfl.rr.com Sun Mar 7 09:06:29 2004 From: pxlpluker at cfl.rr.com (pxlpluker) Date: Sun, 07 Mar 2004 09:06:29 -0500 Subject: Pushing file name to browser In-Reply-To: References: Message-ID: <404B2C65.2040601@cfl.rr.com> Thank you very much. I think that is exactly what I wanted. I really could not find this info anywhere Where could I find reference to this information? Hakan Nilsson wrote: >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! > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From timr at probo.com Thu Mar 11 01:14:22 2004 From: timr at probo.com (Tim Roberts) Date: Wed, 10 Mar 2004 22:14:22 -0800 Subject: a desired python editor References: Message-ID: Nick Vargish wrote: > >I always come back to (X)Emacs in the end. >... >Sometimes I try out the current crop of editors, but it always seems >as though I'm just playing. Like I said, I always come back to >(X)Emacs in the end. Mmmm... Powerful is the dark side. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From s4somesh at yahoo.co.in Wed Mar 3 08:07:15 2004 From: s4somesh at yahoo.co.in (Somesh Bartakkay) Date: 3 Mar 2004 05:07:15 -0800 Subject: Python Event in India .. Message-ID: <5cc5bb23.0403030507.120598f6@posting.google.com> Am basically from India - Pune. here is very less (say NO) Python AwareNess .. so i wanna increase it.. am trying in my own way but for making it in VERY proffesional manner and on very HIGH level ...its necessary to arrange Python Event here. shall anyone guide me how it is possible ? Python Even in INDIA will surely PAY gr8 brains to Python Community ... somesh From theller at python.net Fri Mar 5 13:38:30 2004 From: theller at python.net (Thomas Heller) Date: Fri, 05 Mar 2004 19:38:30 +0100 Subject: Windows command-line length limitation (was Re: is perl better?) References: Message-ID: >> the total string is 6809 characters long. > > This is likely far too long for the Windows command line, but perhaps > 2000 is more sophisticated than I would expect... > >> I do not know the allowed character length (I am using windows 2000) >> but perl just runs the command fine, whereas python results in >> The following character string is too long: Just to throw in some real numbers, MSDN knowledge base article 830473 says: """ On computers running Microsoft Windows XP or later, the maximum length of the string that you can use at the command prompt is 8191 characters. On computers running Microsoft Windows 2000 or Windows NT 4.0, the maximum length of the string that you can use at the command prompt is 2047 characters. This limitation applies to the command line, individual environment variables (such as the PATH variable) that are inherited by other processes, and all environment variable expansions. If you use Command Prompt to run batch files, this limitation also applies to batch file processing. """ Read the article to found out more (but not much more). BTW: The workarounds that the article mentions sound more like the old MSDOS days than like a modern operating system. Ridiculous examples: # Use shorter names for folders and files. # Reduce the depth of folder trees. # Store files in fewer folders so that fewer folders are # required in the PATH environment variable. Thomas From cxprotectr at mail3.s2lmail.com Mon Mar 15 14:28:08 2004 From: cxprotectr at mail3.s2lmail.com (CxProtect) Date: Mon, 15 Mar 2004 14:28:08 -0500 Subject: Recipient: Have detected a virus () in your mail traffic on 15-Mar-2004 with an action Deleted. Message-ID: A non-text attachment was scrubbed... Name: not available Type: multipart/alternative Size: 2 bytes Desc: not available URL: -------------- next part -------------- CxProtect?: Virus Found Notification ------------------ Virus Warning Message (on mail3.s2lmail.com) Email From "geospack at erols.com" was security checked by 3.90 version of CxProtect(tm) Checked on: mail3.s2lmail.com at: 14:26:58, 15-Mar-2004 Monday Engine: 4.97.1F, sign.def:15-Mar-2004, sign2.def:15-Mar-2004, macro.def:15-Mar-2004 Scanning Options Used : ----------------------- Scan inside .ZIP and .ARJ files. Disinfect whenever possible. Scan compressed executables. Scan of all type of files. Remove infected Contents in attachments (Neutralize). Detect standard Zip files irrespective of file extension. Clean inside standard Zip files. From: geospack at erols.com Subject: Re: Re: Thanks! 01. Name: noname (Type: text/plain) >> * No virus found * << 02. Name: document.pif (Type: application/octet-stream) >> * Deleted * << + Neutralized + document.pif is a security risk or a "backdoor" program 03. Name: noname (Type: text/plain) >> * No virus found * << CxProtect Cleaned 0 infections and Neutralized : 1 --------------------------------------------------------- CxProtect? was originally designed, just to demonstrate the power of Command AntiVirus? . -------------- next part -------------- An HTML attachment was scrubbed... URL: From claird at lairds.com Tue Mar 9 16:37:15 2004 From: claird at lairds.com (Cameron Laird) Date: Tue, 09 Mar 2004 21:37:15 -0000 Subject: getting size of gif References: <9L2dna_mgLuovNPd4p2dnA@comcast.com> Message-ID: <104se8bhc5rm477@corp.supernews.com> In article <9L2dna_mgLuovNPd4p2dnA at comcast.com>, Larry Bates wrote: >Get PIL (Python Imaging Library) if you don't already have it > >http://www.pythonware.com/products/pil/index.htm/ > >import Image >pathtogif=r'C:\xxx.gif' # Replace with your path >im=Image.open(pathtogif) >x,y=im.size >im.close() . . . It doesn't require all of PIL, though, for those who have a reason *not* to rely on it; it just takes a couple of byte-twiddles. can easily be translated into pure Python. -- Cameron Laird Business: http://www.Phaseit.net From boole at netcologne.de Sun Mar 14 07:10:05 2004 From: boole at netcologne.de (george) Date: Sun, 14 Mar 2004 13:10:05 +0100 Subject: Python/Tkinter - problem with "wm_attributes" Message-ID: <40544B9D.1000706@netcologne.de> Greetings to all experts. I'm running Python 2.3/Pythonwin 1.63 on Windows 98. I would like to create a window with Tkinter, that is always on top of the screen. In Tkinter.py, Line 1375 f., I'm reading: "On Windows, ... -topmost gets or sets whether this is a topmost window (displays above all other windows)." Therefore my simple code is: ################################# # topmost.pyw from Tkinter import * root = Tk() root.wm_attributes("-topmost", 1) root.mainloop() ################################# Started in IDLE (without the last line), the script runs successful. Started in Pythonwin or executed from the Windows Explorer, it seems to run endless, nothing happens, no window appears. Other settings of attributes (-disabled, -toolwindow) failed in the same way. What do I have failed to notice? Thanks for your help, george From Sibylle.Koczian at Bibliothek.Uni-Augsburg.de Wed Mar 24 09:09:39 2004 From: Sibylle.Koczian at Bibliothek.Uni-Augsburg.de (Sibylle Koczian) Date: Wed, 24 Mar 2004 15:09:39 +0100 Subject: mxDateTime function DateFromString gives wrong year Message-ID: This is very nearly a repetition of a post by Peter Hansen from 2002-07-07 which never got an answer: >>> x = mx.DateTime.Parser.DateFromString('Nov 2003') >>> x Using mx.DateTime Version 2.0.5 for Python 2.3 and ActivePython 2.3.2. The original posting had the same problem with 'October 29/2000'. This isn't corrected either, it still converts to 2004-10-29. 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 edwin at localhost.localdomain Thu Mar 18 10:25:27 2004 From: edwin at localhost.localdomain (Edwin Young) Date: 18 Mar 2004 07:25:27 -0800 Subject: PyGTK: creating a pixbuf from image data References: Message-ID: John Hunter writes: > >>>>> "Edwin" == Edwin Young writes: > > Edwin> Hi, > > Edwin> I'm writing a fractal-generating program in a mixture of C > Edwin> and Python. Python handles all the GUI parts using > Edwin> PyGTK. After finishing the calculations, I have a buffer > Edwin> containing the RGB data of the image. I can display this > Edwin> fine on screen using draw_rgb_image. Now I need to save the > Edwin> image data into a file. gtk.gdk.Pixbuf.save() > > gtk.gdk.Pixbuf does have a save method Right, the problem is getting the data *into* the pixbuf in the first place. Basically I have the image in a long string in memory and need to get that into the Pixbuf somehow. The pixel_array is read-only, so I can't use that. I don't think Gustav's idea will work because the loader expects the *encoded* pixels (+ header, etc) from a jpeg file, and if I already had a jpeg encoder I could just save the file myself. Thanks, -- Edwin From joe at notcharles.ca Wed Mar 24 08:55:42 2004 From: joe at notcharles.ca (Joe Mason) Date: Wed, 24 Mar 2004 13:55:42 GMT Subject: PEP 318 References: <95aa1afa.0403222352.2679dde@posting.google.com> <95aa1afa.0403232104.328356ea@posting.google.com> Message-ID: In article , Ville Vainio wrote: > Andrew> Which is to say, I don't understand how that can work -- > Andrew> the first definition of foo gets clobbered. > > Yes, the name 'foo' gets clobbered every time, but the decorator > always returns the *dispatcher* that is capable of dispatching the > call to the correct definition of 'foo'. The dispatcher preserves the > references to the callables, so they don't get decreffed out of > existence. Except the dispatcher gets clobbered by the second "def foo". Unless it's held in a global and looked up by name... That might be something worth thinking about. Right now, you can always do this: class C: def foo(self, other): ... foo2 = multimethod(Matrix, Matrix)(foo) def foo(self, other): ... foo2 = multimethod(Matrix, Vector)(foo) foo = foo2 undef foo2 The decorator syntax is less flexible. But the whole problem goes away if the decorators are applied between the creation of the function and the binding: 1. make an anonymous function 2. if there are decorators pass it through each in turn, replacing the function with the return value 3. bind the result to the name However, that means the name is unavailable inside the decorators. > Andrew> You *could* have a global registry that's keyed off > Andrew> func_name, as you suggest, but that doesn't work in > Andrew> general... what if I later have: > > Andrew> class C2: > Andrew> def foo(self, other): > Andrew> ... > Andrew> foo = multimethod(Long, String)(foo) > > Andrew> How is the registry not going to help distinguish between > Andrew> the foo methods from C, and the foo methods from C2? Well, obviously you use the mangled name. The real problem comes when you actually do want to throw your multimethod away and use a brand new foo. Joe From theller at python.net Sat Mar 20 11:10:25 2004 From: theller at python.net (Thomas Heller) Date: Sat, 20 Mar 2004 17:10:25 +0100 Subject: py2exe 0.5.0 and data_files References: <87fzc4h036.fsf@u-go.net> Message-ID: <65czjy8e.fsf@python.net> Ulrich Goertz writes: > Hello, > > I am trying to understand how py2exe 0.5.0 deals with data files. > My application tries to access certain data files via sys.path[0] > (e.g. the file 'menus.def' which lies in the same path as the > python script (or the .exe which py2exe produces, respectively) > is accessed via os.path.join(sys.path[0],'menus.def'). > > Now I have the data files which I need in the data_files list given > as an argument to the setup method, and py2exe does copy them to > the dist subdirectory all right. However, sys.path[0] is not the > path where the program resides, but the path + 'library.zip'. > > Is there an elegant way to proceed? Of course, I could remove the > 'library.zip' to find the actual path, but that somehow does not > look like the 'right thing'. I would prefer a solution which works > for the genuine Python script (not packaged by py2exe) as well as > for the .exe. There is a sample 'hello.py' in the py2exe\samples\simple subdirectory, which lets you explore the differences between the normal Python script, and the executable. I don't have time now - more later. Thomas From jcb at iteris.com Sat Mar 13 02:08:19 2004 From: jcb at iteris.com (MetalOne) Date: 12 Mar 2004 23:08:19 -0800 Subject: Python style guidelines References: <3064b51d.0403101112.3449e987@posting.google.com> <4050EAA3.9010807@wberry.org.x> Message-ID: <92c59a2c.0403122308.35513650@posting.google.com> I do not like style guidelines either. If one method can be factually proven better than another method, then it would make sense to encourage the better method. However, when this can't be done, then the guideline is simply based upon taste or gut instinct or personal preference. These all vary from person to person and who is to say what is correct. During my schooling I was taught to always place statements on their own line. x = 0 y = 0 z = 0 I accepted this completely without thinking about it much. 20 years later I have finally come to realize that if (x,y,z) represents a point that x = y = z = 0 or (x,y,z) = (0,0,0) is not always so bad. It conserves lines of code, and being able to see more lines of code at one time is beneficial. Some guidelines recommend functions with only a single return point. I don't understand why this insanity got started. At one point it was recognized that multiple entry points into a function was confusing, but why did it have to get extrapolated to multiple exit points. Upon entry to a function, I sometimes like to verify that everything is ok before proceeding and if it is not just get out. Parameters can validated, resources acquired, or whatever. At my work we currently have a guideline to always use brackets in "if" statements. if { single statement } else { single statement } Simply on the basis that somebody might forget the braces when adding another statement to the block. Has this ever actually happened? What about actually testing the code? It is not too onerous of a guideline, but it does increase lines of code, which affects the ability to easily see more code, which affects overall readability in some cases. Even the usual guideline of placing statements on separate lines I think is sometimes a mistake. if cond: statement elif cond: statement else: statement does not always seem too bad to me where you always just have a single statement. Somebody once convinced me that I should always use descriptive unabreviated variable names. At first this advice seemed a little strange to me. Most code that I had ever encountered abreviated variable names. Vowels tend to be left out. I think it might be a FORTRAN hold over where variables had to be 6 characters or less or was it 8. After a while, I realized people do things like cnt, instead of count. sz instead of size. tmr instead of timer. 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. Expressions are just easier to read. You can simply comment what 'x' means. So variable length is not always so simple to decide upon. And so it goes. I guess I am a believer in TIMTOWTDI. The other thing about guidelines is that once somebody publishes a book with guidelines, lookout. Your employer may soon have you following them all whether you agree with them or not. Rational Rose and UML are great examples of this, but that is another story. From boober95 at rogers.com Tue Mar 2 08:58:54 2004 From: boober95 at rogers.com (Bill) Date: Tue, 02 Mar 2004 13:58:54 GMT Subject: Access 'active directory' from Python on Linux ... Message-ID: Has anyone had experience in accessing MS 'active directory' from Python running on Linux? I've found a few pointers from searching, but a hint might save me some time since setting up the solution might take a bit of effort (and then not work)! From what I can tell you can do it from Python running under Windows, but under Linux seems to require 'openldap'. Bill From sunilmovva at hotmail.com Tue Mar 16 12:08:45 2004 From: sunilmovva at hotmail.com (Sunil Movva) Date: 16 Mar 2004 09:08:45 -0800 Subject: xml.minidom and threads References: <9106c987.0403120759.6b1df015@posting.google.com> <2c60a528.0403150103.1896dbbc@posting.google.com> Message-ID: <9106c987.0403160908.6eafbb3c@posting.google.com> and-google at doxdesk.com (Andrew Clover) wrote in message news:<2c60a528.0403150103.1896dbbc at posting.google.com>... > Sunil Movva wrote: > > > So, I came to suspect if xml.minidom module is thread-safe. > > No it isn't, but I doubt this is your problem as you don't seem to be > trying to access the DOM Nodes from multiple threads, let alone > concurrently. (Is there any good reason why you need to serialise and > re-parse between each thread?) > > A SAXParseException is generally what it says on the tin, caused by > faulty syntax in the XML document being parsed. It is conceivable that > minidom's serialisation code at the second-thread-output stage is > producing something wrong; we'd have to have a look at the string the > third thread is trying to parse to find out what. I was able to fix this problem. It has nothing to do with thread-safety. The function xml.dom.minidom.parseString() throws invalid token exception on trying to parse unicode strings. I forced my app to use regular strings instead. Thanks for the response. -Sunil From ville at spammers.com Sat Mar 6 06:38:10 2004 From: ville at spammers.com (Ville Vainio) Date: 06 Mar 2004 13:38:10 +0200 Subject: is perl better? References: Message-ID: >>>>> "Christian" == Christian Tismer writes: >> 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. Christian> Well, I never claimed that Python is always better than Christian> Perl. There are cases where Perl is really better than Christian> Python. This might be such a case, and I don't mind. I don't think this has anything to do with language features. It's a library issue. Perl achieves the functionality by some system calls, and I can't see why Python couldn't be made to execute the same system calls. In fact it would seem trivial, Perl is OSS after all. -- Ville Vainio http://tinyurl.com/2prnb From dave at pythonapocrypha.com Tue Mar 9 18:24:44 2004 From: dave at pythonapocrypha.com (Dave Brueck) Date: Tue, 9 Mar 2004 16:24:44 -0700 Subject: Can't connect Postgres to Python References: <404E4F96.8000701@sstar.com> Message-ID: <035201c4062d$b4f0a020$6401fea9@YODA> John wrote: > I have tried PostGreSQL, PyGreSQL, pypgsql, psycopg, and PDO and have > yet to connect to PostgreSQL 7.4 (.1 in one box, .2 in the other). > > With PostGreSQL-3.4 and pypgsql-2.4, using setup.py build results in > "error: command 'gcc' failed with exit status 1." > > I couldn't install psycopg-1.1.11 because it asks for PgSql header > files; the only one I can identify is postgres.h. I've been using pyscopg-1.1.11 with PostgreSQL 7.4 and Python 2.3 on Mandrake 9.2 and have found it to work really well for my needs. To get it to build I had to do cp -r postgres-7.4/src/include/catalog /usr/local/pgsql/include/ to get the headers in the right place. Also had to install mxDateTime first. HTH, -Dave From mwh at python.net Mon Mar 15 08:21:56 2004 From: mwh at python.net (Michael Hudson) Date: Mon, 15 Mar 2004 13:21:56 GMT Subject: Fatal Python error: Inconsistent interned string state References: <85c78d18.0403122239.4be5ad04@posting.google.com> Message-ID: bmorgan at usa.net (Byron Morgan) writes: > Anyone run into this before? > > I have a python app that has been reliable, running for days on end > without a crash. Suddenly, It repeatedly crashes with the following > message: Is this reproducable? What extension modules are you using? It sounds like you have a memory scribble somewhere, good luck. Cheers, mwh -- MARVIN: What a depressingly stupid machine. -- The Hitch-Hikers Guide to the Galaxy, Episode 7 From aahz at pythoncraft.com Mon Mar 29 11:57:02 2004 From: aahz at pythoncraft.com (Aahz) Date: 29 Mar 2004 11:57:02 -0500 Subject: Choosing Perl/Python for my particular niche References: <40661C14.8365E058@doe.carleton.ca> Message-ID: 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. The reason people say this is because algorithmic experimentation is cheap in Python/Perl. An O(NlogN) algorithm in Python/Perl will lose to an O(N^2) algorithm in C/C++ with a few elements, but as the data set grows, the O(NlogN) algorithm will pull ahead. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "usenet imitates usenet" --Darkhawk From rogerb at rogerbinns.com Tue Mar 30 19:17:42 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Tue, 30 Mar 2004 16:17:42 -0800 Subject: Python Documentation Blows! References: Message-ID: <6afpj1-qbb.ln1@home.rogerbinns.com> > What would it take to develop an JavaDoc like repository. Have you seen what epydoc produces? Here is an example: http://epydoc.sourceforge.net/stdlib/ I have found *by far* that the best docs are for PHP. It has little to do with the actual official content (which is fairly complete and well written and almost always includes an example), but a lot to do with how anybody can annotate the pages, wiki style. Here is an example for the sort function: http://us2.php.net/manual/en/function.sort.php Having all those comments is really helpful, and they also help for updating the documentation. If there are a lot of comments against a page then the main body really needs some more work! (And for those of you who don't know PHP, you will find the commentary confusing. This is because one of the authors of PHP decided that a list is the same thing as a dict with numeric keys, and so PHP only has a dict type that behaves like lists and dicts. I won't even mention the tripe equals sign operator!) Roger From rogerb at rogerbinns.com Mon Mar 8 16:14:05 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Mon, 8 Mar 2004 13:14:05 -0800 Subject: Working around a lack of 'goto' in python References: Message-ID: > Look, a bug! > > With this "feature", you have to scan the entire body of the loop > looking for a numeric break/continue if you're going to change the > indentation level, then increment or decrement the number. Yes, but you can screw up any code when adding loops. Original: while some condition: do work if condition1: continue if other condition: break do work Add a loop: while some condition: do work for item in stuff: if condition1: continue if other condition: break do work Look, a bug! (The continue and break should be jumping two levels). Roger From antonyliu2002 at yahoo.com Sat Mar 13 03:29:09 2004 From: antonyliu2002 at yahoo.com (Anthony Liu) Date: Sat, 13 Mar 2004 00:29:09 -0800 (PST) Subject: How to read one byte at a time in Python? In-Reply-To: Message-ID: <20040313082909.49602.qmail@web13007.mail.yahoo.com> Yes, during file input, I think that read(1) should satisfy my needs. Although in some cases, I will have to do read(2) for Chinese characters. Thanks --- Peter Hansen wrote: > Anthony Liu wrote: > > > Java has functions that read only one byte at a > time, > > do we have such a function in python? > > Skip assumed you meant during user input. Is that > what you meant, or > did you mean during input from a file or something? > read(1) would do > that, of course... > > -Peter > -- > http://mail.python.org/mailman/listinfo/python-list __________________________________ Do you Yahoo!? Yahoo! Mail - More reliable, more storage, less spam http://mail.yahoo.com From secchi at sssup.it Tue Mar 2 05:52:49 2004 From: secchi at sssup.it (Angelo Secchi) Date: Tue, 2 Mar 2004 11:52:49 +0100 Subject: Little explanation Message-ID: <20040302115249.3d2a897b.secchi@sssup.it> Hi, few days ago I had a problem of converting floating from an IBM/370 system to the actual standard. Thanks to a couple of you (Anton and Howard) I got the code to solve the problem that as expected works fine. I (a newbie not only with Python but also with programming) tried to understand the code by myself but finally I decided to bother the list again for a couple of explanations. First here the code I'm referring to: def ibm370tofloat(fourbytes): i = struct.unpack('>I',fourbytes)[0] sign = [1,-1][bool(i & 0x100000000L)] characteristic = ((i >> 24) & 0x7f) - 64 fraction = (i & 0xffffff)/float(0x1000000L) return sign*16**characteristic*fraction What is difficult to understand for me is the meaning of the bitwise operator &. In particular what do expressions like i & 0x100000000L (i >> 24) & 0x7f i & 0xffffff mean? I know what the objects involved are, I found what 0x stands for and I read the tutorial about Numerical Literals but it is not very clear to me the underlying logic of this three lines of code. Can anyone give me some hints? Also a suggestion where I can find the answers by myself would be very helpful. Angelo -- ======================================================== Angelo Secchi PGP Key ID:EA280337 ======================================================== Current Position: Graduate Fellow Scuola Superiore S.Anna Piazza Martiri della Liberta' 33, Pisa, 56127 Italy ph.: +39 050 883365 email: secchi at sssup.it www.sssup.it/~secchi/ ======================================================== From kamikaze at kuoi.asui.uidaho.edu Mon Mar 1 17:23:56 2004 From: kamikaze at kuoi.asui.uidaho.edu (Mark 'Kamikaze' Hughes) Date: 1 Mar 2004 22:23:56 GMT Subject: How does Ruby compare to Python?? How good is DESIGN of Ruby compared to Python? References: <92c59a2c.0402242319.3a5020d8@posting.google.com> <9-udneX41tPP1KLdRVn-jQ@speakeasy.net> Message-ID: A.M. Kuchling wrote on Fri, 27 Feb 2004 07:42:42 -0600: > On 27 Feb 2004 10:36:39 +0200, > Ville Vainio wrote: >> If you are jonesing for a new language to play with, you could as well >> play with Lisp. At least you would learn something new. > That's pretty much my reaction to Ruby, too. It's kind of neat, and if I > was a Perl person I'd go use Ruby instead of waiting for Perl 6, but it > isn't so different from the existing scripting languages. The primary virtue of Perl used to be that it was the only language with decent regexp support. But now everyone has good regexp support. > If your interest > is in learning new ways of programming that turn your head around, you'd > need to look farther afield (Haskell, ML, Lisp, etc.). And I'd second either OCaml or Haskell as good languages if you want to learn something new, while still being useful for real work. Pure ML is rather awful to do real work in, though it can be done if you're sufficiently functional-minded. OCaml is a pragmatic compromise of ML with programming reality. Haskell, too, is a fairly pragmatic design. I don't think you should deploy either one where someone else might have to maintain your code, but they're educational. Self would be another good educational language, but its current implementation is not very portable. -- Mark Hughes "Doing the impossible makes us mighty." -Captain Malcolm Reynolds, Firefly From Olivier.Dormond at epfl.ch Wed Mar 24 03:53:19 2004 From: Olivier.Dormond at epfl.ch (Olivier Dormond) Date: 24 Mar 2004 10:53:19 +0200 Subject: mod_python and unicode Message-ID: Hi, I'm writing a few web tools in python using mod_python which interact with an LDAP server. The server's answers are UTF-8 encoded and when converting them to latin-1 I get: RuntimeError: cannot unmarshal code objects in restricted execution mode Removing the restriction on the execution mode from mod_python doesn't seem possible so I'd like to know if there is any possibility to decode unicode without loading the codecs module. Cheers, Odie From theller at python.net Fri Mar 5 09:53:01 2004 From: theller at python.net (Thomas Heller) Date: Fri, 05 Mar 2004 15:53:01 +0100 Subject: again py2exe and codecs References: Message-ID: "Achim Domma" writes: > Hi, > > I still have problems to get cjkcodecs to work with py2exe. I added > cjkcodecs to my setup.py like this: > > opts = { > "py2exe" : { > "includes" : ["encodings","encodings.*","cjkcodecs","cjkcodecs.*"], > "packages" : ["encodings","cjkcodecs"] > } > } > > After that, my distribution contains _gb2312.pyd and _big5.pyd but at > runtime I get an unknown encoding error, if I try to use gb2312 or big5. Any > hint? cjkcodecs installs a cjkcodecs.pth file which includes this signle line: import cjkcodecs.aliases This import seems to register the cjk codecs - import lines in pth files are executed (in site.py). py2exe doesn't pick up any pth file, nor does it execute things in them. So, you have to insert the 'import cjkcodecs.aliases' line in your script, and you should be able to build it with this: opts = { "py2exe" : { "packages" : ["encodings","cjkcodecs"] } } If this works for you, feel free to write something up for the wiki ;-) Thomas From jepler at unpythonic.net Tue Mar 2 11:39:58 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Tue, 2 Mar 2004 10:39:58 -0600 Subject: Modifying escape sequences in strings In-Reply-To: References: Message-ID: <20040302163958.GD22280@unpythonic.net> If you want to translate two backslashes into a single backslash, have to write x.replace("\\\\", "\\") the first is a string of length 2 and the second is a string of length 1. I don't know why the tutorial doesn't cover this point explicitly (http://python.org/doc/current/tut/node5.html#SECTION005120000000000000000) but the language reference does (http://python.org/doc/current/ref/strings.html) ... but there are no sequences of two backslashes in the strings you were working with. However, I think that referring to "escaped backslashes" in the string you read shows that there's some other misunderstanding of what is going on. Is your final goal to turn the backslash-n sequences into actual newlines, or what? If this is your goal, then you should use the "string_escape" codec in Python 2.3: >>> '\\n'.decode("string_escape") '\n' This took a string containing backslash-n and returned a string containing a newline character. Jeff From lbates at swamisoft.com Tue Mar 2 11:33:36 2004 From: lbates at swamisoft.com (Larry Bates) Date: Tue, 2 Mar 2004 10:33:36 -0600 Subject: get notepad on windows to front via tcp-server References: <5475062c.0403011527.22364bc4@posting.google.com> Message-ID: <_JSdnVB4DOzBKtnd4p2dnA@comcast.com> You can use win32process to start the app which gives you much more control over window size, environment, etc.: import win32process STARTUPINFO=win32process.STARTUPINFO() STARTUPINFO.dwX=0 STARTUPINFO.dwY=0 STARTUPINFO.dwXSize=800 # Horizontal window size STARTUPINFO.dwYSize=600 # Vertical window size commandLine=None processAttributes=None threadAttributes=None bInheritHandles=0 dwCreationFlags=0 newEnvironment=None currentDirectory="C:\\" # # Start the program # win32process.CreateProcess('C:\\WINDOWS\\system32\\notepad.exe', commandLine, processAttributes, threadAttributes, bInheritHandles, dwCreationFlags, newEnvironment, currentDirectory, STARTUPINFO) -Larry "Roger" wrote in message news:5475062c.0403011527.22364bc4 at posting.google.com... > I've got some MS-windows (XP only?) related questions; hopefully > someone can give me some advise. > > 1) > Is there some way to make notepad to become the front window when it > is started from within a tcp-server, using something like > > os.system("notepad") or > os.system("start /w notepad") > > Using these methods from a python shell works as expected, but using a > tcp-client/server construct gives me notepad in the rear. > > I read an old thread from '98 about something very much related to > this, but it used tk which I don't want to. Besides, the thread ended > undecidedly. > > 2) > From a python shell using > os.system("write") or > os.system("start /w write") > gives me an exit code (zero) before I have closed the application > wordpad. So os.system() is not waiting as I thought it should. > Can this be explained? > > I have NOTEPAD.EXE in C:\windows and notepad.exe and write.exe in > C:\windows\system32. > > Any help would be greatly appreciated. From garryknight at gmx.net Wed Mar 17 20:18:03 2004 From: garryknight at gmx.net (Garry Knight) Date: Thu, 18 Mar 2004 01:18:03 +0000 Subject: Specific question about readlines versus xreadlines References: Message-ID: <1079572682.11396.0@nnrp-t71-03.news.uk.clara.net> Erik gave you the correct answer. I just thought I'd point out a few other things about your code: In message , Pernell Williams wrote: > #opening the file for reading > > str = 'myShortFile' Did you know that str() is a Python function that returns the string representation of an object. To see how it works, run Python interactively and pass it some objects: print str(3) print str('hello') d = {"one": 1, "two": 2, "three": 3} print str(d) In other words, it's not a good idea to redefine str in your code as it hides the original function making it unusable. Also... > file = open(str, 'r') In Python file() is a function that happens to be an alias of open(). So if you redefine it like this you can't do: f = file('myFile', 'r') This is OK if you only intend to use open() but redefining existing Python names is still arguably not good practice. > while 1: > > line = file.readline() > > if line == '': > > break The usual way to read lines from a file is like this (assuming you followed my previous suggestion and stopped using 'file' for the filename: for line in f.readlines(): # process line This will loop until line == '' so you don't even need the break statement. And you can make it shorter still: for line in f: # process line And you can shorten the whole process further still by combining the open with the read: for line in open(filename): # process line I realise that your example is specifically comparing and contrasting the readline() function with the xreadlines() function, but I wasn't sure if you were aware of the different ways of doing the same thing. If you were, please ignore the above paragraph: hopefully it will prove useful to newcomers to Python. > data = line > > print data I'm curious as to why you didn't just do 'print line' rather than assigning it to 'data' first. -- Garry Knight garryknight at gmx.net ICQ 126351135 Linux registered user 182025 From Bill Sun Mar 14 02:39:53 2004 From: Bill (Bill) Date: Sat, 13 Mar 2004 23:39:53 -0800 Subject: List append help References: <105811aq55rah53@corp.supernews.com> <40540841.8070802@zoran.com> Message-ID: <1058329gsgeq85f@corp.supernews.com> Thank you, This was really bugging me. To help me understand, do you know why the return value was None even though it was added to the list? Also, I don't like having to type "arg" on every other line neither, so I won't:-) Miki Tebeka wrote: > >Hello Bill, > >> Could someone please tell me why the "hireCrew" >> method in the following code leaves me with a list that contains "None"? > > ... > > self.myCrew = self.myCrew.append(argHire) >The return value of list.append is None. However it does add the item to >the list. Try: >self.myCrew.append(argHire) > >On a side note, I find this `arg' prefix for an argument irritating :-) > >HTH. >Miki From lbates at swamisoft.com Mon Mar 8 17:32:02 2004 From: lbates at swamisoft.com (Larry Bates) Date: Mon, 8 Mar 2004 16:32:02 -0600 Subject: Reports References: Message-ID: HTMLgen has a nice barchart module that I have used to generate mine. If you want something more complex you can use ReportLab/Graphics to generate charts, but they would be graphics (not pure HTML) that would be displayed as .JPG or .PNG files. -Larry wrote in message news:f046efac.0403070502.736d9a48 at posting.google.com... > ketulp_baroda at yahoo.com wrote in message news:... > > Hi > > I am developing web application. > > I have my data stored in a database.Now I want to generate a bar chart > > & other reports.How can I do it using python? > Will using something like HTMLGen help?? From newsgroups at jhrothjr.com Thu Mar 11 09:37:08 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Thu, 11 Mar 2004 09:37:08 -0500 Subject: Extending Python Syntax with @ References: <104vtblamboehab@corp.supernews.com> <2f9050pq22u53o7aqo9i8ebqj11vo9kilg@4ax.com> <1050odofl644aac@corp.supernews.com> Message-ID: <1050uf4afdkrje5@news.supernews.com> "Cameron Laird" wrote in message news:1050odofl644aac at corp.supernews.com... > In article <2f9050pq22u53o7aqo9i8ebqj11vo9kilg at 4ax.com>, > David MacQuigg wrote: > . > . > . > >going to help me write some code, I won't have time to study it. My > >understanding of lambda functions is simply that they are a way to > >squeeze functions into a tight space: > > > >list_of_funcs = [(lambda x: 2**x), (lambda x: 3**x), (lambda x: 4**x)] > > > >If you are not concerned about space, simply use normal defs: > > > >def f2(x): return 2**x > >def f3(x): return 3**x > >def f4(x): return 4**x > >list_of_funcs = [f2, f3, f4] > > > >Is there any other reason in Python to use lambdas? > . > . > . > In fact, *that*'s not a reason. Part of tribal lore--a true, > documented part, by the way--is that Big Cheese Guido depre- > cates lambdas. He says they're a mistake, and people shouldn't > be using 'em. Whenever you feel like a lambda, define a named > function; it forces the developer to come up with a name for > the operation, and that's likely to make the code more read- > able (I'm slightly abbreviating the argument here). I tend to agree, but for slightly different reasons. Lambdas are a means of in-lining a function definition. However, they are so restricted that we constantly get suggestions for "improving" them by adding more syntax. Given the restrictions, I see the natural growth path as leading to a callable instance or a bound method, not a module level function. Module level functions are a distraction; usually you want to interface with an object, and module level functions make that very difficult. The other reason to avoid lambdas is the DRY principle: Don't Repeat Yourself. Most uses of lambdas I've seen lead to duplication in anything larger than a toy program. What I'd really like is for all of the instructional material with lambdas to just magically vanish and be replaced by instructional material that does whatever it is in proper object oriented fashion, using bound methods for callbacks. Relegate lambda to a sidebar. John Roth > -- > > Cameron Laird > Business: http://www.Phaseit.net From peter at semantico.com Tue Mar 16 04:18:05 2004 From: peter at semantico.com (Peter Hickman) Date: Tue, 16 Mar 2004 09:18:05 +0000 Subject: Static Typing in Python In-Reply-To: References: Message-ID: <4056c64d$0$3473$afc38c87@news.easynet.co.uk> Premshree Pillai wrote: > --- Peter Hickman wrote: > > Premshree Pillai wrote: >>>Like in C, C++, etc, Python too is >>>strongly typed, i.e., variables are necessarily >> >>bound >> >>>to a particular type. [deletia] > The above returns a TypeError in Python, but not in > PHP, which is weakly typed. > > Get it? The only two (or perhaps one and a half) languages you used as reference were C and C++. Which you said 'Like in C, C++, etc, Python too is strongly typed'. What has PHP got to do with it? How does PHP's typing have anything to do with Python's? Typing in C and C++ is different to Python. int c = 0; c = "fred"; No can do in C and C++. c = 0 c = "fred" No problem in Python. So just how is Python strongly typed 'like in C, C++, etc'? From cedgmon at shaw.ca Wed Mar 3 12:59:05 2004 From: cedgmon at shaw.ca (Craig Edgmon) Date: Wed, 03 Mar 2004 09:59:05 -0800 Subject: MySQLdb Module for ActiveState Python 2.3 Message-ID: <1078336745.6666.10.camel@shrek> I am running ActiveState Python-2.3 and I am told that it does not have the module. I am directed to SourceForge, it wants to install in python1.5 on my Fedora environment. I get weird errors after that about a difference between the module and the version of python. Does anyone have an idea about how I can get this connection to work? From mh at pixar.com Wed Mar 17 18:34:24 2004 From: mh at pixar.com (Mark Harrison) Date: Wed, 17 Mar 2004 23:34:24 GMT Subject: how to "source" a file? Message-ID: <4g56c.11369$MC6.9352@newssvr27.news.prodigy.com> I have a set of configuration files that are expressed in python. Users can set up triggers and callbacks as python function calls. Some of these functions have become shared between several products, so I would like to factor out these functions into a separate file. Can someone give me a clue as to the best way to proceed? I'm trying various combinations of import, but with no success. Can someone loan me a clue? Many TIA, Mark -- Mark Harrison Pixar Animation studios From newsgroups at jhrothjr.com Sun Mar 28 20:26:46 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Sun, 28 Mar 2004 20:26:46 -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> Message-ID: <106eut1pe29uab8@news.supernews.com> "Michael" wrote in message news:mailman.21.1080516361.20120.python-list at python.org... > They're planning to remove tab indention support in 3.0? I for one would > be pissed off at such a change. I don't mind people using spaces if they > like but I see no reason I shouldn't be able to use tabs if I like. I > can't see how it should make any difference to Python which you use so > why not allow for personal preference? The basic difficulty with tabs is that there are a huge number of programs "in the wild" that treat tabs differently. Unless you're completely in control of all the programs that will ever be used to edit and display your program, using tabs will cause formatting errors somewhere, to someone under some circumstance that you never thought of. The problems with mixed tabs and spaces are even worse: you can lose indentation and totally mess up the program so it won't even compile if you use the wrong tools on such a program. This is the basic reason why the current standard for library modules is 4 space indentation; it's the only thing that is, for all practical purposes, guaranteed to work for everyone, with any editor, formatter, renderer and printer out there. Python is not Perl. Python's philosophy has never been to provide several different ways of doing things just to provide different ways. There needs to be a demonstrated benefit to the different ways, and tabs don't make that cut. If you want the space savings, ziping the file will do much better. John Roth From tmohr at s.netic.de Wed Mar 10 13:39:11 2004 From: tmohr at s.netic.de (Torsten Mohr) Date: Wed, 10 Mar 2004 19:39:11 +0100 Subject: Interfacing a C++ class, example Message-ID: Hi, i wrote a short example using "swig" to interface a small C++ class. It doesn't yet work, as there is not yet an init function: tmohr at schleim:~/p/python/swig> python Python 2.3+ (#1, Sep 23 2003, 23:07:16) [GCC 3.3.1 (SuSE Linux)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import pcpl Traceback (most recent call last): File "", line 1, in ? ImportError: dynamic module does not define init function (initpcpl) >>> Can anybody tell me what i need to add to make the C++ class available in Python as a data type? Thanks for any hints, Torsten. Here are the sources and the Makefile: MOD = pcpl PYT = $(MOD).cc all: $(PYT) pcpl.so cpl.o: cpl.cc cpl.h g++ -o $@ -c $< $(PYT): swig -python -c++ -o $@ -module $(MOD) cpl.h pcpl.o: wpcpl.cc pcpl.cc cpl.h g++ -o $@ -c $< -I/usr/include/python2.3 pcpl.so: pcpl.o cpl.o gcc -Bdynamic -shared -o $@ $^ clean: -rm -f pcpl.so -rm -f pcpl.o -rm -f cpl.o -rm -f pcpl.cc -rm -f pcpl.h -rm -f pcpl.py ### cpl.h #ifndef CPL_H #define CPL_H 1 class Abc { public: Abc(); ~Abc(); int somefunc(int a); }; #endif ### cpl.cc #include #include #include #include "cpl.h" using namespace std; Abc::Abc() { cout << "Abc()" << endl; } Abc::~Abc() { cout << "~Abc()" << endl; } int Abc::somefunc(int a) { cout << "a is " << a << endl; return 42; } ### wpcpl.cc #include "cpl.h" #include "pcpl.cc" From mogmios at mlug.missouri.edu Mon Mar 29 11:54:16 2004 From: mogmios at mlug.missouri.edu (Michael) Date: Mon, 29 Mar 2004 08:54:16 -0800 Subject: tabbing probs In-Reply-To: References: <106gg1jifa2n9c2@news.supernews.com> <406848CD.5070100@mlug.missouri.edu> Message-ID: <406854B8.5010209@mlug.missouri.edu> >As long as you are the only one to work on your code, your >viewpoint may not cause you any problems. I and others are telling >you that tabs can cause problems with some software, and you can >rightly avoid using that software as long as you don't share your >code. Once that happens, though, things get more complicated. > > That's what you're saying but what I'm hearing is that using tabs + spaces causes problems with some (crappy) software. If I start using an editor that only allows uppercase letters is Python going to disallow lowercase letters to solve a problem with my editor? I'd hope not. Likewise it makes no sense to remove tab indenting because some software has a problem with the difference between tabs and spaces. >One aspect of the tab/spaces issue involves working on other >people's code. You like tabs, I like spaces. Supposing that I >prefer to show a single level of indention as five spaces (for some >reason), what happens when I have to make a change to your code? If >I am aware that you use tabs, then I can adjust to it, but how do I >become aware? To me, it looks like you're putting five spaces in >for each level of indention. The chances are that I won't know >otherwise until I've made some changes, saved the file and tried to >run it. If some of those changes involve changing an indention >level, I may insert spaces before or after your tabs, so now such a >change leaves a line with mixed tabs and spaces, but no visible >indication of which is where. Now when someone else grabs the code >and displays it with tabs set to four spaces instead, what happens? >No sympathy there, either, I would bet, but you do see how things >like that can happen even using only your tools, don't you? > Couldn't you just look at the code and see that it's using tabs or spaces as long as it's uniform? How hard is it to tell the difference? Or is it that your editor makes spaces look like tabs so that it's difficult to tell? I can see how it could be a problem. I just can't see how making tabs not work will fix the problem. If anything I'd make it so one whitespace character counts as one level of indention.. regardless to if your editor shows you the fact. Using multiple spaces or tabs or a combination thereof which don't add up correctly to the required indention level should just throw an error. That's closer to what happens currently and it makes more sense to me than limiting indenting to using only spaces. I think the problem will exist as long as whitespace is significant but I happen to have grown fond of Python's use of whitespace. From tim.one at comcast.net Tue Mar 30 11:05:53 2004 From: tim.one at comcast.net (Tim Peters) Date: Tue, 30 Mar 2004 11:05:53 -0500 Subject: Why '==' ?? In-Reply-To: <106iufn2q88rcea@news.supernews.com> Message-ID: [John Roth] > I believe the earliest versions of Python did use the single equal > sign for comparisons. I don't know why Guido changed it, but > it might be in order to keep his options open. It was to stop ambiguity. This was especially acute at an interactive shell, where guessing what >>> x = y intended often guessed wrong (it's common to wonder whether two things are equal at a shell prompt). After the change, that became obvious: >>> x = y # assignment >>> x == y # equal? False >>> From bdelmee at advalvas.REMOVEME.be Tue Mar 2 18:44:46 2004 From: bdelmee at advalvas.REMOVEME.be (=?ISO-8859-1?Q?Bernard_Delm=E9e?=) Date: Wed, 03 Mar 2004 00:44:46 +0100 Subject: How to access the Oracle9i? In-Reply-To: References: Message-ID: <40451d36$0$1111$6c56d894@feed0.news.be.easynet.net> cx_Oracle works flawlessly for me (windows & HP-UX) http://www.computronix.com/utilities.shtml From N.R.Turner at bradford.ac.uk Sat Mar 20 16:20:03 2004 From: N.R.Turner at bradford.ac.uk (Neil Turner) Date: 20 Mar 2004 13:20:03 -0800 Subject: Unicode and rdf References: <9L6dnSQDVMjVjtLdRVn-jA@speakeasy.net> Message-ID: "A.M. Kuchling" wrote in message > Oh dear. > > Around 2001/2002 I worked on Python code for processing dmoz dumps, but gave > up because the data was so bad -- some categories included content in > various Chinese encodings despite the file's claim to be UTF-8. I > eventually gave up because debugging a program that fails after running for > six hours is really, really tedious. I'm a senior editor at the ODP, so allow me to (attempt to) explain the situation. Originally the ODP used different character encoding for different languages - so while most of the directory used ISO-8859-1 or Windows-1252, Japanese would use Shift_JIS, and so on. This wasn't ideal, so we started the long road towards moving to Unicode. Many of the non-English sections were cloned and converted to Unicode in a testbed area, then the Unicode version was merged back into the main directory - this merging process took place only a few weeks ago. A few weeks back, the entire site was switched over to Unicode - now, if you enter any non-Unicode characters they will show as ?. Naturally, with a directory containing over 4 million entries some non-Unicode characters will be in there, but the aim is to eradicate these in due course. I'll admit it isn't ideal though. -- Neil Turner http://dmoz.org/profiles/totalxsive.html http://www.neilturner.me.uk/ From hamilcar at never.mind Wed Mar 31 00:40:34 2004 From: hamilcar at never.mind (Hamilcar Barca) Date: Tue, 30 Mar 2004 22:40:34 -0700 Subject: Prothon Prototypes vs Python Classes References: <569c605ld1cj8fc1emolk08ete0s1prls1@4ax.com> <106di86neu1qh4d@news.supernews.com> Message-ID: <20040331004033.536$Cl@news.newsreader.com> In article (Mon, 29 Mar 2004 22:36:55 -0800), Mark Hahn wrote: > A2. People that bitch about top-posting. A3. People professing to be computer literate -- some claiming to be programming language designers and wanting to be taken seriously -- who refuse to understand why top-posting doesn't follow the rules of written European language. A4. People who refuse to trim unnecessary quoted material from their follow-ups. -- "Posting at the top because that's where the cursor happened to be is like shitting in your pants because that's where your asshole happened to be." -- Andreas Prilop (c.i.w.a.h) From jcarlson at nospam.uci.edu Fri Mar 12 12:08:10 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Fri, 12 Mar 2004 09:08:10 -0800 Subject: Extending Python Syntax with @ In-Reply-To: <104v8flf6f1bp95@news.supernews.com> References: <104v3lrijtse657@news.supernews.com> <104v8flf6f1bp95@news.supernews.com> Message-ID: > 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. One class of people: end users. Usually, end users don't need to have an IDE, they just use (not write) software without a care in the world. Occasionally, they need to edit something (it happens to everyone at some time), and they need to break out a text editor. Usually this is an INI file, but there are scenarios with applications that ship with an interpreter (Freedom Force) that allow people to change them. Really the ultimate question is whether we (computer scientists, engineers, or anyone who programs) want to limit programming to those with an IDE? I think doing so is wasteful, and requires people who want to do minor editing to deal with learning a new application, just to edit some minor sources. 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? - Josiah From piet at cs.uu.nl Tue Mar 30 10:27:36 2004 From: piet at cs.uu.nl (Piet van Oostrum) Date: 30 Mar 2004 17:27:36 +0200 Subject: OT: FTP sync program? References: Message-ID: >>>>> Miki Tebeka (MT) wrote: MT> Hello All, MT> I'm looking for a *free* program to synchronize files over ftp (like rsync). MT> Any suggestions? If it;s for synchronizing TO an ftp server then llok at: http://www.bstpierre.org/Projects/upload.py -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP] Private email: P.van.Oostrum at hccnet.nl From niemeyer at conectiva.com Wed Mar 10 21:48:37 2004 From: niemeyer at conectiva.com (Gustavo Niemeyer) Date: Wed, 10 Mar 2004 23:48:37 -0300 Subject: [ANN] python-dateutil 0.4 Message-ID: <20040311024837.GA2560@burma.localdomain> What is it? ----------- The dateutil module provides powerful extensions to the standard datetime module, available in Python 2.3+. Features -------- * Computing of relative deltas (next month, next year, next monday, last week of month, and a lot more); * Computing of relative deltas between two given date and/or datetime objects; * Computing of dates based on very flexible recurrence rules (every month, every week on Thursday and Friday, every Friday 13th, and a *LOT* more), using a superset of the iCalendar RFC specification. Parsing of RFC strings is supported as well. * Generic parsing of dates in almost any string format; * Timezone (tzinfo) implementations for tzfile(5) format files (/etc/localtime, /usr/share/zoneinfo, etc), TZ environment string (in all known formats), iCalendar format files, given ranges (with help from relative deltas), local machine timezone, fixed offset timezone, and UTC timezone. * Computing of Easter Sunday dates for any given year, using Western, Orthodox or Julian algorithms; * More than 400 test cases. Changes since 0.3 ----------------- Fixed a parsing bug which affected dates like "Sep.25.2003", as reported by Andre Wobst and catched by the test cases. Where to get it? ---------------- https://moin.conectiva.com.br/DateUtil -- Gustavo Niemeyer http://niemeyer.net From tim.golden at viacom-outdoor.co.uk Tue Mar 23 03:39:14 2004 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Tue, 23 Mar 2004 08:39:14 -0000 Subject: MSSQL Help Message-ID: >I would like to use Python (2.3.3 on Windows 2000 >"Professional") to access >a MSSQL Server and list all of the available databases, as well as the >tables in each database and columns in each table for an >automated test tool >I am designing. I have used the MSSQL module many times in >the past for >Inserting, Updating, and Selecting data from various >databases, but have >never mined for metadata like this before. Is it possible >and, if so, how? The simple answer is: query the data dictionary, either via the INFORMATION_SCHEMA schema: SELECT * FROM INFORMATION_SCHEMA.TABLES or SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'blah' or via the (lower level) sys... views (sysobjects etc.). You can find the info in the SQL Server help. Then just use the Python module as you would to query any other table. If you need more concrete examples, let me know. I have a set of modules which do this kind of thing. But really, it's quite straightforward. 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 Tue Mar 2 14:22:39 2004 From: theller at python.net (Thomas Heller) Date: Tue, 02 Mar 2004 20:22:39 +0100 Subject: python.exe vs pythonw.exe difference? References: Message-ID: "Tim Peters" writes: > [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. It seems to exist, but I don't read it - so this is a good idea. > [Tim] [script, writing to sys.stderr and/or sys.stdout] >>> 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 . That may be, and the idea sounds even better if pythonw 'crashes' when the bit bucket is full. > ideas-ain't-code-ly y'rs - tim Sure ;-) Thomas From ben at wintersun.org Tue Mar 2 06:39:25 2004 From: ben at wintersun.org (Ben Caradoc-Davies) Date: 02 Mar 2004 11:39:25 GMT Subject: Little explanation References: Message-ID: On Tue, 2 Mar 2004 11:52:49 +0100, Angelo Secchi wrote: > What is difficult to understand for me is the meaning of the bitwise > operator &. In particular what do expressions like > i & 0x100000000L > (i >> 24) & 0x7f > i & 0xffffff > mean? This syntax is taken from directly from the C programming language. Consult "ANSI C", second edition, by Kernighan and Ritchie, or see the Python Language Reference: http://www.python.org/doc/current/ref/bitwise.html http://www.python.org/doc/current/ref/shifting.html "&" is "bitwise and". ">>" is "bitshift right". Bitwise boolean operators operate on each bit of the operands, rather than their values as a whole. "&" allows you to select only those bits which are set in both operands. ">>" allows you to move your bits around so that you can interpret your bits as a small integer (selecting a few bits from within a word or longer). Write the *binary* representation of these numbers and try it yourself. Much easier than trying to understand it in hexadecimal. -- Ben Caradoc-Davies http://wintersun.org/ Imprisonment on arrival is the authentic Australian immigration experience. From rainerd at eldwood.com Mon Mar 1 00:12:48 2004 From: rainerd at eldwood.com (Rainer Deyke) Date: Mon, 01 Mar 2004 05:12:48 GMT Subject: Why Python? References: Message-ID: Todd7 wrote: > What makes it better or worse than languages like perl, php, delphi, > or c++? I'll focus on the weaknesses of Python instead of the strengths. 1. Computation intense Python programs tend to be slower than optimized equivalent programs written in languages that compile to native code. 2. Python programs are somewhat difficult to distribute compared to programs in languages that compile to native code. 3. Some other languages make it easier to detect certain classes of errors in your code. With a few exceptions, errors in Python code can only be found by actually running the code or by checking by hand. 4. Python is only somewhat flexible about allowing you to customize the language from within the language. You can define new functions and new data types, but no new operators, no new control structures, nor any type of new syntax. If you need to define a domain-specific language within your program, Python may not be your best choice. -- Rainer Deyke - rainerd at eldwood.com - http://eldwood.com From richie_aj at hotmail.com Tue Mar 23 14:29:55 2004 From: richie_aj at hotmail.com (Richard A. Jones) Date: Tue, 23 Mar 2004 13:29:55 -0600 Subject: urllib2 and POST Message-ID: How do you send a POST to a url? I know how to do this with httplib but how do you do this using urllib2. For example: import urllib2 url = http://123.8.37.87:4080/somewhere/something f = urllib2.urlopen(url) When I attempt this I get HTTP Error 400: HTTP method GET is not supported by this URL. Am I missing something? From dale at riverhall.NO-SPAM.co.uk Mon Mar 22 10:29:59 2004 From: dale at riverhall.NO-SPAM.co.uk (Dale Strickland-Clark) Date: 22 Mar 2004 15:29:59 GMT Subject: Using Oracle on Solaris Message-ID: I need to write a tiny little program which makes use of an Oracle database on Solaris. Just a single SQL statement. Nice and simple. Coming from a Windows/SQLServer/ADO background, I'm having a bit of trouble finding some of the basics. Given that I already have Oracle and Python installed on the Solaris box, what else do I need? A little code snippet would be very handy. Thanks. From beefjerky at hornet.beefjerky.demon.nl Fri Mar 12 14:51:53 2004 From: beefjerky at hornet.beefjerky.demon.nl (Jeroen Wenting) Date: Fri, 12 Mar 2004 20:51:53 +0100 Subject: Simple file line reading References: <40520BD5.9090006@ecn.purdue.edu> Message-ID: <105451c2bm2dd21@corp.supernews.com> "Aaron Deskins" wrote in message news:40520BD5.9090006 at ecn.purdue.edu... > Hello everyone, > I'm relatively new to Python and am trying to write some scripts. me too :) Started last weekend reading seriously > > import string > it = 0 > for line in open("OUTCAR"): > it+=1 > print it > f = open("OUTCAR") print(len(f.readlines())) f.close() will print the number of lines in the file (I think :) might have made a typo or something). -- Jeroen Wenting jwenting at hornet dot demon dot nl From niurka.perez at cimex.com.cu Mon Mar 22 09:05:00 2004 From: niurka.perez at cimex.com.cu (niurka.perez at cimex.com.cu) Date: Mon, 22 Mar 2004 09:05:00 -0500 Subject: static information... Message-ID: <0403221079.AA1079991245@ws3.cimex.com.cu> I've been looking for a way of have static variables in a python class and all I have found is this: class A: static =[] def f(self): A.static = [1,2,3] That seems to be pretty static since that variable can be used either on the class (such as A.static) or on an instance (such as A().static). Now my problem is that every time some create a new instance of this class the variable static is reset to its original value [] and the real value that it took is lost. What I want is someplace to store class's information and not instance's information. Any idea? From op73418 at mail.telepac.pt Fri Mar 5 19:08:53 2004 From: op73418 at mail.telepac.pt (Gonçalo Rodrigues) Date: Sat, 06 Mar 2004 00:08:53 +0000 Subject: Curiosity question on signatures Message-ID: Hi all, I just noticed the following fact: >>> def f(arg): ... print "Arg is %s." % arg ... >>> f(1) Arg is 1. >>> f(arg = 0) Arg is 0. Even "worse": >>> def g(arg1, arg2): ... print "Args: %s, %s." % (arg1, arg2) ... >>> g(arg2 = 9, arg1 = None) Args: None, 9. >>> 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? I'm asking this, because if we define equivalence of functions signatures in the obvious way ("they accept the same calls") then def f(arg): .... def g(name): .... don't have equivalent signatures because f can be called with (arg = 0) which does not work with g. It looks... wrong (maybe because what I have in my mind is the mathematical concept of a function where named arguments do not exist). This is no big deal of course, just a curiosity. With my best regards, G. Rodrigues From max at alcyone.com Tue Mar 16 21:06:28 2004 From: max at alcyone.com (Erik Max Francis) Date: Tue, 16 Mar 2004 18:06:28 -0800 Subject: Inconsistency in Python's Comparisons References: Message-ID: <4057B2A4.F9EC49DD@alcyone.com> Dietrich Epp wrote: > This could cause sorting functions to malfunction. > > >>> class t(object): > ... pass > ... > >>> a = t() > >>> b = u'0' > >>> c = '1' > >>> a < b > True > >>> b < c > True > >>> c < a > True Do you have an example of this that doesn't involve comparisons between different types? In Python, except for complex numbers, comparisons between instances of different types is guaranteed to be consistent, but not necessarily helpful. If you're doing comparisons, not to mention sorting, between instances of fundamentally incommensurable types (like instances of a class and strings), I'd say that's programmer error, although admittedly it is a little strange that you found a circular situation like that. -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE \__/ Liberty without learning is always in peril; learning without liberty is always in vain. -- John F. Kennedy From tismer at stackless.com Mon Mar 29 14:53:13 2004 From: tismer at stackless.com (Christian Tismer) Date: Mon, 29 Mar 2004 21:53:13 +0200 Subject: Orders of magnitude In-Reply-To: <40687AC6.5050401@stackless.com> References: <40687AC6.5050401@stackless.com> Message-ID: <40687EA9.3040800@stackless.com> Christian Tismer wrote: > Robert Brewer wrote: > >> I wrote: >> >> 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? >> >> ...and got replies: > > > Here is another one. > If you believe in statistics, then you might consider > to build a dictionary of SHA digests, only. The chance > that you get a hash clash is very, very small, if you use > the sha 160 bit algorith as in the sha module. A slight change to the idea which goes rather easily with standard Python and very small memory, if you have the disk space: Phase one opens, say, 16 files for writing. In a big loop, you calculate the sha key for every record, and then you form an index from the first 4 bits of the key. Then you write the record into its file. Then you have 16 files with no duplicates between them. You now process every of them using the sha algorithm, again, and you have no memory problem at all. 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 deets_noospaam at web.de Mon Mar 8 16:09:56 2004 From: deets_noospaam at web.de (Diez B. Roggisch) Date: Mon, 08 Mar 2004 22:09:56 +0100 Subject: dynamic names References: Message-ID: Mel Wilson wrote: > tot = tot + eval ("L%s" % L) > exec is a statement. Yup - OPs wrong usage of exec confused me on that one. Thanks for pointing it out. -- Regards, Diez B. Roggisch From wmwd2zz02 at sneakemail.com Mon Mar 1 19:26:25 2004 From: wmwd2zz02 at sneakemail.com (Greg Ewing (using news.cis.dfn.de)) Date: Tue, 02 Mar 2004 13:26:25 +1300 Subject: How does Ruby compare to Python?? How good is DESIGN of Ruby compared to Python? In-Reply-To: References: Message-ID: Joe Mason wrote: > I don't see the distinction. "normal calling syntax" in ruby involves > an object, so "unbound function" isn't a meaningful concept. Which is just what I was trying to say, really. Ruby doesn't have functions, only methods. I'm not saying one is better than the other, just pointing out the difference. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From leo at bella.local Mon Mar 22 06:55:37 2004 From: leo at bella.local (leo) Date: 22 Mar 2004 22:55:37 +1100 Subject: module for terminal questions? Message-ID: hi there for a light weight commandline tool i want to build in same little dialog questions like 'Do you want to proceed? [Y/n]' etc. is there a module avaible what does make that easier then doing it via raw_input? thanks, leo From pinard at iro.umontreal.ca Sat Mar 20 11:04:19 2004 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Sat, 20 Mar 2004 11:04:19 -0500 Subject: [OT] Compilable Python-like language? In-Reply-To: References: Message-ID: <20040320160419.GA4194@titan.progiciels-bpi.ca> [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? If the goal is speed, you might not obtain much by the mere fact of having a binary, and might be surprised anyway by the bloat of size. There are avenues, Pyrex is a good example, in which you may write Python-like code which runs at C speed, if you do proper compromises. If the goal is obfuscation, you might consider Perl from the start! :-) -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From Scott.Daniels at Acm.Org Thu Mar 4 21:10:04 2004 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Thu, 04 Mar 2004 18:10:04 -0800 Subject: Unicode & mx.ODBC module In-Reply-To: <404751e2$0$7055$a726171b@news.hal-pc.org> References: <40466a21$0$7052$a726171b@news.hal-pc.org> <404751e2$0$7055$a726171b@news.hal-pc.org> Message-ID: <4047e9fc$1@nntp0.pdx.net> Chuck Bearden wrote: > I think I'm still not entirely clear on when Unicode encoding & > decoding happen in Python and for what reasons. In my searching on this > problem I kept my eye open for a nice, systematic treatment of Unicode > in Python, but I haven't found anything yet. It is not really tough, but you need to understand some facts that you won't want to believe. 1) You are normally (when using str's) dealing with _bytes_, not _characters_ in strings. Just because your system can print them doesn't mean someone else's system will print the same thing. 2) Unicode is a coding system for _characters_ and not binary values. Especially if you wander into the stranger sections of unicode, a single character may take several positions in a unicode string. 3) Deciding if two unicode strings are _the_same_ is a question of philosophy, and not just programming. OK, with those caveats, you can pretend -- unicode(some_byte_string, encoding) produces a unicode string. The byte string has no coding -- it is a sequence of bytes. The coding is how you interpret those bytes to determine the characters that the bytes mean. Unicode, on the other hand, is a _character_ encoding. In some sense, you should expect the unicode expression "unicode(s, enc)" to "mean" the same thing on all different computers that implement python. It really shouldn't matter what the bytes are in a unicode string, just like it shouldn't matter what the characters are in a byte string. Please let me know whether this is: A) obvious, B) clear, C) comprehensible with effort D) gibberish -- -Scott David Daniels Scott.Daniels at Acm.Org From user at domain.invalid Fri Mar 12 00:27:36 2004 From: user at domain.invalid (user at domain.invalid) Date: Fri, 12 Mar 2004 16:27:36 +1100 Subject: Deprecating reload() ??? References: Message-ID: <40514A48.50907@domain.invalid> Ellinghaus, Lance wrote: > I agree that it does not really work as most people think it does, but how > would you perform the same task as reload() without the reload()? > > Would this be done by "del sys.modules['modulename']" and then perform an > 'import'? Ah, interesting! I've been doing this: del modulename; import modulename but it doesn't pick up any recent changes to the modulename.py file. That's a better solution than exiting Python and starting it up again. Thanks! -- Steven D'Aprano From sean_berry at cox.net Fri Mar 26 20:16:29 2004 From: sean_berry at cox.net (sean) Date: Fri, 26 Mar 2004 17:16:29 -0800 Subject: Python for email? Message-ID: Is there a good module for sending out email? For a website that I am working on, I am writing a program that finds out which presenters have not yet confirmed their scheduled date and sends them an email to confirm. Does python have any modules for use with mail programs like sendmail, or should I just run everything with os.system and os.popen? Thanks for any help. From dw-google.com at botanicus.net Wed Mar 3 18:18:56 2004 From: dw-google.com at botanicus.net (David M. Wilson) Date: 3 Mar 2004 15:18:56 -0800 Subject: Python as replacement for PHP? References: <403fa54b@news.zianet.com> Message-ID: <99dce321.0403031518.56f61c7c@posting.google.com> Bart Nessux wrote... > When it comes to dynamic, DB driven sites, PHP is the only way to go. > Python is not even close to being suited for this task. PHP claims to be > a general-purpose language, but I do not know anyone who uses it for > anything other than dynamic Web programming. Like everyone else who has replied, I seriously question how much experience you have with the multitude of Python web environments available. As an objective, point-by-point look at your specific example of somewhere PHP is strong, here's my reply: [PS: I still use PHP regularly, albeit only for quick unimportant hacks that won't exist in 6 months] - Nearly all the PHP code I have seen (including various large web sites) fails to handle error conditions, and will run amok given a down DB server, bad filesystem permissions, or bad inputs. I have had personal experience, on more than one occasion, of an error condition in someone else's PHP code causing a large amount of damage to a dataset. - The equivalent Python code will almost never do that. Thanks to the religious throwing of exceptions, well written standard libraries, DB adaptors, and so on, the worst Python code has a MUCH better chance of getting stopped in it's tracks just as a fault occurs. py> open("/tmp/foo","w").write(123) Traceback (most recent call last): File "", line 1, in ? TypeError: argument 1 must be string or read-only character buffer, not int [22:15:14] [cape:4:dw]$ php4 < > e [22:15:16] [cape:5:dw]$ cat /tmp/foo [22:15:17] [cape:6:dw]$ Can you tell me exactly what the PHP fwrite function did when I passed it an integer? Can you tell me how many PHP programmers test "(strlen($to_write) == fwrite($fp, $to_write))"? - In the specific instance of database connectivity, Python is far superior, in terms of intuitiveness, security, safety, and so on. Python database APIs are built in a way that protects you by default. - PHP provides no intuitive default support for many common DB operations. Compare the following messes: py> l = MySQLdb.connect() py> c = l.cursor() py> user_input = "%t%" py> match_count = c.execute("SHOW DATABASES LIKE %s", ( user_input )) py> print match_count, "matches:", [ x for x, in c ] 1 matches: ['test'] , etc.) How likely is it that the developer you hire to take over development of either snippet of code will understand the concept behind it? I can't even think of another way of doing database query in Python, without using the low-level interfaces, which is just insane. We could bring the PHP ADODB, or many of the other numerous PHP APIs for DB connectivity into the picture, but which of these are the obvious choice, and officially endorsed? How easy is it to improve on both these examples to add proper error handling? Again, Python wins hands down for elegance, conciseness, and obviousness. - Python has a religious following of thousands, many of whom found freedom through it's restraint, unified path, and downright beauty. The result is a long tradition of structured, well written code. Python has roots in academia, and started life with a defined purpose, and a BDFL who knew what he was doing. - PHP, "the web designer's ideal first language", started out life as "a collection of perl scripts" (that says it all really), then ported to C, then hacked and added to until it was the great swiss army monolith that it is today. PHP has never had a clear, publically documented development path, or indeed any form of structure or organisation, past the menu system of PHP.net PHP developers tend to have started life using Dreamweaver, happy to accept the first solution to a problem that comes their way, and care little about technical merit. Every person (including at the time, myself) who I know that uses, or used PHP, did so because it allowed them to make things look beautiful and dynamic very quickly. - Python gurus, when asked how to make something work, will often appear nasty and horrible, telling you you're doing entirely the wrong thing and you should go back to the drawing board. Much like the hot sting from a smack of a father's hand, this is good, not bad. It is there to direct and discipline you, and improve the way you think. - PHP gurus tend to be experienced web developers, they'll be able to look flash and give you an answer on the spot, but that answer will only further lead to the demise of any structure your coding ever had. - Python tends to be slow, but slow compared to what? The laptop I type this message on has a 2ghz processor. It cost less than ?1000. It is the cheapest laptop money can buy in the UK. I run Python scripts on multi-gigabyte datasets on a daily basis on this machine. I have never considered the scripts to be 'slow'. - PHP is very light on CPU, memory, and so on. I earn a modest amount for a 20 year old, even by Northern Ireland standards. I can't see how I would ever need to resort to PHP because I couldn't afford the hardware to run a complex Python-based site intended for viewing by thousands. Personally, I find the average PHP codebase to be akin to a television station such as MTV: well presented, streamlined, professional looking, but in terms of content, nothing but meaningless, mindless shite. On the other hand, reading certain Python code is more like reading a beautifully typeset hardback novel: black and white - ugly to some, but functional, educational, structured, meaningful, etc, etc. What interests you more - earning money through thoughtless, effortlessly produced rant-syntax that no-one will ever want to look at again, or the daily challenge to produce something that will perfectly fulfill it's intended function, at the cost of a little time, a little brainpower, and a little discipline. I could go on, but I think these points alone are the main reasons I use Python. At the cost only of speed, it protects me, teaches me, profits me, and inspires me to continue being the professional geek that I am. :) David. From __peter__ at web.de Thu Mar 25 07:42:38 2004 From: __peter__ at web.de (Peter Otten) Date: Thu, 25 Mar 2004 13:42:38 +0100 Subject: Split a string by length References: <4062BF09.1070906@rebirthing.co.nz> Message-ID: David McNab wrote: > Now, who's gonna benchmark these n different approaches? Make that n+1 :-) import itertools def chunks(s, cl): for i in xrange(0, len(s), cl): yield s[i:i+cl] def chunklist(s, cl): # aka divide() return [s[i:i+cl] for i in xrange(0, len(s), cl)] def _chunkiter(item, it, N): yield item for item in itertools.islice(it, N): yield item def chunksiter(iterable, N): """ How would you do that without a helper func? Don't hesitate to show me """ N -= 1 it = iter(iterable) for n in it: yield _chunkiter(n, it, N) References: Message-ID: Pascal wrote: > Hello, > > I've a function like this: > def myfunction(data, verbose = False): > dothis... > if verbose: print 'I do this' > dothisother > if verbose: print 'I do this other' > ... > > How can I do to exclude eachtime the `if verbose` statement? How about defining a function like: def myprint(arg): if verbose: print arg and using that? -- Timo Virkkala From andrew-pythonlist at puzzling.org Mon Mar 8 23:37:46 2004 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Tue, 9 Mar 2004 15:37:46 +1100 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: <20040309043746.GC32559@frobozz> On Mon, Mar 08, 2004 at 08:11:16PM -0800, Josiah Carlson wrote: > >That, and I suspect that reading strings in chunks, rather than 1 byte at a > >time, would be much faster also. > > Yes and no. string.find(character) is fast. > > seq = [read_chars.find(i) for i in break_characters] > min(filter(lambda inp:inp>-1, seq)+[-1]) > > May not be quite so fast for large numbers of break characters. For finding any one of multiple characters, I expect the re module would work well, with the bonus that it could easily extend to coping with more complex patterns. -Andrew. From miki.tebeka at zoran.com Wed Mar 10 01:28:16 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Wed, 10 Mar 2004 08:28:16 +0200 Subject: Okay Heres the problem: in Index In-Reply-To: References: Message-ID: Hello, > 1. The numbers 0, 1, 2, 3, that are in the output of > the vector.py are the corresponding position of the > words in the email_message, that I ran against the > dictionary_index. I want the index of the > corresponding word in the dictionary. For example: If > "syntax" was occuring in the dictionary at 500. I want > the 500 syntax instead of 6 syntax > that I am getting right now. When you load the dictionary just remember the line of each "syntax" and print it later. --- *not tested* --- syntax = {} lines = {} for lnum, line in enumerate(open("dictionary.txt")): val, syn = line.strip().split(":") syntax[syn] = long(val) lines[syn] = lnum --- > 1 index value index value index value index value > index value I don't see the problem here. HTH. Miki From droog at orange.gov Wed Mar 17 22:09:44 2004 From: droog at orange.gov (droog) Date: Thu, 18 Mar 2004 03:09:44 GMT Subject: New to Python. References: Message-ID: <9k4i50dnfsi42gdr5rue1vnpq7gfqkanb6@4ax.com> Thanks for helping, and no this is not a homework assignment I just like python and wanted to learn it on my own. droog On Thu, 18 Mar 2004 03:07:05 GMT, droog wrote: >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 jsbenson at bensonsystems.com Tue Mar 2 22:10:47 2004 From: jsbenson at bensonsystems.com (John Benson) Date: Tue, 2 Mar 2004 19:10:47 -0800 Subject: ELF object file analysis tool in Python? Message-ID: <06c401c400cd$20444fe0$210110ac@jsbwxp3> I already googled and only turned up some references dating from 2000. Anybody know of any current Python tool that can open up and dissect information from an ELF (Executable and Linking Format) object file? I don't care about machine language stuff, but goodies like what sources were used in the compile, and what routines are used. From skip at pobox.com Wed Mar 24 15:12:33 2004 From: skip at pobox.com (Skip Montanaro) Date: Wed, 24 Mar 2004 14:12:33 -0600 Subject: portable /dev/null again In-Reply-To: <4061D154.8090809@neggie.net> References: <4061D154.8090809@neggie.net> Message-ID: <16481.60337.370411.907718@montanaro.dyndns.org> John> class nullFile: John> def write(self, data): John> pass John> However, as the above does not present a full Python file object, John> it can't go everywhere that say, sys.stdout can go. How about: class nullFile: def _null(self, *args, **kwds): pass def __getattr__(self, name): return self._null ? Skip From __peter__ at web.de Thu Mar 11 02:41:42 2004 From: __peter__ at web.de (Peter Otten) Date: Thu, 11 Mar 2004 08:41:42 +0100 Subject: index out of range with slice object References: Message-ID: Peter Otten wrote: > Uwe Mayer wrote: > >> a class of mine should support the list interface and implements the >> __len__ and __getitem__ methods. >> >> Now when I ask for an unbounded slice: >> >>>>> len( myObj[:] ) >> >> my __getitem__(self, y) method gets called with >> >> y = slice(0, 2147483647, None) >> >> Now step size is ok, but where does that incredibly large stop index come >> from? Also I expected the start index rather to be None than zero. >> The __len__(self) method returns the correct length, which is 728. >> >> Has anybody encountered something like that bevore? Is that natural or am >> I doing something wrong? > > There seems a transition to be going on, due to extended slices, I > suppose: > >>>> class Old: > ... def __getitem__(self, index): > ... return index > ... >>>> class New(object): > ... def __getitem__(self, index): > ... return index > ... >>>> New()[:] > slice(None, None, None) >>>> Old()[:] > slice(0, 2147483647, None) >>>> > > I found only the old style behaviour documented in the reference manual > http://www.python.org/doc/current/ref/slicings.html: Ok, read it again: "The semantics for an extended slicing are as follows. [...] The conversion of a proper slice is a slice object (see section 3.2) whose start, stop and step attributes are the values of the expressions given as lower bound, upper bound and stride, respectively, substituting None for missing expressions." > > "The lower and upper bound expressions, if present, must evaluate to plain > integers; defaults are zero and the sys.maxint, respectively." > > So "incredibly large" is in fact sys.maxint, which should be obvious if > you convert it to hexadecimal: > >>>> hex(2147483647) > '0x7fffffff' > > Anyway, you can use the indices() method to get the actual boundaries in > both cases: > >>>> Old()[:].indices(10) > (0, 10, 1) >>>> New()[:].indices(10) > (0, 10, 1) >>>> > > Peter From josh+news at nextyme.net Sun Mar 21 10:38:41 2004 From: josh+news at nextyme.net (Josh Smith) Date: Sun, 21 Mar 2004 09:38:41 -0600 Subject: Timeout on a UDP Socket References: Message-ID: In article , w wrote: > I'm having problems with this program hanging on the revc(buf). I was > trying to figure out a way to allow the socket to timeout. I'm have > tried making the socket non-blocking but had on luck. Being very new > to Python, could there be a better way to accomplish this task. The > program works very well, but on occassion is will not receive the data > from the server and hang. You could use a sigalarm (assuming your OS supports that). For an example from the python docs: http://www.python.org/doc/current/lib/node304.html I've also added some example code to your client example demonstrating this (if you'll excuse the intrusion into your code :) ) -jbs # Client program import os.path,signal from socket import * from time import * # Set the socket parameters #host = "localhost" host = "10.0.0.20" port = 21567 buf = 1024 addr = (host,port) def handler(signum,frame): """This is a handler function called when a SIGALRM is received, it simply raises a string exception""" raise "SocketTimeOut" # Create socket UDPSock = socket(AF_INET,SOCK_DGRAM) # Send messages while(1): if not os.path.exists( "user1.inp" ) : sleep( 2 ) else: print "opening....." print "reading....." in_file = open("user1.inp", "r") data = in_file.readline() #print in_line in_file.close() if(UDPSock.sendto(data,addr)): print "Sending message '",data,"'....." if os.path.exists( "user1.inp" ) : os.remove( "user1.inp" ) print "Waiting for Response..." # Receive messages try: # setup signal handler signal.signal(signal.SIGALRM,handler) # 10 seconds is the limit signal.alarm(10) data = UDPSock.recv(buf) # shutdown the alarm signal.alarm(0) print "\nReceived message '", data,"'" #output result message from server f=open( "user1.out", "w" ) f.write( data ) f.close() except "SocketTimeOut": f=open("user1.out","w") f.write("Timed out on receive from "+host+", got no data\n") f.close() # Close socket UDPSock.close() From ketulp_baroda at yahoo.com Wed Mar 3 04:56:20 2004 From: ketulp_baroda at yahoo.com (ketulp_baroda at yahoo.com) Date: 3 Mar 2004 01:56:20 -0800 Subject: attachment Message-ID: 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?? From bignose-hates-spam at and-benfinney-does-too.id.au Wed Mar 24 16:50:15 2004 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 25 Mar 2004 08:40:15 +1050 Subject: Beginner Threaded file reading access References: <2835a96b.0403230909.35be2b7b@posting.google.com> <956003ae.0403241406.1ba944d3@posting.google.com> Message-ID: On 24 Mar 2004 14:06:31 -0800, Andy Robinson wrote: > aahz at pythoncraft.com (Aahz) wrote in message news:... >> In article <2835a96b.0403230909.35be2b7b at posting.google.com>, >> Jesse Noller wrote: >> >With 5 threads - I need each of the 5 threads to read 1 line from >> >the file (but never the same line) and perform the processing. >> >> Bad idea. Never access the same external resource from multiple >> threads. > > Unless each line was a URL which needed a test suite running against > it, or the name of a file needing significant independent processing? Nope. If you want multiple threads to *process the line*, that's great; but only one thread should be *reading the file*. -- \ "No one ever went broke underestimating the taste of the | `\ American public." -- Henry L. Mencken | _o__) | Ben Finney From klausm0762 at yahoo.de Wed Mar 3 15:46:24 2004 From: klausm0762 at yahoo.de (Klaus Momberger) Date: 3 Mar 2004 12:46:24 -0800 Subject: Lua Book References: <2ae25c6b.0403020006.6b99e590@posting.google.com> <1048rn8lpr0acde@corp.supernews.com> <1049gqe9n762hf6@corp.supernews.com> <75a58466.0403021617.7f765581@posting.google.com> Message-ID: <80a8af7d.0403031246.17ad4725@posting.google.com> ciw42 at hotmail.com (ciw42) wrote in message news:<75a58466.0403021617.7f765581 at posting.google.com>... ... > 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. Did you skip the foreword? They wrote just that. Lua is meant as an extension language, not as an replacement for standalone scripting languages. It can be used standalone, of course, which makes sense if you need speed or size of the interpreter matters. I just read the book during a long train-ride and liked it a lot. Terse and to the point, and I could even learn something new from it. E.g. I hadn't heard of coroutines before. I also liked the meta-classes stuff. -klaus From joe at notcharles.ca Sun Mar 28 01:42:50 2004 From: joe at notcharles.ca (Joe Mason) Date: Sun, 28 Mar 2004 06:42:50 GMT Subject: Prothon Prototypes vs Python Classes References: <569c605ld1cj8fc1emolk08ete0s1prls1@4ax.com> Message-ID: In article , Andrew Bennetts wrote: > Actually, in Python, it's even easier than that: > >>>> class C(object): pass > ... >>>> class D(C): pass > ... >>>> C.__subclasses__() > [] Cool. How come this isn't in either the Language Reference or Library Reference? I just skimmed through those looking for special class-related methods the other day, when I first started looking at prototypes, and didn't notice __subclasses__, and now I can't find it in the index. Joe From peter at semantico.com Thu Mar 25 05:00:36 2004 From: peter at semantico.com (Peter Hickman) Date: Thu, 25 Mar 2004 10:00:36 +0000 Subject: Python for large projects In-Reply-To: References: <1060p59d9rg9819@corp.supernews.com> <36wzna6qzur.fsf@hundertwasser.ti.uni-mannheim.de> Message-ID: <4062adc4$0$21343$afc38c87@news.easynet.co.uk> >> That is actually a view held by some people and has been attempted on >>some projects: the programmers do not have access to compilers and deliver >>their code to someone else when complete. I seem to recall this, it was a 'zero defect' policy that IBM OZ tried. It was one of those PHB development methodologies that assumed that if you ran a modern code shop like 'the old days' (of code listings which had to be delivered to the punch room to be turned into punch cards that were then scheduled to be loaded into the hopper to be compiled so you could get a compiler error report two days later - yes thats how we actually used to do it!). The assumption was that 'in the old days' the code was less buggy thus the methods used must be superiour. The fault with this was that the amount of code being produced 'in the old days' was less, much much less. >>I think all these projects failed. Many man years down the drain if I recall, but being IBM they just went and tried it all over again. > Do you have a reference describing such an attempt? Fraid not, it is folklore for us (ex)IBM mainframe programmers but I do recall reading the actual article sometime in the past, oh, 10 years! From mfranklin1 at gatwick.westerngeco.slb.com Thu Mar 4 15:12:44 2004 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Thu, 04 Mar 2004 20:12:44 +0000 Subject: tkFileDialog.askopenfilename In-Reply-To: <8a5a6d82.0403041057.30d4c773@posting.google.com> References: <8a5a6d82.0403041057.30d4c773@posting.google.com> Message-ID: <40478DBC.60207@gatwick.westerngeco.slb.com> Sonia Rovner wrote: > 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? tkFileDialog.saveasfilename could be what you are looking for... trusty pydoc comes to the rescue... $ pydoc tkFileDialog FUNCTIONS askdirectory(**options) Ask for a directory, and return the file name askopenfile(mode='r', **options) Ask for a filename to open, and returned the opened file askopenfilename(**options) Ask for a filename to open askopenfilenames(**options) Ask for multiple filenames to open Returns a list of filenames or empty list if cancel button selected askopenfiles(mode='r', **options) Ask for multiple filenames and return the open file objects returns a list of open file objects or an empty list if cancel selected asksaveasfile(mode='w', **options) Ask for a filename to save as, and returned the opened file asksaveasfilename(**options) Ask for a filename to save as HTH Martin From oussoren at cistron.nl Thu Mar 25 14:53:32 2004 From: oussoren at cistron.nl (Ronald Oussoren) Date: Thu, 25 Mar 2004 20:53:32 +0100 Subject: State of Python scripting on Mac OS X? In-Reply-To: <406225e0@news.nucleus.com> References: <406225e0@news.nucleus.com> Message-ID: <1843AD50-7E96-11D8-8D1D-0003931CFE24@cistron.nl> On 25-mrt-04, at 1:26, Mathieu Fenniak wrote: > On 2004-03-24 16:42:04 -0700, Francis Avila said: >> 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. > > Python currently supports scripting through OSA very well. The > support is not too well documented and can take a bit of getting used > to, though. The interfaces are not the simplest they could be, but > they work very well. > > I've written to starter articles ragaring OSA scripting that might be > useful: > http://stompstompstomp.com/weblog/technical/2003-09-22 > http://stompstompstomp.com/weblog/technical/2004-02-05 > > It's hard to find more information on using OSA with Python. I was > able to scrape together enough to get it working, but I've never found > a great resource. But, after the Python interface is figured out, the > Script Editor application provides enough insight into individual > applications to work. There has been some development w.r.t. OSA scripting using Python, such as http://freespace.virgin.net/hamish.sanderson/appscript.html. Ronald From danb_83 at yahoo.com Thu Mar 11 17:11:04 2004 From: danb_83 at yahoo.com (Dan Bishop) Date: 11 Mar 2004 14:11:04 -0800 Subject: backquote References: <9e5ea2c4.0403110753.5c4d437a@posting.google.com> Message-ID: OlafMeding at compuserve.com (Olaf Meding) wrote in message news:<9e5ea2c4.0403110753.5c4d437a at posting.google.com>... > Is `object` (using backquotes) the same as saying str(object)? Trying > to understand how backquotes work. Thanks for your help. It's the same as using "repr(object)". From mintiSPAMBLOCK at yahoo.com Mon Mar 22 14:14:25 2004 From: mintiSPAMBLOCK at yahoo.com (Minti) Date: 22 Mar 2004 11:14:25 -0800 Subject: OFF-TOPIC:: Why Lisp is not my favorite programming language References: <165b3efa.0403030443.4d591f04@posting.google.com> <40460dd5$0$5916$7a628cd7@news.club-internet.fr> Message-ID: nish20 at netzero.net (Mike Nishizawa) wrote in message news:... > These posts are like big huge neon signs that say, "I'm IGNORANT." If > you hold that 1 language is better than all other languages, then you > ARE ignorant. LISP is a parsing language. It's obviously not made to > do the same things that C is. LISP is extremely fast for processing > data files. > > C in not an end-all be-all of programming languages, even though it is > quite robust. For instance, C is great if you are going to develop > software for 1 platform. However, if you are developing software for > multiple platforms, Java is a better choice. > > Really these discussions boil down to the programmer him/herself, who > is usually the one at fault for poor performance. I'm not quite sure > when this happened, but at some point programmers started relying on > hardware for fast, efficient software and from that point on, the > quality and emphasis placed on writing efficient programs has > diminished. If you want your code to run faster, make it more > efficient... make it use less resources... and use the right language > for the job. Don't try to fit all things under one umbrella because > that language has not been developed yet. > Quite valid arguments. However I have one question to ask, I am quite naive with LISP { just couple of weekends ) but I think the OP did raise some doubts in my mind. I mean to me LISP looks right now to be just OK. Some people said that with all the () it is difficult to code in but I think that with proper indentation that is absolutely ludicurous. However when some one says that the code might be 31.? times slower as compared to C, kinda of scares me. Could assert such figures. I know speed is not the one and only goal but just wondering if these figures are correct. Thanks -- ISA ikaur at acm dot org Replace "kaur" by "singh" From http Sat Mar 27 16:44:14 2004 From: http (Paul Rubin) Date: 27 Mar 2004 13:44:14 -0800 Subject: Random Number References: Message-ID: <7xad226k41.fsf@ruckus.brouhaha.com> talktojamesblair at yahoo.com (james blair) writes: > I am generating a random number using > random.randint(1,10000000000) At least in Python 2.2, 10000000000 is not a valid arg to randint, which has to take two int (not long) values. 10000000000 won't fit in 32 bits. I'm not sure about Python 2.3 or 2.4. > Whats the possibility that the numbers generated will be same when > generated by 100 users at the same time? There's two levels where you have to think about that questions: 1) Is the underlying generator biased enough to make such a collision more likely than pure chance? That would be a failure of what's called the "poker test" (Knuth vol. 2) and Python's PRNG is supposed to be good about that, so you shouldn't get extra (or too few) collisions that way. 2) What's the likelihood of such a collision if the numbers from the generator are really random? Let N be the number of distinct values, in this case N= approx. 10**10. Let k be how many numbers you draw, i.e. in this case k=100. Let the random numbers be a[1],a[2],...,a[N]. If there's no collision, it means that for every i,j with i,j in 1,2,...,k, a[i] != a[j]. There are k**2/2 such (unordered) pairs, and for any i,j, a[i]!=a[j] with probability 1-1/N. So the chance of all the pairs being unequal is (1-1/N)**(k**2/2). That's about exp(-k**2/(2*N)), or about 1 in 2 million for your parameters. The case N=365, k=23 is the famous "birthday paradox". It says that if you have 23 people in a room, there's a better-than-even chance that some two of them have the same birthday. In general, if you have a set of random numbers with N possible values, you can expect to see a collision after seeing O(sqrt(N)) numbers. Those collisions are called "birthday collisions" after the birthday paradox. > Whats the best method to generate random numbers so that they are most > likely unique?? If they're random, there is a chance that they will collide, and the only way to make that less likely is to use a bigger range. From mis-viruswarn at connect.com.au Thu Mar 18 03:18:00 2004 From: mis-viruswarn at connect.com.au (mis-viruswarn at connect.com.au) Date: Tue, 23 Mar 2004 05:18:00 +11660 (EADT) Subject: RE Do you? Message-ID: <20040322181505.B5A2F4F9D7@koro.off.connect.com.au> Your e-mail message with the subject Do you? has an attachment that is not allowed by Connect Internet Solutions From jepler at unpythonic.net Wed Mar 24 13:51:34 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 24 Mar 2004 12:51:34 -0600 Subject: portable /dev/null again In-Reply-To: <4061D154.8090809@neggie.net> References: <4061D154.8090809@neggie.net> Message-ID: <20040324185134.GD11883@unpythonic.net> I think this is a decent idea, though with only two real platforms (Unix, win32) it's not hard to implement. At least, I assume that OSX has /dev/null... if os.name == 'win32': nullfilename = 'nul:' else: nullfilename = '/dev/null nullfile = file(nullfilename, "r+b") note that "nullfile" can be closed just like any other file, which is likely to lead to problems.. or you could os.close(fileno(nullfile)) too.. Jeff From trevp at trevp.net Sun Mar 21 05:50:09 2004 From: trevp at trevp.net (Trevor Perrin) Date: Sun, 21 Mar 2004 02:50:09 -0800 Subject: ANN: TLS Lite 0.3.0 Message-ID: <5.2.0.9.0.20040321024920.02fd9c40@pop.sbcglobal.yahoo.com> I'm pleased to announce a new release of TLS Lite. Several requested features have been added, and I've cleaned things up a lot. New features since 0.2.0 ------------------------- - API docs (courtesy of Epydoc) - integrates with Twisted and asyncore - supports PyCrypto and GMPY for performance - X.509 path validation (requires cryptlib) - supports loading PEM private keys in pure Python - supports OS-specific Random Number Generators - RSA blinding to prevent timing attacks http://trevp.net/tlslite/ TLS Lite is a free python library that implements SSL v3 and TLS v1. TLS Lite supports non-traditional authentication methods such as SRP, shared keys, and cryptoIDs, in addition to X.509 certificates. Trevor From frithiof.jensen at removethis.ted.ericsson.dk Fri Mar 5 07:42:55 2004 From: frithiof.jensen at removethis.ted.ericsson.dk (Frithiof Andreas Jensen) Date: Fri, 5 Mar 2004 13:42:55 +0100 Subject: Gadfly ???? References: <8089854e.0403040124.1c6bd929@posting.google.com> Message-ID: "Fuzzyman" wrote in message news:8089854e.0403040124.1c6bd929 at posting.google.com... > Gadfly looks like an interesting database system for python. I am > working on a couple of projects that may benefit from using a database > (on the other hand, these days - is there really aproblem with using > dictionaries that are a couple of meg in size and searching through > those ??). That you will be reinventing the wheel - databases are good at dealing with storing stuff and ordering/querying for it in many different ways you did not think you would need when starting out. You could even say that an SQL database can be an interface to the data produced by you application - if you need to stick a Report in a MS-Word document or Spreadsheet f.ex.. > > One of these projects is a customer feedback database that will be > installed on our intranet - so I was looking for a pure python > solution..... Why "Pure Python"? Check the http://www.python.org/topics/database/ - if there is a Python DB-API for the database it is practically transparent to use it. > I thought Gadfly was a pure python implementation - however when I > download the package it looks like it's optimised to work with > kjBuckets and kwParsing. *Optimised* yes - it will *work* without though. Gadfly has some other issues: It is a limited SQL language implementation so f.ex. CHECK and KEY constraints will not work - you have to do the syncronising of linked tables and parameter checks "by hand" as it were. PySQLite is the closest to a full SQL implementation of "the simple" databases - beyond that it is a Server; PostGresSQL f.ex. PySQLite comes with a rather complete SQL implementation. Being a file-based database there may be some locking issues preventing simultaneous access to your database depending on the version of windows you have and the version of PySQLite. It can be worked around. From xslt-admin at gnome.org Wed Mar 24 07:00:23 2004 From: xslt-admin at gnome.org (xslt-admin at gnome.org) Date: Wed, 24 Mar 2004 07:00:23 -0500 Subject: Your message to xslt awaits moderator approval Message-ID: <20040324120023.9989.10692.Mailman@moniker.gnome.org> Your mail to 'xslt' with the subject Re: Delivery Protection Is being held until the list moderator can review it for approval. The reason it is being held: Post by non-member to a members-only list Either the message will get posted to the list, or you will receive notification of the moderator's decision. From python at rcn.com Wed Mar 17 04:01:32 2004 From: python at rcn.com (Raymond Hettinger) Date: 17 Mar 2004 01:01:32 -0800 Subject: SHA-based subclass for random module References: <7xptbgjpk4.fsf@ruckus.brouhaha.com> Message-ID: <5d83790c.0403170101.1a0a6452@posting.google.com> [Paul Rubin] > This is intended to be less predicable/have fewer correlations than > the default Mersenne Twister or Wichmann-Hill generators. Comments > are appreciated. 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. Here is a rough cut that extracts a 53 bit float on every pass and leaves the remaining 107 bits of state hidden: import struct import sha import random def srandom(seed): gen = sha.new(seed) digest = gen.digest update = gen.update random.seed(seed) mt = random.random unpack = struct.unpack tofloat = 1.0 / 2 ** 53 while 1: state = digest() randint = unpack('Q', state[:8])[0] >> 11 # grab 53 bits yield randint * tofloat update(state) update(str(mt())) # twister never hurts, but can help period r = srandom('the quick brown fox jumped') for i in xrange(10): print r.next() Raymond Hettinger From paul at prescod.net Sun Mar 28 22:13:09 2004 From: paul at prescod.net (Paul Prescod) Date: Sun, 28 Mar 2004 19:13:09 -0800 Subject: Python as Glue Language In-Reply-To: <40674ad7$1@news.unimelb.edu.au> References: <40674ad7$1@news.unimelb.edu.au> Message-ID: <40679445.60407@prescod.net> Maurice LING wrote: > Hi Everyone, > > From the documentations, it did mention that python is a good glue > language. What does it really means by "glue language"? Does it means > interfacing between modules of different languages? How does that work? > Because it seems that only C is mentioned in the documentations and I'm > not quite interested to program in C unless absolutely essential. Not just C, but also C++, VB and C# (via COM and Python.NET), Java (via Jython and JPE), Fortran (via PyFort) and anything else in the world via sockets, files, pipes, shared memory, web services, standard Internet protocols etc. Python is good for gluing almost anything to almost anything in large part because the Python community makes bridges to every interesting technology in the universe. Paul Prescod From shalabh at cafepy.com Mon Mar 1 17:33:59 2004 From: shalabh at cafepy.com (Shalabh Chaturvedi) Date: Mon, 01 Mar 2004 14:33:59 -0800 Subject: How to use __getattribute__ to access a class attribute? In-Reply-To: <4043956c$0$41749$5fc3050@dreader2.news.tiscali.nl> References: <40425d1b$0$41761$5fc3050@dreader2.news.tiscali.nl> <4043956c$0$41749$5fc3050@dreader2.news.tiscali.nl> Message-ID: Ruud de Jong wrote: > Shalabh Chaturvedi schreef: > >> Ruud de Jong wrote: >> >>> 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. >> >> >> >> If what you're trying to do is get C.a (where C is the class and a is >> the name of the staticmethod) but all you have is the class C and a >> string mname = "a", then just getattr(C, mname) should work. Generally >> this works for any attribute access where you have the attribute name >> in another variable. > > > Erh, hmm, rrriight... Built-in functions. > Completely forgot about that one -- too focussed > on trying to do everything with object methods and such. > I really need to pay more attention to those built-in functions. > > Well, that solves my immediate problem. > I knew there had to be a simple solution :-) > >> >> Another way to get the naked function, which also works for >> classmethods, is to do C.__dict__['a']. See comments below that >> explain what you see. > > > Well, that's not true, at least not on my system (XP, Python 2.3.3): > > >>> class C(object): > def a(): > print "static method a" > a = staticmethod(a) > > > >>> C.__dict__['a'] > > > > [snipped] Sorry, my mistake. In fact it doesn't work for even classmethods. Only for functions. >> To repeat the same experiment, you should call >> type(C).__getattribute__(C, 'a'). Note that in this case C *has* its >> own __getattribute__ attribute (which is meant for instances of C, not >> C itself). > > > C did not have its own __getattribute__ method. It inherited it > from object. True. Left out a little bit of information there (for brevity). > I still find this whole thing slightly ambiguous. > A class C is itself an object, an instance of 'type', > just as x = C() leads to x being an instance of class C. > But x.__getattribute__ and C.__getattribute__ return > different objects. Only if you didn't first do x.__getattribute___ = None . then x.__getattribute__ doesn't even return anything. x.__getattribute__ is never meant to be called. It is only called on /type/ objects. If you want to get an attribute on obj, you call __getattribute__ on type(obj). (Well that's what Python does, you can just use getattr(obj, 'attr')). >> In fact you do this later, and it works. Hmm, at first glance I'd >> expect what you do above to return an exception if passed C instead of >> an instance of C (like any other well behaved method). I don't know >> why that doesn't happen. > > > I would also have expected an exception. The strange thing, as I see > it, is that x.__getattribute__ and type(C).__getattribute__ both give > the correct result, but that C.__getattribute__ *almost* gives the > correct result, but stops at calling the __get__ function on the > desciptor object. What C.__getattribute__ doesn't do (maybe it should?) is to check that the first argument is an instance of C, or at least an instance of object. I'm just guessing here, but if it continues with the default mechanism of __getattribute__, it is going to get the staticmethod object. > > Anyway, now that you've kindly reminded me of the existance of getattr, > I'll not spend any more time trying to understand this. > > Thanks, > > Ruud > From noreply at python.org Wed Mar 3 11:03:46 2004 From: noreply at python.org (noreply at python.org) Date: Wed, 03 Mar 2004 10:03:46 -0600 Subject: Notify about using the e-mail account. Message-ID: Dear user, the management of Python.org mailing system wants to let you know that, Your e-mail account has been temporary disabled because of unauthorized access. For more information see the attached file. For security purposes the attached file is password protected. Password is "73024". The Management, The Python.org team http://www.python.org -------------- next part -------------- A non-text attachment was scrubbed... Name: TextDocument.zip Type: application/octet-stream Size: 12420 bytes Desc: not available URL: From newsgroups at jhrothjr.com Sat Mar 27 20:52:42 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 27 Mar 2004 20:52:42 -0500 Subject: Prothon Prototypes vs Python Classes References: <569c605ld1cj8fc1emolk08ete0s1prls1@4ax.com> Message-ID: <106cc1f2rsnaoe2@news.supernews.com> "David MacQuigg" wrote in message news:569c605ld1cj8fc1emolk08ete0s1prls1 at 4ax.com... > Playing with Prothon today, I am fascinated by the idea of eliminating > classes in Python. I'm trying to figure out what fundamental benefit > there is to having classes. Is all this complexity unecessary? > > Here is an example of a Python class with all three types of methods > (instance, static, and class methods). > > # Example from Ch.23, p.381-2 of Learning Python, 2nd ed. > > class Multi: > numInstances = 0 > def __init__(self): > Multi.numInstances += 1 > def printNumInstances(): > print "Number of Instances:", Multi.numInstances > printNumInstances = staticmethod(printNumInstances) > def cmeth(cls, x): > print cls, x > cmeth = classmethod(cmeth) > > a = Multi(); b = Multi(); c = Multi() > > Multi.printNumInstances() > a.printNumInstances() > > Multi.cmeth(5) > b.cmeth(6) > > > Here is the translation to Prothon. > > Multi = Object() > with Multi: > .numInstances = 0 > def .__init__(): # instance method > Multi.numInstances += 1 > def .printNumInstances(): # static method > print "Number of Instances:", Multi.numInstances > def .cmeth(x): # class method > print Multi, x > > a = Multi(); b = Multi(); c = Multi() > > Multi.printNumInstances() > a.printNumInstances() > > Multi.cmeth(5) > b.cmeth(6) > > > Note the elimination of 'self' in these methods. This is not just a > syntactic shortcut (substiting '.' for 'self') By eliminating this > explicit passing of the self object, Prothon makes all method forms > the same and eliminates a lot of complexity. It's beginning to look > like the complexity of Python classes is unecessary. You're mixing two different issues here. The first one I'm going to address is namespaces. I tend to agree with you, and I've said it before; most languages would benefit a lot by putting different kinds of identifiers in lexically distinct namespaces, and letting the editors take up the slack. We expect modern editors to colorize keywords, why not let them do some of the dogwork? > My question for the Python experts is -- What user benefit are we > missing if we eliminate classes? Duh? Again, as far as I can tell, classes are a leftover idea from static typing. However, you should think of a lot of the standard OO patterns. We have, for example, classes which are never intended to be instantiated, and classes that are, and classes that have only one instance (singletons.) In interactive fiction (and I suspect other application areas) having a class with more than one instance is rare (but not unheard of.) In more normal applications, you usually have a large number of instances of any given class; those instances don't vary in their behavior so it makes sense to optimize access by distinguishing between the class and the instance. This is, in fact, what Python does. It has syntactic support for creating instances of type "class", complete with builtin support for methods and fancy initialization options, and a very abbreviated syntax for the much more prevalent operation of creating instances of type "instance." I've seen another recent comment to the effect that eliminating classes would remove a very valuable level of abstraction for larger programs. The idea is superficially attractive. I'd like to see examples of very large systems done in a prototype based language and how they handled the problem, or if it was, indeed, a problem. I doubt very much if I'm going to find that one extreme or the other is "correct." It seems to differ by what you want to do with it. John Roth > > -- Dave > From kamikaze at kuoi.asui.uidaho.edu Thu Mar 4 17:13:35 2004 From: kamikaze at kuoi.asui.uidaho.edu (Mark 'Kamikaze' Hughes) Date: 4 Mar 2004 22:13:35 GMT Subject: Typecasting References: Message-ID: Jani Yusef wrote on 23 Feb 2004 08:53:31 -0800: > Wow, YAMQFAI (Yet Another Moronic Question From An Indian). What is > terrible is how GE is now suffering because of these dollar a day [...] -- Mark Hughes "Doing the impossible makes us mighty." -Captain Malcolm Reynolds, Firefly From jolsen at mail2world.com Thu Mar 18 08:46:19 2004 From: jolsen at mail2world.com (Jesper) Date: Thu, 18 Mar 2004 13:46:19 GMT Subject: dictionary wart In-Reply-To: <7xr7vquwpo.fsf@ruckus.brouhaha.com> References: <6b17fa95.0403180441.a747b15@posting.google.com> <7xr7vquwpo.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > jolsen at mail2world.com (Jesper Olsen) writes: > >>Does python have a way of defining a dictionary default? >>I think not, but are there any plans to incorporate it? >> >>Intuitively I would imagine that >> >>a={} >>a.set_default(my_default) >> >>would do this -ie. a[my_new_key] should now return the the default >>value my_default instead of creating an exception. > > > No, instead of a[my_new_key] use a.get(my_new_key, my_default). > That does what you want. Unfortunately not - get() is different, because you can not assign to it. For instance in a dictionary which is mapping strings to integers (or lists), I would like to do a[my_key]+=5 expressing that with get() would be awkward. Jesper From ajsiegel at optonline.com Fri Mar 12 09:06:38 2004 From: ajsiegel at optonline.com (Arthur) Date: Fri, 12 Mar 2004 14:06:38 GMT Subject: loop scope References: Message-ID: On Thu, 11 Mar 2004 17:54:56 -0700, David MacQuigg wrote: >> >>>>> b=[4,5,6] >>>>> [t*2 for t in b] >>[8, 10, 12] >>>>> t >>6 >> >>Is this anywhere useful, or more of an artifact? > >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. I am not following this argument. The surprise, specifically, is that I don't think of myself as having declared "t" as a variable. it is don't magically, as a placeholder and for a very specific purpose. So I would expect it to go away outside of the " [ " and " ] " by equal and opposite magic. I ran into the issue while playing at the prompt. Running the same statement I had run previously gave me a different result than before. Surprising. Yes I had tested a list comp, in between. Because I have been around the language for some time, and have my ear to the ground, it didn't take me long to understand what was happening. Flabbergasted, rather than surprised, might have otherwise been the reaction. Art From lbates at swamisoft.com Thu Mar 11 19:13:28 2004 From: lbates at swamisoft.com (Larry Bates) Date: Thu, 11 Mar 2004 18:13:28 -0600 Subject: 2D List comprehension & replace Message-ID: I've gone brain-dead trying to get this to work using list comprehensions. I have a list of lists like the following: l=[[92.6, 0, 93.5], [94.7, 95.6, 95.7], [91.2, 92.1, 93.0]] what I want is a new list with the zero (0) replaced with None. I thought I would use the fact that the command: 0 or None seems to return None. This procedural code does the trick, but I just know it can be done with a single list comprehension. tol=[] for a in l: til=[] for v in a: if a != 0: til.append(v) else: til.append(None) tol.append(til) l=tol Thanks in advance. Larry Bates From fredrik at pythonware.com Mon Mar 15 03:25:19 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 15 Mar 2004 09:25:19 +0100 Subject: getting size of gif References: <9L2dna_mgLuovNPd4p2dnA@comcast.com><104se8bhc5rm477@corp.supernews.com> <1079307022.31907.0@nnrp-t71-02.news.uk.clara.net> Message-ID: Garry Knight wrote: > > note that you don't need all of PIL to run the above example; it's enough > > to install Image.py, ImageFile.py, ImagePalette.py, and the > > *ImagePlugin.py files you need for your application. the binary > > extensions are not needed. > > Gosh, what a payload! you can download the files from the net; you don't have to type them in yourself. > It might not be the Python way of doing things, but this should work > just as well: > > f = open('x.gif', 'rb') > gif = f.read(6) # 'gif89a' > width = ord(f.read(1)) + 256 * ord(f.read(1)) > depth = ord(f.read(1)) + 256 * ord(f.read(1)) > print "width = %d, depth = %d" % (width, depth) > > You could just do f.seek(6) in the second line if you're not worried about > checking that it's a valid gif file. Of course, this only works with > single-image files, not with animated gifs. it gives you the height, not the depth. and it returns the size of the logical screen, so it should work with animated GIFs as well. but it doesn't give you any other information about the file, and it doesn't work for JPEGs, PNG files, or any of the other 35+ formats PIL supports. From andrew-pythonlist at puzzling.org Thu Mar 25 06:34:10 2004 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Thu, 25 Mar 2004 22:34:10 +1100 Subject: Error handling in smtp In-Reply-To: References: Message-ID: <20040325113410.GC29958@frobozz> On Thu, Mar 25, 2004 at 03:22:35AM -0800, james blair wrote: > Hi > I want to handle all the error that are thrown by smtp > Do I have to handle each error seperately > i.e > except SMTPConnectError: > except SMTPResponseException: etc Quick glance at the smtplib module suggests that all of its exceptions inherit from SMTPException, so "except SMTPException:" should do what you want. -Andrew. From b.scharpf at tesionmail.de Fri Mar 5 16:25:15 2004 From: b.scharpf at tesionmail.de (Bertram Scharpf) Date: 5 Mar 2004 21:25:15 GMT Subject: self for modules References: Message-ID: Hallo, Terry Reedy schrieb: > > "Bertram Scharpf" wrote in message > news:slrnc4gvn4.md9.b.scharpf at homer.bertram-scharpf... >> >> when I want to access the module itself, I can write >> >> ---- >> import sys >> module_self = sys.modules[ __name__] >> ---- >> >> Is there a smarter way to do this? > > shorter and not implementation specific is > >>>> mymod = __import__(__name__) >>>> mymod > > > I presume this works in imported module also. Nice idea, indeed. Thank you. Bertram -- Bertram Scharpf Stuttgart, Deutschland/Germany http://www.bertram-scharpf.de From steve at ninereeds.fsnet.co.uk Sat Mar 27 12:06:30 2004 From: steve at ninereeds.fsnet.co.uk (Stephen Horne) Date: Sat, 27 Mar 2004 17:06:30 +0000 Subject: A 'Python like' language References: <40645d8f$0$10775$afc38c87@news.easynet.co.uk> <1068up4kn49778@news.supernews.com> Message-ID: <58cb60lmovocadg9p3ghu39t4ga343gfvd@4ax.com> On Fri, 26 Mar 2004 13:53:45 -0500, Roy Smith wrote: >"John Roth" wrote: >> 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. > >Are you objecting specifically to the use of the tab character for >indenting, or to the use of white space for statement grouping in >general? I don't know about David, but I know that I specifically dislike the use of the tab character. The *real* evil happens when people mix tabs and spaces for indentation, but I always preferred to use spaces rather than tabs. Different people have different tab sizes set up in their editors. As long as you don't mix tabs and spaces, the indentation itself will be clear - but having a different tab size can break other aspects of vertical alignment, damaging readability in other ways. It isn't as bad as the problems that arise when mixing tabs and spaces for indentation, but IMO it is bad enough. Reading (and maintaining consistency with) someone elses preferred indent size isn't really a hassle. Compared with dealing with tab size issues, IMO it's by far the least hassle. And of course any decent editor can convert tab keypresses to equivalent numbers of spaces as you type. On a separate issue, the Prothon developers seem to have the mistaken view that commas influence line continuation in Python. They don't - but parentheses, square brackets and braces do. Though the Prothon extra-indentation system (which is similar to Haskells offside rule, I suppose) is an interesting idea. -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From vincent at visualtrans.de Sat Mar 6 08:24:13 2004 From: vincent at visualtrans.de (vincent wehren) Date: Sat, 6 Mar 2004 14:24:13 +0100 Subject: Getting definition list References: <20040306071202.18241.00000981@mb-m06.aol.com> Message-ID: "Bluexcell" schrieb im Newsbeitrag news:20040306071202.18241.00000981 at mb-m06.aol.com... | ok so i use import to import a py file into my script. | | is there a way to list all the defined function labels that exist in the | imported file? | | ie if i import a file called test and test has defined functions called | myfunction1 my function2 myfunction3 etc but i dont know them, is there a | method to list all the function labels in test and print them as a listing | | test.mfunction1 | test.myfunction2 | test.myfunction3 | | etc. Roughly (untested) something like the following should get you started: import some_module import types d = some_module.__dict__ for k in d: obj = d[k] if type(obj) == types.FunctionType: print "some_module.%s" % k HTH, Vincent Wehren | | | | From lbates at swamisoft.com Thu Mar 25 17:03:49 2004 From: lbates at swamisoft.com (Larry Bates) Date: Thu, 25 Mar 2004 16:03:49 -0600 Subject: Variable scope in classes Message-ID: I'm confused about variable scope in a class that is derived from a base class framework. Can someone enlighten me on why bar.__init__ method can't see self.__something variable in the foo.__init__? Example: class foo: def __init__(self): print self.__something class bar(foo): __something="This is a test" def __init__(self): foo.__init__(self) x=bar() returns the following traceback: Traceback (most recent call last): File "C:\Python22\Lib\site-packages\Pythonwin\pywin\framework\scriptutils.py", line 301, in RunScript exec codeObject in __main__.__dict__ File "F:\SYSCON\SMARTROUTE\classjunk.py", line 13, in ? x=bar() File "F:\SYSCON\SMARTROUTE\classjunk.py", line 10, in __init__ foo.__init__() File "F:\SYSCON\SMARTROUTE\classjunk.py", line 3, in __init__ print self.__something AttributeError: bar instance has no attribute '_foo__something' Is there some "other" way to do this without passing information through foo.__init__ argument list? Regards, Larry Bates Syscon From rogerb at rogerbinns.com Sun Mar 21 12:48:40 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Sun, 21 Mar 2004 09:48:40 -0800 Subject: Python bytecode compatibility between interpreter versions References: <0qudndSnJMpWbsfdRVn-uA@powergate.ca> <7okui1-3no.ln1@home.rogerbinns.com> Message-ID: > > You are considering Python .pyc files and Java class files to be > > the same thing. They aren't. > > They're not 'the same thing'. They are roughly analogous to one > another though, wouldn't you say? No. I explained it further in the message. > Huh?? .pyc files are an "implementation detail of the Python > interpreter"? Care to expound further? 'Coz that sounds > pretty nonsensical... One version of a compliant Python interpretter happens to use these files, and expose that they exist. They are generated on demand and automatically updated. The Python interpretter could have stored them elsewhere on the filesystem (for example in a hidden "cache" directory), but for simplicity's sake stored them alongside the source file. Go ahead and write protect the directories containing your Python source (after deleting all .pyc files). You will find everything runs just fine without any visible .pyc files. If you write your own Python interpretter/compiler, it will be considered compliant if it implements the language correctly. There is *nothing* about bytecodes, or bytecode compatibility. For example if you wanted to write your own that ran on top of Java, you would probably just directly generate class files. If you wrote one that ran on a Palm device you would do something else. It is up to your implementation what it does. The only requirement would be working with Python *source* files. Roger From "Charles Krug" at cdksystems.com Wed Mar 31 09:00:46 2004 From: "Charles Krug" at cdksystems.com (U-CDK_CHARLES\Charles) Date: Wed, 31 Mar 2004 14:00:46 GMT Subject: Choosing Perl/Python for my particular niche References: <40652B0D.7C313F77@doe.carleton.ca> <4069F371.B4D08F58@doe.carleton.ca> Message-ID: On 30 Mar 2004 22:23:50 GMT, Fred Ma wrote: > Robin Munn wrote: >> > > Well, my bout with Perl took much, much more than an hour. > It worked, though. It's probably not enough experience to > get a good look at the strength of Perl. Well, here's two cents American, leaving the exchange calculation as an excercise for the reader. My first task at my last job was to automate a test that could run from the Solaris prompt. Knowing C, I tried to script it in csh, which proved difficult--redirecting stderr was needlessly convoluted. Then I read "csh scripting considered evil" and decided to give the Bourne shell a whirl. Though the syntax had a learning curve, once I cracked that nut, the project "Just Worked." Being a C programmer (embedded systems mostly) it was "Easy" to learn to use Python as "C without the compile" It took some playing before I realized the strength of Python as a prototyping language and stopped trying to write C code in Python. Of course, NOW I'm trying to learn how NOT to write C++ code in VisualBasic, so go fig. From newsgroups at jhrothjr.com Mon Mar 8 13:07:20 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 8 Mar 2004 13:07:20 -0500 Subject: How to implement a union (C data type) in Python? References: <2c22d0af.0403080753.f17a7e0@posting.google.com> Message-ID: <104pdlunkch6na0@news.supernews.com> "chads" wrote in message news:2c22d0af.0403080753.f17a7e0 at posting.google.com... > How would one implement a union (C data type) in Python, given this > simple example? What do you need this for? John Roth From donn at drizzle.com Thu Mar 18 00:50:33 2004 From: donn at drizzle.com (Donn Cave) Date: Thu, 18 Mar 2004 05:50:33 -0000 Subject: '1' + 1 ==> True ??? References: <405915F2.BE5ADDF3@alcyone.com> Message-ID: <1079589031.945449@yasure> Quoth Nicola Mingotti : ... | Even if i can't see it's utility , My guess is that the most important benefit is that any list of Python objects can be sorted. Donn Cave, donn at drizzle.com From drlinux at columbus.rr.com Wed Mar 31 19:03:57 2004 From: drlinux at columbus.rr.com (Dave Reed) Date: Wed, 31 Mar 2004 19:03:57 -0500 Subject: GUI Frameworks in Python? In-Reply-To: References: Message-ID: <200403311903.57465.drlinux@columbus.rr.com> I second the recommendation of Gtk/Glade/libglade with Python. I've used it to write large programs and can confirm that gtk2 will also work on Windows (although I haven't done much other than verify it works). I've written some software to further automate the process of writing GUI programs using Glade/libglade. I'm putting the finishing touches on an article I will be submitting to Linux Journal describing the software. It will hopefully be published in the July issue. I will be releasing the software under the GPL license. I am almost certain that on Linux/Unix wxWindows is just a layer on top of gtk so gtk will certainly be a little faster than wxWindows. I'm not certain what wxWindows runs on top of on MS Windows. Dave From dmq at gain.com Fri Mar 12 20:08:52 2004 From: dmq at gain.com (David MacQuigg) Date: Fri, 12 Mar 2004 18:08:52 -0700 Subject: Deprecating reload() ??? References: <40514A48.50907@domain.invalid> <09b350henbtk9vnai0v7fhtbsqbmubl7vn@4ax.com> <7cj4c.2733$G3.21896@localhost> <8ok3505b3b3g22bk8ci6iagptqav2cfi6r@4ax.com> Message-ID: <7ln4501mfe70sgrrk25fn0sj80f6cn8vt7@4ax.com> On Fri, 12 Mar 2004 11:42:06 -0600, Skip Montanaro wrote: > >> Reload is not broken, and certainly shouldn't be deprecated at least > >> until there's a better solution that won't suffer from reload's one > >> problem, IMHO, which is that it surprises some people by its > >> behaviour. I've written a short description of what reload() does to try and help reduce the confusion. This is intended for EEs who are new to Python. Please see http://ece.arizona.edu/~edatools/Python/Reload.htm I've also started a new thread to discuss this. See "Reload() Confusion" Comments are welcome. -- Dave From csgcsg39 at hotmail.com Wed Mar 10 12:41:42 2004 From: csgcsg39 at hotmail.com (C GIllespie) Date: Wed, 10 Mar 2004 17:41:42 -0000 Subject: Nice way of getting items from two lists Message-ID: Dear All, I have two equal size lists - list1, list2. Basically, each item in list 1 has a partner in list2. I was wanting to do something like So if: list1=['x','y','z'] list2=[1,2,3] then if I did this 'for loop' for name, value in list1,list2: print name, value I would get x,1 y,2 z,3 However, the 'loop' does not work. I could get what I want using range(len(list1)), but I'm trying to improve my programming skills (fortran background, so I'm weaning myself off GOTO's etc). So what's a nice way of doing this? Thanks Colin From thehaas at binary.net Thu Mar 18 12:41:36 2004 From: thehaas at binary.net (thehaas at binary.net) Date: Thu, 18 Mar 2004 17:41:36 GMT Subject: ConfigParser and Unicode Message-ID: I'm trying to read a config file with Unicode characters via ConfigParser with Python 2.3 and am having some problems. The file looks like: [DEFAULT] goodProcRef=PYTHON,RSS,Gr??,LDAP This is how I'm trying to read it: config = ConfigParser() config.read("work.cfg") goodProcRef = config.get(section,"goodprocref").split(",") goodProcRef now looks like this: >>> goodProcRef ['PYTHON', 'RSS', 'Gr\xfc\xdf', 'LDAP'] Obviously, 'Gr??'!='Gr\xfc\xdf' . If I change the split to use u"," instead, I get the following: Traceback (most recent call last): File "", line 1, in ? File "work.py", line 165, in parseConfig goodProcRef = config.get(section,"goodprocref").split(u",") UnicodeDecodeError: 'ascii' codec can't decode byte 0xfc in position 13: ordinal not in range(128) Any ideas on how I can get the correct value? -- Mike Hostetler thehaas at binary.net http://www.binary.net/thehaas From ark at acm.org Fri Mar 19 11:29:19 2004 From: ark at acm.org (Andrew Koenig) Date: Fri, 19 Mar 2004 16:29:19 GMT Subject: Result of ``a is b'' References: <38ec68a6.0403171642.7199763c@posting.google.com> <405A5EC9.6010503@yahoo.com.au> <2eu6c.25407$P45.19517@fe1.columbus.rr.com> Message-ID: "Carl Banks" wrote in message news:2eu6c.25407$P45.19517 at fe1.columbus.rr.com... > > 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. > You know, it's not hard to imagine some abstract mathematical superset > of the normal orthogonal math we use everyday, wherein certain numbers > (or sets or whatever) are not equal to themselves. In which case it > would be entirely appropriate for __eq__ to return False if called > with the same object. Of course, that's not really the typical case. I'm pretty sure that IEEE floating point requires NaN to be defined in such a way that if x is NaN, then x == x must yield False. From mogmios at mlug.missouri.edu Sat Mar 27 21:17:15 2004 From: mogmios at mlug.missouri.edu (Michael) Date: Sat, 27 Mar 2004 18:17:15 -0800 Subject: Prothon Prototypes vs Python Classes In-Reply-To: <106cc1f2rsnaoe2@news.supernews.com> References: <569c605ld1cj8fc1emolk08ete0s1prls1@4ax.com> <106cc1f2rsnaoe2@news.supernews.com> Message-ID: <406635AB.9050803@mlug.missouri.edu> I'm not terribly familiar with the concept of prototypes although I believe I understand the basic meaning and I have worked in languages which do use prototypes (although not called that). Aren't there many times when it is usefult to work with classes where you do not want an instance to exist? Such as multiple level of subclasses where code is kept easily readable by putting it on a the appropiate class for that function alone. Often useful when you'll be using many similar but not identical objects? I can see how it'd be useful to be able to define new methods on an object, or edit the methods on an object but I can not see the purpose to removing classes altogether. Am I correct in my impression that with prototyping you must instantate an object to define it's structure? That would seem wasteful and cluttering of the namespace. Also he way your prototypes read appear less clear to me than a class definition. I fear that you'd wind up with people creating an object.. coding random stuff.. adding a method to that object.. coding more random stuff.. and then adding more to the object. From kraus at hagen-partner.de Tue Mar 16 07:50:12 2004 From: kraus at hagen-partner.de (Wolfram Kraus) Date: Tue, 16 Mar 2004 13:50:12 +0100 Subject: newbie question: nop statement for try/except In-Reply-To: References: Message-ID: <4056F804.8060700@hagen-partner.de> 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 > thanks, leo HTH, Wolfram From dmq at gain.com Mon Mar 15 12:15:33 2004 From: dmq at gain.com (David MacQuigg) Date: Mon, 15 Mar 2004 10:15:33 -0700 Subject: Deprecating reload() ??? References: <6kk6501shlve52ds2rjdopa73jhpchprg3@4ax.com> Message-ID: On Mon, 15 Mar 2004 05:49:58 -0600, Skip Montanaro wrote: > 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 Implementation detail. ( half wink ) >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. If you reload a module M1, and it has an attribute M1.x, which was changed from '1' to '2', we want to change also any references that may have been created with statements like 'x = M1.x', or 'from M1 import *' If we don't do this, reload() will continue to baffle and frustrate new users. Typically, they think they have just one variable 'x' It's interesting to see how Ruby handles this problem. http://userlinux.com/cgi-bin/wiki.pl?RubyPython I'm no expert on Ruby, but it is my understanding that there *are* no types which are implicitly immutable (no need for tuples vs lists, etc.). If you *want* to make an object (any object) immutable, you do that explicitly with a freeze() function. I'm having trouble understanding the benefit of using shared objects for simple numbers and strings. Maybe you can save a significant amount of memory by having all the *system* modules share a common 'None' object, but when a user explicitly says 'M1.x = None', surely we can afford a few bytes to provide a special None for that reference. The benefit is that when you change None to 'something' by editing and reloading M1, all references that were created via a reference to M1.x will change automatically. We should at least have a special 'debug' mode in which the hidden sharing of objects is disabled for selected modules. You can always explicitly share an object by simply referencing it, rather than typing in a fresh copy. x = "Here is a long string I want to share." y = x z = "Here is a long string I want to share." In any mode, x and y will be the same object. In debug mode, we allocate a little extra memory to make z a separate object from x, as the user apparently intended. If we do the updates for just certain types of objects, we will have a non-intuitive set of rules that will be difficult for users to understand. I would like to make things really simple and say: """ If you have a direct reference to an object in a reloaded module, that reference will be updated. If the reference is created by some other process (e.g. copying a string, or instantiation of a new object based on a class in the reloaded module) then that reference will not be updated. Only references to objects from the old module are updated. The old objects are then garbage collected. """ We may have to pay a price in implementation cost and a little extra storage to make things simple for the user. -- Dave From jjl at pobox.com Mon Mar 29 12:22:22 2004 From: jjl at pobox.com (John J. Lee) Date: 29 Mar 2004 18:22:22 +0100 Subject: Britney Spears nude References: Message-ID: "celebsrus" writes: > Britney Spears nude Britney Spears nude Britney Spears nude Britney Spears nude > Britney Spears nude Britney Spears nude Britney Spears nude Britney Spears nude [...] I see Britney has branched out from Semiconductor Physics into Python tutoring... John From donn at drizzle.com Sun Mar 7 23:42:42 2004 From: donn at drizzle.com (Donn Cave) Date: Mon, 08 Mar 2004 04:42:42 -0000 Subject: Need better string methods References: <0d4k40987t6d70bahqil3geth640bufgoc@4ax.com> Message-ID: <1078720961.66546@yasure> Quoth David MacQuigg : ... | # Current best Python: | clean = [' '.join(t.split()).strip('.') for t in line.split('|')] | | This is too much to expect of a non-programmer, even one who | undestands the methods. The usability problems are 1) the three | variations in syntax ( methods, a list comprehension, and what *looks | like* a join function prefixed by some odd punctuation), and 2) The | order in which each step is entered at the keyboard. ( I can show | this in step-by-step detail if anyone doesn't understand what I mean.) | 3) Proper placement of parens can be confusing. I quite agree, except of course like most other followups I don't necessarily agree that this is current best Python. Skip's probably right that a procedural style is best for casual Python users, and maybe for anyone. It really clears up order of evaluation, for one thing. Just for variety, here's how I imagine a Haskell user would write it (omitting the definition of strip, join and split): clean line = map ((strip '.') . (join ' ') . (split ' ')) (split '|' line) Still sacrifices readability for the sake of doing it all in one expression, and is overly abstract as usual, but at least the syntax is relatively simple. It avoids the right/left association switching that you got with your "best" version above - queer thing about classic OOP languages like Python, that functions associate left with their primary object, but right with the rest of their parameters, and in expressions like that it makes me feel a little sea-sick. Possibly unfamiliar notations above are pretty simple - Function composition: (f . g . h) a = (f (g (h a))) Partial application: (split ' ') b = split ' ' b (which makes for a different natural parameter order than Python's) Donn Cave, donn at drizzle.com From jmeile at hotmail.com Thu Mar 11 04:48:35 2004 From: jmeile at hotmail.com (Josef Meile) Date: Thu, 11 Mar 2004 10:48:35 +0100 Subject: Python style guidelines In-Reply-To: References: <3064b51d.0403101112.3449e987@posting.google.com> Message-ID: <405035a3$1@pfaff2.ethz.ch> > Is there something missing you think should be there? There's no particular > reason a PEP needs to be continually updated. In particular, notions of > good Python style haven't changed a lot over the past ten years. > > Skip I agree, those are good guidelines, but I don't agree with: - Don't compare boolean values to True or False using == (bool types are new in Python 2.3): No: if greeting == True: Yes: if greeting: What would happened if you do: >>> a='test' >>> if a.find('foo'): ... print "foo was found" ... foo was found I think you should never do a direct boolean comparison. Instead one should use a more elaborate boolean expresion like: >>> a='test' >>> if a.find('foo') >= 0: ... print "foo was found" ... You will have problems specially if you come from languages where values minor than zero are considered to be false. I think the previous sintax is ambiguous. Regards, Josef From OlafMeding at compuserve.com Tue Mar 30 15:39:40 2004 From: OlafMeding at compuserve.com (Olaf Meding) Date: 30 Mar 2004 12:39:40 -0800 Subject: PyChecker and stdin Message-ID: <9e5ea2c4.0403301239.28fb55fb@posting.google.com> Is there a way to tell PyChecker to "skip" a line of source code? Or any other workarounds would also greatly appreciated. This line: s = sys.stdin.read(4) Causes this PyChecker error: IOError: [Errno 9] Bad file descriptor Thanks much for your help. Olaf From newsgroups at jhrothjr.com Fri Mar 12 07:09:19 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Fri, 12 Mar 2004 07:09:19 -0500 Subject: Static Typing in Python References: Message-ID: <1053a5hrsag1nc2@news.supernews.com> "Premshree Pillai" wrote in message news:mailman.307.1079086151.19534.python-list at python.org... > How do I force static typing in Python? By using another language. Try Java. John Roth > > -Premshree Pillai > > ===== > -Premshree From steve at waypath.com Mon Mar 29 17:53:31 2004 From: steve at waypath.com (Steve @ Waypath) Date: Mon, 29 Mar 2004 14:53:31 -0800 Subject: process wrapper? References: <5ficndxjntWG4frd38DK-w@speakeasy.net> <1080539401.173853@yasure> <2pWdnQuWrvGhE_Xd38DK-g@speakeasy.net> Message-ID: <5q6dndSDho6ZNPXd38DK-w@speakeasy.net> "Donn Cave" wrote in message news:donn-959027.13550629032004 at nntp6.u.washington.edu... > 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. I think I found the problem here. I was editing in Windows, saving to a mounted Linux drive, running in Linux. It looks like some end-of-line chars I didn't account for. I'm still having defunct trouble, but I'm going to split this one off into a separate thread, going back a few steps. > 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. So, if I'm following this correctly, if I use os.P_NOWAIT, I shouldn't have to apply waitpid(), no? And, then, I shouldn't have a zombie process if I use P_NOWAIT, either. Am I getting this? > > Donn Cave, donn at drizzle.com From mark at prothon.org Mon Mar 29 17:48:52 2004 From: mark at prothon.org (Mark Hahn) Date: Mon, 29 Mar 2004 14:48:52 -0800 Subject: A 'Python like' language References: <40645d8f$0$10775$afc38c87@news.easynet.co.uk> <1068up4kn49778@news.supernews.com> <4064C129.1B8C937C@alcyone.com> Message-ID: <5J1ac.64492$cx5.5801@fed1read04> > So does "foo.bar = 5" add a "bar" slot to "foo" or does it change bar in the parent object? It took me great trouble to learn to use attribute instead of slot to keep Prothon in sync with Python. I even had to globally replace "slot" with "attr" in all my code a week ago, so I'll be replacing your use of slot with attribute. "foo.bar = 5" will always add an attribute bar to foo. You have to say "parent.bar = 5", or if foo is the current self object, you would say "^bar = 5". The caret(^) prefix reads as "super" and replaces the period prefix when you want atrribute lookup to start at the parent of self instead of at self. This was documented yesterday on the website. I realize that there is not currently any automatic way to change a value found by inheritance. I'm open to suggestions. None of the Prothon features will be cast in stone until 7/04 so make your suggestions known at Prothon mailing lists. "Glenn Andreas" wrote in message news:gandreas-29DDCC.09162829032004 at news.mpls.visi.com... > In article , > "Mark Hahn" wrote: > > > > Not quite the same, as with Prothon it looks like it always relates to > > > the self object, whereas in a `with' clause you can make it relates to > > > any object you wish. > > > > Just to confuse the issue, I'd like to point out that in Prothon, the > > leading dot does always relate to the self object, but the 'with' clause > > sets the self object to any object you want at any time. So both statements > > above are true at once. The concept of changing the self object on the fly > > is somewhat bizzare, much like changing the protoype on the fly, which you > > can also do. > > > Out of curiousity (and on a somewhat related topic), how do you handle > "class variables" - i.e., variables that exist in the "super" object, > and should be accessable by all "sub objects"? > > Accessing them is straightforward - for "foo.bar" if foo doesn't have > bar, but it inherits from an object that does have bar, you get that, > but what about foo.bar on the LHS of an expression? So does "foo.bar = > 5" add a "bar" slot to "foo" or does it change bar in the parent object? > > Self had a full blown system for variable access & setting, combined > with its multiple inheritance for some pretty interesting abilities > (essentially, all "getters" and "setters" were functions, so you could > have something be a constant by only providing a getter, etc...) > > NewtonScript actually had two different assignment operators "=" and > ":=" which determined how it behaved (though it got complex because it > sort of had multiple inheritance - everything inherited from _two_ > parents, the "real" parent and a "_proto", which seems strange, but it > made sense in the runtime of the Newton, but that's a bit off topic). From news at woody.datatailors.com Tue Mar 9 06:34:46 2004 From: news at woody.datatailors.com (Peter van Kampen) Date: Tue, 9 Mar 2004 12:34:46 +0100 Subject: Sending bulk email from a Python script References: <104q5jpg86q2udf@corp.supernews.com> <2004030819064420092%cs1spw@bathacuk> Message-ID: In article <2004030819064420092%cs1spw at bathacuk>, Simon Willison wrote: > experience other people may have with this kind of task. At the moment I'm > looking at using smtplib and just cycling through calling smtp.send() once > for every address but I'm not confident that that this is a particularly > efficient method. If there's a better option I'd love to hear about it. You can try to use BCC's. We send a message to several (I think we settled for 25) people at once. We only mail a few hundred people at the time (using php, which uses sendmail) but it's very fast (the mailing is invoked from a webpage and there seems to be no more than the usual delay which was 'good enough' to not bother to measure 'real' speed) and seems to work flawlessly. The drawback is that you cannot test which addresses failed (other than checking /var/log/mail). PterK -- Peter van Kampen pterk -- at -- datatailors.com From csgcsg39 at hotmail.com Wed Mar 10 12:36:32 2004 From: csgcsg39 at hotmail.com (C GIllespie) Date: Wed, 10 Mar 2004 17:36:32 -0000 Subject: Reading from stdin References: Message-ID: > probably both your C- and your python scripts use buffered output. So > the C-program will not print line-by-line but rather en-block after > many bytes of output have accumulated. > > In your C-program, do this (that's most likely your problem): > > printf("%f\n",x); /* print valuable data */ > fflush(stdout); /* make sure it's written to stdout */ Yep, that was the problem. Thanks Colin From vipul_parmar_us at yahoo.com Thu Mar 4 02:04:43 2004 From: vipul_parmar_us at yahoo.com (=?iso-8859-1?q?vipul=20parmar?=) Date: Thu, 4 Mar 2004 07:04:43 +0000 (GMT) Subject: can anybody tell me how to compile the C code with embedded python. Message-ID: <20040304070443.99472.qmail@web40702.mail.yahoo.com> hi, i m trying to compile a program called abc.c having python API used. now i want to compile the c code and run as a binary. i won't be able to create binary in linux 7.3. i m having python2.2. plz some one tell me how to link the python code with c. i have to install anything else other than python development package or what? waiting for reply, vipul parmar ________________________________________________________________________ Yahoo! Messenger - Communicate instantly..."Ping" your friends today! Download Messenger Now http://uk.messenger.yahoo.com/download/index.html From premshree_python at yahoo.co.in Thu Mar 18 19:31:51 2004 From: premshree_python at yahoo.co.in (=?iso-8859-1?q?Premshree=20Pillai?=) Date: Fri, 19 Mar 2004 00:31:51 +0000 (GMT) Subject: Static Typing in Python In-Reply-To: <40596d5b$0$10731$afc38c87@news.easynet.co.uk> Message-ID: <20040319003151.33399.qmail@web8310.mail.in.yahoo.com> --- Peter Hickman wrote: > Jacek Generowicz wrote: > > Peter Hickman writes: > > > > > >>So just how is Python strongly typed 'like in C, > C++, etc'? > > > > > > It isn't. It's _more_ strongly typed that C and > C++ :-) > > > > If you are really interested in the answer, I've > already explained it > > to you elsewhere in this thread, and you can > Google for it. > > > > Happy trolling. > > What I want is Premshree's answer. Because, unless > you can read his > mind, you do not know what he meant when he said > that. Your > interpretation of what he said is only that. > > Come on Premshree, how is Python strongly typed like > in C, C++ etc? Mistake! Mistake! I confused a lot of stuff. Sorry. Python is strong typed. C is _weak typed_ Sorry about the confusion. -Premshree Pillai > > Examples, not handwaving. > -- > http://mail.python.org/mailman/listinfo/python-list ===== -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 18:11:37 2004 From: mogmios at mlug.missouri.edu (Michael) Date: Mon, 29 Mar 2004 15:11:37 -0800 Subject: tabbing probs In-Reply-To: <106glq882vcn659@news.supernews.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> <106gg1jifa2n9c2@news.supernews.com> <406848CD.5070100@mlug.missouri.edu> <106glq882vcn659@news.supernews.com> Message-ID: <4068AD29.6020907@mlug.missouri.edu> >You're contradicting yourself. In a prior post, you said that if you >had a crappy editor, then change it. Now you're saying that you >think you would have to press the space bar or the backspace key >multiple times, and you're not going to give up that crappy editor >for one that works properly. > An editor is crappy if it inserts anything other than what you type into the code. If I press tab and four spaces are inserted that is crap. If I press 'A' and 'a' is inserted that is crap. To me, it sounds as if this entire issue is caused by crappy editors that think they know better than the programmers. If you want a smart alec paper clip telling you what to do when you're editing code then feel free to do so but I just want raw access to my code. From ptmcg at austin.stopthespam_rr.com Wed Mar 10 22:17:29 2004 From: ptmcg at austin.stopthespam_rr.com (Paul McGuire) Date: Thu, 11 Mar 2004 03:17:29 GMT Subject: Extending Python Syntax with @ References: Message-ID: "David MacQuigg" wrote in message news:s2vu409dio5vc9ndl81dcinteagrkpntf5 at 4ax.com... > 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: > > print @(separator = None) x, y, z > > @x,y:x*x+y*y -- anonymous function > > @f(x,y) -- generator function that can accept new arguments > with each call > > @x @y @z -- short for instance variables in a method definition > > Each of these examples is debatable, but my point is that there are > many enhancement requests like this, and some may be worthy of > inclusion in the core language. It would be nice if there was a > consistent way to add stuff like this. It certainly beats adding ugly > statements like 'lambda'. > > It might even be possible to allow limited extension of the language > by users, provided the extensions are introduced by the special > symbol. This would allow the flexibility of Ruby or Lisp without the > cost of forking the language into many dialects. > > Maybe we should collect a bunch of little enhancements like the above, > and put them all into one PEP. Any suggestions? Pet peeves? Stuff > you would like to see, but not worthy of a PEP by itself? > > -- Dave > Pet peeve: gratuitous inclusion of magic symbols into an otherwise easy-to-understand language syntax. -- Paul From scav at blueyonder.co.uk Thu Mar 11 17:28:18 2004 From: scav at blueyonder.co.uk (Peter Harris) Date: Thu, 11 Mar 2004 22:28:18 +0000 Subject: How to convert string to list without eval or exec In-Reply-To: References: <1078921034.4651.0@nnrp-t71-02.news.uk.clara.net> Message-ID: <3F54c.237$2s5.183@news-binary.blueyonder.co.uk> Peter Otten wrote: > DomF wrote: > > >>>>I'm not allowed to use eval or exec. >>> >>>- write to a file >>>- load the file as module :-) >> >>This made me laugh out loud after reading all the heavy duty parsing >>options, is that bad? > > > It's just like eval and exec in that it allows to execute untrusted code. > > Peter Would it be safe to use eval but within a namespace with no globals or locals? Then the expression could only include literals. Actually, builtins would be visible too. And you don't want to eval "[ file('important_file','w') ]" ! But I think there's a way to hide builtins as well, although I forget what it is. Peter Harris From rogerb at rogerbinns.com Mon Mar 1 15:10:24 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Mon, 1 Mar 2004 12:10:24 -0800 Subject: Licensing of wrappers around C/C++ code under more restrictive licensing. References: <7ed8f64d.0402280218.5ff447cf@posting.google.com> <9tt9h1-h1d.ln1@home.rogerbinns.com> Message-ID: <7uhch1-gev.ln1@home.rogerbinns.com> > I am surprised you even went as far as looking at the license for OSE as > in looking at "bitpim", not sure that what OSE had to offer in the way > of functionality would even have made it appropriate for what you were > doing. I am putting in an XML-RPC over SSL interface to allow the BitPim software and the cell phone to be on different machines. OSE was attractive because of the SOAP support as well. (I think it would have later been ruled out due to lack of SSL anyway). Note section 7 of the Artistic License: 7. C or perl subroutines supplied by you and linked into this Package shall not be considered part of this Package. > I would like to make a bit of money from the 14 years of work that I > have put into all of this. :-) Very understandable :-) If only monetizing open source software was easy! Roger From aahz at pythoncraft.com Mon Mar 1 12:07:32 2004 From: aahz at pythoncraft.com (Aahz) Date: 1 Mar 2004 12:07:32 -0500 Subject: Garbage collector and threads References: <1EJ0c.4334$mx4.105438@nnrp1.uunet.ca> Message-ID: In article <1EJ0c.4334$mx4.105438 at nnrp1.uunet.ca>, Nicolas Fleury wrote: >Aahz wrote: >> >> Yes, Don't Do That. Do not rely on finalizers for external resources >> (such as threads). > >Why? Isn't a kind of RAII applied to Python? What's "RAII"? >> Note that your understanding of Python's memory management could use some >> improvement: GC *never* runs on objects containing __del__ > >Well, I guess you're right. What I mean is the reasons behind the call >to __del__, whatever it is ref-counting or something else. Wouldn't a >class like CancellableThread, with a sub-class implemented cancel method >called when the object is not referred in any other thread be useful? Perhaps, but threading needs references to created threads in order to implement its functionality. You might try building your own thread constructs using ``thread`` directly. -- 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 P at draigBrady.com Tue Mar 30 04:26:03 2004 From: P at draigBrady.com (P at draigBrady.com) Date: Tue, 30 Mar 2004 10:26:03 +0100 Subject: GUI Frameworks in Python? In-Reply-To: References: Message-ID: <40693D2B.2050603@draigBrady.com> Hugh Macdonald wrote: > I've recently been trying out various different GUI frameworks in Python and > was wondering if I could get your input on the pros and cons of the > different ones... > > wxPython: I love the programming side of wxPython, but I find it's just so > slow to initialise in the first place. > > Tkinter: While it's fast to load up, the syntax has never really appealed to > me > > GTK: Unknown - I'm looking into it today I have to recommend GTK, especially in combination with libglade. I've a presentation and a couple of sample apps here: http://www.pixelbeat.org/talks/pygtk P?draig. From rawbobb at hotmail.com Tue Mar 16 21:22:31 2004 From: rawbobb at hotmail.com (bobb) Date: Wed, 17 Mar 2004 02:22:31 GMT Subject: INTRANET zope References: Message-ID: start with CMF and maybe plone. www.zope.org "Andrzej Mleczko" wrote in message news:c35h6l$n77$1 at topaz.icpnet.pl... > Hmmm... not all. Look at www.zope.com > I'm searching for something like http://www.zope.com/Products/Zope4Intranets > but open source. > > U?ytkownik "Mikl?s" napisa? w wiadomo?ci > news:c34ul1$qid$1 at namru.matavnet.hu... > > > > "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 newsgroups at jhrothjr.com Sun Mar 14 19:41:31 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Sun, 14 Mar 2004 19:41:31 -0500 Subject: Question about the email package References: <3T65c.3667$GQ3.1622@newsread3.news.atl.earthlink.net> Message-ID: <1059v14ofa2tmed@news.supernews.com> "Adonis" wrote in message news:3T65c.3667$GQ3.1622 at newsread3.news.atl.earthlink.net... > Is there a way to retrieve the message body using the email package? or is > the email package just for parsing mime formatted messages? or would I have > to parse the information retrieved from poplib myself. I have scanned the > entire documentation to no avail. googling only gained little. > > Any help is greatly appreciated. The final example in the documentation works quite well for taking an e-mail saved as a file and breaking it into pieces. John Roth > > Adonis > > From selwyn at aotearoa_is_home.nz Tue Mar 16 00:46:25 2004 From: selwyn at aotearoa_is_home.nz (selwyn) Date: Tue, 16 Mar 2004 18:46:25 +1300 Subject: new to programming: suggestion In-Reply-To: <3d5e65ea.0403152115.3df7e8c1@posting.google.com> References: <3d5e65ea.0403152115.3df7e8c1@posting.google.com> Message-ID: lutz and ascher's learning python is excellent. pius wrote: > i'm new in programming; i'd like to find a good programming book, full > of examples guiding me step to step in the marvellous world of > programming. > Is there anybody who can suggest me where to find what i'm searching? > Thanks a lot. > pus From claird at lairds.com Thu Mar 11 00:13:25 2004 From: claird at lairds.com (Cameron Laird) Date: Thu, 11 Mar 2004 05:13:25 -0000 Subject: Extending Python Syntax with @ References: <104vg6f87k7gb19@corp.supernews.com> Message-ID: <104vtblamboehab@corp.supernews.com> In article , Pierre Rouleau wrote: >David MacQuigg wrote: >> On Thu, 11 Mar 2004 01:28:47 -0000, claird at lairds.com (Cameron Laird) >> wrote: >> >> > > > >> >> I guess this reflects our different backgrounds. I've been an >> electronic design engineer for many years. I never heard of lambda's >> or lambda calculus until learning Python, and the name still doesn't >> evoke much meaning for me. I've never used APL, J, or Perl. I wonder >> how many technical professionals who are *not* programmers would know >> what a lambda is? I wonder if Python is becoming more a language for . . . >I was trained as an EE myself and started programming in assembler on >microprocessors, then in C , then in C++, reading, reading, reading,.... > >Just the mere fact that you are talking about lambda shows that you know >what it is, as I do now and as people learning Python will know when >they use it. They'll learn, that why they are technical professionals, no? . . . For more on what lambda means to me, and others, see or or or ... -- Cameron Laird Business: http://www.Phaseit.net From ianb at colorstudy.com Sun Mar 14 14:51:10 2004 From: ianb at colorstudy.com (Ian Bicking) Date: 14 Mar 2004 11:51:10 -0800 Subject: import, functions, and threading References: Message-ID: <359f85cd.0403141151.1546b5d0@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. Just saw this on the week Python URL... anyway, an alternative that should be safer: somemodule = None def whatever(): global somemodule if somemodule is None: import somemodule I'm still not sure if it's entirely safe in all cases, but I think it is...? Anyway, it allows for lazy loading. From steve at ninereeds.fsnet.co.uk Wed Mar 24 04:18:26 2004 From: steve at ninereeds.fsnet.co.uk (Stephen Horne) Date: Wed, 24 Mar 2004 09:18:26 +0000 Subject: PEP 318 References: <99dce321.0403211817.3704fe2@posting.google.com> <7x1xnlqs77.fsf@ruckus.brouhaha.com> Message-ID: <9rj260dlq137kq3vr25bt3n813eqgoi40v@4ax.com> On Wed, 24 Mar 2004 18:15:42 +1200, "Greg Ewing (using news.cis.dfn.de)" wrote: >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. I just assumed the intention was that the word 'generator' would be special-cased in the 'as' clause - you can do pretty much anything as long as you spot the need while it's still just syntax. Beyond that, it is probably possible by using the parser module. Just a bit of AST hackery really. Though having never actually used that module, I can't be sure. -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From mark at prothon.org Tue Mar 30 17:19:39 2004 From: mark at prothon.org (Mark Hahn) Date: Tue, 30 Mar 2004 14:19:39 -0800 Subject: [OT] Top posting is a PITA [was : Prothon Prototypes vs Python Classes] References: <569c605ld1cj8fc1emolk08ete0s1prls1@4ax.com> <106di86neu1qh4d@news.supernews.com> <4069a001$0$4237$afc38c87@news.easynet.co.uk> <4069e9d9$0$8915$636a15ce@news.free.fr> Message-ID: <0omac.74900$cx5.32735@fed1read04> > make your posts more readable Sorry. I really really try to remember to quote from below. If you go through my posts you will see that I remember most of the time. The last few days I have been reponding to four or five mailing lists after months of only coding and my fingers are worn out. "Bruno Desthuilliers" wrote in message news:4069e9d9$0$8915$636a15ce at news.free.fr... > Peter Hickman wrote: > > Gerrit wrote: > > > >> only one. I think it is the wrong answer to say that people shouldn't > >> bitch about top-posting - it _does_ annoy people (including me and Aahz). > > > > > > Will you please reign in you ego and qualify your statement 'it annoys > > *SOME* people'. > > Well, it seems that it annoys *most* people here. BTW, I was about to do > the same... (Mark, if you read us : your work seems pretty interesting, > so do *yourself* a favor and make your posts more readable !-). > > > I find all the bitching about top posting to be a > > greater distraction than top posting itself! > > So please stop bitching about people bitching about top-posting. > > >> There are conventions on usenet (and mailing lists), and they are there > >> with reason. I would like to kindly ask you to try to do more > >> 'bottom-posting'. It makes your postings easier and prettier to read. > > > > I find bottom posting to be a real pain as when I look at a new message > > it defaults to showing me the top of the message and I then have to > > scroll through pages of quoted posts that I have already read just to > > read one or two lines stuck at the bottom. > > If you have to do so, then the poster didn't get point : only quote > what's needed. > > (snip) > > > > > I have never left a group because of the trolls. > > I have never left a group because of the noobies. > > I have left a group because of the constant whining about top posting. > > May I suggest you to count how many messages Mark posted here before > someone kindly suggested that he could help everyone by doing a simple > thing ? If that's what you call 'constant whining', then you are the troll. > > > People who whine on about 'top posting' are the sort of people who draft > > 'clean desk' policies. If you want to whine about top posting then start > > alt.whine.top.posting and have fun. > > Apr?s vous, mon cher. > > Bruno > From ray_molachaNOSPAM at gmx.co.uk Wed Mar 24 16:03:44 2004 From: ray_molachaNOSPAM at gmx.co.uk (Ray Molacha) Date: Wed, 24 Mar 2004 21:03:44 GMT Subject: Simple raster graphics ? How do I ... References: Message-ID: Excellent. Thanks a lot Chris. I'm looking at it right now, and it looks great. Just what I was looking for, and a lot more. From antonyliu2002 at yahoo.com Sat Mar 13 03:35:45 2004 From: antonyliu2002 at yahoo.com (Anthony Liu) Date: Sat, 13 Mar 2004 00:35:45 -0800 (PST) Subject: Unicode is driving me nuts! In-Reply-To: <16466.22306.480990.299621@montanaro.dyndns.org> Message-ID: <20040313083545.50340.qmail@web13007.mail.yahoo.com> Thank you, Skip. You know what, I guess I'll give up using unicode, as you also mentioned you used to have headache with it. I'll probably just read by bytes and check if the byte is a Chinese character. If it is, read 2 bytes instead. What do you think? This way, I will hopefully not to have a lot of unreadable characters. --- Skip Montanaro wrote: > > Anthony> str = unicode(raw_str, myencoding) > > Anthony> This works just fine with a small > sample Chinese document. > > Anthony> But when I attempted to run the script > on the entire corpus, I > Anthony> get the typical "incomplete multibyte > sequence error" or > Anthony> "UnicodeEncodeError: 'ascii' codec > can't encode characters in > Anthony> position 0-23: ordinal not in > range(128)" > > Can you craft a small example which demonstrates the > error but which you > think is correctly encoded? > > Anthony> I am at my wit's end, so frustrated at > handling > Anthony> non-ascii texts. > > Unicode creates lots of problems for the > uninitiated. I pulled my hair out > for a long time. It took me a couple tries to get > my system to work > (more-or-less) with Unicode. It's still got the > occasional problem. > > Skip > __________________________________ Do you Yahoo!? Yahoo! Mail - More reliable, more storage, less spam http://mail.yahoo.com From piet at cs.uu.nl Sat Mar 13 09:46:43 2004 From: piet at cs.uu.nl (Piet van Oostrum) Date: 13 Mar 2004 15:46:43 +0100 Subject: root password in a .py script References: Message-ID: >>>>> Bart Nessux (BN) wrote: BN> Dave Brueck wrote: >> What is it that this script is doing? How is it getting invoked? And if it's >> being invoked by a non-root user, why should that user be allowed to do >> something that requires root privileges? Is there any reason why you simply >> don't run the script as root? BN> The script is setting the root password. It is running as root, by root as BN> a daily cron job. It does three things: BN> 1. Set root password to XXXXXXXXX BN> 2. Make certain ssh is enabled on the machine, if not enable it. BN> 3. Email the machine's IP to the admins BN> Root is the owner of the script... it's perms are 700 BN> Why am I doing this? Because users turn off ssh and change the root BN> password. Mac OSX allows "administrative" users to do this. This script BN> undoes their changes. Why don't you run a server process on a central server machine where you only have to type in the password when that machine boots. And then run cron jobs at all the client machines that get the password from the server. Use ssl connections with client certificates for security. -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP] Private email: P.van.Oostrum at hccnet.nl From steve at waypath.com Mon Mar 29 14:17:51 2004 From: steve at waypath.com (Steve @ Waypath) Date: Mon, 29 Mar 2004 11:17:51 -0800 Subject: process wrapper? References: <5ficndxjntWG4frd38DK-w@speakeasy.net> <1080539401.173853@yasure> Message-ID: Donn, Thanks for the reply. I haven't yet implemented a working spawnv call, so I'm not confident my tests are valid. Here's a sample: ########## File: test1.py ------------ import os, time if __name__=='__main__': os.spawnv(os.P_NOWAIT,'python',['test2.py']) for step in range(10): print 'test1 checking in' time.sleep(1) ########## File: test2.py ------------ import time if __name__=='__main__': for step in range(10): print 'test2 checking in' time.sleep(1) ########## stdout: # python test.py test1 checking in ... test1 checking in [ 10 iterations of 'test1 checkin in'; none of 'test2 checking in'] ########### While test 1 is running, a ps (in another shell): # ps x | grep python 11726 pts/1 S 0:00 python test1.py 11727 pts/1 Z 0:00 [python ] 11729 pts/2 S 0:00 grep python ########### I see this defunct thing with every spawnv test I try. The defunct process goes away when the calling process (test1.py, in this case) finishes. Where am I going wrong here? Thanks Steve @ Waypath.com "Donn Cave" wrote in message news:1080539401.173853 at yasure... > Quoth "Steve @ Waypath" : > ... > | I've tried every implementation of os.system, os.popen*, os.spawn* , and > | (os.fork + os.exec*) for which I can find an example or that I can imagine, > | but I can't come up with anything that works for me. os.spawnv() looked > | very promising, but every process I start with it goes defunct. > > Well, you need to fix that, no? spawnv works for people, and very > likely it's the perfect thing for your application. So start with > a simple Python program that uses spawnv on some ordinary utility, > like "date" for example, and if you can't get it to work you will > have a more specific question to pose. > > Donn Cave, donn at drizzle.com From mwilson at the-wire.com Sat Mar 20 17:55:17 2004 From: mwilson at the-wire.com (Mel Wilson) Date: Sat, 20 Mar 2004 17:55:17 -0500 Subject: Reload() Confusion References: Message-ID: In article , David MacQuigg wrote: >I'm going to be teaching EEs some basic Python using the first few >chapters of Learning Python, 2nd ed. by Mark Lutz. The discussion on >Reloading Modules starting on page 266 is confusing and I believe >incorrect. On page 266 it says that a reload "changes the existing >module object in place." That's a little vague, but on page 267 it >says "every reference to a module object anywhere in your program is >automatically affected by a reload." > >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. It seems to me that the module keeps its identity over the reload: Python 2.3 (#46, Jul 29 2003, 18:54:32) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import re >>> id(re) 9940176 >>> reload(re) >>> id(re) 9940176 >>> > >I've re-written the section on Reload Basics, and I would like to get >some comments, both on correctness and clarity. > >http://ece.arizona.edu/~edatools/Python/Reload.htm > >Your help will be appreciated, both by me and by the students >struggling through this the first time. > I agree with you. It seems that the module code is re-executed in the previously-existing modules namespace. Wherever that code created new objects the first time, it will create brand-new objects the second time. Small integers and interned strings will keep their identities (of course), as will objects referenced through other modules. Nothing is explicitely deleted, so bindings can be left over from the modules prior incarnation. No other namespaces will be affected except when code in the module explicitely calls for it. For what it's worth, the following code: #======================= """M1 version 1""" a=1 b=2 c=[1] d=[2] #======================= """M1 version 2""" a=1 b=4 c=[3] e=[4] #======================= """test_reload.py""" import os, shutil def module_contents (M): print "Doc: ", M.__doc__ for k, v in M.__dict__.items(): if not k.startswith ("__"): print "%s:\t%d\t%s" % (k, id(v), v) def grab_contents (M): d = {} for k, v in M.__dict__.items(): if not k.startswith ("__"): d[k] = v return d #os.remove ("M1.pyc") shutil.copyfile ("M1_1.py", "M1.py") import M1 module_contents (M1) mc = grab_contents (M1) print os.remove ("M1.pyc") shutil.copyfile ("M1_2.py", "M1.py") reload (M1) module_contents (M1) print '\nMC:' for k, v in mc.items(): print "%s:\t%d\t%s" % (k, id(v), v) Which gives F:\home\mwilson\Projects\python\testscript>python test_reload.py Doc: M1 version 1 a: 8463376 1 c: 9940432 [1] b: 8470496 2 d: 9940368 [2] Doc: M1 version 2 a: 8463376 1 c: 9940272 [3] b: 8468480 4 e: 9937584 [4] d: 9940368 [2] MC: a: 8463376 1 c: 9940432 [1] b: 8470496 2 d: 9940368 [2] The second os.remove seems to be required in case the reloaded version of M1.py is older than the imported one. Regards. Mel. From ajsiegel at optonline.com Wed Mar 17 16:01:23 2004 From: ajsiegel at optonline.com (Arthur) Date: 17 Mar 2004 13:01:23 -0800 Subject: asking for python community opinion about groovy References: <6b4509ac.0403170801.79aa64b7@posting.google.com> Message-ID: <213df9a1.0403171301.2ee03910@posting.google.com> menceur at hotmail.com (M.M.) wrote in message news:<6b4509ac.0403170801.79aa64b7 at posting.google.com>... > > IMO, it will be better to support the Jython project. Because Jython > exists, it's very useful and powerful. In fact, I think java community > want to have its own "scripting" language because java community is > not open-minded enough and will not accept to use something for the > outside. I doubt he would disagree with your fundamental point, but I did happen across this: http://www.python.org/~jeremy/weblog/040203.html Art From bouil at bouil.org.invalid Mon Mar 15 18:45:35 2004 From: bouil at bouil.org.invalid (Nicolas Bouillon) Date: Tue, 16 Mar 2004 00:45:35 +0100 Subject: Replace accented chars with unaccented ones Message-ID: Hi I would like to replace accentuel chars (like "?", "?" or "?") with non accetued ones ("?" -> "e", "?" -> "e", "?" -> "a"). I have tried string.replace method, but it seems dislike non ascii chars... Can you help me please ? Thanks. From fgeiger at datec.at Thu Mar 4 10:52:09 2004 From: fgeiger at datec.at (F. GEIGER) Date: Thu, 4 Mar 2004 16:52:09 +0100 Subject: How to catch a generic exception? References: Message-ID: try: generateSomeException() except Exception, e: print e HTH Franz "Boogie El Aceitoso" schrieb im Newsbeitrag news:dcie40t170sbhifs7mihfg9h1jm5prnbf0 at 4ax.com... > 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 stewart at midtoad.homelinux.org Fri Mar 5 22:33:14 2004 From: stewart at midtoad.homelinux.org (midtoad) Date: Sat, 06 Mar 2004 03:33:14 GMT Subject: Split a sentence by punctuations using Python References: <14b36d18.0403051444.21b3937e@posting.google.com> Message-ID: <_Db2c.716830$ts4.680605@pd7tw3no> chad wrote: > I want to split sentences by using punctuations, numeric numbers as > the delimiters. > > You know, string.split does not work for this objective. So how can i > achieve this? Thanks. check out kodos on sourceforge. It's a small GUI that allows you to interactively try out regexp expressions and see the results as you type. very handy! Stewart From opengeometry at yahoo.ca Sat Mar 6 22:00:14 2004 From: opengeometry at yahoo.ca (William Park) Date: 7 Mar 2004 03:00:14 GMT Subject: Can python read up to where a certain pattern is matched? References: Message-ID: Anthony Liu wrote: > I am kinda new to Python, but not new to programming. > I am a certified Java programmer. > > I don't want to read line after line, neither do I > want to read the whole file all at once. Thus none of > read(), readline(), readlines() is what I want. I want > to read a text file sentence by sentence. Question: How do I read sentence by sentence? Answer: Read input stream char by char. -- William Park, Open Geometry Consulting, Linux solution for data processing and document management. From mrchameleon at hotmail.com Thu Mar 25 21:07:45 2004 From: mrchameleon at hotmail.com (Chris Reay) Date: 25 Mar 2004 18:07:45 -0800 Subject: win gui thoughts? perhaps a non-Pythonic approach? References: Message-ID: <7652139e.0403251807.619375da@posting.google.com> > i need some advice. i'm a back end programmer historically, but have > been exploring python for webapps and enjoying it. > > i need to build some simple Win client-server or standalone apps. > > the result needs to look professional and attractive, and i need > something i can get working fairly quickly with a modest learning curve. > I contrast this with Delphi which is > any thoughts on this? I know this is clp, but I've had some experience of this dilemma. 1. Delphi is good if the project is very simple and mostly GUI & data, without much business logic. 2. Python is better if there's much data and logic, and (little or) no GUI. 3. Python is a pleasure to write. Delphi is not. C# is somewhere in between (particularly if you have some c/c++/Java experience). 4. My latest MS Win project requires all: GUI, data, C/S, logic. I'm using Visual C#.net and so far I believe it's a good choice. I'm a Python-phile who believes in using the right tool for the job. Hth. From Python at ivonet.nl Sun Mar 14 07:27:29 2004 From: Python at ivonet.nl (Ivo) Date: Sun, 14 Mar 2004 13:27:29 +0100 Subject: Embedded WebDesign with Python Message-ID: <002e01c409bf$b7caeef0$9600000a@pc001> Maybee you python junkies can help me. My Goal: A website where the content is fully shaped by python in my html. At this moment I use Apache 2 in combination with mod_python and Spyce No I understand that mod_python allows embedded python, but I don't understand how. Can someone give me a pointer or a good link to some good pointers (which would already be a good pointer ;-) Thanks, Ivo. From No.Spam.mc at No.Spam.mclaveau.No.Spam.com Thu Mar 25 16:11:55 2004 From: No.Spam.mc at No.Spam.mclaveau.No.Spam.com (Michel Claveau/Hamster) Date: Thu, 25 Mar 2004 22:11:55 +0100 Subject: How to import a module based on an argument References: Message-ID: Plus utilisable : More useful : def functionname( module, var1): exec('from '+module+' import *') print upper(var1) functionname('string', 'azerty') From phipps.xue at sap.com Tue Mar 30 21:00:49 2004 From: phipps.xue at sap.com (Phipps Xue) Date: Wed, 31 Mar 2004 10:00:49 +0800 Subject: GUI Frameworks in Python? References: Message-ID: I'm really sorry for my ignorance of pyGTK in Windows. I've installed pyGTK in my desktop by following Jon's reply message. I feel it's really so cool, after run a helloworld application. Phipps "Phipps Xue" wrote in message news:c4ba4d$i9g$1 at news1.wdf.sap-ag.de... > pyGTK is also a good GUI frameworks but it's not available now for windows > platform. I suppose it's its most important shortage. > > Phipps > "Hugh Macdonald" wrote in message > news:mailman.102.1080629227.20120.python-list at python.org... > > I've recently been trying out various different GUI frameworks in Python > and > > was wondering if I could get your input on the pros and cons of the > > different ones... > > > > wxPython: I love the programming side of wxPython, but I find it's just so > > slow to initialise in the first place. > > > > Tkinter: While it's fast to load up, the syntax has never really appealed > to > > me > > > > GTK: Unknown - I'm looking into it today > > > > Qt: I have yet to manage to install it on my system > > > > Anything else? > > > > > > Hugh Macdonald > > > > > > From mon-at-cox-net Wed Mar 31 20:38:49 2004 From: mon-at-cox-net (Nick Monyatovsky) Date: Wed, 31 Mar 2004 20:38:49 -0500 Subject: Python vs Perl (an example) References: Message-ID: >Hello, > >I recently wrote a Perl version of pyAlbum.py [1] -- a >Python script to create an image album from a given >directory -- plAlbum.pl [2]. > >It made me realize how easy-to-use Python is. > >[1] >http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/271246 >[2] >http://www.premshree.resource-locator.com/cgi-bin/source.pl?file=../perl/plAlbum.pl > >-Premshree Pillai > >===== >-Premshree >[http://www.qiksearch.com/] > I cannot help, but make a couple of observations: 1. Although you point about Python being easy has some merit, I would not bring up an awkwadly written Perl script to back up that argument. 2. There are many things which are very easy to do in Perl, and are very cumbersome in Python. Regular expressions is a vivid example. Saying very generically that Python is easier than Perl is just an invitation for flame wars. 3. Lastly, Perl is not aspiring to or has ever claimed to be easy. That is not its strength and attraction. (Although, on a simple example like this, a more conventional Perl script (see below) is pretty comparable). If you'd like to demonstrate that Python is easier than Perl, you'll need to find a better case. ----------------- pyAlbum.pl ------------------------- =head pyAlbum.pl Perl version of the pyAlbum.py script that creates an album of images from a given directory (c) 2004 Premshree Pillai (27/02/04) http://www.qiksearch.com/ =cut use Tk::Image; my @files; my $count = 0; my $total = 0; sub getDir { print "Enter the directory to read images from (rel/abs path): "; $dirName = ; chomp $dirName; -d $dirName or warn "Directory does not exist!" and getDir(); } sub retPrevFile { my $index = shift; return "" unless $index; return sprintf '« Previous', $files[$index - 1]; } sub retNextFile { my $index = shift; return "" if $index == $#files; return sprintf 'Next »', $files[$index + 1]; } sub retPipe { my $index = shift; return " | " if $index and $index < $#files; return ""; } sub getSlideName { print "Enter base name for album: "; $slideName = ; chomp $slideName; -d "$dirName/$slideName" and warn "Directory $slideName exists!" and getSlidename(); mkdir "$dirName/$slideName" or die; } my $format = q[ %s

%s

%s (%s/%s)

%s%s%s
]; getDir(); getSlideName(); print "Enter a title for the album: "; $title = ; chomp $title; print "Enter image scaling factor (e.g., 0.5, for default) "; $scale = || '1.0'; chomp $scale; chdir $dirName; @files = <*.*>; $total = scalar(@files); chdir $slideName; foreach $file (@files) { open FILE , ">$file.htm"; printf FILE $format, $title, $title, $file, $count + 1, $total, $file, $file, retPrevFile($count), retPipe($count), retNextFile($count); close FILE; $count++; warn "File $file.htm created.\n" } print "\n", "Album created!\n"; From cygnus at cprogrammer.org Wed Mar 10 13:12:22 2004 From: cygnus at cprogrammer.org (Jonathan Daugherty) Date: Wed, 10 Mar 2004 13:12:22 -0500 Subject: Graphics. Message-ID: <20040310181222.GA10997@mail.theserver.ath.cx> Hello all, I'm looking for a good 2d/3d graphics library with python bindings (or written in python). I've found a few packages so far, and I'd like to know what you guys think before I settle on one of them; I'm having a hard time deciding which one to use. - VPython: a 3d python package with high-level primitive support and good user interface input processing, but no alpha channel API from what I can tell (I need alpha processing capabilities) - pygame: all-around high-level graphics manipulation with good event API and alpha channel support, more do-it-yourself than vpython - pyopengl: low-level (yet obviously powerful and high-performance) option which integrates well with SDL / pygame Right now my objective is to find a good API that will allow me to perform fast alpha and blitting operations for a fancy menu system. Do any of you have experience and subsequent advice? I'm leaning toward pygame. -- _ ,^. _ ,'/ -' '- \`. / | \ / | \ Jonathan Daugherty | | | | | | | \_,' `._/ | http://www.cprogrammer.org | | \ / `. .' `--._.--' From fperez528 at yahoo.com Mon Mar 8 12:22:00 2004 From: fperez528 at yahoo.com (Fernando Perez) Date: Mon, 08 Mar 2004 10:22:00 -0700 Subject: os.popen() failing under ipython+cygwin, I'm stumped. References: Message-ID: Hi Jason, Jason Tishler wrote: > Fernando, > > On Mon, Mar 08, 2004 at 09:01:05AM -0700, Fernando Perez wrote: >> Any help would be much appreciated. > > Does rebasing your Cygwin installation help? > > http://www.tishler.net/jason/software/rebase/rebase-2.2.README I passed the tip to the cygwin user who sees the problem, many thanks. Since I don't have cygwin myself, I'll have to wait for him to do any testing. I'll report back if I hear from him on any results. Best regards, f. From breetai at sdf.lonestar.org Fri Mar 5 15:47:14 2004 From: breetai at sdf.lonestar.org (Eduardo Bernal) Date: Fri, 05 Mar 2004 13:47:14 -0700 Subject: Upgrade 2.2.2 to 2.3.3: Keep my old 3rd party modules or rebuild them or reinstall from scratch? Message-ID: <4048E752.75F37710@sdf.lonestar.org> I'd like to upgrade to 2.3.3, mostly to use VPython. I have a lot of stuff not in the standard distro, VPython, PIL, wxPython, eGenix tools, etc. How much of this stuff can I still use as is, i.e. just copying over the 2.2 site-lib stuff to the 2.3 site-lib stuff? What will I have to rebuild? TIA Ed -- You'd better beat it. You can leave in a taxi. If you can't get a taxi, you can leave in a huff. If that's too soon, you can leave in a minute and a huff. -- Groucho Marx From peter at engcorp.com Sat Mar 20 17:42:22 2004 From: peter at engcorp.com (Peter Hansen) Date: Sat, 20 Mar 2004 17:42:22 -0500 Subject: [OT] Compilable Python-like language? In-Reply-To: References: Message-ID: <7fadnUoM0Z9SVcHd4p2dnA@powergate.ca> Ed Cogburn wrote: > 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. Have I > been looking in the wrong places? I certainly can't be the only person > to want a Pythonish language that can be compiled. You certainly aren't the first to ask, and like many others you don't give any reason for wanting it compiled. Were you hoping for greater performance? Resistance to reverse engineering? Easier packaging and distribution? Or something else? There are good and effective solutions for each of these problems, and as a result relatively little reason you should want Python to be just like those other languages in this respect. -Peter From tismer at stackless.com Mon Mar 29 10:52:53 2004 From: tismer at stackless.com (Christian Tismer) Date: Mon, 29 Mar 2004 17:52:53 +0200 Subject: Tabbing probs In-Reply-To: <40684458.9030507@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> <106g7r5nbg9ur16@news.supernews.com> <406829FF.5060304@mlug.missouri.edu> <40682BD8.3040501@stackless.com> <40684458.9030507@mlug.missouri.edu> Message-ID: <40684655.2060602@stackless.com> Michael wrote: > >> 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.. ... Once again: They use tabs but they want to do 4 space indentation. That means they use a tab when it fits, and 4 spaces when not... def mixed_tabs(): ....if blah: # this is 4 spaces --------pass # this is one tab -- 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 myang at clarku.edu Thu Mar 25 21:18:18 2004 From: myang at clarku.edu (myang) Date: Thu, 25 Mar 2004 21:18:18 -0500 Subject: import a modified module Message-ID: I am revising a python module, and try it in python shell. Each time after the module is modified, how can I import the new module? I remember there is an "import" like staff to do it, but dont know its name clearly. I was not able to google out it, and the huge bulk of python documentation is fearsome. :( Regards, Yang From esuvs at yahoo.co.uk Thu Mar 4 08:09:45 2004 From: esuvs at yahoo.co.uk (David) Date: Thu, 04 Mar 2004 13:09:45 +0000 Subject: Problem displaying images with TkInter Message-ID: Hi, I'm new to python so I'm probably making a fairly simple mistake, but look at the example below. It simply displays a rectangle and an image. ------------------------------------------------- from Tkinter import * root = Tk() c = Canvas(root, width=1024, height = 1024) c.pack() c.create_rectangle(10,10,50,50) mudPhoto = PhotoImage(file="/root/metropolis/mud.gif") c.create_image(50, 50, anchor=NW, image=mudPhoto) root.mainloop() ----------------------------------------------- Now I try to modify it so that the image and rectangle only appear when I click the mouse on the canvas. I use the following code: ----------------------------------------------- from Tkinter import * root = Tk() def OnClick(event): print "click!!!" c.create_rectangle(10,10,50,50) mudPhoto = PhotoImage(file="/root/metropolis/mud.gif") c.create_image(50, 50, anchor=NW, image=mudPhoto) c = Canvas(root, width=1024, height = 1024) c.pack() c.bind("",OnClick) root.mainloop() ---------------------------------------------- However when I click the mouse it prints 'click!!!' and draws the rectangle as expected. However it doesn't draw the image! Does anyone have any idea why this would be? Thanks for any help, David From dmq at gain.com Thu Mar 4 19:08:49 2004 From: dmq at gain.com (David MacQuigg) Date: Thu, 04 Mar 2004 17:08:49 -0700 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> <6ubf401c2qtarfoa36m03572dprj0h9kkl@4ax.com> Message-ID: <4pgf409lhtme32fb4gmdfdar8astq074jv@4ax.com> On Thu, 04 Mar 2004 22:43:41 +0000, Stephen Horne wrote: >def print (*args) : > sys.stdout.write (string.join ([str(i) for i in args], " ") + "\n") Cool. But we can go one better. The join function requires that we import the soon-to-be-deprecated ( I am told.) string module. The proper way ( I am told.) is to use the join *method*: >>> def prnt(*args): sys.stdout.write(' '.join([str(i) for i in args]) + '\n') >>> prnt(1,2,3) 1 2 3 >>> Actually, I think this is rather ugly. The string 'method' still looks like a 'function'. We really need a 'join' method that takes a list of strings as its 'front-door' object and the 'joiner' as its optional 'side-door' input. Then we could do like Ruby and say: [str(i) for i in args].join(' ').append('\n') For another good example of Ruby's advantage in sequential operations on strings see http://userlinux.com/cgi-bin/wiki.pl?RubyPython Incidentally, sys.stdout.write(i) *will* work on integers (at least in Python 2.3.3 running in IDLE 1.0.2) It doesn't work if I start Python from a command line!! Very strange. I do run my examples before posting. -- Dave From fpetermaas at netscape.net Thu Mar 18 03:21:55 2004 From: fpetermaas at netscape.net (Peter Maas) Date: Thu, 18 Mar 2004 09:21:55 +0100 Subject: '1' + 1 ==> True ??? In-Reply-To: References: Message-ID: Nicola Mingotti schrieb: > 2) Like C -----> Char is converted to int > #include > int main(){ > printf("%i %i", '1' > 1 , '1' + 1 ); > return 0; > } That's not really a conversion. '1' is 0x31 in memory and 0x31 > 1. C simply compares memory locations, so comparisons are perhaps even be machine dependent. Unlike C, Python's comparison results for different types are defined in a strange but archicture independent way, see Python Library Reference 2.3.3. The important thing is that objects of different types are not equal. > Excuse me again for mistakes or possible (but unwanted) > rude language . Sorry, no excuse. :-) Really, please stop excusing, for the following reasons: 1. It's GREAT that you post in English, as I don't understand Italian. 2. Native speakers also make mistakes. 3. Nobody expects an excuse (I think). :-) 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 ally_burnett at yahoo.co.uk Wed Mar 17 05:10:39 2004 From: ally_burnett at yahoo.co.uk (alastair) Date: 17 Mar 2004 02:10:39 -0800 Subject: Handling geoTIFF files Message-ID: <23ae7099.0403170210.540888cd@posting.google.com> Hi, I am trying to use Python to do the following: - read in an image in geoTIFF format - extract the tags from the file - do something interesting with the tags I've read about the Python Imaging Library (PIL) which seems to do what I need with TIFF files. I was wondering if anyone knows if this library will work with geoTIFF files or if there are any other methods of doing what I need. Many thanks, Alastair. From newsgroups at jhrothjr.com Mon Mar 29 08:05:44 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 29 Mar 2004 08:05:44 -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> Message-ID: <106g7r5nbg9ur16@news.supernews.com> "Michael" wrote in message news:mailman.36.1080541549.20120.python-list at python.org... > > >The basic difficulty with tabs is that there are a huge > >number of programs "in the wild" that treat tabs > >differently. Unless you're completely in control of all > >the programs that will ever be used to edit and display > >your program, using tabs will cause formatting errors > >somewhere, to someone under some circumstance > >that you never thought of. > > > > > Which programs? I find spaces to cause weird issues. Especially if you > use some half assed editor that uses variable width fonts. I don't have very much sympathy for people who use poor editors to write programs. I've got a lot of sympathy for people who are stuck with defective rendering and printing programs for analyzing programs that they didn't write in the first place, though. Note that Python, which is mostly what we're talking about on this newsgroup, comes with a reasonably competent editor called Idle. There are very few environments where you can use Python at all where you can't use Idle. I've never seen variable width fonts to change the width of spaces on the left, unless it was doing something like full justification. As far as rendering programs, the most obvious culprit is OE, which for all of its defects and security problems, is still one of the most used mail and newsgroup clients out there. I'll also point out that even programs that properly follow the tab "standard" will not render well since the standard is that a tab goes to the next multiple of 8. The number 8 has nothing to do with readability: it was decided on as the best compromise on compressing the number of characters going over a line when line speeds were *very* slow and teletypes really were electromechanical monsters with these little metal stops called 'tabs' in the back. There is, of course, no standard at all for how to change the default tabbing in programs, which means that one has to deal with each and every one on an individual basis - if it's even possible. Reading the source for Idle is quite enlightening: there is a comment about Tk doing something rather absurd if you change the tab default. > >The problems with mixed tabs and spaces are even > >worse: you can lose indentation and totally mess up > >the program so it won't even compile if you use the > >wrong tools on such a program. > > > > > That'd just be bad programming to use different formatting standards > within the same program. At least within the same file. Definitely. > >This is the basic reason why the current standard for > >library modules is 4 space indentation; it's the only > >thing that is, for all practical purposes, guaranteed to > >work for everyone, with any editor, formatter, > >renderer and printer out there. > > > > > I don't see how it is any better than a standard of always using a > single tab or space for indention. I hate code that requires me to press > multiple space or delete keys to change the block level of a line of > code. I'm a coder and therefore am lazy. Why press four keys when I > could press one? Any programming editor worth the name will insert spaces when you use the tab key; likewise it will adjust with the backspace key. This is not a problem unique to Python, after all. The same comment applies to variable width fonts. A good programming editor will not use them. > >Python is not Perl. Python's philosophy has never > >been to provide several different ways of doing things > >just to provide different ways. There needs to be a > >demonstrated benefit to the different ways, and tabs > >don't make that cut. If you want the space savings, > >ziping the file will do much better. > > > > > I'm not a fan of multiple ways but I think it's different to remove a > feature than to add a feature. Breaking existing code for pointless > reasons is bad. I'd rather they keep tab support than spaces but since > both have a historical support I'd be wary of removing either. Again > zipping files is adding additional steps which IMO is bad from a lazy > coder point of view. The lazy coder standard of coding keeps code > simple. Smaller isn't a significant problem in most cases. > From gh at ghaering.de Wed Mar 24 10:31:12 2004 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Wed, 24 Mar 2004 16:31:12 +0100 Subject: using MySQLdb module In-Reply-To: <40619FBD.2010609@zslide.com> References: <40619FBD.2010609@zslide.com> Message-ID: <4061A9C0.9000001@ghaering.de> vincent Salaun wrote: > hi, > > i'd like to use the MySQLdb module in my jython script but it doesn't > work ... > Is it possible or does this module only work with python ? [...] This module only works with traditional Python, not with Jython. To use MySQL from Jython, use mxJDBC module, which is integrated in modern Jython versions, anyway. -- Gerhard From adeleinandjeremy at yahoo.com Mon Mar 29 15:35:00 2004 From: adeleinandjeremy at yahoo.com (Adelein and Jeremy) Date: Mon, 29 Mar 2004 12:35:00 -0800 (PST) Subject: ESR's fortune.pl redone in python - request for critique Message-ID: <20040329203500.47023.qmail@web40805.mail.yahoo.com> 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), except that instead of generating a sigline for mail, it prints a fortune to screen in the traditional manner of the Unix fortune. I have succeeded in terms of functionality, but because I am only a novice programmer, I would appreciate any comments, criticism, suggestions, alternative options, etc. that more experienced programmers would be willing to give, whether technical or stylistic in nature. Here is my code: #! /usr/bin/env python ## fortune ## Jeremy Conn ## Version 0.9, 20020329 ## GNU GPL http://www.fsf.org/licenses/gpl.html ## Description: Generates a random fortune for display onscreen from ## a single file of quotes which the user maintains; the ## quotes can be multi-line, and are separated by lines ## containing only a percent sign (same format as ## traditional fortune files). import random import re import sys FORTUNES_FILE = ".fortune" # What file should we use? if len(sys.argv) > 1: fortunes_file = sys.argv[1] else: fortunes_file = FORTUNES_FILE # Let's see if we can open that file for reading try: fi = open(fortunes_file, 'r') except: sys.exit("Cannot open fortunes file %s." % fortunes_file) # Collect the file pointers to each fortune entry in the file fp_entry = [0] line = fi.readline() while line != "": if re.match(r'^%$', line): fp_entry.append(fi.tell()) line = fi.readline() # Seek to a random entry try: fi.seek(random.choice(fp_entry)) except: sys.exit("Cannot seek.") # Add the entry to output message and then print it fortune = '' line = fi.readline() while line != '': if re.match(r'^%$', line): break fortune += line line = fi.readline() print fortune # Return fp to beginning of file, close the file, and exit program fi.seek(0,0) fi.close() sys.exit() - Jeremy adeleinandjeremy at yahoo.com __________________________________ Do you Yahoo!? Yahoo! Finance Tax Center - File online. File on time. http://taxes.yahoo.com/filing.html From jcarlson at nospam.uci.edu Tue Mar 2 20:40:27 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Tue, 02 Mar 2004 17:40:27 -0800 Subject: Group comment In-Reply-To: References: Message-ID: >>You may as well suggest /* and */, as they are far more well known, and >>significantly more acceptable (in my opinion) than your syntax. >>Considering that /* */ has not already been added to the language, I >>doubt that an aribirary magical syntax for commenting code would be added. >> > > > /* > /* you missed the point */ > */ I understood that nuance, and while your syntax allows nesting of comments, it is still arbitrary and magical. May as well use an "if False:" construct and gain the benefit of visual indentation, regardless of an editor's syntax highlighting capability. - Josiah From tim.one at comcast.net Tue Mar 23 13:35:31 2004 From: tim.one at comcast.net (Tim Peters) Date: Tue, 23 Mar 2004 13:35:31 -0500 Subject: import, functions, and threading In-Reply-To: <25b5433d.0403231000.4003f7fa@posting.google.com> Message-ID: [Aahz] >> 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. [Phillip J. Eby] > 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. A more common deadlock is this one, in various guises (some much subtler than this! this is meant to be as obvious as possible), which has no explict locks: """ import threading import time initialized = False class Worker(threading.Thread): def run(self): global initialized import sha self.accum = sha.new() initialized = True while True: pass Worker().start() while not initialized: time.sleep(1) print 'OK!' """ If you import that as a module, you'll deadlock: the import lock is held by the thread doing the import, that thread is spinning in the loop waiting for the new thread's run() method to set initialized to True, but the new thread's run() method is blocked on the "import sha", waiting for the import lock. There's no problem if sha is imported at module level instead. The lesson I take from that isn't to avoid function-level imports, though, it's that merely importing a module shouldn't start threads as a side effect. Yes, I am a Zope Corp employee . From t-meyer at ihug.co.nz Tue Mar 16 16:33:20 2004 From: t-meyer at ihug.co.nz (Tony Meyer) Date: Wed, 17 Mar 2004 10:33:20 +1300 Subject: where can I find Paris Hilton video? In-Reply-To: <1ED4ECF91CDED24C8D012BCF2B034F13057AA792@its-xchg4.massey.ac.nz> Message-ID: <1ED4ECF91CDED24C8D012BCF2B034F1304677AE3@its-xchg4.massey.ac.nz> > "Philipp Lenssen" wrote in message > news:c340l1$23rse7$2 at ID-203055.news.uni-> berlin.de... > > montezum wrote: > > > > > where can I find Paris Hilton video? > > > > Where you find everything. In Google. > > > Or easier: rent a videocamera, book a flight to Paris, take a > cab to the Hilton, shoot some video, take a cab to the > airport, and fly back home. You have a strange definition of "easier". :) =Tony Meyer From steve at ninereeds.fsnet.co.uk Tue Mar 30 22:51:06 2004 From: steve at ninereeds.fsnet.co.uk (Stephen Horne) Date: Wed, 31 Mar 2004 04:51:06 +0100 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: On Tue, 30 Mar 2004 14:58:44 +0200, Gerrit wrote: >Mark Hahn wrote: >> But everything in Prothon is subject to change until > 7/04. > >Is that April the 7th or July the 4th? You didn't spot the little clue? As in _why_ the 4th of July? :-) -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From dmq at gain.com Tue Mar 23 21:33:16 2004 From: dmq at gain.com (David MacQuigg) Date: Tue, 23 Mar 2004 19:33:16 -0700 Subject: IDLE won't launch, and other frustrations References: Message-ID: <8hs160ltsqq9k3k18cfs7h2jtdro6rss98@4ax.com> On Tue, 23 Mar 2004 20:12:53 -0500, "Michael A. Covington" wrote: >All looks good except - IDLE won't start at all!!! I try to launch it, get >a few seconds of the hourglass cursor, and it's gone, with nothing on the >screen and no processes running! > >Rebooting didn't cure this. What gives? This is a common problem with lots of causes. Do a Google search on 'start IDLE group:comp.lang.python' Here is one good thread: IDLE won't start 13-Oct-2003 http://www.google.com/groups?hl=en&lr=&ie=UTF-8&oe=UTF-8&threadm=9b4l30tn66bhni11hdatu8ot7uvpme8h13%404ax.com&rnum=10&prev=/groups%3Fq%3Dstart%2BIDLE%2Bgroup:comp.lang.python%26hl%3Den%26lr%3D%26ie%3DUTF-8%26oe%3DUTF-8%26scoring%3Dd%26selm%3D9b4l30tn66bhni11hdatu8ot7uvpme8h13%25404ax.com%26rnum%3D10 In spite of these problems, I'm very happy with IDLE. Once you get it working, it is ideal for students. I also use it in my development work, along with Qt Designer for the GUI part. -- Dave From ieyf4fu02 at sneakemail.com Wed Mar 31 01:24:20 2004 From: ieyf4fu02 at sneakemail.com (Greg Ewing (using news.cis.dfn.de)) Date: Wed, 31 Mar 2004 18:24:20 +1200 Subject: Prothon Prototypes vs Python Classes In-Reply-To: <4069a001$0$4237$afc38c87@news.easynet.co.uk> References: <569c605ld1cj8fc1emolk08ete0s1prls1@4ax.com> <106di86neu1qh4d@news.supernews.com> <4069a001$0$4237$afc38c87@news.easynet.co.uk> Message-ID: Peter Hickman wrote: > I find bottom posting to be a real pain as when I look at a new message > it defaults to showing me the top of the message and I then have to > scroll through pages of quoted posts that I have already read just to > read one or two lines stuck at the bottom. That's equally bad. The issue isn't about so-called "top-posting" vs. "bottom-posting". The issue is that you should only be quoting SMALL amounts of the original post -- just enough to establish a context for what you're about to say. Then people don't have to scroll either way to find the new content. (You will notice that I did not quote any more of the original message, either at the top or the bottom.) -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From claird at lairds.com Mon Mar 1 09:02:01 2004 From: claird at lairds.com (Cameron Laird) Date: Mon, 01 Mar 2004 14:02:01 -0000 Subject: Why Python? References: <1045c7gfn9ipj38@corp.supernews.com> Message-ID: <1046gip10m5m9bc@corp.supernews.com> 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 . 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 ...). -- Cameron Laird Business: http://www.Phaseit.net From christian at mvonessen.de Sun Mar 28 09:11:46 2004 From: christian at mvonessen.de (Christian von Essen) Date: Sun, 28 Mar 2004 16:11:46 +0200 Subject: How to run another .py file w/o exec command? In-Reply-To: References: Message-ID: CaptainN at altel.net wrote: > Hi everybody, > > I'm sure there's a way to do this, but I can't find it. How can I execute > another .py file from my first .py file without using an exec* command? > They're both in the same directory, and it would be nice to have some > run("another.py") type statement as opposed to a big exec with absolute > pathnames and garbage like that. > > It works the way I have it, but it just seems like a bad way in general to > do it. I'm runnning Python 2.3.3 on win32. > > Thanks! > CaptainN > > > I'm really new to python, but there are several ways with the import statement: 1) If the code you want to execute is not in a class but just like this: File: other.py class A: pass print "You've called me!" then you can just import it with "import other" and the print statement gets executed, like any other thing at column 0 2) If 1) is not the case i.e. File: other.py class A: pass def method(): print "You've called me!" you can import it with "import other", too and just do "other.method()" or "from other import *" and "method()" Christian von Essen From snail at objmedia.demon.co.uk Fri Mar 5 09:29:15 2004 From: snail at objmedia.demon.co.uk (Stephen Kellett) Date: Fri, 5 Mar 2004 14:29:15 +0000 Subject: Getting params in callback function. Message-ID: Hello everyone. I've written a tracing function in C which is called when Python executes each function and line and exceptions etc. I don't know much about Python (I've been using assembly, C++ and Java in varying amounts since 1983), so I'd very much appreciate some help trying to get this information. If this is not the correct newsgroup to ask this question, please suggest an alternative. How can I determine what the parameters to a function are when the callback is called when Python enters a function? I've included a code snippet below for clarity. int pythonCallback(PyObject *obj, PyFrameObject *frame, int what, PyObject *arg) { switch(what) { case PyTrace_CALL: { // entering a function, arg is always NULL // my attempt at getting the params // I thought they may be here, but this code fails // I initially thought of getting the type name // and if that worked I could move on to getting // the value, but even getting the type name failed int i; wprintf(_T("Num locals: %d\n"), frame->f_nlocals); for(i = 0; i < frame->f_nlocals; i++) { PyObject *po; char *objTypeName; po = frame->f_localsplus[i]; objTypeName = po->ob_type->tp_name; wprintf(_T("Local %d: type: %s\n"), i, objTypeName); } } break; case PyTrace_EXCEPTION: { // exiting a function via an exception // arg is Exception information as returned by // sys.exc_info() } break; case PyTrace_LINE: { // line number event, arg is always NULL } break; case PyTrace_RETURN: { // leaving a function // arg is Value being returned to the caller } break; default: { // unknown operation } break; } return 0; } Thank you for reading, hope you can shed some light on this. Stephen -- Stephen Kellett Object Media Limited http://www.objmedia.demon.co.uk RSI Information: http://www.objmedia.demon.co.uk/rsi.html From newsgroups at jhrothjr.com Tue Mar 30 11:08:57 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Tue, 30 Mar 2004 11:08:57 -0500 Subject: Tabs and spaces References: <569c605ld1cj8fc1emolk08ete0s1prls1@4ax.com><106cc1f2rsnaoe2@news.supernews.com><406635AB.9050803@mlug.missouri.edu><106ceeeqc8ph126@news.supernews.com><106g7r5nbg9ur16@news.supernews.com> Message-ID: <106j6v5t8sr9k37@news.supernews.com> "Gerrit" wrote in message news:mailman.114.1080652458.20120.python-list at python.org... John Roth wrote: > As far as rendering programs, the most obvious > culprit is OE, which for all of its defects and security > problems, is still one of the most used mail and newsgroup > clients out there.
T h e r e   i s   a   s o l u t i o n   ; - )
1. This only works if you are using html, which is strongly discouraged (but still depressingly prevalent) 2. The OE problem is on the recipient's side, not on the sender's side. John Roth Gerrit. -- Weather in Twenthe, Netherlands 30/03 13:55 UTC: 15.0?C wind 5.8 m/s E (57 m above NAP) -- here will soon be Gerrit Holl's very own signature From ivoras at __geri.cc.fer.hr Thu Mar 4 16:00:39 2004 From: ivoras at __geri.cc.fer.hr (Ivan Voras) Date: Thu, 04 Mar 2004 22:00:39 +0100 Subject: Postgres BYTEA problems In-Reply-To: <27ab36b3.0403031305.3e1ed4f7@posting.google.com> References: <27ab36b3.0403031305.3e1ed4f7@posting.google.com> Message-ID: Steve wrote: > a character that must be escaped. > so if I should be getting > "\x00\x01" > I'll get > "\\x00\\x01" Are you sure that it's the dbapi driver that is doing it, or maybe the data was written to the database in that way (e.g. not chr(00)+chr(01) but '\' 'x' '0' '0' ...)? From __peter__ at web.de Fri Mar 5 07:21:01 2004 From: __peter__ at web.de (Peter Otten) Date: Fri, 05 Mar 2004 13:21:01 +0100 Subject: Tkinter main window needs to disappear References: Message-ID: Herman Geldenhuys wrote: > Blanki've got to use a library(tkSnack) in Tkinter, but i don't want to > use the Tk GUI. i need to create a Tkinter.Tk() and call it's main loop > for the package to work, but like I said, I don't want to use the GUI. > when I do this, there pops up a gui (main) window, but how do I make it > disappear? >>> import Tkinter >>> root = Tkinter.Tk() >>> root.withdraw() '' I'd rather have the window not appear in the first place, but I don't know how to achieve that, either. Peter From HughMacdonald at brokenpipefilms.com Tue Mar 30 01:48:56 2004 From: HughMacdonald at brokenpipefilms.com (Hugh Macdonald) Date: Tue, 30 Mar 2004 07:48:56 +0100 Subject: GUI Frameworks in Python? Message-ID: <006701c41623$12c7b1c0$0600a8c0@Hugh> I've recently been trying out various different GUI frameworks in Python and was wondering if I could get your input on the pros and cons of the different ones... wxPython: I love the programming side of wxPython, but I find it's just so slow to initialise in the first place. Tkinter: While it's fast to load up, the syntax has never really appealed to me GTK: Unknown - I'm looking into it today Qt: I have yet to manage to install it on my system Anything else? Hugh Macdonald From mogmios at mlug.missouri.edu Fri Mar 5 11:10:03 2004 From: mogmios at mlug.missouri.edu (Michael) Date: Fri, 05 Mar 2004 08:10:03 -0800 Subject: Python Database Driven Web Development In-Reply-To: <5E62CFE4CB546F44ADCABD9852C2C8EC048C94@email.toronto.visiontv.ca> References: <5E62CFE4CB546F44ADCABD9852C2C8EC048C94@email.toronto.visiontv.ca> Message-ID: <4048A65B.9040007@mlug.missouri.edu> You'll probably want to look at mod_python and MySQLdb. I like to sepperate appliation logic from UI logic using xml-rpc but that's only needed if you want the ability to have multiple front-ends or want a clean sepperation. >What do I need other than Python, Apache, and MySQL to develop a database driven intranet? Do I need to use any framework or application server? If I do please kindly direct me where to go. > From newsgroups at jhrothjr.com Mon Mar 15 10:52:30 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 15 Mar 2004 10:52:30 -0500 Subject: Seeking advice on GUI code architecture References: Message-ID: <105bkcsje8e3mbe@news.supernews.com> "Qp" wrote in message news:Zp95c.6130$CI3.3590 at fe03.usenetserver.com... > Hi, I've got a generic coding architecture question about an application I'm > developing. Given that I've never developed anything quite like this before > (especially not in Python), I'd appreciate any pointers that you can give > me. > > The app is a network client written using Twisted and Tkinter. The clients > will connect to a server, communicate via public & private chat, and also > play simple games. > > My problem is this: how do you keep your GUI code seperate from as much > underlying code as possible? As I begin, I find myself adding a lot of > intermediate code (not Tkinter, but not Twisted either) to the GUI class, > and it's beginning to clutter things up. It really seems as if I should > have a GUI class, a network class, and some separate way of communicating > between them... but I can't seem to visualize the structure in my mind. > > If anyone has tips, docs, or examples, I would greatly appreciate it. The suggestions about MVC and Facade patterns are right on. One thing that will help *a lot* is to provide a second UI for your program. Make it text based for testing. That will force you to factor out common behavior. John Roth > > Thanks a lot. > > > From newsgroups at jhrothjr.com Sun Mar 28 07:44:56 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Sun, 28 Mar 2004 07:44:56 -0500 Subject: Prothon Prototypes vs Python Classes References: <569c605ld1cj8fc1emolk08ete0s1prls1@4ax.com> <106cc1f2rsnaoe2@news.supernews.com> <406635AB.9050803@mlug.missouri.edu> <106ceeeqc8ph126@news.supernews.com> Message-ID: <106di86neu1qh4d@news.supernews.com> "Mark Hahn" wrote in message news:v0r9c.38988$cx5.22021 at fed1read04... > > although for reasons I've mentioned elsewhere, I won't use Prothon. > > Can you please point me to those reasons? Since I got into a minor flame war over them, including a very snide and oh so superior response from one yahoo who almost hit my killfile over it, I'll just mention that there are ***very good***, that is ***extremely good*** reasons why the Python standard is to use spaces for indentation, and why the option of using tabs will be removed in 3.0. There are enough interesting languages out there to investigate that I simply won't bother with candidates that don't play fair with ***all*** the tools I use, or that people I communicate with use. John Roth From rogerb at rogerbinns.com Tue Mar 9 23:23:15 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Tue, 9 Mar 2004 20:23:15 -0800 Subject: Working around a lack of 'goto' in python References: Message-ID: <9qh2i1-2up.ln1@home.rogerbinns.com> Roy Smith wrote: > 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 :-) It also affects former Java weenies. As a Java programmer you expect your code to be run under a JIT (and not interpretted) and you are aware that exceptions are significantly more expensive than straight forward code. This is less of an issue in Python as interpretters don't tend to have as expensive exceptions compared to "normal" code. http://www.javaworld.com/javaworld/jw-08-2000/jw-0818-exceptions-p2.html (2/3rds of the way down) Roger From tim.one at comcast.net Thu Mar 18 16:49:56 2004 From: tim.one at comcast.net (Tim Peters) Date: Thu, 18 Mar 2004 16:49:56 -0500 Subject: Release history ? In-Reply-To: Message-ID: [Bror Johansson] > I've searched for, but haven't found, a compilation of the incremental > differences between major releases of Python, starting from (my entry > version) 1.4 or 1.5. > > Is there somewhere something that contains this info? Look at Misc/HISTORY in your Python distribution. Misc/NEWS contains most-recent history, and the older parts of that migrate into Misc/HISTORY as the centuries go by. From simon_place at whsmithnet.co.uk Sun Mar 7 18:31:30 2004 From: simon_place at whsmithnet.co.uk (simon place) Date: Sun, 07 Mar 2004 23:31:30 +0000 Subject: machine control script ( parameterless method? ) In-Reply-To: <404b63a7$0$295$626a14ce@news.free.fr> References: <340a6b1b6f65b385490e5d818b2b6c9e@news.scbiz.com> <20040306123424.20326.00000892@mb-m04.aol.com> <404a1dcd$1_1@mk-nntp-1.news.uk.worldonline.com> <404b63a7$0$295$626a14ce@news.free.fr> Message-ID: <404bb0d3_2@mk-nntp-1.news.uk.worldonline.com> F. Petitjean wrote: > On Sat, 06 Mar 2004 simon place wrote: > > [snip] > >>that's why the question is actually only about >>getting rid of the brackets. > > If the action is a property, simply writing someobject.someobject can > trigger a get method whithout the brackets. > > Regards. thanks this is lot better, i might be able to except a dot but if anyone has an idea about getting rid of this too? From dw-google.com at botanicus.net Fri Mar 5 06:30:10 2004 From: dw-google.com at botanicus.net (David M. Wilson) Date: 5 Mar 2004 03:30:10 -0800 Subject: os.popen varies return type depending on exit status? Message-ID: <99dce321.0403050330.572a68da@posting.google.com> Hi there, on Linux: >>> [ type(popen(cmd).close()) for cmd in ( 'true', 'foo' ) ] sh: line 1: foo: command not found [, ] This feels inconsistent to me, and it just bit me because I was expecting a 0 exit status on success, not None. Does close() return this for historic reasons? David. From vincent.salaun at zslide.com Fri Mar 26 06:19:35 2004 From: vincent.salaun at zslide.com (vincent Salaun) Date: Fri, 26 Mar 2004 12:19:35 +0100 Subject: extending dbexts Message-ID: <406411C7.9060606@zslide.com> hi, i'd like to know if it's possible to extend dbexts to other database modules as MySQLdb ... For the moment, it only supports zxJDBC and mxODBC modules but they say that it "could easily be modified to support others. It allows developers to write scripts without knowledge of the implementation language of Python (either C or Java). " (see http://www.jython.org/docs/zxjdbc.html for details). I just begin to use python and i looked at dbexts.py but it seems to be a bit complicated .... Does anybody know if dbexts support new modules now or if there are projects around that ? I searched some resources about dbexts on the web but didn't find so much things .... thanks, vincent From achrist at easystreet.com Thu Mar 18 23:54:21 2004 From: achrist at easystreet.com (Al Christians) Date: Thu, 18 Mar 2004 20:54:21 -0800 Subject: new to programming: suggestion In-Reply-To: References: <3d5e65ea.0403152115.3df7e8c1@posting.google.com> Message-ID: <105kv93nqqrr809@corp.supernews.com> There's a great old book from about 25 years ago: "Graded Problems in Computer Science". It's a language-neutral set of problem sets that starts with very simple basics and takes you through a big part of what was the undergraduate CS curriculum back then. Nothing much about GUI's or OO's or relational databases, but you'll be able to code real good when you've worked your way through it. And of course, you can use GUI's and OOP as you work the problems. You'll need a basic reference for your language of choice to help you get through it. Al From steve at waypath.com Sun Mar 28 20:29:56 2004 From: steve at waypath.com (Steve @ Waypath) Date: Sun, 28 Mar 2004 17:29:56 -0800 Subject: process wrapper? Message-ID: <5ficndxjntWG4frd38DK-w@speakeasy.net> I need help. I'm trying to write a process wrapper class in Python (on Linux) that let's one: - read service definitions from a config file (where a service definition includes a bash command to start the service, and the service is a daemon) - call a method that will start up the service - call a method that will shut down the service. - other stuff not relevant here Where I'm stumped is in starting up the service in a way that: - doesn't block the running of the main process (i.e. returns control back to the wrapper, so it will listen for more commands) - let's me get some kind of handle on the started service that I can later use to shut down the service. I've tried every implementation of os.system, os.popen*, os.spawn* , and (os.fork + os.exec*) for which I can find an example or that I can imagine, but I can't come up with anything that works for me. os.spawnv() looked very promising, but every process I start with it goes defunct. I won't bore you with examples of stuff that doesn't work. I've tried so many things, my head is spinning. I don't care if I wrap the process in a handler that my main process controls/kills or if I spin off a process but track it's PID, to kill later. I don't care if the PID is in memory or written to a file I can read later. Can anyone point me in the right direction? From jacek.generowicz at cern.ch Tue Mar 2 09:05:45 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 02 Mar 2004 15:05:45 +0100 Subject: Why Python? References: <4043597F.30506@cs.com> Message-ID: Gerhard H?ring writes: > One debugging feature that Python doesn't support is > "edit-while-debugging" (edit the function/method) you just debug, > something which is possible in VB and VC6, for example) Sorry ... what do you mean by "edit while debugging" ? Something like XCode's "fix-n-continue" ? In other words the ability to redefine a function in a running program (possibly even before the stack has been unwound after an error (or breakpoint) was encountered) ? [Something which has been an inherent part of the language in many members of the Lisp family for decades, BTW] If you forget about not unwinding the stack, Python certainly supports this. Now, how would one prevent stack unwiding when an exception is raised ... in order to allow the user to inspect the stack frames navigate them, redifine any functions, and then allow continuation? [I guess I could find the answer in the pdb source.] From JasonHarper at pobox.com Fri Mar 19 02:13:33 2004 From: JasonHarper at pobox.com (Jason Harper) Date: Fri, 19 Mar 2004 00:13:33 -0700 Subject: Updating Widgets References: Message-ID: <405A9B0E.242E70EC@pobox.com> SWright wrote: > Is it possible to make the un-named button update without closing and > reopening the window? No, not if you insist on not giving the button a name so that you can refer to it later. The only widget options that can automatically track changes to a variable are those with "variable" in their names, for example the textvariable= option on Labels. Even in the cases where you can use a variable, it doesn't really buy you much to be able to call .set() on the variable rather than .config() on the widget - you have to keep a reference to SOMETHING in either case. I think the only places in Tkinter where use of a Tcl variable is unavoidably required are the Radiobutton and Checkbox widgets, and the corresponding menu items. Jason Harper From andy at reportlab.com Mon Mar 22 18:00:09 2004 From: andy at reportlab.com (Andy Robinson) Date: Mon, 22 Mar 2004 23:00:09 -0000 Subject: 3 weeks to go until Python UK! Message-ID: The UK Python Conference 2004 is just 3 weeks away, at the Randolph Hotel in Oxford, April 16-17 2004 (Fri/Sat). Come and listen to top Python experts including David Ascher, Alex Martelli, Samuele Pedroni, Marc-Andre Lemburg, Chris Withers, Duncan Booth, Armin Rigo and more. http://www.accu.org/conference/python.html The event follows on from a 2-day Open Source Forum discussing the key issues in the software industry, with speakers from IBM, SuSE, MySQL, Zope (Paul Everitt), ActiveState (David Ascher) reflecting on the state and direction of Open Source Software and debating key issues such as software patents. Come and make it a week! http://www.accu.org/conference/opensource.html Python companies may be interested in our budget sponsorship package: a stand and a 10-minute lunchtime talk on the Friday or Saturday Python track for just ?200. This is an ideal chance to showcase your skills or solutions to an audience of architects and decision makers from throughout the UK software development, or to advertise your Python product. http://www.accu.org/conference/sponsorship.html Best Regards Andy Robinson UK Python Conference chair From and-google at doxdesk.com Thu Mar 25 07:59:54 2004 From: and-google at doxdesk.com (Andrew Clover) Date: 25 Mar 2004 04:59:54 -0800 Subject: confused with xml and minidom References: Message-ID: <2c60a528.0403250459.2679a64f@posting.google.com> Guy Robinson wrote: > table.childnode('tbody').getElementsByTagname('tr') doesn't work. There is no such method as 'childnode'. childNodes is a list of all children of tbody, including tr elements and text nodes representing the whitespace in the document. You can search through it manually: def getChildElementsByTagName(parentNode, tagnem): els= [] for child in parentNode.childNodes: if child.nodeType==child.ELEMENT_NODE and child.tagname==tagname: els.append(child) return els tbody= table.getChildElementsByTagName('tbody')[0] trs= tbody.getChildElementsByTagName('tr') or just use getElementsByTagName: tr= table.getElementsByTagName('tr')[0] Note that getElementsByTagName works recursively, so for example in the case of nested tables you'll get more items returned than just the direct children. Also in the standard DOM the NodeList objects returned by getElementsByTagName are supposed to be 'live' and will change as the document is updated. This isn't supported in minidom, but might be in other implementations, so it's a good idea to use list() to convert the NodeList to a static non-updating Python list before using it if you're going to be changing the document at the same time. > Delete this row and insert the new rows? document.createDocumentFragment() a new fragment and appendChild the new row elements to it, then tbody.replaceChild(fragment, tr). -- Andrew Clover mailto:and at doxdesk.com http://www.doxdesk.com/ From hellprout at yahoo.com Wed Mar 31 02:58:01 2004 From: hellprout at yahoo.com (hellprout) Date: 30 Mar 2004 23:58:01 -0800 Subject: problem with wxtextctrl Message-ID: <5b8834c2.0403302358.2698f8f3@posting.google.com> hi , i have a problem with a wxtextctrl with multiline option. i want to write a file , line after line , in my wxtextctrl . But my file is too longer , and the wxtextctrl can't write the end of the file , i miss 100 lines of my file ... What can i do to have all data file ? what library can i use to replace wxtextctrl ? thanks sylvain ---- Bonjour , j'ai un probl?me avec un wxtextctrl , j'ai un fichier qui dooit ?tre trop long pour la m?moire d'un wxtextctrl donc les 100 derni?res lignes du fichier n'apparaissent pas . Comment puis je faire ? dois je changer de methode ? merci sylvain From No.Spam.mc at No.Spam.mclaveau.No.Spam.com Fri Mar 19 06:54:54 2004 From: No.Spam.mc at No.Spam.mclaveau.No.Spam.com (Michel Claveau/Hamster) Date: Fri, 19 Mar 2004 12:54:54 +0100 Subject: Python Tic Tac Toe References: Message-ID: Hi ! Bad I.A., but nice sample for Python-Web-Programming. Michel Claveau From mogmios at mlug.missouri.edu Wed Mar 31 04:15:11 2004 From: mogmios at mlug.missouri.edu (Michael) Date: Wed, 31 Mar 2004 01:15:11 -0800 Subject: Python Documentation Blows! In-Reply-To: <406a753b$0$12020$79c14f64@nan-newsreader-02.noos.net> References: <40699A31.8000708@yahoo.com> <20040330161531.GA17112@vulcan.cprogrammer.org> <4069C839.6020109@mlug.missouri.edu> <406a753b$0$12020$79c14f64@nan-newsreader-02.noos.net> Message-ID: <406A8C1F.6040905@mlug.missouri.edu> >As was mentioned in a recent thread python is definitively >the tool for applications with complex code and no or little UI. >For UI-intense apps, win32 C# and delphi are still hard to beat > > I wouldn't say that. Python definately benefits from portability and easy to write and maintain code. Much better than C#, Delphi, Java, VB, etc. Tkinter is just UGLY though. wxPython looks good and isn't hard to code but it's hard to learn because of the bad documentation. >Possibly a smart (and not necessarily big) wxpython book >could prove a decisive argument for wxpython and python >as well specifically for the "MS visual *" and delphi user >communities > > I'd like to see such a book. Maybe a couple. An in-debth book would be great for me. A Learn Visually wxPython book for beginners would be a good idea too. >Is it time for the python community to commit a bit >more to the wxwidgets/wxpython environment? >I feel so > > I lot of Python people don't like wxPython. I'm really not sure why as it always works for me. I think wxPython is great but really needs more of an experienced and vocal community and as I said some Python centric documentation. From vincent at visualtrans.de Thu Mar 4 17:46:24 2004 From: vincent at visualtrans.de (vincent wehren) Date: Thu, 4 Mar 2004 23:46:24 +0100 Subject: Debugging Python extensions References: Message-ID: "Gus Tabares" schrieb im Newsbeitrag news:c42b7031.0403041232.2941952 at posting.google.com... | Hello all, | | I'm writing some Python extensions in C under Windows using Visual | Studio .NET 2003. I want to be able to debug my extensions using .NET. | I'm not very clear on the exact process of doing this. | | So far I have compiled a debug version of the 'pythoncore' project | that is located in the Python sources. This has produced the | python23_d.dll which I will use to link with my pyd. | | I have a few questions after this step: | 1. Do I need to compile my own version of Python2.3 to debug my pyd? Yes, you need python23_d.dll (which you say you already have, as well as python_d.exe | 2. Do I have to name my debug pyd as filename_d.pyd? Yes. | 3. Does the init function need to be named initfilename_d? No. | | I understand that .NET 2003 is not "supported" (I believe only VS6 is) | but I would think using .NET 2003 would not be much different aside | from converting the projects to the new format. I think it was Martin v. L?wis who created the VC++ 7.1 projects that live in the PCBuild directory for the current development version - you can download it off http://cvs.perl.org/snapshots/python/python/python-latest.tar.gz Check the readme.txt in that same directory for further details... HTH, Vincent Wehren | Thanks, | Gus From jmeile at hotmail.com Thu Mar 18 09:29:15 2004 From: jmeile at hotmail.com (Josef Meile) Date: Thu, 18 Mar 2004 15:29:15 +0100 Subject: Hiding console window In-Reply-To: References: Message-ID: <4059b239$1@pfaff2.ethz.ch> Peter Hansen wrote: > Lucas Raab wrote: > >> I'm looking to play a joke on a friend and I'm wondering if there's a >> way to >> not show or hide the DOS console. My friend doesn't have python so I >> have to >> compile it to an EXE. > > > Use py2exe to compile Python programs to EXEs. > > You would need to define what "hide" means to you to get a useful answer > to the first part of the question. I would just click on the "close" > gadget in the upper right corner, if I wanted to "hide" a DOS console... > > -Peter I think there is a way of telling py2exe that the program is a windows exe, so you won't see the console. You just have to invoque the py2exe help. If I'm not wrong the option should be "--help" or "-h" Regards, Josef From claird at lairds.com Mon Mar 8 21:36:34 2004 From: claird at lairds.com (Cameron Laird) Date: Tue, 09 Mar 2004 02:36:34 -0000 Subject: Sending bulk email from a Python script References: <104q5jpg86q2udf@corp.supernews.com> <2004030819064420092%cs1spw@bathacuk> Message-ID: <104qbdi22opnib8@corp.supernews.com> In article <2004030819064420092%cs1spw at bathacuk>, Simon Willison wrote: . . . >Our largest list at the moment is 4,000 addresses. The business we are in >(local online newspaper) means we are very unlikely to ever have more than >10,000. The answer certainly relates to sendmail, but I'm interested in any >experience other people may have with this kind of task. At the moment I'm >looking at using smtplib and just cycling through calling smtp.send() once >for every address but I'm not confident that that this is a particularly >efficient method. If there's a better option I'd love to hear about it. . . . You didn't mention how often you're doing this. If it's only daily, there's no problem looping through smtp.send() as you describe. Really. You're doing the right thing. And good luck to you. I have a soft spot for local news outlets. -- Cameron Laird Business: http://www.Phaseit.net From premshree_python at yahoo.co.in Wed Mar 3 09:11:16 2004 From: premshree_python at yahoo.co.in (=?iso-8859-1?q?Premshree=20Pillai?=) Date: Wed, 3 Mar 2004 14:11:16 +0000 (GMT) Subject: Python for Beginners Message-ID: <20040303141116.38036.qmail@web8307.mail.in.yahoo.com> Hey, A set of slides introducing folks who are new to Python is available at http://premshree.resource-locator.com/python-seminar-210204/slides/pySlide1.jpg.htm Thought it'd be useful. -Premshree Pillai [http://www.qiksearch.com/] ===== -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 claird at lairds.com Thu Mar 25 15:39:09 2004 From: claird at lairds.com (Cameron Laird) Date: Thu, 25 Mar 2004 20:39:09 -0000 Subject: execute shell command pipeline References: <8757b529.0403251215.29333930@posting.google.com> Message-ID: <1066grdahs0f764@corp.supernews.com> In article <8757b529.0403251215.29333930 at posting.google.com>, Paul wrote: >Hi, > >I'm a Python newbie and I'm wondering how I can do the following Perl thing: > >open(F, 'grep -b 2004 logfile | head -1 | cut -d: -f1 |') or die "blah, blah"; >$offset = ; >( or $offset = `grep -b 2004 logfile | head -1 | cut -d: -f1`; ) > >in Python. When I tried: > >offset = os.popen('grep -b 2004 logfile | head -1 |cut -d: -f1').read() > >I get a whole bunch of error messages -- > >grep: writing output: Broken pipe . . . Python has too many answers to this. I recommend you start with import commands offset = commands.getoutput('grep -b 2004 logfile | head -1 |cut -d: -f1') -- Cameron Laird Business: http://www.Phaseit.net From has.temp2 at virgin.net Thu Mar 4 04:05:05 2004 From: has.temp2 at virgin.net (has) Date: 4 Mar 2004 01:05:05 -0800 Subject: Python as replacement for PHP? References: <403fa54b@news.zianet.com> <99dce321.0403031518.56f61c7c@posting.google.com> <7xad2x5wfm.fsf@ruckus.brouhaha.com> Message-ID: <69cbbef2.0403040105.4c8f7ea@posting.google.com> Paul Rubin wrote in message news:<7xad2x5wfm.fsf at ruckus.brouhaha.com>... > PHP's web environment are > database integration right there for you the moment you install PHP. Ancient proverb say: One man's "database integration" is another's "tight coupling". :) From wberry at wberry.org.x Thu Mar 11 17:39:31 2004 From: wberry at wberry.org.x (Will Berry) Date: Thu, 11 Mar 2004 17:39:31 -0500 Subject: Python style guidelines References: <3064b51d.0403101112.3449e987@posting.google.com> Message-ID: <4050EAA3.9010807@wberry.org.x> Style guidelines and coding standards are the devil! I would enjoy nothing more than reading an ACM paper entitled "Coding Standards Considered Harmful". I've never seen a single real-life case where the coding standard was anything other than the personal preferences of the guy in charge. No consensus, no objectivity, just consistently unreadable code. I think nothing is more evil about coding standards than indentation. My code (not only in Python but in C/C++ and PHP as well) for whatever reason always ends up having about 6 levels of indentation in some places. If the "standard" indentation is anything more than 2 spaces: for each little loop or conditional: you have to indent more and more until: long lines of code (such as calls or complex \ mathematical expressions) have to span more \ lines than they would if only the indentation \ were shorter else: you could simply wrap longer lines and complex \ mathematical formulas without indentation on the remaining \ lines but that just makes your code look like garbage A close second is my undying hatred for same-line opening braces in C. When's the last time you saw Pascal code like: PROCEDURE This_language_sucks(); BEGIN ... END; So I hate coding standards eternally, and the ISO 9000 certifiers that push them. They only result in the majority of developers hating to write code. My opinion is that if engineers cannot be trusted to their own coding styles, you should have caught that in the interview process and not hired them. Open source projects have probably the best argument for coding standards for that reason. Or, for large projects and open source projects, have an auto-styler run on all checked-in code. That would at least do away with the spaces-or-tabs problem. -- Will Berry Co-founder, Second Brain website hosting http://www.secondbrainhosting.com/ From jcarlson at nospam.uci.edu Fri Mar 19 12:34:57 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Fri, 19 Mar 2004 09:34:57 -0800 Subject: Best way to convert string a to utf-* In-Reply-To: References: Message-ID: s = u"some unicode string" utf_8_encoded = s.encode('utf-8') Is this what you were looking for? - Josiah From altis at semi-retired.com Tue Mar 30 13:17:23 2004 From: altis at semi-retired.com (Kevin Altis) Date: Tue, 30 Mar 2004 10:17:23 -0800 Subject: Python Documentation Blows! References: Message-ID: <1Miac.27$iV.12091@news.uswest.net> Are you looking for something dynamic and formatted like pydoc? If so, it is included with Python, so you can run your own server and pick up the doc strings in your own modules and packages. There is also a public server for standard libs. http://pydoc.org/2.3/ Here's an example for the os module. http://pydoc.org/2.3/os.html ka "Adam T. Gautier" wrote in message news:mailman.123.1080662628.20120.python-list at python.org... > OK, First off I am new to Python but I am a convert. I sat down and > wrote two medium complexity applications in Python from scratch and > learning the language in a few days. If I were to do this in C++ and/or > Java it would have taken atleast a month (Rember I was also learning the > Python language). But, I am sick of the documentation! I don't really > use too many Java example applications when I am writing in Java because > (1.) I have been writting in Java since it was called Oak and 2.) I have > the JavaDocs that give me a good grounding as to what the > package/class/function/const is doing). Is there anythin comperable for > Python? It is a shame that the only limitation of a great is > documentation. Is there a project that is trying to do this? Am I > completely off my rocker? Is the Tutorial and Module documentation on > python.org enough? What would it take to develop an JavaDoc like > repository. I don't know much about the PyPI but is a requirement > documentation? What I think would be cool is a PyPI wiki that is > dedicated to to documentation. When a module is submitted it is sent > through a dog auto-gen that generates wiki pages. The wiki pages would > be a reference page(s) (think javadoc), an example code page(s), and a > tutorial thread page(s). Just the refrence page would be auto generated > and the example and tutorial page(s) could be created by the developer > and/or the community in very wiki like style. What do y'all think? > From peufeu at free.fr Mon Mar 29 11:59:39 2004 From: peufeu at free.fr (PF) Date: Mon, 29 Mar 2004 18:59:39 +0200 Subject: Tabbing probs 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> <40684458.9030507@mlug.missouri.edu> Message-ID: I use tabs only. Can't stand spaces. I don't want to hit backspace 4 times to indent back after the end of a block. When I open python files which use spaces, and I insert a code line into them, my editor will insert tabs. And here is a bug. Then I set it to use spaces. Then I open another files, which contains tabs. Argh. I'd like my editor to test automatically if a file has spaces or tabs. Anyone knows a good editor on linux which does this ? And also has good macros ? -- Utilisant M2, le client e-mail r?volutionnaire d'Opera : http://www.opera.com/ From steve at ninereeds.fsnet.co.uk Tue Mar 23 04:39:28 2004 From: steve at ninereeds.fsnet.co.uk (Stephen Horne) Date: Tue, 23 Mar 2004 09:39:28 +0000 Subject: PEP318 alternate syntax idea Message-ID: It just occurred to me that if decorators really catch on, there could be cases where they are applied repeatedly to many functions, and possibly with many decorators. Combine that with many (and variable numbers of) parameters per function and readability could be seriously hit. In C++, the 'private', 'public' and 'protected' modifiers for class members are not applied individually to every single member. This always struck me as being a good thing, and it irritates me that in C# and java every single definition needs to specify it's visibility. Yes, there's a default, but you still often get a lot of definitions that don't match the default. Some classes present a lot of public member functions as their interface, for instance. If I were inventing a language, I would allow more modifiers to be moved away from the definitions/declarations to some kind of preamble. In C++, for instance, it bugs me if I have to individually declare each of a group of members to be static, or mutable, or whatever. With that in mind, 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" ... -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From skip at pobox.com Sun Mar 21 10:06:17 2004 From: skip at pobox.com (Skip Montanaro) Date: Sun, 21 Mar 2004 09:06:17 -0600 Subject: Python bytecode compatibility between interpreter versions In-Reply-To: References: <0qudndSnJMpWbsfdRVn-uA@powergate.ca> <7okui1-3no.ln1@home.rogerbinns.com> Message-ID: <16477.44905.69126.894069@montanaro.dyndns.org> >> pyc files are a behind the scenes implementation detail of one >> version of the Python interpreter that are automatically generated >> and maintained. Jon> Huh?? .pyc files are an "implementation detail of the Python Jon> interpreter"? Care to expound further? 'Coz that sounds pretty Jon> nonsensical... As I mentioned in my previous post, the distiction between the Java VM and the Python VM is that the former is delivered separate from the compiler and other tools, while the latter is delivered afresh with each Python distribution. Guido would be free to eliminate the Python VM from the next version of Python and instead directly interpret the abstract syntax tree emitted by the compiler. PyChecker and other tools which operate directly with the bytecode would break, but Python applications should still work. Think of it this way. The Java virtual machine architecture is sort of akin to the current Wintel architecture. The Python virtual machine architecture would like Microsoft shipping a new, possibly incompatible, CPU with each copy of Windows. Skip From andrew.henshaw at gtri.gatech.edu Mon Mar 15 23:47:42 2004 From: andrew.henshaw at gtri.gatech.edu (Andrew Henshaw) Date: Mon, 15 Mar 2004 23:47:42 -0500 Subject: Advice needed: large OpenGL + Widgets Project for Molecular Graphics References: <5eb8fb88.0403151925.4f63842b@posting.google.com> Message-ID: <105d1nfbbjbul97@corp.supernews.com> Rick Muller wrote: ...snip... > 4. wxPython/PyOpenGL > Advantages: Seems to be a healthy, integrated solution to putting > an OpenGL window inside of a widget. Pretty widgets, and lots of > fancy features. > > Disadvantages: The OpenGL install still crashed under Windows. A > widget set that not many people use? Also requires the most amount > of code rewrite, although if it's the best option it isn't a > problem. > This is the path we've chosen and it has worked out really well. I am surprised about the install difficulties, as we've put the code on several systems and never had a problem. -- Andy From achaljalan at yahoo.com Sat Mar 27 17:54:57 2004 From: achaljalan at yahoo.com (achaljalan at yahoo.com) Date: Sat, 27 Mar 2004 14:54:57 -0800 (PST) Subject: Regular Expressions Message-ID: <20040327225457.61257.qmail@web12826.mail.yahoo.com> Hey, I have a string s =740446505 "O'HANLON, Benjamin" i need to use one RE to convert it into (740446505, "O'HANLN", "Benjamin"), I am using python 2.3 and have been stuydin the various tutotrials and the howto websites for the past 3 days and haven't managed to find a solution. Any help to get to the solution will be very very helpful. Thanks in advance for all the help. Achal Jalan --------------------------------- Do you Yahoo!? Yahoo! Finance Tax Center - File online. File on time. -------------- next part -------------- An HTML attachment was scrubbed... URL: From roccomoretti at hotpop.com Wed Mar 17 14:22:30 2004 From: roccomoretti at hotpop.com (Rocco Moretti) Date: Wed, 17 Mar 2004 13:22:30 -0600 Subject: Python style guidelines In-Reply-To: References: <3064b51d.0403101112.3449e987@posting.google.com> <4050EAA3.9010807@wberry.org.x> <92c59a2c.0403122308.35513650@posting.google.com> Message-ID: Heather Coppersmith wrote: > On 12 Mar 2004 23:08:19 -0800, > jcb at iteris.com (MetalOne) wrote: >>Some guidelines recommend functions with only a single return >>point. I don't understand why this insanity got started. At >>one point it was recognized that multiple entry points into a >>function was confusing, but why did it have to get extrapolated >>to multiple exit points. Upon entry to a function, I sometimes >>like to verify that everything is ok before proceeding and if it >>is not just get out. Parameters can validated, resources >>acquired, or whatever. > > > It's that "resources acquired" part that messes people up. I've > seen it over and over and over again. Memory leaks. Dangling > pointers. Unrecoverable file handles. Especially as functions > that acquire lots of resources evolve over time and someone adds > code to acquire another resource or detect another error condition > and then doesn't find all the subsequent exit points. It's less > of an issue with languages with proper garbage collection, but it > can be a real nightmare in (e.g.) C or assembler. Unit tests that > cover all possible resource leaks are difficult to construct > correctly. C++ partially addresses the problem with RIAA (if > coders use it properly) and a hodgepodge of "smart" objects that > do pseudo self-garbage collection. Unfortunately, the way I've seen "single exit points" handled in complex functions is either to use a flag variable, which may or may not correspond to the temporary variable for storing the return value, or to enclose the whole function in an try: except block, raising a specialized exception to quit. Neither of these is too elegant in my opinion, and runs into the same problems seen with breaking out of deeply nested loops. (A suggestion for which on a recent thread, BTW, was to put them in a function and use return from multiple points). Perhaps someone should write up a PEP: def fun(params): #Function body finally: #Cleanup code Disavowing-all-responsibility-(Unless-Guido-likes-it)-ly'rs -Rocco From eniac at sdf-eu.org Wed Mar 24 10:56:59 2004 From: eniac at sdf-eu.org (Geiregat Jonas) Date: Wed, 24 Mar 2004 15:56:59 +0000 Subject: best module for parsing a small xml file Message-ID: <4061a11e$0$277$ba620e4c@news.skynet.be> What's the best module for pasring a small xml file ? From mcfletch at rogers.com Tue Mar 16 15:09:31 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Tue, 16 Mar 2004 15:09:31 -0500 Subject: embedding opengl in wxpython window [Re: Advice needed: large In-Reply-To: References: <5eb8fb88.0403151925.4f63842b@posting.google.com> Message-ID: <40575EFB.8020104@rogers.com> DH wrote: ... > I never installed OpenGL or GLUT. OpenGL comes with Windows. In > python 2.2 everything worked fine. Does the python 2.3 version not > weak link glut or something? No version of PyOpenGL 2.x has, to my knowledge, ever included GLUT. Could be you installed it without noticing? It's not a complex process after all, just drag a single DLL to a directory in the system path. I've been known to forget doing such things in the past. That said, could be that something is importing OpenGL.GLUT from the Python side that wasn't importing it before... don't know what that would be, though. Otherwise engaged at the moment, so little time to explore. Have fun, Mike _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From guy at NOSPAM.r-e-d.co.nz Wed Mar 24 20:25:22 2004 From: guy at NOSPAM.r-e-d.co.nz (Guy Robinson) Date: Thu, 25 Mar 2004 13:25:22 +1200 Subject: py2exe question Message-ID: I want to package a program (using py2exe) that utilises a number of python scripts so that people can't see or change the source code. But there is one python script containing some functions I do want the user to be able to change. Then when they run the program again these functions are available to the main program. Is this possible? How could I do it? Guy From skip at pobox.com Sun Mar 28 18:05:23 2004 From: skip at pobox.com (Skip Montanaro) Date: Sun, 28 Mar 2004 17:05:23 -0600 Subject: examples of doing syadmin activities as a web app In-Reply-To: References: Message-ID: <16487.23091.967564.114832@montanaro.dyndns.org> Dustin> I've looked at it briefly (if I recall it is written in Perl). Yes. Dustin> I may go back and investigate that more thoroughly but I still Dustin> wonder: Dustin> - Are there any Python based examples? Dunno. Dustin> - Is webmin well designed? (Not trying to troll, just curious if Dustin> it is well thought out or just a hack) I don't know that either, but I suspect that with its plugin architecture it's getting pretty mature. I've only ever used it as a side-effect of using NagMIN. Dustin> If any of you were to design such a beast (web based system Dustin> admin tool) from scratch which framework would you consider a Dustin> good match? I'd give Quixote a look, though all the other Python-based solutions in this space (Zope, Webware, etc) are probably all equally suitable. It probably depends mostly on what framework you're most comfortable with. Skip From mwilson at the-wire.com Tue Mar 16 12:48:18 2004 From: mwilson at the-wire.com (Mel Wilson) Date: Tue, 16 Mar 2004 12:48:18 -0500 Subject: loop scope References: Message-ID: In article , Jacek Generowicz wrote: >Imagine we have a "nested" keyword which is similar to "global", only >it ensures that the name is found in the nearest enclosing scope. Now >the above problem could be resolved by defining "inc" as follows. > > def make(): > x = 0 > ... > def inc(n): > nested x > x = x+n > ... > >Works just like global would have done, only it is aware of the >other socpes between local and global. > >> "Greg Ewing (using news.cis.dfn.de)" writes: >> >> > It wouldn't do to make the whole (non-comprehension) >> > for-loop a new scope, because that would make any >> > variables assigned within the loop body local as well. > >Not if you have a "nested" keyword at your disposal. > >What situations would this not cover ? Far too few. After the `nested x` statement comes `nested nested x` and `nested nested nested x`, with the accumulating maintenance headaches. All so that programmers can choose data names badly. Almost like running into `continue 17` within a nest of loops. Regards. Mel. From llothar at web.de Wed Mar 17 14:32:33 2004 From: llothar at web.de (Lothar Scholz) Date: 17 Mar 2004 11:32:33 -0800 Subject: fox 1.2.x and FXPy References: <4e1cc86c.0403151008.669e2e45@posting.google.com> Message-ID: <6ee58e07.0403171132.6c3f7f22@posting.google.com> katximan at gmx.net (Asier) wrote in message news:<4e1cc86c.0403151008.669e2e45 at posting.google.com>... > Is there any plan to make bindings of the future fox toolkit 1.2.x for > python? New widgets, antialiased fonts and so on is a "Good Thing". I don't think that Lyle will put more work in the project and it will be a lot of work to get 1.2.x running. Even the ruby bindings that are actively under development are still 1.0.x If you don't like GTK or WxWidgets you should look at the FLTK bindings. From ndeskins at ecn.purdue.edu Fri Mar 12 14:13:25 2004 From: ndeskins at ecn.purdue.edu (Aaron Deskins) Date: Fri, 12 Mar 2004 14:13:25 -0500 Subject: Simple file line reading Message-ID: <40520BD5.9090006@ecn.purdue.edu> Hello everyone, I'm relatively new to Python and am trying to write some scripts. I've written a program (with the help of a friend) to search a text file line by line for a certain section of information and then process some of that information. This was on machines with Python 2.2.1 and 2.3.2. When I try the same program on another machine using Python 2.1.2 and another with Python 1.5.2, the script does not work. I've isolated the part of the code giving me problems below. The code below should just print out a number for every line. The actual code has some other commands to run at each line of the code. I just want to read each line of the file, run some commands on the contents of that line, and stop when the end of the file is reached. import string it = 0 for line in open("OUTCAR"): it+=1 print it The error message is: Traceback (most recent call last): File "testr.py", line 3, in ? for line in open("OUTCAR"): TypeError: loop over non-sequence Thanks for your help. -- Aaron Deskins Graduate Student Chemical Engineering Purdue University From jcarlson at nospam.uci.edu Wed Mar 17 21:24:16 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Wed, 17 Mar 2004 18:24:16 -0800 Subject: Start and control an extern program In-Reply-To: References: <4051087D.1050409@zoran.com> Message-ID: > It wouldn't be portable to versions of Python that don't have threads, > one would suppose. > > Have you encountered such? Frequently? The only platform I've run into that doesn't support threads is Cygwin (a couple years back). I don't know if modern Python + Cygwin supports threads, so it may be worth checking. On the other hand, every version of Python I've used on linux since mid 2001 (Python 2.0 on linux kernel 2.4.x) has supported threads. - Josiah From newsgroups at jhrothjr.com Sat Mar 13 12:06:12 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 13 Mar 2004 12:06:12 -0500 Subject: Python Script for Running a Python Program over Different Files inthe Directory References: Message-ID: <1056ft6qik02gd3@news.supernews.com> "Shalen chhabra" wrote in message news:mailman.351.1079166133.19534.python-list at python.org... > Hey, > > Can anyone give me a snippet for running a python program over all the files > in the directory. > For ex: I have ten files in a directory and I want to run a python program > against all of these files, I wish to do the same using another python code > instead of running each of these files one by one, which would be cumbersome > giving the argv of each file every single time. > > This can be easily done using a shell script but I just wanted to have a > flavour of python for this. Given your reply to the attempts to help, I'm going to assume that what you want is to separate the actual manipulation of each file from the logic of determining which files to manipulate. If this isn't what you want, please stop reading now and don't bother to reply - it'll save both of us aggrivation. The answer to the problem is the visitor pattern. It's a standard pattern (see "Design Patterns" [GOF].) The directory program is: ---------- DirBase.py ------------------------ # Basic classes for file maintenance import os, stat, os.path class DirectoryList(object): def __init__(self, pathName): self.dirList = os.listdir(pathName) self.pathName = pathName self.dirList.sort() def walk(self, visitor): for fileName in self.dirList: filePath = os.path.join(self.pathName, fileName) fileStatus = os.stat(filePath) if stat.S_ISREG(fileStatus.st_mode): visitor.doFile(filePath, fileStatus) else: visitor.doDir(filePath, fileStatus) class cleanDirectory(object): def doFile(self, filePath, fileStatus): os.remove(filePath) def doDir(self, dirPath, dirStatus): DirectoryList(dirPath).walk(cleanDirectory()) os.rmdir(dirPath) def fetchFile(inDirPath, fileName): filePath = os.path.join(inDirPath, fileName) fileObj = open(filePath, 'rb') fileText = fileObj.read() fileObj.close() return fileText def fetchTextFile(inDirPath, fileName): filePath = os.path.join(inDirPath, fileName) fileObj = open(filePath, 'rt') fileList = fileObj.readlines() fileObj.close() return fileList def storeFile(fileText, outNameList, fileStatus): outFilePath = os.path.join(*outNameList) outFileObj = open(outFilePath, 'wb') outFileObj.write(fileText) outFileObj.close() os.utime(outFilePath,(fileStatus.st_atime, fileStatus.st_mtime)) def storeTextFile(fileList, outNameList, fileStatus): outFilePath = os.path.join(*outNameList) outFileObj = open(outFilePath, 'wt') outFileObj.writelines(fileList) outFileObj.close() os.utime(outFilePath,(fileStatus.st_atime, fileStatus.st_mtime)) ------------------------------------------------------------ An example of how to use it is: ----------- MyFileManipulationProgram.py --------------- # reorganize files captured from the *** web site import os, stat, os.path import re from DirBase import * def setUpOutdir(): DirectoryList("outDir").walk(cleanDirectory()) class copyPicture(object): def doFile(self, filePath, fileStatus): head, tail = os.path.split(filePath) fileText = fetchFile(head, tail) storeFile(fileText, ("outDir", "pics", tail), fileStatus) def doDir(self, dirPath, dirStatus): pass # precompile patterns used for multiple files script = re.compile(r"") meta = re.compile(r"") cmnt = re.compile(r"<\!--.*?-->") cmnt1 = re.compile(r"<\!--//-->") html = re.compile(r"\.html") class copyWebPage(object): def doFile(self, inFilePath, fileStatus): head, tail = os.path.split(inFilePath) fileName, extension = os.path.splitext(tail) inFileText = fetchFile(head, tail) print ("path: '%s' head: '%s' tail: '%s' name: '%s' ext: '%s'\n" % (inFilePath, head, tail, fileName, extension)) if extension == ".htm": inFileText = script.sub("", inFileText) #inFileText = meta.sub("", inFileText) inFileText = cmnt1.sub("", inFileText) inFileText = html.sub(".htm", inFileText) subPattern = "%s_files" % tail[:-4] inFileText = re.sub(subPattern, "pics", inFileText) storeFile(inFileText, ("outDir", tail), fileStatus) def doDir(self, dirPath, dirStatus): pass def main(inDirPath): DirectoryList(inDirPath).walk(copyWebPage()) if __name__ == "__main__": setUpOutdir() main(r"c:\mydirectory") ---------------------------------------------------------------------- I have any number of file fixup programs that use the same DirBase.py program. HTH John Roth > Thanks > Shalen From alx5962NOSPAN at yahoo.com Tue Mar 2 16:50:40 2004 From: alx5962NOSPAN at yahoo.com (Alex) Date: Tue, 2 Mar 2004 22:50:40 +0100 Subject: variable name using a for References: <4044d7f3$0$4664$626a14ce@news.free.fr> <1049mi9ktod7o35@corp.supernews.com> <4044e177$0$24960$626a14ce@news.free.fr> Message-ID: <404501c1$0$24935$626a14ce@news.free.fr> Sean you rock!!!!!!!! You solved my problem ! 1000 thank you are not enough ! :) Alex "Sean Ross" a ?crit dans le message de news:xv51c.8749$qA2.552179 at news20.bellglobal.com... > > "Alex" wrote in message > news:4044e177$0$24960$626a14ce at news.free.fr... > [snip] > > so in my code: > > for x in range(nbSujets): > > self.button1 = xbmcgui.ControlButton(50, 100, 40, 30, "B"+str(x) ) > > self.addControl(self.button1) > > for x in range(nbSujets): > button_name = "button%d"%x > setattr(self, button_name, xbmcgui.ControlButton(50, 100, 40, 30, > "B%d"%x )) > self.addControl(getattr(self, button_name)) > > > > From sean_berry at cox.net Tue Mar 30 01:15:37 2004 From: sean_berry at cox.net (sean) Date: Mon, 29 Mar 2004 22:15:37 -0800 Subject: A couple of Python CGI questions Message-ID: <9g8ac.65379$Bg.14309@fed1read03> I tried getting mod_python to work but have had lots of problems getting it running. So, I have settled on using python cgi. I have already got it going and it seems to run fast enough for me. My questions are: 1. Is there any way to access variables from within a string like perl cgi? I have found that the best way for me to write html tables is to use a print """""" string. That way I can write one print """, and then write html as if I were writing an html file. For example: print """
This is cool
""" I really like this and it is a lot like typing the following in Perl cgi: print < This is cool EOF So, is there any way to access variables from within the string, besides using %s? In perl, I just put the $variable in the string and it replaces the varname with the value. 2. Is there a good online resourse for pyton cgi? 3. How do you collect request variables from forms sent to the python cgi page, whether post or get? Thanks very much for the help... I will continue to google for my answers. Sean From aahz at pythoncraft.com Thu Mar 11 11:27:51 2004 From: aahz at pythoncraft.com (Aahz) Date: 11 Mar 2004 11:27:51 -0500 Subject: Python style guidelines References: <3064b51d.0403101112.3449e987@posting.google.com> <405035a3$1@pfaff2.ethz.ch> Message-ID: In article <405035a3$1 at pfaff2.ethz.ch>, Josef Meile wrote: > >I agree, those are good guidelines, but I don't agree with: > >- Don't compare boolean values to True or False using == (bool > types are new in Python 2.3): > > No: if greeting == True: > Yes: if greeting: > >What would happened if you do: > > >>> a='test' > >>> if a.find('foo'): >... print "foo was found" >... >foo was found >>> 'foo' in 'test' False -- 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 skip at pobox.com Sat Mar 27 09:04:58 2004 From: skip at pobox.com (Skip Montanaro) Date: Sat, 27 Mar 2004 08:04:58 -0600 Subject: examples of doing syadmin activities as a web app In-Reply-To: References: Message-ID: <16485.35338.556301.749395@montanaro.dyndns.org> Dustin> I'm looking for an example of a well designed web application Dustin> used to do sys-admin type functions. I think the most popular tool in this space is WebMIN . Skip From dave at pythonapocrypha.com Wed Mar 24 12:07:03 2004 From: dave at pythonapocrypha.com (Dave Brueck) Date: Wed, 24 Mar 2004 10:07:03 -0700 Subject: Python for large projects References: <1060p59d9rg9819@corp.supernews.com> <1080150619.4947.6.camel@wintermute.atriaky.sk> Message-ID: <01a101c411c2$6e797e00$6b1e140a@YODA> gabor wrote: > On Wed, 2004-03-24 at 15:16, Bill Rubenstein wrote: > > ...snip... > > > > other thing is, that in the projects i work on, there seems to be > > > > very hard to do unit tests > > ...snip... > > > > The ability to do unit testing should not be an afterthought. It should be > > considered as a major influence on the architecture of a project. > > > > If one cannot do proper unit testing, the architecture of the project is > > questionable. > > ok, so let's use a specific example: > > imagine you're building a library, which fetches webpages. > > you have a library which can fetch 1 webpage at a time, but it is a > synchronous library (like wget). you call him, and he returns the page. > > but you want an async one. > > so you decide to build a threadpool, where every thread will do this: > look into a queue, and if there is a new URL to fetch, fetches it with > his wget-like library, and saves the html page somewhere (and maybe > signals something). > > and now the user who uses your library, simply adds the URL to fetch, > and can check later asynchronously whether they are already fetched or > not. > > could you tell me what unit tests would you create for this example? Which unit tests you create depends on the structure of your library and what APIs it exposes, but FWIW we test stuff like this all the time (although some people might call our tests involving the other side of the network connection "system tests" - I don't care as the point is that it detects regression and ensures correct functionality). The nightly batch fires up a very simple Python server (we pass in the host and port to pind to on the command line) and we encode in the URLs commands telling the server how to respond, e.g. http://127.0.0.1:4000/cmd_timeout_10/foo.avi # instead of responding, sleep for 10 seconds to test client timeouts http://127.0.0.1:4000/cmd_mb_1/bar.avi # return a 1 MB file http://127.0.0.1:4000/cmd_redir_www.google.com/baz.avi # return an HTTP redirect to www.google.com http://127.0.0.1:4000/cmd_mb_2/cmd_dropconnafter_500k/bleh.txt # return a 2 MB response, but drop connection after 500k bytes http://127.0.0.1:4000/cmd_shutdown/biff.avi # shut down the server This server is trivial to write - it just splits the URLs by '/' and interprets any 'cmd_' portions and generates an appropriate response. Anyway, with something like that in place you can then proceed to test all sorts of things in your library. A lot of your tests won't require a server at all since they will be testing how your library reacts to poor inputs, but for the tests that do require a server you have a block of tests like: ADDR = '127.0.0.1', 4000 StartListenServer(ADDR) # spawns the server process # all of your tests that require a remote server to be present StopListenServer(ADDR) Whatever your file fetching tool does, you can test. -Dave From jcarlson at uci.edu Wed Mar 31 04:52:38 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Wed, 31 Mar 2004 01:52:38 -0800 Subject: Why '==' ?? In-Reply-To: <8089854e.0403302319.1ab56af0@posting.google.com> References: <8089854e.0403302319.1ab56af0@posting.google.com> Message-ID: > if a = 3 > print 'Yeah baby' > > are still *unambiguous*.... yet the interpreter refuses to understand > you...... Oh, the CPython interpreter understands you, it just doesn't like what you say. I (and I'm sure the majority of other Python users) agree with the interpreter, your modified syntax leaves something to be desired. You syntax also /makes ambiguous/ the following currently valid Python syntax... if a == 3: \ print "hello" If we converted that to /your/ syntax, it would read... if a = 3 \ print "hello" Which would get internally translated to... if a = 3 print "hello" I don't think it makes sense, and I wouldn't expect an interpreter to think it makes sense of it either. > Theres no reason why a single '=' shouldn't be understood in a > conditional.... Except that it would be a 'special case' when two different syntactical symbols mean the same thing. "Special cases aren't special enough to break the rules." - The Zen of Python, by Tim Peters > As for needing a ':' to allow statements after a 'def' or a > conditional.... python already has the ';' for that... why insist on a > ':' Do you even read the docs? Python does not have ';' to allow statements after a def, Python has ';' because it allows you to place more than one statement on a single line. That is, it allows... a = 1;b = 2;c = 3; /not/ because it allows the absolutely ugly: def fun(a,b): print a,; print b; You should note that ':' is placed in syntactically different locations than ';', because they have syntactically different meanings. ':' means "there is some scope that is being enclosed", while ';' means "that is the end of the previous statement". - Josiah From fpetermaas at netscape.net Thu Mar 18 06:01:18 2004 From: fpetermaas at netscape.net (Peter Maas) Date: Thu, 18 Mar 2004 12:01:18 +0100 Subject: float problem In-Reply-To: References: Message-ID: Tomasz Stochmal schrieb: > The problem is that when I call float('713566671863.6850') I get > 713566671863.68506 - when rounding to 4 becomes 713566671863.6851 > > Output becomes 7135666718636851 but it should be 7135666718636850 > > Last digit is 1 but should be 0 which is wrong ! > > How do I do it ? I think it' impossible because you operate at the border of the IEEE754 float8 precision. struct.pack("d", 713566671863.68506) and struct.pack("d", 713566671863.6851) will yield the same result: '\xec\xf5~j|\xc4dB' which means that the two float literals are represented by the same 64bit string. I you want arbitrary precision use Python's long integers. 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 gandalf at geochemsource.com Fri Mar 19 12:30:37 2004 From: gandalf at geochemsource.com (Gandalf) Date: Fri, 19 Mar 2004 18:30:37 +0100 Subject: lambda trouble References: Message-ID: <405B2E3D.6040807@geochemsource.com> Darabos Daniel wrote: >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: > Well, it is not suprising. In a lambda expression, everything after the : is symbolic. It is compiled, not evaluated. You can use a named function instead of an unnamed one: [GCC 3.3.3 [FreeBSD] 20031106] on freebsd5 Type "help", "copyright", "credits" or "license" for more information. >>> def p(x): ... print x ... >>> l = [] >>> for i in range( 5 ): ... def func(): ... p(i) ... l.append( func ) ... >>> for k in l: ... k() ... >>> l [, , , , ] >>> You have different functions. However, in every function, the name 'i' is not a local name. (Python has only two levels: local and global.) Here is another solution. However, it uses eval. Probably, it is not the fastest one. def p(x): print x l = [] for i in range( 5 ): l.append(eval("lambda: p( %s )"%i)) for k in l: k() Udv, Laci From beliavsky at aol.com Wed Mar 10 14:12:37 2004 From: beliavsky at aol.com (beliavsky at aol.com) Date: 10 Mar 2004 11:12:37 -0800 Subject: Python style guidelines Message-ID: <3064b51d.0403101112.3449e987@posting.google.com> Is there a more recent set of Python style guidelines than PEP 8, "Style Guide for Python Code", by van Rossum and Warsaw, at http://www.python.org/peps/pep-0008.html , which is dated July 5, 2001? From shalen_itbhu at hotmail.com Sat Mar 13 03:22:09 2004 From: shalen_itbhu at hotmail.com (Shalen chhabra) Date: Sat, 13 Mar 2004 08:22:09 +0000 Subject: Python Script for Running a Python Program over Different Files in the Directory Message-ID: Hey, Can anyone give me a snippet for running a python program over all the files in the directory. For ex: I have ten files in a directory and I want to run a python program against all of these files, I wish to do the same using another python code instead of running each of these files one by one, which would be cumbersome giving the argv of each file every single time. This can be easily done using a shell script but I just wanted to have a flavour of python for this. Thanks Shalen _________________________________________________________________ Fast. Reliable. Get MSN 9 Dial-up - 3 months for the price of 1! (Limited-time Offer) http://click.atdmt.com/AVE/go/onm00200361ave/direct/01/ From mariube+netnews+ at ifi.uio.no Tue Mar 30 13:57:04 2004 From: mariube+netnews+ at ifi.uio.no (Marius Bernklev) Date: Tue, 30 Mar 2004 20:57:04 +0200 Subject: Equality and identity Message-ID: <3cfvfkmi337.fsf@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 But that isn't true for tuples: >>> (5,2) == (5,2) True >>> (5,2) is (5,2) False Why not? Are tuples mutable in some way I've missed, or are there other reasons for this behaviour? To me, it seems natural to concider (5,2) and (5,2) the same object, just like "5,2" and "5,2". Marius -- "Who needs crypto WYCWLT?" -- William Newman From claird at lairds.com Sun Mar 28 08:13:38 2004 From: claird at lairds.com (Cameron Laird) Date: Sun, 28 Mar 2004 13:13:38 -0000 Subject: os module question References: <7vt9c.49985$Bg.5493@fed1read03> Message-ID: <106djs2148g9g1a@corp.supernews.com> In article , Miki Tebeka wrote: >Hello Sean, > >> os.system() always seems to return all output so I don't know why that >> doesn't work. >The return value is the exit status. > >Miki ... which leaves the question of what *will* satisfy Rasputin. While I don't seem to have fortune(1) on any of my hosts today, I believe import os print os.popen("fortune -f").read() is it. -- Cameron Laird Business: http://www.Phaseit.net From simonb at NOTTHISBIT.webone.com.au Tue Mar 16 16:15:23 2004 From: simonb at NOTTHISBIT.webone.com.au (Simon Burton) Date: Wed, 17 Mar 2004 08:15:23 +1100 Subject: list inheritance or delegation? References: <78b6a744.0403161251.34fad544@posting.google.com> Message-ID: On Tue, 16 Mar 2004 12:51:15 -0800, george young wrote: > [python 2.3.3, x86 linux] > I need an object that behaves much like a list, but has some additional > features. It seems that I can do this either by inheriting from type > list, or by emulating list by defining __len__, __getitem__, and maybe a > bunch of other methods. Thirdly, I could inherit from UserList, but > that's deprecated now. > > Inheriting from list would save me implementing a bunch of methods that I > might want. But if I inherit from list, how do I get access to the data? > E.g., I need a customized 'setitem' method that does the insert and then > does some other things too. With UserList, I could: > > class mylist(UserList): > def __setitem__(self,i,y): > self.dostuff(y) > self.data[i]=y > > but when inheriting from 'list', I'm not sure how to do this. > class mylist(list): def __setitem__(self,i,y): self.dostuff(y) list.__setitem__(self,i,y) same with __init__ etc. > I couldn't find anything in the docs about inheriting from builtin types, > though it seems to be an encouraged practice. It seems like if one is > encouraged to inherit from builtins, there needs to be at least a concise > description of the 'inheritable api' for each such type. E.g. does > __init__ or __new__ handle initial values. Maybe I'm just missing > something obvious... > > So, I'm asking: > 1) what are the issues/tradoffs between inheriting from list and emulating > it with my own methods referencing a list data member. One drawback is you (may) have to override all list methods, rather than leave them undefined. The slicing stuff is particularly hairy. Simon. > > 2) how do I get enough access to list's data to do the inheritance. > > 3) I'm whining about lack of documentation for #2. > > Thanks, > George Young From mark at prothon.org Tue Mar 30 01:36:55 2004 From: mark at prothon.org (Mark Hahn) Date: Mon, 29 Mar 2004 22:36:55 -0800 Subject: Prothon Prototypes vs Python Classes References: <569c605ld1cj8fc1emolk08ete0s1prls1@4ax.com> <106di86neu1qh4d@news.supernews.com> Message-ID: A2. People that bitch about top-posting. "Aahz" wrote in message news:c4akqh$gml$1 at panix2.panix.com... > In article , > Mark Hahn wrote: > > > >I didn't know I was going the opposite direction from Python. I guess I'll > >have to change that. > > > >I guess I didn't make it clear that no design decisions were frozen in the > >language. > > A: Because it messes up the order in which people normally read text. > Q: Why is top-posting such a bad thing? > A: Top-posting. > Q: What is the most annoying thing on usenet? > -- > Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ > > "usenet imitates usenet" --Darkhawk From elainejackson7355 at home.com Sat Mar 20 23:42:47 2004 From: elainejackson7355 at home.com (Elaine Jackson) Date: Sun, 21 Mar 2004 04:42:47 GMT Subject: lambda trouble References: Message-ID: The problem, they say, is that a variable in a FOR clause can't bind a variable inside a lambda abstraction. Fortunately the lambda operator itself doesn't share this limitation, so you can make the variable visible to the binder in the FOR clause by binding with a lambda and then evaluating the resulting abstraction at the variable in question, like so: >>> def p(x): print x >>> list=[] >>> for i in range(5): list.append((lambda j: lambda: p(j))(i)) >>> x=map(lambda f: f(),list) 0 1 2 3 4 Or, more concisely, >>> def p(x): print x >>> list=[(lambda j: lambda: p(j))(i) for i in range(5)] >>> x=map(lambda f: f(),list) 0 1 2 3 4 From alexander.dejanovski at laposte.net Thu Mar 4 09:29:59 2004 From: alexander.dejanovski at laposte.net (Alexander DEJANOVSKI) Date: Thu, 04 Mar 2004 15:29:59 +0100 Subject: ANN : JyRetic 1.0RC4, Retic Admin 1.3 and Retic SOAP 0.3 released Message-ID: <5.1.0.14.2.20040304152945.01f4d128@127.0.0.1> JyRetic 1.0RC4, Retic Administrator 1.3 and Retic SOAP Tester 0.3 were just released. (http://retic.sourceforge.net) Changes are : Retic Admin 1.3: - New : popup menus have appeared to ease operations (try right-clicking on lists and trees), especially adaptor design. - New : possibility to subscribe to get a notice on adaptor end, through a Jabber message (Email will come in future releases) - Improvement : Refresh schedule is now threaded and non-blocking. You can then set auto-refresh on, while you'll be able to work on other tabs without being interrupted - New : Images in Running/Terminated adaptors tracking let you know the execution status - New : Terminated adaptors can be filtered according to end date/hour and/or status - New : Partial internationalization support (french and english supported, through languages files) => All texts haven't been translated yet. JyRetic 1.0RC4 : - Bug fix : ToXML pipe didn't work because of an internal type mismatch - Bug fix : Scheduler didn't want to add recurrent events if there were none already scheduled - Bug fix : SQLSource didn't properly close the JDBC connection (which didn't prevent it from working) - Bug fix : Jabber communications with the server are back up - Improvement : SQLSink threaded inserts now use persistent connections overall adaptor execution (instead of opening/closing connection for each message) - Some other small bug fixes I might forget. - Improvement : Support for Xindice 1.1 (to use prior versions of Xindice, place the right libs in the javalib dir and modify jython.bat or jython.sh to include them in the local classpath) Retic SOAP 0.3 : Major bug fix that prevented from generating correct SOAP Envelopes on some SOAP implementations. ============================================================= WHAT IS RETIC ? Retic is an EAI Server. The aim is to permit applications to communicate, even if they don't speak the same language (which means transport protocols as well as data structures). This is done by building adaptors. An adaptor is composed of : - One source - Several pipes (process data transformations) - Several sinks (destination of data) - Several loggers (using log4j) - Preprocessors (executed only once before adaptor execution - for example => drop/create a table through a SQL query) - Postprocessors (executed only once after adaptor execution - for example => creation of an index on a table through a SQL query) It is written in Jython and works 100% fine with only Java 1.3+ installed (although some libs like cocoon.jar and poi-block.jar might only work on Java 1.4, delete them in case you can't upgrade) on your system (jython 2.1 is embedded in the releases). It provides connectivity with : JMS, HTTP, SOAP, UDDI, FTP, Xindice, JDBC, Jabber, SMTP and more... ============================================================= Enjoy !! PS : I'd need some help to restart the Python version of Retic. Anyone interested in contributing should contact me. From donn at u.washington.edu Mon Mar 29 15:04:58 2004 From: donn at u.washington.edu (Donn Cave) Date: Mon, 29 Mar 2004 12:04:58 -0800 Subject: process wrapper? References: <5ficndxjntWG4frd38DK-w@speakeasy.net> <1080539401.173853@yasure> Message-ID: In article , "Steve @ Waypath" wrote: > Thanks for the reply. I haven't yet implemented a working spawnv call, so > I'm not confident my tests are valid. Here's a sample: > > ########## > File: test1.py > ------------ > import os, time > if __name__=='__main__': > os.spawnv(os.P_NOWAIT,'python',['test2.py']) OK, that can be fixed. When the documentation says "path" for some functions, and "file" for others (e.g., spawnvp), the distinction is that "path" includes the directory specification, either absolute or relative to the current working directory. spawnv wants a path, so the above doesn't work unless "python" is a file in your current working directory. To resolve this problem, I would just write in the absolute path, or you may use spawnvp instead. But don't give it python's path. Instead, at least consider invoking the Python program file directly - put its path there as the 2nd parameter, not python's. Then your argument list (the 3rd parameter) will be correct as written. If you invoke python itself, then you'll need to make test2.py the second argument, directing python to interpret that file. If you decide to do as I suggest, test2.py will have to be executable (chmod 755) and start with a line like "#!/usr/bin/python", as appropriate for your system. From there on, your test1.py program no longer needs to know how test2.py is actually implemented. > ########### > While test 1 is running, a ps (in another shell): > # ps x | grep python > 11726 pts/1 S 0:00 python test1.py > 11727 pts/1 Z 0:00 [python ] > 11729 pts/2 S 0:00 grep python > > ########### > I see this defunct thing with every spawnv test I try. The defunct process > goes away when the calling process (test1.py, in this case) finishes. Where > am I going wrong here? It's a zombie! UNIX leaves a dead process in the table as long as its parent might come back and ask for the status. It goes either when the parent gets its status with a wait function (like waitpid()), or when the parent exits. Donn Cave, donn at drizzle.com From yan at NsOeSiPnAeMr.com Mon Mar 8 18:53:49 2004 From: yan at NsOeSiPnAeMr.com (Kamus of Kadizhar) Date: Mon, 08 Mar 2004 18:53:49 -0500 Subject: Unicode (Japanese) fonts in Images References: Message-ID: On Mon, 08 Mar 2004 22:12:32 +0000, Rich wrote: > Am I doing anything obviously wrong? I can't help you with the specifics, but make sure you're not confusing UTF-8 encodings (strings) with unicode (integers). That one's bitten me in the butt more than once. Also, pango might help, though I don't know if it will do what you need. http://www.pango.org/ --Kamus -- o__ | If you're old, eat right and ride a decent bike. ,>/'_ | Q. (_)\(_) | Usenet posting` From extern.mustafa.goermezer at volkswagen.de Tue Mar 2 06:44:12 2004 From: extern.mustafa.goermezer at volkswagen.de (Goermezer, Mustafa (PROSTE)) Date: Tue, 2 Mar 2004 12:44:12 +0100 Subject: Converting office files to PDF Message-ID: Hello, with CoInitializeEx it is possible for word, excel or powerpont to run in multiple instances. So you can build a webbased converter to convert Office documents with spyce and mod_python (I have tested it, it runs fine !): Example for multiple instances: pythoncom.CoInitializeEx(pythoncom.COINIT_APARTMENTTHREADED) myWord = win32com.client.DispatchEx('Word.Application') myWord.Application.ActivePrinter="Printer name" myDoc = myWord.Documents.Open("filename.doc", False, False, False)#please see VBAWD10.CHM in Office directory myDoc.Saved=1 myWord.PrintOut(True, False, 0, "postscriptfile.ps") ##please see VBAWD10.CHM in Office directory while myWord.BackgroundPrintingStatus > 0: time.sleep(1) myDoc.Close() myWord.Quit() del myDoc del myWord Ghost() #ghostscript-command to convert created postscript file to PDF pythoncom.CoUninitialize() A ready script to convert files in commandline is on my homepage www.goermezer.de. Python rulez !!! Mustafa From donn at u.washington.edu Thu Mar 4 15:42:00 2004 From: donn at u.washington.edu (Donn Cave) Date: Thu, 04 Mar 2004 12:42:00 -0800 Subject: Redirecting stdout and stdin References: Message-ID: In article , Matthew Thorley wrote: > 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. As suggested in another followup, you may need some type of "expect" interface to deal with ssh's password prompt, because ssh needs a tty device there. It turns off tty echo, and may not be willing to proceed if the (pipe) device can't handle that ioctl. It also needs a distinct source for the password input, because it's supposed to read up stdin input and copy it to the remote sshd, so it will open /dev/tty for the password. If this sounds like a lot of trouble, it's really worse than it sounds. Ssh can authenticate other ways besides passwords, and that's really worth considering. In that case you can use plain popen (instead of popen2 which you evidently were using above), and stdout will not show up on the terminal (as it wasn't in your experiment above - that was stderr.) Donn Cave, donn at u.washington.edu From skip at pobox.com Sun Mar 28 18:18:02 2004 From: skip at pobox.com (Skip Montanaro) Date: Sun, 28 Mar 2004 17:18:02 -0600 Subject: xmlrpc, httplib and SSL In-Reply-To: <000d01c4144b$67dbd760$3501a8c0@rogersqyvr14d3> References: <114d01c41448$4433c1e0$0000fea9@dell8200> <000d01c4144b$67dbd760$3501a8c0@rogersqyvr14d3> Message-ID: <16487.23850.656173.195877@montanaro.dyndns.org> Roger> I did, except the base implementation can't be called. It hs Roger> this line of code in it: Roger> self.connection.shutdown(1) Roger> ie it will close the connection after every response, no matter Roger> what. Can you submit a patch to SF which abstracts that into its own method ("end_request" or something similar?) which can be overridden. ... [snip] ... Roger> It isn't that trivial. See also previous comment about all the Roger> pieces of code that try to use connections etc at most once. That sounds like the main problem. Sounds like getting the shutdown() call into its own overridable method would help a lot. Skip From peter at semantico.com Fri Mar 12 04:50:52 2004 From: peter at semantico.com (Peter Hickman) Date: Fri, 12 Mar 2004 09:50:52 +0000 Subject: Extending Python Syntax with @ In-Reply-To: <1051159aq8rifd0@corp.supernews.com> References: <40507cd4$0$15845$afc38c87@news.easynet.co.uk> <1051159aq8rifd0@corp.supernews.com> Message-ID: <405187fd$0$2803$afc38c87@news.easynet.co.uk> Cameron Laird wrote: > Forth. Lisp. Tcl. I was thinking of even less than that. Just define a few flow control things and get everything out of the objects. I expect it would look either like lisp or smalltalk. There would only be one built in datatype, the message, and all the objects would chuck messages around. Thus the language as such would have a very limited syntax. load Object.class; load Stream.class; x = new Object; s = new Stream; s.print x.to_string; So we have declare variables, load classes and pass messages. From claird at lairds.com Tue Mar 23 11:24:09 2004 From: claird at lairds.com (Cameron Laird) Date: Tue, 23 Mar 2004 16:24:09 -0000 Subject: Python for large projects References: Message-ID: <1060p59d9rg9819@corp.supernews.com> In article , Dave Brueck wrote: >Piet wrote: >> >>>>> Jacek Generowicz (JG) wrote: >> >> JG> I feel honour-bound to point out that citing static typing (explicit >> JG> static typing, in particular) as a means of creating more correct >> JG> programs, to be one of the greatest contemporary myths of software >> JG> engineering. . . . >I'm not familiar enough with some of the more modern languages that use >explicit static typing to know if they offer other advantages beyond helping >the compiler be more efficient, but from experience I don't hesitate to say >that the explicit type systems of Pascal/C++/Java seem to do more harm than >good (meaning that if they provide some benefit, overall it's still a net >negative due to the extra burden they place on the developers). For large >projects in particular they seem to get in the way more and more as the project >increases in size. > >-Dave > > I want to call attention to this. Dave and I appear to be in agreement that, while common wisdom in our field is that C++, Java, and so on, are serious languages that are the only realistic choices for large projects, we are both saying that they're at a particular DISadvantage there. If you have a big job, you *particularly* need to look at Python (or Erlang, or Eiffel, or ...) -- Cameron Laird Business: http://www.Phaseit.net From xpythonist at yahoo.com.br Thu Mar 18 08:59:28 2004 From: xpythonist at yahoo.com.br (=?iso-8859-1?q?Aloysio=20Figueiredo?=) Date: Thu, 18 Mar 2004 10:59:28 -0300 (ART) Subject: dictionary wart In-Reply-To: <6b17fa95.0403180441.a747b15@posting.google.com> Message-ID: <20040318135928.12147.qmail@web61002.mail.yahoo.com> Why don't you extend the dict type to have your custom behaviour? >>> class mydict(dict): ... def __init__(self, args, default): ... dict.__init__(self, args) ... self._default = default ... def __getitem__(self, item): ... return self.get(item, self._default) ... >>> x = mydict({'a' : 1, 'b' : 2}, 'default') >>> x['a'] 1 >>> x['b'] 2 >>> x['foo'] 'default' >>> --- Jesper Olsen escreveu: > Does python have a way of defining a dictionary default? > I think not, but are there any plans to incorporate it? > > Intuitively I would imagine that > > a={} > a.set_default(my_default) > > would do this -ie. a[my_new_key] should now return the the default > value my_default instead of creating an exception. This would be > similar to how it is done in other languages, eg. Ruby: > > a={} > a.default=value > > But surprisingly, in python set_default is a dictionary method used > for looking up a key... > > Jesper > -- > http://mail.python.org/mailman/listinfo/python-list ______________________________________________________________________ Yahoo! Mail - O melhor e-mail do Brasil! Abra sua conta agora: http://br.yahoo.com/info/mail.html From try_vanevery_at_mycompanyname at yahoo.com Mon Mar 22 21:46:00 2004 From: try_vanevery_at_mycompanyname at yahoo.com (Brandon J. Van Every) Date: Mon, 22 Mar 2004 18:46:00 -0800 Subject: 3D apps in Python? References: Message-ID: Mike C. Fletcher wrote: > > However, these engines (save maybe ZOE, about which I know next to > nothing) are focused primarily on teaching, rather than game or > application development. Particularly given your legendarily high > standards, I think you'll find that none are sufficient for your needs > wrt building practical 3D apps in Python. The collective wisdom on > that would seem to be "wrap a C/C++ engine if you need any sort of > interactive speed on a non-trivial application". Yes, that is looking like the task before me. I haven't found 3D anything - app, engine, whatever - that is truly Python-oriented for its development. Python is viewed by the 3D world as a scripting language, not a development language. > If you do find any other engines, consider adding them to the list > here: http://www.py3d.org/py3d_zwiki/Python3dLinks > (the formatting is messed up, but the information is often useful). Thanks for this link. Somehow, I have missed it in all the archive and Google hunting. -- Cheers, www.indiegamedesign.com Brandon Van Every Seattle, WA "Troll" - (n.) Anything you don't like. Usage: "He's just a troll." From Bill Sun Mar 14 02:05:14 2004 From: Bill (Bill) Date: Sat, 13 Mar 2004 23:05:14 -0800 Subject: List append help Message-ID: <105811aq55rah53@corp.supernews.com> I am trying to do an exercise in an online tutorial that but the tutorial does not list the solution. Could someone please tell me why the "hireCrew" method in the following code leaves me with a list that contains "None"? Be nice, this is my first go at this, thanks! class Organization: def __init__(self, argName, argLeader, argCrew): self.myName = argName self.myLeader = argLeader self.myCrew = argCrew def getName(self): return self.myName def setLeader(self, argLeader): self.myLeader = argLeader def getLeader(self): return self.myLeader def getCrew(self): return self.myCrew def hireCrew(self, argHire): self.myCrew = self.myCrew.append(argHire) return self.myCrew x = Organization("MyOrg", "JB", ["TL", "BK"]) print x.getName(), x.getLeader(), x.getCrew() x.hireCrew("PD") print x.getName(), x.getLeader(), x.getCrew() From newsgroups at jhrothjr.com Mon Mar 22 08:37:46 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 22 Mar 2004 08:37:46 -0500 Subject: PEP 318 References: Message-ID: <105tr24i9fak784@news.supernews.com> "Jacek Generowicz" wrote in message news:tyfisgx6wfo.fsf at pcepsft001.cern.ch... > Nicolas Fleury writes: > > > I've given some Python courses, and the first reaction when showing > > a class with some methods is something like "so I guess when the > > first parameter is not named 'self' it makes a class method?". > > Just as a point of information: > > I teach Python courses ... hands-on interactive style ... class size = > 12 ... I've given 8 of these so far ... I have _never_ had this > reaction. (80% of the students have previous C++ and/or Java > experience, and usually someone asks "How do I do class/static > methods?".) > > Maybe the reason nobody believes this is because, fairly early on in > the treatment of classes, I point out that there is nothing special > about the name "self", but I usually ask the students what they make > of it, before offering any of my own comments. Excellent class design! When I was doing classes, I found one of the most important questions I could ask myself in the after-the-class analysis was "what could I have said earlier that would have dealt with this question / confusion?" > > If easing the creation of class methods is so important, I would > > prefer a more radical approach with a end result that would be more > > intuitive to newcomers: > > While I agree that there is a lot to be said for Python being guided > by the principle of least surprise, I would argue against letting > Python be shaped by the expectations of people whose expectations have > been moulded by Java and C++, as those expectations are typically > fundamentally flawed, and certainly inappropriate to Python. (For > example, most (Java and C++ people, and hence generally most) people > expect there to be access control, and hundreds of getters and setters > all over the place. We do _not_ want this in Python. Etc., etc.. > > > - Give a warning for all methods with first parameter not named "self" > > in next versions of Python. > > That would be acceptable ... Only if the intention is to move to making it a built-in. Otherwise there really are people who use some other name than self (usually to save keystrokes.) > > - In a future major version of Python, 3 or 4, self becomes a keyword > > and a first parameter named otherwise implies a class method (I > > understand it could mean a lot of changes in code not using self). > > ... that would (IMHO) not. John Roth From halloleo at noospaam.myrealbox.com Wed Mar 10 18:19:24 2004 From: halloleo at noospaam.myrealbox.com (leo) Date: Thu, 11 Mar 2004 10:19:24 +1100 Subject: ta (was Re: cmdline args to a piped python prog) References: Message-ID: thanks a lot, piet. leo "Piet van Oostrum" wrote in message news:wzvfld3rl2.fsf at ordesa.cs.uu.nl... > >>>>> "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 salvatore at nolog.org Thu Mar 11 18:46:31 2004 From: salvatore at nolog.org (Salvatore) Date: Fri, 12 Mar 2004 00:46:31 +0100 Subject: Create static method dynamically In-Reply-To: References: Message-ID: As I always say, the beauty is in the simplicity :-) Thank you very much Peter Regards Salvatore From claird at lairds.com Sun Mar 14 15:55:35 2004 From: claird at lairds.com (Cameron Laird) Date: Sun, 14 Mar 2004 20:55:35 -0000 Subject: Extracting info from OS/hardware References: Message-ID: <1059hm7s63ebh4f@corp.supernews.com> In article , Thomas Weholt <2002 at weholt.org> wrote: >I need a piece of code to extract as much info about OS, current status and >hardware from a machine as possible ( at least, all available partitions and >free space on these, CPU-speed, free/total memory and stuff like that ) at >one given moment on Linux and Windows. > >Any hints? Can I call something in win32all on Windows or read some file on >linux? I'm not sure where to begin. . . . I was hoping someone else would answer this. My impression is that there are dozens of answers to this. I know I've seen quite a few such utilities advertised in places like Freshmeat. I haven't kept track of them at all. "... as much info ... as possible ...": whoooo! Usually when a manager says that to me, I ask for how much he's willing to pay. As it turns out, notions like "free space", "CPU speed", and so on are surprisingly poorly standardized. It's far from clear what they mean for any particular platform. Sooooooo, what I usually do is define my requirements carefully, and write up my own tool. -- Cameron Laird Business: http://www.Phaseit.net From ieyf4fu02 at sneakemail.com Mon Mar 29 00:36:47 2004 From: ieyf4fu02 at sneakemail.com (Greg Ewing (using news.cis.dfn.de)) Date: Mon, 29 Mar 2004 17:36:47 +1200 Subject: A 'Python like' language In-Reply-To: References: <40645d8f$0$10775$afc38c87@news.easynet.co.uk> <95aa1afa.0403262049.4b2a6f78@posting.google.com> Message-ID: Jon Franz wrote: > What I found interesting was: > - native threads via locks on each object Presumably this is bearable because of the lack of reference counting, so that objects don't need to be locked and unlocked at too frantic a rate. But I wonder what effect the lack of reference counting has on cache-friendliness of the memory management system. > - the stackless-ness I wonder what effect that has on the ability of C code to make callbacks into the interpreter. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From dmq at gain.com Mon Mar 22 13:53:23 2004 From: dmq at gain.com (David MacQuigg) Date: Mon, 22 Mar 2004 11:53:23 -0700 Subject: explicit variable scoping References: Message-ID: On Mon, 22 Mar 2004 03:19:46 -0800 (PST), Eyal Lotem wrote: [snip motivation for changing the scope rules] >A) Only get rid of the assignment-makes-local >heuristic, by changing the meaning of the "global" >keyword: > >def f(): > global.a = 1 # Assigns to the module.a > a = 2 # Assigns to a local variable > >This allows accessing globals, and IMO serves for >better explicitness about variables which is very >desirable and consistent with instance variable >access. I'm not seeing much advantage over: global a; a = 1 When you say "accessing" globals, we need to distinguish between "referencing" and "setting". Referencing globals is already automatic. Setting globals needs special syntax. For the few times I need to set global variables, I'm not feeling much need for streamlining the existing syntax. Most of my use of global variables is global within a named module. In this case, I refer explicitly to the module name. e.g. M1.a = 1 So the improvement above would apply only to the case where you need to set global variables in the main module. [snip how to migrate old code] >B) Create a hierarchy of "locals" for nested scopes, >which are accessible via an overloaded or new keyword >thus: > >I) > b = 1 > def f(): > a = 2 > def g(): > global.a = 3 > global.global.b = 4 Ugh!! >II) > b = 1 > def f(): > a = 2 > def g(): > parent.a = 3 > global.b = 4 > What about aunts and uncles? :>) I'm not feeling much need to set variables other than local or global, but I can see where this might be useful to someone. The tradeoff is convenience for a few vs a mess from lots of users who will abuse the flexibility. (The same kind of tradeoff as with the GOTO statement.) I would not give up *essential* flexibility for this reason, but we are talking here of just a convenience. If we want to set variables in intermediate scopes, I would prefer a syntax like: b = 1 def f(): a = 2 def g(): global.f.a = 3 global.b = 4 Of course, this means we also have to allow functions to have attributes. If we are going to make one more change in the scope rules, I would like to see a grand simplification -- the current rules are good, just extend them to *any* nested scopes. If I set up a hierarchy of 7 nested classes, I should be able to reference variables at a higher level without fully qualified names. Again, this is just a convenience. Mainly, it would make teaching Python simpler. -- Dave From steve at ninereeds.fsnet.co.uk Fri Mar 5 10:17:51 2004 From: steve at ninereeds.fsnet.co.uk (Stephen Horne) Date: Fri, 05 Mar 2004 15:17:51 +0000 Subject: Again: Please hear my plea: print without softspace References: <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> <3o9f40tpvn2bj29p5g23i4et9hv3qii4hu@4ax.com> <40483f1e.4458859@news.t-online.de> Message-ID: On Fri, 05 Mar 2004 08:50:50 GMT, m.bless at gmx.de (Martin Bless) wrote: >[Stephen Horne ] > >>Easy solution - write your extender such that it takes the original >>file in the constructor... >> >> sys.stdout = ExtendedFile (sys.stdout) > > >Hhm, > >>>> import sys >>>> class MyFile(sys.stdout): >... pass >... >Traceback (most recent call last): > File "", line 1, in ? >TypeError: file() argument 2 must be string, not tuple >>>> > >what do you mean? > >mb - Martin Bless I think I was being stupid. The stuff about 'constructor' and 'inheritance' seemed right when I hadn't thought it through, of course. I was intending inheritence from the file class, but since when do you specify a particular instance to 'inherit' from in the constructor??? Probably I need a brain test! The obvious alternative is to try to add an extra method to sys.stdout, but this doesn't work out - I assume the dictionary of attributes for file has been fixed. Replacing sys.stdout.write doesn't work - how does the replacement method call the original write once it has been overwritten. Probably the nearest equivalent is to make a wrapper class, and perhaps a factory function to create instances wrapping existing files. Unfortunately, there isn't a UserFile class to make this easier. -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From cookedm+news at physics.mcmaster.ca Sun Mar 7 03:49:26 2004 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Sun, 07 Mar 2004 03:49:26 -0500 Subject: Working around a lack of 'goto' in python References: Message-ID: At some point, "Brett" wrote: > Two areas where I've found 'goto' two be useful in other languages are in > (untested examples in C++) > > (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; > > END: /* continue */; If you're not doing anything between the loops, I like to use a generator: def iindices(klimit, jlimit, ilimit): for k in xrange(klimit): for j in xrange(jlimit): for i in xrange(ilimit): yield k, j, i for k, j, i in iindices(klimit, jlimit, ilimit): if test_fails(k, j, i): break -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From greg.invalid at capra.us.invalid Wed Mar 3 02:33:46 2004 From: greg.invalid at capra.us.invalid (Greg Krohn) Date: Wed, 03 Mar 2004 07:33:46 GMT Subject: Why does my Tkinter GIF image disappear when inside a class? In-Reply-To: References: Message-ID: midtoad wrote: > I'm trying to display a GIF image in a label as the central area to a > Tkinter GUI. The image does not appear, though a space is made for it. > Why is this so? > > I notice that I can display a GIF image in the central area of a simple > menu-bar app as shown below in the first code sample. But, when I set up my > app with a class, as shown below in the second code sample, the image > disappears. > > How can I correct this? I'm sure the answer would jump out at me if I > thought more clearly about it... > > thanks > S > > --- > #basicmenu.py : displays GIF image > > > from Tkinter import * > > > def callback(text): > print "called the callback!: "+text > > root = Tk() > > # create a menu > menu = Menu(root) > root.config(menu=menu) > > filemenu = Menu(menu) > menu.add_cascade(label="File", menu=filemenu) > filemenu.add_command(label="New", command=callback('new')) > filemenu.add_command(label="Open...", command=callback('open')) > filemenu.add_separator() > filemenu.add_command(label="Exit", command=callback('exit')) > > helpmenu = Menu(menu) > menu.add_cascade(label="Help", menu=helpmenu) > helpmenu.add_command(label="About...", command=callback('about')) > > img00 = PhotoImage(format='gif',data= > 'R0lGODlhKwAQAJEAACWgA/3bYYNOGgAAACwAAAAAKwAQAAACfIyPqcsrD2M0' > +'oAJqa8h29yAkITiG3HWmKWiUrdtpseZdtcfmJSyjvf2Z5Q671u0wA9I+RtLj' > +'ZcwgfxglTTchjqS34JUrCUMQySOzih07Tb62eeneqSfU8vsmf65xZa8S/zI3' > +'dlLD5deRl1dlxdT4MYIA2TBJuSZ2iZkZVgAAOw==') > > newLabel = Label(root,image=img00) > t = str(img00.width()) + ' wide x ' + str(img00.height()) + ' high' > newLabel.pack() > Label(root,text='The image is\n'+t).pack() > > mainloop() > --- > #basicmenu2gifobj.py : doesn't display image > > from Tkinter import * > > class gifMenu: > def __init__(self, parent): > > # create a menu > menu = Menu(parent) > parent.config(menu=menu) > > filemenu = Menu(menu) > menu.add_cascade(label="File", menu=filemenu) > filemenu.add_command(label="New", command=callback('new')) > filemenu.add_command(label="Open...", command=callback('open')) > filemenu.add_separator() > filemenu.add_command(label="Exit", command=callback('exit')) > > helpmenu = Menu(menu) > menu.add_cascade(label="Help", menu=helpmenu) > helpmenu.add_command(label="About...", command=callback('about')) > > img00 = PhotoImage(format='gif',data= > 'R0lGODlhKwAQAJEAACWgA/3bYYNOGgAAACwAAAAAKwAQAAACfIyPqcsrD2M0' > +'oAJqa8h29yAkITiG3HWmKWiUrdtpseZdtcfmJSyjvf2Z5Q671u0wA9I+RtLj' > +'ZcwgfxglTTchjqS34JUrCUMQySOzih07Tb62eeneqSfU8vsmf65xZa8S/zI3' > +'dlLD5deRl1dlxdT4MYIA2TBJuSZ2iZkZVgAAOw==') > > newLabel = Label(parent,image=img00) > t = str(img00.width()) + ' wide x ' + str(img00.height()) + ' high' > newLabel.pack() > Label(parent,text='The image is\n'+t).pack() > > class callback: > def __init__(self, text): > self.text = text > def __call__(self): > print 'Command is: ',self.text > > ###################################################################### > > # Create GUI in root window for testing. > if __name__ == '__main__': > title='Menu test with GIF' > root = Tk() > #Pmw.initialise(root) > root.title(title) > > #exitButton = Tkinter.Button(root, text = 'Exit', command = > root.destroy) > #exitButton.pack(side = 'bottom') > gifMenu = gifMenu(root) > > > root.mainloop() Short answer: Replace img00 with self.img00 Longer answer: It's a wart (as far as I'm concerned) in Tkinter. As soon as code execution falls out of __init__ (where img00 was created), the variable img00 is destroyed, hence Tkinter can't find the image. So you need to find some way of keeping the image persistant. Like making it an instance variable, like above, or making it global, etc. greg From python at rcn.com Thu Mar 25 05:07:58 2004 From: python at rcn.com (Raymond Hettinger) Date: 25 Mar 2004 02:07:58 -0800 Subject: SHA-based subclass for random module References: <7xptbgjpk4.fsf@ruckus.brouhaha.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> <5d83790c.0403240124.2a80e784@posting.google.com> <4ql8c.42261$ct5.13462@newssvr25.news.prodigy.com> Message-ID: <5d83790c.0403250207.41600412@posting.google.com> > > What might be nice is if longs had methods for converting to and from > > bytestrings. > > I was thinking the same. How about something like: > > bigNumber = long(bigNumberString, 256) > > bigNumberString = bigNumber.tostring() > > The string->long conversion treats a big-endian byte string as "base > 256", and converts it to a non-negative integer. > > The long->string conversion would only work on non-negative integers. > It's 'inspired' by the array module's "tostring()" method, which returns > a similarly low-level string. > > Big-endian seems the common way to do this, at least in cryptography, in > the common ASN.1 encodings, and in the libraries I've seen. If this is something you want, file a feature request on SF. Raymond From python at g2swaroop.net Fri Mar 5 16:11:49 2004 From: python at g2swaroop.net (Swaroop C H) Date: 5 Mar 2004 13:11:49 -0800 Subject: A Byte of Python - Python Book / Tutorial Message-ID: <5168381b.0403051311.5f1c843f@posting.google.com> Hello everyone, I have a written a book on Python which serves as a tutorial or guide for anyone who wants to learn Python. It specifically targets beginners but experienced programmers can benefit a lot with the special notes for them. The chapters are : Contents at a Glance 1. Introduction 2. Installing Python 3. First Steps 4. Basics 5. Operators and Expressions 6. Control Flow 7. Functions 8. Modules 9. Data Structures 10. Problem Solving - Writing a Python Script 11. Object-Oriented Programming 12. Input/Output 13. Exceptions 14. The Python Standard Library 15. More Python 16. What Next? 17. Appendices * Free/Libre and Open Source Software (FLOSS) * About The book is located at : http://www.python.g2swaroop.net/ During my first brush with Python, I felt there was a need for a good introductory guide to Python, and recent discussions on comp.lang.python reinforce that. I hope this book helps fill that void. This is my first attempt at writing anything so huge and so I am looking forward to your suggestions and criticisms so that I can further improve the book. Thanks, Swaroop C H www.python.g2swaroop.net From ngps at netmemetic.com Mon Mar 15 06:47:49 2004 From: ngps at netmemetic.com (Ng Pheng Siong) Date: 15 Mar 2004 11:47:49 GMT Subject: Generating images on-the-fly Message-ID: Hi, I'm looking for code to generate images on-the-fly using whatever imaging toolkit du jour. This is to build a defense against blog comment auto-spamming. TIA. Cheers. -- Ng Pheng Siong http://firewall.rulemaker.net -+- Firewall Change Management & Version Control http://sandbox.rulemaker.net/ngps -+- Open Source Python Crypto & SSL From theller at python.net Tue Mar 2 14:09:00 2004 From: theller at python.net (Thomas Heller) Date: Tue, 02 Mar 2004 20:09:00 +0100 Subject: py2exe odbc:cannot import dbi module References: Message-ID: mederis at hotmail.com (Marc Ederis) writes: > Hello, > > I'm trying to create an executable with py2exe, and it uses the odbc > module. The script runs fine until I use py2exe on it and run the > .exe. Then I get: > > -- > Traceback (most recent call last): > File "dbmod.py", line 2, in ? > File "odbc.pyo", line 9, in ? > File "odbc.pyo", line 7, in __load > odbc: Cannot import dbi module > -- > > dbi.dll is in the dist folder, and so is odbc.pyd. > > Does anyone know how to solve this problem? It seems you have to first explicitely import the dbi module before the odbc module can be imported. """ import dbi, odbc """ py2exe doesn't know that dbi.dll is a python extension - it is only found as binary dependency. And you should not (must not?) distribute odbc32.dll, which is also copied to the dist folder. In py2exe 0.5, you *should* be able to specify dll_exludes = ["odbc32.dll"] but this doesn't seem to work. Thomas From __peter__ at web.de Mon Mar 22 03:03:58 2004 From: __peter__ at web.de (Peter Otten) Date: Mon, 22 Mar 2004 09:03:58 +0100 Subject: Slow Python - what can be done? References: <480e9240.0403180943.64bee13d@posting.google.com> <480e9240.0403181909.741abfa8@posting.google.com> <105skus763ms4bf@corp.supernews.com> Message-ID: Jason Sewall wrote: > It's affine for the one-line-pair case, but the full algorithm actually > uses n line pairs to describe a nonlinear transformation. Since the Would you care to post a small driver program (if feasible)? I'd like to try the "complex numbers as points" approach on it. > transformations are weighted for each pair, the matrix solution doesn't > cut it for the general case. > > Of course, since I didn't mention it, you wouldn't have known that - > sorry. No problem. Peter From newsgroups at jhrothjr.com Sat Mar 27 21:33:50 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 27 Mar 2004 21:33:50 -0500 Subject: Prothon Prototypes vs Python Classes References: <569c605ld1cj8fc1emolk08ete0s1prls1@4ax.com> <106cc1f2rsnaoe2@news.supernews.com> <406635AB.9050803@mlug.missouri.edu> Message-ID: <106ceeeqc8ph126@news.supernews.com> "Michael" wrote in message news:406635AB.9050803 at mlug.missouri.edu... > I'm not terribly familiar with the concept of prototypes although I > believe I understand the basic meaning and I have worked in languages > which do use prototypes (although not called that). > > Aren't there many times when it is usefult to work with classes where > you do not want an instance to exist? Such as multiple level of > subclasses where code is kept easily readable by putting it on a the > appropiate class for that function alone. Often useful when you'll be > using many similar but not identical objects? I can see how it'd be > useful to be able to define new methods on an object, or edit the > methods on an object but I can not see the purpose to removing classes > altogether. Am I correct in my impression that with prototyping you must > instantate an object to define it's structure? That would seem wasteful > and cluttering of the namespace. Also he way your prototypes read appear > less clear to me than a class definition. I fear that you'd wind up with > people creating an object.. coding random stuff.. adding a method to > that object.. coding more random stuff.. and then adding more to the > object. It's certainly true that in a prototype based language all objects exist: there are no objects that the compiler deals with but does not put into the resulting program. And it's quite true that it does open up the floodgates for a lot of messiness. On the other hand, there are application areas where that is exactly what you need: I've already mentioned interactive fiction, and there are undoubtedly others. I'd like to play around with a prototype based language to see how it works, although for reasons I've mentioned elsewhere, I won't use Prothon. I'd be using IO if they had a windows executable installer, rather than requiring me to compile the silly thing. John Roth From ng4rrjanbiah at rediffmail.com Thu Mar 4 01:24:33 2004 From: ng4rrjanbiah at rediffmail.com (R. Rajesh Jeba Anbiah) Date: 3 Mar 2004 22:24:33 -0800 Subject: Python as replacement for PHP? References: <403fa54b@news.zianet.com> <99dce321.0403031518.56f61c7c@posting.google.com> Message-ID: [Well, this time I have decided to troll -- all because of prolong irritating ignorant posts/crossposts. And, this is intentional crosspost.] dw-google.com at botanicus.net (David M. Wilson) wrote in message news:<99dce321.0403031518.56f61c7c at posting.google.com>... > Bart Nessux wrote... > > > When it comes to dynamic, DB driven sites, PHP is the only way to go. > > Python is not even close to being suited for this task. PHP claims to be > > a general-purpose language, but I do not know anyone who uses it for > > anything other than dynamic Web programming. > > Like everyone else who has replied, I seriously question how much > experience you have with the multitude of Python web environments > available. As an objective, point-by-point look at your specific > example of somewhere PHP is strong, here's my reply: > > [PS: I still use PHP regularly, albeit only for quick unimportant > hacks that won't exist in 6 months] So.. you don't have any important works :-/ > - Nearly all the PHP code I have seen (including various large web > sites) fails to handle error conditions, and will run amok given a > down DB server, bad filesystem permissions, or bad inputs. I have had > personal experience, on more than one occasion, of an error condition > in someone else's PHP code causing a large amount of damage to a > dataset. Good news. Well done PHP! > - The equivalent Python code will almost never do that. Thanks to the > religious throwing of exceptions, well written standard libraries, DB > adaptors, and so on, the worst Python code has a MUCH better chance of > getting stopped in it's tracks just as a fault occurs. > > py> open("/tmp/foo","w").write(123) > Traceback (most recent call last): > File "", line 1, in ? > TypeError: argument 1 must be string or read-only character buffer, > not int > > > [22:15:14] [cape:4:dw]$ php4 < > > > e > [22:15:16] [cape:5:dw]$ cat /tmp/foo > [22:15:17] [cape:6:dw]$ > > Can you tell me exactly what the PHP fwrite function did when I passed > it an integer? Can you tell me how many PHP programmers test > "(strlen($to_write) == fwrite($fp, $to_write))"? Ok...understand. idiot-proof? > - In the specific instance of database connectivity, Python is far > superior, in terms of intuitiveness, security, safety, and so on. > Python database APIs are built in a way that protects you by default. Perhaps, idiots' own language? > - PHP provides no intuitive default support for many common DB > operations. Compare the following messes: > > py> l = MySQLdb.connect() > py> c = l.cursor() > py> user_input = "%t%" > py> match_count = c.execute("SHOW DATABASES LIKE %s", ( user_input > )) > py> print match_count, "matches:", [ x for x, in c ] > 1 matches: ['test'] > > > $user_input = "%t%"; > $query_sql = sprintf("SHOW DATABASES LIKE \"%s\"", > mysql_real_escape_string($user_input, $s)); > $query = mysql_query($query_sql, $s); > $matches = array(); > while ($row = mysql_fetch_array($query, MYSQL_NUM)) $matches[]= > $row[0]; > echo sizeof($matches), " matches: ", var_export($matches, true); > > > Tell me, of these two popular examples of bad code in both languages, > which is the more intuitive to read, which is the more elegant to keep > secure, and which would you prefer to be reading, and modifying in 18 > months time? [In this case, which was the quicker to create? The > Python example. The PHP counterpart has a syntax error somewhere, I > care not where.] > > How many different ways can you dream up the same functionality in the > PHP example? (mysql_escape_string, , etc.) > > How likely is it that the developer you hire to take over development > of either snippet of code will understand the concept behind it? I > can't even think of another way of doing database query in Python, > without using the low-level interfaces, which is just insane. > > We could bring the PHP ADODB, or many of the other numerous PHP APIs > for DB connectivity into the picture, but which of these are the > obvious choice, and officially endorsed? > > How easy is it to improve on both these examples to add proper error > handling? Again, Python wins hands down for elegance, conciseness, and > obviousness. Yes, agreed. Idiots' language. > - Python has a religious following of thousands, many of whom found > freedom through it's restraint, unified path, and downright beauty. > The result is a long tradition of structured, well written code. > Python has roots in academia, and started life with a defined purpose, > and a BDFL who knew what he was doing. > > - PHP, "the web designer's ideal first language", started out life as > "a collection of perl scripts" (that says it all really), then ported > to C, then hacked and added to until it was the great swiss army > monolith that it is today. PHP has never had a clear, publically > documented development path, or indeed any form of structure or > organisation, past the menu system of PHP.net LOL! Joke of the millennium. > PHP developers tend to have started life using Dreamweaver, happy to > accept the first solution to a problem that comes their way, and care > little about technical merit. Every person (including at the time, > myself) who I know that uses, or used PHP, did so because it allowed > them to make things look beautiful and dynamic very quickly. Yet another good joke. > - Python gurus, when asked how to make something work, will often > appear nasty and horrible, telling you you're doing entirely the wrong > thing and you should go back to the drawing board. Much like the hot > sting from a smack of a father's hand, this is good, not bad. It is > there to direct and discipline you, and improve the way you think. > > - PHP gurus tend to be experienced web developers, they'll be able to > look flash and give you an answer on the spot, but that answer will > only further lead to the demise of any structure your coding ever had. Huh?? > - Python tends to be slow, but slow compared to what? The laptop I > type this message on has a 2ghz processor. It cost less than ?1000. It > is the cheapest laptop money can buy in the UK. I run Python scripts > on multi-gigabyte datasets on a daily basis on this machine. I have > never considered the scripts to be 'slow'. > > - PHP is very light on CPU, memory, and so on. I earn a modest amount > for a 20 year old, even by Northern Ireland standards. I can't see how > I would ever need to resort to PHP because I couldn't afford the > hardware to run a complex Python-based site intended for viewing by > thousands. > > > Personally, I find the average PHP codebase to be akin to a television > station such as MTV: well presented, streamlined, professional > looking, but in terms of content, nothing but meaningless, mindless > shite. On the other hand, reading certain Python code is more like > reading a beautifully typeset hardback novel: black and white - ugly > to some, but functional, educational, structured, meaningful, etc, > etc. > > What interests you more - earning money through thoughtless, > effortlessly produced rant-syntax that no-one will ever want to look > at again, or the daily challenge to produce something that will > perfectly fulfill it's intended function, at the cost of a little > time, a little brainpower, and a little discipline. > > I could go on, but I think these points alone are the main reasons I > use Python. At the cost only of speed, it protects me, teaches me, > profits me, and inspires me to continue being the professional geek > that I am. :) comp.lang.php is not the right place for you to show your stupidity. You should consider stripping headers as many other PHP ignorants () did before throwing your thoughts. HTH. HAND. -- From comp.lang.php "Success is not what you achieve, but it is what you die for" If you live in USA, please support John Edwards. Email: rrjanbiah-at-Y!com From cygnus at cprogrammer.org Tue Mar 30 14:24:32 2004 From: cygnus at cprogrammer.org (Jonathan Daugherty) Date: Tue, 30 Mar 2004 14:24:32 -0500 Subject: Python Documentation Blows! In-Reply-To: <4069C839.6020109@mlug.missouri.edu> References: <40699A31.8000708@yahoo.com> <20040330161531.GA17112@vulcan.cprogrammer.org> <4069C839.6020109@mlug.missouri.edu> Message-ID: <20040330192432.GA20081@vulcan.cprogrammer.org> # wxPython would be my example of some of the worst (non-existant) # documentation available for Python while PyGame would be my example of # some of the best. Yeah, I agree that pygame's docs are really good. I enjoy bouncing around in those when I am working with pygame. wxPython is just bad in that its docs are sprinkled throughout the wxWindows docs and there isn't a central place to go when you want to know How To Do Something that is not explicitly treated by the wxWindows docs. -- _ ,^. _ ,'/ -' '- \`. / | \ / | \ Jonathan Daugherty | | | | | | | \_,' `._/ | http://www.cprogrammer.org | | \ / `. .' `--._.--' From gustabares at verizon.net Thu Mar 4 15:32:51 2004 From: gustabares at verizon.net (Gus Tabares) Date: 4 Mar 2004 12:32:51 -0800 Subject: Debugging Python extensions Message-ID: Hello all, I'm writing some Python extensions in C under Windows using Visual Studio .NET 2003. I want to be able to debug my extensions using .NET. I'm not very clear on the exact process of doing this. So far I have compiled a debug version of the 'pythoncore' project that is located in the Python sources. This has produced the python23_d.dll which I will use to link with my pyd. I have a few questions after this step: 1. Do I need to compile my own version of Python2.3 to debug my pyd? 2. Do I have to name my debug pyd as filename_d.pyd? 3. Does the init function need to be named initfilename_d? I understand that .NET 2003 is not "supported" (I believe only VS6 is) but I would think using .NET 2003 would not be much different aside from converting the projects to the new format. Thanks, Gus From nid_oizo at yahoo.com_remove_the_ Mon Mar 1 14:23:35 2004 From: nid_oizo at yahoo.com_remove_the_ (Nicolas Fleury) Date: Mon, 01 Mar 2004 14:23:35 -0500 Subject: Garbage collector and threads In-Reply-To: References: <1EJ0c.4334$mx4.105438@nnrp1.uunet.ca> <6uK0c.4347$mx4.106055@nnrp1.uunet.ca> Message-ID: Aahz wrote: > As Michael Hudson said, it doesn't work that way in Python, because all > Python objects are global (and I mean truly global here, not just module > global). Essentially, all objects are heap objects that can be traced > by crawling through Python's internals. I understand that. RAII is often used when speaking of scoped variables. In my case I was talking about global scope in main thread. > Right. As I said, you have to use the ``thread`` module directly; you > can't use ``threading``. But even if I use "thread", I have no way to put the functionality in one class if I want access the members in the running thread. >>I just want a way to garantee that all my threads are cancelled when the >>main thread is finished. > > So hold references to them and call the ``cancel()`` method yourself. That's a possible solution. Make a custom Thread class with a cancel method and with all instances registered somewhere. At the end of the main thread, I call something to cancel all these threads. There's however some problems with that solution: - Parent threads need to be cancelled before their children threads. - It only works at the end of the main thread; it cannot be used at the middle of an appplication. - The cancellations are not automatic (I guess there's a way to do it by overriding something like exit, anyway...) All these problems are solved by using RAII with the Canceller class I shown in a previous message, so I prefer using this solution. In fact, what I would really need, is a mechanism, and I don't know if there's already one, to disable ref-counting of a thread object in its corresponding thread, so that I could provide a single class for cancellable threads. Regards, Nicolas From peter at engcorp.com Thu Mar 18 21:32:52 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 18 Mar 2004 21:32:52 -0500 Subject: tkinter, threads and asyncore together In-Reply-To: References: Message-ID: duane voth wrote: >>#to control asyncore >>while 1: >> asyncore.loop(.1) >> if not fromgui.empty(): >> #handle messages from GUI > > > The above doesn't work for me - asyncore.loop() always blocks. From the asyncore docs: loop( [timeout[, use_poll[, map]]]) Enter a polling loop that only terminates after all open channels have been closed. Seems to me that the behaviour is as expected. -Peter From R.Brodie at rl.ac.uk Thu Mar 18 12:51:36 2004 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Thu, 18 Mar 2004 17:51:36 -0000 Subject: ConfigParser and Unicode References: Message-ID: wrote in message news:kbl6c.29656$wg.22030 at okepread01... > > Obviously, 'Gr??'!='Gr\xfc\xdf' . >>> 'Gr??' != 'Gr\xfc\xdf' False From altis at semi-retired.com Fri Mar 5 15:17:50 2004 From: altis at semi-retired.com (Kevin Altis) Date: Fri, 5 Mar 2004 12:17:50 -0800 Subject: function to return a list of all methods for an object References: <4048d717$0$277$626a14ce@news.free.fr> Message-ID: "F. Petitjean" wrote in message news:4048d717$0$277$626a14ce at news.free.fr... > On Fri, 5 Mar 2004 10:39:23 -0800, Kevin Altis wrote: > > I need a way of getting a list of all the methods for an object. I want the > > unbound methods for the objects class for some further manipulation. > > > ... I came up with > > a much simpler version that uses dir(), but would like a sanity check before > > committing to it. Perhaps there is a better way? This only needs to work > > with Python 2.2 and later, so I won't mind say "Doh!" if I've missed the > > obvious simple solution and someone points out my stupidity. > > > > > > import types > > import pprint > import inspect > help(inspect.getmembers) > > > > > def getMethods(object): > # don't use object ! > > methods = [] > > names = dir(object.__class__) > > for name in names: > > m = getattr(object.__class__, name) > > if isinstance(m, types.MethodType): > > #print "method:", m > > methods.append(m) > > return methods > > > > > Try it : > b = inspect.BlockFinder() > inspect.getmembers(inspect.BlockFinder, inspect.ismethod) Awesome! Looks like I need to do a little refactoring if I'm going to deal with the list of tuples result, but in the meantime I can do a list comprehension like this in in the test so I still have a list of unbound methods. methods = [t[1] for t in inspect.getmembers(e.__class__, inspect.ismethod)] Thanks for pointing out inspect, ka From lbates at swamisoft.com Wed Mar 3 15:50:51 2004 From: lbates at swamisoft.com (Larry Bates) Date: Wed, 3 Mar 2004 14:50:51 -0600 Subject: pythonservice -register References: <9e5ea2c4.0403030733.1cb50edc@posting.google.com> Message-ID: On my machine (Windows XP Pro also ActivePython 2.2) I get the following: Registering the Python Service Manager ... After that everything works as documented. -Larry "Olaf Meding" wrote in message news:9e5ea2c4.0403030733.1cb50edc at posting.google.com... > What is the pythonservice.exe for? What does pythonservice.exe really > do? > > I installed and am using ActivePython (on Windows XP). > > Working on writing a Windows service in Python. The "Python > Programming on Win32" book says I should first register the > pythonserive. This does not seem to work (see error below). However, > the books SmallestService seems to run anyway. > > Thanks for your help. > > Olaf > > *** Here is the error: *** > C:\Python23\Lib\site-packages\win32>pythonservice /register > Registering the Python Service Manager... > Fatal Python error: PyThreadState_Get: no current thread > > This application has requested the Runtime to terminate it in an > unusual way. > Please contact the application's support team for more information. From http Tue Mar 30 03:44:07 2004 From: http (Paul Rubin) Date: 30 Mar 2004 00:44:07 -0800 Subject: Orders of magnitude References: Message-ID: <7xr7va7mi0.fsf@ruckus.brouhaha.com> "Robert Brewer" writes: > No, don't rewrite it! :D I have even *more* requirements, which are > mostly in my code but not really documented, and some are changing. I'm > working on a more scalable solution, since I then need to apply the same > code to a 20-million-record DB. I'm doing fine--just wondered in > particular about ways to optimize that single step. Thanks for your > help. Maybe you're at the point where you should use a real database (e.g. MySQL) to hold that kind of data, instead of rolling your own and messing with it on the fly. From ramen at lackingtalent.com Fri Mar 19 17:20:36 2004 From: ramen at lackingtalent.com (Dave Benjamin) Date: Fri, 19 Mar 2004 22:20:36 -0000 Subject: tuples or lists References: <3064b51d.0403161208.78350dac@posting.google.com> Message-ID: In article , Martin v. L?wis wrote: > beliavsky at aol.com wrote: >> Is "use tuples instead of lists, when possible" a good rule? > > The party line is: "use lists for similar items, tuples for > different items". If you come from a C++ background, tuples > are mostly used what structs are used for, and lists are used > in the std::vector context. I might or might not agree with this depending on the context. In most cases, I would use a dictionary in Python where I would use a struct in C++ unless the struct was small and obvious, because the naming of values aids in comprehension. I typically use tuples for: - points - ranges - the % operator (by design) - ordered lists of key/value pairs (such as for a SELECT/OPTION list) - groups of function arguments None of these usages necessarily involves different items, but the last three often do. In general, I really don't like the look of the ('singleton',) tuple, so in functions expecting sequences, I tend to use lists for consistency. -- .:[ dave benjamin: ramen/[sp00] -:- spoomusic.com -:- ramenfest.com ]:. : please talk to your son or daughter about parametric polymorphism. : From gry at ll.mit.edu Tue Mar 16 15:51:15 2004 From: gry at ll.mit.edu (george young) Date: 16 Mar 2004 12:51:15 -0800 Subject: list inheritance or delegation? Message-ID: <78b6a744.0403161251.34fad544@posting.google.com> [python 2.3.3, x86 linux] I need an object that behaves much like a list, but has some additional features. It seems that I can do this either by inheriting from type list, or by emulating list by defining __len__, __getitem__, and maybe a bunch of other methods. Thirdly, I could inherit from UserList, but that's deprecated now. Inheriting from list would save me implementing a bunch of methods that I might want. But if I inherit from list, how do I get access to the data? E.g., I need a customized 'setitem' method that does the insert and then does some other things too. With UserList, I could: class mylist(UserList): def __setitem__(self,i,y): self.dostuff(y) self.data[i]=y but when inheriting from 'list', I'm not sure how to do this. I couldn't find anything in the docs about inheriting from builtin types, though it seems to be an encouraged practice. It seems like if one is encouraged to inherit from builtins, there needs to be at least a concise description of the 'inheritable api' for each such type. E.g. does __init__ or __new__ handle initial values. Maybe I'm just missing something obvious... So, I'm asking: 1) what are the issues/tradoffs between inheriting from list and emulating it with my own methods referencing a list data member. 2) how do I get enough access to list's data to do the inheritance. 3) I'm whining about lack of documentation for #2. Thanks, George Young From wmgill at gcgroup.net Thu Mar 4 14:42:07 2004 From: wmgill at gcgroup.net (William D. Gill) Date: Thu, 4 Mar 2004 14:42:07 -0500 Subject: python classes References: <9f1bd$40476c26$42a655ea$13320@msgid.meganewsservers.com> Message-ID: "Peter Otten" <__peter__ at web.de> wrote in message news:c27t0v$fhn$05$1 at news.t-online.com... > William D. Gill wrote: > <<<<<------SNIP----->>>>> > > class MyClass: > > def __init__(self, id=0000): > > self.data = MyOtherClass(id) # data is an object with name, id > > and other properties > > I think this is an extra complication that gains you nothing. The only > exception would be that data would not be initialized in MyClass.__init__() > but lazily at some later point, a usefull pattern if for a significant part > of the MyClass instances you can get away with not initializing data at > all. You would then change MyClass as follows: > My thinking was to create a class for each table that contains pieces of the whole customer information , and wrap OOPS! I mean include :) those classes in the overall customer class object. That way by supplying id, all the different constructors would go get the right data. At my level (pre-novice) it's probably better to use one customer class and sequential programming in the constructor: select * from table A where id=1234 self.company_name = A.name ... select * from table B where id=1234 self.mailto=B.mailto self.billto = B.billto ... select * from table C where id=1234 self.cell=C.cell self.list=C.list ... (using multiple selects because they may produce different size record sets) <<<<<------SNIP----->>>>> > I suppose that was a mutual misunderstanding. Did you mean this by > "wrapping"? > > try: > customer = Customer.fromId(1234) > except InvalidCustomer, e: > print e Yes Thanks, Bill From roy at panix.com Sun Mar 7 21:11:14 2004 From: roy at panix.com (Roy Smith) Date: Sun, 07 Mar 2004 21:11:14 -0500 Subject: Working around a lack of 'goto' in python References: Message-ID: In article , "Roger Binns" wrote: > Brett wrote: > > Two areas where I've found 'goto' two be useful in other languages are in > > (untested examples in C++) > > What you have is what many other languages allow with integers after break or > continue statements. For example you can do 'break 2' or 'continue 3' to > break or continue out of the respective number of enclosing for loops. Yuck. Bletch. Barf. From Sibylle.Koczian at Bibliothek.Uni-Augsburg.de Mon Mar 22 09:22:23 2004 From: Sibylle.Koczian at Bibliothek.Uni-Augsburg.de (Sibylle Koczian) Date: Mon, 22 Mar 2004 15:22:23 +0100 Subject: socket.gethostbyaddr() doesn't show existing aliases Message-ID: Hello all, the documentation for the socket module says that gethostbyaddr should return the primary host name and alternative host names if there are any. But the alias list is empty even in cases where I know aliases exist. I can get them using gethostbyname_ex, but that only works with names, not with IP addresses, and I want to resolve both sorts. I'm using Python 2.3.2 on Windows NT4, SP6. What's wrong? Thank you, 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 mwh at python.net Fri Mar 5 05:10:51 2004 From: mwh at python.net (Michael Hudson) Date: Fri, 5 Mar 2004 10:10:51 GMT Subject: mimic -i from script References: Message-ID: Peter Hansen writes: > John Hunter wrote: > > > Is it possible at the end of a script to issue some python command > > that will cause the python shell to open as if the -i flag had been > > used > > See the first item in > http://www.python.org/doc/2.3/whatsnew/section-other.html And if 2.3 isn't an option, you might be able to use the standard library module code.py to good effect. Cheers, mwh -- QNX... the OS that walks like a duck, quacks like a duck, but is, in fact, a platypus. ... the adventures of porting duck software to the platypus were avoidable this time. -- Chris Klein, alt.sysadmin.recovery From mailscan1-admin at mail.fairfax.com.au Mon Mar 29 06:10:29 2004 From: mailscan1-admin at mail.fairfax.com.au (mailscan1-admin at mail.fairfax.com.au) Date: Mon, 29 Mar 2004 21:10:29 +1000 (EAST) Subject: An email has been blocked Re: Mail System (dfauth@access.fairfax.com.au) Message-ID: An email was blocked because it contained an executable or a filtered attachment. It had the following details: From: python-list at python.org To: dfauth at access.fairfax.com.au Subject: Mail System (dfauth at access.fairfax.com.au) From ods at strana.ru Thu Mar 11 09:14:45 2004 From: ods at strana.ru (Denis S. Otkidach) Date: Thu, 11 Mar 2004 17:14:45 +0300 (MSK) Subject: RuntimeError: cannot unmarshal code objects in restricted execution mode In-Reply-To: Message-ID: More accurate: the problem is when module has compiled version (.pyc), so I can run the script first time without error. DSO> When I execute python code from C++ application with DSO> PyEval_EvalCode and this code contains imports of other DSO> modules DSO> then I got the error "RuntimeError: cannot unmarshal code DSO> objects DSO> in restricted execution mode". How can I switch into DSO> noraml (unrestricted) mode? DSO> DSO> Python 2.2.2, Linux. Actual code looks like the following: DSO> DSO> tstate = Py_NewInterpreter(); DSO> main_module = PyImport_AddModule("__main__"); DSO> main_dict = PyModule_GetDict(main_module); DSO> obj_res = PyEval_EvalCode(calc_code, main_dict, main_dict); -- Denis S. Otkidach http://www.python.ru/ [ru] From me at privacy.net Mon Mar 15 06:38:40 2004 From: me at privacy.net (Heather Coppersmith) Date: 15 Mar 2004 06:38:40 -0500 Subject: Static Typing in Python Message-ID: On Sat, 13 Mar 2004 12:47:43 -0500, "Sean Ross" wrote: > # trivial example based on http://io.kicks-ass.net/LocalVariables > class A: > def __init__(self): > self.area = None > def square(self, side): > self.arae = side * side # spelling mistake creates new attribute > def circle(self, radius): > self.area = 3.14 * radius * radius > a = A() > a.circle(1) > print a.area # 3.14 -> ok > a.square(4) > print a.area # 3.14 -> unintended What about __slots__ (with recent pythons and new styly classes)? >>> class A(object): ... __slots__ = 'area' ... def __init__(self): ... self.arae = None ... >>> a = A( ) Traceback (most recent call last): File "", line 1, in ? File "", line 4, in __init__ AttributeError: 'A' object has no attribute 'arae' Regards, Heather -- Heather Coppersmith That's not right; that's not even wrong. -- Wolfgang Pauli From jacek.generowicz at cern.ch Wed Mar 24 03:47:22 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 24 Mar 2004 09:47:22 +0100 Subject: Python for large projects References: <1060p59d9rg9819@corp.supernews.com> Message-ID: gabor writes: > i wanted to use python for a project in our company... we wanted to > build a fairly big system/program. > > but when i recommended python, i got a question like: > (previously all the programs were written in java) > "if one of our programmers changes a method in a class/interface, we > immediately will know about it, because the next program-rebuild will > simply fail. but if we would use python, we wouldn't find it out". "if one of our programmers changes a method in a class, without changing the interface, but introduces a logic error, we won't know about it, because the program will happily compile, but, as we have no test suite, the runtime error will go unnoticed." The errors which static typing system catch at compile time, are just a tiny fraction of all the errors that programmers make, and they are usually the most boring, and most obvious errors. > yes, i know that people usually recommend unit testing for this, but > imho it is not a good enough argument It is not a good enough argument for convincing those who already firmly believe that static typing somehow helps in the overall software development process. Yes, it is an unfortunate fact of human nature that people often acquire ushakeable beliefs, which make them very unreceptive to evidence which points to flaws in said beliefs. > other thing is, that in the projects i work on, there seems to be > very hard to do unit tests ... and one thing that makes unit testing very difficult, is static typing ... (which is why statically-typed projects are less likely to have (any, let alone good) unit test suites, which is why statically typed projects are far more likely to be bug infested). > ... most of the parts of the system can't be that easily be tested > (how do you unittest a threadpool? a servlet?). Yes, some things are harder to unit test than others. That in no way affects the _necessity_ of testing it ... and static typing only makes testing harder (and less testing means more bugs ... hence static typing means more bugs.) > yes, i've heard that "if you can't make unittests, that means your > classes/modules/packages depend too much on each othere, and that > means you wrote bad code. Yes, there is some truth to that, but I consider it irrelevant to what we are discussing. _All_ software must be tested, whether written with or without static typing. Static typing makes testing more difficult, therefore static typing lets more bugs slip through the net. (I hope I've repeated that often enough in this article to for it to be noticed my more than one reader :-) (In next week's episode of "Static Typing Sucks" we discuss static typing systems' penchent for rejecting perfectly _correct_ programs because they contain what the rigid type system considers to be a type error, even though said "error" would have no adverse influence on the correct running of the program.) From gherron at islandtraining.com Mon Mar 8 21:43:59 2004 From: gherron at islandtraining.com (Gary Herron) Date: Mon, 8 Mar 2004 18:43:59 -0800 Subject: a desired python editor In-Reply-To: References: Message-ID: <200403081844.00023.gherron@islandtraining.com> 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 1 and 2 are no-brainers, although, as a matter of terminology, calling it freeware is going cause severe heartburn for some. 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 From "Charles Krug" at cdksystems.com Thu Mar 18 11:34:49 2004 From: "Charles Krug" at cdksystems.com ("Charles Krug" at cdksystems.com) Date: Thu, 18 Mar 2004 16:34:49 GMT Subject: [Python Win32] Accessing Python COM objects Message-ID: Hello Bruces: I've created a logging class. The interface from Python's PoV works like this: X = myLogger() # Creates an instance X("some user", "some process", "A message to be logged") Works a champ. I'd like to be able to use identical semantics from VB. However, it VB seems not to recognize the syntax. I've created a COM class that has-a myLogger instance. I've exposed the __call__ method in _public_methods_ But vb cannot access the COM log object via its instance name the way that Python can. As a check, I added a public logEntry() method to the COM class. I've verified that all the features of the COM class work correctly, EXCEPT "call by name" (which I expect to invoke the __call__ method.) Is there some way to convince VB to allow this? I'm referring to "Python Programming on Win32" 1st Ed. Is this simply not possible? It's not a "problem" so much as a preference. Thanks Charles Krug From ville at spammers.com Tue Mar 23 01:35:30 2004 From: ville at spammers.com (Ville Vainio) Date: 23 Mar 2004 08:35:30 +0200 Subject: Voting (was Re: PEP 318 References: Message-ID: >>>>> "Skip" == Skip Montanaro writes: Skip> It will probably be a BDFL pronouncement. After all, that's Skip> why he's the Of course it will - still, that didn't stop us from voting before :-). There should be a kind of "standard voting system" for PEPs, w/o administration overhead of occasional seperate vote. It would be a data point, if nothing else. The result of the vote could be stored together w/ the accepted/approved pep. Actually, any third party could whip out the voting system, but the illusion of authority would be more convincing if PSF was involved. It would be fun, esp. if it was easier than the conditional expression vote of yore :-). FWIW, I prefer def f(x,y) [wrapper,wrapper...]: pass or def f(x,y) as iterable: pass and would oppose def f [wrapper, wrapper...] (x,y): pass Like others, I want to see the param list right next to the function name. -- Ville Vainio http://tinyurl.com/2prnb From beliavsky at aol.com Mon Mar 29 19:01:42 2004 From: beliavsky at aol.com (beliavsky at aol.com) Date: 29 Mar 2004 16:01:42 -0800 Subject: Integer, 64 Bit, signed and unsigned References: Message-ID: <3064b51d.0403291601.3001b2ca@posting.google.com> Arithmetic with 8-byte integers will be much faster when using Fortran and C++ compilers that directly support it, compared to Python, which resorts to infinite precision arithmetic when 4-byte integers cannot be used. Search for "speed integer*8" in this newsgroup -- there was a discussion in late Feb early March 2004. Torsten Mohr wrote in message news:... > 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 aldo123 at onet.pl Tue Mar 16 07:11:42 2004 From: aldo123 at onet.pl (mic) Date: Tue, 16 Mar 2004 13:11:42 +0100 Subject: win32: using postdata and safearray Message-ID: I'm stuck with following problem. Using webbrowser control I try to make custom-made request. I found working example of this written in VBS but porting it to Python doesn't seem to work. The key is navigate (or navigate2) method, that accepts PostData as one of it's parameters. As stated in reference: "The post data specified by PostData is passed as a SAFEARRAY Data Type structure. The variant should be of type Array and point to a SAFEARRAY Data Type. The SAFEARRAY Data Type should be of element type Integer, dimension one, and have an element count equal to the number of bytes of post data." Therefore I try to send simple 'ABC' string together with HTTP request by creating list of ascii integers [65,66,67]. The list is supposed (as far as I understand) to be automatically converted into safearray, but instead of: [hex]: 41 42 43 the sequence of following bytes is being sent: [hex]: 03 00 34 00 00 00 00 00 41 00 00 00 00 00 00 00 03 00 34 00 00 00 00 00 42 00 00 00 00 00 00 00 03 00 34 00 00 00 00 00 43 00 00 00 00 00 00 00 a3 f0 00 What's curious, I noticed some small differences between using tuples and lists - the tuple seem to add some additional bytes at the end. It looks like some wrong conversion of types, but I don't know any idea how to fix it or maybe convert it manually. Regards, Michal From jcarlson at nospam.uci.edu Mon Mar 1 16:32:55 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Mon, 01 Mar 2004 13:32:55 -0800 Subject: Speed Comparison Perl Python & C In-Reply-To: <3064b51d.0403011035.554e7731@posting.google.com> References: <3064b51d.0403011035.554e7731@posting.google.com> Message-ID: > i = 1 > j = 0 > while i < 100000000: > j = j + i > i = i + 1 > print j > > Python 93.4 > Fortran 0.28 Not quite fair. The Python version does long-integer (infinite-precision) math when i is greater than 65534 on a 32 bit processor. You are really counting is the time to do 100,065,535 integer additions and 99934465 long-integer additions. Furthermore, you allow fortran to optimize the loop, but you don't optimize the python loop yourself, using those portions built-in that are known to be fast. print sum(xrange(100000000)) takes half-as long as the while loop on my machine, yet does the exact same calculations. Your Fortran definition includs a message saying "use 64-bit integers here": integer*8 :: i,j You are comparing apples to oranges on multiple levels. Don't. - Josiah From Python at ivonet.nl Sun Mar 14 15:10:26 2004 From: Python at ivonet.nl (Ivo) Date: Sun, 14 Mar 2004 21:10:26 +0100 Subject: Is reverse reading possible? References: <20040314191047.15699.qmail@web13012.mail.yahoo.com> Message-ID: <002d01c40a00$64069fd0$9600000a@pc001> Please explain a bit more... Can you tell me more about the lay-out of the file Is it still formatted per line or per char? I don't know how to handle chinese because I have never seen it in ASCII Please give an example... ----- Original Message ----- From: "Anthony Liu" To: "py" Sent: Sunday, March 14, 2004 8:10 PM Subject: Re: Is reverse reading possible? > Jeff and Ivo, > > Thank you very much for your solution. Yes, I figure > out it is easy for an ascii text. > > The files (nearly 4M each)I am gonna read are a > mixture of Chinese and English, where each Chinese > character has 2 bytes and each English (ASCII) has 1 > byte, although the majority of the texts is Chinese. > > So, if we reverse-read it without taking into > consideration the 2-byte Chinese characters, we are > gonna get the Chinese characters spelled out in the > wrong way - unreadable! > > So, it might be tedious to read such a text reversely > unless you have a smarter idea. Do you? > > > > --- Jeff Epler wrote: > > on seekable, byte-oriented binary files, sure. > > > > import errno > > > > SEEK_SET, SEEK_CUR, SEEK_END = range(3) > > > > class Reversed: > > def __init__(self, f): > > self.f = f > > self.f.seek(-1, SEEK_END) > > self.at_eof = 0 > > > > def read_byte(self): > > if self.at_eof: return '' > > byte = self.f.read(1) > > try: > > self.f.seek(-2, SEEK_CUR) > > except IOError, detail: > > if detail.errno == errno.EINVAL: > > self.at_eof = 1 > > else: > > raise > > return byte > > > > def __iter__(self): return self > > > > def next(self): > > r = self.read_byte() > > if r == '': raise StopIteration > > return r > > > > >>> "".join(Reversed(file("/etc/redhat-release", > > "rb"))) > > '\n)worraY( 1 esaeler eroC arodeF' > > > > Jeff > > > __________________________________ > Do you Yahoo!? > Yahoo! Mail - More reliable, more storage, less spam > http://mail.yahoo.com > > -- > http://mail.python.org/mailman/listinfo/python-list > > From jepler at unpythonic.net Sun Mar 28 10:57:37 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Sun, 28 Mar 2004 09:57:37 -0600 Subject: Prothon Prototypes vs Python Classes In-Reply-To: <569c605ld1cj8fc1emolk08ete0s1prls1@4ax.com> References: <569c605ld1cj8fc1emolk08ete0s1prls1@4ax.com> Message-ID: <20040328155736.GA28726@unpythonic.net> I just wanted to jump on the "Python *can* do prototypes" bandwagon, and offer my own solution. To me, a prototype looks like a class where all methods are classmethods. Well, then, just fix that up in a metaclass. The only other wrinkle I addressed was calling __init__ (because an instance is never created). Special methods (such as __add__, __call__) probably don't do anything sane. This code is distributed under the "Free to a good home" license. Jeff import sys, types class PrototypeMeta(type): def __init__(cls, name, bases, dict): super(PrototypeMeta, cls).__init__(name, bases, dict) for name, value in dict.items(): if isinstance(value, types.FunctionType): setattr(cls, name, classmethod(value)) # cls always has __init__ -- it can either be object's init, # (which is a wrapper_descriptor) or a desired init (which is # a bound classmethod). call it if it's the right one. if isinstance(cls.__init__, types.MethodType): cls.__init__() def __call__( __metaclass__ = PrototypeMeta class Thing: name = "Unnamed Thing" desc = "(Undescribed thing)" def __init__(self): print "created a new thing:", self.name def look(self): print "You see a", self.name print self.desc class Room: name = "Unnamed Room" desc = "(Undescribed room)" contents = [] def look(self): print "You are in", self.name print print self.desc print if self.contents: print "Things here:" for c in self.contents: print c.name print class Python(Thing): name = "a snake" desc = "This snake has the number '%s' written on its belly" \ % sys.version.split()[0] class LivingRoom(Room): name = "Living Room" desc = """There is a large window on the south side of the room, which is also the location of the door to the outside. On the west wall is an unused fireplace with plants on the mantle. A hallway is to the west, and the dining room is north.""" contents = [Python] class DarkRoom(Room): def look(self): print "Where am I? It's dark in here!" print print LivingRoom.look() DarkRoom.look() Python.look() From allena29 at elsol.zwan Sat Mar 13 11:53:05 2004 From: allena29 at elsol.zwan (allena29 at elsol.zwan) Date: Sat, 13 Mar 2004 16:53:05 +0000 Subject: ANN: pyshaper - for easy traffic-shaping References: Message-ID: On Sun, 14 Mar 2004 02:23:35 +1300, David McNab wrote: > Hi, > > I've released an alpha of 'pyshaper' - a python prog which makes > traffic-shaping (bandwidth allocation/management) a snap. > .. > Caveats: > - it's in alpha - only tested on Debian sid with kernel 2.6.4 - > worst-case scenario - no system damage, but possible bugs might > cause it to not work as well as desired. > [allena29 at elsol bin]$ pyshaper.orig File "/usr/bin/pyshaper.orig", line 1253 main() ^ IndentationError: expected an indented block Regards, adam From s.meyer at ass-hannover.de Wed Mar 17 12:41:50 2004 From: s.meyer at ass-hannover.de (Sebastian Meyer) Date: Wed, 17 Mar 2004 18:41:50 +0100 Subject: Problem with threads and signals References: Message-ID: "Diez B. Roggisch" schrieb im Newsbeitrag news:c39d3f$nqm$01$2 at news.t-online.com... > Under Linux, similar things worked for me. Did you call setDaemon(True) on > your bg threads? > No, i didnt call setDaemon ... is this essential to gain the functionality i want? Sebastian From stewart at midtoad.homelinux.org Fri Mar 12 22:06:23 2004 From: stewart at midtoad.homelinux.org (midtoad) Date: Sat, 13 Mar 2004 03:06:23 GMT Subject: drowning newbie References: Message-ID: elizabeth fletcher wrote: > Want to use Sam Rushing's calldll Python Module on a windows box. I don't > understand how to install it. I have several books that do not detail the > steps in installing a 3rd party module in Windows. Anybody want to throw > me life preserver? the installation process depends on whether you have source code or binary. If it's source code, usually you unzip a package, then look for a file called setup.py and run: python setup.py build (this step may not be required) and then python setup.py install Your module will go into PYTHONDIR / lib/site-packages/MODULE_NAME. if it's a binary dll file that you have, you just copy it into the folllowing directory: PYTHONDIR / DLLs. At least that's the general approach for Python2.3. cheers Stewart From llothar at web.de Wed Mar 24 16:44:42 2004 From: llothar at web.de (Lothar Scholz) Date: 24 Mar 2004 13:44:42 -0800 Subject: Python for large projects References: Message-ID: <6ee58e07.0403241344.2a7c1fa5@posting.google.com> "Raaijmakers, Vincent \(GE Infrastructure\)" wrote in message news:... > I agree, Python is great but Smalltalk still rules... > > Especially the development environments. If Python would have had the > same IDE it could so much more powerful. > Still don't understand that no commercial products are available that > even come close to that. > I would like to pay for it. Mature plugins in Eclipse, a 'P'Builder from > Borland..... > > Still, nothing compares to IDE's like VisualAge for Smalltalk. Indeed, > so productive. This has to do that Smalltalk and Python are both dynamical typed but completely different in technical points. You simply can't do a lot of things in Python that are so easy to do in an image based IDE. Because python code can do a lot of things during the import and imports can depend on the runtime there is a huge problem. This is a problem that nobody can solve, without changing the python language. From grahamd at dscpl.com.au Tue Mar 2 00:30:27 2004 From: grahamd at dscpl.com.au (Graham Dumpleton) Date: 1 Mar 2004 21:30:27 -0800 Subject: Licensing of wrappers around C/C++ code under more restrictive licensing. References: <7ed8f64d.0402280218.5ff447cf@posting.google.com> <9tt9h1-h1d.ln1@home.rogerbinns.com> <7uhch1-gev.ln1@home.rogerbinns.com> Message-ID: "Roger Binns" wrote in message news:<7uhch1-gev.ln1 at home.rogerbinns.com>... > > I am surprised you even went as far as looking at the license for OSE as > > in looking at "bitpim", not sure that what OSE had to offer in the way > > of functionality would even have made it appropriate for what you were > > doing. > > I am putting in an XML-RPC over SSL interface to allow the BitPim software > and the cell phone to be on different machines. OSE was attractive > because of the SOAP support as well. (I think it would have later > been ruled out due to lack of SSL anyway). Yep, no SSL support. The SOAP support is pretty basic as well, and is even a bit broken compared to XML-RPC. This is because the SOAP interface can't handle empty dictionaries, nor can it handle keys in dictionaries which aren't valid XML element names. These are problems with the SOAP XML encoding format, not with the ZSI SOAP toolkit used. The issue of keys in dictionaries being valid XML names is solved with some encoding mechanism in later SOAP versions, but am not sure if OSE automatically picks up the code changes in ZSI for that if present. I know of no solution to the empty dictionary problem. The basic problem is that at the other end it will decode as an empty string instead. Overall, OSE is better if your focus is actually C++ rather than Python and you want the Python wrappers for gluing stuff together and for add ons. If only using Python, you do get lumbered with a lot of extra baggage you don't really need. > Note section 7 of the Artistic License: > > 7. C or perl subroutines supplied by you and linked into this Package > shall not be considered part of this Package. You might want to look at the Artistic License 2.0. Its version of this clause is somewhat better written. Also, the Original Artistic License does get a lot of criticism because it has loopholes and is not actually deemed as being GPL compatible nor really a free software license. It only appears in the list of free software licenses because the criteria was relaxed in a certain way such that it was acceptable. There was conjecture that in time the criteria would be tightened and as a result the Original Artistic License would not longer be classifiable as a free software license. People will probably start to wonder what bullshit I am talking here and I may well be. I can't remember where, but I saw comments to this effect in my browsing in the last day when trying to find commentaries on the Artistic License 2.0. Unfortunately I still don't quite know what the idea of 4 (c) as an option in clause 4 is mean't to be at: 4 (c) permit and encourage anyone who receives a copy of the Modified Version permission to make your modifications Freely Available in some specific way. I see the Artistic License 2.0 as being possibly a good choice for what I do, but that one only has to satsify ONE of the parts of each of clause 4 and 6 worries me a bit as I feel that some of the choices really let people off very easily and may cause me conflict with other licenses I have to satisfy. I even saw one comment by someone which I am not at all sure about, which suggest that the Artistic License 2.0 was worded in such a way that it didn't prevent someone taking what you had done and then relicensing it under the GPL. If that is possible, that would not be good for me as you have lost any gaurantees of being able to preserve the intergrity of the overall package. So damn confusing at times, but then one shouldn't trust what people on the net say anyway on such things. > > I would like to make a bit of money from the 14 years of work that I > > have put into all of this. :-) > > Very understandable :-) If only monetizing open source software was > easy! I'd say it is nigh on impossible if what you are providing is nuts and bolts components. Yes it may be possible if what you have is an end user application, but if it is just glue ..... From skip at pobox.com Sat Mar 27 08:58:44 2004 From: skip at pobox.com (Skip Montanaro) Date: Sat, 27 Mar 2004 07:58:44 -0600 Subject: A 'Python like' language In-Reply-To: References: <40645d8f$0$10775$afc38c87@news.easynet.co.uk> <1068up4kn49778@news.supernews.com> Message-ID: <16485.34964.927473.201372@montanaro.dyndns.org> D> 3 solutions: D> 1. Use spaces instead of tabs. Hit the space bar yourself, or an D> editor that replaces tabs with spaces. Won't work. Prothon requires tabs. D> 2. Include as a .py or text file instead of inline. 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. D> 3. Get a different email program. That would be the tail wagging the dog. I suspect everybody writes far more email which doesn't include programs. They should be able to use whatever email program suits them best. 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. Skip From usenet at spling.plus.com Fri Mar 19 10:17:26 2004 From: usenet at spling.plus.com (Matthew Bell) Date: Fri, 19 Mar 2004 15:17:26 GMT Subject: Basic Inheritance Question References: <405aeb3c$0$41757$5fc3050@dreader2.news.tiscali.nl> Message-ID: Ruud de Jong wrote: > Matthew Bell schreef: > > I've got a conceptual problem to do with inheritance. > > I'd be grateful if someone could help to clear up my > > confusion. <...deletia...> > You were nearly there. You don't need a ; > __init__ does not return anything. > Just initialize the baseclass with the things you want: > >>> class myList(list): > def __init__(self): > list.__init__(self, [1,2,3]) > >>> m = myList() > >>> m > [1, 2, 3] > >>> Ruud, The light has come on! Thanks very, very much for the pointer. Given Python's general elegance I knew there must be an obvious way of doing this but I just couldn't see it. I do now. Thanks again, Matthew. From fumanchu at amor.org Thu Mar 25 14:52:36 2004 From: fumanchu at amor.org (Robert Brewer) Date: Thu, 25 Mar 2004 11:52:36 -0800 Subject: Decoding numerical and name based HTML entities Message-ID: William Park wrote: > Pieter Claerhout wrote: > > Hi all, > > > > what would be the easiest way in Python to decode HTML > entities to a unicode > > string? I would need a function that supports both > numerical as well as name > > based HTML entities. > > > > I already did some googling, but I only found a function > that decoded > > numerical ones, and this function didn't support unicode... > > Dictionary "table" would be first thing I'd try, ie. > tohtml['&'] = '&' > fromhtml['&'] = '&' That dictionary already exists ;) >>> import htmlentitydefs >>> htmlentitydefs.name2codepoint[u'amp'] 38 >>> unichr(38) u'&' Robert Brewer MIS Amor Ministries fumanchu at amor.org From skip at pobox.com Wed Mar 17 07:59:59 2004 From: skip at pobox.com (Skip Montanaro) Date: Wed, 17 Mar 2004 06:59:59 -0600 Subject: problem with cjkcodecs on Mandrake linux In-Reply-To: <20040317050108.71682.qmail@web13006.mail.yahoo.com> References: <4057C28E.92965723@alcyone.com> <20040317050108.71682.qmail@web13006.mail.yahoo.com> Message-ID: <16472.19407.226726.381537@montanaro.dyndns.org> Anthony> But I am using gbcxterm, which displays Chinese very well, Anthony> plus, I think I can also input Chinese using this terminal. Anthony> Then why do I still have this problem? Look in your installed site.py file for the encoding variable and change it as you like. The default is "ascii". Sounds like your sys admin may have changed it to "latin-1". Skip From shane at zope.com Thu Mar 25 10:19:40 2004 From: shane at zope.com (Shane Hathaway) Date: Thu, 25 Mar 2004 10:19:40 -0500 Subject: Make 'def' and 'class' usable within expressions In-Reply-To: References: <4062EF99.1050802@zope.com> Message-ID: <4062F88C.40200@zope.com> Thomas Heller wrote: > Shane Hathaway writes: >>> # Define an interface. >>> ICustomer = Interface(class): >>> def get_id(): >>> """Return the customer ID""" >> >>Today, this would be written as: >> >> class ICustomer: >> def get_id(): >> """Return the customer ID""" >> ICustomer = Interface(ICustomer) > > > With PEP 318 in place, it would be written as: > > class ICustomer [Interface]: > def get_id(): > """Return the customer ID""" > > Hm. > > I like the third way best. Why? The 'Interface(class)' idiom confuses > me. But maybe I'm infected by the PEP 318 virus. 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. Shane From lbates at swamisoft.com Wed Mar 31 13:02:46 2004 From: lbates at swamisoft.com (Larry Bates) Date: Wed, 31 Mar 2004 12:02:46 -0600 Subject: Creating Charts References: Message-ID: I use Reportlib/Graphics and it works well for me. I have one project where I generate nearly 8,000 unique barcharts (grading data for every school in my state) and it is very fast. I don't see the PIL requirement as bad, I use PIL for lots of other projects also. Getting this going is worth the effort. Larry Bates Syscon, Inc. "Thomas Guettler" wrote in message news:pan.2004.03.31.07.23.50.10533 at thomas-guettler.de... > Hi! > > I need to create some simple charts with python. > A list contains integers between 0 and mymax. > > I want to see how the values are distributed (How > many are 0, how many are mymax, ...). The result should > be a small (200x200) png file. > > I searched a bit: > - gnuplot: Too big, too complicated > - matplotlib: Too much gtk binding (I only need a png) > - reportlib: Needs PIL. First try failed (_renderPM missing) > > Any hints on how to create charts? > There need not to be a python-binding. I can > call the external application with os.system(). > > Operating System: Linux 2.4.20 > > Thanks, > Thomas > From patois at calvix.org Sat Mar 20 10:52:17 2004 From: patois at calvix.org (Yannick Patois) Date: Sat, 20 Mar 2004 16:52:17 +0100 Subject: Package name with '.' in them: Python Bug ? In-Reply-To: <105oe5k5ovugi5e@news.supernews.com> References: <105mmlt1ld7jvb9@news.supernews.com> <8ef9bea6.0403192150.57dbddef@posting.google.com> <105oe5k5ovugi5e@news.supernews.com> Message-ID: Hi, It's always very funny to read commented on onself at the third person;) I'm sorry to lost reader's time on this message, which is off-topic, but, I couldnt resist to respond, being directly involved in this post. John Roth wrote: > The reason he's getting the flack he's getting > His response to Terry's > original attempt to help him see what was going on was > both rude and sarcastic; that kind of behavior simply isn't > acceptable on this newsgroup. Then, the behavior of Terry should also have been quoted as rude and sarcastic. Most readers understood what I meant with my (incorrect) qualification of "static". I hope persons should be able to post here even if they dont master python vocabulary from a to z. If qualifiying someone as smart enough to correct my own lack of vocabulary is "both rude and sarcastic", then I feel that heavily underlining the lack of vocabulary of a contributor could be qualified the same. And my answer was so because of this attitude. Of course, it's not an excuse: replying to rudness by rudness is simply stupid, I do agree. 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 piedmontbiz at aol.com Wed Mar 3 20:21:32 2004 From: piedmontbiz at aol.com (PiedmontBiz) Date: 04 Mar 2004 01:21:32 GMT Subject: Multi-user quiz show game References: Message-ID: <20040303202132.12138.00000806@mb-m02.aol.com> > I'll let the experts answer this one. But I have a question. Do you rule >out a >> > http server ? If I were doing this I would avoid the apparent complexity >> > wxpython and just use standard html and javascript to pass the answers >to the >> > server. The python script could record time it got the "get" and return >it with >> > the validation. >> > >> > >> > allen >> >> Thanks, Allen! Your solution is actually quite attractive, as it just >> simplify the whole thing a lot.... I would consider it very >> seriously... >> >> Thanks again, >> Alex > > > > > > > > I was going to do this for my own curiosity, maybe a pythonics syntax quiz. But I wondered, if this was done over the internet rather than an intranet setup, how could a server script take into consideration the time it takes for a response to travel for the user to the server? Two or more users could submit the correct answer at the same galactic standard time yet their responses would be routed differently to the server. Allen Allen From jcarlson at nospam.uci.edu Sat Mar 27 14:02:27 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Sat, 27 Mar 2004 11:02:27 -0800 Subject: Beginner Threaded file reading access In-Reply-To: <106as5joq2o4n93@corp.supernews.com> References: <2835a96b.0403230909.35be2b7b@posting.google.com> <4im76054evpqbgkk2ja96rq66t1rm9r2uk@4ax.com> <106as5joq2o4n93@corp.supernews.com> Message-ID: >>It is even worse than that. In windows, Python is really a single >>process, and no amount of threading is going to let one instance of >>Python use more than 100% of a single CPU. I'm not sure if this is also >>the case with linux or OS X. >> > > Go through this with me. I agree with your conclusion, and I > don't keep up with Windows engineering. Moreover, I think it's > important that we educate the masses that multithreading in- > herently *slows* operations on a single CPU. However, I was > sure that Windows *does* include the ability to distribute > intraprocess native threads across SMP. Am I misreading you? > Are you making the point that Python's use of Windows threads > only provides for concurrency between, in practice, one I/O > and one computational operation? I should have given some background. I've got dual processors and run windows 2000. It works great. I've done threaded development, both in IO bound and in processor bound applications. On my dual processor machine, no amount of threads in a single Python process will ever allow you to use 100% of both processors. Up to 100% of one processor, which amounts to 50% of both with the automatic processor migration that Windows likes to do. I believe this is the result of Python threads needing the GIL, but don't quote me on that, I don't have an intimate working knowledge of the GIL or the inner workings of Python to know for sure. In practice, threads work just fine for IO bound applications; I've done blocking sockets programming with threads, and they've worked pretty well. However, the thread overhead is awful for more than a half dozen threads when you want to do /anything/ other than reading and writing from sockets. - Josiah From http Mon Mar 29 04:57:54 2004 From: http (Paul Rubin) Date: 29 Mar 2004 01:57:54 -0800 Subject: A 'Python like' language References: <40645d8f$0$10775$afc38c87@news.easynet.co.uk> <2jS9c.58187$cx5.18518@fed1read04> Message-ID: <7x7jx4gel9.fsf@ruckus.brouhaha.com> "Mark Hahn" writes: > > What does stacklessness do for me as an application programmer? > > The first thing is lack of recursion limits. Later you will find > continuations and other cool things. You gonna have a real compiler? You might also take the opportunity to back off on some of Python's dynamicness. Have you looked at PyPy? From jbenson at sextans.lowell.edu Tue Mar 30 19:55:47 2004 From: jbenson at sextans.lowell.edu (Jim Benson) Date: Tue, 30 Mar 2004 17:55:47 -0700 (MST) Subject: proper use of braces in Python (was: Prothon Prototypes vs Python Classes) In-Reply-To: <406A0CFD.2080600@mlug.missouri.edu> Message-ID: On Tue, 30 Mar 2004, Michael wrote: > > >>Right. Then we can have "does the brace go on the same line or the > >>next line" wars. > >> > >> > > > > int main (void) > > { > > if (true) > > { > > } > > > > return 0; > > } > > > >There is no other way. > > > > > No way, that wastes an entire line of code with a single brace! > > int main ( void ) { > if ( true ) { > return 1; > } > return 0; > } > > This is clearly better. Compact yet easy to read. I try formatting my > Python code exactly like this and it always complains about my braces.. > clearly wrong. > > Hi, ...just a food for thought from a Python list lurker. I have always been a strong adherent to the if (true) { } form. Not too long ago on this list (i think it was), someone pointed out that you never see: If (true) BEGIN: END humm...i thought, your right, in that case i guess i would probably write the BEGIN on a different line...not sure what indention of the END i would choose. Jim From newsgroups at jhrothjr.com Wed Mar 24 07:42:38 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Wed, 24 Mar 2004 07:42:38 -0500 Subject: PEP 318 References: Message-ID: <10630ij5763n72d@news.supernews.com> "Jess Austin" wrote in message news:e4e0340c.0403232103.7fd0d6b0 at posting.google.com... > 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? I don't know how you would unsupport it, actually. It's simply a function call, after all. John Roth From skchim0 at engr.uky.edu Mon Mar 1 18:52:44 2004 From: skchim0 at engr.uky.edu (Satish Chimakurthi) Date: Mon, 1 Mar 2004 17:52:44 -0600 Subject: Function calling another function References: Message-ID: <000901c3ffe8$4aae0540$0300a8c0@D4XN6B41> Hi all, Thanks a lot and sorry. It was an indentation mistake. Caused havoc for 30 mins for me. Thanks again Regards, Satish ----- Original Message ----- From: "Diez B. Roggisch" Newsgroups: comp.lang.python To: Sent: Monday, March 01, 2004 4:14 PM Subject: Re: Function calling another function > > My question is surely a basic one, but somehow, I am not able to figure it > > out. > > > When I execute satish.py, main() executes. I was expecting y() to execute > > first and then x() and then y() again. I wanted function x() to be capable > > of calling function y(). With this form of code, seems like function x() > > is not recognising function y(). Is there any sort of import or anything > > else that I can do here ?? > > Works for me: > > def main(): > y() > x() > > > def y(): > print "y" > > def x(): > print "x" > y() > > main() > > gives me: > > > x > y > x > > As expected. > -- > Regards, > > Diez B. Roggisch > -- > http://mail.python.org/mailman/listinfo/python-list From vqrsdw at yahoo.com Tue Mar 9 11:08:42 2004 From: vqrsdw at yahoo.com (wruuqr ewfjbc) Date: Tue, 9 Mar 2004 08:08:42 -0800 (PST) Subject: Remembered arguments to a function Message-ID: <20040309160842.66870.qmail@web60108.mail.yahoo.com> Should I have expected the behavior of this function? Is this a bug? Is it wise to exploit this behavior? def test(a, b, d={}): ''' sample output: Python 2.1.3 (#35, Apr 8 2002, 17:47:50) [MSC 32 bit (Intel)] on win32 Type "copyright", "credits" or "license" for more information. >>> x = test(1, 2) >>> x {1: 2} >>> x = test(3, 4) >>> x {3: 4, 1: 2} >>> y = test(5, 6) >>> y {5: 6, 3: 4, 1: 2} >>> test(7, 8) {7: 8, 5: 6, 3: 4, 1: 2} ''' d[a] = b return d __________________________________ Do you Yahoo!? Yahoo! Search - Find what you?re looking for faster http://search.yahoo.com From no at spam.com Wed Mar 31 13:35:33 2004 From: no at spam.com (Didier Morandi) Date: Wed, 31 Mar 2004 20:35:33 +0200 Subject: [OT] Top posting is a PITA In-Reply-To: <868yhhhv1u.fsf@igor.home.mkp.ca> References: <569c605ld1cj8fc1emolk08ete0s1prls1@4ax.com> <106di86neu1qh4d@news.supernews.com> <4069a001$0$4237$afc38c87@news.easynet.co.uk> <4069e9d9$0$8915$636a15ce@news.free.fr> <406a98ee$0$290$edfadb0f@dread12.news.tele.dk> <868yhhhv1u.fsf@igor.home.mkp.ca> Message-ID: Mike Pelletier wrote: ../.. > Didier Morandi said that the greatest reason for posting is so one may > "get help or information". Didier Morandi said that *his advice on* the greatest reason... D. From michele.simionato at poste.it Sat Mar 20 03:29:40 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 20 Mar 2004 00:29:40 -0800 Subject: parsing emails Message-ID: <95aa1afa.0403200029.6859e390@posting.google.com> I use Mozilla or Netscape, so my emails are stored in the nsmail directory or the Mozilla's equivalent. What's the simplest way to look at them and extract the mails with a given subject? In principle I could use a regular expression, but I bet there are better solutions already available. Second question: are Mozilla and Netscape compatible, i.e. are the emails stored with the same format and can I use the same extraction method on both? TIA, Michele Simionato From newspost at lolmc.com Wed Mar 24 14:07:34 2004 From: newspost at lolmc.com (Lol McBride) Date: Wed, 24 Mar 2004 19:07:34 +0000 Subject: Is this the correct way to implement TestSuite? Message-ID: Hi all, I've been using unittest for a while now but only creating test cases for individual modules of an application e.g class foo() has a reciprocal module called class fooTestCase() class bar() has a reciprocal module called class barTestCase() Now my app has quite a few modules and I want to run a single test that calls all of the xxxTestCase() modules and therefore runs all of the tests I have created so far.Looking at the docs for unittest I see a section showing the following code which seems to fit what I want: suite1 = module1.TheTestSuite() suite2 = module2.TheTestSuite() alltests = unittest.TestSuite((suite1, suite2)) However as I'm somewhat slow on the uptake for some things I'm unsure how to create the module to contain the code above.Below is what I think is how to do it and I would appreciate it if someone could let me know if this is correct or where I have gone wrong. import unittest import os import sys sys.path.append('../..') sys.path.insert(0,os.pardir) import fooTestCase import barTestCase class allTests(unittest.TestCase): def makeSuites(self): suite1 = module1.TheTestSuite() suite2 = module2.TheTestSuite() alltests = unittest.TestSuite((suite1, suite2)) -- It's action,reaction - random interaction. So who's afraid of a little abstraction?Can't get no satisfaction from the facts? you better run home boy,a facts a fact from Rome to Nome. Copyright Peart,Lifeson and Lee From rick_muller at yahoo.com Tue Mar 16 11:15:59 2004 From: rick_muller at yahoo.com (Rick Muller) Date: 16 Mar 2004 08:15:59 -0800 Subject: Advice needed: large OpenGL + Widgets Project for Molecular Graphics References: <5eb8fb88.0403151925.4f63842b@posting.google.com> Message-ID: <5eb8fb88.0403160815.36d716a6@posting.google.com> "Mike C. Fletcher" wrote in message news:... > Rick Muller wrote: > ... > > >3. Tkinter/PyOpenGL/Togl > > Advantages: Least amount of modules to install. > > > > Disadvantages: Tk is ugly. Tk is old. Tk doesn't look good on > > Macintosh/Aqua. Togl is either dead or dying? > > > > > Togl is pretty much history. I'll likely fix the installer one last > time for the next bug-fix release (2.0.2) and then drop the thing. I've > been looking for someone who uses Tkinter+Togl to champion maintenance > of the thing for years and never found anyone interested enough to > bother. I'm not a huge fan of Tkinter either, for that matter. Help me out with this: is it that the togl project is history, or that the Python bindings for Togl are history? I've poked around the Togl website (http://togl.sf.net), and I'm not overwhelmed with new releases. Plus, there don't seem to be many posts to the mailing list in the last year. But I'm amazed that more people don't need to put an OpenGL window in a graphical widget -- seems like a common task. How do people do this? Thanks for the responses! From tundra at tundraware.com Thu Mar 11 05:48:58 2004 From: tundra at tundraware.com (Tim Daneliuk) Date: 11 Mar 2004 05:48:58 EST Subject: [ANN]: twander 3.146 Released And Available Message-ID: 'twander' Version 3.146 is now released and available for download at: http://www.tundraware.com/Software/twander The last public release was 3.135 Existing users should upgrade as this release contains several bug fixes. This release also introduces these new features: 1) Abilty to toggle automatic refresh on- and off from the keyboard. 2) Ability to force a display refresh after a command is launched. 3) "Shortcut" (alias) references to the built-in variables when composing a command manually. Complete details of all fixes, changes, and new features can be found in the WHATSNEW.txt file included in the distribution. Users are strongly encouraged to join the twander-users mailing list as described in the documentation. What Is 'twander'? ------------------ 'twander' is a macro-programmable Filesystem Browser which runs on both Unix-like systems as well as Win32 systems. It embraces the best ideas of both similar GUI-driven programs (Konqueror, Windows Explorer) as well as text-based interfaces (Midnight Commander, List, Sweep). Or, If You Prefer The "Elevator Pitch" -------------------------------------- 'twander' is: - A better file browser for Unix and Win32. (Tested on FreeBSD, Linux, Win32.) - A way to make browsing the same on all the OSs you use. - A macro-programmable tool that lets *you* define the features. - A GUI navigation front-end for your shell. - A way to "can" workflows for your technically-challenged colleagues. - A way to free yourself from the shackles of the mouse. - A way to significantly speed up your day-to-day workflow. - A Python/Tkinter application - about 3100/1300 lines of code/comments - A RCT (Really Cool Tool) that will have you addicted in a day or two See the web page for more information and a screen shot. Better still, download the tarball and read the documentation. ------------------------------------------------------------------------------ Tim Daneliuk tundra at tundraware.com From fumanchu at amor.org Sat Mar 20 16:41:21 2004 From: fumanchu at amor.org (Robert Brewer) Date: Sat, 20 Mar 2004 13:41:21 -0800 Subject: New restrain builtin function? Message-ID: Pierre Rouleau wrote: > In several occasions, I found myself looking for a function > that would take a value and restrict is within a specified > set of boundaries... > > def restrain(value, theMin, theMax) : > > assert(theMax >= theMin) > return min(max(value,theMin),theMax) > I'd find a limit() function more useful, where either min or max is optional: def limit(value, lower=None, upper=None): """Return value limited by lower and/or upper bounds.""" if upper is not None: value = min(value, upper) if lower is not None: value = max(value, lower) return value This allows for single-boundary limits: >>> limit(3, 5) 5 >>> limit(3, upper=1) 1 And a no-op: >>> limit(3) 3 Also, you don't need to assert that upper >= lower; in fact, if upper is less than lower, you can use the same function for exclusive boundaries: >>> limit(3, 5, 1) 5 However, I find both restrain(3, 1, 5) and limit(3, 1, 5) difficult to read. It would be nice to produce the same thing with some other syntax. If we did it in C, we could at least write: limit(lower=None, value, upper=None). But perhaps there's some other means I'm not thinking of. It'd be nice to have "value" look different than upper and lower. Maybe something like: limit(value, (lower, upper)), or even value.limit(lower, upper) using a __limit__ customizable method. Hmm. Robert Brewer MIS Amor Ministries fumanchu at amor.org From donn at u.washington.edu Thu Mar 11 11:49:54 2004 From: donn at u.washington.edu (Donn Cave) Date: Thu, 11 Mar 2004 08:49:54 -0800 Subject: Python style guidelines References: <3064b51d.0403101112.3449e987@posting.google.com> <405035a3$1@pfaff2.ethz.ch> <405087fc$1@pfaff2.ethz.ch> Message-ID: In article , Peter Hansen wrote: [... re "if a.find(v):"] > I believe it's more likely they just forgot what find() did return, as > they were writing the code. I've done the same, thinking it was a > boolean, not thinking that it returned a negative but that negatives > were considered false. I'm sure that's common. In principle, seems to me that in many if not most cases the "index" function expresses the result better - for example, try: t = a.index(e) except ValueError: return a else: return a[:t] But for some reason, the average programmer seems to greatly prefer non-valid error returns over exceptions, even though they're naturally idiosyncratic and prone to this kind of error. I sure don't recall seeing "index" very often, anyway. Donn Cave, donn at u.washington.edu From axelboldt at yahoo.com Tue Mar 16 18:38:39 2004 From: axelboldt at yahoo.com (Axel Boldt) Date: 16 Mar 2004 15:38:39 -0800 Subject: Semantics of == Message-ID: <40200384.0403161538.7407d9e2@posting.google.com> 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) >>> 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. >>> s[0]=2 >>> w[0]=2 >>> s==w False All of a sudden they have become unequal. Axel From missive at frontiernet.net Sun Mar 7 09:43:05 2004 From: missive at frontiernet.net (Lee Harr) Date: Sun, 07 Mar 2004 14:43:05 GMT Subject: Eric /Qt documentation / how-to? References: Message-ID: On 2004-03-07, Stewart Midwinter wrote: > I'm trying to get an idea of how the Eric3 IDE works. I've got it > installed and running, and also have the Qt Designer installed and > running. Thanks to a a tutorial I found in the Qt section of the > moinmoin at python.org, I have figured out how to use .ui files in a > python script to create my GUI. So far, so good. > > What I don't see is the value I would get from using Eric3. I mean, I > can use the Scintilla editor on a standalone basis, and launch Qt > Designer manually. What extra value would I get by using Eric3? Is > there a way to create .py files out of .ui files by using Eric3? > I think the killer feature of eric is either debugging or refactoring. Take a look for docs mentioning "bicycle repair man" From rien at focus.demon.nl Sun Mar 28 13:35:26 2004 From: rien at focus.demon.nl (Rien Kok) Date: Sun, 28 Mar 2004 20:35:26 +0200 Subject: Installing Python 2.3.3 on RH 7.3 Message-ID: <106e6nge2aiiqa9@corp.supernews.com> Hi, I have a strange problem. I want to install Plone (Plone2-2.0.0rh-2.i386.rpm) Because Plone 2.0 needs Python 2.3.3, I installed Python 2.3.3 from source (Python-2.3.3.tar). Everything went well. After installing Python I did a reboot of the server and checked if Python works. Quote: [root at homeserver root]# python Python 2.3.3 (#1, Mar 28 2004, 11:29:35) [GCC 2.96 20000731 (Red Hat Linux 7.3 2.96-113)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> So I suppose I installed the right version of Python. But when I tried to install Plone2-2.0.0rh-2.i386.rpm it gives the following error: Quote: [root at homeserver Zope-Plone]# rpm -Uvh Plone2-2.0.0rh-2.i386.rpm error: failed dependencies: /usr/bin/python2.3 is needed by Plone2-2.0.0rh-2 expat >= 1.95.5 is needed by Plone2-2.0.0rh-2 libc.so.6(GLIBC_2.3) is needed by Plone2-2.0.0rh-2 python2.3 >= 2.3.3 is needed by Plone2-2.0.0rh-2 When I installed Python from source, Python was installed in "/usr/local/bin/" in stead of "/usr/bin/" so I copied "Python2.3" from "/usr/local/bin/" to "/usr/bin/" but that doesn't help. What can I do to change (or extend) the path so Plone can find the right version of Python. Thanks, Rien From joe at notcharles.ca Wed Mar 24 12:07:48 2004 From: joe at notcharles.ca (Joe Mason) Date: Wed, 24 Mar 2004 17:07:48 GMT Subject: Python for large projects References: Message-ID: In article , Jacek Generowicz wrote: > Sometimes I want to run a program that I _know_ full well is full of > bugs, dammit! During the whole of the development process, the > program is full of bugs, by definition ... I still want to be able to > see how it behaves, in order to investigate what to do about > it. Static type systems all too often forbid me to do this. (Even > Hindley Milner type systems.) But, like you said, type errors are the most trivial kinds of errors. Why do you want to know what'll happen if you pass it a float instead of an int, when you know full well that can never happen in practice due to static typing? (Wait, I know. So that you'll know whether it degrades gracefully or requires a big conversion function that will take effort to write. Damn, I'm not much of a devil's advocate, am I?) Joe From sross at connectmail.carleton.ca Tue Mar 23 11:19:18 2004 From: sross at connectmail.carleton.ca (Sean Ross) Date: Tue, 23 Mar 2004 11:19:18 -0500 Subject: explicit variable scoping References: Message-ID: <7rZ7c.11361$A_2.694679@news20.bellglobal.com> "Eyal Lotem" wrote in message news:mailman.279.1080051991.742.python-list at python.org... > Explicit "let"s do seem to get rid of the > local-vs-global issue, while providing an elegant > solution to the nested-functions variable access > problems. > > d=1 > e=9 > def f(): > def a=None,b=3 # Since locals are typically > # created via an assignment > # it makes much sense to allow > # unifying the creation of their > # scope [def] with the assignment > # to eliminate some redundancy > b=4 # rebinding > d=5 # raise error, neither local or global > global e > def g(): > e=10 # global assignment > b=5 # rebinding > def a=7 # new local binding > print a, b, e # will print None, 5, 10 Hi. Re-using "def" like that really is confusing. Maybe try "let": let d = 1 let e = 9 def f(): let a, b = None, 3 b = 4 # rebind d = 5 # raise error, should be "let d = 5" def g(): e = 10 # global assignment b = 5 # rebind b in f let a = 7 # new local binding print a, b, e # will print None 5 10 Or, perhaps ":=" : d := 1 e := 9 def f(): a, b := None, 3 b = 4 # rebind d = 5 # raise error, should be "d := 5" def g(): e = 10 # global assignment b = 5 # rebind b in f a := 7 # new local binding print a, b, e # will print None 5 10 From gh at ghaering.de Thu Mar 4 20:15:37 2004 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Fri, 05 Mar 2004 02:15:37 +0100 Subject: How to find size of file? In-Reply-To: References: Message-ID: Walter Huf wrote: > 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? >>> import os >>> os.stat("c:/tmp/x.html").st_size 567L -- Gerhard From stewart at midtoad.homelinux.org Fri Mar 5 23:38:49 2004 From: stewart at midtoad.homelinux.org (midtoad) Date: Sat, 06 Mar 2004 04:38:49 GMT Subject: A Byte of Python - Python Book / Tutorial References: <5168381b.0403051311.5f1c843f@posting.google.com> Message-ID: another question - in your quick summary of GUI libraries, what happened to Tkinter? It seems to have by far the most extensive documentation available, so it is conspicuous by its absence. cheers Stewart From steve at ninereeds.fsnet.co.uk Tue Mar 23 19:19:17 2004 From: steve at ninereeds.fsnet.co.uk (Stephen Horne) Date: Wed, 24 Mar 2004 00:19:17 +0000 Subject: PEP318 alternate syntax idea References: Message-ID: I seem to have written more than I intended below. Whether the repetition of decorators will be a real issue is, of course, undecided. Maybe the idea anticipates a problem which will never be important anyway. What I mean to say is that, if the following reads like I'm upset or on the attack or something, I'm not. Sometimes, when I'm just trying to be clear what I'm saying, I actually get very verbose and very unclear, and too often I get right up peoples noses. Especially when I'm stressed out for other reasons, as is definitely the case right now. I hope this isn't _too_ bad... On 23 Mar 2004 11:39:05 -0800, JimJJewett at yahoo.com (Jim Jewett) wrote: >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. First off, indented blocks work in a very similar way to each other in Python simply because of convenience - Python is a dynamic language and can thus do many things with imperitive code that static languages cannot. But that doesn't mean there is a fundamental principle at work here. In terms that an evolutionary theorist might used, this pattern is a spandrel - an indirect and accidental consequence of something else. The principle is that 'dynamic is good', which says nothing at all about the meaning of indented blocks. In programming in general, indented block structures serve a range of purposes, many of them having nothing to do with how code is executed. Member declarations in a statically typed language, for instance, are not executed at all because they are not imperitive code. If it is useful to group a range of things together for any purpose, an indented block is very often the means of doing it. The indentation is often optional in terms of the language spec., but that is besides the point. Python has not, AFAIK, deliberately opted out of that 'anything whenever it's the right thing' use of blocks. It has tended to only use a restricted type of block, but not out of principle - only as a side-effect of something else. Other kinds of blocks may still be 'the right thing'. Besides, I'm not confident that the distinction you have drawn is valid. Any statement in 'if', 'while' and 'for' indented blocks is 'normal'. What is modified is NOT how the code is run, but merely whether, when, or how many times the block as a whole is run. Once the code in the block is entered, it progresses normally just as if it was not in an indented block. Compare that with the code within a class or function definition. There is more 'strange' going on than just control over when the code is executed. Assignments and definitions operate differently, so that the items assigned or defined end up in a different namespace dictionary. If it is valid to modify assignments and definitions such that the targets of assignments and declarations are different, then why isn't it valid to change other aspects of the way that assignments and declarations are completed? IMO, there is no fundamental difference between decorating and redirecting in this context. All it implies, after all, is that the current dictionary gets wrapped with something that overrides __setattr__ (to something that applies the decorators before calling the wrapped dictionarys __setattr__). Basically, even if there were any principle behind restricting what an indented block can do beyond asking 'what is the right thing' (which AFAIK there isn't), class and def blocks already do, in part, essentially the same thing that a decorate block would do (tweak the way that assignments and definitions operate by changing the dictionary that they target). >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. There are frequently many functions in a class that follow a similar pattern simply because they do similar jobs. Take, for instance, the following in the Python string class... isalnum, isalpha, isdigit, islower, isspace, istitle, isupper Isn't it logical that if one function in such a group needed decorating, all of them would? Of course it is! Does that mean that there is some link between the decorations, or that there is a sensible name for the whole set of decorations? Of course not! The pattern in the decorations is another example of a spandrel - the reason for the pattern lies elsewhere (in the overall similarity between the member functions) and has nothing much to do with the meanings of the decorators. -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From sdementen at hotmail.com Wed Mar 17 02:34:27 2004 From: sdementen at hotmail.com (Sebastien de Menten) Date: 16 Mar 2004 23:34:27 -0800 Subject: destructuring tuple and list Message-ID: <8dad5312.0403162334.435de9c6@posting.google.com> 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... Thank you Sebastien From bart_nessux at hotmail.com Fri Mar 12 22:15:44 2004 From: bart_nessux at hotmail.com (Bart Nessux) Date: Fri, 12 Mar 2004 22:15:44 -0500 Subject: root password in a .py script References: <87y8q5g8sg.fsf@strauser.com> Message-ID: What do you guys think of something like this... I know it's not safe, but it would keep the *average* user from immediately seeing the password: def stupid(): objects0 = ["j", "a", "b"] objects1 = ["T", "x", "f"] objects2 = ["/", ":", ";"] objects3 = ["d", "w", "v"] objects4 = ["0", "9", "4"] objects5 = ["H", "B", "G"] objects6 = ["!", "~", "'"] objects7 = ["o", "l", "e"] objects8 = ["U", "M", "E"] objects9 = ["=", "+", "-"] compiled = objects9[0] + objects1[2]\ + objects5[0] + objects6[1] + objects0[2]\ + objects4[1] + objects3[2] + objects7[1]\ + objects2[2] + objects8[0] return compiled stupid() How else could I twist this up? From ephilpva at sfs.uni-tuebingen.de Mon Mar 22 08:47:45 2004 From: ephilpva at sfs.uni-tuebingen.de (Katja Filippova) Date: Mon, 22 Mar 2004 14:47:45 +0100 Subject: problems with nltk Message-ID: <405EEE81.1050201@sfs.uni-tuebingen.de> hi, Has anybody tried using natural language toolkit (http://nltk.sourceforge.net/) under Python (my version is 2.1.1)? problems: first, I wanted to import a module, as it is written in the manual, but it didn't work: >>> from nltk.token import * Traceback (most recent calls last): File "", line 1, in ? ImportError: No module named nltk.token since there was such module I thought that Python simply didn't look for it in the right directory and I rewrote the path: import sys, os SRCDIR="/home/name/nltk-1.3" sys.path.append(SRCDIR) print sys.path After that the error message changed to: >>> from nltk.token import * Traceback (most recent call last): File "", line 1, in ? File "__init__.py", line 49, in ? ---------------- File "/...........python211/lib/python2.1/lib-tk/Tkinter.py", line 35, in ? import _tkinter # If this fails your Python may not be configured for Tk ImportError: libtk8.3.so: cannot open shared object file: No such file or directory Then I typed import _tkinter but it didn't help, I got the same error message as before: File "/...........python211/lib/python2.1/lib-tk/Tkinter.py", line 35, in ? import _tkinter # If this fails your Python may not be configured for Tk ImportError: libtk8.3.so: cannot open shared object file: No such file or directory If I try to import the module again I get: Traceback (most recent call last): File "", line 1, in ? File "/home/name/nltk-1.3/nltk/token.py", line 308 yield self._deep_restrict(item, props, incl) ^ SyntaxError: invalid syntax Does it really mean that Python is not configured for Tk? What does "" mean? Is it the problem with nltk rather than with Python? thanx in advance, Katja From skip at pobox.com Wed Mar 24 10:32:19 2004 From: skip at pobox.com (Skip Montanaro) Date: Wed, 24 Mar 2004 09:32:19 -0600 Subject: declaring multimethods [Was: Re: 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: <16481.43523.114080.750272@montanaro.dyndns.org> Michele> Please take what I posted just as an idea (it is not even my Michele> idea!), not as an implementation proposal. I don't have an Michele> implementation, but I am pretty much convinced that it is Michele> possible and not that hard. ... Michele> Just to support your point that the decorator idea is a Pandora Michele> box, and we can extract anything from it ;) Perhaps, but the box is already there. All the decorator syntax does is maybe make it a bit easier to pry off the lid. ;-) Still, I'd like to follow this thread just a little further, mostly just to see where it goes. I will assume the presence of PEP 318 decorators. We have a Matrix(?) class which we want to multiply by various other object types: class multimethod [singleton]: def __init__(self): self.methods = {} def __call__(self, t1, t2): def decorator(f): ... here's where the work gets done ... return something_like_f return decorator class Matrix: 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 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 object. It knows the proposed types from t1 and t2 in the enclosing method's scope and it knows the function's name, so it has enough for a C++-style signature. It can save a list of tuples consisting of the function object and t2 in self.methods keyed by the name and t1 (t1 must always be the class). Hmmm... t1 presents a problem since at the time multimethod(Matrix,Matrix) is called there is no Matrix class available (it hasn't been bound yet). You'd have to fudge that and use strings as the type names. That presents another problem. Classes, unlike functions, don't have name attributes, so mapping the names passed to multimethod() to classes is problematic. You could punt and decorate the class: class Matrix [attributes(_name="Matrix")]: ... but then you're naming the class twice. 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")]: 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 Skip From user_77 at hotmail.com Thu Mar 4 09:27:01 2004 From: user_77 at hotmail.com (Nobody) Date: Thu, 04 Mar 2004 14:27:01 GMT Subject: testing - please ignore References: Message-ID: "Barry Warsaw" wrote in message news:mailman.6.1078363609.772.python-list at python.org... > This is a test message, please ignore. > > -Barry > > > > No. :) From stewart at midwinter.ca Fri Mar 19 16:09:39 2004 From: stewart at midwinter.ca (Stewart Midwinter) Date: 19 Mar 2004 13:09:39 -0800 Subject: Getting both PID and output from a command References: <3cc4824d.0403190259.1e06a578@posting.google.com> Message-ID: <9396ba6f.0403191309.7d3b7439@posting.google.com> hugh at brokenpipefilms.com (Hugh Macdonald) wrote in message news:<3cc4824d.0403190259.1e06a578 at posting.google.com>... > I'm calling a command from within a python script and I need to be > able to both catch the output (stdout and stderr) from it and also > have the PID (so that I can kill it) Take a look in PyPi for popen5. It may do what you want, but only in Linux: the Windows version isn't complete yet. S From ally_burnett at yahoo.co.uk Thu Mar 18 05:59:49 2004 From: ally_burnett at yahoo.co.uk (alastair) Date: 18 Mar 2004 02:59:49 -0800 Subject: Handling geoTIFF files References: <23ae7099.0403170210.540888cd@posting.google.com> Message-ID: <23ae7099.0403180259.6241c23a@posting.google.com> Hi, Thanks for the advice so far - I've had a look at GDAL but I'm not sure how to get started, and can't seem to find a whole lot of information to help me. If you can offer any advice on how to use the GDAL library in Python that would be great (or anywhere I can find a tutorial/help). Thanks, Alastair. From bogus@does.not.exist.com Sun Mar 14 10:01:13 2004 From: bogus@does.not.exist.com () Date: Sun, 14 Mar 2004 07:01:13 -0800 Subject: List append help References: <105811aq55rah53@corp.supernews.com> <40540841.8070802@zoran.com> <1058329gsgeq85f@corp.supernews.com> <140320040426395478%DavidMLewis.NO@SPAM.mac.com> Message-ID: <1058stra6a89193@corp.supernews.com> Thank you! David Lewis wrote: > >In article <1058329gsgeq85f at corp.supernews.com>, Bill wrote: > >> Thank you, This was really bugging me. To help me understand, do you know >> why the return value was None even though it was added to the list? > >It?s a philosophical decision made throughout Python. When an operation >is destructive (i.e. it changes the object on which it operates rather >than returning a new, changed, object), it returns None to emphasize >the point. > >Best, > David From ketulp_baroda at yahoo.com Sun Mar 7 08:00:19 2004 From: ketulp_baroda at yahoo.com (ketulp_baroda at yahoo.com) Date: 7 Mar 2004 05:00:19 -0800 Subject: attachment References: <4049ad99$0$564$e4fe514c@news.xs4all.nl> Message-ID: Irmen de Jong wrote in message news:<4049ad99$0$564$e4fe514c at news.xs4all.nl>... > ketulp_baroda at yahoo.com wrote: > > > 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?? > > No, the actual file contents is submitted as part of the HTTP POST request. > (make sure you use method="post" and enctype="multipart/form-data" in your form). > Python's cgi module knows how to deal with it. > > Where you store your file is entirely up to you and depends on what > you want to do with it. > > --Irmen Hi Thanks for your reply. Ya the actual contents are posted along with the file. See my application is like this: 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 From val at vtek.com Tue Mar 9 09:06:19 2004 From: val at vtek.com (Val Bykoski) Date: 9 Mar 2004 06:06:19 -0800 Subject: dynamic names References: Message-ID: "Diez B. Roggisch" wrote in message news:... > Mel Wilson wrote: > > > tot = tot + eval ("L%s" % L) > > exec is a statement. > > Yup - OPs wrong usage of exec confused me on that one. Thanks for pointing > it out. Thanks so much you guys for all your help and advice. Now i understand much better my problem (i didn't before!) and love Python even more. enjoying-to-learn-from-great-community-ly y'rs, val From anton at vredegoor.doge.nl Sat Mar 27 03:47:00 2004 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Sat, 27 Mar 2004 09:47:00 +0100 Subject: Converting IBM Floats..Help.. References: <40641706$0$133$3a628fcd@reader1.nntp.hccnet.nl> <1069j3h2kb44909@news.supernews.com> Message-ID: <40653fa6$0$122$3a628fcd@reader3.nntp.hccnet.nl> "John Roth" wrote: >> Some time ago there was a question on this group about 4-byte IBM >> floats, and maybe questions about other formats will follow in the >> future. Here's a flexible -but possibly slow?- approach to handle >> these kind of problems. It uses a stream of bytes (a file for example) >> as input and returns a series of floats. > >There are only the two legacy formats. More recent >IBM mainframes also support standard IEEE-488 floating >point, which should provide no difficulty whatsoever in >converting. No byte borders anymore. I'm redefining the world and you are still talking about IBM-floats? Anton From jcm at FreeBSD-uk.eu.org Wed Mar 3 13:15:44 2004 From: jcm at FreeBSD-uk.eu.org (Jonathon McKitrick) Date: Wed, 3 Mar 2004 18:15:44 +0000 Subject: ready to use python, need help with GUI decision Message-ID: <20040303181544.GB74292@dogma.freebsd-uk.eu.org> Hi all, I am totally hooked on what I have learned about python. I am going to use it to develop a simple data entry app I need for some financial record keeping. I understand tkinter is official and simple to use, but many who use wxPython swear by it, and it is gaining ground. I would like to run on any platform, but that's not critical. What I want to do is support an app that will grow over time, and should look clean. I don't want to spend lots of time maintaining GUI code rather than app logic. Can anyone offer any advice? jm -- My other computer is your Windows box. From miki.tebeka at zoran.com Thu Mar 18 16:46:36 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Thu, 18 Mar 2004 23:46:36 +0200 Subject: shutils.move lose files ! In-Reply-To: <409a56e2.0403180527.29c851a1@posting.google.com> References: <409a56e2.0403180527.29c851a1@posting.google.com> Message-ID: Hello Shagshag, >>>>import os >>>>os.mkdir('c:/stupid') >>>>open('c:/stupid/atest.txt', 'w').write('a file') >>>>os.listdir('c:/stupid') > > ['atest.txt'] > >>>>import shutil >>>>shutil.move('c:/stupid', 'c:/stupid/donotexist') >>>>os.listdir('c:/stupid') > > > Traceback (most recent call last): > File "", line 1, in -toplevel- > os.listdir('c:/stupid') > WindowsError: [Errno 3] Le chemin d'acc?s sp?cifi? est introuvable: > 'c:/stupid/*.*' >>> from os import mkdir, listdir >>> from shutil import move >>> mkdir("c:/temp/xxx") >>> open("c:/temp/xxx/moo", "w").write("moo") >>> move("c:/temp/xxx/moo", "c:/temp/xxx/goo") >>> listdir("c:/temp/xxx") ['goo'] >>> This is on win2k Miki From robin at jessikat.fsnet.co.uk Fri Mar 12 03:41:54 2004 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Fri, 12 Mar 2004 08:41:54 +0000 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: In article , Richard Tobin writes >> 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 I guess that's why there are now two versions pyRXP & pyRXPU. Personally I find XML pretty awful as a lingua franca, but everyone else seems to think it's the new sliced bread. As to whether RXP is a good 'parser' my latest test of pyRXPU (RXP 1.3.0) with James Clark's XML Test Cases version 1998-11-18 gives Ran 373 tests in 1.282s FAILED (failures=2, errors=1) Clearly I have some way to go and we'll have to work harder. -- Robin Becker From aahz at pythoncraft.com Sat Mar 13 19:56:23 2004 From: aahz at pythoncraft.com (Aahz) Date: 13 Mar 2004 19:56:23 -0500 Subject: Python & the job market References: Message-ID: In article , kbass wrote: > >I am starting to learn Python but I want to know how the job market >looks for programming using Python. I really don't see many jobs >(probably one or two) that require Python experience at all. Most DBA >and SA positions that I have seen require Perl and most development >position require Java or C++ so how can learning Python benefit my >career if there are little to no chance that an employer will require >the use of Python or consider using Python over other programming >languages such as Java? Have you looked at http://www.python.org/Jobs.html ? In general, jobs that require programming but not as a primary skill (such as DBA and SA positions) allow one the opportunity to add Python gradually and silently. They're easier than straight programming jobs in some respects because projects tend to be smaller and less visible. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "usenet imitates usenet" --Darkhawk From max at alcyone.com Sat Mar 20 19:45:22 2004 From: max at alcyone.com (Erik Max Francis) Date: Sat, 20 Mar 2004 16:45:22 -0800 Subject: file.tell() ? References: <731b3eeb.0403201635.8fa84d@posting.google.com> Message-ID: <405CE5A2.E07A692D@alcyone.com> Chris McAvoy wrote: > The reason I ask is, I have a very large file to parse line by line. > I thought I'd try and use an iterator, but it looks like the iterator > is really reading the entire file into memory before it starts > iterating. So my best option is still to use file.readline(). > > Am I understanding this correctly? Am I using the iterator > incorrectly? The iterating methods of file input tend to buffer input, so calling things like .tell or additionally trying to read data manually is not going to work properly. If it's important to you that you have total control over the current "read pointer" in the file, call .readline manually. If you don't care and just want to read through everything, use the iterators. -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE \__/ The average dog is a nicer person than the average person. -- Andrew A. Rooney From demian0311 at yahoo.com Thu Mar 4 21:13:18 2004 From: demian0311 at yahoo.com (demian neidetcher) Date: 4 Mar 2004 18:13:18 -0800 Subject: vim & python References: <221dd125.0403011151.504ce09d@posting.google.com> <221dd125.0403032332.d4282f4@posting.google.com> Message-ID: <1668af80.0403041813.354d19d6@posting.google.com> > Thanks for all of the answers to the second question, but what about > vim scripting with python? I can not find *anything* about it (no > docs, books or tutorials) i'm not using the built-in integration that can be built into vim. my vim scripting with python is really just re-directing lines in a file from vim thru a python script that reads from std in (your code from vim) and writes to std out (the results replace your old lines). here are some scripts i have, might give you an idea of what i'm doing. http://www.ophinity.com/papers/wrangling/index.html From owp at utanet.at Tue Mar 16 06:09:48 2004 From: owp at utanet.at (Simon Erikson) Date: 16 Mar 2004 03:09:48 -0800 Subject: wxPython "Frames within Frames" Message-ID: Hello: I would like to build an app consisting of a "root" frame that can contain an arbitrary number of child frames (the user will click to create them). Each of these child frames needs the full functionality of a frame (title,menu,status bars, min,max,close icons, scroll bars, sizing, moving). In addition, the user must be able to create grandchild frames within these child frames, to an arbitrary depth (in practice limited to 10 or so). As I understand it, MDI provides the means of creating the root and first generation frames, but not the further generations. I found this at 'http://www.orbtech.com/www/wx/epydoc/public/wx.Frame-class.htm' A frame is a window whose size and position can (usually) be changed by the user. It usually has thick borders and a title bar, and can optionally contain a menu bar, toolbar and status bar. A frame can contain any window that is not a frame or dialog. Does this last sentence mean my quest is hopeless? Can someone please help me? Thanks - Simon. From miki.tebeka at zoran.com Thu Mar 11 19:44:23 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Fri, 12 Mar 2004 02:44:23 +0200 Subject: wrestling with unittest paths..needs suggestions In-Reply-To: References: Message-ID: <405107E7.9020307@zoran.com> Hello Vincent, > path to main class... say: > > path = /home/workspace/src/foo > There is a module Foo.py > /home/workspace/src/foo/Foo.py > > My unittest is in: > /home/workspace/src/test/foo > so: > /home/workspace/src/test/foo/FooTest.py Usually the `test' directory is under the source directory (/home/workspace/src/foo/test), this simplifies things. > import os, sys > testpath = os.path.abspath('/home/workspace/src/foo') > sys.path.append(testpath) > > Well, it works but if I have to do that for every test module that I write.. > Very nasty.. Have a look at python's test suite for a good example (/usr/lib/python23/test). There is one `test_support.py' module that each test import. If you need you can fix the path in this module only. If you use foo/test then just write `sys.path.append("..")' in test_support.py HTH. Miki From steve at ninereeds.fsnet.co.uk Sat Mar 27 20:35:43 2004 From: steve at ninereeds.fsnet.co.uk (Stephen Horne) Date: Sun, 28 Mar 2004 02:35:43 +0100 Subject: A 'Python like' language References: <40645d8f$0$10775$afc38c87@news.easynet.co.uk> <1068up4kn49778@news.supernews.com> Message-ID: <1f9c60dtvj2alu8lk522l29nerqrv0trv3@4ax.com> On Fri, 26 Mar 2004 20:25:11 +0100, Valentino Volonghi aka Dialtone wrote: >Anyway GvR just posted on the python-dev saying this: > >== >No, I want to reserve the leading dot for attribute assignment to a >special object specified by a 'with' statement, e.g. > >with self: > .foo = [1, 2, 3] > .bar(4, .foo) >== I missed that. There's good precedent - it's the Pascal 'with' block, but better (the leading dot tells you that you're dealing with a 'with' item rather than normal scoping rules). But - well - just recently, people keep telling me that indented blocks are purely about control flow. I keep disagreeing, but no-one has bothered agreeing with me so I was feeling rather lonely and miserable in this crusade :-( A 'with' block clearly has nothing at all to do with control flow. All it does is provide some kind of local context for the contents of the block. Very much like a suggestion or two that I have made recently (none of which all that original, as far as I can tell). Nonetheless, I will object. The with block, in this form, provides an abbreviated alias for one identifier. Zero length is quite severely abbreviated, of course, but better 'compression' could frequently be achieved by abbreviating two or more identifiers. For general applications, I'd rather have a small blocks and a simple alias facility. An alias would never make it into dictionaries - it would be handled entirely by the compiler. For example... someverylongname = 1 block : alias x = someverylongname x = 2 print someverylongname # result is '2' Depending on how the alias was implemented, it might also be possible to alias certain kinds of expression... alias x = someobj.someobj.membername I wouldn't allow arbitrary expressions here, and it raises questions about when the alias is bound to the referenced object which start to push things towards normal identifiers so I'd have serious thoughts, but there are cases that are probably worth considering where an alias could reasonably be bound by the compiler without needing to insert anything into any runtime dictionaries. The trouble is that doing something like that would probably be difficult as the compiler would need dictionary-like symbol tables above and beyond what exists in the runtime environment, and the run-time environment would have to provide for storage beyond what is held in the normal dictionaries. Anyway, personally, I'd say the prefix dot should be reserved for 'self' if used at all. It will certainly be by far the most common case, perhaps to the point that people will assume 'self' as soon as they see the prefix dot, which means that readability will be affected by using 'with' for other variables. And if using 'with' for anything other than 'self' creates readability issues and gets to be considered bad style, the 'with' line itself is redundant. -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From peter at semantico.com Fri Mar 12 04:42:12 2004 From: peter at semantico.com (Peter Hickman) Date: Fri, 12 Mar 2004 09:42:12 +0000 Subject: OFF-TOPIC:: Why Lisp is not my favorite programming language In-Reply-To: <40515E92.3080201@nospam.uci.edu> References: <165b3efa.0403030443.4d591f04@posting.google.com> <404675da@news.tce.com> <1sw3c.20562$rD5.1087@twister.socal.rr.com> <40515E92.3080201@nospam.uci.edu> Message-ID: <405185f5$0$16368$afc38c87@news.easynet.co.uk> Josiah Carlson wrote: > 3. Spend a month teaching her object orientation with C++. Perhaps Ruby for the OO stuff if you are familier with it. Less gotcha's than C++. All depends on the sort of person she is. A wide range of programming languages is always a good idea. How about Prolog just for the hell of it? From michele.simionato at poste.it Wed Mar 24 00:20:34 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 23 Mar 2004 21:20:34 -0800 Subject: PEP 318 - posting draft References: Message-ID: <95aa1afa.0403232120.28f166dc@posting.google.com> Skip Montanaro wrote in message news:... > Here's the current state of PEP 318. I have no strong opinion about "[]" vs. "as", so brackets can go. However, may I suggest that (for Python 2.4) we only implement single decorators for functions only? The order of application in the case of multiple decorators is not obvious and actually I am not convinced the current proposal is the best one for the multiple decorator case. So, I will stick to the original PEP request (single decorators for functions) for Python 2.4, leaving further extensions (I want further extensions, but not *right* now) for the future. We need more thinking and experience with the multiple decorator syntax before adding it to the language. Just my $0.02, Michele Simionato From altis at semi-retired.com Wed Mar 17 13:31:41 2004 From: altis at semi-retired.com (Kevin Altis) Date: Wed, 17 Mar 2004 10:31:41 -0800 Subject: simple http server References: Message-ID: "Gelo Ilzi" wrote in message news:c39rul$dri$1 at news2.netvision.net.il... > I'm trying to implement a very simple http server with cgi functionality. > The code is simple: > > import CGIHTTPServer, BaseHTTPServer > httpd = BaseHTTPServer.HTTPServer(('',8000), > CGIHTTPServer.CGIHTTPRequestHandler) > httpd.serve_forever() > > I've created a subdir 'cgi-bin' which contains a python script. Now when I > enter this directory, i.e., go to the url http://localhost:8000/cgi-bin/ my > browser shows: > > Error response > Error code 403. > Message: CGI script is not a plain file ('/cgi-bin/'). > Error code explanation: 403 = Request forbidden -- authorization will not > help. > > Plain html pages are ok. > > It seems I misunderstand something very basical. Could somebody help me > please. > > Thank you in advance. That is correct behavior, you can't browse the cgi-bin directory. Put a CGI script in that directory like the one below to dump the environment variables and then go directly to that URL. Depending on your platform and location of Python, you might have to change the first line, but this will verify your CGIs are working. ka --- #!/usr/local/bin/python print "Content-type: text/html\r\n\r\n", print '' print "" print "
"
import os, sys
from cgi import escape
print "Python %s" % sys.version
keys = os.environ.keys()
keys.sort()
for k in keys:
    print "%s\t%s" % (escape(k), escape(os.environ[k]))
print "
" print "" From savieg at stadt.duesseldorf.de Wed Mar 24 11:02:19 2004 From: savieg at stadt.duesseldorf.de (savieg at stadt.duesseldorf.de) Date: Wed, 24 Mar 2004 17:02:19 +0100 Subject: !!Virus gefunden!! Message-ID: <20040324160727.5528E409E2@mail02.duesseldorf.de> Es wurde ein Virus in Ihrer E-Mail gefunden: --- Scan information follows --- Result: Virus Detected Virus Name: W32.Mydoom.F at mm File Attachment: svtbkc.zip Attachment Status: deleted --- Original message information follows --- From: python-list at python.org To: heinrichh at intramail.stv-ddorf.de Date: Wed, 24 Mar 2004 10:07:19 -0600 Subject: STOLEN Message-Id: <20040324160723.D94B75CEF1 at mail01.duesseldorf.de> Received: from mail01.duesseldorf.de ([194.113.247.113]) by SAVIEG.stv-ddorf.de (SAVSMTP 3.1.1.32) with SMTP id M2004032417021911043 for ; Wed, 24 Mar 2004 17:02:19 +0100 From deetsNOSPAM at web.de Tue Mar 30 08:14:29 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Tue, 30 Mar 2004 15:14:29 +0200 Subject: marshalling python data structures in php References: <930ba99a.0403292243.2d5d3997@posting.google.com> Message-ID: > any thoughts? Use xmlrpc or soap or corba - these are designed for inter-language operations. There is no need to reinvent the wheel. -- Regards, Diez B. Roggisch From molivier at caregroup.harvard.edu Sat Mar 13 17:36:41 2004 From: molivier at caregroup.harvard.edu (supportgeek) Date: 13 Mar 2004 14:36:41 -0800 Subject: read/enter text based on cursor position Message-ID: Greetings. Would anyone know the right direction to point me on this one? I need to read text from a Windows Application based on cursor position. And enter text based on what is read. Example:(the interface of the windows application would look something like this.) ----------------------------------- Windows Application X ----------------------------------- Name: Address: City: State: Zip: ----------------------------------- I need to scan the application for address - and put in my address, etc... Right now I am using sendkeys but it really isn't cutting it) The only part I need help on in this is getting the location of where it says address, or whatever field is the case. I was thinking it might be possible to somehow read to the left based on cursor position. If anyone could point me in the right direction I would appreciate it. Thanks in Advance. Mike From http Thu Mar 4 11:52:26 2004 From: http (Paul Rubin) Date: 04 Mar 2004 08:52:26 -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> Message-ID: <7x7jy0o8qd.fsf@ruckus.brouhaha.com> paul at boddie.net (Paul Boddie) writes: > As a PHP replacement, I'd argue that a number of existing frameworks > are good and obvious enough - cue developer adverts for Spyce, > CherryPy, etc. ;-) While those are nice pieces of code, they're not in the official distribution, which means they're a separate point of failure for maintenance, security auditing, and so forth. I.e., if you're trying to pitch Python for some project and convince management that it's secure and adequately maintained, you now have to separately make the exact same pitch for Spyce. And you then have to pick out a database interface layer and make another separate pitch for THAT. With PHP, pitch once, get a yes or no, and you're done. And no, that's NOT a pointy-haired boss problem, those are real issues, not bureaucrats being stupid. > With the PSP support in mod_python, I'd argue that > the bar has been lowered further. I'm not familiar with this and will have to check into it further. > But in the short to medium term, expect better application > portability between frameworks - the need to run various popular > applications in different environments is making itself increasingly > evident. You mean the problems of having a "multitude" of environments are making themselves evident. If Python is to have anything like PHP's wide deployment for web apps, the maintainers have to pick one of those environments (probably Zope, I guess), include it in the official Python distribution and declare it to be under official maintenance, and do the same for a database interface. To first approximation, if something isn't in the official distribution, it doesn't exist. > > > We could bring the PHP ADODB, or many of the other numerous PHP APIs > > > for DB connectivity into the picture, but which of these are the > > > obvious choice, and officially endorsed? > > > > That's precisely the situation Python is in now! > > 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 ;-). From loic at fejoz.net Thu Mar 25 09:29:19 2004 From: loic at fejoz.net (Yermat) Date: Thu, 25 Mar 2004 15:29:19 +0100 Subject: Split a string by length In-Reply-To: References: <4062BF09.1070906@rebirthing.co.nz> Message-ID: Peter Otten a ?crit : > Yermat wrote: > > >>take care with that kind of comparisons... > > > I'll add a disclaimer next time :-) > > >>Especially look at the last two comparison ! the only difference is the >>construction of the list... >> >>so what ? "Beautiful is better than ugly" >>Make your choice ;-) > > > I should have made explicit my "result" that timing doesn't matter much (I > think) in this case. I think too. That should only be implementation detail... >>[..] >>timeit.py -s"from chunk import chunksiter" >>"list(chunksiter('aabbccddee', 2))" >>100000 loops, best of 3: 11.8 usec per loop >> >>timeit.py -s"from chunk import chunksiter" "[ x for x in >>chunksiter('aabbccddee', 2)]" >>100000 loops, best of 3: 15.2 usec per loop > > > These last two timings are useless. The following (and two nested loops > without continue in either loop or break in the inner loop) is the only > sane use case: > > >>>>[list(ch) for ch in chunks.chunksiter("aabbccdd", 2)] > > [['a', 'a'], ['b', 'b'], ['c', 'c'], ['d', 'd']] > > > Looks reasonable. Now let's separate the above in two steps: > > >>>>lst = [ch for ch in chunks.chunksiter("aabbccdd", 2)] >>>>map(list, lst) > > [['a'], ['a'], ['b'], ['b'], ['c'], ['c'], ['d'], ['d']] > > > Did you expect that? Errorprone indeed. Of course you could use tee() from > the itertools example page to make it more robust, but I would expect even > more overhead... Well done ! I missed that point ! Make it simple... Finally the chunklist or chunks are my favorite for general chunk function. For string I would have use the regexp anyway... Who want to make a web site with python challenge like that one ? ;-) yermat From mstenner at ece.arizona.edu Sat Mar 13 15:11:48 2004 From: mstenner at ece.arizona.edu (Michael Stenner) Date: Sat, 13 Mar 2004 13:11:48 -0700 Subject: pre-processing source from distutils Message-ID: Is it possible to pre-process source code from distutils? I don't want to do anything too fancy. I just want to put the VERSION from setup.py (and maybe a date) into the module at sdist or build time (I haven't decided which of those would be cleaner). Anybody know of a clean way to do this? I don't mind writing an arbitrarily complex function to edit files or whatever. The problem is getting it called at the right time and knowing what mode setup.py is being called in. Thanks, Michael From hjwidmaier at web.de Thu Mar 18 14:53:47 2004 From: hjwidmaier at web.de (Hans-Joachim Widmaier) Date: Thu, 18 Mar 2004 20:53:47 +0100 Subject: Perceived optparse shortcomings References: <6e990e29.0403162320.584328ea@posting.google.com> Message-ID: Am Wed, 17 Mar 2004 09:36:24 -0600 schrieb Skip Montanaro: > 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. After some small changes to optparse, it is. It's the route I went, and I'm satisfied with the result. Hans-J. From drconrad at metaplay.com.au Mon Mar 29 21:04:15 2004 From: drconrad at metaplay.com.au (Simon Wittber) Date: Tue, 30 Mar 2004 10:04:15 +0800 Subject: Orders of magnitude In-Reply-To: Message-ID: <000c01c415fb$4f6a5600$0000fea9@simonxp> >A list 10 million integers suck up ~160 megs of memory with Python. Sorting a list of 10000000 integers sounds like a job for Numeric. The below code does the job in 22 seconds. Numeric consumes ~40MB for the initial array, then grabs another ~40MB, once the sorting starts. Its about as lean as you can get it. -------cut-here-------------------------- import Numeric import RandomArray import time print "creating array...", r = RandomArray.binomial((4294967294/2), .5, 10000000) print "done." s = time.clock() print "sorting array...", Numeric.sort(r) print "done." print "finding duplicates..." ou = r[0] dc = 0 for u in r[1:]: if u == ou: dc += 1 else: ou = u print "done. (%d) duplicates." % dc print "completed in ", time.clock() - s, "seconds." -------cut-here-------------------------- Output: creating array... done. sorting array... done. finding duplicates... done. (278) duplicates. completed in 22.2402900369 seconds From kbass at midsouth.rr.com Sat Mar 13 20:56:30 2004 From: kbass at midsouth.rr.com (kbass) Date: Sat, 13 Mar 2004 19:56:30 -0600 Subject: Python & the job market References: <16467.45496.356599.481075@montanaro.dyndns.org> Message-ID: <01b001c40967$93707a00$97443d42@homebass1> ----- Original Message ----- From: "Skip Montanaro" Newsgroups: comp.lang.python To: "kbass" Cc: Sent: Saturday, March 13, 2004 7:13 PM Subject: Re: Python & the job market > > kbass> I am starting to learn Python but I want to know how the job > kbass> market looks for programming using Python. > > Better than a year ago. I don't know what it is in overall numbers, but > it definitely seems to be growing. > > kbass> I really don't see many jobs (probably one or two) that require > kbass> Python experience at all. > > Have you checked out > > http://www.python.org/Jobs.html > > and the job sites it refers to? > > kbass> Most DBA and SA positions that I have seen require Perl and most > kbass> development position require Java or C++ ... > > This is not surprising. These languages all have larger installed bases > than Python. > > kbass> ... so how can learning Python benefit my career if there are > kbass> little to no chance that an employer will require the use of > kbass> Python or consider using Python over other programming languages > kbass> such as Java? > > A fair number of us have figured out ways to do that. Here are some > suggestions: > > * Get a job which is nominally not a programming position (say, sys > admin). For the little bits and pieces you wind up writing to do your > job better use Python, then make them available to your fellow sys > admins. > > * Infiltrate a job for which another programming language is "required". > Then start looking here > > http://www.python.org/cgi-bin/moinmoin/PythonAdvocacy > > for ways to convince your colleagues that Python might be a better > choice for some things. > > * Hang out your shingle as an independent consultant. > > * Got some good ideas and some good skills? Check out Mark > Shuttleworth's bounties page: > > http://www.markshuttleworth.com/bounty.html > > You have to be a bit more patient and creative, but it's definitely > possible. > > Skip > I have experience about 4 years of Java experience (designed and developed numerous projects as a consultant in the past), 10+ years of Oracle experience, about 5 years of Perl experience so programming is not a problem . I guess my main point that I should have touch upon was learning Python and influencing management to go the Python route in a company where Java is the standard. The Python Advocacy site is a good starting point to achieve the goal of influencing direct management but influencing other programmers could be an endeavor within itself too. One to five programmers developing in Python would be considered 'rouge programmers' at my company so convincing Java and VB programs to use Python will be a definite challenge. It took me about 2 to 4 months to successfully influence management that Linux AS was a direction that our departmental server should be but influencing them about Python maybe an uphill battle due to other I.T. departments and non-I.T. departments using Java and VB. I am up for the challenge. I reviewed the projects on Mark Shuttleworth's bounties page and I think that I will attempt to do some research and try one soon. kbass From ykingma at accessforall.nl Sat Mar 27 05:07:34 2004 From: ykingma at accessforall.nl (Ype Kingma) Date: Sat, 27 Mar 2004 11:07:34 +0100 Subject: A 'Python like' language References: <40645d8f$0$10775$afc38c87@news.easynet.co.uk> <95aa1afa.0403262049.4b2a6f78@posting.google.com> Message-ID: <40655266$0$557$e4fe514c@news.xs4all.nl> Michele Simionato wrote: > 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 ;-) The implementation of indentation is a minor issue. Many editors have facilities to deal with them. The point is that Prothon uses indentation. I hope this will help in making it at least as easy to read and maintain as Python. Who knows, at some point Prothon might 'fall back' to spaces... I like the prototypes _very_ much. They leave out many of the implicit mechanisms in classes and they are relatively easy to explain. My first impression is that one can use prototypes like classes, but they allow more flexibility. I wonder what influence they will have on the classic class/object dichotomy in OO land. As for the 'with' statement: I remember getting introduced to it in Pascal, where it led to confusion an did not contribute to code readability because of that. Pascal allowed more than one variable to be used in the 'with' statement iirc. On the contrary, the examples in Prothon are quite readable: no confusion because there is only one implied variable, and there is syntax (the leading dot) to show where it is used. I do not yet know in detail how Prothon deals with module namespaces. These are important for larger scale programs, so I hope they got that right. One thing I'm missing on the website is support for basic structured datatypes like the list and the dictionary in Python. The syntax support that Python has for these greatly contributes to useability. Regards, Ype From trevp_spam at trevp.net Wed Mar 24 14:35:28 2004 From: trevp_spam at trevp.net (Trevor Perrin) Date: Wed, 24 Mar 2004 19:35:28 GMT Subject: SHA-based subclass for random module In-Reply-To: <5d83790c.0403240124.2a80e784@posting.google.com> 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> <5d83790c.0403240124.2a80e784@posting.google.com> Message-ID: <4ql8c.42261$ct5.13462@newssvr25.news.prodigy.com> Raymond Hettinger wrote: > [Trevor Perrin] > >>I'm proposing that getrandstring() (returning a string) is a better >>primitive than getrandbits() (returning a long). > [...] > > Sorry, I do not think that introducing a string method into an > otherwise numeric module would make it easier to use. Okay. > What might be nice is if longs had methods for converting to and from > bytestrings. I was thinking the same. How about something like: bigNumber = long(bigNumberString, 256) bigNumberString = bigNumber.tostring() The string->long conversion treats a big-endian byte string as "base 256", and converts it to a non-negative integer. The long->string conversion would only work on non-negative integers. It's 'inspired' by the array module's "tostring()" method, which returns a similarly low-level string. Big-endian seems the common way to do this, at least in cryptography, in the common ASN.1 encodings, and in the libraries I've seen. Trevor From max at alcyone.com Sat Mar 20 07:26:17 2004 From: max at alcyone.com (Erik Max Francis) Date: Sat, 20 Mar 2004 04:26:17 -0800 Subject: \r\n problem in cgi module? References: Message-ID: <405C3869.84308C6A@alcyone.com> Jane Austine wrote: > The HTML page includes: > > > > Then I extract the "text" as such: > > f=cgi.FieldStorage() > text=f['text'].value > > The surprise is "text" contains "\r\n" instead of "\n", when running > on windows. > > Why does this happen, and what am I supposed to do? Isn't cgi module > supposed to provide "universal_new_line"? CGI has a weird specification where textareas are supposed to be delimited with CR LF, regardless of the platform. Weird, I know, but the CGI module isn't wrong here. -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE \__/ Nobody can reach me, nobody can touch me; it's a wonderful feeling. -- Aaliyah From shane at zope.com Fri Mar 26 09:54:33 2004 From: shane at zope.com (Shane Hathaway) Date: Fri, 26 Mar 2004 09:54:33 -0500 Subject: Make 'def' and 'class' usable within expressions In-Reply-To: References: <6E57243C-7EF3-11D8-8D1D-0003931CFE24@cistron.nl> Message-ID: <40644429.3060201@zope.com> Shane Hathaway wrote: > On Fri, 26 Mar 2004, Ronald Oussoren wrote: > > >>On 25-mrt-04, at 22:11, Shane Hathaway wrote: >> >>>I just thought of a better way to write this. >>> >>> myHandlers = {} >>> myHandlers["click"] = def(x,y): >>> print "click at x,y" >>> myHandlers["enter"] = def(): >>> print "mouse entered" >>> myHandlers["exit"] = def(): >>> print "mouse exited" >>> >>>I think that's pretty nice. >> >>And how would you write in-line callbacks for functions that take >>multiple callbacks (such as an on-success and on-error handler)? > > > I would write a class. > > obj.add_listener(class): > def on_success(self): > print 'yay!' > def on_error(self): > print 'ohh.' Oops, that's not quite correct. It should pass an instance rather than a class. obj.add_listener((class)()): def on_success(self): print 'yay!' def on_error(self): print 'ohh.' That's not pretty. :-( Shane From sean at sands.beach.net Thu Mar 25 17:28:28 2004 From: sean at sands.beach.net (Sean Berry) Date: Thu, 25 Mar 2004 22:28:28 GMT Subject: How to import a module based on an argument References: Message-ID: In article , sean at sands.beach.net (Sean Berry) writes: > I don't know that this partilarily bad programming, > but I was interested in doing the following. > > def functionname( module, var1, var2 ): > import module > > I would like to be able to pass the module name > as an argument and have the module imported as a result. > > For instance... functionname( os, "1", 234) > > Thanks for any help. Thanks for the help, and exec("import "+modname) does indeed import the module. But, what if I want to call a function from within this module that takes as an argument the name of a module. For example if I was making a module like the following import inspect def functionname( modname ): exec("import "+modname) s = inspect.getsource( modname ) return s How do I cast modname as a module name and not as a string? Thanks. -- From rogerb at rogerbinns.com Mon Mar 22 02:25:12 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Sun, 21 Mar 2004 23:25:12 -0800 Subject: Python bytecode compatibility between interpreter versions References: Message-ID: > So we can't even count on the fact that Python 2.2 running under Windows > on an Athlon will generate a .pyc file that's identical with that > generated by the exact same version (2.2) of the interpreter running > under Linux on, say, a Pentium III, and further, is not even *guaranteed* > to run on it?!? There are no guarantees that the same .pyc files will work the next day with the same interpretter. The interpretter could change the format every single day if the implementor so wanted. > This does not seem to fit in with what I've been reading... it would > be a lot more logical (and convenient) if we can count on .pyc portability > across different _patch versions_ (.x.y) of the same minor version (.x) > of CPython on whatever platform it is running on, Now in practise the .pyc files are not changed every day because there is no need, but an implementation is free to do so. In many cases they are the same between platforms and minor versions, but that is not a specification or a requirement. > and I believe that > Python's contributors would make an effort to ensure that this is the case. Why? To distribute executable Python code, you distribute the .py files. To distribute executable Java code, you distribute .class files. They can be wrapped up in .zip and .jar archives respectively. Java is defined as a compiled language. Python is not a compiled language, although an implementation is free to do so. If you really really want a compiled form of Python, try Jython which compiles to Java .class files. Roger From jacob at cd.chalmers.se Fri Mar 19 18:59:38 2004 From: jacob at cd.chalmers.se (Jacob Hallen) Date: 19 Mar 2004 23:59:38 GMT Subject: Europython Call for Participation Message-ID: EuroPython 2004 to be held 7-9 June in G?teborg, Sweden. The EuroPython conference will have tracks for Science, Business, Education, Applications, Frameworks, Zope and the Python language itself. Lightning talks, Open Space and BOF sessions are also planned. There will be tutorials as well, both for newcomers to Python and Python users interested in special subjects. In the days before and after the conference, programming sprints will be arranged. In the call for participation prospective speakers are welcomed to give either a formal, refereed paper or a less formal regular presentation. "We see a lot of interest in this years conference even before officially announcing it, with people asking for accomodation information, wanting to give talks and volunteering for other tasks", says Jacob Hall?n, head organiser. "We hope that people will stay for a few days after the conference to join spontaneously organised programming sprints", says Laura Creighton, sprint coordinator. "Sprints are fun, and we will have good facilities for them." Important dates * Refereed paper proposals: 19 March - 31 March * Submission of talks: 19 March - 15 April. * Early Bird registration: 31 March - 1 May. For more information and submission forms, please visit http://www.europython.org -- From ray_molachaNOSPAM at gmx.co.uk Tue Mar 23 04:37:56 2004 From: ray_molachaNOSPAM at gmx.co.uk (Ray Molacha) Date: Tue, 23 Mar 2004 09:37:56 GMT Subject: Newbie Formatting Question References: Message-ID: Hi Heather. Thanks for that very clear explanation -- and thanks for the nice example of a dynamically generated format specification. (BTW, I'm the original poster, I was just posting from the wrong identity.) Ray From mcfletch at rogers.com Mon Mar 22 19:34:08 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Mon, 22 Mar 2004 19:34:08 -0500 Subject: 3D apps in Python? In-Reply-To: References: Message-ID: <405F8600.3020703@rogers.com> To the best of my knowledge, there's only a few where the engine itself is written in Python: * Alice -- I believe early versions used to be written in Python to a Direct3D API, think they've been moving away from that in later versions, possibly toward a Java implementation? * OpenGLContext -- my testing/demo environment for PyOpenGL, which is based loosely on a VRML97 scenegraph model (and includes simple VRML97 loaders and the like). o Provides Transform,Group,Switch, PointLight,SpotLight,DirectionalLight, Background, Shape, Appearance, Material, ImageTexture, TextureTransform, IndexedFaceSet, IndexedLineSet, PointSet, Box, Sphere, Text, FontStyle, Polyline2D, NurbsCurve2D, Contour2D, NurbsSurface,TrimmedSurface, and NurbsCurve nodes (some with only partial support, it should be noted) o Has basic navigation, polygon tessellation, transparency and selection passes * ZOE is apparently written in Python, never played with it. Claims to focus on wireframes and particle systems. * VisualPython (VPython) may have some significant portion of the code in Python, but I can't say how much (or indeed whether there is any). However, these engines (save maybe ZOE, about which I know next to nothing) are focused primarily on teaching, rather than game or application development. Particularly given your legendarily high standards, I think you'll find that none are sufficient for your needs wrt building practical 3D apps in Python. The collective wisdom on that would seem to be "wrap a C/C++ engine if you need any sort of interactive speed on a non-trivial application". If you do find any other engines, consider adding them to the list here: http://www.py3d.org/py3d_zwiki/Python3dLinks (the formatting is messed up, but the information is often useful). Take care, Mike Brandon J. Van Every wrote: >I am looking for open source 3D applications written primarily in Python. >Not Python scripted, but rather, Python as the primary means of development, >dropping to C++ or C only when necessary for efficiency. Any pointers >appreciated. Surveys of leading open source 3D engines, such as Nebula and >Crystal Space, haven't yielded anything. I'm now starting to look at >non-game applications. > > _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From jcarlson at nospam.uci.edu Wed Mar 24 02:45:31 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Tue, 23 Mar 2004 23:45:31 -0800 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: > 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). Do like a standard file read does, buffer some extra bytes for the future, 4k should be sufficient for most needs. > But you don't need getrandbits(). [snip] > 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. As provided, using bits or bytes, it is easy to convert either way. While there are sources that are better suited for generating bytes (which you provide), there are entropy producers that give bits at a time. If I remember correctly, there is a serial port, USB, processor and even chipset entropy generators that all produce bits (some faster than others). Personally, I find bits far more useful, because while I can do binary operations on long integers, strings don't have |,^,&. >> 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. I could have sworn the other was that MT had cycle that seemed to be provably longer than any pure SHA based generator. I will also point out that Raymond had offered a generator using MD5 (which Paul gave us a link to showing that it was all but broken) that really just used MD5 as a bit twiddler to take 128 bits of MT to get 53 bits of output. The bit of code I offered merely goes a step further and uses SHA as a bit twiddler to take 160 bits of MT and 104 bits of previous state to get 53 bits of output. Taking 160 bits of MT reduces the cycle to 1/5 of its original period, but I would expect that the output of the SHA digest to not cycle for some nontrivial number of MT cycles, unless SHA and MT are internally doing something quite similar (I don't believe this is the case). - Josiah From jcarlson at nospam.uci.edu Mon Mar 15 16:04:44 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Mon, 15 Mar 2004 13:04:44 -0800 Subject: Static Typing in Python In-Reply-To: References: Message-ID: > 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. - Josiah From dale at riverhall.NOSPAM.co.uk Wed Mar 10 19:01:47 2004 From: dale at riverhall.NOSPAM.co.uk (Dale Strickland-Clak) Date: 11 Mar 2004 00:01:47 GMT Subject: Cgi: Print Text files with wordwrap! References: Message-ID: Walter Huf pushed the bounds of literature with: > Okay, I'm writing a cgi program, and I can send files and stuff, but > how do I send text files with word wrap enabled? If a line of text is > wider than the browser, and unsightly scrollbar appears on the bottom. > How would I make it so that the text automatically wraps in the > browser without putting a whole bunch of linebreaks in the text file? > > --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! =----- > If you send plain text, it will be presented exactly how you send it, line breaks and all. If you want it to wrap to the browser window, you have to make it look like HTML. The bare minimum you can get away with is

tags where you want new paragraphs - plus a head and a tail. -- Dale Strickland-Clark Riverhall Systems Ltd, www.riverhall.co.uk From halloleo at noospaam.myrealbox.com Wed Mar 10 01:48:26 2004 From: halloleo at noospaam.myrealbox.com (leo) Date: Wed, 10 Mar 2004 17:48:26 +1100 Subject: cmdline args to a piped python prog Message-ID: hi there a python file can evaluate cmdline arguments like python myprog.py arg1 arg2 arg3... when i feed python with my program via terminal input like cat myprog.py | python how can i then specifiy the cmdline arguments arg1 arg2 arg3...? thanks a lot, leo ps: wondering why i ask? -- emacs calls python code from abuffer always in the latter way. From jdtiede at sstar.com Wed Mar 10 23:19:41 2004 From: jdtiede at sstar.com (John D. Tiedeman) Date: Wed, 10 Mar 2004 22:19:41 -0600 Subject: Can't connect Postgres to Python Message-ID: <404FE8DD.5090202@sstar.com> John wrote: >> I have tried PostGreSQL, PyGreSQL, pypgsql, psycopg, and PDO and have >> yet to connect to PostgreSQL 7.4 (.1 in one box, .2 in the other). >> >> With PostGreSQL-3.4 and pypgsql-2.4, using setup.py build results in >> "error: command 'gcc' failed with exit status 1." >> >> I couldn't install psycopg-1.1.11 because it asks for PgSql header >> files; the only one I can identify is postgres.h. > > Dave Brueck wrote: I've been using pyscopg-1.1.11 with PostgreSQL 7.4 and Python 2.3 on Mandrake 9.2 and have found it to work really well for my needs. To get it to build I had to do cp -r postgres-7.4/src/include/catalog /usr/local/pgsql/include/ to get the headers in the right place. Also had to install mxDateTime first. HTH, -Dave ************************************************************************************ This looked like exactly what I need. But after I copied the header files as you instructed, I still got "configure: error: missing PostgreSQL headers." I tried with and without the trailing /, with and without /catalog, all to no avail. From jjl at colt-telecom.nl Mon Mar 29 12:07:30 2004 From: jjl at colt-telecom.nl (John J. Lee) Date: 29 Mar 2004 18:07:30 +0100 Subject: ANN: Python UK Conference, 16th - 17th April 2004 Message-ID: The Python UK conference is taking place on Friday and Saturday 16th and 17th of April, as part of the ACCU Spring Conference at the Randolph Hotel in the centre of Oxford. The impressive list of speakers includes David Ascher, Alex Martelli, Armin Rigo of Psyco and PyPy fame, Duncan Booth, Chris Withers, and core CPython and Jython developers Michael Hudson and Samuele Pedroni. The Python conference follows a 2-day Open Source event with well-known open-source leader and Pythonista Eric Raymond, co-founder of Zope corp Paul Everitt, and a host of other interesting speakers. http://www.accu.org/conference/ http://www.accu.org/conference/python.html http://www.accu.org/conference/opensource.html Though all the official speakers are invited, there will be considerable space during breaks and after hours for Python mini-talks, Birds of a Feather meetings and sprints (possibly including a PyPy sprint). There are also very reasonable sponsorship options (starting from ?200 for a lunchtime stand and talk) for Python companies wishing to promote themselves; see the 'sponsorship' page of the site for details. John From sangwan at kisti.re.kr Wed Mar 31 03:30:17 2004 From: sangwan at kisti.re.kr (±è»ó¿Ï) Date: Wed, 31 Mar 2004 17:30:17 +0900 Subject: [Python/C] Help me.. How to passa dictionary to C function? Message-ID: I'm a newbie in Python and Python/C API.. I have a simple question. I want to access python dictionary data type from C extension module. ---- spam.c ---- #include PyObject *wrap_clear(PyObject *self, PyObject *args) { int count; PyObject *dict; PyObject *newdict; newdict = PyDict_New(); // newdict is created in C module if (!PyArg_Parse(args, "O", &PyDict_Type, &dict)) { return NULL; } if (PyDict_Check(newdict)) { // newdict is a dictionary printf("newdict is ok\n"); } else { printf("newdict is not ok\n"); } if (PyDict_Check(dict)) { // dict is from python printf("dict is ok\n"); } else { printf("dict is not ok\n"); } return Py_BuildValue("i", 0); } static PyMethodDef spamMethods[] = { {"clear", wrap_clear, 1 }, { NULL, NULL } }; void initspam() { PyObject *m; m = Py_InitModule("spam", spamMethods); } ------------ $ gcc -fpic -c -I/usr/local/python/include/python2.3 -I/usr/local/python/lib/p ython2.3/config spam.c $ gcc -shared spam.o -o spam.so $ python Python 2.3.3 (#1, Mar 29 2004, 18:57:19) [GCC 2.96 20000731 (Red Hat Linux 7.3 2.96-113)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import spam >>> d = {"count":1} >>> d {'count': 1} >>> spam.clear(d) newdict is ok -------> newdict is a dictionary dict is not ok --------> but dict is not a dictionary 0 >>> How can i access to the dictionary from C module?? Thanks in advance.. From david at rebirthing.co.nz Thu Mar 4 00:19:07 2004 From: david at rebirthing.co.nz (David McNab) Date: Thu, 04 Mar 2004 18:19:07 +1300 Subject: Fresh Python for Rotting Web Hosts Message-ID: <4046BC4B.5080504@rebirthing.co.nz> Hi, As a drastic solution to the endemic problem of poor python support amongst budget (< $10 USD /month) web hosts, I've created a HOWTO document called 'Fresh Python For Rotting Web Hosts', which is available at: http://www.freenet.org.nz/python/fresh-python-for-rotting-web-hosts.html It walks beginning-intermediate Python web app developers through the steps of custom-building a self-contained small-footprint yet full-featured latest-version Python environment (around 9-14MB), installing this in one's home directory on budget web hosts, and using it to drive a website written as python CGI files. Intended audience is people who can't justify the $25/month+ which it often costs to host a site on more python-friendly hosts. This approach can serve as a stepping stone for sites starting small, looking later to migrate to more decent hosts. Please feel welcome to peer-review the document, and let me know of any inaccuracies, omissions or unclear sections. -- Kind regards David -- leave this line intact so your email gets through my junk mail filter From info at ing-monteleone.com Mon Mar 8 16:21:17 2004 From: info at ing-monteleone.com (Ing Giuseppe Monteleone) Date: Mon, 08 Mar 2004 21:21:17 GMT Subject: class problem with Embedded Python Message-ID: I Have a problem with embedded python: the interpeter work and i can call my object. In other word the code import geppo geppo.boxwrite("test") where geppo is my own module, work well, but when i try to define a class like this import geppo class pippo: pass geppo.boxwrite("test") the C function PyRun_SimpleString give me a ret value < 0, an error. Moreover when I ty to use an arimethic function I get a memory fault import geppo v = 3+3 geppo.boxwrite(v) that code generate a memory fault. Some one can help me ? Thanks In Giuseppe Monteleone From aahz at pythoncraft.com Mon Mar 8 15:24:56 2004 From: aahz at pythoncraft.com (Aahz) Date: 8 Mar 2004 15:24:56 -0500 Subject: PEP 328: Imports: Multi-Line and Absolute/Relative Message-ID: I'm a bit late with this, but better late than never... PEP: 328 Title: Imports: Multi-Line and Absolute/Relative Version: $Revision: 1.2 $ Last-Modified: $Date: 2004/01/31 05:19:25 $ Author: Aahz Status: Draft Type: Standards Track Python-Version: 2.4 Content-Type: text/x-rst Created: 21-Dec-2003 Post-History: 8-Mar-2004 Abstract ======== The ``import`` statement has two problems: * Long ``import`` statements can be difficult to write, requiring various contortions to fit Pythonic style guidelines. * Imports can be ambiguous in the face of packages; within a package, it's not clear whether ``import foo`` refers to a module within the package or some module outside the package. For the first problem, it is proposed that parentheses be permitted to enclose multiple names, thus allowing Python's standard mechanisms for multi-line values to apply. For the second problem, it is proposed that all ``import`` statements be absolute by default (more precisely, relative to ``sys.path``) with special syntax for accessing package-relative imports. Rationale for Parentheses ========================= Currently, if you want to import a lot of names from a module or package, you have to choose one of several unpalatable options: * Write a long line with backslash continuations:: from Tkinter import Tk, Frame, Button, Entry, Canvas, Text \ LEFT, DISABLED, NORMAL, RIDGE, END * Write multiple ``import`` statements:: from Tkinter import Tk, Frame, Button, Entry, Canvas, Text from Tkinter import LEFT, DISABLED, NORMAL, RIDGE, END (``import *`` is *not* an option ;-) Instead, it should be possible to use Python's standard grouping mechanism (parentheses) to write the ``import`` statement:: from Tkinter import (Tk, Frame, Button, Entry, Canvas, Text LEFT, DISABLED, NORMAL, RIDGE, END) This part of the proposal already has BDFL approval. Rationale for Absolute Imports ============================== In current Python, if you're reading a module located inside a package, it is not clear whether :: import foo refers to a top-level module or to another module inside the package. To resolve the ambiguity, it is proposed that ``foo`` will always be a module or package reachable from ``sys.path``. Because this represents a change in semantics, absolute imports will be optional in Python 2.4 through the use of :: from __future__ import absolute_import This PEP will be updated when it is decided to make absolute imports the default, probably Python 2.5 or 2.6. This part of the proposal already has BDFL approval. Rationale for Relative Imports ============================== With the shift to absolute imports, the question arose whether relative imports should be allowed at all. Several use cases were presented, the most important of which is being able to rearrange the structure of large packages without having to edit sub-packages. In addition, a module inside a package can't easily import itself without relative imports. Guido approved of the idea of relative imports, but there has been a lot of disagreement on the spelling (syntax). 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). Here are the contenders: * One from Guido:: from .foo import and :: from ...foo import These two forms have a couple of different suggested semantics. One semantic is to make each dot represent one level. There have been many complaints about the difficulty of counting dots. Another option is to only allow one level of relative import. That misses a lot of functionality, and people still complained about missing the dot in the one-dot form. The final option is to define an algorithm for finding relative modules and packages; the objection here is "Explicit is better than implicit". (The algorithm proposed is "search up from current package directory until the ultimate package parent gets hit".) * The next set of options is conflated from several posters:: from __pkg__.__pkg__ import and :: from .__parent__.__parent__ import Many people (Guido included) think these look ugly, but they *are* clear and explicit. Overall, more people prefer ``__pkg__`` as the shorter option. * Finally, some people dislike the way you have to change ``import`` to ``from ... import`` when you want to dig inside a package. They suggest completely rewriting the ``import`` syntax:: from MODULE import NAMES as RENAME searching HOW or :: import NAMES as RENAME from MODULE searching HOW [from NAMES] [in WHERE] import ... However, this most likely could not be implemented for Python 2.4 (too big a change), and allowing relative imports is sufficiently critical that we need something now (given that the standard ``import`` will change to absolute import). More than that, this proposed syntax has several open questions: - What is the precise proposed syntax? (Which clauses are optional under which circumstances?) - How strongly does the ``searching`` clause bind? In other words, do you write:: import foo as bar searching XXX, spam as ham searching XXX or:: import foo as bar, spam as ham searching XXX Open Issues =========== The BDFL needs to decide which of the various options for relative imports works best. Additional proposals are still welcome. As usual, Guido prefers reasons to histrionics. References ========== For more background, see the following python-dev threads: - `Re: Christmas Wishlist `__ - `Re: Python-Dev Digest, Vol 5, Issue 57 `__ - `Relative import `__ - `Another Strategy for Relative Import `__ Copyright ========= This document has been placed in the public domain. .. Local Variables: mode: indented-text indent-tabs-mode: nil sentence-end-double-space: t fill-column: 70 End: From cookedm+news at physics.mcmaster.ca Tue Mar 9 17:22:08 2004 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Tue, 09 Mar 2004 17:22:08 -0500 Subject: curses bkgd problem References: <404C9A46.4070206@geochemsource.com> Message-ID: At some point, Gandalf wrote: > Gandalf wrote: > >> stdscr = curses.initscr() # Get standard screen >> curses.start_color() # Uses colors >> stdscr.bkgd(' ',curses.COLOR_BLUE ) # Set background of the main window >> curses.noecho() # Do not echo input >> curses.cbreak() # CBreak mode: process keys immediately >> (no ENTER) >> stdscr.keypad(1) # keypad mode: parse control sequences >> stdscr.redrawwin() >> stdscr.refresh() >> >> However, it is displaying $ characters in black instead of >> displaying a blue background full of spaces. >> This must be a problem with my bkgd call since this works fine: >> >> curses.init_pair(1, curses.COLOR_RED, curses.COLOR_WHITE) >> stdscr.addstr(0, 0, curses.longname(), curses.color_pair(1) ) >> stdscr.refresh() >> > Now I'm doing this: > > def clrscr(): > global stdscr > (maxy,maxx) = stdscr.getmaxyx() > line = ' ' * (maxx-1) > for row in range(maxy): > stdscr.addstr(row, 0, line, curses.color_pair(1) ) > > which works fine except that the right side of the screen is still > black. Use a line of maxx blanks: line = ' ' * maxx > It is a very clumsy solution. Any ideas? Nope ... puzzled. Looks like colour in curses is harder than it looks :-) -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From droog at orange.gov Wed Mar 17 22:28:22 2004 From: droog at orange.gov (droog) Date: Thu, 18 Mar 2004 03:28:22 GMT Subject: New to Python. References: Message-ID: Thanks Roy! Could you please show me an alternative and better way of doing it? tia On Wed, 17 Mar 2004 22:22:41 -0500, Roy Smith wrote: >In article , > droog wrote: > >> 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) > >I cut-and-pasted the above onto my machine (just changed the pathname to >/usr/share/dict/words). It finds every line in the file! The problem >appears to be that the find() method returns -1 when there's no match, >which tests as True. Other than that, the code seems pretty reasonable. From peterstrempel at yahoo.com Thu Mar 11 13:56:16 2004 From: peterstrempel at yahoo.com (Peter Strempel) Date: 11 Mar 2004 18:56:16 GMT Subject: embed python References: Message-ID: In article , Marc Schellens wrote: > Can somebody tell me how to handle > this #include issue when embedding python? Usually "#include "Python.h" is the right way. Then tell your compiler to add "python2.3" to the include list. On gcc pass "-I/usr/include/python2.3" or similar to the compilation step. > Why NOT (according to the python doc) ude > #include > ? Well, you actually can do that, it will work just as above way. But when you upgrade your Python to 2.4, you need to change your sourcecode. Otherwise you only need to change your Makefile. Maybe there is another, more important reason. I don't know. :) > And which is the library to link if I want to > use pyhton from my application? -lpython2.3 (or -lpython23 on some systems) will find the right library, which is libpython2.3.so in most cases (or libpython23.so or python23.dll if you are on Win32). Peter From jacek.generowicz at cern.ch Mon Mar 1 04:07:53 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 01 Mar 2004 10:07:53 +0100 Subject: Feature request: subclassing FunctionType [Was: Some language proposals] References: <95aa1afa.0402262158.5b33de79@posting.google.com> <95aa1afa.0402272327.29828430@posting.google.com> <95aa1afa.0402292302.1283af4c@posting.google.com> Message-ID: michele.simionato at poste.it (Michele Simionato) writes: > Jacek Generowicz wrote in message news:... > > I think that you are misleading yourself. You are comparing apples to > > quinces. > > I thank you for the long post and the time you spent in clarifying the > issue I had; however, you are speaking to a converted, since I already > came to the same conclusion on my own (see my reply to Bengt Richter). Ah, OK, sorry. Didn't see that one at the time I was writing. > Still, I maintain that the ability to subclass FunctionType would be nice ;) I agreed with you originally on that, and I still do :-) Just one thing bothers me about your conclusions in your reply to Bengt ... [As my discussion turned out longer than I originally intended, let me pull the summary up here to the top: In short, the reason Scheme hides the "feature" is that there is no iteration in Scheme, only recursion. ] michele.simionato at poste.it (Michele Simionato) writes: > But still it is easy to forget that the helper function is needed > and that using directly the lambda would not work. It is kind of > error prone. Don't think about helper functions, think about the scopes that are intoduced. It's not the function that matters, it's the scope (the inner binding), which in Python can only be introduced by nesting a function, while in Scheme and CL you can use let. > Scheme is less error prone since it uses local loop variables The behaviour has nothing to do with globality or locality of the variable which is used. It depends on whether the same binding is being updated, or whether a new binding is being created each time around the loop. > and automatically generates separate closures: Python also greates separate closures. Scheme (and Python when you instruct it to do so) creates separate bindings of the same name so that the binding found by the free variables in the closure is different for each closure. > (define list-of-adders '()) > > (let loop ((i 0)) > (set! list-of-adders (cons (lambda (x) (+ x i)) list-of-adders)) > (if (= i 1) 'exit (loop (add1 i)))) > > (define add1 (first list-of-adders)) > (define add0 (second list-of-adders)) [...] > You can get Python behavior if you explicitely use a global variable: > > (define list-of-adders '()) > (define i 0) > > (let loop () > (set! list-of-adders (cons (lambda (x) (+ x i)) list-of-adders)) > (if (= i 1) 'exit (begin (set! i (add1 i)) (loop)))) In the second case you are updating the _single_ (global as it happens) binding [(set! i (add1 i))]. In the first case you do (loop (add1 i)) which certainly looks like it's passing the new value to a function which will create a new binding (though I suspect that there's some macrology behind the scenes). If, in the first case, you were to introduce a local variable to the loop and use (set! i (add1 i)) to update it, just like you do to the global, you'd see the closures sharing the same value again. As I said before, iteration in Scheme is usually (always?) implemented via recursion, so it's difficult create a loop with a genuine looping variable. If you used recursion to implement iteration in Python, you'd get the same as in Scheme: def make_adders(i): if i < 0: return [] return make_adders(i-1)+[lambda x:x+i] add0, add1 = make_adders(1) print add0(0) # => 0 print add1(0) # => 1 In short, the reason Scheme hides the "feature" is that there is no iteration in Scheme, only recursion. Disclaimer: I am no Scheme expert. There may well be Schemes which support real iteration, but I believe that the usual and even encouraged means of iterating in Scheme is via recursion. (Note, this is _not_ the case in Common Lisp.) Please correct me if you know this to be wrong. From cookedm+news at physics.mcmaster.ca Tue Mar 30 15:13:17 2004 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Tue, 30 Mar 2004 15:13:17 -0500 Subject: GUI Frameworks in Python? References: <8089854e.0403300518.3a180414@posting.google.com> <20040330143520.31dccb5e.HughMacdonald@brokenpipefilms.com> Message-ID: At some point, Gary Herron wrote: > On Tuesday 30 March 2004 05:35 am, Hugh Macdonald 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... > > No! GTK is most definitely cross platform. I use it on both Windows > and Linux with great success. And it's very consistent in the sense There's no (working) native port for Mac OS X [1], so I'd call it only mostly cross-platform. You could use the X version, and run an X server, but I could argue you could do the same under Windows... [1] there are some partly-complete ports of GTK 1.2, but nothing for GTK 2.x -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From User at Invalid.domain Wed Mar 17 08:30:02 2004 From: User at Invalid.domain (Debian User) Date: Wed, 17 Mar 2004 15:30:02 +0200 Subject: debian packages Message-ID: <405852DA.8030808@Invalid.domain> With redhat deciding go make some real money from the fruits of their labour, management decided to try out debian. This leads me to my possible future problem: is there a way to create debian (deb) packages using distutils (or any other python extensiom) for python scripts? I used to build RPMS using distutils and custom spec files. From m.bless at gmx.de Wed Mar 3 05:32:34 2004 From: m.bless at gmx.de (Martin Bless) Date: Wed, 03 Mar 2004 10:32:34 GMT 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> Message-ID: <4046aa14.9853593@news.t-online.de> ["Rainer Deyke" ] >but only because 'sys.stdout.write' is too long to type all >the time, and never with more than one argument. Yes, I feel it's a pity that the standard write method of file objects doesn't take multiple arguments. Would take some of the pressure. One thing I can do since Python-2.2 is to inherit from 'file' and add for example a 'writem' (write many, write multiple) method. This does work. Unfortunately it seems I can't add that 'writem' method to sys.stdout, as the following shows. Anybody any ideas? #!/usr/bin/env python # -*- coding: iso-8859-1 -*- """Test file object.""" __author__ = "Martin Bless, 2004-03-03" if 1 and "this does work": class MyFile(file): def writem(self,*args): "Method to write many arguments." for arg in args: self.write(str(arg)) f2name = 'xxxtempfile' f2 = MyFile(f2name,'w') f2.writem(1,2,3,4) f2.close() if 1 and "this does not work with sys.stdout": """ Attempt to add a method to a class at runtime. See Python Cookbook or ASPN, Object-Oriented Programming, Brett Cannon. """ import sys def writem(self,*args): "Function to be turned into a method.." for arg in args: self.write(str(arg)) # will not work setattr(sys.stdout.__class__,'writem',writem) """The above 'setattr' will give this error: Traceback (most recent call last): File "test_file_object.py", line 33, in ? setattr(sys.stdout.__class__,'writem',writem) TypeError: can't set attributes of built-in/extension type 'file' """ mb - Martin Bless From blairsp at dca.net Sat Mar 6 19:51:12 2004 From: blairsp at dca.net (SPD) Date: Sat, 06 Mar 2004 19:51:12 -0500 Subject: twisted.protocols.sip Message-ID: Hello: I'm new to Python and Twisted but not new to programming. I need to create a test tools to send and receive Session Initiation Protocol (SIP) messages. I understand twisted.protocols.sip offers this capability but I cannot get a demo program to work. Does anyone have a basic example program they can share? Thanks, Steve From nid_oizo at yahoo.com_remove_the_ Mon Mar 1 12:33:59 2004 From: nid_oizo at yahoo.com_remove_the_ (Nicolas Fleury) Date: Mon, 01 Mar 2004 12:33:59 -0500 Subject: Garbage collector and threads In-Reply-To: References: <1EJ0c.4334$mx4.105438@nnrp1.uunet.ca> Message-ID: <6uK0c.4347$mx4.106055@nnrp1.uunet.ca> Aahz wrote: > What's "RAII"? "Resource Acquisition Is Initialization" It's a term frequently used in C++ to describe the use of constructor and destructor for resource allocation/deallocation. >>to __del__, whatever it is ref-counting or something else. Wouldn't a >>class like CancellableThread, with a sub-class implemented cancel method >>called when the object is not referred in any other thread be useful? > > > Perhaps, but threading needs references to created threads in order to > implement its functionality. You might try building your own thread > constructs using ``thread`` directly. I still don't know how to implement it. I can do something very simple like: class Canceller: def __init__(self, thread): self.thread = thread def __del__(self): self.thread.cancel() self.thread.join() but I can't merge the concept with a Thread class, because the self passed to run would be a reference to the object... I don't know if a language extension would be worth the effort or if there's a cool solution I'm missing, but what is sure is that I write a lot of code to cancel threads in finalizers of parent objects. I don't want deamon threads so that everything is stopped cleanly, but at the same time it is error-prone in a GUI application, because I risk to have the process still running after a quit. I just want a way to garantee that all my threads are cancelled when the main thread is finished. Regards, Nicolas From bignose-hates-spam at and-benfinney-does-too.id.au Wed Mar 10 17:19:35 2004 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 11 Mar 2004 09:09:35 +1050 Subject: Extending Python Syntax with @ References: <104v3lrijtse657@news.supernews.com> Message-ID: On Wed, 10 Mar 2004 16:50:58 -0500, John Roth wrote: > Someday people will get over their attachment with being able to write > programs with any old text editor that happens to be lying around, and > being able to print their programs without needing a special > formatting program, but that day isn't today, and I doubt if it's > tomorrow. I doubt it's ever, because such a day would have to be preceded by the day when programs no longer need to be inspected, maintained or transferred between systems not specifically set up as developer workstations. -- \ "Those who can make you believe absurdities can make you commit | `\ atrocities." -- Voltaire | _o__) | Ben Finney From freyley at gmx.net Sat Mar 6 13:41:39 2004 From: freyley at gmx.net (Jeff Schwaber) Date: Sat, 06 Mar 2004 10:41:39 -0800 Subject: Working around a lack of 'goto' in python In-Reply-To: References: Message-ID: <1078598499.24853.6.camel@zadie> On Sat, 2004-03-06 at 10:18, Brett wrote: > Two areas where I've found 'goto' two be useful in other languages are in > (untested examples in C++) > > (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; > > END: /* continue */; try: for k in range(10): for j in range(10): for i in range(10): if "some test": raise Exception("test") except: pass > and (2) repeating a while or for loop from the beginning: > > BEGIN: > for (n=0; n < 20; ++n) > if (/* some test */) goto BEGIN; for n in range(20): if "some test": continue Jeff From riccardo_cut-me at cut.me.sideralis.net Sat Mar 20 13:35:15 2004 From: riccardo_cut-me at cut.me.sideralis.net (Riccardo Galli) Date: Sat, 20 Mar 2004 19:35:15 +0100 Subject: parsing emails References: <95aa1afa.0403200029.6859e390@posting.google.com> Message-ID: On Sat, 20 Mar 2004 00:29:40 -0800, Michele Simionato wrote: > I use Mozilla or Netscape, so my emails are stored in the nsmail > directory > or the Mozilla's equivalent. What's the simplest way to look at them > and > extract the mails with a given subject? In principle I could use a > regular expression, but I bet there are better solutions already > available. > Second question: are Mozilla and Netscape compatible, i.e. are the > emails stored with the same format and can I use the same extraction > method on both? > > TIA, > > > Michele Simionato Ciao Michele, maybe you could use something like that """code not tested""" import email import mailbox fp=file('fileName','r') mbox = mailbox.UnixMailbox(fp, email.message_from_file) msg_list=[] for msg in mbox.next(): if msg['Subject']=="the subject you're searching for": msg_list.append(msg) fp.close() for msg in msg_list: print msg Dunno about Mozilla/Netscape compatibility, but I think they'll use the same mail format. Ciao, Riccardo -- -=Riccardo Galli=- _,e. s~ `` ~@. ideralis Programs . ol `**~ http://www.sideralis.net From shane at zope.com Fri Mar 26 09:38:07 2004 From: shane at zope.com (Shane Hathaway) Date: Fri, 26 Mar 2004 09:38:07 -0500 (EST) Subject: Make 'def' and 'class' usable within expressions In-Reply-To: <6E57243C-7EF3-11D8-8D1D-0003931CFE24@cistron.nl> References: <1065uf99la6if29@news.supernews.com> <40634B15.1090006@zope.com> <6E57243C-7EF3-11D8-8D1D-0003931CFE24@cistron.nl> Message-ID: On Fri, 26 Mar 2004, Ronald Oussoren wrote: > > On 25-mrt-04, at 22:11, Shane Hathaway wrote: > > > > I just thought of a better way to write this. > > > > myHandlers = {} > > myHandlers["click"] = def(x,y): > > print "click at x,y" > > myHandlers["enter"] = def(): > > print "mouse entered" > > myHandlers["exit"] = def(): > > print "mouse exited" > > > > I think that's pretty nice. > > And how would you write in-line callbacks for functions that take > multiple callbacks (such as an on-success and on-error handler)? I would write a class. obj.add_listener(class): def on_success(self): print 'yay!' def on_error(self): print 'ohh.' Shane From tismer at stackless.com Mon Mar 29 12:45:46 2004 From: tismer at stackless.com (Christian Tismer) Date: Mon, 29 Mar 2004 19:45:46 +0200 Subject: How To capture an id into an array.. In-Reply-To: <494182a9.0403290932.5e09cfc6@posting.google.com> References: <494182a9.0403290932.5e09cfc6@posting.google.com> Message-ID: <406860CA.9040304@stackless.com> Balaji wrote: > Thanks for all the initial help.... > > Sorry for bugging you again... > > Here is a part of my code.. > > Suppose if some body wants to assign an e=E() to an expression class.. > > he may define then e=v+v1(where v and v1 both belong to a variable class) > > now again if we define say v2=V() and then try to multiply v2 with e then I want > to raise an error that it is a nonlinear term.. > > So what I though was if i keep track of all the instances id then I might raise > an exception... > > But the problem was i couldnt check the right side of an assigment... > > Can the right side of an assignment be checked... You can intercept the process of assignment. In older python, this was done overwriting __setattr__, but today it is much simpler and cleaner to user property objects. You can just define a setter that does certain checks. >>> print property.__doc__ property(fget=None, fset=None, fdel=None, doc=None) -> property attribute fget is a function to be used for getting an attribute value, and likewise fset is a function for setting, and fdel a function for del'ing, an attribute. Typical use is to define a managed attribute x: class C(object): def getx(self): return self.__x def setx(self, value): self.__x = value def delx(self): del self.__x x = property(getx, setx, delx, "I'm the 'x' property.") >>> 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 jbperez808 at yahoo.com Mon Mar 22 12:03:06 2004 From: jbperez808 at yahoo.com (Jon Perez) Date: Tue, 23 Mar 2004 01:03:06 +0800 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: Roger Binns wrote: > 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. Afaik, each app will start its own copy of a 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. Like I mentioned earlier, I am aware of 'freezing' but having to bundle an interpreter with every app is exactly what I would rather avoid... > 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. What would be great is to not have to choose between a Windows, Mac or Linux or XXX download (like in a proper Java app). > 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. But you're not saying that .pyc files contain profiling information, right? Because that is what it's sounding like... > 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. Yes, this is the main difference between Java and Python. Python prefers the source to be present, Java doesn't care. > With the addition of zip imports in Python 2.3, Correct me if I'm wrong, but I thought you just said earlier that zip imports predated Java by several years and now you're saying they've just been added to Python 2.3? From max at alcyone.com Tue Mar 16 19:44:50 2004 From: max at alcyone.com (Erik Max Francis) Date: Tue, 16 Mar 2004 16:44:50 -0800 Subject: Result of ``a is b'' References: <40200384.0403151632.35496ee6@posting.google.com> <40200384.0403161255.7fca7a8c@posting.google.com> Message-ID: <40579F82.6CA29952@alcyone.com> Skip Montanaro wrote: > Here is my "is" rule: > > Use "is" to compare two objects only if one is explicitly known to > be a > singleton defined by the language (None, Ellipsis, True, False). I'd add "or defined by the programmer within his code." Although admittedly I don't use it that way much. -- __ 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 moncho.leon at gmx.net Mon Mar 15 05:36:51 2004 From: moncho.leon at gmx.net (Ramon Leon Fournier) Date: Mon, 15 Mar 2004 11:36:51 +0100 Subject: Static Typing in Python References: Message-ID: Premshree Pillai wrote: > How do I force static typing in Python? If you want def foo(int bar): print bar then you probably want to give Pyrex a try. Theek hai. Ram?n From skip at pobox.com Sun Mar 7 09:29:21 2004 From: skip at pobox.com (Skip Montanaro) Date: Sun, 7 Mar 2004 08:29:21 -0600 Subject: Need better string methods In-Reply-To: <0d4k40987t6d70bahqil3geth640bufgoc@4ax.com> References: <0d4k40987t6d70bahqil3geth640bufgoc@4ax.com> Message-ID: <16459.12737.511890.925460@montanaro.dyndns.org> David> I am convinced that Python can do anything that can be done by David> these CPL's, but I know it will be an uphill battle getting David> design engineers to learn yet another scripting language.... David> The resistance will come from people who throw at us little bits David> and pieces of code that can be done more easily in their chosen David> CPL. Then throw little bits and pieces of code back at them that can be done more easily in Python. <0.5 wink> David> String processing, for example, is one area where we may face David> some difficulty. ... David> # Ruby: David> # clean = line.chomp.strip('.').squeeze.split(/\s*\|\s*/) David> This is pretty straight-forward once you know what each of the David> methods do. David> # Current best Python: David> clean = [' '.join(t.split()).strip('.') for t in line.split('|')] David> This is too much to expect of a non-programmer, even one who David> undestands the methods. ... My arguments from the "Zen of Python" would be: Beautiful is better than ugly. Simple is better than complex. Sparse is better than dense. Readability counts. These aphorisms are especially important for non-programmers. They simply aren't going to be able to remember what the above Ruby or Python code does in six months without at least a little bit of study, especially if it's buried in other similar code. That study will distract them, however momentarily, from the actual task at hand. That breaks their chain of concentration on the actual task at hand and lowers their productivity. To that end, my proposed solution for your string smashing problem would be something like: import csv for row in csv.reader(file("gradoo.csv"), delimiter='|'): print row # elide spaces row = [" ".join(s.split()) for s in row] print row # trim leading ... row = [s.lstrip(".") for s in row] print row given that gradoo.csv contains the line from your example. The advantages that I see are: * it's got some simple comments which identify the work being done * it's easier to add new operations if needed in the future * avoiding long chains of string methods makes the code easier to read Skip From skip at pobox.com Sun Mar 28 20:26:25 2004 From: skip at pobox.com (Skip Montanaro) Date: Sun, 28 Mar 2004 19:26:25 -0600 Subject: xmlrpc, httplib and SSL In-Reply-To: <16487.23850.656173.195877@montanaro.dyndns.org> References: <114d01c41448$4433c1e0$0000fea9@dell8200> <000d01c4144b$67dbd760$3501a8c0@rogersqyvr14d3> <16487.23850.656173.195877@montanaro.dyndns.org> Message-ID: <16487.31553.364009.314912@montanaro.dyndns.org> >>>>> "Skip" == Skip Montanaro writes: Roger> I did, except the base implementation can't be called. It hs Roger> this line of code in it: Roger> self.connection.shutdown(1) Roger> ie it will close the connection after every response, no matter Roger> what. Skip> Can you submit a patch to SF which abstracts that into its own Skip> method ("end_request" or something similar?) which can be Skip> overridden. Does this (untested) change help? You should be able to override the finish() method in a subclass. Skip % cvs diff SimpleXMLRPCServer.py Index: SimpleXMLRPCServer.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/SimpleXMLRPCServer.py,v retrieving revision 1.8 diff -c -r1.8 SimpleXMLRPCServer.py *** SimpleXMLRPCServer.py 2 Nov 2003 09:47:05 -0000 1.8 --- SimpleXMLRPCServer.py 28 Mar 2004 23:56:38 -0000 *************** *** 422,428 **** # shut down the connection self.wfile.flush() ! self.connection.shutdown(1) def log_request(self, code='-', size='-'): """Selectively log an accepted request.""" --- 422,431 ---- # shut down the connection self.wfile.flush() ! self.finish() ! ! def finish(self): ! self.connection.shutdown(1) def log_request(self, code='-', size='-'): """Selectively log an accepted request.""" From bac at OCF.Berkeley.EDU Thu Mar 25 08:46:21 2004 From: bac at OCF.Berkeley.EDU (Brett C.) Date: Thu, 25 Mar 2004 08:46:21 -0500 Subject: python-dev Summary for 2004-03-01 through 2004-03-15 Message-ID: <4062E2AD.50200@ocf.berkeley.edu> python-dev Summary for 2004-03-01 through 2004-03-15 ++++++++++++++++++++++++++++++++++++++++++++++++++++ This is a summary of traffic on the `python-dev mailing list`_ from March 01, 2004 through March 15, 2004. It is intended to inform the wider Python community of on-going developments on the list. To comment on anything mentioned here, just post to `comp.lang.python`_ (or email python-list at python.org which is a gateway to the newsgroup) with a subject line mentioning what you are discussing. All python-dev members are interested in seeing ideas discussed by the community, so don't hesitate to take a stance on something. And if all of this really interests you then get involved and join `python-dev`_! This is the thirty-seventh summary written by Brett Cannon (waiting for PyCon to start). To contact me, please send email to brett at python.org ; I do not have the time to keep up on comp.lang.python and thus do not always catch follow-ups posted there. All summaries are archived at http://www.python.org/dev/summary/ . Please note that this summary is written using reStructuredText_ which can be found at http://docutils.sf.net/rst.html . Any unfamiliar punctuation is probably markup for reST_ (otherwise it is probably regular expression syntax or a typo =); you can safely ignore it, although I suggest learning reST; it's simple and is accepted for `PEP markup`_ and gives some perks for the HTML output. Also, because of the wonders of programs that like to reformat text, I cannot guarantee you will be able to run the text version of this summary through Docutils_ as-is unless it is from the `original text file`_. .. _PEP Markup: http://www.python.org/peps/pep-0012.html The in-development version of the documentation for Python can be found at http://www.python.org/dev/doc/devel/ and should be used when looking up any documentation on something mentioned here. PEPs (Python Enhancement Proposals) are located at http://www.python.org/peps/ . To view files in the Python CVS online, go to http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/python/ . Reported bugs and suggested patches can be found at the SourceForge_ project page. The `Python Software Foundation`_ is the non-profit organization that holds the intellectual property for Python. It also tries to forward the development and use of Python. But the PSF_ cannot do this without donations. You can make a donation at http://python.org/psf/donations.html . Every penny helps so even a small donation (you can donate through PayPal or by check) helps. .. _python-dev: http://www.python.org/dev/ .. _SourceForge: http://sourceforge.net/tracker/?group_id=5470 .. _python-dev mailing list: http://mail.python.org/mailman/listinfo/python-dev .. _comp.lang.python: http://groups.google.com/groups?q=comp.lang.python .. _Docutils: http://docutils.sf.net/ .. _reST: .. _reStructuredText: http://docutils.sf.net/rst.html .. _PSF: .. _Python Software Foundation: http://python.org/psf/ .. contents:: .. _last summary: http://www.python.org/dev/summary/2004-02-01_2004-02-29.html .. _original text file: http://www.python.org/dev/summary/2004-03-01_2004-03-15.ht ===================== Summary Announcements ===================== Still looking for a summer job or internship programming. If you know of one, please let me know. Ever since I first had to type Martin v. Loewis' name, I have had issues with Unicode in the summary. When I realized there was a problem I thought it was Vim changing my Unicode in some way since I would notice problems when I reopened the file in TextEdit, OS X's included text editor that I have always used for writing the summaries (and no, I am not about to use Vim to do this nor Emacs; spoiled by real-time spelling and it is just the way I do it). Well, I was wrong. Should have known Vim was not the issue. Turned out that TextEdit was opening the text files later assuming the wrong character encoding. When I forced it to open all files as UTF-8 I no longer had problems. This also explains the weird MIME-quoted issues I had earlier that Aahz pointed out to me since I was just copying from TextEdit into Thunderbird_, my email client, without realizing TextEdit was not reading the text properly. So I thought I finally solved my problem. Ha! Not quite. Turned out to be a slight issue on the generation of the email based on the tool chain for how we maintain the python.org web site. This is in no way the web team's fault since I have unique requirements for the Summaries. But without having to do some recoding of ht2html_ in order to specify the text encoding, I wasn't sure how I should handle this. I thought I had this solved under reST_, but my solution turned out not to work. So the battle continues. So, for the moment, Unicode is not working for the summaries. And here is a question of people who read the Summaries on a regular basis: would you get any benefit in having new summaries announced in the `python.org RSS feed`_? Since this entails one extra, small step in each summary I am asking people to email me to let me know if this would in any way make their lives easier. So please let me know if knowing when a new summary is out by way of the RSS feed would be beneficial to you or if just finding from `comp.lang.python`_ or `comp.lang.python.announce`_ is enough. I actually wrote this entire summary either in the airport or on the flight to DC for PyCon (thank goodness for emergency aisles; my 6'6" frame would be in much more pain than it is otherwise) and thus on Spring Break! I am hoping to use this as a turning point in doing the Summaries on a semi-monthly basis again. We will see if Spring quarter lets me stick to that (expecting a lighter load with less stress next quarter). .. _Thunderbird: http://www.mozilla.org/projects/thunderbird/ .. _ht2html: http://ht2html.sf.net/ .. _directive: http://docutils.sourceforge.net/spec/rst/directives.html .. _python.org RSS feed: http://www.python.org/channews.rdf .. _PyCon: http://www.pycon.org/ .. _comp.lang.python.announce: http://groups.google.com/groups?q=comp.lang.python.announce&ie=UTF-8&oe=UTF-8&hl=en&btnG=Google+Search ========= Summaries ========= -------- PEP news -------- PEP 309 ("Partial Function Application") has been rewritten. PEP 318 got a ton of discussion, to the point of warranting its own summary: `PEP 318 and the discussion that will never end`_. PE 327, which is the spec for the Decimal module in the CVS sandbox, got an update. Contributing threads: - `PEP 309 re-written `__ - `Changes to PEP 327: Decimal data type `__ ----------------------------------------------- Playing willy-nilly with stack frames for speed ----------------------------------------------- A patch to clean up the allocation and remove the freelist (stack frames not in use that could be used for something else) was proposed. Of course it would have been applied immediately if there wasn't a catch: recursive functions slowed down by around 20%. A way to get around this was proposed, but it would clutter up the code which was being simplified in the first place. Guido said he would rather have that than have recursive calls take a hit. Then a flurry of posts came about discussing other ways to try to speed up stack allocation. Contributing threads: - `scary frame speed hacks `__ - `reusing frames `__ ---------------------------------------------- PEP 318 and the discussion that will never end ---------------------------------------------- Just looking at the number of contributing threads to this summary should give you an indication of how talked about this PEP became. In case you don't remember the discussion `last time`_, this PEP covers function/method(/class?) decorators: having this:: def foo() [decorate, me]: pass be equivalent to:: def foo(): pass foo = me(decorate(foo)) What most of the discussion came down to was syntax and the order of application. As of this moment it has come down to either the syntax used above or putting the brackets between the function/method name and the parameters. Guido spoke up and said he liked the latter syntax (which is used by Quixote_). People, though, pointed out that while the syntax works for a single argument, adding a long list starts to separate the parameter tuple farther and farther from the function/method name. There was at least one other syntax proposal but it was shot down quickly. Order of application seems to have been settled. Some want the order to be like in the example. Others, though, want the reverse order: ``decorate(me(foo))``. In the end, though, the order in the example code is what people preferred. In the end it was agreed the PEP needed to be thoroughly rewritten which is currently happening. .. _last time: 2004-02-01_2004-02-29.html#function-decoration-and-all-that-jazz .. _Quixote: http://www.mems-exchange.org/software/quixote/ Contributing threads: - `Pep 318 - new syntax for wrappers `__ - `new syntax (esp for wrappers) `__ - `PEP 318 - function/method/class decoration `__ - `(Specific syntax of) PEP 318 - function/method/class `__ - `PEP 318 - generality of list; restrictions on elements `__ - `PEP 318 needs a rewrite `__ - `Python-Dev Digest, Vol 8, Issue 20 `__ - `PEP 318 trial balloon (wrappers) `__ - `funcdef grammar production `__ ---------------------------------------- Compiler optimization flags for the core ---------------------------------------- The topic of compiler flags that are optimal for Python came up when Raymond Hettinger announced his new LIST_APPEND opcode (discussed later in `Optimizing: Raymond Hettinger's personal crack`_). This stemmed from the fact that the bytecode has not been touched in a while. This generated a short discussion on the magic that is caches and how the eval loop always throws a fit when it gets played with. One suggestion was to rework some opcodes to use other opcodes instead in order to remove the original opcodes entirely from the eval loop. But it was pointed out it would be better to just factor out the C code to functions so that they are just brought into the cache less often instead of incurring the overhead of more loops through the eval loop. This then led to AM Kuchling to state that he was planning in giving a lightning talk at PyCon_ about various compiler optimization flags he tried out on Python. Looks like that compiling Python/ceval.c with -Os (optimizes for space) w/ everything else using -O3 gave the best results using gcc 3. This sparked the idea of more architecture-dependent compiler optimizations which would be set when 'configure' was run and detected the hardware of the system. In the end no code was changed in terms of the compiler optimizations. Contributing threads: - `New opcode to simplifiy/speedup list comprehensions `__ - `Who cares about the performance of these opcodes? `__ ------------------------------------------------------ Take using Python as a calculator to a whole new level ------------------------------------------------------ I remember once there was a thread on `comp.lang.python`_ about how to tell when you had an addiction to Python. One of the points was when you start to use Python as your calculator (something I admit to openly; using the 'sum' built-in is wonderful for quick addition when I would have used a Scheme interpreter). Well, Raymond Hettinger had the idea of adding a 'calculator' module that would provide a ""pretty good" implementations of things found on low to mid-range calculators like my personal favorite, the hp32sII student scientific calculator". He then listed a bunch of functionality the HP calculator has that he would like to see as a module. Beyond sparking some waxing about calculators, and the HP 32sII especially (I used a TI-82 back in high school and junior college so I won't even both summarizing the nostalgic daydreaming on HP calculators), the discussion focused mainly on what functionality to provide and the accuracy of the calculations. The former topic focused on what would be reasonable and relatively easy to implement without requiring a mathematician to write in order to be correct or fast. The topic of accuracy, though, was not as clear-cut. First the issue of whether to use the in-development Decimal module would be the smart thing to do. The consensus was to use Decimal since floating-point, even with IEEE 754 in place, is not accurate enough for something that wants to be as accurate as an actual calculator. Then discussions on the precision of accuracy came up. It seemed like it would be important to have a level of precision kept above the expected output precision to make sure any rounding errors and such would be kept to a minimum. Raymond is going to write a PEP outlining the module. Contributing threads: - `calculator module `__ ------------------------ dateutil module proposed ------------------------ Gustavo Niemeyer offered to integrate his dateutil_ module into the stdlib. Discussion of how it should tie into datetime and whether all of it or only some of its functionality should be brought in was transpired. As of right now the discussion is still going on. .. _dateutil: https://moin.conectiva.com.br/DateUtil Contributing threads: - `dateutil `__ ---------------------------------------------- Optimizing: Raymond Hettinger's personal crack ---------------------------------------------- Raymond Hettinger, the speed nut that he is, added a new opcode to Python to speed up list comprehensions by around 35%. But his addiction didn't stop there. Being the dealer of his own drug of choice, Raymond got his next fix by improving on iterations for dictionaries (this is, of course, after all of his work on the list internals). As always, thanks goes to Raymond for putting in the work to make sure the CPython interpreter beats the Parrot_ interpreter by that much more come `OSCON 2004`_ and the Pie-thon contest. And, at Hye-Shik Chang's request, Raymond listed off his list of things to do to feed his addiction so he doesn't go into withdrawls any time in the future. Most of them are nice and involved that would make great personal/research projects. .. _Parrot: http://www.parrotcode.org/ .. _OSCON 2004: http://conferences.oreillynet.com/os2004/ Contributing threads: - `New opcode to simplifiy/speedup list comprehensions `__ - `Joys of Optimization `__ From paschen at mavd.de Tue Mar 23 08:11:22 2004 From: paschen at mavd.de (Bjoern Paschen) Date: Tue, 23 Mar 2004 14:11:22 +0100 Subject: 3D apps in Python? In-Reply-To: References: <338366A6D2E2CA4C9DAEAE652E12A1DE014C718C@au3010avexu1.global.avaya.com> <405FAA1D.83576D05@alcyone.com> Message-ID: <1080047465.56698@mail.mavd.de> Brad wrote: > What a sick fuck. Now I know why they call people like him trolls. I am looking forward to it. Its pure entertainment :). From donn at u.washington.edu Tue Mar 30 15:00:52 2004 From: donn at u.washington.edu (Donn Cave) Date: Tue, 30 Mar 2004 12:00:52 -0800 Subject: Equality and identity References: <3cfvfkmi337.fsf@nelja.ifi.uio.no> Message-ID: In article <3cfvfkmi337.fsf at nelja.ifi.uio.no>, Marius Bernklev wrote: > 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 > > But that isn't true for tuples: > >>> (5,2) == (5,2) > True > >>> (5,2) is (5,2) > False > > Why not? Are tuples mutable in some way I've missed, or are there > other reasons for this behaviour? To me, it seems natural to concider > (5,2) and (5,2) the same object, just like "5,2" and "5,2". Note that the Python interpreter is a program, with finite limits on its implementation. It is not an algebraic system. If you find that (5,2) and (5,2) are not the same object, rather than trying to infer properties of types from this, first you might ask `what would it take, as implementor of Python, to always use the same object for these two quantities?' and, `how important is it to do so?' This may lead you to make a few more experiments with strings and find some holes in your identity proposition there, too. Don't make the mistake that people seem recently so prone to make, of an unhealthy preoccupation with "is" and identity. When you need to test for equality, always use "==". Donn Cave, donn at u.washington.edu From hufman at cobalty.com Wed Mar 10 16:58:11 2004 From: hufman at cobalty.com (Walter Huf) Date: 10 Mar 2004 15:58:11 -0600 Subject: Cgi: Print Text files with wordwrap! Message-ID: Okay, I'm writing a cgi program, and I can send files and stuff, but how do I send text files with word wrap enabled? If a line of text is wider than the browser, and unsightly scrollbar appears on the bottom. How would I make it so that the text automatically wraps in the browser without putting a whole bunch of linebreaks in the text file? --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 fumanchu at amor.org Wed Mar 3 14:14:59 2004 From: fumanchu at amor.org (Robert Brewer) Date: Wed, 3 Mar 2004 11:14:59 -0800 Subject: Efficiently test for positive re.match then use the result? Message-ID: elmlish wrote: > I'm currently befuddled as to how to efficiently test for a > positive re. > match then use the results of that match in a function. > > 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. > >>> alist = ['boo','hoo','choo'] > >>> [re.match('choo',line) for line in calist if > re.match('choo',line)] > [<_sre.SRE_Match object at 0x11e218>] What's wrong with: alist = ['boo','hoo','choo'] for line in alist: m = re.match('choo', line) if m: doSomethingWith(m.groups(0)) FuManChu From fumanchu at amor.org Tue Mar 16 21:52:41 2004 From: fumanchu at amor.org (Robert Brewer) Date: Tue, 16 Mar 2004 18:52:41 -0800 Subject: Result of ``a is b'' Message-ID: 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. ;) FuManChu From jdtiede at sstar.com Tue Mar 16 17:47:26 2004 From: jdtiede at sstar.com (John D. Tiedeman) Date: Tue, 16 Mar 2004 16:47:26 -0600 Subject: Can't connect Postgres to Python In-Reply-To: References: Message-ID: <405783FE.1050507@sstar.com> John wrote: >>At this point, using the command >> conn = psycopg.connect("dbname=personal", serialize=0) >>from psycogq documentation, I get >> NameError: name 'psycopg' is not defined >> >>What am I missing? >> >> > >Hi John. You need to import the module first: > >import psycopg > >You may have more errors to figure out, but this will at least get you to the >next step. > >-Dave > > This is the configuration I used: ./configure --with-postgres/libraries=/usr/local/pgsql/lib --with-postgres-includes=/usr/local/pgsql/include --with-zope=/usr/lib/Zope-2.6.2-src --with-mxdatetime-includes=/usr/lib/python2.2/site-packages/mx/DateTime/mxDateTime When I try to import psycopg, I get "no module named DateTime." I found that mxDateTime.so is in ...Python2.2/site-packages/mx/DateTime/mxDateTime. Could I have the wrong version, do I need to put it in the Python2.3 directory, or what? From mark at prothon.org Wed Mar 31 19:46:55 2004 From: mark at prothon.org (Mark Hahn) Date: Wed, 31 Mar 2004 16:46:55 -0800 Subject: Prothon, metaclasses, Zope [Was: A 'Python like' language] References: <95aa1afa.0403272243.78d60724@posting.google.com> <95aa1afa.0403280258.41dc5cd9@posting.google.com> <8y8ac.68250$cx5.51296@fed1read04> Message-ID: Greg: Just a quick note to let you know that I do intend to reply to this but haven't had the time. Greg Ewing (using news.cis.dfn.de) wrote: > Mark Hahn wrote: >>> But presumably he wants the check done only once, when a subclass is >>> defined, *not* every time said subclass is instantiated. >> >> You can have a different __init__ for an object and it's prototpe.So >> the Prothon equivalent of a subclass can easily have different >> __init__ behaviour than it's child (what you call instance). > > Can you post some code illustrating how you would do this > in Prothon? I still can't see how, at the point where you > do > > X = Base() > > anything can tell whether you're intending to use X as > an instance of Base or whether you're going to go on to > say > > with X: > def ... > > and use X as a prototype which inherits behaviour from > Base. In both cases, Base.__init__ is going to get invoked > before you have a chance to define any other __init__ that > might override it. From peter at engcorp.com Mon Mar 29 22:43:35 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 29 Mar 2004 22:43:35 -0500 Subject: Richards bench benchmark In-Reply-To: <6748553f.0403291446.27fb7b93@posting.google.com> References: <6748553f.0403291446.27fb7b93@posting.google.com> Message-ID: Duncan Lissett wrote: > Is there a Python implementation of Martin Richards benchmark Bench? > > Be interesting to add it to these > www.lissett.com/ben/exp/bench1.htm I doubt one exists yet. There doesn't even appear to be a specification. It even looks like different implementations of that benchmark were implemented by random people porting arbitrary other versions. For example, the Algol68 one comes from Pascal, and the Pascal one came from C (?). Worse than that, I can't find a specification for the benchmark anywhere. What's it supposed to do? Writing this in Python by reverse engineering a possibly buggy implementation from some other language would be a wonderful exercise in futility. There's a hint on http://www.cl.cam.ac.uk/users/mr/Bench.html (Martin's own page on the subject) which suggests ("designed for the comparison of System Implementation Languages") that this is not a suitable benchmark for Python anyway. Python doesn't normally get used in that domain, and it might be it can't even do what is required without resorting to C extensions... My guess is there are more modern benchmarks that are much more effective at comparing Python performance in areas where it's really used, but without even a paper describing this one, who could say? -Peter From simon_place at whsmithnet.co.uk Sat Mar 6 13:51:54 2004 From: simon_place at whsmithnet.co.uk (simon place) Date: Sat, 06 Mar 2004 18:51:54 +0000 Subject: machine control script ( parameterless method? ) In-Reply-To: <20040306123424.20326.00000892@mb-m04.aol.com> References: <340a6b1b6f65b385490e5d818b2b6c9e@news.scbiz.com> <20040306123424.20326.00000892@mb-m04.aol.com> Message-ID: <404a1dcd$1_1@mk-nntp-1.news.uk.worldonline.com> Bluexcell wrote: > Assuming your machine program is not hard wired..then the user is using some > form of GUI or other interface to alter the parameters for control, why not use > a Tkinter GUI to create the program I/O interface.. the checks and safeguards > for for incorrect entry are hidden and the user is more inclined to enter the > right data in the right place? i was thinking of using a text control for the user to edit an action script, ( thsts why im thinking of python.) v.v.little code, v.flexible ( i don't have to worry about malicious user) that's why the question is actually only about getting rid of the brackets. From koen_vossen at pandora.be Tue Mar 30 17:36:39 2004 From: koen_vossen at pandora.be (Koen Vossen) Date: Tue, 30 Mar 2004 22:36:39 GMT Subject: Bug in socket module? Message-ID: Hi, I came across some exceptional behaviour (pun intended) when I was programming a small chat server. I've simplified my original code to the following minimal version that still exhibits the same problem: #!/usr/bin/env python import socket s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.bind(('', 1234)) s.settimeout(10) try: print "The Meaning of Life." data, address = s.recvfrom(1024) except KeyboardInterrupt: pass When I start this little snippet, it just sits waiting for the socket to return some data, as expected. However, when I press CTRL-C before the timeout occurs it crashes on a KeyboardInterrupt exception, despite the fact that I have set up a handler to catch the latter. koen at s031845:~/workdir> ./weird.py The Meaning of Life. Traceback (most recent call last): File "./weird.py", line 11, in ? data, address = s.recvfrom(1024) KeyboardInterrupt When I omit the settimeout method call, or when I replace recvfrom by raw_input, the program behaves as expected. I'm using the following version of python: Python 2.3+ (#1, Jan 7 2004, 09:17:35) [GCC 3.3.1 (SuSE Linux)] on linux2 I've found that on Windows the same behaviour occurs. Am I onto something here? Koen Vossen -- Replace the underscore by a dot to obtain my email address. Public PGP key available @ pgp.mit.edu From bokr at oz.net Tue Mar 2 14:45:40 2004 From: bokr at oz.net (Bengt Richter) Date: 2 Mar 2004 19:45:40 GMT Subject: Group comment References: Message-ID: On Mon, 1 Mar 2004 08:57:56 -0600, Skip Montanaro wrote: > > 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 > """ Though there's always the corner case where there's already something triple-quoted in the segment you want to comment/quote out. If we had string-delimited quoting a la mime, we could solve that. E.g., q'arbitrary string''arbitrary string' or Q'arbitrary string' 'arbitrary string' Where the upper case Q signals the syntax that the line tail after the delimiter is ignored. (thus the second quote above also includes the \n at the end of the quoted < ...> line) thus Q'XXX' i=1 i+=1 print i print i+1 'XXX' and then no problem to do: Q'YYY' Q'XXX' i=1 i+=1 print i print i+1 'XXX' 'YYY' (The single quotes are for readability, not part of the actual quoting delimiters) You could deal with the final-escape char problem if you had a no-escapes raw string version of this. Maybe signal that with double quoted delimiter strings, e.g., q"+++"this ends in backslash\"+++" which would define the same string constant as 'this ends in backslash\\' > >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. The other side of the coin is that it's sometimes useful to write if True: # .. pasted code that has indentation "if True" is also handy to defer processing in interactive mode, e.g., >>> print 'hi' hi >>> print 'ho' ho >>> if True: ... print 'hi' ... print 'ho' ... hi ho That's my clpy quota for today ;-) Regards, Bengt Richter From dw-google.com at botanicus.net Sun Mar 28 21:16:30 2004 From: dw-google.com at botanicus.net (David M. Wilson) Date: 28 Mar 2004 18:16:30 -0800 Subject: asyncore deficiencies References: <99dce321.0403271928.69ef6eeb@posting.google.com> Message-ID: <99dce321.0403281816.4df96025@posting.google.com> Josiah Carlson wrote... > I agree that there should probably be some sort of asyncore2; I have a > handful of boilerplate servers and clients that I use as a base any time > I need something. Optimally, an asyncore2 library would have simple > clients and servers ready to be subclassed and customized as needed. I would expect such things to be provided by modules that are dependant on asyncore, eg. as asynchat is. It's beyond the scope of what asyncore tries to do. > I'm curious as to why you need to use a private map. Most uses of > private maps I've seen haven't added any sort of meaningful > functionality that couldn't have been handled by the default map. Yours > could be an exception, but I'm still curious. I don't need a private map, however given that the other option was a module variable, I naturally chose to provide my own to increase any required future flexibility. Indeed there is little, if anything to be gained from using your own map, but the option was there. > Again, you need to use asyncore.poll. The poll function is not documented in the manual, nor do any docstrings suggest it is a public interface. Internally asyncore chooses which of poll, poll2, or poll3 to use inside loop, so calling these directly also bypasses some of asyncore's OS-independance functionality. > I've never used asyncore with UDP sockets, but maybe using > "handle_connect = handle_read" in your subclass definition could be > sufficient. I see this as a workaround, and as such I think the point still stands. :) > That is exactly why polling is optional. Select is available on every > platform, but poll is faster on platforms that support it... That is not true at all. If you are feeling investigative, quite a complete starting point would be . There is lots of information there regarding various OS implementations async IO performance using poll, epoll, select, aio_*, etc. > The trick with doing this is that you end up interrupting other > potentially ready sockets with handling an exception. If you are > feeling fiesty, I believe you can use the following and get the error > propagated back up: > def handle_error(self): > raise That's a good point, but I don't have a problem restarting the poll after handling an exception, a) because it shouldn't happen very often, b) will probably mean shutting down the service rather than trying to continue, and c) exceptions are generally expensive special cases anyway. If an exception is propogating up from the dispatcher, that means the dispatcher's method did not handle the exception, which should mean it gets passed back up the stack as it does with all other code, eventually ending up with a traceback print if it wasn't handled. I dislike the handle_error method since it is essentially redundant in the face of Python's own exception handling mechanism. If a dispatcher wants it's own function to handle exceptions, it should wrap it's methods in a try block. I assume handle_error was provided to allow graceful teardown of a dispatcher that was erroneous, but it isn't granular enough to be useful for tearing down complicated objects, given an exception that could have been generated anywhere in a couple of screenfuls worth of code, and an object that could be in any state. > > - Decoupling from socket objects: removal of the __getitem__ magic > > which causes screenfuls of abuse for a simple typo at the wrong stage > > in execution. > > Infinite recursion in asyncore? Yikes, I've not hit that bug before. > Care to post some offending code? It was entirely my fault, but here is the example anyway. :) py> from asyncore import * py> class D(dispatcher): ... def __init__(self): ... self.foo ... dispatcher.__init__(self) ... py> D() Traceback (most recent call last): File "", line 1, in ? File "", line 3, in __init__ File "/usr/lib/python2.3/asyncore.py", line 365, in __getattr__ return getattr(self.socket, attr) File "/usr/lib/python2.3/asyncore.py", line 365, in __getattr__ return getattr(self.socket, attr) File "/usr/lib/python2.3/asyncore.py", line 365, in __getattr__ return getattr(self.socket, attr) > One could even have a framework for registering even handlers...yikes, > this is starting to sound like wxPython. I don't know if that is a good > idea or not. NAME asyncore Basic infrastructure for asynchronous socket service clients and servers. I think that answers the question. Is anyone else interested in this? I have already made small modifications to the asyncore module to fix a few things, but nothing mentioned here. I could put together a proposed asyncore2 module if there was interest. I may do it, out of need, anyway. :) David. From fumanchu at amor.org Mon Mar 8 12:48:03 2004 From: fumanchu at amor.org (Robert Brewer) Date: Mon, 8 Mar 2004 09:48:03 -0800 Subject: Initializing Member Variables Message-ID: Boy did I mess up. I wrote: > Your immediate issue is this: putting __dict = {} in the *class* > declaration does not make a separate attribute for each *instance*; it > merely makes a single attribute for the class. To create an attribute > for the class, you must write code which--surprise, surprise--adds > that attribute to the *instance*. ...when I should have written: Your immediate issue is this: putting __dict = {} in the *class* declaration does not make a separate attribute for each *instance*; it merely makes a single attribute for the class. To create an attribute for the INSTANCE, you must write code which--surprise, surprise--adds ^^^^^^^^ that attribute to the *instance*. FuManChu From Scott.Daniels at Acm.Org Wed Mar 10 13:11:25 2004 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 10 Mar 2004 10:11:25 -0800 Subject: name of this python program In-Reply-To: References: Message-ID: <404f628d$1@nntp0.pdx.net> leo wrote: > 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 Depending on your python version, you might try for __file__. -- -Scott David Daniels Scott.Daniels at Acm.Org From teiffel at attglobal.net Wed Mar 3 15:05:19 2004 From: teiffel at attglobal.net (Marcello Pietrobon) Date: Wed, 03 Mar 2004 15:05:19 -0500 Subject: function arguments passed by reference Message-ID: <40463A7F.5090609@attglobal.net> Hello, My background is C++ I would like to know for sure if it is possible to pass a value by reference to a function AND having it changed by the function itself def changeValue( text ): text = 'c' print text return >>> txt = 'a' >>>changeValue( txt ) 'c' >>>print txt 'a' Question 1) I guess that in Python ( differently than in C++) somehow txt is passed by reference even if its value is not changed. Is this true ? Question 2) How can I define a function that changes the value of txt ( without having to return the changed value ) ? Question 3) Is there some documentation talking extensively about this ? Thank you, Marcello From sdfATexpertuneDOTcom Thu Mar 18 11:20:53 2004 From: sdfATexpertuneDOTcom (Scott F) Date: Thu, 18 Mar 2004 16:20:53 -0000 Subject: New to Python. References: <40593E14.EAF16BD5@alcyone.com> Message-ID: "Terry Reedy" wrote in news:mailman.126.1079617542.742.python-list at python.org: >> You really want to use double backslashes (\\) here or use a raw >> string (r'...'). If not, this will eventually bite you. > > Or forward slashes (/), which avoids the whole problem. > for file() and similar, forward slashes are great, but try to spawn() something and a raw string works better. SDF From tdelaney at avaya.com Tue Mar 23 16:50:07 2004 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Wed, 24 Mar 2004 08:50:07 +1100 Subject: PEP 318 Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE01535405@au3010avexu1.global.avaya.com> > From: Skip Montanaro > > You'll be free to write your generator functions like so: > > def generator(f): > return f > > def silly_counter(n) [generator]: > for i in range(10): > yield n+i Ooh - I hadn't thought of that one Skip. I like it. Of course, rather than just passing the function through, I'd probably want to check that it was actually a generator. def generator (f): assert f.func_code.co_flags & 0x20 return f def silly_counter(n) [generator]: for i in range(10): yield n+i Tim Delaney From ruud.de.jong at consunet.nl Sat Mar 6 06:36:12 2004 From: ruud.de.jong at consunet.nl (Ruud de Jong) Date: Sat, 06 Mar 2004 12:36:12 +0100 Subject: CAN You help Re: Writing dictionary output to a file In-Reply-To: <20040306105936.20709.qmail@web60805.mail.yahoo.com> References: <20040306105936.20709.qmail@web60805.mail.yahoo.com> Message-ID: <4049b71a$0$41754$5fc3050@dreader2.news.tiscali.nl> First of all, please keep the discussion on comp.lang.python. Others may benefit from this as well. dont bother schreef: >Hey Can you help me with that? >My Problem is exactly here: > >You did not get me: >heres what I have to ask: > >"How to preserve this attribute -- line >number/position of the word in the dictionary." > I still don't understand the actual need for this. If the purpose is to provide a frequency count of words in a message compared with words in a dictionary, why would you need the actual *position* of the word in the dictionary? Is it really imprtant if the match was with the 6th or the 27th entry? And how do you handle addtions to the dictionary? So my first advice would be for you to make sure that you really *need* the position. >For example: If I am comparing words in a message with >the words in a dictionary, whenever there is a match, >I want to record the corresponding location of the >word in the dictionary. > I think you want to record the word, not it's position. Positions will change when new words are added to a dictionary, especially if the dictionary is kept in alphabetical sorted order. >heres the code I am using for matching the words in >the dictionary with the words in the message: > >for i in msg: > if i in dct: > try: > vector[i] += 1 > > except: > vector[i] = 1 > > I assume that this is preceded by something like: vector = {} Here you are filling the vector map with words as keys (not their positions), and their frequency counts as values. Aside: using a bare except is frowned upon: it will catch *every* error. What you probably want is something like: try: vector[i] += 1 except KeyError: vector[i] = 1 > >How to I store the corresponding location of the word >in the dictionary which is matching > Again, why would you need this? > >and then I will use this location as the key of the >vector and the value is being computed by vector[i] > And here is where the misunderstanding is. vector is keyed by the word itself, not by its position in the dictionary. > > >for v,i in enumerate(vector): > Confusing naming. enumerate(iterable) gives a list of (index, value) tuples. When you enumerate a map, the index values are of course sequential integers, starting with 0, but the values are essentially arbitrary keys from the mapping. So, here you have: v == irrelevant integer index value, and i == arbitrary key (=word) from vector > vector[i] /= a > I assume a is an integer, otherwise this would fail. You divide the count for the word i by a (total number of words in msg?). > #print v,i, vector[i] ; if u want to see the word >too that was commmon > This would print , , > print v,":",vector[i] > This would print : That still leaves the question: why would you want to relate the words in the message to their *position* in a dictionary? I still have not seen anything where you would need that. Regards, Ruud. From usenet_spam at janc.invalid Tue Mar 30 23:55:42 2004 From: usenet_spam at janc.invalid (JanC) Date: Wed, 31 Mar 2004 04:55:42 GMT Subject: [OT] Top posting is a PITA [was : Prothon Prototypes vs Python Classes] References: <4069a001$0$4237$afc38c87@news.easynet.co.uk> <4069e9d9$0$8915$636a15ce@news.free.fr> <0omac.74900$cx5.32735@fed1read04> Message-ID: "Mark Hahn" schreef: > I really really try to remember to quote from below. If you go through my > posts you will see that I remember most of the time. The last few days I > have been reponding to four or five mailing lists after months of only > coding and my fingers are worn out. Try OE-QuoteFix, it can help you, and it's free: Also, I think OE allows you to select the text-to-quote _before_ replying. -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From cpl.19.ghum at spamgourmet.com Sun Mar 28 18:18:25 2004 From: cpl.19.ghum at spamgourmet.com (Harald Massa) Date: Mon, 29 Mar 2004 01:18:25 +0200 Subject: Prothon Prototypes vs Python Classes References: <106dukh7ncf9ad4@news.supernews.com> Message-ID: 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". Harald From shifflett at nps.navy.mil Thu Mar 11 17:44:26 2004 From: shifflett at nps.navy.mil (D. Shifflett) Date: 11 Mar 2004 14:44:26 -0800 Subject: Select on Win XP Message-ID: Hi all, I am trying to run a Python program on my Win XP box, that I brought over from a Linux box. Of course, on Linux it works fine, but not so on Win XP. The program has a button to cause a packet to be sent to a server, the program also has a thread to read packets from the server. I send a packet, I get one back, pretty simple. I am using select() to wait for packets and it isn't functioning as expected. select() doesn't return until I have sent a packet even though I am using a short timeout (1 second) So whats happening is I send a packet, select() returns but I have no input yet, then I have to send the packet again then select returns and I can read the response to the first packet. Hoepfully I am doing something wrong on the Win system. Any help would be appreciated. Here's a snippet of the code from sys import argv from gtk import * import socket import time import threading import select ... my_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) my_sock.bind(('', MY_PORT)) class readerthread(threading.Thread): def __init__(self): self._stopevent = threading.Event() print "thread init" threading.Thread.__init__(self, name="readerthread") def run(self): 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) # read from the socket, etc if il != []: data, addr = my_sock.recvfrom(1024) print "recv() Data length %d" %len(data) print "recv() Data %s" % data else: print "No input from select" def join(self,timeout=None): """ Stop the thread """ self._stopevent.set() threading.Thread.join(self, timeout) ... def button_cb(button): my_sock.sendto(data, (SERVERADDR, SERVERPORT)) ... From http Fri Mar 19 05:01:54 2004 From: http (Paul Rubin) Date: 19 Mar 2004 02:01:54 -0800 Subject: SHA-based subclass for random module References: <7xptbgjpk4.fsf@ruckus.brouhaha.com> <5d83790c.0403190105.69ca83e7@posting.google.com> Message-ID: <7x8yhxtast.fsf@ruckus.brouhaha.com> python at rcn.com (Raymond Hettinger) writes: > I offer this as an alternative: > > from random import Random > from struct import unpack > import md5 Why md5 instead of sha? > class MD5Random(Random): > def newrandom(self, tofloat = 1.0 / 2 ** 53): > plaintxt = str(Random.random(self)) What's Random.random(self) supposed to do? > ciphertxt = md5.new(plaintxt).digest() I think you mean update. > randint = unpack('> 11 # grab 53 bits > return randint * tofloat > > Advantages over the original: > > * Much faster Yes, other version wasn't optimized. Both call the hash function approx once per output though. > * Much shorter code But doesn't support all the operations specified in the Random API. What's up with that? > * More readable code Perhaps so. It took me a little while to figure out in the previous version that the security came from revealing only part of the output of each hash (107 secret bits for SHA). In the md5 version there's only 75 secret bits, which is cutting things a little close. It may be harder to do a concrete security proof for this construction too (I'm not sure, I've never done one). > * Threadsafe Always a plus. > * Takes advantage of MT's proven equidistribution, of its passing > known tests for randomness, and of its known period (in contrast, > SHA-1 was designed as a digest that makes it computationally > intractable to find a different message giving the same signature -- > that does *not* imply the non-existence of short cycles for some > keys). I'm missing something here--if you're just trying to avoid possible cycles, why do you want to use MT instead of a sequential counter? The counter is guaranteed to never cycle (unless you overflow the 512 bit compression function input, which won't happen in the life of the universe). Note that while there's probably some short cycles in the double-SHA construction, the chance of finding one is infinitesimally small (it means finding a 320 bit birthday collision). Hitting one by accident is comparable to guessing an AES key by accident. Finding one by brute force or by cryptanalysis is again comparable to breaking AES. > * It uses both MD5 and the Mersenne Twister as they were designed (in > contrast, my google searches show *no* research on using SHA-1 in OFB > and reapplying SHA-1 again to conceal the output). Applying a collision resistant hash function to itself is a standard construction for making a PRF and is the basis of HMAC. I believe the relevant paper is Bellare, M., Canetti, R., and Krawczyk, H., "Pseudorandom Functions Revisited: The Cascade Construction". Proc. of the 37th IEEE Symp. on Foundation of Computer Science, 1996, webbed (PostScript) at: http://www.research.ibm.com/security/bck1.ps but I haven't slogged all the way through it yet. It has a concrete security proof and I've always found those things incredibly fussy and pedantic compared to normal math papers. I haven't yet figured out the reason why they're like that, or if they're really need to be. I'd like to attempt to do one for this generator though, once we settle on an algorithm. See also the other references to RFC 2104, notably Krawczyk et al's original HMAC paper from Crypto 96. My guess is the reason you haven't found any publications specific to SHA1 with this construction is that nobody has found any results against SHA1. As far as anyone can tell, the output is undistinguishable from random. From ieyf4fu02 at sneakemail.com Wed Mar 24 01:10:42 2004 From: ieyf4fu02 at sneakemail.com (Greg Ewing (using news.cis.dfn.de)) Date: Wed, 24 Mar 2004 18:10:42 +1200 Subject: PEP 318 In-Reply-To: References: <4qet50hla2dna5g8gqcbbfj2tsmu3smkp7@4ax.com> Message-ID: Peter Hansen wrote: > If it's a list, then just as surely a tuple should be allowed in its > place, as in every (?) other such case in Python that I can think of. > Would that be part of the proposal? No, in the current version of the PEP, it's not. The square brackets don't denote construction of a list. No sequence object of any kind is constructed -- the expressions are simply evaluated and applied one at a time. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From moranar at daleclick.com Sun Mar 14 16:11:07 2004 From: moranar at daleclick.com (Adriano Varoli Piazza) Date: Sun, 14 Mar 2004 18:11:07 -0300 Subject: Extracting info from OS/hardware In-Reply-To: <1059hm7s63ebh4f@corp.supernews.com> References: <1059hm7s63ebh4f@corp.supernews.com> Message-ID: <200403141811.40195.moranar@daleclick.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 El Dom 14 Mar 2004 17:55, Cameron Laird escribi?: > In article , > > Thomas Weholt <2002 at weholt.org> wrote: > >I need a piece of code to extract as much info about OS, current status > > and hardware from a machine as possible ( at least, all available > > partitions and free space on these, CPU-speed, free/total memory and > > stuff like that ) at one given moment on Linux and Windows. > > > >Any hints? Can I call something in win32all on Windows or read some file > > on linux? I'm not sure where to begin. > > . > . > . > I was hoping someone else would answer this. > > My impression is that there are dozens of answers to this. > I know I've seen quite a few such utilities advertised in > places like Freshmeat. I haven't kept track of them at > all. > > "... as much info ... as possible ...": whoooo! Usually > when a manager says that to me, I ask for how much he's > willing to pay. As it turns out, notions like "free > space", "CPU speed", and so on are surprisingly poorly > standardized. It's far from clear what they mean for any > particular platform. > > Sooooooo, what I usually do is define my requirements > carefully, and write up my own tool. > -- > > Cameron Laird > Business: http://www.Phaseit.net In Linux, you can get a lot of information on hardware and status by examining files in the /proc directory. For example, from doing cat /proc/cpuinfo on my system: [adriano at localhost adriano]$ cat /proc/cpuinfo processor : 0 vendor_id : AuthenticAMD cpu family : 6 model : 8 model name : AMD Athlon(TM) XP 1700+ stepping : 1 cpu MHz : 1833.218 cache size : 256 KB fdiv_bug : no hlt_bug : no f00f_bug : no coma_bug : no fpu : yes fpu_exception : yes cpuid level : 1 wp : yes flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 mmx fxsr sse syscall mmxext 3dnowext 3dnow bogomips : 3629.05 For disk space and free space, you check /proc/diskstats, etc. No idea about how to do it on Windows, but programs like "Treesize" tell me it mustn't be that hard. Ciao. - -- Adriano Varoli Piazza http://moranar.com.ar ICQ: 4410132 MSN: adrianomd at hotmail.com Claves gpg / pgp en hkp://subkeys.pgp.net -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.4 (GNU/Linux) iD8DBQFAVMqLkDP9anP2KHwRApTsAKChjLmg0AlCaQeRCzPhXBpZ3sq/twCg2kWq XyZNT8JkZeDn+hcmchUDP+8= =ioqx -----END PGP SIGNATURE----- From my.name at my.org.fr Mon Mar 22 12:35:11 2004 From: my.name at my.org.fr (Nicolas Decoster) Date: Mon, 22 Mar 2004 18:35:11 +0100 Subject: PyBuffer. Question on memory shared by C app and python. Message-ID: <405F23CF.1050808@my.org.fr> Hi. I have an app that allocates memory. I have created a python buffer that shares this memory. Example: data = (double*) malloc(size*sizeof(double)); buffer = PyBuffer_FromReadWriteMemory(data, size*sizeof(double)); The app and python interpreter does lots of things they find usefull. And one day, the app decides to free the memory: free(data); How can the app tell python not to try to access memory no more? Am I sure at this point that the app is the only one that has a ref on my Object? Thanks in advance for any suggestions. Nicolas. -- Noveltis From max at alcyone.com Thu Mar 25 17:27:32 2004 From: max at alcyone.com (Erik Max Francis) Date: Thu, 25 Mar 2004 14:27:32 -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> Message-ID: <40635CD4.C518231C@alcyone.com> Axel Boldt wrote: > Like I said, it would clarify the semantics of == for lists. Another > use would be to hash on values of lists. What part of the semantics are you unclear about? Two sequences are equal if they are element-wise equal. That is the definition that people rely on, that's the definition that the interpreter uses, and that definition is even consistent with the behavior you saw with the self-referencing lists which for some reason surprised you. -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE \__/ Whoever named it necking was a poor judge of anatomy. -- Groucho Marx From asdf at asdf.com Thu Mar 25 21:41:24 2004 From: asdf at asdf.com (asdf sdf) Date: Fri, 26 Mar 2004 02:41:24 GMT Subject: win gui thoughts? perhaps a non-Pythonic approach? In-Reply-To: References: Message-ID: > > bottom-line: i suspect that i'll much more quickly get a good gui > working with Delphi than with wxPython, and for little money to boot. > Might be a throwaway in the long-term but no problem if it is cheap and > easy. My customer doesn't care either way. > > any thoughts on this? > > i continue to research and i see a couple pythonic-ish approaches. PythonCard which is quick with good doc and samples. It is right on top of wxPython so it could serve as gentle intro to wxPython and has somewhere to go (wxDesigner, inexpensive) if I start to hit the limits of PythonCard. In the commercial area, QTDesigner with pyQT and possibly BlackAdder. Alarm bells go off when BlackAdder is mentioned because it arrived extremely late with an entire feature set (ruby support) removed. Python support is said to be complete, though. QT is a thoroughly mature, professional tool. Possibly a major learning curve if BlackAdder is a no-show. I think that pythonic gui design tools appear viable. I'm still trying to figure out if they are the best choice, for me, from a practical perspective (tradeoffs of learning curve and power v. non-pythonic commercial alternatives.) Expense is not really a major factor. From kkto at csis.hku.hk Wed Mar 10 10:58:30 2004 From: kkto at csis.hku.hk (Isaac To) Date: Wed, 10 Mar 2004 23:58:30 +0800 Subject: Working around a lack of 'goto' in python References: <7id67l8dro.fsf@enark.csis.hku.hk> Message-ID: <7ismggofrt.fsf@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()? Regards, Isaac. From jcarlson at nospam.uci.edu Sat Mar 20 05:04:19 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Sat, 20 Mar 2004 02:04:19 -0800 Subject: Package name with '.' in them: Python Bug ? In-Reply-To: References: Message-ID: > Well, I wrote one (it's generated names, that's why it happenned) ;) That doesn't make it a good idea. If it wasn't clear, I meant that of the thousands of Python source files I've seen, I've never seen any named with a dot. Probably because they don't work correctly, as you have found. You didn't answer my question as to whether module_5.py is reasonable replacement for the module.5.py naming scheme you are currently using. >> 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. The documentation is specific, you quoted it yourself: "This function does not handle hierarchical module names (names containing dots)." Any file name with a dot that is not the extension of the file, is considered hierarchical, and is "not handled". >> 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. Then you agree that your naming scheme is flawed. Stop doing it. - Josiah From calvin at ironfroggy.com Sun Mar 14 12:01:57 2004 From: calvin at ironfroggy.com (Calvin Spealman) Date: Sun, 14 Mar 2004 12:01:57 -0500 Subject: A Byte of Python - Python Book / Tutorial References: <5168381b.0403051311.5f1c843f@posting.google.com> Message-ID: > Iregards<5168381b.0403051311.5f1c843f at posting.google.com>,sentenceop C H wrote: >> >>I have a written a book on Python which serves as a tutorial or >>guide for anyone who wants to learn Python. It specifically targets >>beginners but experienced programmers can benefit a lot with the >>special notes for them. In regards to the Unicode string section, you end it to the sentence, "If you use plain English, don't be worried about this.", which is a bad thing to tell newbies and one of the largest, if not _the_ largest, reasons internationalization is so hard to achieve. It is just so easy to ignore good practices, like using Unicode strings even before you "have" to. By this same logic, you could say that a Japanese coder should just use some native character set that only has Japanese characters, because he/she doesnt speak English. This is crap. What am I complaining for? I'm just saying, if anything, we should say that all strings should be unicode strings, and should do so in our own code as well. From eltronic at juno.com Wed Mar 31 22:09:57 2004 From: eltronic at juno.com (eltronic at juno.com) Date: Wed, 31 Mar 2004 22:09:57 -0500 Subject: rlght click menu missing in most Tk apps Message-ID: <20040331.220959.-154733.0.eltronic@juno.com> here is some code to add right click context menus. in the few apps I've edited sofar, it just works, once you run rCbinder with the root of the gui or bind B3 all present and future widgets will have right click. there will be a line something like root=Tk.mainloop() #or Tkinter.mainloop() in epydoc it was necessary to look into the gui class and find one of the attributes has the root. add this before the root= line at the same indentation. rCbinder(gui._rootframe) #or root or whatever gui.mainloop() #or root. or= or whatever .|= hopefully authors or dedicated users of Tk apps will see how simple it is to add this basic service and will add the code themselves. in Qt you get rightclick menu's for free with all entry widgets. for gtk and wx, I don't know, probably is similar to one or the other. in pydoc it was necessary to add a search button also bind like the in the Entry widget so pydoc could be entirely mouse driven. self.search_btn = Tkinter.Button(self.search_frm, text='search', pady=0, command=self.search) ... self.search_btn.pack(side='right') ... self.search_ent.bind('',rClicker, add='') self.result_lst.bind('',rClicker, add='') in pydoc there are only 2 entry widgets so it was simpler to just bind them to rClicker directly rClicker takes an event as a parameter as default. if I ever get a sourceforge id I will post a patch. I found some of the original clues in Idle, which for unknown reasons doesn't provide rightclick copy & paste. I wouldn't take the lack of outcry as confirmation that noone is missing this basic expected convenience. you should assume some people think your app is broken and possibly have quit using and recommending it. certainly they rclick numerous times and are annoyed when nothing familiar happens. You can get fancy and disable or remove choices like don't display cut or delete where they don't make sense. you can add application specific shortcuts too, per widget, by checking the event._name attribute or type, you do name your widgets don't you? adding cascading menus is just like for pulldown menus. I've left all that out to simplify and shorten this posting. here are the 2 functions to add------------- def rClicker(e): ''' right click context menu for all Tk Entry and Text widgets ''' import Tkinter try: def rClick_Copy(e, apnd=0): e.widget.event_generate('') def rClick_Cut(e): e.widget.event_generate('') def rClick_Paste(e): e.widget.event_generate('') e.widget.focus() nclst=[ (' ',None), # (' Cut', lambda e=e: rClick_Cut(e)), (' Copy', lambda e=e: rClick_Copy(e)), (' Paste', lambda e=e: rClick_Paste(e)), ] rmenu = Tkinter.Menu(None, tearoff=0, takefocus=0) for (txt, cmd) in nclst: if txt == ' ------ ': rmenu.add_separator() else: rmenu.add_command(label=txt, command=cmd) rmenu.entryconfigure(0, state = 'disabled') rmenu.tk_popup(e.x_root-3, e.y_root+3,entry="0") except Tkinter.TclError: print ' - rClick menu, something wrong' pass return "break" def rClickbinder(r): import Tkinter try: for b in [ 'Text', 'Entry', 'Listbox', 'Label']: # r.bind_class(b, sequence='', func=rClicker, add='') except Tkinter.TclError: print ' - rClickbinder, something wrong' pass #I don't know this is the best way to go. but, #don't let the perfect be the enemy of the good enough #e ________________________________________________________________ The best thing to hit the Internet in years - Juno SpeedBand! Surf the Web up to FIVE TIMES FASTER! Only $14.95/ month - visit www.juno.com to sign up today! From stewartNO at SPAMmidtoad.homelinux.org Sun Mar 7 13:50:16 2004 From: stewartNO at SPAMmidtoad.homelinux.org (Stewart Midwinter) Date: Sun, 07 Mar 2004 18:50:16 GMT Subject: Socket Receive Buffer In-Reply-To: References: Message-ID: christofer wrote: > I am writing a small IRC type server. I also have a small test client > for obvious reasons. My problem is that when receiving input from the > server, my client sometimes ends up with two messages in the same > input buffer, which obviously causes problems. Anybody know why it is > doing this? Are you delimiting each message sent from the server with a '\n' ? From joe at notcharles.ca Tue Mar 9 13:53:50 2004 From: joe at notcharles.ca (Joe Mason) Date: Tue, 09 Mar 2004 18:53:50 GMT Subject: Working around a lack of 'goto' in python References: Message-ID: 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. 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, and if you don't catch it right it can escape up the call stack. Obviously the static vs. dynamic argument doesn't apply to Python, but I was replying to a massively dogmatic statement about all languages, not just Python. A more pragmatic argument is that, for C++, while (condition) { ... goto ENDLOOP; ... } ENDLOOP: ... Is just easier to read, and takes less typing, than // declare an EndLoopException class, which I forget how to do because // I haven't used C++ exceptions in ages try { while (condition) { ... throw EndLoopException; ... } } catch (EndLoopException e) { // this space intentionally left blank } The former is a well-understood idiom, and a not too inelegant workaround for the lack of named break. The latter is a horribly clumsy looking workaround for the same lack. Joe From aahz at pythoncraft.com Wed Mar 10 05:43:22 2004 From: aahz at pythoncraft.com (Aahz) Date: 10 Mar 2004 05:43:22 -0500 Subject: "print" as function not statement References: Message-ID: In article , Paul Prescod wrote: > >This is just a trial balloon. It isn't even in proper PEP format yet. >Don't take it too personally! Your arguments are persuasive, but I disagree with your conclusions. Given that almost every programming language has something like "print" built into it, we can't afford to drop that name. I think you need to find a path that permits mutation from a reserved word. The other issue is that you're wrong to make print() a function. Instead, it should be a callable object. That way, the default print object has state: print(a, b, c) print.set_output(my_file) print(a, b, c) print(x, y, z) print.set_separator(None) print("The value is: ", 3) > Debug-useful return value > > As a convenience, if the show function is passed a > single object to show, it returns that object. If > it is passed more then one, it returns them as a > tuple. This can be very convenient in debugging > contexts. I'm in agreement with the person who said that this would be too confusing in interactive mode. Then again, if print is an object, it'd be easy to set this behavior, too. -- 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 jcarlson at nospam.uci.edu Tue Mar 9 23:00:08 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Tue, 09 Mar 2004 20:00:08 -0800 Subject: generating points on a grid - efficiently In-Reply-To: References: Message-ID: > It is exponential in the number of dimensions, making various > assumptions (mainly that all ordinalities are roughly equal). It is > polynomial in the ordinality of dimensions, again with assumptions > (constant number of dimensions, all ordinalities roughly equal). It is > linear in the number of grid points. It is constant time, for a > specific set of inputs. > > When you write O(n), formally you have to define what n means. But I > don't think Rajarshi needed to be so formal. His intention should have > been clear, though - he didn't intend O(n^k), but rather O(k^n) where > n is the number of dimensions - making performance exponential. > > The real problem is that the number of output grid points is obviously > exponential in the number of dimensions (or polynomial in the > ordinalities, etc) so it's impossible to improve on this performance > characteristic while still generating all the grid points - only the > constant scalings can be improved. You do make a good point, and additionally proper algorithm analysis takes into account the data representation size of the input and output. If my input is a list of j sublists, certainly my input size is the sum of the length of each sublist (times the size of each element, which I will assume constant), which I will call m. However, my output, no matter how many lists there are, is of size o(j * m^j) (yes, that was little o). Now, looking at the actual problem, we have output of size exactly: j*len(sublist1)*len(sublist2)*len(sublist3)... In the extreme conditions: m*1^m <= size(output) <= (m/3)*3^(m/3) m <= size(output) <= m*3*(m/3 -1) Indeed, the output size (and time) /is/ worst-case exponential in the size of the input. We get that '3' either through numerical testing, or through calculus, which would give us 'e' as producing the largest size output. Testing both 2 and 3 show us that 3 is larger. I should have done the math in the initial post, thank you for pointing out my initial mistake, and allowing me to prove it mathematically. - Josiah From jdrugo at gmx.at Sun Mar 7 17:29:07 2004 From: jdrugo at gmx.at (Jan Drugowitsch) Date: Sun, 7 Mar 2004 22:29:07 +0000 Subject: ImportError when trying to import own C++ module In-Reply-To: <200403072156.25664.jdrugo@gmx.at> References: <200403072156.25664.jdrugo@gmx.at> Message-ID: <200403072229.16237.jdrugo@gmx.at> On Sunday 07 March 2004 21:56, Jan Drugowitsch wrote: > 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 Oops, I must have missed the 'U' there. Nevermind, after adding library_dirs=["."] and libraries=["AClass"] to the BClass Extention, everything works. Cheers, Jan -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: signature URL: From newsgroups at jhrothjr.com Sun Mar 28 15:51:33 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Sun, 28 Mar 2004 15:51:33 -0500 Subject: Prothon Prototypes vs Python Classes References: <569c605ld1cj8fc1emolk08ete0s1prls1@4ax.com><106cc1f2rsnaoe2@news.supernews.com><406635AB.9050803@mlug.missouri.edu><106ceeeqc8ph126@news.supernews.com> <106dukh7ncf9ad4@news.supernews.com> Message-ID: <106eeoho1cgqc6b@news.supernews.com> "Mark Hahn" wrote in message news:ZNF9c.49108$cx5.10276 at fed1read04... > Mutability is an interesting area. I just added an unmutable bit in the > Prothon internal object which makes the read_lock call a no-op and causes a > write_lock call to throw an exception. This makes the object > write-protected and makes the lock code run much faster. > > I did this for internal performance reasons, but after doing it I realize > that extending it to the Ruby freeze() level would be really good. Tying > the freezing in somehow to the bang! methods is also in interesting area of > research. > Mark Hahn (Prothon Author) I think that's a very rational way to go about it. I don't think that lexical labeling will work, though. It makes initialization too difficult. John Roth > P.S. If this belongs in the Prothon list instead of Python, let us know. > > > "David MacQuigg" wrote in message > news:bi1e601vsm4qtqaieqdo69bco64m7naupa at 4ax.com... > > On Sun, 28 Mar 2004 11:15:34 -0500, "John Roth" > > wrote: > > > > > > > >"Paul Prescod" wrote in message > > >news:mailman.10.1080485351.20120.python-list at python.org... > > >> John Roth wrote: > > >> > > >> > It's certainly true that in a prototype based language all objects > > >> > exist: there are no objects that the compiler deals with but does > > >> > not put into the resulting program. And it's quite true that it does > > >> > open up the floodgates for a lot of messiness. > > >> > > >> Ummm. This is also true for Python. Python classes exist at runtime. > > >> > > >> foo = 5 > > >> > > >> class foo: # oops. I've overwritten foo > > >> def bar(self): > > >> pass > > >> > > >> print foo > > >> print dir(foo) > > >> print type(foo) > > >> > > >> Paul Prescod > > > > > >Sure. But misusing classes as instances is quite rare in > > >practice, and plugging members into instances is also > > >quite rare in practice. Python's highly dynamic nature > > >opens it up to a lot of difficulty in principle, but most > > >deveopers seem to be quite disciplined in their use of > > >dynamism. > > > > > >The difficulty here is simply that there is no way of > > >isolating a base object that is supposed to be the platform > > >for other objects from objects that are supposed to be > > >updatable with new behavior. > > > > > >The higher a tower you want to build, the firmer the > > >foundation. Conventions help, but if the conventions > > >are helped along by the language, that's even better. > > > > In Ruby you can freeze() any object. But it seems like in this case, > > just giving your base object a distinct name, like PrototypePolygon > > will remind you not to change its definition later as you create > > triangles, rectangles, etc. > > > > I also would have no objection to some syntactic lock, like any object > > name ending in an underscore is an immutable object. We could also do > > this the other way around. Objects, by default are immutable. That > > would take care of most uses. If you want a mutable object, give it a > > name ending in ! (bang). > > > > -- Dave > > > > From __peter__ at web.de Tue Mar 2 13:33:56 2004 From: __peter__ at web.de (Peter Otten) Date: Tue, 02 Mar 2004 19:33:56 +0100 Subject: Computing test methods in unittest.TestCase References: <4044BE1E.7000408@jandecaluwe.com> Message-ID: Jan Decaluwe wrote: > I'm working on a unit test for a finite state machine (FSM). The FSM > behavior is specified in a dictionary called transitionTable. It has a > key per state with a tuple of possible transitions as the corresponding > value. A transition is defined as a number of input values, a next > state, and a documentation string. > > I want to test each possible transition in a separate test method. For [...] > As the number of transitions can be large, I want to > "compute" the test methods, based on the transitionTable info. [...] > Anyone with better ideas? Use a test suite instead and turn each FSMTest.testXXX() method into a TestCase instance: class TransitionTest(unittest.TestCase): def __init__(self, state, transition): unittest.TestCase.__init__(self) self.state = state self.transition = transition def bench(self, state, transition): pass def runTest(self): Simulation(self.bench(self.state, self.transition)).run() def __str__(self): return "Check state %s - %s" % (self.state, getDoc(self.transition)) def makeSuite(): suite = unittest.TestSuite() for st, trs in transitionTable.iteritems(): for tr in trs: suite.addTest(TransitionTest(st, tr)) return suite if __name__ == "__main__": unittest.main(defaultTest="makeSuite") Peter From kbass at midsouth.rr.com Thu Mar 11 20:49:46 2004 From: kbass at midsouth.rr.com (kbass) Date: Fri, 12 Mar 2004 01:49:46 GMT Subject: Newby Question: Python and A Nested Dictionary Message-ID: <_G84c.1393$P45.950@fe1.columbus.rr.com> I am new to Python and I am attempting to retrieve data from a database and I would like to place this data into a nested dictionary. After placing the data into a dictionary, I would like to loop through the data using for loops. How would I do this? The format that I am attempting is: Select data ... Get data ... Place data into a nested dictionary Rev[A] [B] = [500, 700, ...] for value1 in a: for value2 in Rev[A] for value3 in Rev[A][B] print something kbass From mickel at csc.fi Wed Mar 10 01:25:13 2004 From: mickel at csc.fi (=?ISO-8859-1?Q?Mickel_Gr=F6nroos?=) Date: Wed, 10 Mar 2004 08:25:13 +0200 (EET) Subject: Unicode and rdf In-Reply-To: References: Message-ID: On Tue, 9 Mar 2004, Richard West wrote: > I'm trying to parse the rdf dumps from dmoz.org (Open Directory > Project) and am having great difficulty just getting Python to read > the files. Have you tried rdflib by Daniel Krech? http://rdflib.net/ Regards, Mickel Gr?nroos -- Mickel Gr?nroos, application specialist, linguistics, Research support, CSC PL 405 (Tekniikantie 15 a D), 02101 Espoo, Finland, phone +358-9-4572237 CSC is the Finnish IT center for science, www.csc.fi From FBatista at uniFON.com.ar Wed Mar 31 12:41:08 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Wed, 31 Mar 2004 14:41:08 -0300 Subject: PEP 327: Decimal data type Message-ID: People: This PEP is ready for your review. As always, any feedback is very welcomed. Thank you! . Facundo From robin at jessikat.fsnet.co.uk Fri Mar 26 18:07:51 2004 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Fri, 26 Mar 2004 23:07:51 +0000 Subject: A 'Python like' language References: <40645d8f$0$10775$afc38c87@news.easynet.co.uk> <1068up4kn49778@news.supernews.com> Message-ID: In article <1068up4kn49778 at news.supernews.com>, John Roth writes ..... >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. > luckily I learned the opposite and outlook has been off my radar since its inception. I prefer tabs, but it seems hard to convince many programs that they have meaning so probably the prothoneers have it wrong. >John Roth > > -- Robin Becker From bogus at bogus.net Fri Mar 12 01:17:54 2004 From: bogus at bogus.net (Paul McGuire) Date: Fri, 12 Mar 2004 06:17:54 GMT Subject: put your money where your mouse is, or why I prefer Spanish to English: a proposal References: Message-ID: "Simon Wittber" wrote in message news:mailman.296.1079066607.19534.python-list at python.org... > Are you ranting or attempting to be humourarse? > > S. > I believe this was a "modest proposal." -- Paul From deetsNOSPAM at web.de Mon Mar 15 12:09:57 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Mon, 15 Mar 2004 18:09:57 +0100 Subject: (no subject) References: Message-ID: myang wrote: > > How can I covert these codes into human-readable string? I am sure the > filecontains only some float numbers and some characters. If you know s/t about the data you expect, you can use the module struct to convert the raw data. -- Regards, Diez B. Roggisch From eric at zomething.com Wed Mar 17 10:02:12 2004 From: eric at zomething.com (Eric @ Zomething) Date: Wed, 17 Mar 2004 07:02:12 -0800 Subject: heapq iteration? Message-ID: <20040317070212.2058820938.eric@zomething.com> I'm missing something critical about how heapq works. I assumed I could iterate through the heap, but I get partial iteration: >>> listB [56, 208, 89, 413, 273, 199, 73, 21, 89, 13, 27, 199, 273, 413, 11, 22, 56, 2, 208] >>> heapify(listB) >>> for h in listB: m=heappop(listB) print m, '\t',listB 2 [11, 13, 73, 21, 27, 199, 89, 22, 89, 273, 56, 199, 273, 413, 208, 208, 56, 413] 11 [13, 21, 73, 22, 27, 199, 89, 56, 89, 273, 56, 199, 273, 413, 208, 208, 413] 13 [21, 22, 73, 56, 27, 199, 89, 208, 89, 273, 56, 199, 273, 413, 208, 413] 21 [22, 27, 73, 56, 56, 199, 89, 208, 89, 273, 413, 199, 273, 413, 208] 22 [27, 56, 73, 56, 208, 199, 89, 208, 89, 273, 413, 199, 273, 413] 27 [56, 56, 73, 89, 208, 199, 89, 208, 413, 273, 413, 199, 273] 56 [56, 89, 73, 208, 208, 199, 89, 273, 413, 273, 413, 199] 56 [73, 89, 89, 208, 208, 199, 199, 273, 413, 273, 413] 73 [89, 89, 199, 208, 208, 199, 413, 273, 413, 273] 89 [89, 208, 199, 208, 273, 199, 413, 273, 413] >>> TIA, Eric From rmanx at gmx.de Thu Mar 25 12:01:05 2004 From: rmanx at gmx.de (Robert) Date: Thu, 25 Mar 2004 18:01:05 +0100 Subject: threading crashes application References: Message-ID: Hi the problem is not solved but I have found a workaround. I have found out that "self.result.addTO(self.line)" is causing problems. No idea why it crashed sometimes, but not it is stable. Robert From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Sat Mar 6 05:47:42 2004 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Sat, 06 Mar 2004 11:47:42 +0100 Subject: is perl better? In-Reply-To: <80a8af7d.0403051630.2b278bf0@posting.google.com> References: <80a8af7d.0403051630.2b278bf0@posting.google.com> Message-ID: <4049ac4d$0$564$e4fe514c@news.xs4all.nl> Klaus Momberger wrote: > you might try to define classpath as a system environment variable and > increase the environment buffer size using the /E:nnnnn option of > command.com. command.com is not used on windows NT/2000/XP > It can be set from CONFIG.SYS with an entry like: > > SHELL=C:/WINNT/SYTEM32/command.com C:\ /P /E:4096 Config.sys ditto. This won't work because he uses a windows 2000 system. --Irmen From ray_molachaNOSPAM at gmx.co.uk Wed Mar 24 13:02:25 2004 From: ray_molachaNOSPAM at gmx.co.uk (Ray Molacha) Date: Wed, 24 Mar 2004 18:02:25 GMT Subject: Simple raster graphics ? How do I ... Message-ID: Hi Everybody. I'm learning Python on a Windows computer, using PythonWin. I'd like to be able to do some simple raster graphics, like clearing the screen and plotting a point of some color. I want to plot some fractals and math functions just for fun. I understand the math ok -- I don't know how to do simple raster graphics. I've looked through the documentation, but nothing obvious jumped out at me. I saw the turtle module, but it seemed like overkill -- and maybe not exactly suited to my purpose -- given what I remember of Logo. (What I want to do would have been really easy in QBasic a few years back.) I also did a Google search on , which turned up enough hits, but I had trouble telling what would be appropriate. The obvious solutions seemed to use packages and modules that were only (as far as I could tell) available on Linux. I'd be grateful if someone would point me in the right direction. Or have computer graphics gotten so complicated that it's hard to do simple things nowadays? TIA Ray From tjreedy at udel.edu Mon Mar 8 21:20:03 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 8 Mar 2004 21:20:03 -0500 Subject: Recursive function always returns None References: Message-ID: "Patrick LeGresley" wrote in message news:pan.2004.03.09.01.16.40.825600 at stanford.edu... > Hi, > > I have a sample piece of code for which I can't understand why it > returns the output it does. I am running Python 2.3.2 on Redhat > Linux 8.0 (x86 hardware). Here is the code and output: > > granada 6% cat tmp.py > def test(astring): > > if (len(astring) >= 30): > print 'astring =',astring > return astring > else: > astring = astring + astring > test(astring) None is the default return when you do not specify one, as you did not for the second branch ;-). Add 'return' before 'test' on final line. Don't feel too stupid -- I am sure most of us have forgotten a 'return' or 'yield' at least once. However, testing with test(50*'a') would have given different behavior that might have given you a clue. Also think about (or try) test('').* Terry J. Reedy * hint: 0+0=0 From dave at nullcube.com Sat Mar 13 19:21:47 2004 From: dave at nullcube.com (Dave Harrison) Date: Sun, 14 Mar 2004 11:21:47 +1100 Subject: DCOracle2 and header files ?? Message-ID: <20040314002147.GA24122@dave@alana.ucc.usyd.edu.au> Hi All, Im trying to use the DCOracle2 library but I've never worked with Oracle before, yet have to investigate the effort involved in porting a database we have to it. When I try running a `make` in the DCOracle2 dir having set the env variables correctly I get the following error : make || ./builderrors) make[1]: Entering directory `/root/DCOracle2/src' gcc -fPIC -DNDEBUG -O2 -g -pipe -march=i386 -mcpu=i686 -D_GNU_SOURCE -fPIC -I/usr/include/python2.2 -I/usr/include/python2.2 -DHAVE_CONFIG_H -I/u01/app/oracle/or_home/rdbms/demo -I/u01/app/oracle/or_home/network/public -I/u01/app/oracle/or_home/plsql/public -I/u01/app/oracle/or_home/rdbms/public -DORACLE9i -DUSEOWNXID -c ././dco2.c -o ./dco2.o dco2.c: In function `Cursor_bind': dco2.c:3275: error: `dword' undeclared (first use in this function) dco2.c:3275: error: (Each undeclared identifier is reported only once dco2.c:3275: error: for each function it appears in.) dco2.c:3275: error: syntax error before ')' token dco2.c:3277: error: syntax error before ')' token dco2.c:3294: error: syntax error before ')' token make[1]: *** [dco2.o] Error 1 make[1]: Leaving directory `/root/DCOracle2/src' Ive looked in the /u01/app/oracle/or_home/rdbms/demo dir to check for the header files that should be there, but they arent. Does anyone know how I am supposed to install the header files ?? or if this is a problem that has another solution ?? Im no longer subscribed to the python-list mailling list, so if you could reply directly I would appreciate it. Thanks in advance Dave -- Dave Harrison Nullcube dave at nullcube.com http://www.nullcube.com From hungjunglu at yahoo.com Fri Mar 26 11:37:05 2004 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 26 Mar 2004 08:37:05 -0800 Subject: Python for large projects References: <1060p59d9rg9819@corp.supernews.com> Message-ID: <8ef9bea6.0403260837.72a8fade@posting.google.com> > On Tue, 2004-03-23 at 17:24, Cameron Laird wrote: > > > they're at a particular DISadvantage there. If you have a > > big job, you *particularly* need to look at Python (or Erlang, > > or Eiffel, or ...) -------------------------------------------- gabor wrote in message news:... > ... > i wanted to use python for a project in our company... we wanted to > build a fairly big system/program. > > but when i recommended python, i got a question like: > (previously all the programs were written in java) > "if one of our programmers changes a method in a class/interface, we > immediately will know about it, because the next program-rebuild will > simply fail. but if we would use python, we wouldn't find it out". -------------------------------------------- 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 From mcfletch at rogers.com Mon Mar 1 01:48:07 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Mon, 01 Mar 2004 01:48:07 -0500 Subject: Licensing of wrappers around C/C++ code under more restrictive licensing. In-Reply-To: References: <7ed8f64d.0402280218.5ff447cf@posting.google.com> Message-ID: <4042DCA7.2040302@rogers.com> Andrew Koenig wrote: >"Mike C. Fletcher" wrote in message >news:mailman.1.1078031359.21439.python-list at python.org... > > > >>The FSF peoples seem to have a different interpretation, as, last I >>heard, they suggest that software that links to any GPL software, even >>at run-time constitutes an infringement (regardless of your not having >>distributed the GPL code yourself, and the end-user having a perfectly >>valid license to link the two for personal use). >> >> > >Can you provide evidence to support this claim? > > Mmm, evidence, always fun to research... A quick search didn't turn up any statements which are black and white on the particular issue of a "scripting language" API. As noted in the paragraph above, I was going by other people's statements. Closest thing I could find were these: What is the difference between "mere aggregation" and "combining two modules into one program"? Mere aggregation of two programs means putting them side by side on the same CD-ROM or hard disk. We use this term in the case where they are separate programs, not parts of a single program. In this case, if one of the programs is covered by the GPL, it has no effect on the other program. Combining two modules means connecting them together so that they form a single larger program. If either part is covered by the GPL, the whole combination must also be released under the GPL--if you can't, or won't, do that, you may not combine them. What constitutes combining two parts into one program? This is a legal question, which ultimately judges will decide. We believe that a proper criterion depends both on the mechanism of communication (exec, pipes, rpc, function calls within a shared address space, etc.) and the semantics of the communication (what kinds of information are interchanged). If the modules are included in the same executable file, they are definitely combined in one program. If modules are designed to run linked together in a shared address space, that almost surely means combining them into one program. By contrast, pipes, sockets and command-line arguments are communication mechanisms normally used between two separate programs. So when they are used for communication, the modules normally are separate programs. But if the semantics of the communication are intimate enough, exchanging complex internal data structures, that too could be a basis to consider the two parts as combined into a larger program. Also: However, in many cases you can distribute the GPL-covered software alongside your proprietary system. To do this validly, you must make sure that the free and non-free programs communicate at arms length, that they are not combined in a way that would make them effectively a single program. The difference between this and "incorporating" the GPL-covered software is partly a matter of substance and partly form. The substantive part is this: if the two programs are combined so that they become effectively two parts of one program, then you can't treat them as two separate programs. So the GPL has to cover the whole thing. And: If the program dynamically links plug-ins, and they make function calls to each other and share data structures, we believe they form a single program, so plug-ins must be treated as extensions to the main program. This means that linking the GPL-covered plug-in with the main program would violate the GPL. However, you can resolve that legal problem by adding an exception to your program's license which gives permission to link it with the non-free main program. Which is from the GNU.org FAQ. here: http://www.fsf.org/licenses/gpl-faq.html Now, the first two quotes don't explicitly state that, in the event that you let *someone else* distribute the GPL software, you are okay with using direct and intimate communication (which the Python module being discussed would, I think, qualify as). However, that is the image that arises. That is, if you are not distributing the GPL software you might be okay, if not for that third paragraph. The first two quotes suggest that, if your software links "intimately" with the GPL software and you distribute both pieces of software (even though only "alongside" one another, (such as two download links from a web-site?)), though, then your package is a derivative work and thus GPL-requiring. The third quote, however, goes much farther. A plug-in, presumably downloaded entirely separately from an application (hence plug-in) is somehow able to violate the license of the plug-in merely by being loaded by the proprietary application, effectively by being "linked in" by the user. In the situation we are describing, a GPL library with an arguably more intimate linking (the Pythonic interface) is being loaded into a proprietary application, we would seem to have met all of the conditions outlined in that third paragraph (and more). To make that work, the using application somehow has to be a derivative work of the plug-in, which, particularly in the case of a plug-in API, makes no sense, after all, the plug-in API is from the application and almost certainly has no code specific to the GPL-licensed plug-in. What would stop a user from using the plug-in with the application? How this works, (other than wishful thinking) I don't know, as it had been my impression that the unmodified use of GPL software on your own computer wasn't affected by the GPL. The strange thing about the third quote is that, from the GPL section 0 (the FAQ has no legal weight AFAIK): Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. which seems to allow the *end user* to combine proprietary code with unmodified GPL-licensed software for their own use. As mentioned in the earlier message, I don't think there's been too much case law saying that you can claim copyright on something which doesn't include any of your code, the LGPL even explicitly states (section 5), if there's no LGPL code in the given element, then it is not a derivative work. Still, there must be some logic which makes the application above somehow a derivative of its plug-in. Though again, I was under the impression that, for personal use, you could create derivatives which linked against proprietary code (even intimately)... Anywho, hope that's sufficient, must be off to write now. Mike (In case anyone is silly enough to think I were... "I am not a lawyer") _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From jaustin at post.harvard.edu Mon Mar 22 19:15:43 2004 From: jaustin at post.harvard.edu (Jess Austin) Date: 22 Mar 2004 16:15:43 -0800 Subject: PEP 318 References: Message-ID: I'll preface by saying that I haven't fully grokked all the possible uses of decorators. Also, I can sympathize with the complaints about seeing a function definition and then seeing a classmethod call on that function 50 lines later (actually that seems like a case for refactoring but never mind). b-) The brackets and the 'as' both seem awkward to me. Also, introducing a requirement that definition and decoration take place on the same line seems to limit the the possibilities of decoration. Perhaps my class wants to offer several faces of the same method: 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. later, Jess From ville at spammers.com Sun Mar 28 04:34:01 2004 From: ville at spammers.com (Ville Vainio) Date: 28 Mar 2004 12:34:01 +0300 Subject: Choosing Perl/Python for my particular niche References: <40652B0D.7C313F77@doe.carleton.ca> <40657D14.3FBE7E82@doe.carleton.ca> <106b7k2s8af5c3c@corp.supernews.com> <106be9aroogdq77@corp.supernews.com> Message-ID: >>>>> "Cameron" == Cameron Laird writes: >> Since you happily use Perl, Python or Tcl, I have a >> question. How do you decided which one to use? :-) >> >> Robert Cameron> Most often, whatever is already at hand. It'll be Cameron> interesting some day to come across an organization that Cameron> doesn't already have a standard in place. Many organizations don't, esp. if the actual product they produce is not written in either of the languages. Some code may exist, but there is no "official" standard. And if there is, there is a good possibility of changing it if you are able to demonstrate clear technical superiority in skunkworks projects. And w/ Python, you are. Been there, done that :-). -- Ville Vainio http://tinyurl.com/2prnb From asdf at asdf.com Thu Mar 25 21:46:47 2004 From: asdf at asdf.com (asdf sdf) Date: Fri, 26 Mar 2004 02:46:47 GMT Subject: win gui thoughts? perhaps a non-Pythonic approach? In-Reply-To: <7652139e.0403251807.619375da@posting.google.com> References: <7652139e.0403251807.619375da@posting.google.com> Message-ID: Chris Reay wrote: > 1. Delphi is good if the project is very simple and mostly GUI & data, > without much business logic. > 2. Python is better if there's much data and logic, and (little or) no > GUI. > 4. My latest MS Win project requires all: GUI, data, C/S, logic. I'm > using Visual C#.net and so far I believe it's a good choice. > thankx for the feedback. sounds like you're supporting the idea that python is a better _language_ than pascal (delphi), but that delphi has a more effective toolset/framework for gui work. is .net the better framework for gui work also, or is that choice imposed on you by customer requirements? From python at rcn.com Fri Mar 19 04:22:30 2004 From: python at rcn.com (Raymond Hettinger) Date: 19 Mar 2004 01:22:30 -0800 Subject: SHA-based subclass for random module References: <7xptbgjpk4.fsf@ruckus.brouhaha.com> Message-ID: <5d83790c.0403190122.60c311c@posting.google.com> Correction to the last posting. The method name should have been random() instead of newrandom(). Raymond From gandreas at no.reply Thu Mar 25 12:19:39 2004 From: gandreas at no.reply (Glenn Andreas) Date: Thu, 25 Mar 2004 11:19:39 -0600 Subject: Make 'def' and 'class' usable within expressions References: <1065uf99la6if29@news.supernews.com> Message-ID: In article , Shane Hathaway wrote: > John Roth wrote: > > If you can make a contribution to a good syntax for > > a code block, I for one would welcome it. > > > > Just to give you a start: Ruby puts a single code block > > at the end of the parameter list where it's quite obvious > > what it is and where it does not interrupt the flow of reading > > the method call. In python, I'd like to be able to put code > > blocks wherever I can currently put a function / method > > object. > > > > For example: > > > > result = map(lambda: ..., list1, list2, list3) > > > > is readable - barely. > > > > result = map(def (x, y, z): > > something > > something else > > return > > list1, list2, list3) > > > > becomes much less readable. This is the problem that > > needs to be solved to make code blocks fly. > > That's one of the things I'm trying to achieve, too. Using this syntax, > I would write it this way: > > result = map(def(x, y, z), list1, list2, list3): > something > something else > return x > > Shane > 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? 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" } (since you'd have to write: myHandlers = { "click" : def(x,y), "enter" : somePreviousFunctionForEnter, "exit" : somePreviousFunctionForExit } : print "click at x,y" which, due to the large distance between the "def" and the body is terribly hard to figure out) From newsgroups at jhrothjr.com Wed Mar 17 17:28:26 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Wed, 17 Mar 2004 17:28:26 -0500 Subject: Newbie Python (Game) Programming Question References: Message-ID: <105hkcg5796il98@news.supernews.com> "Tina" wrote in message news:QX36c.26341$%06.21748 at newsread2.news.pas.earthlink.net... > Thanks to both of you. I'm very much a Python newbie and the ability to make > things callable wasn't addressed too well/at all in either of the Python > books I'm learning from. > > 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. For general interactive fiction, see the rec.arts.int-fiction newsgroup and check out the periodic FAQ posting. There are two Python interactive fiction systems: PAWS (Python Adventure Writing System) and PUB (Python Universe Builder). Neither one is very popular, but they may give you some ideas. John Roth > > From csgcsg39 at hotmail.com Thu Mar 4 05:41:58 2004 From: csgcsg39 at hotmail.com (C GIllespie) Date: Thu, 4 Mar 2004 10:41:58 -0000 Subject: Calling C programs Message-ID: Dear All, 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') and os.execv('/tmp/hello',[' ']) but I can't seem to store the return value. Many thanks Colin From hove at bccs.no Tue Mar 30 06:08:22 2004 From: hove at bccs.no (Joakim Hove) Date: Tue, 30 Mar 2004 13:08:22 +0200 Subject: ESR's fortune.pl redone in python - request for critique References: Message-ID: <4yekrazj6h.fsf@skjellgran.ii.uib.no> > I would appreciate any comments, criticism, suggestions, alternative > options, etc. Here are some random comments; needless to say they represent my subjective view. Others mitht disagree heartily! > FORTUNES_FILE = ".fortune" > > # What file should we use? > if len(sys.argv) > 1: > fortunes_file = sys.argv[1] > else: > fortunes_file = FORTUNES_FILE Using the same variable name with only difference in capitalization I consider very bad taste. I would suggest using for instance the variable name 'default_fortunes_file' instead of FORTUNES_FILE. > fp_entry = [0] You probably want to start with an *empty* list, not a list with '0' as the first element, i.e. fp_entry = [] > fortune = '' > line = fi.readline() > while line != '': > if re.match(r'^%$', line): > break > fortune += line > line = fi.readline() > print fortune Wouldn't it be more natural to look for '%' instead of blank lines: fortune = '' line = fi.readline() while line: if re.match(r'^%$',line): break fortune += line line = fi.readline() > # Return fp to beginning of file, close the file, and exit program > fi.seek(0,0) > fi.close() > sys.exit() I like to close the files explicitly, like you do. However it is not really necessary, they are closed automatically (by the garbage collector I guess). Repositioning the -- /--------------------------------------------------------------------\ / Joakim Hove / hove at bccs.no / (55 5) 84076 | \ | Unifob AS, Avdeling for Beregningsvitenskap (BCCS) | Stabburveien 18 | | CMU | 5231 Paradis | \ Thorm?hlensgt.55, 5020 Bergen. | 55 91 28 18 / \--------------------------------------------------------------------/ From fletcher at worldnet.att.net Fri Mar 12 22:00:40 2004 From: fletcher at worldnet.att.net (elizabeth fletcher) Date: Sat, 13 Mar 2004 03:00:40 GMT Subject: drowning newbie Message-ID: Want to use Sam Rushing's calldll Python Module on a windows box. I don't understand how to install it. I have several books that do not detail the steps in installing a 3rd party module in Windows. Anybody want to throw me life preserver? From teiffel at attglobal.net Wed Mar 3 18:02:10 2004 From: teiffel at attglobal.net (Marcello Pietrobon) Date: Wed, 03 Mar 2004 18:02:10 -0500 Subject: function arguments passed by reference In-Reply-To: <104cj8vkrqb6i20@news.supernews.com> References: <104cj8vkrqb6i20@news.supernews.com> Message-ID: <404663F2.5040602@attglobal.net> John Roth wrote: >"Marcello Pietrobon" wrote in message >news:mailman.8.1078344338.736.python-list at python.org... > > >>Hello, >> >>My background is C++ >> >>I would like to know for sure if it is possible to pass a value by >>reference to a function AND having it changed by the function itself >> >> >>def changeValue( text ): >> text = 'c' >> print text >> return >> >> >>> txt = 'a' >> >>>changeValue( txt ) >>'c' >> >>>print txt >>'a' >> >>Question 1) >>I guess that in Python ( differently than in C++) somehow txt is passed >>by reference even if its value is not changed. >>Is this true ? >> >>Question 2) >>How can I define a function that changes the value of txt ( without >>having to return the changed value ) ? >> >>Question 3) >>Is there some documentation talking extensively about this ? >> >> > >The key concept is that everything is an object, and all objects >are passed by reference in the sense that what's bound to the >funtion's parameters is the objects that were passed in. > >However, you cannot affect the bindings in the calling environment. >Regardless of what you do (unless you do some deep magic with >the invocation stack) nothing is going to affect the bindings in the >caller. > >So you can rebind anything you want to the parameters within >the function, and it will have no effect on the calling environment. > >On the other hand, if you mutate a mutable object that was passed >as a parameter, that change will be visible after you return. > >For example: > >def foo(bar): > bar = "shazoom" > >a = "shazam" >foo(a) > >The result is that a is still "shazam." > >However, if you do this: > >def foo(bar): > bar.append("shazoom") > >a = ["shazam"] >foo(a) > >the result is: > >["shazam", "shazoom"] > >HTH >John Roth > >"shazoom" ::= ["strength", "health", "aptitude", "zeal", "ox, power of", >"ox, power of another", "money"] > >whatever the value you passed in remains. > > Thank you for the answers, difficult to get used to these concepts after coming from C++ ! But I am starting to understand: the main difference between Python and C++ is that I need to keep in mind what is mutable and what is not mutable in Python Cheers, Marcello From sjf at autograf.pl Mon Mar 1 10:34:22 2004 From: sjf at autograf.pl (..:: sjf ::..) Date: Mon, 1 Mar 2004 16:34:22 +0100 Subject: Reading selected data from text files References: Message-ID: U?ytkownik "Paul McGuire" napisa? w wiadomo?ci news:MVK%b.7974$lS1.1103 at fe2.texas.rr.com... > "..:: sjf ::.." wrote in message > news:c1njho$adr$1 at nemesis.news.tpi.pl... > > Hello Pythoners! > > > > There are a lot of files containing data such as: > > > > file1: > > 0950 1550 > > > > file22: > > 0952 1552 > > > > > -- > > ..:: sjf ::.. > > "Linux is like Wigwam. No gates, no windows... Apache inside ;-)" > Try this: > > import sets > import os > > uniqueElems = sets.Set() > > testdata = """ > 0950 1550 > 0952 1552 > 1000 1020 1050 1130 1150 1200 1245 1600 > 1002 1022 1052 1132 1152 1202 1247 1602 > 1005 1025 1055 1135 1155 1205 1250 1605 > """ > for line in testdata.split("\n"): > uniqueElems.update( line.split() ) > # if running Python 2.3.1 or later, replace previous line with > # uniqueElems |= line.split() ^^^^^^^ OK, but what is that? -- ..:: sjf ::.. "Linux is like Wigwam. No gates, no windows... Apache inside ;-)" From joe at notcharles.ca Tue Mar 9 11:57:52 2004 From: joe at notcharles.ca (Joe Mason) Date: Tue, 09 Mar 2004 16:57:52 GMT Subject: Working around a lack of 'goto' in python References: Message-ID: In article , Y2KYZFR1 wrote: >> > Step away from the computer slowly . . . >> > >> > There is absolutely NO LEGITIMATE REASON to use GOTO in any modern >> > language, ESPECIALLY Python, EVER! >> > >> > No stay away from computers until you understand how and why this is. >> >> >> Bull. I've used goto's in similar cases as those presented. I have >> found that in the right cases they are quite readable. Never had a >> problem with them when used like this. >> >> So you didn't answer the question, how would you do this clearly in >> Python? >> > > same way you would do it in any other OBJECT ORIENTED language. Use > the appropriate pattern. Which would be what? (No, it's not exceptions. Stay away from this thread until you understand why it's not.) Joe From john at neggie.net Wed Mar 24 16:39:31 2004 From: john at neggie.net (John Belmonte) Date: Wed, 24 Mar 2004 16:39:31 -0500 Subject: portable /dev/null again In-Reply-To: <16481.62214.163592.282439@montanaro.dyndns.org> References: <4061D154.8090809@neggie.net> <16481.60337.370411.907718@montanaro.dyndns.org> <4061ED09.1080506@neggie.net> <16481.62214.163592.282439@montanaro.dyndns.org> Message-ID: <40620013.30702@neggie.net> Skip Montanaro wrote: > In general you can't pass file descriptors between programs. A library I'm using requires a file descriptor to output to, and I'd like to give it /dev/null. > While I agree you can open /dev/null for reading, it's rarely used that way. Agreed, I suggested it for completeness. > If you want something that returns an honest-to-god file object, how about: > > import os > def nullfile(mode="wb"): > return file(os.path.exists("/dev/null") and > "/dev/null" or > "nul:", mode) This code will break if Python ever supports a new OS that doesn't use one of those file names. > Guido made an astute observation the other day which I can't find at the > moment. It went something like, "The biggest problem I have now is > convincing people that just because something's not already in the standard > library doesn't mean it belongs there." I suspect this applies. If a > portable null file object is the cats pajamas for you, write something and > throw it in your personal toolbox or post it to your personal Python page > where others can find it. I'm not interested in cats or pajamas, just the os library telling me what the null filename is for the OS I'm running on, just as it tells me what the path separator, etc. is. I've already put an implementation in my local library, but it may well break in the future as I've explained, and I feel other Python users facing this shouldn't have to do the same. -John -- http:// if ile.org/ From garryknight at gmx.net Sun Mar 14 12:25:58 2004 From: garryknight at gmx.net (Garry Knight) Date: Sun, 14 Mar 2004 17:25:58 +0000 Subject: where can I find Paris Hilton video? References: <20040314105158.138$FE@news.newsreader.com> Message-ID: <1079285158.21022.2@echo.uk.clara.net> In message <20040314105158.138$FE at news.newsreader.com>, Mike W. wrote: > > "montezum" wrote in message > news:Vd2dnQi55L8-S87d4p2dnA at look.ca... >> where can I find Paris Hilton video? > > Most likely not in any of these groups.... But you could ask anyone you see standing around outside the Paris Hilton with a video camera... -- Garry Knight garryknight at gmx.net ICQ 126351135 Linux registered user 182025 From Holger.Joukl at LBBW.de Wed Mar 17 05:22:47 2004 From: Holger.Joukl at LBBW.de (Holger Joukl) Date: Wed, 17 Mar 2004 11:22:47 +0100 Subject: Problem with threads and signals Message-ID: Hi, put some debug output in the code (print statements in the shutdown function). 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. 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??? Cheers Holger Der Inhalt dieser E-Mail ist vertraulich. Falls Sie nicht der angegebene Empf?nger sind oder falls diese E-Mail irrt?mlich an Sie adressiert wurde, verst?ndigen Sie bitte den Absender sofort und l?schen Sie die E-Mail sodann. Das unerlaubte Kopieren sowie die unbefugte ?bermittlung sind nicht gestattet. Die Sicherheit von ?bermittlungen per E-Mail kann nicht garantiert werden. Falls Sie eine Best?tigung w?nschen, fordern Sie bitte den Inhalt der E-Mail als Hardcopy an. The contents of this e-mail are confidential. If you are not the named addressee or if this transmission has been addressed to you in error, please notify the sender immediately and then delete this e-mail. Any unauthorized copying and transmission is forbidden. E-Mail transmission cannot be guaranteed to be secure. If verification is required, please request a hard copy version. From jepler at unpythonic.net Fri Mar 26 23:04:22 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Fri, 26 Mar 2004 22:04:22 -0600 Subject: Passing items of a lsit as arguments In-Reply-To: References: Message-ID: <20040327040422.GA21568@unpythonic.net> On Fri, Mar 26, 2004 at 09:31:47PM +0000, Tobias Pfeiffer wrote: > Hi! > > I want to call a function that was defined with *args in the header, e.g. > 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) You can call the functions with the arguments you want this way: create_polygon(*bla + (...,), **{'fill'=blue}) However, Tkinter.Canvas is forgiving in the way it accepts arguments. For instance, this works just fine: >>> c.create_polygon([(10, 10), (10, 30), (30, 30), (30, 10)], fill="blue") or even >>> c.create_polygon([40, 40, 60, 40, 60, 60, 40, 60], fill="green") so just write '...create_polygon(bla, ..., fill=blue)'. Jeff From zh at li.org Tue Mar 30 02:51:50 2004 From: zh at li.org (zh at li.org) Date: Tue, 30 Mar 2004 16:51:50 +0900 Subject: Failure (python-list@python.org) Message-ID: <20040330075150.E8ABB31794@yellow.sys.hokudai.ac.jp> ------------------ Virus Warning Message (on vw2) Found virus WORM_NETSKY.Q in file data3420.zip The file data3420.zip is moved to /etc/iscan/virus/virENC86a4wO. - Hokkaido University VirusWall ----------------- -------------- next part -------------- Mail Delivery Failure - This mail couldn't be shown. ------------- failed message ------------- TXe~?r#_.Ws-?UuVY7Ux_FwpK:p7kbiv%2rNg4k&NV?0t;$ 8)L?nh;GdyR~)k+#zi6$doJ%*d7't?Xr%|5Hv0IHV$Q$?A BZ;iO)>n5!W'!MV$yAPyFM??zrr1v_0A38.gO~d;.4L ? References: Message-ID: Carl Banks wrote: > You know what? I'd like to have a fast, compiled language that looks > like Python, too. Great. Now _why_ would it have to be compiled? "Fast" is understandable (though not an absolute measure), but "compiled" is meaningless without some reason behind it. Compilation is not something which inherently delivers any particular value to anyone. Depending on the specifics of the problem at hand, it _might_ be a way of getting better performance, or better packaging, etc. So I'd like a faster Python too (at least, for purposes of the current discussion... it's actually plenty fast for me), but I couldn't care less if it were compiled because that's an implementation detail or something. -Peter From thehofffs at hotmail.com Thu Mar 25 21:44:43 2004 From: thehofffs at hotmail.com (Emhoff) Date: 25 Mar 2004 18:44:43 -0800 Subject: Regular expressions and sub Message-ID: <1c750f1c.0403251844.3e027d93@posting.google.com> Hey hey -- I've got a question about regular expression substitions. Basically, I want to do something like this: re.sub(r"(stuff)|(blah)", r"I was \00", "stuff blah") Which would yield the string "I was stuff I was blah" -- but I get "I was \x00 I was \x00" because apparently the replace string is simply being interpreted as a normal string, and not a regular expression. So, my question is, is there a simple way to do what I want? Thanks much, John From jacek.generowicz at cern.ch Mon Mar 15 03:54:23 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 15 Mar 2004 09:54:23 +0100 Subject: loop scope References: Message-ID: David MacQuigg writes: > >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). > > I think the current design of Python is the right compromise between > narrow scopes that avoid conflicts between identical names and broad > scopes that minimize the need for global declarations. Imagine having > to declare globals inside every loop that needed to set some value > outside of its own tiny little scope. And what if the variable I want to affect is in an enclosing scope, but not the global scope ? Doesn't this rather suggest that the whole global declaration business is rather flawed? It sort of made sense when we only had 3 scopes in Python (only 2 of which were "userland" scopes) , but with nested scopes it's simply not up to the job. Ultimately, the problem can be traced to having no distinction between inctroducting a new binding and rebinding an existing name. From hungjunglu at yahoo.com Tue Mar 9 14:48:24 2004 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 9 Mar 2004 11:48:24 -0800 Subject: DLL version number References: <8ef9bea6.0403081509.31b3f9e@posting.google.com> <404d1159_5@127.0.0.1> Message-ID: <8ef9bea6.0403091148.19e75629@posting.google.com> "Roger Upole" wrote in message news:<404d1159_5 at 127.0.0.1>... > You can use win32api.GetFileVersionInfo. > See /demos/getfilever.py for an example of how to use it. > Roger > > "Hung Jung Lu" wrote in message > news:8ef9bea6.0403081509.31b3f9e at posting.google.com... > > > > If I have a Windows DLL file, how can I retrieve its version number > > (e.g.: 2.40.4275.1)? Does Win32 extensions, ctypes or related modules > > provide such a utility? Thanks. However, I still have problems. What I need are the 4-part version numbers, which GetFileVersionInfo() does not provide. I tried several alternatives, including GetFileVersionInfo() and the mwi module. However, these alternatives do NOT give the 4-part version number that one sees by right-clicking on a DLL (on Win2k.) The puzzling part is that apparently at the C level, the data structure _DllVersionInfo contains only 3 parts: dwMajorVersion, dwMinorVersion, dwBuildNumber. (For COMCAT.DLL, GetFileVersionInfo() gives only two-part version number: 4.71, whereas if you right click in Windows 2000, you get a four-part version number: 4.71.1460.1) Anyway, the relationship between the 4-part version number and the 3-part version number is highly non-trivial and I do not see any easy rules that applies to all DLLs. (For some DLLs, the last part of a 3-part version number can be split into the last two parts of the 4-version number, but this rule is not universal.) I wonder what Windows uses internally to get the 4-part version numbers? regards, Hung Jung From claird at lairds.com Thu Mar 11 10:24:25 2004 From: claird at lairds.com (Cameron Laird) Date: Thu, 11 Mar 2004 15:24:25 -0000 Subject: Extending Python Syntax with @ References: <40507cd4$0$15845$afc38c87@news.easynet.co.uk> Message-ID: <1051159aq8rifd0@corp.supernews.com> In article <40507cd4$0$15845$afc38c87 at news.easynet.co.uk>, Peter Hickman wrote: . . . >Maybe what we need is a language that has only a grammer and the syntax >/ vocabulary comes from the objects. Or is that AppleScript? Forth. Lisp. Tcl. -- Cameron Laird Business: http://www.Phaseit.net From deets_noospaam at web.de Sun Mar 7 18:52:34 2004 From: deets_noospaam at web.de (Diez B. Roggisch) Date: Mon, 08 Mar 2004 00:52:34 +0100 Subject: dynamic names References: Message-ID: Val Bykoski wrote: > tot=tot + ("L%s" % L) Here you seem to miss an exec - the line should probably read like this: tot = tot + exec("L%s" % L) -- Regards, Diez B. Roggisch From and-google at doxdesk.com Mon Mar 15 04:03:13 2004 From: and-google at doxdesk.com (Andrew Clover) Date: 15 Mar 2004 01:03:13 -0800 Subject: xml.minidom and threads References: <9106c987.0403120759.6b1df015@posting.google.com> Message-ID: <2c60a528.0403150103.1896dbbc@posting.google.com> Sunil Movva wrote: > So, I came to suspect if xml.minidom module is thread-safe. No it isn't, but I doubt this is your problem as you don't seem to be trying to access the DOM Nodes from multiple threads, let alone concurrently. (Is there any good reason why you need to serialise and re-parse between each thread?) A SAXParseException is generally what it says on the tin, caused by faulty syntax in the XML document being parsed. It is conceivable that minidom's serialisation code at the second-thread-output stage is producing something wrong; we'd have to have a look at the string the third thread is trying to parse to find out what. -- Andrew Clover mailto:and at doxdesk.com http://www.doxdesk.com/ From bobx at linuxmail.org Sat Mar 6 18:18:17 2004 From: bobx at linuxmail.org (Robert) Date: Sat, 06 Mar 2004 18:18:17 -0500 Subject: Tkinter3000 Message-ID: <89WdnQhnm6Gkwdfd4p2dnA@adelphia.com> Is the WCK still an active project? Also, at one point there was going to be an O'Reilly book on Tkinter, did that die? Robert From michele.simionato at poste.it Mon Mar 1 13:55:21 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 1 Mar 2004 10:55:21 -0800 Subject: Thoughts on new vs traditional idioms References: <5d83790c.0402290218.2d3c493f@posting.google.com> Message-ID: <95aa1afa.0403011055.1fea6bff@posting.google.com> Michael Hudson wrote in message news:... > Well, I think calling __init__ directly is a horrendous idea. It just > reads badly. > Seconded. Michele From me at privacy.net Sat Mar 13 08:22:35 2004 From: me at privacy.net (Heather Coppersmith) Date: 13 Mar 2004 08:22:35 -0500 Subject: Python style guidelines References: <3064b51d.0403101112.3449e987@posting.google.com> <4050EAA3.9010807@wberry.org.x> <92c59a2c.0403122308.35513650@posting.google.com> Message-ID: On 12 Mar 2004 23:08:19 -0800, jcb at iteris.com (MetalOne) wrote: > I do not like style guidelines either. If one method can be > factually proven better than another method, then it would make > sense to encourage the better method. However, when this can't > be done, then the guideline is simply based upon taste or gut > instinct or personal preference. These all vary from person to > person and who is to say what is correct. Agreed. > During my schooling I was taught to always place statements on their > own line. > x = 0 > y = 0 > z = 0 > I accepted this completely without thinking about it much. > 20 years later I have finally come to realize that if (x,y,z) > represents a point that > x = y = z = 0 or > (x,y,z) = (0,0,0) > is not always so bad. It conserves lines of code, and being able to > see more lines of code at one time is beneficial. In python, x = y = z = 0 (x, y, z) = (0, 0, 0) is exactly two statements, so all is still well with the world. ;-) > Some guidelines recommend functions with only a single return > point. I don't understand why this insanity got started. At > one point it was recognized that multiple entry points into a > function was confusing, but why did it have to get extrapolated > to multiple exit points. Upon entry to a function, I sometimes > like to verify that everything is ok before proceeding and if it > is not just get out. Parameters can validated, resources > acquired, or whatever. It's that "resources acquired" part that messes people up. I've seen it over and over and over again. Memory leaks. Dangling pointers. Unrecoverable file handles. Especially as functions that acquire lots of resources evolve over time and someone adds code to acquire another resource or detect another error condition and then doesn't find all the subsequent exit points. It's less of an issue with languages with proper garbage collection, but it can be a real nightmare in (e.g.) C or assembler. Unit tests that cover all possible resource leaks are difficult to construct correctly. C++ partially addresses the problem with RIAA (if coders use it properly) and a hodgepodge of "smart" objects that do pseudo self-garbage collection. A single exit point also gives me a fighting chance to add something to the logical end of a function, like setting the "I'm done" flag or logging the result. If I know that my function only has one exit point, then it's also easier to add "let's see what this function is returning" debugging code, because I know exactly where to put it and where to look for it later when I want to take it out. In some systems, the fact that a given function reaches its (single) exit point is extremely valuable information. OTOH, I'm usually the first one to stand up at a design review and declare that some function or some method is too long or too complex and should be broken up *before* such problems occur. And that all said, I agree that a bunch of pre-checks and a quick exit, BEFORE DOING ANYTHING ELSE, near the top of a function can make the rest of some functions much more clear. Again, I've seen it a million times: I'll add one more validation down here, but forget to release that memory we just acquired up there. > At my work we currently have a guideline to always use brackets in > "if" statements. > if > { > single statement > } > else > { > single statement > } Yep, those guidelines are useless. Shouldn't we spend our code review time doing something productive? > And so it goes. I guess I am a believer in TIMTOWTDI. The more code I read, the more I wish people would use the *obvious* way. ;-) > The other thing about guidelines is that once somebody publishes > a book with guidelines, lookout. Your employer may soon have > you following them all whether you agree with them or not. > Rational Rose and UML are great examples of this, but that is > another story. Yes it is, and I have lived it. Eeuuww. Regards, Heather -- Heather Coppersmith That's not right; that's not even wrong. -- Wolfgang Pauli From theller at python.net Thu Mar 25 06:24:57 2004 From: theller at python.net (Thomas Heller) Date: Thu, 25 Mar 2004 12:24:57 +0100 Subject: Problems with py2exe 0.50 and win98se and win2k References: Message-ID: <4qsdcgom.fsf@python.net> jamesl at appliedminds.com (James Laamnna) writes: > 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. Can it be that py2exe collects some system dlls in the dist dir? Thomas From alx5962NOSPAN at yahoo.com Tue Mar 2 13:52:18 2004 From: alx5962NOSPAN at yahoo.com (Alex) Date: Tue, 2 Mar 2004 19:52:18 +0100 Subject: variable name using a for Message-ID: <4044d7f3$0$4664$626a14ce@news.free.fr> Hi I would like to create a variable (a string) in 'for' statement with a name linked to the for value. Like this: for y in range(nbSujets): name + str(y) = 'abc' But it doesn't work with Python.... I read the official documentation but I was not able to find infos about this.. How to make this works please? Thanks Alex From rogerb at rogerbinns.com Sat Mar 13 00:24:12 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Fri, 12 Mar 2004 21:24:12 -0800 Subject: Unicode is driving me nuts! References: <20040312231904.63687.qmail@web13004.mail.yahoo.com> Message-ID: Skip Montanaro wrote: > Unicode creates lots of problems for the uninitiated. For the uninitiated, I heartily recommend Joel's article: http://www.joelonsoftware.com/articles/Unicode.html Roger From skip at pobox.com Thu Mar 11 13:19:28 2004 From: skip at pobox.com (Skip Montanaro) Date: Thu, 11 Mar 2004 12:19:28 -0600 Subject: backquote In-Reply-To: References: <9e5ea2c4.0403110753.5c4d437a@posting.google.com> Message-ID: <16464.44464.132738.996372@montanaro.dyndns.org> >> `object` is equivalent to repr(object). Paul> Is this syntax one of those vestigial short-cuts that is on Paul> somebody's hit list for future deprecation? I suspect so, but not before Python 3. Skip From prouleau at impathnetworks.com Wed Mar 17 20:20:22 2004 From: prouleau at impathnetworks.com (Pierre Rouleau) Date: Wed, 17 Mar 2004 20:20:22 -0500 Subject: Swig-Python problems In-Reply-To: References: Message-ID: matteo wrote: > 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 > 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?? What does your interface space file (examplei.i) contain? From jepler at unpythonic.net Fri Mar 5 10:49:44 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Fri, 5 Mar 2004 09:49:44 -0600 Subject: reg exp and octal notation In-Reply-To: References: <4048938a$0$41754$5fc3050@dreader2.news.tiscali.nl> Message-ID: <20040305154944.GE31275@unpythonic.net> If you have a string and want to perform backslash-substitution on it, use python2.3's "string_escape" codec. Two examples: >>> s = "\\n" >>> s '\\n' >>> s.decode("string_escape") '\n' >>> "\x30" '0' >>> "\\x30" '\\x30' >>> "\\x30".decode("string_escape") '0' You can remove the trailing newline this way: if s.endswith("\n"): s = s[:-1] Jeff From jepler at unpythonic.net Mon Mar 1 16:29:59 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 1 Mar 2004 15:29:59 -0600 Subject: Function calling another function In-Reply-To: <00c201c3ffda$2293c990$559ea380@D4XN6B41> References: <00c201c3ffda$2293c990$559ea380@D4XN6B41> Message-ID: <20040301212959.GE6936@unpythonic.net> Code very much like yours works fine here. One reason it might not work in your case is if the "..." part of 'def x()' creates a local variable named y. $ cat /tmp/basic_one.py def main(): y() x() def y(): print "y" def x(): print "x" y() main() $ python /tmp/basic_one.py y x y Jeff From andersjm at dancontrol.dk Wed Mar 10 09:46:18 2004 From: andersjm at dancontrol.dk (Anders J. Munch) Date: Wed, 10 Mar 2004 15:46:18 +0100 Subject: PEP 328: Imports: Multi-Line and Absolute/Relative References: Message-ID: <404f2a3b$0$726$edfadb0f@dread11.news.tele.dk> "Aahz" wrote: > > from Tkinter import (Tk, Frame, Button, Entry, Canvas, Text > LEFT, DISABLED, NORMAL, RIDGE, END) +1 > Here are the contenders: > > * One from Guido:: > > from .foo import > > and :: > > from ...foo import +1 I presume from ..sibpack import amod will import from a sibling package; a common need. IMO relative imports should be preferred over absolute imports. An absolute import is sort of like a global variable. Relative imports should require minimal effort and look good. It has been argued that the dot is too small and easily overlooked. However, it is replacing something that's _completely_ invisible, and I haven't heard at lot of complaints about that. And if the dot-count is off it's not a big problem, you get an import error and fix it. >The final option is to define an algorithm > for finding relative modules and packages; the objection here is > "Explicit is better than implicit". (The algorithm proposed is > "search up from current package directory until the ultimate package > parent gets hit".) -1. Too DWIM. - Anders From http Mon Mar 22 22:27:59 2004 From: http (Paul Rubin) Date: 22 Mar 2004 19:27:59 -0800 Subject: SHA-based subclass for random module 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> Message-ID: <7x7jxc9r9c.fsf@ruckus.brouhaha.com> Trevor Perrin writes: > Actually, Random could be made even easier to subclass. getrandbits > (which is new in 2.4) returns a long. It would be better for us if > there was a getrandstring() function that an underlying generator > could implement. This would also be a helpful addition to the API, at > least for cryptographic uses. I agree with this, and was going to propose the same thing. getrandbits can be defined easily in terms of getrandstring, and the current sample sharandom implemenation at http://www.nightsong.com/phr/python/sharandom.py does something along those lines. From no at sp.am Thu Mar 11 12:42:56 2004 From: no at sp.am (DH) Date: Thu, 11 Mar 2004 11:42:56 -0600 Subject: Video module? In-Reply-To: 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 > stable enough for my purposes. I have also tried using Windows Media > Player with COM, but that is cumbersome. The module must work on Windows > (and preferably on Linux as well). Basically, what I need to be able to > do is play a selected interval of the movie and if possible also rip > the sound track from the movie file as a WAV file. On windows, those are the only two options I know of - pygame or activex/com. On mac, you have quicktime, too. Or you could use jython and java with the java media framework or qtjava. From jacek.generowicz at cern.ch Mon Mar 15 13:54:07 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 15 Mar 2004 19:54:07 +0100 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: Peter Hickman writes: > Jacek Generowicz wrote: [...] > Right. I should listen to you because you are an authority on Typing > but ignore Guido van Rossum. No, I am saying that you should try using your brain. > So you are saying the Guido van Rossum doesn't know what he is talking > about and I should take it from you what he really meant? No, I am saying that you should try thinking about the _meaning_ of the words in the context in which they appear. > you are positing to know what he really meant. I am suggesting an interpretation of what he said, which you are free to accept or reject. However, I recommend that you accept or reject it on the basis of some _thoughtful_ consideration of the information being presented to you. You appear to be bent on not thinking at all. > > ... he seems to be suggesting that Python is NOT weakly typed ... so > > the implication seems to be that it IS strongly typed. What he's > > really hinting at is the fact that weak-vs-strong and > > static-vs-dynamic are orthogonal axes. > > Well if we are to assume that Guido doesn't know what he is talking > about then you can probably twist his words to suit whatever you want > him to mean (as opposed to what he actually said). > > > > (Hint: "runtime typing" is almost synonymous with "dynamic typing".) > > Hint: Guido used the words 'strong', 'weak' and 'runtime' in the same > discussion and clearly delineated one from the others. Hint: read it again, and try to _think_ about what it actually means, rather than trying to find support for your misconceptions. > > What an absurd statement. You are suggesting that Python's type system > > somehow depends on the relative magnitudes of two people's knowledge. > > When one of them is the creator and guiding light of the language. Yes. So, if Guido were to have a stroke tonight and become a human vegetable, thereby making my knowledge of Python exceed his, Python's type system would magically change from weak to strong overnight ? Just _think_ about what you are saying. 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. > > I certainly don't know more about Python than Guido does, but I do > > appear to know more about type system nomenclature than Guido does :-) > > Is this a resort to argument from authority. (no smiley) Did you even read the very next thing I wrote? which you conveniently (for your trolling purposes) elided. > > Argument from authority is remains very unconvincing, even if that > > authority is Guido himself. > > pot/kettle/black I presented you with an explanation of what I consider strong, weak, static and dynamic typing to mean. I pointed out to you that in the very piece of an interview you quoted, Guido seems to be agreeing with me. Nowhere am I suggesting that you believe me because of my "authority"; I am suggesting that you _think_ about what is being said. All you have to say is "Guido this, Guido that". Are you capable of thinking for yourself ? (Congratulations for making me sound like Erik Naggum). Now, if you want to discuss what strong, weak, static and dynamic typing means, and how it applies to various languages, then I'm happy to discuss it with you. If all you are going to do is repeat your misconceptions and your religious belief in Guido's complete infallability, then don't be surprised if you don't hear from me again. From vincent at visualtrans.de Mon Mar 1 14:11:12 2004 From: vincent at visualtrans.de (vincent wehren) Date: Mon, 1 Mar 2004 20:11:12 +0100 Subject: default print format for floats References: <3064b51d.0403011046.4238998d@posting.google.com> Message-ID: schrieb im Newsbeitrag news:3064b51d.0403011046.4238998d at posting.google.com... | By default, Python prints many floating point numbers with 17 digits | after the decimal place. I would like to make the DEFAULT 4 decimal | places. Is this possible? | | For example, the code | | from string import join | x = [1.0,0.3,0.4] | print x | print join(["%4.1f" % y for y in x]) | | gives the output | | [1.0, 0.29999999999999999, 0.40000000000000002] | 1.0 0.3 0.4 | | I want the simplicity of "print x", without so many decimal places. I wouldn't cjanging "DEFAULT BEHAVIOR", but a slight modification of the above gives you: >>> x = [1.0, 0.3, 0.4] >>> print ", ".join(["%.4f" % y for y in x]) 1.0000, 0.3000, 0.4000 Is this what you're after? HTH, Vincent Wehren From premshree_python at yahoo.co.in Mon Mar 15 21:18:19 2004 From: premshree_python at yahoo.co.in (=?iso-8859-1?q?Premshree=20Pillai?=) Date: Tue, 16 Mar 2004 02:18:19 +0000 (GMT) Subject: Static Typing in Python In-Reply-To: Message-ID: <20040316021819.14345.qmail@web8308.mail.in.yahoo.com> --- Jacek Generowicz wrote: > Peter Hickman writes: > > > Perhaps you should read the following > > I have read it before. I still disagree with the > implication that > Python is weakly typed just much as I did when I > first read it. I second that. Python *is* strongly typed. ===== -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 fpetermaas at netscape.net Fri Mar 12 05:36:44 2004 From: fpetermaas at netscape.net (Peter Maas) Date: Fri, 12 Mar 2004 11:36:44 +0100 Subject: How to add pairs to a dict? In-Reply-To: References: Message-ID: Anthony Liu schrieb: > I want to keep adding pairs my phone_book dict like > so: > > phone_book={'jack':2313, 'john':3436} > > And then each time when a new pair is created, for > example, 'tom':5678, I want to add it to the dict so > that the dict becomes > > phone_book={'jack':2313, 'john':3436} I assume you want phone_book['tom'] = 5678 which leaves phone_book as {'jack':2313, 'john':3436, 'tom':5678} 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 jeff at nwbc-chicago.org Wed Mar 31 17:41:15 2004 From: jeff at nwbc-chicago.org (Jeff Mikels) Date: Wed, 31 Mar 2004 16:41:15 -0600 Subject: Palm Desktop Syncs with Outlook Message-ID: Here is a python script to synchronize Palm Desktop Datebook files with Outlook's Calendar I'm releasing it under the Python license as version 0.1. -------------------------------------------------------------------------------- ''' palm2Outlook.py Author: Jeff Mikels Version: 0.1 License: Python Purpose: Synchronize (only one way right now) Palm Desktop with MS Outlook Usage: just run it, and then select the Calendar Folder to import Palm Desktop items into. Warning: no duplicates are created. The Palm Desktop information writes over any Outlook items with the same text Dependencies: palmFile.py, pythonWin ''' import palmFile, win32com.client def createAppointment(a,targetFolder): return saveAppointment(a,targetFolder.Items.Add( 1 )) #olAppointmentItem = 1 def changeAppointment(a,appt): targetFolder = appt.Parent appt.Delete() return createAppointment(a,targetFolder) def saveAppointment(a,appt): ''' from palmFile calendarEntryFields = ( "recordID", "status", "position", "startTime", "endTime", "text", "duration", "note", "untimed", "private", "category", "alarmSet", "alarmAdvUnits", "alarmAdvType", "repeatEvent" ) ''' try: if a['untimed']: appt.AllDayEvent = 1 appt.Start = makeTime(a['startTime']) appt.End = makeTime(a['endTime']) appt.Subject = a['text'] appt.Body = a['note'] if a['alarmSet']: if a['alarmAdvType'] == 0: appt.ReminderMinutesBeforeStart = a['alarmAdvUnits'] elif a['alarmAdvType'] == 1: #hours appt.ReminderMinutesBeforeStart = a['alarmAdvUnits'] * 60 else: #a['alarmAdvType'] = 2: #days appt.ReminderMinutesBeforeStart = a['alarmAdvUnits'] * 60 * 24 else: appt.ReminderSet = 0 if a['repeatEvent']['repeatEventFlag']: repeatDetails = appt.GetRecurrencePattern() if a['repeatEvent']['brand'] == 1: #daily repeatDetails.RecurrenceType = 0 #olRecursDaily = 0 elif a['repeatEvent']['brand'] == 2: #weekly repeatDetails.RecurrenceType = 1 #olRecursWeekly = 1 repeatDetails.DayOfWeekMask = ord(a['repeatEvent']['brandDaysMask']) elif a['repeatEvent']['brand'] == 3: #monthly by day repeatDetails.RecurrenceType = 3 #olRecursMonthlyNth = 3 repeatDetails.Instance = a['repeatEvent']['brandWeekIndex'] + 1 #Palm uses 0 for first week, but Outlook uses 1 #For Day of Week, Palm only uses one possible day #and not a whole mask like Outlook. This field has Monday = 0 and Sunday = 6 #Outlook is looking for Sunday = 2**0, Monday = 2**1, Tues = 2**2 etc. repeatDetails.DayOfWeekMask = 2**((a['repeatEvent']['brandDayIndex']+1) % 7) elif a['repeatEvent']['brand'] == 4: #monthly by date repeatDetails.RecurrenceType = 2 #olRecursMonthly = 2 repeatDetails.DayOfMonth = a['repeatEvent']['brandDayNumber'] elif a['repeatEvent']['brand'] == 5: #yearly repeatDetails.RecurrenceType = 5 #olRecursYearly = 5 repeatDetails.MonthOfYear = a['repeatEvent']['brandMonthIndex'] + 1 #Palm stores this from 0-11 repeatDetails.DayOfMonth = a['repeatEvent']['brandDayNumber'] repeatDetails.PatternStartDate = makeDate(a['startTime']) repeatDetails.Interval = a['repeatEvent']['interval'] if a['repeatEvent']['endDate'] != 1956545999: repeatDetails.PatternEndDate = makeDate(a['repeatEvent']['endDate']) appt.Save() return appt except: import pprint print '\nSAVE APPOINTMENT ERROR:\n\tsaveAppointment encountered an error while saving this item.\n' pprint.pprint(a) print '\n' return None def findAppt(a,folderToSearch): try: return folderToSearch.Items.Find('[Subject] = "' + a['text'] + '"') except: import pprint print '\nFIND APPOINTMENT ERROR:\n\tfindAppt encountered an error looking for this event\n' pprint.pprint(a) print '\n' return None def makeDate(timeval): import time retVal = time.localtime(timeval) return str(retVal[1]) + '/' + str(retVal[2]) + '/' + str(retVal[0]) # m/d/yyyy def makeTime(timeval): import time retVal = time.strftime("%m/%d/%Y %I:%M %p", time.localtime(timeval)) return retVal def parseOlTime(timestring): import time retVal = time.mktime(time.strptime(timestring,'%m/%d/%y %H:%M:%S')) return retVal palmData = 'c:\\Program Files\\Palm\\MikelsJ\\datebook\\datebook.dat' fileStruct = palmFile.readPalmFile(palmData) events = fileStruct[0]['datebookList'] #events = palmFile.getUpcomingEvents(fileStruct,7) ol = win32com.client.Dispatch("Outlook.Application") olNS = ol.GetNamespace("MAPI") #olFolders = olNS.Folders() calFolder = olNS.PickFolder() #calFolder = olNS.Folders('Personal Folders').Folders('Calendar-Test') for event in events: appointment = findAppt(event,calFolder) if not appointment: appointment = createAppointment(event,calFolder) #appointment.Display() else: pass #appointment = changeAppointment(event,appointment) #appointment.Display() ''' DEFINING CONSTANTS with win32com we can read the constants directly from Outlook's Object model at runtime from win32com.client import gencache gencache.EnsureModule('{00062FFF-0000-0000-C000-000000000046}', 0, 9, 0) or specify the constants directly olAppointmentItem = 1 or run C:\Python23\Lib\site-packages\win32com\client\makepy.py and select Microsoft Outlook this step parses all the constants and win32com keeps track of them I've done this, so I can just use the constants (theoretically) ''' -------------------------------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From mogmios at mlug.missouri.edu Mon Mar 29 01:25:43 2004 From: mogmios at mlug.missouri.edu (Michael) Date: Sun, 28 Mar 2004 22:25:43 -0800 Subject: Prothon Prototypes vs Python Classes In-Reply-To: <106eut1pe29uab8@news.supernews.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> Message-ID: <4067C167.5050708@mlug.missouri.edu> >The basic difficulty with tabs is that there are a huge >number of programs "in the wild" that treat tabs >differently. Unless you're completely in control of all >the programs that will ever be used to edit and display >your program, using tabs will cause formatting errors >somewhere, to someone under some circumstance >that you never thought of. > > Which programs? I find spaces to cause weird issues. Especially if you use some half assed editor that uses variable width fonts. >The problems with mixed tabs and spaces are even >worse: you can lose indentation and totally mess up >the program so it won't even compile if you use the >wrong tools on such a program. > > That'd just be bad programming to use different formatting standards within the same program. At least within the same file. >This is the basic reason why the current standard for >library modules is 4 space indentation; it's the only >thing that is, for all practical purposes, guaranteed to >work for everyone, with any editor, formatter, >renderer and printer out there. > > I don't see how it is any better than a standard of always using a single tab or space for indention. I hate code that requires me to press multiple space or delete keys to change the block level of a line of code. I'm a coder and therefore am lazy. Why press four keys when I could press one? >Python is not Perl. Python's philosophy has never >been to provide several different ways of doing things >just to provide different ways. There needs to be a >demonstrated benefit to the different ways, and tabs >don't make that cut. If you want the space savings, >ziping the file will do much better. > > I'm not a fan of multiple ways but I think it's different to remove a feature than to add a feature. Breaking existing code for pointless reasons is bad. I'd rather they keep tab support than spaces but since both have a historical support I'd be wary of removing either. Again zipping files is adding additional steps which IMO is bad from a lazy coder point of view. The lazy coder standard of coding keeps code simple. Smaller isn't a significant problem in most cases. From tjreedy at udel.edu Tue Mar 9 14:26:03 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 9 Mar 2004 14:26:03 -0500 Subject: While: else: (was Re: Working around a lack of 'goto' in python) References: <20040309035213.GB18682@unpythonic.net><003c01c405a9$b4483720$3501a8c0@rogersqyvr14d3><20040309142924.GI12662@unpythonic.net> Message-ID: "Terry Reedy" wrote in message news:c2l3j0$6q7$1 at sea.gmane.org... > It is ironic that these comments on while-else should arise in a thread on > goto. In: > > if condition: something() > else: somethingelse() > > it is clear somethingelse executes when condition is false. If Python had > label and goto statements, one could write: > > label: start > if condition: > something() > modify_condition_vars() > goto: label > else: somethingelse() > > It is still clear that somethingelse executes when condition is or becomes > false. The difference is that something may be executed zero to many times > first. Also, barring an infinite loop, somethingelse is guaranteed to > execute. In today's real Python, we delete the label and goto and change > 'if' to 'while' and write the above as > > while condition: > something() > modify_condition_vars() > else: somethingelse() > > It may be less clear, but somethingelse still executes when condition is or > becomes false after zero to many executions of something (and > modify_condition_vars). Add: At this point, the else: is useless since the same would be true if it were omitted. However ... > To complicate matters, add a second goto to the pseudoPython: > > label: start > if condition: > something() > if condition2: > goto: done > modify_condition_vars() > goto: label > else: somethingelse() > label: done > > Now, somethingelse may be bypassed by the new goto. So it executes if and > when condition is or becomes false, which may or may not never happen. In > today's real Python, break is used instead for the same effect. > > while condition: > something() > if comdition2: break > modify_condition_vars() > else: somethingelse() > > In the special case of iterating through a list, where the condition is > 'there is another item in the list', this is condensed further to > > for item in list > something() > if comdition2: break > else: somethingelse() > > Again, somethingelse executes if and when the condition becomes false, > which is to say, when the list is exhausted (which maybe the reader is by > now), which process may be 'broken' by the break statement. > > Terry J. Reedy From htgk at mail.com Mon Mar 22 09:34:47 2004 From: htgk at mail.com (Moe A) Date: 22 Mar 2004 06:34:47 -0800 Subject: Thread performance Message-ID: <74dd441a.0403220634.67d0a0c9@posting.google.com> I'm writing a multi-threaded app in python that uses pygtk..and obviously the performance of subroutines invoked from a thread rather than from a GUI callback leave something to be desired. i cant implement a simple lock system because most of the threads are started from the various modules i'm using. so is there some way to commandeer the majority of processing power from one of the threads without making the gui unresponsive? From eric at zomething.com Tue Mar 16 02:34:38 2004 From: eric at zomething.com (Eric @ Zomething) Date: Mon, 15 Mar 2004 23:34:38 -0800 Subject: new to programming: suggestion Message-ID: <20040315233438.455935233.eric@zomething.com> alessandro wrote: > i'm new in programming; i'd like to find a good programming book, full > of examples guiding me step to step in the marvellous world of > programming. In terms of "books", Learning Python by Lutz and Ascher is very good. The caveat might be that in 200 pages it will expose you to more programming concepts than you might have to deal with in 500 pages of a book of a 'lesser' language; still, "Learning Python" is clear and easy to absorb. For example, I was flipping through pages 700-800 of Sams "C# Primer Plus" and did not find any concepts I wasn't familiar with after reading (sometimes skimming) "Learning Python", which is only 366 pages total including Appendices and the Index. If you want a step-by-step book with tons of examples, and do not care what language, I would suggest "Sams Teach Yourself C++ in 21 Days", 885 pages. It's quite comprehensible. Get through that, or a good portion of that, then try Python, and I'll bet my $2 you really appreciate Python. But if you're not stuck on the idea of buying a book, you might just download Python, keep IDLE open on your desktop, and go through some of the online tutorials you can find at http://www.Python.org. IDLE makes it very easy to learn by doing. Wonder if something works /this/ way? Type it in and hit return. There are great examples posted to this list every day. Have fun! From miki.tebeka at zoran.com Sun Mar 28 05:11:54 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Sun, 28 Mar 2004 13:11:54 +0300 Subject: os module question In-Reply-To: <7vt9c.49985$Bg.5493@fed1read03> References: <7vt9c.49985$Bg.5493@fed1read03> Message-ID: Hello Sean, > os.system() always seems to return all output so I don't know why that > doesn't work. The return value is the exit status. Miki From dmq at gain.com Wed Mar 24 19:22:31 2004 From: dmq at gain.com (David MacQuigg) Date: Wed, 24 Mar 2004 17:22:31 -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: <988460ht0bbbteu1ngq8sdrjm46ph8bjli@4ax.com> On Wed, 24 Mar 2004 09:48:00 +0000, Stephen Horne wrote: >On Tue, 23 Mar 2004 18:40:07 -0700, David MacQuigg >wrote: > >>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". > >RTFM doesn't really work when you don't have a keyword to look up. The extension syntax is *always* associated with a statement. The documentation on the extension is at the end of the section on that statement. >Symbols (and worse, odd combinations of symbols where it's hard to >tell which symbols are part of the same syntax rule and which are not) >that you've not seen before tend not to suggest where in the manual to >look. We need a single unique symbol, one that doesn't conflict with existing syntax, and has no special meaning itself. By using this symbol for extensions of *many* statements, we minimize the amount of new words or syntax users have to learn. >If 'as' is too generic, then what about 'decorators'. That clearly >states what follows and can easily be looked up, making the 'RTFM' >attitude justifiable. "Decorators" is clear as to its meaning, but a little too long, especially if it causes statments with multiple decorators to run over one line. It also limits the syntax to this one statement. You would not want to extend the syntax of a print statement, for example, with decorators=(separator = ' ', terminator = '\n'). >OTOH, there is the 'def' keyword for people to look up already in this >case. Exactly. All the syntax has to say is "This is an extension of the def statement." >>Does it make sense to have a general symbol for modifications of the >>simple standard syntax? > >Not really. What happens when there are two different ways of >modifying the same syntax? When the first one was defined with no >awareness that another kind of modification might be needed later? I guess I'll need an example here. Seems like the potential for future incompatibilities is *greater* if the syntax itself has "special meaning" ( e.g. "decorators" instead of [] ). >My opinion is that it is better to try to avoid symbols and >over-generic keywords, and to try to be more explicit about what the >modification actually is (in this case, decorators). Particularly >where the syntax may be infrequently used. > >Of course short is sweet too. Easy answers are very rare. I would favor short in the case of decorating def statements. Even if we use syntax unique to this statement (e.g. [] ) it seems pretty clear this is a modification of a normal def. The symantic burden is carried by the decorator names, which can be as explicit as you like. Also, I think in programs where the syntax is useful, it will be used a lot, so ease of typing and readability is an issue. We just need to avoid the Perl problem. We can do that by not using different symbols for extending different statements. -- Dave From noah at noah.org Fri Mar 19 21:06:11 2004 From: noah at noah.org (Noah) Date: 19 Mar 2004 18:06:11 -0800 Subject: Getting both PID and output from a command References: <3cc4824d.0403190259.1e06a578@posting.google.com> Message-ID: hugh at brokenpipefilms.com (Hugh Macdonald) wrote in message news:<3cc4824d.0403190259.1e06a578 at posting.google.com>... > I'm calling a command from within a python script and I need to be > able to both catch the output (stdout and stderr) from it and also > have the PID (so that I can kill it) > > I can do one or other of these, but I can't find any way to do them > both at the same time. > > So far, I've got the following options: > > > To get the output from the command: > > >>> fdin, fdout, fderr = os.popen3(command) > > > Or to get the PID so that I can kill it: > > >>> pid = os.spawnvp(os.P_NOWAIT, command.split()[0], command.split()) > > > I've tried doing the following to grab stderr (I only need stderr, not > stdout in this case) > > >>> fderr = os.pipe() > >>> sys.stderr = fderr > >>> pid = os.spawnvp(os.P_NOWAIT, command.split()[0], command.split()) > > But this doesn't seem to help.... It still just outputs stderr to the > terminal and when I try to do fderr.read(1) I don't get anything... > > Any help would be very welcome > > > Hugh Macdonald Hi, The Pexpect library lets you run external commands. You get output from a command and you can get the pid. http://pexpect.sourceforge.net/ You should be able to write code like this: import pexpect child = pexpect.spawn (command.split()[0], command.split()) print child.pid try: print child.read() except pexpect.TIMEOUT: child.kill (9) One problem is that the stdout and stderr are merged into a single stream. This is a limitation of the Python pty library. Oops... You will still be able to read the error, but you can't read it separately from stdout. Note, I wouldn't trust using a pipe. You will not see any data on the pipe until the child decides to flush the pipe. There is no way to force the child to flush it's stdout (your stdin from your point of view). Pipes are bad for working with child apps that use the stdio libary. You need a pty for that. Yours, Noah From dlissett0 at yahoo.com Mon Mar 29 17:46:47 2004 From: dlissett0 at yahoo.com (Duncan Lissett) Date: 29 Mar 2004 14:46:47 -0800 Subject: Richards bench benchmark Message-ID: <6748553f.0403291446.27fb7b93@posting.google.com> Is there a Python implementation of Martin Richards benchmark Bench? Be interesting to add it to these www.lissett.com/ben/exp/bench1.htm From jcarlson at nospam.uci.edu Thu Mar 18 16:34:42 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Thu, 18 Mar 2004 13:34:42 -0800 Subject: loop scope In-Reply-To: References: Message-ID: > 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 Ick. Thank god Python doesn't seem to be heading in this direction. - Josiah From jsbenson at bensonsystems.com Fri Mar 12 00:04:57 2004 From: jsbenson at bensonsystems.com (John Benson) Date: Thu, 11 Mar 2004 21:04:57 -0800 Subject: More glossary items: a correction Message-ID: <083d01c407ef$90e23ae0$210110ac@jsbwxp3> Actual etymology of "the calculus": Long before the advent of the differential and integral calculus, there was the renal calculus, known to moderns as the humble kidney stone. Ever since Newton and Leibnitz, passing advanced mathematics has been considered as hard as passing kidney stones, and much beer has been spilled in the attempt to make both go more easily. As Latin was the lingua franca* of science until the 1800's, it was natural for the gouty and kidney-stone-plagued privileged classes attending college to refer to the agony of higher mathematics first as a renal calculus, and later as "the" calculus. As for the argument that the ancient Romans did arithmetic with stones, lining them up to make I's, V's, X's and so on, I find it somewhat contrived and much less satisfying than my theory: it's mine, and I own it. * Latin for "language of the hot dogs" or "expert's language" From donn at u.washington.edu Fri Mar 26 17:50:11 2004 From: donn at u.washington.edu (Donn Cave) Date: Fri, 26 Mar 2004 14:50:11 -0800 Subject: Fork+Timeout References: Message-ID: In article , "Oliver Kurz" wrote: > do someone new how I can do the following? > > I call a method which reads from a socket. So ... this method could hang > forever and so my call hangs too ... > > So ... I can not change the behavior of this Method, so I have to change my > call. > > I though by forking the call to this function and set a timeout to this > call, so my program won't hang forever. > > But I don't know how I should do this and if this is the correct/best way to > do this. You might be able to get something like that to work. If you want to give it a try, I would start by learning to use signal.alarm(), and then see if its SIGALRM signal will interrupts a socket recv() on your platform. You won't need fork, I don't think. You can probably do better, though, if you can get at the socket. My favorite way to approach this kind of situation is to wait for I/O on all relevant devices with select.select(). When select says your method's socket is readable, you can call the method, and it will return right away. You can probably do better, though. I like select.select(), which waits for I/O on any of a collection of devices. That will tell you when it's safe to call your method. It will work only if 1) you have access to the socket object, 2) the method doesn't use fileobject I/O on the socket (because its buffering confuses the issue), and 3) the other inputs to your program work with select. (Oh, and if you're on UNIX.) If it's an X11 graphical application, you'll want to use the external I/O dispatching mechanism provided by your X toolkit instead. Donn Cave, donn at u.washington.edu From cbearden at hal-pc.org Wed Mar 3 18:28:33 2004 From: cbearden at hal-pc.org (Chuck Bearden) Date: 03 Mar 2004 23:28:33 GMT Subject: Unicode & mx.ODBC module Message-ID: <40466a21$0$7052$a726171b@news.hal-pc.org> I'm having a tough time understanding how to manage Unicode when loading data into an MS SQL server. I'm still pretty new to Unicode, but I think I have a grasp of the basic concepts. I'm running ActivePython 2.3.2 Build 230 on Windows XP. I have the Egenix mx.ODBC package version 2.0.1 (thanks, Marc-Andre). I have a script that is loading the contents of selected HTML files into a database, along with information identifying the file. Here is a sample script: -------------------------begin snippet------------------------- import sys import mx.ODBC.Windows #-- initialize the db connection dbname = 'theDb' uname = 'theUser' password = 'thePassword' dsn = "DSN=%s;UID=%s;PWD=%s" % (dbname, uname, password) con = mx.ODBC.Windows.DriverConnect(dsn) #-- handle UTF-8 encoded Unicode; this worked when loading XML files con.encoding = 'utf-8' con.stringformat = mx.ODBC.Windows.UNICODE_STRINGFORMAT cur = con.cursor() #-- get the contents of our file (crudely: filename is 2nd arg) html_f = open(sys.argv[1], 'r') htmldata = html_f.read() html_f.close() #-- make statement string and insert values tuple, and execute stmnt = """ INSERT INTO pmLinkHTML (PMID, Ord, HTML, HTMLlen) VALUES (?, ?, ?, ?) """ val_t = (549, 0, htmldata, len(htmldata)) cur.execute(stmnt, val_t) cur.close() con.close() --------------------------end snippet-------------------------- For my pains I am rewarded with: Traceback (most recent call last): File "./unitest.py", line 27, in ? cur.execute(stmnt, val_t) UnicodeDecodeError: 'utf8' codec can't decode byte 0xbe in position 45662: unexpected code byte Byte 45662 of the HTML file is indeed "\xBE". I don't think that should be a problem. What am I doing wrong? I have spent a fair bit of time googling the ng in various ways, and consulting Python in a Nutshell and the online standard library docs at python.org. It may be something quite obvious to a better-informed coder, but I am prepared to learn. Many thanks in advance. Chuck Bearden From jcarlson at nospam.uci.edu Fri Mar 12 11:19:53 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Fri, 12 Mar 2004 08:19:53 -0800 Subject: OFF-TOPIC:: Why Lisp is not my favorite programming language In-Reply-To: <4051936c$0$2136$afc38c87@news.easynet.co.uk> References: <165b3efa.0403030443.4d591f04@posting.google.com> <404675da@news.tce.com> <1sw3c.20562$rD5.1087@twister.socal.rr.com> <40515E92.3080201@nospam.uci.edu> <405185f5$0$16368$afc38c87@news.easynet.co.uk> <4051936c$0$2136$afc38c87@news.easynet.co.uk> Message-ID: > I take it her name isn't Josiah Jr? *laugh* god I hope not. I would have had to father her by the time I was 10. That would be a seriously funny surprise to my wife and parents, "um guys, I just found out that back when I was 10, I gave a girl my cooties." In all seriousness though, I think that kids should learn some Assembly, if only because it gets to be fun to reorganize cycle by cycle execution. Maybe not at 13, but at least 2nd year of undergraduate CS education. - Josiah From maxm at mxm.dk Fri Mar 19 02:27:20 2004 From: maxm at mxm.dk (Max M) Date: Fri, 19 Mar 2004 08:27:20 +0100 Subject: cgi lib question In-Reply-To: References: Message-ID: <405AA0D8.3070302@mxm.dk> Gandalf wrote: > > 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: You can use this module, which make it easy: http://www.mxm.dk/products/public/iisUtils regards Max M From dmq at gain.com Sat Mar 27 10:56:57 2004 From: dmq at gain.com (David MacQuigg) Date: Sat, 27 Mar 2004 08:56:57 -0700 Subject: A 'Python like' language References: <40645d8f$0$10775$afc38c87@news.easynet.co.uk> <95aa1afa.0403262049.4b2a6f78@posting.google.com> Message-ID: On 26 Mar 2004 20:49:00 -0800, michele.simionato at poste.it (Michele Simionato) wrote: >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 ;-) I almost had the same reaction when I first read this, but I did continue reading, and I'm glad. I remember making the same mistake when I first read about Python using whitespace to control structure. "Oh no, not another FORTRAN.", and I didn't look again for 3 months. This is a small problem with a simple solution (see my earlier post), and one that will retain the advantages of tabs. -- Dave From curzio.basso at unibas.ch Thu Mar 4 11:22:16 2004 From: curzio.basso at unibas.ch (Curzio Basso) Date: Thu, 04 Mar 2004 17:22:16 +0100 Subject: [Numeric] why is Float32 incorrect for ufuncs? Message-ID: <404757b9$1@maser.urz.unibas.ch> Hello everyone, I am a beginner with Numerical Python, and there is a thing I do not understand in the behaviour of the ufuncs. Maybe someone can enlighten me. Why is the following not working? >>> import Numeric >>> a=Numeric.ones((2,2),Numeric.Float32) >>> a array([[ 1., 1.], [ 1., 1.]],'f') >>> a/=2 Traceback (most recent call last): File "", line 1, in ? TypeError: return array has incorrect type If I use Numeric.Float64 as typecode everything works fine, but I do not understand why is this needed. thanks for your help. curzio. From no at sp.am Tue Mar 16 13:25:52 2004 From: no at sp.am (DH) Date: Tue, 16 Mar 2004 12:25:52 -0600 Subject: embedding opengl in wxpython window [Re: Advice needed: large In-Reply-To: References: <5eb8fb88.0403151925.4f63842b@posting.google.com> Message-ID: >> Yeah, it doesn't work on Windows for me either with python 2.3. It >> used to work with python 2.2. Now it complains about not finding glut. > > > If you encounter a bug like this, please submit a bug-report to the > project so that it can be fixed. As a quick check though, you did > install the GLUT binary package in your system32 directory, right? > PyOpenGL doesn't include the GLUT library itself, only a binding for it. I never installed OpenGL or GLUT. OpenGL comes with Windows. In python 2.2 everything worked fine. Does the python 2.3 version not weak link glut or something? From ywantmore at hotmail.com Tue Mar 16 06:51:39 2004 From: ywantmore at hotmail.com (free free) Date: Tue, 16 Mar 2004 11:51:39 +0000 Subject: Send commads to printer Message-ID: Hi, i'am writing a python program and now i need to print some stuff. Before print i want to set the text to condensed text and to italic, so i have to send some esc commads to printer. my code pp=open("/dev/lpr","w") pp.write(chr(27)+chr(15)) pp.write("This should be condensed\n") pp.write(chr(27)+chr(52)) pp.write("This should be italic too\n\f") pp.close() what i get is text in normal font. I think chr(27) does not send the ESC char to printer. Does anyone knows who to do this ?????????' Thanks in advance for your help _________________________________________________________________ Fast. Reliable. Get MSN 9 Dial-up - 3 months for the price of 1! (Limited-time Offer) http://click.atdmt.com/AVE/go/onm00200361ave/direct/01/ From mark at prothon.org Mon Mar 29 04:19:47 2004 From: mark at prothon.org (Mark Hahn) Date: Mon, 29 Mar 2004 01:19:47 -0800 Subject: A 'Python like' language References: <40645d8f$0$10775$afc38c87@news.easynet.co.uk> <1068up4kn49778@news.supernews.com> <4064C129.1B8C937C@alcyone.com> Message-ID: > Not quite the same, as with Prothon it looks like it always relates to > the self object, whereas in a `with' clause you can make it relates to > any object you wish. Just to confuse the issue, I'd like to point out that in Prothon, the leading dot does always relate to the self object, but the 'with' clause sets the self object to any object you want at any time. So both statements above are true at once. The concept of changing the self object on the fly is somewhat bizzare, much like changing the protoype on the fly, which you can also do. Mark Hahn (Prothon Author) "Erik Max Francis" wrote in message news:4064C129.1B8C937C at alcyone.com... > Valentino Volonghi aka Dialtone wrote: > > > Anyway GvR just posted on the python-dev saying this: > > > > == > > No, I want to reserve the leading dot for attribute assignment to a > > special object specified by a 'with' statement, e.g. > > > > with self: > > .foo = [1, 2, 3] > > .bar(4, .foo) > > == > > > > So another feature of this prothon (and a major one) is going to be a > > python one > > too. > > Not quite the same, as with Prothon it looks like it always relates to > the self object, whereas in a `with' clause you can make it relates to > any object you wish. > > -- > __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ > / \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE > \__/ Drifting from woman-who-tries misconstrued / Shifting to > woman-wise -- Lamya From theller at python.net Tue Mar 30 14:47:03 2004 From: theller at python.net (Thomas Heller) Date: Tue, 30 Mar 2004 21:47:03 +0200 Subject: doctest Message-ID: <1xnace2w.fsf@python.net> I've just read the 'Automating testing with doctest' pycon paper, and I'm exited about the future of doctest. This simple script reads the ctypes docs written in StructuredText, and runs and tests the code examples in it: """ import doctest ex = doctest._extract_examples(file("tutorial.stx").read()) doctest._run_examples(ex, {}, 0, "tutorial.stx", 0, 0) """ Do I understand correctly that the doctest-pretty printer will eventually remove the remaining 'warts', ie that doctest complains about the address part in this? And is it already available somewhere? >>> class X(object): pass ... >>> x = X() >>> x >>> <__main__.X object at 0x008FA3F0> Thomas From news at woody.datatailors.com Sun Mar 21 14:38:01 2004 From: news at woody.datatailors.com (Peter van Kampen) Date: Sun, 21 Mar 2004 20:38:01 +0100 Subject: Accessing MS-Access DB from Linux References: Message-ID: In article , Gustavo Rahal wrote: > Hi > > How can I access a MS-Access DB from a linux machine? I am doing a > website that will be hosted on Linux and has to access a Windows > machine with the MS-Access DB. See: http://groups.google.com/groups?hl=en&q=python+ms+access+linux http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&th=d9959a0a2901877a Hth, PterK -- Peter van Kampen pterk -- at -- datatailors.com From mariube+netnews+ at ifi.uio.no Tue Mar 30 15:12:41 2004 From: mariube+netnews+ at ifi.uio.no (Marius Bernklev) Date: Tue, 30 Mar 2004 22:12:41 +0200 Subject: Equality and identity In-Reply-To: (David M. Cooke's message of "Tue, 30 Mar 2004 15:03:28 -0500") References: <3cfvfkmi337.fsf@nelja.ifi.uio.no> Message-ID: <3cf1xnagkli.fsf@nelja.ifi.uio.no> cookedm+news at physics.mcmaster.ca (David M. Cooke) writes: > In your example, 5 and "hei", for various reasons, are compiled to > reference the exact same object, so 'is' returns True. However, no > such caching is done with tuples, so (5,2) and (5,2) compile to > references to different objects (whose contents are equal). Thanks! Marius -- "Who needs crypto WYCWLT?" -- William Newman From joe at notcharles.ca Wed Mar 31 12:31:46 2004 From: joe at notcharles.ca (Joe Mason) Date: Wed, 31 Mar 2004 17:31:46 GMT Subject: Looking for example of brilliant python code showing off its features References: Message-ID: In article , j_mckitrick wrote: > I'd like pointed to an example of some python code that just really > shows off what it can do. I'd rather it focus on language features > than just library functions, but anything is really OK. > > So does anyone have or know of any amazing python code I can check > out? Check the Python Cookbook (google should find it). Joe From studyhall at reynolddemarcojr.com Wed Mar 24 12:40:11 2004 From: studyhall at reynolddemarcojr.com (study_hall) Date: 24 Mar 2004 09:40:11 -0800 Subject: study_hall Message-ID: <9141e943.0403240940.3ea62574@posting.google.com> Computer Science majors Students helping Students join study_hall http://groups.yahoo.com/group/study_hall/ From randall at tnr.cc Wed Mar 17 18:28:41 2004 From: randall at tnr.cc (Randall Smith) Date: Wed, 17 Mar 2004 23:28:41 GMT Subject: how best to iterate i times ? In-Reply-To: References: Message-ID: Thank you all. You were all very helpful. Randall Mike Rovner wrote: > Randall Smith wrote: > >>for i in range(100000): >>dothis() >> >>I like how clean this syntax is, but this method is very wasteful. >>The list created by range(100000) consumes a fair amount of memory >>and it is only used to iterate. > > ... > >>So, question is: What is the efficient, elegant, pythonic way to >>iterate with integers? > > > Solely for that purpose 'xrange' was created: > > for i in xrange(100000): > dothis() > > HTH, > Mike > > > > > > From fma at doe.carleton.ca Sat Mar 27 08:09:46 2004 From: fma at doe.carleton.ca (Fred Ma) Date: 27 Mar 2004 13:09:46 GMT Subject: Choosing Perl/Python for my particular niche References: <40652B0D.7C313F77@doe.carleton.ca> Message-ID: <40657D14.3FBE7E82@doe.carleton.ca> Cameron Laird wrote: > > Where to begin? I'm seriously surprised that you haven't > mentioned Tcl, originally created to serve CAD needs, and > still more prevalent than either Perl or Python in CAD, I was under the impression (rightly or wrongly) that Tcl was good at interfacing to, and controlling, CAD tools. I was more motivated by the need to massage data, though they probably overlap greatly. My experience with Tcl is limited to using Synopsys DC shell to do unconventional things, like traverse my design hierarchy (originally in verilog) flattening and stripping out things. At the time, the documentation for their dcshell was more complete than for their Tcl version of the same. But it's good to know that Tcl is an option to Perl and Python, at least for some things. > from all I know. Perl is indeed present, too, although, > in some ways, PythonCAD > is the most interesting action in this domain. All three > languages have enough to recommend them, and are close > enough in their capabilities, that I feel comfortable ad- > vising you to choose the one that suits *you* best. If > you like thinking in Perl, choose that; you'll miss out > on a few Python capabilities, but you'll be as productive > as with any other choice. Good to know that at a personal level, I can run faster with whichever one I feel more comfortable with (though I have yet to explore Python for personal comfort). I was also trying to take into consideration the prevalence of Perl in digital design. Along this line, I should clarify that by CAD, I don't mean general purpose computer aided drawing. I mean software that helps designers in digital design, much of which is not graphical. In fact, my area is more combinatoric optimization and graph theory-ish than drawing. Sometimes, I forget that CAD has a much more general meaning than this. > Either Perl or Python is going to satisfy you for algorithmic > experiments much, MUCH more than Matlab or C++. Make the > switch, *now*. I'm surprised to hear that. Perhaps it's related to the confusion above (due to the initial generality of my description). My thesis research deals with evolutionary algorithms (EAs) for programming coarse grain reconfigurable logic platforms. They tend to be heavy on computation, and I migrated to C++ for the speedup compared to matlab. Matlab has been made fast for highly vectorizable computation, but the restrictive conditions for such speedup was, too restrictive. I saw some examples of genetic algorithms in Perl (or perhaps it was Python), but assumed (maybe prematurely) that it was much slower than C++. Other factors also contributed to this impression, including the fact that I augment the evolutionary search with local searh heuristics, giving rise to complicated control flow in the code. So I've used C++ for the computation engine code, and shell/data-massaging scripts for "glue" activity. Matlab I'm using because I've got alot of familiarity invested in its graphing capabilities (to assess data rather than drawing). I'm also pretty familiar with its compact vectorized operations, which helps for data massaging in the post-processing phase. > Either Perl or Python can adequately substitute for shell > in the uses you describe. They pipeline fine themselves; > 'fact, I'm working on an essay on how they're *better* at > pipelining. Actually, I was thinking more along the lines of pipelining Perl commands in a bash command pipeline, along with other commands. But it's good to know that they pipeline within their own scripts (if I understand you correctly), and for general shell scripting. > "The translater is freeware, so has limitations ...": I > don't understand how to read this. Has it been your > experience that commercial CAD packages are perfect, and > without limitations? The man page for "verilator" says this: "many limitations and lack of features compared to a commercial simulator". One of the things that prompted me to ask about Perl/Python is because I'm looking at making many changes throughout a number of files in order to accommodate the limitations. Regardless of limitations carried by commercial tools, these are the ones that I have to deal with. > I work with VNC a lot, too. You seem to believe that > there's a special relation between VNC and Perl; do I > have that right? That surprises me. If anything, I'd > say Tcl leads in that domain http://www-106.ibm.com/developerworks/linux/library/l-vnc/ >. I described my experience with VNC just as an example of the various situation in which I had to make sense of Perl scripts. The vncserver script is written in Perl, at least for TightVNC, and for older versions of RealVNC I seem to recall. That's the extent to which I delved into VNC, since my area of study (and thus the area where I spend most of my time) is in "CAD" algorithms, as described above. I was driven more by a need to expediently get a certain kind/level of functionality from VNC rather than the intention of developing it. > I generally favor Python over Perl; in the absence of > more details, I think there's mild evidence that those > who don't specialize in programming are happier over the > long term with the readability of the former. They're > very close, though. The one most certain advantage > Python boasts is a dimension that I'd think important > to you, although you haven't mentioned it: Python's > interfaces to C++ are MUCH easier to manage than Perl's. > Perl6 will change this. For now, though, it's FAR > easier to practice "dual-level programming" with Python > and C++. If you have a large existing library of C++ > work, I think that tips the balance toward Python. > Understand, SWIG and other alternatives make Perl-to-C++ > links possible; with Python's facilities, though, > including Pyrex, they're *fun*. That's good news, from my standpoint. I don't know what level of programming qualifies a person to be "specializing in programming", thus leading to more satisfaction with Python. I've tried to read my own C++ code after half a year, and have gained a new appreciation for the importance of readability. So I'm still fine-tuning my idea of adequate commenting. Since I'm working on my thesis rather than commercial code, I don't have large amounts of generic C++ library code. Just a big-ish heap of routines/functions for the problem that I'm investigating, as the algorithms that I choose to try morph. My impression is that you think Python would be more appropriate for my situation. Just wondering if you can comment on the merit of having lots of Perl code around. It seems to be prevelant in a digital design tool environment. It may not matter all that much to me right now, but it would be nice to be on the same wavelength as others if I find myself in a team situation. As I mentioned, there have already been situations where a nodding familiarity with Perl has helped in making use of other people's tools. > There's more to say; I'll be back later. Thanks for your comments, and looking forward to hear any further comments. Fred -- Fred Ma Dept. of Electronics, Carleton University 1125 Colonel By Drive, Ottawa, Ontario Canada, K1S 5B6 From newsgroups at jhrothjr.com Wed Mar 10 08:04:22 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Wed, 10 Mar 2004 08:04:22 -0500 Subject: PEP 328: Imports: Multi-Line and Absolute/Relative References: <104q64b2uf3nl0b@news.supernews.com> Message-ID: <104u4ktn5hoc9db@news.supernews.com> "Aahz" wrote in message news:c2mrrq$1k7$1 at panix1.panix.com... > In article <104q64b2uf3nl0b at news.supernews.com>, > John Roth wrote: > > > >I think this is a serious conceptual issue, and I'd prefer to not > >support upwards references at all. That doesn't mean they should be > >prohibited, but if someone wants to dig a pit for himself with circular > >coupling across module hierarchies, then he should be required to > >wield the shovel himself. It is not, after all, that difficult to > >sort through sys.modules to figure out where you are in the import > >hierarchy. > > While that makes some sense, what about "uncle" references within the > current package? I'm not sure what you mean by "Uncle." The term usually means "parent's brother" or "some son of your grandparents other than your father" so I'd assume it would go up one directory and then sideways, which would require going up another directory. If you are refering to another module in the same directory that this one came from, then I'd code that as: import *.foo However, possibly you meant "cousin?" I can see a use case for that as a packaging convenience. To make this concrete, let's assume we have a package named "A" with subpackages named "B" and "C". If B contains module "B1", then we might want to be able to refer to module C1 in package C from module B1 in package B as if it was originally on the pythonpath. If B and C are both on the pythonpath, then you need to say: import C.C1 However, if they aren't, then you would have to say something like: import ^.C.C1 > > >That leaves references to the current package. I'm going to suggest an > >"*" as an indicator for "this package." The reason for an asterisk is > >my background in mainframe assembler: it means "here" in that language, > >so I'm obviously not particularly attached to it. It's also already in > >use in the "from foo import *" syntax. > > > >A reference beginning in the current directory is thus: > > > >import *.spam.eggs > > That's functionally equivalent to the suggested > > import .spam.eggs Certainly. An * is easier to see on the screen. I believe that was one of the issues with the single dot notation. John Roth > -- > 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 premshree_python at yahoo.co.in Mon Mar 1 15:31:34 2004 From: premshree_python at yahoo.co.in (=?iso-8859-1?q?Premshree=20Pillai?=) Date: Mon, 1 Mar 2004 20:31:34 +0000 (GMT) Subject: makeExe.py: An explanation for the uninitiated Message-ID: <20040301203134.94546.qmail@web8307.mail.in.yahoo.com> Hey, For the uninitiated: an explanation of makeExe.py (http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/266471), in the form of an article, ?Create Python Executables Automatically?, is available at DevX: http://www.devx.com/opensource/Article/20247 -Premshree Pillai [http://www.qiksearch.com/] ===== -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 antonyliu2002 at yahoo.com Tue Mar 9 22:08:31 2004 From: antonyliu2002 at yahoo.com (Anthony Liu) Date: Tue, 9 Mar 2004 19:08:31 -0800 (PST) Subject: [python-chinese] Linux上 # -*- coding: cp936 -*- 出 错 In-Reply-To: <000001c4064a$c5e7dcf0$d9824094@localnet> Message-ID: <20040310030831.81293.qmail@web13007.mail.yahoo.com> Thank you! John. Yes, gbk encoding works on the Win2K system, just as cp936 does. But if I run the same code on the Mandrake, the system says that gbk is an unknown encoding. The same happens to cp936. I did a 'locate cjk' on the Mandrake system and get: [antony at ocho antony]$ locate cjk /usr/share/doc/bind-9.2.3/draft/draft-ietf-idn-cjk-01.txt /usr/share/ghostscript/7.07/examples/cjk /usr/share/ghostscript/7.07/examples/cjk/all_ac1.ps /usr/share/ghostscript/7.07/examples/cjk/all_ag1.ps /usr/share/ghostscript/7.07/examples/cjk/all_aj1.ps /usr/share/ghostscript/7.07/examples/cjk/all_aj2.ps /usr/share/ghostscript/7.07/examples/cjk/all_ak1.ps /usr/share/ghostscript/7.07/examples/cjk/gscjk_ac.ps /usr/share/ghostscript/7.07/examples/cjk/gscjk_ag.ps /usr/share/ghostscript/7.07/examples/cjk/gscjk_aj.ps /usr/share/ghostscript/7.07/examples/cjk/gscjk_ak.ps /usr/share/ghostscript/7.07/examples/cjk/iso2022.ps /usr/share/texmf/doc/help/Catalogue/entries/cjk-fonts.html /usr/share/texmf/doc/help/Catalogue/entries/cjk.html /usr/share/i18n/locales/translit_cjk_variants /usr/share/i18n/locales/translit_cjk_compat /usr/lib/cups/filter/cjktexttops /usr/X11R6/bin/rxvt.cjk --- John Li wrote: > 1) I converted your email--it looks like > it had an ascii encoding, not a gb encoding. > > 2) On your system, does locale.getdefaultlocale()[1] > return ISO8859-1 or cp936, after > '# -*- coding: cp936 -*-'? > You can simply use unicode('中华人民共和国','gbk') > (cp936 is more of a Microsoft name; 'gbk' is > more common elsewhere) > > 3) You have to install CJKCodecs from > http://cjkpython.i18n.org/ before the unicode() > and encode() functions work with gbk/cp936. > > --------------------------------- > > 我在我的Win2K上运行如下的代码没有问题。 > > # -*- coding: cp936 -*- > import locale > encoding = locale.getdefaultlocale()[1] > s1 = > unicode('中华人民共和国', > encoding) > s2 = > '中华人民共和国' > print s1.encode(encoding), s2 > print len(s1), len(s2) # 输出:7 14 > > 代码是从楼上某位仁兄提供的链接上得到的。 > > 但是,我如果在实验室的Mandrake > linux上运行这一段程序,就得到如下的错误: > > SyntaxError: 'unknown encoding: cp936' > > 是不是因为这个mandrake上没有中文系统? > 我不是超级管理员,我要让超级用户安装什么东西呢? > > Mandrake上的locale如下: > > >>> locale.getdefaultlocale() > ['en_US', 'ISO8859-1'] > > _______________________________________________ > python-chinese list > python-chinese at lists.python.cn > http://python.cn/mailman/listinfo/python-chinese > __________________________________ Do you Yahoo!? Yahoo! Search - Find what you?re looking for faster http://search.yahoo.com From jcarlson at nospam.uci.edu Fri Mar 19 20:08:19 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Fri, 19 Mar 2004 17:08:19 -0800 Subject: Package name with '.' in them: Python Bug ? In-Reply-To: References: Message-ID: > 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 Considering that you have shown that it does not work, and that there is documentation stating that it is not /meant/ to work, then the error is in the way /you/ name /your/ modules, not the way Python handles /incorrectly/ named modules. - Josiah From cookedm+news at physics.mcmaster.ca Thu Mar 11 16:26:18 2004 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Thu, 11 Mar 2004 16:26:18 -0500 Subject: Extending Python Syntax with @ References: <104vtblamboehab@corp.supernews.com> <2f9050pq22u53o7aqo9i8ebqj11vo9kilg@4ax.com> <1050odofl644aac@corp.supernews.com> Message-ID: At some point, Kyler Laird wrote: > Richie Hindle writes: >>[Cameron] >>> Whenever you feel like a lambda, define a named function; >>[Kyler] >>> How do you cleanly do that? >>> foo = range(-10, 10) >>> my_op = lambda x: float(x) / max(map(abs, foo)) >>> bar = map(my_op, foo) > >>foo = range(-10, 10) >>def my_op(x): >> return float(x) / max(map(abs, foo)) >>bar = map(my_op, foo) > >>...did I misunderstand? > > Well, your solution depends on a global variable. That's going to > get *really* ugly if we move beyond the trivial example given here. > There are other problems but they're apparently not obvious with > that example. The lambda depends on a global variable too (or at least, a variable up one scope). > How 'bout some non-working code to shine some more light on it? (If > pressed, I should be able to come up with similar code that works!) > > 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, ... > return( > lambda x, y: ( > x * A + y * B + > x * y * C + > ..., > x * G + y * H + > x * y * I + > ... > ) > ) > elif ... # Repeat lots of times for variations. > > map_im = foo.open('map.tif') > map_translation = make_translation_function(map_im.get_GCPs, type='LSF') > > path_im = foo.open('path.tif') > path_translation_i = make_translation_function(path_im.get_GCPs, type='LSF', invert=True) > > # Mark all points on map that are red in path. > for (x, y) in all_red_pixels(path_im): > (lon, lat) = path_translation_i(x, y) > (x, y) = map_translation(lon, lat) > map_im.putpixel((x, y), mark_val) > > Now, let's pretend that this is part of a larger program that's doing lots > of things with, potentially, lots of images, and let's also say that we > allow user-defined/imported extensions to make_translation_function(). > How are you going to make a *clean* solution using named functions? Umm, easily? You don't have to refer to functions by their original name; they are first-class objects. 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 elif ... # Repeat lots of times for variations. I've even optimized by premultiplying x and y, which couldn't do in the lambda, and made the code clearer by breaking up the calculation. -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From lbates at swamisoft.com Mon Mar 15 18:09:04 2004 From: lbates at swamisoft.com (Larry Bates) Date: Mon, 15 Mar 2004 17:09:04 -0600 Subject: Embedded WebDesign with Python References: Message-ID: Before you spend too much time you should take a look at www.zope.org. Larry Bates "Ivo" wrote in message news:mailman.21.1079267258.745.python-list at python.org... > Maybee you python junkies can help me. > > My Goal: > A website where the content is fully shaped by python in my html. > > At this moment I use Apache 2 in combination with mod_python and Spyce > > No I understand that mod_python allows embedded python, but I don't > understand how. Can someone give me a pointer or a good link to some good > pointers (which would already be a good pointer ;-) > > Thanks, > Ivo. > > From dmq at gain.com Sun Mar 28 12:14:32 2004 From: dmq at gain.com (David MacQuigg) Date: Sun, 28 Mar 2004 10:14:32 -0700 Subject: Prothon Prototypes vs Python Classes References: <569c605ld1cj8fc1emolk08ete0s1prls1@4ax.com><106cc1f2rsnaoe2@news.supernews.com><406635AB.9050803@mlug.missouri.edu><106ceeeqc8ph126@news.supernews.com> <106dukh7ncf9ad4@news.supernews.com> Message-ID: On Sun, 28 Mar 2004 11:15:34 -0500, "John Roth" wrote: > >"Paul Prescod" wrote in message >news:mailman.10.1080485351.20120.python-list at python.org... >> John Roth wrote: >> >> > It's certainly true that in a prototype based language all objects >> > exist: there are no objects that the compiler deals with but does >> > not put into the resulting program. And it's quite true that it does >> > open up the floodgates for a lot of messiness. >> >> Ummm. This is also true for Python. Python classes exist at runtime. >> >> foo = 5 >> >> class foo: # oops. I've overwritten foo >> def bar(self): >> pass >> >> print foo >> print dir(foo) >> print type(foo) >> >> Paul Prescod > >Sure. But misusing classes as instances is quite rare in >practice, and plugging members into instances is also >quite rare in practice. Python's highly dynamic nature >opens it up to a lot of difficulty in principle, but most >deveopers seem to be quite disciplined in their use of >dynamism. > >The difficulty here is simply that there is no way of >isolating a base object that is supposed to be the platform >for other objects from objects that are supposed to be >updatable with new behavior. > >The higher a tower you want to build, the firmer the >foundation. Conventions help, but if the conventions >are helped along by the language, that's even better. In Ruby you can freeze() any object. But it seems like in this case, just giving your base object a distinct name, like PrototypePolygon will remind you not to change its definition later as you create triangles, rectangles, etc. I also would have no objection to some syntactic lock, like any object name ending in an underscore is an immutable object. We could also do this the other way around. Objects, by default are immutable. That would take care of most uses. If you want a mutable object, give it a name ending in ! (bang). -- Dave From leoel at gmx.at Thu Mar 11 09:41:30 2004 From: leoel at gmx.at (Leopold Schwinger) Date: Thu, 11 Mar 2004 15:41:30 +0100 Subject: Python database In-Reply-To: <4050647e$1@puffinus.its.uu.se> References: <4050647e$1@puffinus.its.uu.se> Message-ID: <40507a0d$1@e-post.inode.at> none wrote: > > Facts: > > (1) I don't know anything about data bases > > (2) I don't have much time to learn about them (but I do have SOME time) > > (3) I need to store (and retrieve) thousands of pages for a wiki, and > need to be able to perform simple searches in the data base (but nothing > else) > > (4) I want to have open source free of charge programs > > Can someone recommend a simple, easy-to-program data base? As far as I > have understood there is no standard data base in Python. Why is this > so? Do people have too different needs? > > / Any help is much appreciated! > If you want to make a Wiki-Page with full-text-search: ==> http://moin.sourceforge.net/ and: its based on python and Apache greetings Leo From LVC3MEDIC at LVTALK.COM Fri Mar 12 23:21:07 2004 From: LVC3MEDIC at LVTALK.COM (Frank) Date: 12 Mar 2004 20:21:07 -0800 Subject: usenet is being killed by one specific person. That person is (jeff) jbond@nowhere.com Message-ID: usenet is being killed by one specific person. That person is (jeff) jbond at nowhere.com usenet is being killed by one specific person. That person is warrant out for Alan P (alan at nowhere.com) AKA (jeff) jbond at nowhere.com The Day & Night Stalker Is Now (jeff) jbond at nowhere.com AKA Alan P (alan at nowhere.com with video and pics email me. this info. is on amw, dr.phill and Jeff BOND jbond at nowhere.com AKA Alan P (alan at nowhere.com Did you know that it's U.S. Postal Inspectors who investigate mail thefts? They get high ratings for their work, in the last year alone arresting over 6,000 theft suspects. JEFF thinks he can run and hide but jeff can't run and hide in mexico. AGE 38 HT. 5' 8" WT. 160 HR. BLK. EYS. BR. RACE W BLK. MUTS. 1. RED CAR LIC# WHT. LIC. PLT. 950PM 3-3-04 2. WHT. FORD BRON. LIKE OJ LIC. # 3-4-04 1230AM. VIDEO, PICS. W/SOUND http://tinyurl.com/27ohw From lbates at swamisoft.com Tue Mar 9 14:55:37 2004 From: lbates at swamisoft.com (Larry Bates) Date: Tue, 9 Mar 2004 13:55:37 -0600 Subject: getting size of gif References: Message-ID: <9L2dna_mgLuovNPd4p2dnA@comcast.com> Get PIL (Python Imaging Library) if you don't already have it http://www.pythonware.com/products/pil/index.htm/ import Image pathtogif=r'C:\xxx.gif' # Replace with your path im=Image.open(pathtogif) x,y=im.size im.close() -Larry "biner" wrote in message news:b82e5469.0403091126.33d0afe7 at posting.google.com... > 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 aahz at pythoncraft.com Wed Mar 31 10:19:13 2004 From: aahz at pythoncraft.com (Aahz) Date: 31 Mar 2004 10:19:13 -0500 Subject: wxPython book (was Re: Python Documentation Blows!) References: <40699A31.8000708@yahoo.com> <406a753b$0$12020$79c14f64@nan-newsreader-02.noos.net> Message-ID: In article <406a753b$0$12020$79c14f64 at nan-newsreader-02.noos.net>, francois lepoutre wrote: > >Possibly a smart (and not necessarily big) wxpython book could prove a >decisive argument for wxpython and python as well specifically for the >"MS visual *" and delphi user communities. 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. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "usenet imitates usenet" --Darkhawk From ark at acm.org Tue Mar 30 13:17:01 2004 From: ark at acm.org (Andrew Koenig) Date: Tue, 30 Mar 2004 18:17:01 GMT Subject: Why '==' ?? References: <8089854e.0403300510.1971c24@posting.google.com> Message-ID: "Fuzzyman" wrote in message news:8089854e.0403300510.1971c24 at posting.google.com... > 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 ? One reason is that you can assign multiple variables at the same time: a = b = c = 0 Would you prefer the first = to be assignment and the others to be comparison? (it's certainly possible -- PL/I does it that way -- but would you prefer it?) From devnull at example.com Wed Mar 31 21:21:28 2004 From: devnull at example.com (Derek Fountain) Date: Thu, 01 Apr 2004 10:21:28 +0800 Subject: Using bound variables in Tkinter events References: <4067a227$0$16577$5a62ac22@freenews.iinet.net.au> Message-ID: <406b7c51$0$16594$5a62ac22@freenews.iinet.net.au> > import Tkinter as tk > root = tk.Tk() > > def check(action): > print {"1":"inserting", "0": "deleting"}.get(action, "should never > happen") > return True > checkId = root.register(check) > > entry = tk.Entry(root, validate="key", validatecommand=checkId + " %d") > entry.pack() > root.mainloop() > > The above was found by trial and error, so no warranties :-) Awesome, thank you. I don't understand what's going on though. Can you explain a bit? I don't understand the mechanism which is expanding the %d. Is there some magic in the tk.Entry constructor which does it, or is that root.register() doing something clever? > You could use check() directly, like > > entry = tk.Entry(root, validate="key", validatecommand=check) > > but then it will be called without parameters. That's as far as I'd got and I was beginning to think it was impossible to get the parameters. At least I now know it can be done, even if I don't understand how! From steve at ninereeds.fsnet.co.uk Sat Mar 27 11:28:25 2004 From: steve at ninereeds.fsnet.co.uk (Stephen Horne) Date: Sat, 27 Mar 2004 16:28:25 +0000 Subject: The problem with "as" [was "Re: PEP 318"] References: <988460ht0bbbteu1ngq8sdrjm46ph8bjli@4ax.com> <1fl660532t2rffk3f7klh4g1ei9rnhi3p9@4ax.com> <6oj860t65n3lmqp3aurigkl12hb1a6lknm@4ax.com> Message-ID: On Fri, 26 Mar 2004 09:48:17 -0700, David MacQuigg wrote: >There may also be some objection to the fact that this use of >indentation (setting options) is inconsistent with every other use >(controlling program flow). I already gave my opinions on that issue elsewhere. First off, the relative consistency in how Python uses blocks is a side-effect of an unrelated principle, not a principle in itself - the 'right thing' can still be to use block structure for other things. Secondly, Python doesn't just use indented blocks purely to control program flow - it is also used to define local contexts in the sense of local scopes (class, def) so why not do the same, but with local options being the local context? >This is the best time to do it, while we are learning the >language. Later, we will forget the problems we had in learning. Actually, I've been using Python for about 7 years or so, on and off - slightly longer than I've been using C++, and it's almost certainly my record holder for the longest period of sustained more-or-less-regular use (though sadly not for quantity). I first started with Python 1.4 on an iMac, as a result of a desperate search for languages I could actually run on that thing. To the extent that I'm still learning Python, I'll probably always still be learning it ;-) -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From newsgroups at jhrothjr.com Wed Mar 24 09:41:01 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Wed, 24 Mar 2004 09:41:01 -0500 Subject: [Slightly OT] Re: Voting (was Re: PEP 318 References: <95aa1afa.0403230250.4c9da7a2@posting.google.com> <1060m0593q1uo0d@news.supernews.com> Message-ID: <10637ibo30epo6f@news.supernews.com> "Joe Mason" wrote in message news:slrnc631sn.32m.joe at gate.notcharles.ca... > In article <1060m0593q1uo0d at news.supernews.com>, John Roth wrote: > > I'd support the "Majority Rules" algorithm. See the article in > > Scientific American (March, 2004 edition) If you run the > > There's no free version of the article online, but the authors are given > as Partha Dasgupta and Eric Maskin, and googling on the latter led me to > http://www.sss.ias.edu/papers/papereleven.pdf. Thanks for the reference. A large part of the SA article is a revised version of this, with the recent French election added as another example, and with a few relatively minor changes. The section on why the Concordet Paradox is of relatively minor concern is new. Since it involves the effects of ideology and passion, it might be worth looking at from a theoretical standpoint. > I've only skimmed it, but I'm a little confused by his terms in that > paper. He first starts, it seems, by defining "plurality/majority rule" > as simply allowing everybody to cast a vote for one candidate, and "a > candidate wins if he or she garners, respectively, a plurality or > majority of all votes cast" - in other words, the obvious way. But > later on he says, "in true majority rule the winner is the candidate who > beats everyone else in a pairwise comparison", which is Condorcet's > Method. > So I'll assume the "Majority Rules" algorithm is yet another dumbed-down > name for Pairwise Voting aka Condorcet's Method, and say that I like it, > but there's not much point using it for a yes/no vote. If you're saying to > let people vote on several alternate syntaxes plus "reject outright" - > perfect. That's the way I understand it. If it's a yes/no vote on one syntax, I agree, there's not much point. My concern was not getting into another PEP 308 mess due to a poor choice of voting method. > > Cycles are, of course, a problem with that method; you just > > have to do something else to break the tie. Almost anything will > > do if you filter the ballots to just include the issues/candidates > > involved in the tie. > > There's a fair amount of analysis on the best method, actually. In this > case, "Guido's choice" is probably a good one. (Normally it's done by > counting the relative magnitude of each pairwise win and things like > that. I'm not clear on whether the existance of a cycle means everyone > in the cycle is really a tossup or if it's fuzzier.) Your comments indicate you're probably much more in touch with voting method theory than I am! My take on it is that it needs to be done using availible data - that is, the original votes. I don't know if the original data on PEP 308 is still availible. It would be interesting (although it might just be throwing fuel on a fire that should be allowed to die down) to reanalyze it (and I don't know if I'm volunteering to do it or not!) John Roth > > Joe From theller at python.net Tue Mar 9 10:03:50 2004 From: theller at python.net (Thomas Heller) Date: Tue, 09 Mar 2004 16:03:50 +0100 Subject: Using Pythonwin to poke at Windows apps? References: <44254d3d.0403090600.3b14d84c@posting.google.com> Message-ID: <4qsym59l.fsf@python.net> 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. > 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 Thomas From grey at despair.dmiyu.org Fri Mar 26 21:24:29 2004 From: grey at despair.dmiyu.org (Steve Lamb) Date: Sat, 27 Mar 2004 02:24:29 GMT Subject: A 'Python like' language References: <40645d8f$0$10775$afc38c87@news.easynet.co.uk> <1068up4kn49778@news.supernews.com> <106959g6i63cv77@news.supernews.com> Message-ID: On 2004-03-26, John Roth wrote: > "D Martin" wrote in message > news:ax%8c.9470$wg1.4018 at edtnps84... >> 3 solutions: >> 1. Use spaces instead of tabs. Hit the space bar yourself, or an editor >> that replaces tabs with spaces. >> 2. Include as a .py or text file instead of inline. >> 3. Get a different email program. > All of these fail for one simple reason. Let's hit > the chorus, guys: > "We're right, everybody else needs to change..." Hey, that's the Chorus from the Microsoft song! You're the one using Lookout! You're the one complaining about the shortfalls in your tools because Microsoft sings that song. *YOU* deal with it. -- 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 tismer at stackless.com Mon Mar 29 17:35:24 2004 From: tismer at stackless.com (Christian Tismer) Date: Tue, 30 Mar 2004 00:35:24 +0200 Subject: Orders of magnitude In-Reply-To: References: Message-ID: <4068A4AC.5040501@stackless.com> Robert Brewer wrote: > I wrote: > > 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? > > ...and got replies: And here my last one, hopefully: I changed the program to use just one file, and 10 million of about 300 bytes, each. There was one duplicate. The program identified it. The whole process took about six minutes, using a temp file with pickled bins of 300 MB, only. It will work for you, regardless of record size. :-)) have fun -- 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/ -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: unduplicator.py URL: From ptmcg at users.sourceforge.net Mon Mar 1 14:04:36 2004 From: ptmcg at users.sourceforge.net (Paul McGuire) Date: Mon, 01 Mar 2004 19:04:36 GMT Subject: Regular Expressions in Python References: Message-ID: <8PL0c.19420$lS1.16356@fe2.texas.rr.com> "fossil_blue" wrote in message news:c7c33240.0403010618.12391181 at posting.google.com... > Dear Gurus, > > I am trying to find out how to write an effective regular expression > in python for the following scenario: > > "any number of leading spaces at the beginning of a line" "follow > by a string" "there maybe a string that starts with *" > > for example: > > END *This is a comment > > but I don't want to match this: > > END e * This is a line with an error (e) > > thanks, > Noel Here's an example with sample code using both re's and pyparsing. Note that the single .ignore() call takes care of ignoring comments on all contained grammar constructs, and non-significant whitespace is implicitly ignored (so no need to litter your matching expressions with lots of opt_spaces-type content). -- Paul ======================== from pyparsing import Word, alphas, alphanums, restOfLine, LineEnd, ParseException testdata = """ END *This is a comment END*This is a comment (but the next line has no comment) END END e * This is a line with an error (e)""" enquote = lambda st : ( '"%s"' % st ) print "test with pyparsing" grammar = Word( alphas, alphanums ).setName("keyword") + LineEnd() comment = "*" + restOfLine grammar.ignore( comment ) for test in testdata.split("\n"): try: print enquote(test),"\n->", print grammar.parseString( test ) except ParseException, pe: print pe print import re print "test with re" opt_spaces = " *" #identifier = "[A-Za-z_][A-Za-z0-9_]+" - I'm guessing this regexp should have ()'s for accessing content as a group identifier = "([A-Za-z_][A-Za-z0-9_]+)" comment = "\*.*" opt_comment = "(%s)?" % comment pat = re.compile(opt_spaces + identifier + opt_spaces + opt_comment + "$") for test in testdata.split("\n"): print enquote(test),"\n->", if pat.match(test): print pat.match(test).groups() else: print "Bad text" ======================== Gives this output: test with pyparsing "" -> Expected keyword (0), (1,1) "END *This is a comment" -> ['END'] " END*This is a comment (but the next line has no comment)" -> ['END'] " END" -> ['END'] " END e * This is a line with an error (e)" -> Expected end of line (8), (1,9) test with re "" -> Bad text "END *This is a comment" -> ('END', '*This is a comment') " END*This is a comment (but the next line has no comment)" -> ('END', '*This is a comment (but the next line has no comment)') " END" -> ('END', None) " END e * This is a line with an error (e)" -> Bad text From dkuhlman at rexx.com Tue Mar 30 14:28:56 2004 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Tue, 30 Mar 2004 11:28:56 -0800 Subject: ANN: exportLiteral extension to generateDS.py Message-ID: I've implemented an extension to generateDS.py. generateDS.py generates Python classes that represent the elements in an XML document, given an Xschema definition of the XML document type. The new extension will export a Python literal representation of the XML document. What It Does ============ When generateDS.py generates the Python source code for your classes, this new feature also generates an "exportLiteral" method in each class. If you call this method on the root (top-most) object, it will write out a literal representation of your class instances as Python code. generateDS.py also generates a function at top level (parseLiteral) that parses an XML document and calls the "exportLiteral" method on the root object to write the data structure (instances of your generated classes) as a Python module that you can import to (re-)create instances of the classes that represent your XML document. Why You Might Care ================== This feature means that the classes that you generate from an XML schema support the interchangeability of XML and Python literals. This means that, given classes generated by generateDS.py for your XML document type, you can perform the following transformations: - Translate an XML document into a Python module containing a literal definition of the contents of the XML document. - Translate the literal definition of a Python data structure into an XML instance document. This capability enables you to: - Work with an XML (text) document, then exchange it for a Python text representation of the content of that document. - Work with a Python literal text representation of your XML document, then exchange that for an XML document that represents the same content. - "Freeze" your XML document as a Python module that you can import. The module can be edited with your text editor, so perhaps it would be better to say that it is frozen, but not too hard. The classes that you generate with generateDS.py can be used to: 1. Read in an XML document. 2. (Optionally) modify the Python instances that represent that XML document. 3. Write the instances out as a Python module that you can later import. Where to Find It ================ You can find generateDS.py at: http://www.rexx.com/~dkuhlman/generateDS.html. Dave -- http://www.rexx.com/~dkuhlman dkuhlman at rexx.com From news at grauer-online.de Mon Mar 1 06:15:04 2004 From: news at grauer-online.de (Uwe Grauer) Date: Mon, 01 Mar 2004 12:15:04 +0100 Subject: KinterBasDB problems in Linux In-Reply-To: References: Message-ID: 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 ! > I don't have any proplems with cross-platform issues. Working on Win2000 + suse linux 8.2, 9.0 and FB 1.5, kinterbasdb from http://sourceforge.net/projects/kinterbasdb/ Try this version! Uwe From premshree_python at yahoo.co.in Sat Mar 13 09:59:42 2004 From: premshree_python at yahoo.co.in (=?iso-8859-1?q?Premshree=20Pillai?=) Date: Sat, 13 Mar 2004 14:59:42 +0000 (GMT) Subject: Static Typing in Python In-Reply-To: <67efcd4ccaf87ddf3c640aad5517017a@news.teranews.com> Message-ID: <20040313145942.9464.qmail@web8308.mail.in.yahoo.com> --- Dang Griffith wrote: > On Sat, 13 Mar 2004 07:07:50 +0000 (GMT), Premshree > Pillai > wrote: > > > --- Jacek Generowicz > >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, but you can use pychecker to get similar > results. > > >Don't you think forced variable declaration is an > >important requirement in a language? > > Not really. Forced variable initialization is > what's important. > Unlike C, et al, and Perl, variables don't have a > default > initial value. If you try reference a variable that > hasn't been > initialized ("bound to a value", in python lingo), > python raises a > NameError exception. > > --dang > p.s. > I know technically Perl initializes to 'undef', but > it's magically > treated as 0 or an empty string, depending on > context, so the > effect is much the same. > -- > http://mail.python.org/mailman/listinfo/python-list Not forcing variable initialization does have its problems. Here's what I mean: http://www.livejournal.com/users/premshree/10624.html?thread=53376#t53376 ===== -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 eric at zomething.com Sat Mar 13 21:29:04 2004 From: eric at zomething.com (Eric @ Zomething) Date: Sat, 13 Mar 2004 18:29:04 -0800 Subject: Python & the job market Message-ID: <20040313182904.1198338832.eric@zomething.com> > I have experience about 4 years of Java experience (designed and developed > numerous projects as a consultant in the past), 10+ years of Oracle > experience, about 5 years of Perl experience so programming is not a problem > . I guess my main point that I should have touch upon was learning Python > and influencing management to go the Python route in a company where Java is > the standard. Question: in terms of these kind of objectives, how important are a world class IDE and world class libraries? Python: Batteries are included, but do we need 110/220v power source as part of the package for the "next phase"? Or, from perhaps a Guido perspective, is that going beyond what Python was intended for? Eric Pederson "Anything is possible" - LB From project5 at redrival.net Sat Mar 13 06:11:23 2004 From: project5 at redrival.net (Andrei) Date: Sat, 13 Mar 2004 12:11:23 +0100 Subject: Python Script for Running a Python Program over Different Files in the Directory References: Message-ID: <1a5q7p54c0ib7.1q4js3buj4tb6$.dlg@40tude.net> Shalen chhabra wrote on Sat, 13 Mar 2004 08:22:09 +0000: > Can anyone give me a snippet for running a python program over all the files > in the directory. You can use os.listdir() to get all files in a given path as a list. Then you can loop over that list and do whatever you like to each item in that list. -- 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 tismer at stackless.com Mon Mar 29 08:24:03 2004 From: tismer at stackless.com (Christian Tismer) Date: Mon, 29 Mar 2004 15:24:03 +0200 Subject: [Windows] Pygtk2 incompatible with Stackless In-Reply-To: <5b3fd64f.0403290502.3260fbc7@posting.google.com> References: <5b3fd64f.0403290502.3260fbc7@posting.google.com> Message-ID: <40682373.7020901@stackless.com> Lorenzo Gatti wrote: > Last weekend I tried to install Pygtk2 on Windows. I succeeded > (maybe), but I discovered a likely bug. > I have Windows 2000, Python 2.3.3 (with ActivePython installed after > the normal version) and a recent Stackless 3.0 python23.dll. > I think I've chosen correct and matching versions of GTK2 (Dropline > distribution 2.2.4-2) and Pygtk2 (pygtk 2.2.0-1.win32-py2.3.exe). > I installed both in the default locations (pygtk in site-packages, > GTK2 in c:\programmi\file comuni\gtk). > Then I added c:\programmi\file comuni\gtk\lib to the PATH to load GTK2 > libraries, I added %PATH% to the PYTHONPATH environment variable > (previously empty) to load the GTK libraries from Python too, and with > advice from Microsoft Dependency Walker I rearranged PATH because a > mismatched iconv.dll from ActiveTcl was loaded instead of the GTK2 > one. > I had an unrelated installation problem: the pygtk initialization code > looks for directory names like "gtk-2.0" and there is one such > directory in the GTK installation. This directory is assumed to be the > pygtk installation subdirectory for GTK 2.0. Instead of hacking pygtk > I copied the files there. > > After all this entertainment I could import the whole family of > modules and call pygtk.require("2.0") without errors, but I had a > surprise: > > C:\>python > Python 2.3.3 Stackless 3.0 040324 (#51, Mar 24 2004, 18:07:02) [MSC > v.1200 32 bit (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. > >>>>import gtk >>>>gtk.Window() > > Traceback (most recent call last): > File "", line 1, in ? > RuntimeError: more keyword list entries than argument specifiers > > > This cryptic message comes from getargs.c and appears to be an > incorrect specification of some function in Pygtk, but it isn't. > Reverting to the normal python23.dll the result appears correct: > > C:\>python > 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 gtk >>>>gtk.Window() > > > (:540): Gtk-WARNING **: Impossibile trovare il gestore dei temi in > module_path: "wimp", > > > > The only configuration difference between the two transcripts is a > replaced c:\winnt\system32\python23.dll. > > Like most users, I have little need to use Stackless Python and Pygtk > at the same time, but this issue can be worth investigating for the > Stackless and/or Pygtk2 developers. Thanks for pointing us to that problem. It is of course relevant since Stackless tries to be a complete replacement for Python. In a slightly too rigorous implementation of thread pickling, I renamed some builtin types slightly, which caused other problems, already. These changes will be gradually undone. I very much hope that the Pygk2 problem belongs to this simple class. thanks - 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 egusenet at verizon.net Wed Mar 24 15:48:02 2004 From: egusenet at verizon.net (Eric) Date: Wed, 24 Mar 2004 15:48:02 -0500 Subject: [Slightly OT] Re: Voting References: <95aa1afa.0403230250.4c9da7a2@posting.google.com> <1060m0593q1uo0d@news.supernews.com> Message-ID: <1gb5t0f.d82mu51pbs2vmN%egusenet@verizon.net> Joe Mason wrote: > In article <1060m0593q1uo0d at news.supernews.com>, John Roth wrote: > > I'd support the "Majority Rules" algorithm. See the article in > > Scientific American (March, 2004 edition) If you run the > > There's no free version of the article online, but the authors are given > as Partha Dasgupta and Eric Maskin, and googling on the latter led me to > http://www.sss.ias.edu/papers/papereleven.pdf. > > So I'll assume the "Majority Rules" algorithm is yet another dumbed-down > name for Pairwise Voting aka Condorcet's Method, and say that I like it, > but there's not much point using it for a yes/no vote. If you're saying to > let people vote on several alternate syntaxes plus "reject outright" - > perfect. Yes, what they are decribing is a Condorcet Method, which they term 'True Majority Rule' and then provide to give a rather strong justification for such a method. More information about Condorcet methods can be found at: http://electionmethods.org/ http://www.alumni.caltech.edu/~seppley/ http://en.wikipedia.org/wiki/Condorcet_method From gandalf at geochemsource.com Mon Mar 8 11:07:34 2004 From: gandalf at geochemsource.com (Gandalf) Date: Mon, 08 Mar 2004 17:07:34 +0100 Subject: curses bkgd problem Message-ID: <404C9A46.4070206@geochemsource.com> Hi Python Gurus! I read the documentation on the python curses module and I started a new application. So far I did this: stdscr = curses.initscr() # Get standard screen curses.start_color() # Uses colors stdscr.bkgd(' ',curses.COLOR_BLUE ) # Set background of the main window curses.noecho() # Do not echo input curses.cbreak() # CBreak mode: process keys immediately (no ENTER) stdscr.keypad(1) # keypad mode: parse control sequences stdscr.redrawwin() stdscr.refresh() However, it is displaying $ characters in black instead of displaying a blue background full of spaces. This must be a problem with my bkgd call since this works fine: curses.init_pair(1, curses.COLOR_RED, curses.COLOR_WHITE) stdscr.addstr(0, 0, curses.longname(), curses.color_pair(1) ) stdscr.refresh() (writes "X11$terminal$emulator" in the top left corner in red and white). Please help me out with a few lines of code. Thanks in advance. G From ExchangeAV at kaydara.com Wed Mar 24 09:26:44 2004 From: ExchangeAV at kaydara.com (ExchangeAV at kaydara.com) Date: Wed, 24 Mar 2004 09:26:44 -0500 Subject: Symantec AVF detected a repairable/quarantined virus in a message you sent Message-ID: <1fcb01c411ac$087af720$030200c0@kaydara.com> Subject of the message: Mail Delivery (failure webmaster at kaydara.com) Recipient of the message: Renel Plouffe From simoninusa2001 at yahoo.co.uk Wed Mar 3 00:11:05 2004 From: simoninusa2001 at yahoo.co.uk (simo) Date: 2 Mar 2004 21:11:05 -0800 Subject: Which Python module for PostgreSQL? References: Message-ID: <30260531.0403022111.1a2928b7@posting.google.com> 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). From jayoconnor at earthlink.net Mon Mar 22 20:12:50 2004 From: jayoconnor at earthlink.net (Jay O'Connor) Date: Tue, 23 Mar 2004 01:12:50 GMT Subject: Python for large projects In-Reply-To: <7xr7vkbdtx.fsf@ruckus.brouhaha.com> References: <7xisgxt51r.fsf@ruckus.brouhaha.com> <105uk4987h7tm77@corp.supernews.com> <7xad28313c.fsf@ruckus.brouhaha.com> <7xr7vkbdtx.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Jay O'Connor writes: > >>>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? >> >>6 and 8, maybe 3...and 10 of course > > > I think 6 and 8 would depend on decimal arithmetic; some modules for > that have been proposed but nothing is released yet, afaik. Depends on what you mean. If you're talking desktop line-of-business software for the IRS, a bank, or any business then there's probably not going to be a lot of heavy math. If you're talking some sort of automatic transaction processing then maybe different, but I can't see the math really being that hoary. I've seen financial transaction software written in TCL which was running a *lot* slower than Python. Even in that case, I/O for getting yuor transactions and storing your results are going to be over head so I would really discount Python unless the example could be defined better. I'd seriously consider Python to start with (but I'd consider Smalltalk first so..) > I can't see answering 3 without also answering 2. A browser is a fairly straightforward piece of work that I think any slowness in a particular language is going to be noticed when you repeat a fundamental operation (render an element) many, many times. I think there's going to be a lot more 'stuff' going on in office suite. That's just speculation, the real reason I didn't consider #2 was that I overlooked it Take care, Jay From ville at spammers.com Sat Mar 13 03:41:55 2004 From: ville at spammers.com (Ville Vainio) Date: 13 Mar 2004 10:41:55 +0200 Subject: Xemacs syntax highlighting References: <1d17eeb7.0403111721.7aae9a76@posting.google.com> Message-ID: >>>>> "Skip" == Skip Montanaro writes: Ville> I'm using color-theme.el myself: Ville> http://www.emacswiki.org/cgi-bin/wiki/ColorTheme Ville> I urge everyone to check it out, esp. if you spend >= 8 Ville> hours a day staring at emacs windows :). Skip> Thanks for the suggestion. Got a favorite theme for Python Skip> bufferrs or do you rotate through a small set of themes to Skip> give your eyes a break? Actually, I mostly stare C++ code, and use the same color theme for all my emacsing. I use color-theme-midnight at work (LCD) because of the peaceful contrast, and color-theme-clarity at home on my low end CRT. Both have a black background. Some day I should find the energy to go through all the color themes :). -- Ville Vainio http://tinyurl.com/2prnb From No.Spam.mc at No.Spam.mclaveau.No.Spam.com Sat Mar 27 15:29:49 2004 From: No.Spam.mc at No.Spam.mclaveau.No.Spam.com (Michel Claveau/Hamster) Date: Sat, 27 Mar 2004 21:29:49 +0100 Subject: A 'Python like' language References: <40645d8f$0$10775$afc38c87@news.easynet.co.uk> Message-ID: >>> http://www.advogato.org/person/JoeNotCharles/diary.html?start=2 Cool link ! Thanks. @-salutations -- Michel Claveau m?l : http://cerbermail.com/?6J1TthIa8B site : http://mclaveau.com From bdelmee at advalvas.REMOVEME.be Mon Mar 22 14:52:08 2004 From: bdelmee at advalvas.REMOVEME.be (=?ISO-8859-1?Q?Bernard_Delm=E9e?=) Date: Mon, 22 Mar 2004 20:52:08 +0100 Subject: Using Oracle on Solaris In-Reply-To: References: Message-ID: <405f4467$0$1121$6c56d894@feed0.news.be.easynet.net> > Given that I already have Oracle and Python installed on the Solaris box, > what else do I need? You'll need a C compiler (Sun's or gcc), and the cx_Oracle module. Grab the source code at http://www.computronix.com/utilities.shtml When building the module (see the included instructions), make sure you've got a working oracle environment (eg 'sqlplus' can be invoked, and the oracle libraries can be found by the linker...) The Python Database API is documented at: http://www.python.org/peps/pep-0249.html Cheers, Bernard. From bignose-hates-spam at and-benfinney-does-too.id.au Wed Mar 17 21:35:38 2004 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 18 Mar 2004 13:25:38 +1050 Subject: New to Python. References: Message-ID: On Thu, 18 Mar 2004 02:53:48 GMT, droog wrote: > 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. Can you show us code that you've tried that fails to do what you want? -- \ "I never forget a face, but in your case I'll be glad to make | `\ an exception." -- Groucho Marx | _o__) | Ben Finney From atmo at go2.pl Sun Mar 14 08:20:48 2004 From: atmo at go2.pl (Ringwraith) Date: Sun, 14 Mar 2004 14:20:48 +0100 Subject: multiple items selection in tkinter tree Message-ID: Hi! Have anyone ever tried to modify the Gene Cash's Tkinter tree widget (available from http://home.cfl.rr.com/genecash/) so it supports multiple items selection ( selection of multiple files like in Windows Explorer - CTRL and SHIFT keys for file selection)? Or maybe someone knows the tree component available to download that supports multiple items selections? Then I will be able to take a look at the code and see how the multiple selection is implemented. Thank you in advance for any hints! Best Wishes, Niki From jepler at unpythonic.net Thu Mar 25 11:38:49 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Thu, 25 Mar 2004 10:38:49 -0600 Subject: Converting IBM Floats..Help.. In-Reply-To: <41A1CBC76FDECC42B67946519C6677A9A20DFD@pippin.int.etrials.com> References: <41A1CBC76FDECC42B67946519C6677A9A20DFD@pippin.int.etrials.com> Message-ID: <20040325163849.GB16608@unpythonic.net> Note that Python floats are C doubles, which generally have a 53-bit mantissa. This means that not all ibm360 floats can be exactly represented. The exponent ranges may also not match up. Finally, I have no idea if ibm360 floats have special representations for cases like denormal, NaN, infinity, etc. so these aren't handled. Basically, the approach is to pull the bits out of the original string and then do some arithmetic to turn them into floats. I don't know anything about ibm360 format, but I followed your description, and the test passes.. import struct def ibm360_decode(s): l = struct.unpack(">Q", s)[0] sign = l >> 63 exponent = (l >> 56) & 0x7f - 64 mantissa = (l & ((1L<<56) - 1)) / (16. ** 14) return [1,-1][sign] * (16**exponent) * mantissa def test(): vectors = [ (155, 'B\x9b\x00\x00\x00\x00\x00\x00'), (77, 'BM\x00\x00\x00\x00\x00\x00'), (1, 'A\x10\x00\x00\x00\x00\x00\x00'), (0, '\x00\x00\x00\x00\x00\x00\x00\x00'), ] for v, s in vectors: d = ibm360_decode(s) print v, d, `s` assert d == v if __name__ == '__main__': test() From cookedm+news at physics.mcmaster.ca Thu Mar 4 16:11:07 2004 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Thu, 04 Mar 2004 16:11:07 -0500 Subject: maximum element? References: Message-ID: At some point, Ivan Voras wrote: > What is the 'most pythonic' way of searching the largest element in a > list/tuple? > > My 'standard' idea is: > > max = list[0] # or -infinity, or whatever... > for i in list: > if i > max: > max = i > > While this is ok, I somehow 'feel' there could be a more concise > solution... :) max(list) -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From Scott.Daniels at Acm.Org Mon Mar 22 09:56:34 2004 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Mon, 22 Mar 2004 06:56:34 -0800 Subject: What's missing from python? In-Reply-To: <405ee0d0$0$63627$5a6aecb4@news.aaisp.net.uk> References: <405ee0d0$0$63627$5a6aecb4@news.aaisp.net.uk> Message-ID: <405f065c$1@nntp0.pdx.net> John Burton wrote: > One of the reasons I like python so much is that the standard > installation comes with a whole lot of libraries to do lots of useful > things but there seem to be a few things missing from the standard > library which would be useful in many projects: > > Encryption - AES and 3DES. Possibly RSA and Certificate processing. This almost certainly not go in. You can get into a big legal hassle when you ship encryption binaries around, as some governments tend to think of them as "munitions" and regulate traffic in them. Python just wants to avoid that hassle, and so leaves it up to you to put it together. > DNS - Something better than gethostbyaddr for looking up other record > types. Hmmm -- I personally have no need, but whatever floats your boat. The general rule is to build a module, get people using it, and if there is both enough interest and a maintainer, propose its addition. > Database - Something suitable for small projects / prototypes like > pysqlite or something in pure python even. I'd personally use such a thing, but perhaps it would be a big chunk of code. It would need its own maintainer. Is pysqlite sufficiently unencumbered by license? > SSL/TLS - Some useful support... If you can figure out how to finesse the encryption issue, I'm sure something in this area might be a go. > Is there any reason why those things are not already in the standard > library? Ah -- a volunteer to build and support -- I like that. -- -Scott David Daniels Scott.Daniels at Acm.Org From list-python at ccraig.org Tue Mar 30 12:44:10 2004 From: list-python at ccraig.org (Christopher A. Craig) Date: 30 Mar 2004 12:44:10 -0500 Subject: Orders of magnitude References: <40699063.1080005@stackless.com> <20040330090610.E5F5.JCARLSON@uci.edu> Message-ID: Josiah Carlson writes: > According to the stored headers, the message IDs are not valid for any > of the messages in the thread. You should check the thread on google > groups to notice how everyone else sees the 'threads'. The only reason > Google, or even other clients place them in the same group, is because > the messages all have proper subjects. Because you're seeing the nntp IDs added when it went through the mail to news gateway. Similarly, your posts don't show up as correct replies to Christian or me because we see the smtp IDs added when it went through the news to mail gateway. -- Christopher A. Craig "When all else fails, manipulate the data." From halloleo at noospaam.myrealbox.com Sun Mar 7 20:05:23 2004 From: halloleo at noospaam.myrealbox.com (leo) Date: Mon, 8 Mar 2004 12:05:23 +1100 Subject: calling python in emacs from a shell buffer doesn't make input/output. Message-ID: hi there i'm running python 2.3.3 on on my panther imac and at work on cygwin-windows. on both systems, i can create a shell buffer and it works as expected: it accepts input processes and on RET shows the output in the buffer, etc... however when i call python interactivly in this shell buffer it doesn't accept any input and therefore doesn't do any output at all -- until i kill the shell with C-c C-d: then python processes all the input characters i have typed, writes its output to the buffer and quits. after that the shell quits obviously as well. so, python works kind of correct, but the input/output transfer to the buffer is not done interactivly. any clue? thanks, leo _______________________________________________ Pythonmac-SIG maillist - Pythonmac-SIG at python.org http://mail.python.org/mailman/listinfo/pythonmac-sig From sean_berry at cox.net Tue Mar 30 01:35:45 2004 From: sean_berry at cox.net (sean) Date: Mon, 29 Mar 2004 22:35:45 -0800 Subject: A couple of Python CGI questions References: <9g8ac.65379$Bg.14309@fed1read03> Message-ID: <2z8ac.65499$Bg.26470@fed1read03> What about collection variables passed via the URL... like someprogram.cgi?userid=Seam How would I collect the userid = Sean part? Thanks in advance. "sean" wrote in message news:9g8ac.65379$Bg.14309 at fed1read03... > I tried getting mod_python to work but have had lots of problems getting it > running. So, I have settled on using python cgi. > > I have already got it going and it seems to run fast enough for me. > > My questions are: > 1. Is there any way to access variables from within a string like perl cgi? > I have found that the best way for me to write html tables is to use a print > """""" string. That way I can write one print """, and then > write html as if I were writing an html file. For example: > print """ > > > > >
This is cool
> """ > I really like this and it is a lot like typing the following in Perl cgi: > print < > > > >
This is cool
> EOF > > So, is there any way to access variables from within the string, besides > using %s? In perl, I just put the $variable in the string and it replaces > the varname with the value. > > 2. Is there a good online resourse for pyton cgi? > 3. How do you collect request variables from forms sent to the python cgi > page, whether post or get? > > > Thanks very much for the help... I will continue to google for my answers. > > Sean > > > From noone at nowhere.net Sat Mar 27 23:16:59 2004 From: noone at nowhere.net (Rasputin) Date: Sat, 27 Mar 2004 23:16:59 -0500 Subject: os module question Message-ID: On the bash shell if I type "fortune -f" it outputs: ___% /usr/share/games/fortunes ___% zippy ___% fortunes ___% fortunes2-o ___% limerick-o ___% startrek ___% fortunes2 ___% unamerican-o ___% fortunes-o ___% linuxcookie When I type os.system("fortune -f") in python it outputs: ___% fortunes '' How do I bypass it and get the orginal output? From j.r.gao at motorola.com Mon Mar 1 21:38:57 2004 From: j.r.gao at motorola.com (J.R.) Date: Tue, 2 Mar 2004 10:38:57 +0800 Subject: Setting wrap mode in wxStyledTextCtrl will significantly make the performance down Message-ID: Hi, I want to use the wxStyledTextCtrl to open a huge ascii file, see almost 10MB. After I set the wrap mode, i.e. set to wxSTC_WRAP_WORD, the open and resize of the wxStyledTextCtrl will be much slow. Any idea to resolve this issue? Thanks, J.R. From mark at prothon.org Mon Mar 29 06:12:04 2004 From: mark at prothon.org (Mark Hahn) Date: Mon, 29 Mar 2004 03:12:04 -0800 Subject: A 'Python like' language References: <40645d8f$0$10775$afc38c87@news.easynet.co.uk> <4067e157$0$3599$afc38c87@news.easynet.co.uk> Message-ID: > or that you had come to this conclusion from a different route That's actually impossible to tell. The period prefix used with the "with" clause came first, which comes from Python 3.0. Then the capitalization was independent I think. But I used to Program in Ruby so the whole concept of being able to tell scope by just looking at the vars might be from Ruby. In any case, if it came before, it must be credited. "Peter Hickman" wrote in message news:4067e157$0$3599$afc38c87 at news.easynet.co.uk... > Mark Hahn wrote: > > >>although there is no reference to this trait being borrowed from Ruby > > > > > > I will fix that. > > Cheers, actually I wasn't sure if it was inspired by Ruby or that you > had come to this conclusion from a different route. Looks interesting. From andrew-pythonlist at puzzling.org Wed Mar 24 20:04:51 2004 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Thu, 25 Mar 2004 12:04:51 +1100 Subject: Any way to get information from fun objects about their parameters? In-Reply-To: References: Message-ID: <20040325010451.GC17117@frobozz> On Thu, Mar 25, 2004 at 12:49:57AM +0000, Kenneth McDonald wrote: > 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. Look at the pydoc module in the standard library, which can do all this and more. -Andrew. From tismer at stackless.com Sat Mar 6 15:50:04 2004 From: tismer at stackless.com (Christian Tismer) Date: Sat, 06 Mar 2004 21:50:04 +0100 Subject: Working around a lack of 'goto' in python In-Reply-To: References: Message-ID: <404A397C.2090408@stackless.com> Rene Pijlman wrote: > Brett: > >>What are the techniques in python for simulating these algorithms without a >>'goto' command? > > > While we're on the subject, is there any way to simulate the 'comefrom' > statement? Sure. If you grab old Stackless python 1.0 with Python 2.0, you have first class continuations, and you can make your code come from wherever you want :-) It *is* possible, but this was no serious proposal. - 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 max at alcyone.com Wed Mar 17 19:43:20 2004 From: max at alcyone.com (Erik Max Francis) Date: Wed, 17 Mar 2004 16:43:20 -0800 Subject: Specific question about readlines versus xreadlines References: Message-ID: <4058F0A8.834DA5DF@alcyone.com> Pernell Williams wrote: > Thank you for your responses. I have a more specific question about > "file.seek() and file.readline()" versus "file.seek() and > file.xreadlines". The latter won't work, since F.xreadlines buffers its reads. -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE \__/ Everyone wants to look good at his own funeral. -- Louis Wu From n8 at toglimi.langhirano.it Wed Mar 24 09:10:02 2004 From: n8 at toglimi.langhirano.it (Nico Alberti) Date: Wed, 24 Mar 2004 15:10:02 +0100 Subject: py2exe and activex controls Message-ID: First of all sorry should this be a lame question, I tried to look at a possible solution in google, but I was not successful. I am trying to create an .exe of the ActiveXWrapper_Acrobat.py from the wxPython demo programs. While it runs smoothly in Pythonwin or from the command line, the executable file I obtain from py2exe does not work and exits with these error messages: Traceback (most recent call last): File "acrobat.py", line 123, in ? File "acrobat.py", line 119, in __init__ File "acrobat.py", line 41, in __init__ AttributeError: 'NoneType' object has no attribute 'Pdf' 14:53:44: Debug: e:\Projects\wx2.4\src\msw\app.cpp(439): 'UnregisterClass(canvas )' failed with error 0x00000584 (class has still open windows*.). 14:53:44: Debug: e:\Projects\wx2.4\src\msw\app.cpp(446): 'UnregisterClass(no red raw canvas)' failed with error 0x00000584 (class has still open windows*.) Does py2exe need some special tweaking for dealing with wxWindows and/or ActiveX calls? Any help would be greatly appreciated. Thanks in advance. -- Ciao Nico * roughly translated. In Italian in the original message. From peter at engcorp.com Sat Mar 20 22:50:00 2004 From: peter at engcorp.com (Peter Hansen) Date: Sat, 20 Mar 2004 22:50:00 -0500 Subject: Any module which can act as a BitSet? In-Reply-To: References: Message-ID: Senthoorkumaran Punniamoorthy wrote: > I wanted to know in Python are there any module available which can > perform the same funtionality as a BitSet classs in Java. Here is the > Java Doc for that. > > http://java.sun.com/j2se/1.4.2/docs/api/java/util/BitSet.html This was asked a month or so ago. Here's the thread: http://groups.google.com/groups?th=faed34ee3de309bf&seekm=bvto8j%24t54%241%40news.service.uci.edu (Short answer: not really, though the OP last time quickly wrote something that satisfied his own needs. Maybe yours are no different?) -Peter From jdtiede at sstar.com Mon Mar 15 17:43:19 2004 From: jdtiede at sstar.com (John D. Tiedeman) Date: Mon, 15 Mar 2004 16:43:19 -0600 Subject: Python-list Digest, Vol 6, Issue 162 In-Reply-To: References: Message-ID: <40563187.1050205@sstar.com> On 2004-03-11 Dave Brueck wrote: >Here's the configure command I used, don't know if it will help you at all: > >./configure --with-postgres-libraries=/usr/local/pgsql/lib >--with-postgres-includes=/usr/local/pgsql/include >--with-zope=/home/dave/Zope261 >--with-mxdatetime-includes=/usr/lib/python2.3/site-packages/mx/DateTime/mxDateT >ime > >-Dave > > I adapted to: ./configure --with-postgres/libraries=/usr/local/pgsql/lib --with-postgres-includes=/usr/local/pgsql/include --with-zope=/usr/lib/Zope-2.6.2-src --with-mxdatetime-includes=/usr/lib/python2.2/site-packages/mx/DateTime/mxDateTime I have python2.3 but mx is only in 2.2 for some reason. Zope-2.6.2 says use Python 2.1 only; it didn't install satisfactorily but as I'm not planning to use on a website at this point does that matter? The libraries are there. At this point, using the command conn = psycopg.connect("dbname=personal", serialize=0) from psycogq documentation, I get NameError: name 'psycopg' is not defined What am I missing? From CousinStanley at hotmail.com Wed Mar 24 00:17:21 2004 From: CousinStanley at hotmail.com (Cousin Stanley) Date: Tue, 23 Mar 2004 22:17:21 -0700 Subject: 3D apps in Python? References: <405FB88A.12995153@alcyone.com> <4060C0C6.3BA8FF23@alcyone.com> Message-ID: > ZOE (http://www.alcyone.com/software/zoe/) looks really nice. Erik .... I'd also like to add a word of thanks for making your ZOE packagae and examples available .... The included Linear Algebra module, la.py, is very nice in itself and will probably be useful to me in the future .... -- Cousin Stanley Human Being Phoenix, Arizona From ressler at cheetah.jpl.nasa.gov Thu Mar 18 13:06:46 2004 From: ressler at cheetah.jpl.nasa.gov (Michael Ressler) Date: 18 Mar 2004 18:06:46 GMT Subject: Slow Python - what can be done? References: <480e9240.0403180943.64bee13d@posting.google.com> Message-ID: In article <480e9240.0403180943.64bee13d at posting.google.com>, Jason wrote: > 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. > # This is the slow part of the program > dest = list(self.data.getdata()) > src = source.data.getdata() > for x in range(0, self.data.size[0] - 1): > for y in range(0, self.data.size[1] - 1): "For loops" are evil ;-) Though I'm not familiar with your algorithm, you should investigate the Numeric/numarray package, which is designed to do lots of number crunching fast. If you can cast your problem into good Numeric form, you'll see a speedup of a factor of hundreds. Mike -- Dr. Michael Ressler Research Scientist, Astrophysics Research Element, Jet Propulsion Laboratory Email: ressler at cheetah.jpl.nasa.gov Phone: (818)354-5576 "A bad night at the telescope is still better than the best day at the office." From mark at prothon.org Sun Mar 28 14:22:52 2004 From: mark at prothon.org (Mark Hahn) Date: Sun, 28 Mar 2004 11:22:52 -0800 Subject: Prothon, metaclasses, Zope [Was: A 'Python like' language] References: <95aa1afa.0403272243.78d60724@posting.google.com> Message-ID: > BTW, I wonder how Prothon would solve this problem Me too. I'll have to take a stab at it. Mark Hahn (Prothon author daring to raise his head in the Python forum). "Michele Simionato" wrote in message news:95aa1afa.0403272243.78d60724 at posting.google.com... > > Hello, my name is Skip and I am metaclass-unaware. I've been programming in > > Python for about ten years and I have yet to write a metaclass. At first I > > thought it was just that metaclasses were new to the language, but now as > > more and more people use them and proclaim their widespread benefits, I have > > come to realize that through years of abuse my brain has become addicted to > > classic classes. > > I began using Python since version 2.2.1 and without knowing anything > about OOP, so I had the advantage of a fresh start ;) Still, I will readily > admit that I was not immediately sold to metaclasses and actually I was > kind of skeptical about them. The "Putting metaclasses to work" book > made me change my mind. At this point I have becomed so accustomed to > metaclasses that I am disturbed when I cannot use them. > > Just a real life example. I started studying Zope few days ago. > Writing my first class I got caught since I was overriding a predefined Zope > method. I made a dir() and discovered that the context object in Zope > has more than four hundreds (400!) attributes. In such a situation it > is likely to override a predefined name, especially now that I am a > beginner and I have a fair chance of reimplementing (badly) something > which is already available. So, I thought: "well, this a job for a metaclass" > and in five minutes I implemented a metaclass raising an error if I was > inadvertently overriding a predefined name (except names such as __init__ > and similia, of course). Everything was nice and good until the moment > I tested the metaclass on a Zope class and got a segmentation fault. > > Since I don't know anything about Zope internals I can only make a guess > of what happened and I would be happy if some Zope guru here could > confirm (possibly educated) guess. > > In my understanding, Zope tweaked Python classes at C level code, introducing > the concept of Extension classes. Extension classes are instances of a C coded > metaclass which does a lot of magic (for instance there are methods which > are automatically generated each time I create an extensions class); > unfortunately, this metaclass does not follow the protocol of Python 2.2+ > metaclasses. This is evidently an historical accident, since Zope Extension > Classes were invented before Python 2.2 [*]; the net result is that I cannot > mix Python classes with custom metaclasses and Zope Extension classes. > > I have heard that this is a temporary wart and that Zope 3 will solve > this issue (I'd like to have a confirmation here). However, for the > moment, I had to come out with a non-metaclass solution. > > So, I reverted my mind to the pre-metaclass functioning mode (which required > a certain effort) and I wrote a function that takes a class, looks at > its dictionary, and raises an error if the class overrides an attribute > which is already defined in the parent classes. The solution works, > but it is kind of ugly compared to the metaclass solution: > > 1. The metaclass can raise the error *before* the metaclass is created, > whereas the function works a posteriori, *after* the overriding is done; > if find it to be conceptually unsatisfactory, I don't want to create > a class just to throw it away. The alternative is to use a class factory, > but then I have just re-invented a metaclass with an ugly call syntax. > > 2. The metaclass can be inherited, so the check is automatic for all children; > on the contrary, I have to call the function by hand each time I define > a new class. This means writing twice the class name, which is error > prone if I later rename the class and I forget to update the function > call. > > Whereas it is true that in most cases you can find a non-metaclass solution, > it is also true that in most case the metaclass solution is by far more > elegant than the alternative. > > BTW, I wonder how Prothon would solve this problem, i.e. selectively > forbidding the overriding of names, with an easy of use/elegance > comparable to the Python metaclass solution. > > Michele Simionato > > > [*] I would be curious to know if Guido decided to expose metaclasses in > Python since he noticed that they were already being used in real applications > such as Zope (in some hidden form), or if there was some other reason. From olku at web.de Wed Mar 17 09:24:11 2004 From: olku at web.de (Oliver Kurz) Date: Wed, 17 Mar 2004 15:24:11 +0100 Subject: imaplib.IMAP4: Bug in implementation Message-ID: <200403171424.i2HEOBQ27912@mailgate5.cinetic.de> > > 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. Even if I use two \ it doesn't work, cause the IMAP-server doesn't like the quoting. BTW! Python makes two \ from this one. But as I said the problem is the quoting of the arguments. --? -- Oliver?Kurz From jepler at unpythonic.net Thu Mar 11 09:42:02 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Thu, 11 Mar 2004 08:42:02 -0600 Subject: RuntimeError: cannot unmarshal code objects in restricted execution mode In-Reply-To: References: Message-ID: <20040311144202.GB14393@unpythonic.net> You need to determine why the builtins in main_dict are not the same as the interpreter's builtins -- this is the reason for "restricted execution mode". ./Objects/frameobject.c: f->f_restricted = (builtins != tstate->interp->builtins); Jeff From fpetermaas at netscape.net Fri Mar 12 08:25:45 2004 From: fpetermaas at netscape.net (Peter Maas) Date: Fri, 12 Mar 2004 14:25:45 +0100 Subject: Static Typing in Python In-Reply-To: References: Message-ID: Peter Maas schrieb: > class doesTypeChecking: > def __init__(self): > aString = "" > aFloat = 0.0 sorry, I was too hasty. Here is the tested code: 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 Mit freundlichen Gruessen, Peter Maas -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Hubert-Wienen-Str. 24 Tel +49-241-93878-0 Fax +49-241-93878-20 eMail peter.maas at mplusr.de ------------------------------------------------------------------- From mark at prothon.org Thu Mar 25 11:25:56 2004 From: mark at prothon.org (Mark Hahn) Date: Thu, 25 Mar 2004 08:25:56 -0800 Subject: Prothon, a classless Python Message-ID: I would like to announce a new interpreted object-oriented language very closely based on Python, that is Prototype-based, like Self (http://research.sun.com/research/self/language.html) instead of class-based like Python. I have named the language Prothon, short for PROtotype pyTHON. You can check it out at http://prothon.org. The prototype scheme makes object oriented computing very simple and complicated things like meta-classes dissapear. Once you get used to prototypes, classes seem old-fashioned. You can inherit data as well as methods and you can switch prototypes on the fly. Anyone who knows Python can program in Prothon with almost no learning curve. Prothon is pre-alpha, but runs well enough to give it a spin. Basic types, the File object, importing, packages, and the Re module are ready to try. It runs on Linux/Unix and Windows. Obviously Prothon is not Python compatible, so I have taken the liberty of implementing many changes that have been imagined for the almost mythical Python 3.0. Right now I've made decisions unilaterally, but I'm not planning on freezing language decisions until 7/04, so get on the Prothon mailing lists and make your opinions known. Since the Prothon interpreter has been written from the ground up, we've had the opportunity to make it industrial-strength. We feel this is very important for high-end hosting applications, and that this is a current weakness of Python and it's GIL. Prothon has no GIL. Here are some interpreter features: - Uses native OS threads, even multiple interpreters can run at once on the same objects. - Locking is done at the object level with shared read locks and exclusive write locks. - No recursion limits, Prothon is stackless. - Garbage collection is mark-and-sweep in a seperate thread. - C coding is simple. Macros simulate coding at Prothon level. (No reference counting!) - Ints are 64-bits, internal architecture is all 64-bit. - Built on Apache Portable Runtime (APR) for stability, ease in porting, and eventual integration with Apache. From lbates at swamisoft.com Tue Mar 2 11:10:43 2004 From: lbates at swamisoft.com (Larry Bates) Date: Tue, 2 Mar 2004 10:10:43 -0600 Subject: NT Services and EventLog problems References: Message-ID: <2ImdnVPOZbydL9ndRVn-vw@comcast.com> I made the change, but get the exact same error message. I went back and checked the book again and it reads (on page 359): "The files PythonService.exe, win32evtlog.pyd, and win32service.pyd each have a set of generic messages. Each file has nine messages for each of the classes Error, Informational, Warning, and Success." I tried all three of these AND servicemanager.pyd and I can't make any of them work. Mark Hammond, are you out there anywhere? Regards, Larry "Pieter Claerhout" wrote in message news:mailman.14.1078214898.12614.python-list at python.org... > 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 jdhunter at ace.bsd.uchicago.edu Mon Mar 29 22:06:50 2004 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Mon, 29 Mar 2004 21:06:50 -0600 Subject: histogram type thingy for (unique) dict items In-Reply-To: <5e8bd451.0403291801.51071ca2@posting.google.com> (kp87@lycos.com's message of "29 Mar 2004 18:01:03 -0800") References: <5e8bd451.0403291801.51071ca2@posting.google.com> Message-ID: >>>>> "kevin" == kevin parks writes: kevin> hi. I've been banging my head against this one a while and kevin> have asked around, and i am throwing this one out there in kevin> the hopes that some one can shed some light on what has kevin> turned out to be a tough problem for me (though i am kevin> getting closer). kevin> i have been mucking with a lot of data in a dictionary that kevin> looks like: If I'm understanding you correctly, something like the following should speed you on your way: foo = { (5, 138, 1) : [ 0, 2, 7 ], (7, 264, 1) : [ 0, 2, 7 ], (9, 367, 0) : [ 0, 2, 7 ], (5, 156, 1) : [ 0, 7, 2 ], (8, 315, 1) : [ 0, 7, 2 ], (8, 317, 1) : [ 0, 7, 2 ], (1,2,3) : [4,5,6],} # reverse the dict so that the values point to a list of keys which # share that value, ignoring the order of the vale rd = {} # reverse dict for key, val in foo.items(): val.sort() rd.setdefault(tuple(val),[]).append(key) for key,val in rd.items(): print key,val # make a count dictionary countd = {} for key, val in rd.items(): countd[key] = len(val) print key, countd[key] You can easily sort the count dictionary - search google for order dictionary by values. Hope this helps, JDH From peter at engcorp.com Tue Mar 30 12:28:29 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 30 Mar 2004 12:28:29 -0500 Subject: Richards bench benchmark In-Reply-To: <6748553f.0403300836.744e3e22@posting.google.com> References: <6748553f.0403291446.27fb7b93@posting.google.com> <6748553f.0403300836.744e3e22@posting.google.com> Message-ID: Duncan Lissett wrote: > Peter Hansen wrote in message news:... > > >>There's a hint on http://www.cl.cam.ac.uk/users/mr/Bench.html >>(Martin's own page on the subject) which suggests ("designed for the >>comparison of System Implementation Languages") that this is not >>a suitable benchmark for Python anyway. Python doesn't normally >>get used in that domain, and it might be it can't even do what >>is required without resorting to C extensions... > > > That would be sad, given that language implementors have used Bench to > explore the performance characteristics of Smalltalk and Self and > Java. > > "Benchmarking Java with the Richards benchmark" > http://research.sun.com/people/mario/java_benchmarking/richards/richards.html That has useful additional info I couldn't find on Richards' own site. (His own site refers to it as "bench", but I guess others call it "richard" -- it helps to be searching for the right thing.) It appears the "specification" is his original, which was written in BCPL. It also seems that the problem is relatively generic, just a "task scheduler", without really requiring low-level support of the kind I feared (after looking at the Pascal and C versions). I'd implement it in Python for kicks, but I'm not sure how I'd know whether my version was doing the right thing. Are there any tests for it? Ways of ensuring the output is correct? -Peter From tjreedy at udel.edu Sat Mar 20 01:41:39 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 20 Mar 2004 01:41:39 -0500 Subject: Package name with '.' in them: Python Bug ? References: <105mmlt1ld7jvb9@news.supernews.com> <8ef9bea6.0403192150.57dbddef@posting.google.com> Message-ID: "Hung Jung Lu" wrote in message news:8ef9bea6.0403192150.57dbddef at posting.google.com... > > "Yannick Patois" wrote in message > > > Under some naming conditions of module files, it seems that python lost > > > class static variables values. > --------------------------------- > "John Roth" wrote in message news:<105mmlt1ld7jvb9 at news.supernews.com>... > > There is no such thing as a static variable in Python. > --------------------------------- > "Terry Reedy" wrote in message news:... > > Since 'static variable' is not a Python concept, I do not know what you > > mean. > --------------------------------- > > 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. >That's the standard jargon in languages like C++ or Java. Python is neither C++ nor Java. It's data model is quite different. Imported jargon is meaningless to those not familiear with is. Adding the word 'static' to 'class attribute' or 'class variable' adds nothing since there is no differentiation from a hypothetical 'non-static' class attribute. > To be fair, the same jargon persists in Python when it comes to > staticmethod(): staticmethod in Python 2.3 has nothing to do with > "function staticity", but rather it refers to "class statiticity". 'class statiticity'? is meaningless to me. Actually, 'staticmethod' is something of a misnomer since the effect of staticmethod(function) is to mark the function as one to *not* be wrapped as a method but to be left alone as a function, just like function attributes of instances. 'unwrapped' might have been better. I think there was an overstriving for parallelism with 'classmethod', which is an accurate and meaningful term (the contrast being with 'instance method'). Terry J. Reedy From axel.koehler at tu-berlin.de Tue Mar 16 04:30:53 2004 From: axel.koehler at tu-berlin.de (Axel Koehler) Date: Tue, 16 Mar 2004 10:30:53 +0100 Subject: Start and control an extern program References: <4051087D.1050409@zoran.com> Message-ID: Josiah Carlson writes: >> But what is a timer objekt? Can't find it in my documentation of the >> python library. > > threading.Timer > http://www.python.org/doc/current/lib/timer-objects.html > Thank you for the hint, but this needs threads, is this really portabel in all versions of python under linux? Axel -- ___________________________________________________________________________ Dipl. Ing. Axel K"ohler, axel.koehler at tu-berlin.de Tel: 030-314 73141 TU Berlin, FAK I, Sekr. FR 3-15, Franklinstr. 28-29 10587 Berlin From pwatson at redlinec.com Sat Mar 13 23:30:26 2004 From: pwatson at redlinec.com (Paul Watson) Date: Sat, 13 Mar 2004 22:30:26 -0600 Subject: execute script everywhere References: Message-ID: <4053dfe3$1_1@themost.net> "myang" wrote in message news:mailman.12.1079231052.745.python-list at python.org... > > After we compile a C program, we can put the executable file under a > directory (like /bin) so that we can run it everywhere, and don't have to > type the full path. > Can we do the same thing to a python script? > For example, I have a script.py under "/home/john/". Can I just type "python > script.py" to run it under another directory "/home/tom/"? > Thanks! > > Yang It appears that you are on a UNIX system. Most systems will support "shebang" proceesing of the first line in the file. The first line tells UNIX to find 'python' in the PATH and run it to exectute this script. Use 'man env' for more information. #! /usr/bin/env python import os import sys ... When you do this, you do not need to uses the word 'python' on the command. At the '$' prompt, just use: script.py The first line tells it to use Python to process the file. Of course /home/john where the script.py file exists must be in the PATH variable in order to run it from anywhere. Just like you have /bin in your PATH variable already. From mickel at csc.fi Thu Mar 11 06:18:23 2004 From: mickel at csc.fi (=?ISO-8859-1?Q?Mickel_Gr=F6nroos?=) Date: Thu, 11 Mar 2004 13:18:23 +0200 (EET) Subject: Video module? Message-ID: 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 stable enough for my purposes. I have also tried using Windows Media Player with COM, but that is cumbersome. The module must work on Windows (and preferably on Linux as well). Basically, what I need to be able to do is play a selected interval of the movie and if possible also rip the sound track from the movie file as a WAV file. Any ideas anybody? Cheers, Mickel Gr?nroos -- Mickel Gr?nroos, application specialist, linguistics, Research support, CSC PL 405 (Tekniikantie 15 a D), 02101 Espoo, Finland, phone +358-9-4572237 CSC is the Finnish IT center for science, www.csc.fi From sross at connectmail.carleton.ca Sat Mar 27 14:11:20 2004 From: sross at connectmail.carleton.ca (Sean Ross) Date: Sat, 27 Mar 2004 14:11:20 -0500 Subject: PEP 318 : Def and Class in expressions References: Message-ID: "PF" wrote in message news:opr5jagci1b723ru at news.free.fr... > > Hello, > > I'm pleased to see activity on this topic as it pains me to write > "classmethod" two pages of code after the method definition. However I > find the decorators to obfuscate the syntax and lessen the expressivity > (ie. they restrain what can be done). > > All these problems come from the fact that the execution of the > "foo=staticmethod(foo)" must be delayed after the execution of the "def" > statement because it must act on the function after it has been defined. > > Normal program execution thus flow forces it to be placed after the > "def", while readability would require it to be placed *before* the 'def'. > > How to reverse the execution order ? One method would be to use an > expression, but that would get very ugly soon, and Python's indented > syntax does not lend itself well to such twistings. To mix a few previous > postings : > > mymethod = staticmethod( def (args): > method code... > ) > > is just plain ugly. > > mymethod = staticmethod( def (args) ): > method code... > > is also quite ugly. > > I don't like the decorators either. > > So the root of the problem is the fact that the source code executes from > top to bottom. I see two solutions. Check out "Re: Meta-class fun with PEP 318 [was Re: PEP 318 - posting draft]", for another solution, but only for methods. decorate("g", staticmethod) def g(): return "G" Sean From budr at local.host Thu Mar 4 17:51:39 2004 From: budr at local.host (Bud Rogers) Date: Thu, 04 Mar 2004 16:51:39 -0600 Subject: what is a good intro book on python ? References: Message-ID: vincent wehren wrote: > "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) I am actively lusting for the Cookbook. I have had LP 1st edition for a while. Is there enough more/newer/better about the 2nd edition to justify buying it as well? budr From skip at pobox.com Tue Mar 9 14:35:17 2004 From: skip at pobox.com (Skip Montanaro) Date: Tue, 9 Mar 2004 13:35:17 -0600 Subject: getting size of gif In-Reply-To: References: Message-ID: <16462.7285.494398.712218@montanaro.dyndns.org> Sebastien> I would like to know if there is a module out there to help Sebastien> me get the size of a gif image. Yup. Check out PIL from Pythonware. Skip From premshree_python at yahoo.co.in Mon Mar 1 06:38:11 2004 From: premshree_python at yahoo.co.in (=?iso-8859-1?q?Premshree=20Pillai?=) Date: Mon, 1 Mar 2004 11:38:11 +0000 (GMT) Subject: Image width, height. Message-ID: <20040301113811.36552.qmail@web8310.mail.in.yahoo.com> Hello, Is there a Py module available using which I can find the width and height of any image format? -Premshree ===== -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 happ_dickson at yahoo.ca Tue Mar 2 18:25:18 2004 From: happ_dickson at yahoo.ca (b0x) Date: Tue, 2 Mar 2004 17:25:18 -0600 Subject: HOWTO: Python 2.3 on Fedora Core 1 Linux References: Message-ID: 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 theller at python.net Tue Mar 2 13:06:12 2004 From: theller at python.net (Thomas Heller) Date: Tue, 02 Mar 2004 19:06:12 +0100 Subject: python.exe vs pythonw.exe difference? References: Message-ID: "Tim Peters" writes: > [moving this from comp.lang.python to zope-dev; it really belongs on a > Zope list, although schemes to change what pythonw does probably belong > on python-dev] [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] > [Thomas Heller] >> It has been reported that writing to the original sys.stdout (and >> maybe also sys.stderr) sooner or later raises an IOError when running >> pythonw.exe, unless these are redirected. Could this be the problem? > > It could, although I have no idea what WinXP does (and don't have access to > XP). 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 I get exactly the same, on Win XP Pro, both for sys.stdout and sys.stderr. > The point of pythonw.exe is that no console is created or inherited, and the > default stdin, stdout and stderr provided by MS C in that case are unusable > (although the output flavors can appear to be usable until some secret MS > limit is exceeded -- at least under Win98SE). 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? 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. Thomas From grelens at NOSPAMyahoo.NOTNEEDEDfr Thu Mar 11 12:07:37 2004 From: grelens at NOSPAMyahoo.NOTNEEDEDfr (GrelEns) Date: Thu, 11 Mar 2004 18:07:37 +0100 Subject: Speed up loading and free memory... References: <4050244d$0$305$636a15ce@news.free.fr> <110320040725438317%bscholln@mac.com> Message-ID: <40509cc2$0$289$626a14ce@news.free.fr> "benjamin schollnick" a ?crit dans le message de news: 110320040725438317%bscholln at mac.com... > Maybe a different method of handling this would solve your issue. > > For example, does the data all have to be stored in a single file? > Would using multiple indexs, and multiple storage files improve your > performance? > > But those are question I can not answer... files must not be modified, index file contains on one line a key and an offset which can be use to go directly to data file. thx From piedmontbiz at aol.com Mon Mar 1 16:18:35 2004 From: piedmontbiz at aol.com (PiedmontBiz) Date: 01 Mar 2004 21:18:35 GMT Subject: Multi-user quiz show game References: Message-ID: <20040301161835.20170.00000686@mb-m27.aol.com> >From: likwoka at yahoo.com (Alex Li) >Date: 3/1/04 2:51 PM Eastern Standard T >Hi all, > >I would like to create a quiz show game for play in a party. The >physical setup would probably be a big screen where everyone (players >and host) can see, which shows a question, and a multiple choice of >answer. The player, with a client computer and keyboard in front, >will press a key to pick an answer. The client program, will then >send the player's choice through the wire to the server program. The >server program will validate the player's answer and the one that is >correct and fastest will get a point. Then we go on to the next >questions...etc. > >Some more specific requirements: >1) the programm will probably run on some windows machines >2) need unicode support (ie. questions and answers will be shown in >Chinese) >3) the display will be a full screen display (ie, no window's toolbar >or taskbar shown) > >My current thinking is: >1) Use twisted for the networking code >2) Use wxpython for the screen display > >My questions are: >Does anyone have any recommendation of what frameworks/libraries to >use? I am kind of worry about mixing all these libraries/frameworks >together for them to play nicely... Would pygame help simplify? > >Thanks a lot, >Alex > > > I'll let the experts answer this one. But I have a question. Do you rule out a http server ? If I were doing this I would avoid the apparent complexity wxpython and just use standard html and javascript to pass the answers to the server. The python script could record time it got the "get" and return it with the validation. allen From mwh at python.net Mon Mar 15 07:46:49 2004 From: mwh at python.net (Michael Hudson) Date: Mon, 15 Mar 2004 12:46:49 GMT Subject: Deprecating reload() ??? References: <09b350henbtk9vnai0v7fhtbsqbmubl7vn@4ax.com> <7cj4c.2733$G3.21896@localhost> <8ok3505b3b3g22bk8ci6iagptqav2cfi6r@4ax.com> <6kk6501shlve52ds2rjdopa73jhpchprg3@4ax.com> Message-ID: David MacQuigg writes: > 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__'. They'll be None, mostly. Cheers, mwh -- C++ is a siren song. It *looks* like a HLL in which you ought to be able to write an application, but it really isn't. -- Alain Picard, comp.lang.lisp From leens_chacko at hotmail.com Wed Mar 31 16:57:15 2004 From: leens_chacko at hotmail.com (Leeny) Date: 31 Mar 2004 13:57:15 -0800 Subject: Pymat Message-ID: Hi Group, Hope someone can help me with this problem. I am a new user to python and am currently working with pymat module of python. I tried to create plots thru pymat using pymat.eval(h, 'plot(x,y)') This is working fine. However, i dont know how to print or save this plot as a .tif image something like print(gcf, '-dtiff', 'test') using pymat. Please help me!!!! Thanks Leeny From paul at prescod.net Wed Mar 10 14:24:45 2004 From: paul at prescod.net (Paul Prescod) Date: Wed, 10 Mar 2004 11:24:45 -0800 Subject: Unicode and rdf In-Reply-To: References: Message-ID: <404F6B7D.9070503@prescod.net> Richard West wrote: > I'm trying to parse the rdf dumps from dmoz.org (Open Directory > Project) and am having great difficulty just getting Python to read > the files. The files are RDF in UTF-8 encoding according to the > dmoz.org web site, but I get the following error: > > UnicodeDecodeError: 'utf8' codec can't decode bytes in position > 52376-52378: invalid data Perhaps you could try using another XML parser or validator unrelated to Python. I am 90% confident that you will find that it will report the same problem. For instance you could use "xmlwf" that comes with Expat http://sourceforge.net/projects/expat/ Paul Prescod From garryknight at gmx.net Mon Mar 22 16:30:30 2004 From: garryknight at gmx.net (Garry Knight) Date: Mon, 22 Mar 2004 21:30:30 +0000 Subject: Newbie Formatting Question References: Message-ID: <1079991015.28749.0@lotis.uk.clara.net> In message , . wrote: > I'm going through "How to Think Like a Computer Scientist", and > am in chapter 11. (aside: what do you think of the book? any > recommendations for other books?) I thought it was a good introduction both to programming and to Python. Here are a few others: Learning to Program: http://www.freenetpages.co.uk/hp/alan.gauld/ A Byte of Python: http://www.python.g2swaroop.net/ Dive Into Python: http://diveintopython.org/ Text Processing in Python: http://gnosis.cx/TPiP/ Python Cookbook: http://aspn.activestate.com/ASPN/Cookbook/Python/ An Introduction to TkInter: http://www.pythonware.com/library/tkinter/introduction/index.htm And more: http://www.tcfb.com/freetechbooks/bookphyton.html > I have a question about an example of formatting in the book > (page 120). There is a line that says: > > print "%-20x %12.02f" % (student, wages[student]) > > I understand what's going on, and the example works fine. > I just don't understand what the 0 is doing in the %12.02f format > specification. I thought it might be to force padding zeroes, but > I get the same result with or without the 0. Also, %12.0002f > gives the same result. Was this a typo, or is there something > that I'm not understanding? I don't know if it was a typo or whether it's just the author's habit to put an extra 0 in there. It works fine with or without it for any number I could throw at it. The C sprintf() function uses a similar specification in which the 0 in that position does (AFAICR) mean 'pad with zeroes'. A specification of "%12.02f" would yield "1.20" while a specification of "%12.2f" would yield "1.2". Python seems to force the zero-padding, or it doesn't use sprintf() maybe... -- Garry Knight garryknight at gmx.net ICQ 126351135 Linux registered user 182025 From zinc at unknown.com Thu Mar 25 14:52:12 2004 From: zinc at unknown.com (zinc) Date: Thu, 25 Mar 2004 19:52:12 +0000 Subject: How to install pyGTK(2) Message-ID: Hi Pythoneers, Im interested in trying some gui programming with the GTK2 toolkit. I found this brief article,(http://www.linuxjournal.com/article.php?sid=6586), that speaks about utilising 'Glade' to help build these gui. I downloaded the pyGTK tarball from http://www.daa.com.au/~james/software/pygtk/ i do the usual ./configure, make, makeinstall. Everything goes well, but when i try a sample script python says it can't import gtk (i did a help, modules and there is no gtk module listed). After googling for sometime i found a pygtk slackpack (im running slack 9.1 by the way ;)), and installed that instead. I then tried the sample script again and this time no gtk problems( the module is now listed). but it now bombs out on the second import line: import libglade??? I have glade2 installed, and libglade, but i check python modules and there is no libglade module listed. Ive googled, but now im getting confused. Phew.. I'm really just after a step by step guide to what to download and where to install everything i need to get started building gui's with glade+pyGTK+python. This would be much appreciated. I promise i googled hard, but sometimes i can't see the wood for the trees :/ Getting my pyGTK, pyGTK2+pyGLADE+python-libglade's all mixed up and just a little lost. Any help would be warmly received. Regards zinc From max at NcOviSsPiAoMntech.com Mon Mar 1 13:31:43 2004 From: max at NcOviSsPiAoMntech.com (max khesin) Date: Mon, 01 Mar 2004 18:31:43 GMT Subject: Jython Debugger? Message-ID: Hi all, I was takling to someone who has been using Jython for a while. Their biggest complaint is the luck of a good debugger. I was really surprised. Isn't there anything decent out there? thanks, max From mark at hahnca.com Mon Mar 29 16:27:35 2004 From: mark at hahnca.com (Mark Hahn) Date: Mon, 29 Mar 2004 13:27:35 -0800 Subject: A 'Python like' language References: <40645d8f$0$10775$afc38c87@news.easynet.co.uk> <95aa1afa.0403262049.4b2a6f78@posting.google.com> <20040329122936.GA1088@alcyon.progiciels-bpi.ca> Message-ID: <00e601c415d4$a750d8c0$d701a8c0@MarkVaio> > Is there some inter-operability sought between Prothon and Python? No, I assumed from day one that the lack of classes meant a fundamental incompatability. However, even though I am designing a new language, I have no desire to re-invent anything for any arbitrary reason, so I chose to "steal" everything from Python unless it conflicted with the prototype paradigm or I or other Pythoners considered the current Python broken. I am changing to all of Guido's "regrets" for example. One example of something I consider broken in Python is the generator scheme using the def keyword and not allowing nesting of generators. I just added docs for my gen keyword today to the Prothon website. ----- Original Message ----- From: "Fran?ois Pinard" To: "Mark Hahn" Cc: Sent: Monday, March 29, 2004 4:29 AM Subject: Re: A 'Python like' language [Mark Hahn] > > Yes, this seemed interesting to me too. But when arrived at the sentence > > "Prothon only allows tabs for indentation" I couldn't continue reading ;-) > It appears we will be bowing to pressure and switching to spaces. This might be good news. Despite a bit curious about prototype-based languages, I initially stopped reading about Prothon when I saw that it chose mandatory TABs. `make' is the only tool for which I still give in such things :-). Allow me a question. Is there some inter-operability sought between Prothon and Python? That could ease taming communities. As far as I understood, so far, these are currently meant as incompatible beasts. -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From michael at foord.net Thu Mar 18 10:06:48 2004 From: michael at foord.net (Fuzzyman) Date: Thu, 18 Mar 2004 15:06:48 +0000 Subject: dictionary wart References: <6b17fa95.0403180441.a747b15@posting.google.com> <7xr7vquwpo.fsf@ruckus.brouhaha.com> Message-ID: <4eej50944f0lk1dc3fag82qumcsk4t39j9@4ax.com> On Thu, 18 Mar 2004 13:46:19 GMT, Jesper wrote: >Paul Rubin wrote: >> jolsen at mail2world.com (Jesper Olsen) writes: >> >>>Does python have a way of defining a dictionary default? >>>I think not, but are there any plans to incorporate it? >>> >>>Intuitively I would imagine that >>> >>>a={} >>>a.set_default(my_default) >>> >>>would do this -ie. a[my_new_key] should now return the the default >>>value my_default instead of creating an exception. >> >> >> No, instead of a[my_new_key] use a.get(my_new_key, my_default). >> That does what you want. > >Unfortunately not - get() is different, because you can not assign to it. >For instance in a dictionary which is mapping strings to integers (or >lists), I would like to do > >a[my_key]+=5 > >expressing that with get() would be awkward. > >Jesper You can however subclass dict to create something that *behaves* like a dictionary, but for unknown keys returns a default : Regards, Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html e.g. (untested - but should work) class defaultDict(dict): """A dictionary that returns a default for non-existent keys. Won't work for methods like pop unless you also define them as well.""" def __init__(self, default): dict.__init__(self) self.default = default def __getitem__(self, item): if self.has_key(item): return dict.__getitem__(self, key) else: return self.default if __name__ == '__main__': a = defaultDict(3) a['test'] = 4 print a['test'] print a['fish'] --- Everyone has talent. What is rare is the courage to follow talent to the dark place where it leads. -Erica Jong Ambition is a poor excuse for not having sense enough to be lazy. -Milan Kundera http://www.voidspace.org.uk Where Headspace Meets Cyberspace Cyberpunk and Science Resource Site Exploring the worlds of Psychology, Spirituality, Science and Computing -- http://www.fuchsiashockz.co.uk http://groups.yahoo.com/group/void-shockz http://www.learnlandrover.com From jcarlson at nospam.uci.edu Tue Mar 23 16:06:33 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Tue, 23 Mar 2004 13:06:33 -0800 Subject: problems with nltk In-Reply-To: References: Message-ID: > Traceback (most recent call last): > File "", line 1, in ? > File "/home/name/nltk-1.3/nltk/token.py", line 308 > yield self._deep_restrict(item, props, incl) Python 2.1 does not support generators. You need 2.2 or later. - Josiah From tismer at stackless.com Mon Mar 22 18:39:11 2004 From: tismer at stackless.com (Christian Tismer) Date: Tue, 23 Mar 2004 00:39:11 +0100 Subject: Slow Python - what can be done? In-Reply-To: <480e9240.0403180943.64bee13d@posting.google.com> References: <480e9240.0403180943.64bee13d@posting.google.com> Message-ID: <405F791F.8050001@stackless.com> Jason wrote: > 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. That's ok. > 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. Well, I am on this least for years now, and I know most of the answers in advance (and most have been here), so I'm not adding new stuff how to optimize this. Although in fact your inner point class raises the expenses considerably. If you need a fast algorithm right now, you need to change your program, probably by writing or using C extensions. This has always been the flip side of Python: When the real fun begins, Python is too slow. It is great on everything but speed. Advice then mostly concentrates on how to make you using something else for the time critical code. This is what we will solve by the PyPy project. We are besides other things automating a way to analyse and optimize Python programs for C-like speed. The advantage is that you can stick with your Python program. It will just be very fast, compared to, say, C. (We don't know yet *how exactly* this will compare :-) So, if you have the time, wait for two years. Or use Psyco, and rewrite your Points to use simple Tuples, or use NumPy. But please keep a copy of your initial approach. I would be very interested to see how this compares when we have the first results from our PyPy project. 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 mirrorball at interair.com.br Tue Mar 9 17:15:46 2004 From: mirrorball at interair.com.br (Carolina Feher) Date: 9 Mar 2004 14:15:46 -0800 Subject: Is this a bug? Message-ID: <4cc8f8db.0403091415.e606e29@posting.google.com> >>> def f(a): ... return 5 ... >>> class A(list): ... g = f ... def __new__(cls): ... c = list.__new__(cls, [1, 2]) ... c.g() ... return c ... >>> a = A() >>> a [] Why is an empty list returned? From michele.simionato at poste.it Mon Mar 1 03:14:48 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 1 Mar 2004 00:14:48 -0800 Subject: Feature request: subclassing FunctionType [Was: Some language proposals] References: <95aa1afa.0402262158.5b33de79@posting.google.com> Message-ID: <95aa1afa.0403010014.4222ce8e@posting.google.com> Thinking a bit more, the issue is not about the scope rules, it is about how the "for" loop is interpreted. Currently for i in iterable: is interpreted as try: it=iter(iterable) while True: i=it.next() except StopIteration: pass The issue would disappear if the "for" loop included an hidden function call and was interpreted as follows: try: it=iter(iterable) def helper(i): while True: helper(it.next()) except StopIteration: pass For instance, in the example I am talking about, def make_adders(n): return [lambda x: x+i for i in range(n)] would be interpreted as def make_adders(n): try: adders=[] it=iter(range(2)) def helper(i): adders.append(lambda x: x+i) while True: helper(it.next()) except StopIteration: return adders Essentially, the "i" variable would be passed via the helper function call and at each iteration the lambda function would see a different value of it. I am proposing nothing here, just asking if it would make sense to have a looping construct acting this way (my guess is that this has already been proposed and discussed). This would have the added benefit of avoiding a non-local loop variable (i.e. a loop variable which exists even outside the loop) which is the actual unfortunate behavior. Michele Simionato From cookedm+news at physics.mcmaster.ca Wed Mar 10 16:57:42 2004 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Wed, 10 Mar 2004 16:57:42 -0500 Subject: question: numarray c extension error handling? References: Message-ID: At some point, "Russell E. Owen" wrote: > 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."); This is ok; if PyArg_ParseTuple is NULL, no objects are created (or INCREF'd). Also, if it's not NULL, okernel is a borrowed reference; you shouldn't DECREF it. > > /* Align, Byteswap, Contiguous, Typeconvert */ > kernel = NA_IoArray(okernel, tFloat64, C_ARRAY); > ... > if (!kernel...) > return PyErr_Format( _convolveError, > "Convolve1d: error converting array inputs."); This is also ok (assuming there is nothing between this and the above which makes a reference to objects). If NA_IoArray returns NULL, there isn't anything to DECREF. > ... > Py_XDECREF(kernel); > ... > } Personally, I write it like this: static PyObject * Py_Convolve1d(PyObject *obj, PyObject *args) { PyObject *okernel,...; PyArrayObject *kernel = NULL; if (!PyArg_ParseTuple(args, "OO|O", &okernel, ...)) { PyErr_Format(_convolveError, "Convolve1d: Invalid parameters."); goto error; } kernel = NA_IoArray(okernel, tFloat64, C_ARRAY); if (!kernel...) { PyErr_Format( _convolveError, "Convolve1d: error converting array inputs."); goto error; } ...more stuff... Py_XDECREF(kernel) return the result error: Py_XDECREF(kernel) return NULL; } Notice that kernel was initialized to NULL, so Py_XDECREF will work in all cases. Clean error-handling code like this is one of the few places I use goto in C. You now have only two exits out of the function, at the bottom, and so it's _much_ easier to keep track of what needs to be DECREF'd. -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From skip at pobox.com Tue Mar 23 15:56:11 2004 From: skip at pobox.com (Skip Montanaro) Date: Tue, 23 Mar 2004 14:56:11 -0600 Subject: "The Python Robot" is going mad ? In-Reply-To: References: Message-ID: <16480.42091.110343.341483@montanaro.dyndns.org> Robert> at http://www.robotstxt.org/wc/active/html/python.html I learned Robert> the robot "The Python Robot" is maintained by www.python.org. Like amk said, "them ain't us". (Well, he said it using a more cultured Canadian dialect of English.) If you can send the IP address(es) it's coming from, one of us python.org webmaster types can almost certainly confirm that it's not coming from any of the python.org or python.net machines. To shorten your search, here are the IP addresses I know of: www.python.org (aka fang.python.org) 194.109.137.226 creosote.python.org 213.84.134.214 mail.python.org 12.155.117.29 www.python.net (aka starship.python.net) 217.160.219.194 Skip From katximan at gmx.net Mon Mar 15 13:08:38 2004 From: katximan at gmx.net (Asier) Date: 15 Mar 2004 10:08:38 -0800 Subject: fox 1.2.x and FXPy Message-ID: <4e1cc86c.0403151008.669e2e45@posting.google.com> Is there any plan to make bindings of the future fox toolkit 1.2.x for python? New widgets, antialiased fonts and so on is a "Good Thing". GTK is a pain, wxpython is horribly slow, and tkinter doesn't have good look and widgets are too basic. The bindings in http://fxpy.sf.net are very old and python 2.3 isn't supported. If you need bindings for linux it compiles without problems, but under Windows+VC6 I've had lots of problems, so after a lot of tries I've compiled the bindings of fox 1.0.51 for windows with jpeg+png+zlib support, with the mingw32 (gcc 3.3.1) suite (uffs!!!) for python 2.3.x. It seems to work reasonably well. If anyone is interested in the package I can e-mail it (tar.bz2, weights about 2MB) I've tried the tnfox bindings but they are very slow and need some non-standard libraries from msvc 7.1 and openssl. -- Asier. From danb_83 at yahoo.com Sat Mar 27 19:55:39 2004 From: danb_83 at yahoo.com (Dan Bishop) Date: 27 Mar 2004 16:55:39 -0800 Subject: Random Number References: Message-ID: talktojamesblair at yahoo.com (james blair) wrote in message news:... > Hi > I am generating a random number using > random.randint(1,10000000000) > Whats the possibility that the numbers generated will be same when > generated by 100 users at the same time? The probability that all 100 numbers will be the same is 1e-1000. But you probably wanted the probability that *any* two numbers will be the same, which is approximately 4.95e-07, or about 1 in 2 million. > Whats the best method to generate random numbers so that they are most > likely unique?? If the probability of collisions is low, use: def UniqueRandom(a, b): "Generator for random integers between a and b, inclusive." alreadyUsedNumbers = sets.Set() while True: randomNumber = random.randint(a, b) if randomNumber not in alreadyUsedNumbers: alreadyUsedNumbers.add(randomNumber) yield randomNumber If the probability of collisions is high, use: def UniqueRandom(a, b): "Generator for random numbers between a and b, inclusive." sampleSpace = range(a, b + 1) random.shuffle(sampleSpace) return iter(sampleSpace) From Robert at AbilitySys.com Mon Mar 15 19:39:32 2004 From: Robert at AbilitySys.com (Robert D. Young) Date: Mon, 15 Mar 2004 16:39:32 -0800 Subject: Controlling .idlerc Message-ID: <105cl2iju9b7j5a@corp.supernews.com> Is there a way to tell IDLE where to put the .idlerc dir? Every time I start IDLE using Python Win32 2.3.3, it puts a .idlerc dir in whatever dir I happen to be in... - Robert From skip at pobox.com Fri Mar 5 23:19:10 2004 From: skip at pobox.com (Skip Montanaro) Date: Fri, 5 Mar 2004 22:19:10 -0600 Subject: securely overwrite files with Python In-Reply-To: References: <2004030517425550073%bob@redivicom> Message-ID: <16457.20798.273176.811105@montanaro.dyndns.org> Thomas> A file system that moves around files when you overwrite them, Thomas> will only move the data blocks, not the inode. The inode will Thomas> stay the same, and in the same position on the storage device. Thanks. It's been years since I looked at any file system structures. I was indeed confusing inodes and data blocks. Skip From and-google at doxdesk.com Wed Mar 10 08:18:53 2004 From: and-google at doxdesk.com (Andrew Clover) Date: 10 Mar 2004 05:18:53 -0800 Subject: PEP 328: Imports: Multi-Line and Absolute/Relative References: <7xllm94p47.fsf@ruckus.brouhaha.com> Message-ID: <2c60a528.0403100518.d6c6094@posting.google.com> Paul Rubin wrote: >> -1.sibling_package > Ugh! Yes. Ugh indeed. > What's wrong with ../sibling_package Module paths are not filesystem paths. Emulating filesystem paths - and Unix-specific filesystem paths at that - as part of module paths is misleading and undesirable IMO. > or ../../uncle_package/cousin_package This completely reinvents module paths as Unix-style filesystem paths, with implications for cacheing the cousin_package module in the uncle_package object and so on. Too big a change for my tastes. I don't see anything wrong with a parent-package magic module name like the suggested __pkg__. It changes existing module path syntax least so could even be sort-of supported on Python <=2.3 using import hooks. It's not as if packages are usually nested deeply enough that the few extra characters of length really matter. -- Andrew Clover mailto:and at doxdesk.com http://www.doxdesk.com/ From ketulp_baroda at yahoo.com Sat Mar 6 03:43:28 2004 From: ketulp_baroda at yahoo.com (ketulp_baroda at yahoo.com) Date: 6 Mar 2004 00:43:28 -0800 Subject: Reports Message-ID: Hi I am developing web application. I have my data stored in a database.Now I want to generate a bar chart & other reports.How can I do it using python? From fletcher at worldnet.att.net Fri Mar 12 22:19:15 2004 From: fletcher at worldnet.att.net (elizabeth fletcher) Date: Sat, 13 Mar 2004 03:19:15 GMT Subject: drowning newbie References: Message-ID: Actually, I have the .pyd file (which I understand is basically a dll file) and placed it in the DLL directory in the PYTHON23 directory. In the interactive window I type "import calldll" and I get an error (ImportError: DLL load failed: The specified module could not be found) I shoudn't if the dll is installed correctly.....right? "midtoad" wrote in message news:PUu4c.39038$Up2.27668 at pd7tw1no... > elizabeth fletcher wrote: > > > Want to use Sam Rushing's calldll Python Module on a windows box. I don't > > understand how to install it. I have several books that do not detail the > > steps in installing a 3rd party module in Windows. Anybody want to throw > > me life preserver? > > the installation process depends on whether you have source code or binary. > > If it's source code, usually you unzip a package, then look for a file > called setup.py and run: > python setup.py build (this step may not be required) > and then > python setup.py install > > Your module will go into PYTHONDIR / lib/site-packages/MODULE_NAME. > > if it's a binary dll file that you have, you just copy it into the > folllowing directory: > PYTHONDIR / DLLs. > > At least that's the general approach for Python2.3. > > cheers > Stewart > From ed-no at spam-eepatents.com Thu Mar 25 16:16:05 2004 From: ed-no at spam-eepatents.com (Ed Suominen) Date: Thu, 25 Mar 2004 13:16:05 -0800 Subject: Globbing in List Search? References: <4LGdndsGmLrdv__dRVn-tw@centurytel.net> Message-ID: Your reply, particularly what's quoted below, was very helpful. Thank you. - Ed Suominen Peter Otten wrote: >>>> def index(names, pattern): > ...?????for?i,?n?in?enumerate(names): > ...?????????????if?fnmatch.fnmatch(n,?pattern): > ...?????????????????????return?i > ...?????return?-1 From python at rcn.com Fri Mar 19 16:21:32 2004 From: python at rcn.com (Raymond Hettinger) Date: Fri, 19 Mar 2004 16:21:32 -0500 Subject: SHA-based subclass for random module In-Reply-To: <20040319170506.GH1796@unpythonic.net> Message-ID: <006001c40df8$270c8940$a0ba2c81@oemcomputer> > 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? Change the plaintext line to read: plaintxt = str(Random.getrandbits(self, 128)) Now, 128 bits of input space gets digested to 128 bits and then only 53 of those bits are used in to compute the float. That should preclude the formation of an inversion table. Raymond Hettinger P.S. getrandbits(n) is new, C coded method in Py2.4 for acquiring bits directly from the underlying generator without intermediate floats and without losing threadsafety. From pinard at iro.umontreal.ca Thu Mar 4 10:33:57 2004 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Thu, 4 Mar 2004 10:33:57 -0500 Subject: vim & python In-Reply-To: <221dd125.0403032332.d4282f4@posting.google.com> References: <221dd125.0403011151.504ce09d@posting.google.com> <221dd125.0403032332.d4282f4@posting.google.com> Message-ID: <20040304153357.GA5404@titan.progiciels-bpi.ca> > > I have a bunch of questions about using python scripting in vim and > > about editing python with vim. > Thanks for all of the answers to the second question, but what about > vim scripting with python? I can not find *anything* about it (no > docs, books or tutorials) Just do: :h python in Vim, to get a compact, yet very usable description of Vim scripting capabilities. On my machine, this command displays the contents of: /usr/share/vim/vim62/doc/if_pyth.txt You might have to recompile Vim with Python-enabled, if not already. If you visit the Vim site, you might search the scripts for those based on Python extensibility, too. I wrote one such script as an exercise (but also to cover one of my needs), you might find it from my home page (see my signature), picking "FP Etc.", then looking around for "Allout-Vim". I use Python scripting of Vim very regularly, and it works wonderfully for me. I hope it will for you as well! :-) -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From wmwd2zz02 at sneakemail.com Sun Mar 14 22:25:26 2004 From: wmwd2zz02 at sneakemail.com (Greg Ewing (using news.cis.dfn.de)) Date: Mon, 15 Mar 2004 16:25:26 +1300 Subject: How to add pairs to a dict, typo corrected in this one. In-Reply-To: References: Message-ID: Avik Ghose wrote: > If you have a dict called phone_book, when you get a new name_value pair > say 'tom' you can do. > > phone_book['tom'] = 33445511; By the way, you may want to store your phone numbers as strings rather than integers, just in case any of them need to have leading zeroes... -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From csgcsg39 at hotmail.com Fri Mar 5 03:17:33 2004 From: csgcsg39 at hotmail.com (C GIllespie) Date: Fri, 5 Mar 2004 08:17:33 -0000 Subject: Parsing xml file using python References: <14b36d18.0403041649.252d2e7c@posting.google.com> Message-ID: > 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: See http://diveintopython.org/xml_processing/index.html for a nice introduction Colin From ir4u4 at yahoo.com Mon Mar 8 03:56:03 2004 From: ir4u4 at yahoo.com (Equis Uno) Date: 8 Mar 2004 00:56:03 -0800 Subject: pdb help... Message-ID: <692feddd.0403080056.564a194a@posting.google.com> Hi, I read the documentation on pdb and comprehended about 20% of it. Also I poked at google and found no answer to a question which must have been asked/answered a few times. Suppose I have a module named IamModule.py How do I set a breakpoint at line 1 and step through the lines of code? I'm sorry for such a silly question but I've been dumbed down by a Java IDE named IntelliJ. There it is easy, I click to the left of an arbitrary line to set my breakpoint and then I click on a greenBug to run code up to the breakpoint. Once it is stopped at the breakpoint I can inspect various things. Enough about Java. Back to Python... If I can just figure out how to set a breakpoint; I'll be set. I know I'm supposed to use the breakpoint command. I think maybe I'm loading my module wrong or something. thanks, -moi From cedgmon at shaw.ca Tue Mar 2 12:47:07 2004 From: cedgmon at shaw.ca (Craig Edgmon) Date: Tue, 02 Mar 2004 09:47:07 -0800 Subject: A Simple Server to Capture Single Short Requests Message-ID: <1078249626.12663.6.camel@shrek> I am working through Steve Holdens book on Python Web Development and this may seem like an obvious question, but my error states that MyRequestHandler is not defined. Any ideas on this? import SocketServer class MyRequestHandler(SocketServer.BaseRequestHandler): def handle(self): print "_____________________________" print "From: ", self.client_address print "_____________________________" input = self.request.recv(10240) print input.replace('\r', '') print "_____________________________" self.request.send("HTTP/1.1 200 OK\r\n") self.request.send("Content-Type: text/html\n\n") self.request.send("

Hello!

") self.request.close() myServer = SocketServer.TCPServer(('', 8080), MyRequestHandler) myServer.handle_request() From claird at lairds.com Wed Mar 10 19:08:30 2004 From: claird at lairds.com (Cameron Laird) Date: Thu, 11 Mar 2004 00:08:30 -0000 Subject: How to simulate a TTY with popen2? References: Message-ID: <104vbfu5bl0ekda@corp.supernews.com> In article , Tiziano Bettio wrote: >Hi Everybody, > >I'm stuck trying to write a python module for the vlc videoplayer on >linux (http://www.videolan.org). I'm using the popen2 module to open a >pipe to the program. If I open the vlc player in a shell it recognizes >that I'm running it from a TTY. >Same command with popen2-4 and the vlc doesn't seem to find a TTY so it >tries to open a gui and fails resulting in ending itself. > >So here's my question: >Is there a way to open a pipe in python imitating a TTY or am I doing >something completely wrong? > >Greetz TC Is Pexpect exactly what you want? -- Cameron Laird Business: http://www.Phaseit.net From somebody at nowhere.com Mon Mar 8 01:51:28 2004 From: somebody at nowhere.com (Sean Richards) Date: Mon, 08 Mar 2004 19:51:28 +1300 Subject: Best way to run ipython inside of emacs shell? References: <692feddd.0403072229.7d1d4675@posting.google.com> Message-ID: <87r7w3vnkf.fsf@hugin.valhalla.net> ir4u4 at yahoo.com (Equis Uno) writes: > Hi, > > I just figured out how to run python inside of emacs: > > I use meta-x shell to start a shell and then once I see a shell > prompt I enter the python command and I get a well-behaved python > shell inside of emacs. > > I'm trying to figure out the best way to run ipython inside of emacs. > > When I run the ipython shell command inside of an emacs shell it > does not act very clean (the prompt is messy looking). > > So I put two files in my /usr/share/emacs/site-lisp/ dir: > > python-mode.el > ipython.el > > I got both files from > http://ipython.scipy.org/ > > I'm not sure what to do next. > > So far I've tried this: > > -run meta-x ipython while inside of a shell buffer > -run meta-x ipython while inside of a shell buffer which is running ipython > -run meta-x ipython while inside of a python-mode buffer > > All three of the above ideas obviously don't work. > > Please post some clues. > > thanks, > > -moi I think you need to read this ... http://www.python.org/emacs/python-mode/installation.html and also read the commented section at the top of ipython.el Sean -- "Hver sin smak", sa vintapperen, han drakk mens de andre sloss. From leeg at teaching.physics.ox.ac.uk.valid Wed Mar 10 09:46:41 2004 From: leeg at teaching.physics.ox.ac.uk.valid (leeg) Date: Wed, 10 Mar 2004 14:46:41 +0000 Subject: Working around a lack of 'goto' in python References: Message-ID: Stephen Horne wrote: > On Tue, 09 Mar 2004 01:34:06 +0000, leeg > wrote: > >>Y2KYZFR1 wrote: >> >> >>> >>> No stay away from computers until you understand how and why this is. >> >>*points at the Linux kernel source* > > Examples of use are not proof that such use is a good thing. > > More relevant here, kernal programming is not the kind of job that > Python is designed for. What is justifiable in kernal programming is > not necessarily justifiable for the kinds of applications that are > written in Python. On similar principles, whats justifiable in the > Python source code is not necessarily justifiable in, errrm, Python > source code :-) > Y2kyzfr1's statement was that GOTO is a bad thing and should never be used, which is not a discussion of the lack or otherwise of a particular statement in the Python language. I agree that an example is not a good advocation. However in the case of the kernel source, if thousands of people have looked at the code and not come up with a better way to do whatever is done without a goto, then the goto method must have at least *some* merit :-). On the subject of kernel hacking and Python, why can't kernel programming be considered in Python? Because the reference implementation of the language is interpreted[1], and interpreted slowly? That's the case with Java too; however people have written Java machines in software and in hardware that are plenty fast enough to write whole operating systems in, and have goen on to write whole operating systems in them. The same could in principle be done with Python, and Python is a language in which one could principally write a whole operating system. So why should that be irrelevant in a discussion of Python? [1]"Byte compilation" is a jargontastic way of saying tokenised, then interpreted. -- Graham Lee I am leeg, for we are many "An upsettingly large part of academia right now seems to be working on bringing Java into the 1980s." - Avi Bryant http://users.ox.ac.uk/~wadh1342 From buzzard at urubu.freeserve.co.uk Mon Mar 22 09:37:50 2004 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Mon, 22 Mar 2004 14:37:50 -0000 Subject: Python / COM / Word References: Message-ID: "Tim Golden" wrote in message news:mailman.224.1079947879.742.python-list at python.org... > DS> I'm having a little trouble trying to automate Word > DS> (2002). I'm hoping to be able to create and process > DS> documents relatively independently of any existing open > DS> Word documents. > [...] > DS> Ideally I'd like to have independent 'Word instances', so I > DS> can hack around to my heart's content without jeopardising > DS> documents opened and created by some hapless user (which > DS> would also be me). > > I think this is what you want: (using Word2000, but I doubt it matters) > > > > ActivePython 2.2.3 Build 227 (ActiveState Corp.) based on > Python 2.2.3 (#42, Nov 13 2003, 09:57:55) [MSC 32 bit (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. > >>> import win32com.client > >>> w1 = win32com.client.DispatchEx ("Word.Application") > >>> w1.Visible = True > >>> # (Word Appears; New Document; scribbles a bit...) > ... w2 = win32com.client.DispatchEx ("Word.Application") > >>> w2.Visible > 0 > >>> w2.Visible = True > >>> # (second Word appears; another New doc. First one still untouched) > ... > >>> > > > > TJG > Thanks, I'll give it a go. Duncan From newsgroups at jhrothjr.com Fri Mar 26 19:35:26 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Fri, 26 Mar 2004 19:35:26 -0500 Subject: Converting IBM Floats..Help.. References: <40641706$0$133$3a628fcd@reader1.nntp.hccnet.nl> Message-ID: <1069j3h2kb44909@news.supernews.com> "Anton Vredegoor" wrote in message news:40641706$0$133$3a628fcd at reader1.nntp.hccnet.nl... > "Ian Sparks" wrote: > > > Some time ago there was a question on this group about 4-byte IBM > floats, and maybe questions about other formats will follow in the > future. Here's a flexible -but possibly slow?- approach to handle > these kind of problems. It uses a stream of bytes (a file for example) > as input and returns a series of floats. There are only the two legacy formats. More recent IBM mainframes also support standard IEEE-488 floating point, which should provide no difficulty whatsoever in converting. John Roth > Anton From NAIGIMSESRIMAIL at gims.com Wed Mar 3 11:26:08 2004 From: NAIGIMSESRIMAIL at gims.com (GroupShield for Exchange (ESRIMAIL)) Date: Wed, 3 Mar 2004 18:26:08 +0200 Subject: ALERT - GroupShield ticket number OA94_1078331159_ESRIMAIL_1 was generated Message-ID: Action Taken: The attachment was quarantined from the message and replaced with a text file informing the recipient of the action taken. To: python-list at python.org From: noreply at python.org Sent: 462019840,29622585 Subject: Notify about using the e-mail account. Attachment Details:- Attachment Name: TextDocument.zip File: TextDocument.zip Infected? Yes Repaired? No Blocked? No Deleted? No Virus Name: W32/Bagle.gen!pwdzip -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/ms-tnef Size: 1885 bytes Desc: not available URL: From ville at spammers.com Fri Mar 12 04:56:16 2004 From: ville at spammers.com (Ville Vainio) Date: 12 Mar 2004 11:56:16 +0200 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> <40515E92.3080201@nospam.uci.edu> <405185f5$0$16368$afc38c87@news.easynet.co.uk> Message-ID: >>>>> "Peter" == Peter Hickman writes: Peter> Josiah Carlson wrote: >> 3. Spend a month teaching her object orientation with C++. Peter> Perhaps Ruby for the OO stuff if you are familier with it. Less Peter> gotcha's than C++. All depends on the sort of person she is. You missed Josiah's point (at least as I understood it) - the idea was to show how painful programming can be, and then experience the revelation of switching to Python. It's a standard practice in some religious circles, where people are guided to wallow in remorse of original sins and other unpleasant stuff, and then feel the relief of divine forgiveness. As a side note, Ruby has no OO advantages over Python. This has been discussed in this newsgroup extensively. -- Ville Vainio http://tinyurl.com/2prnb From newsgroups at jhrothjr.com Wed Mar 3 16:13:09 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Wed, 3 Mar 2004 16:13:09 -0500 Subject: MVC-type Framework in Python References: Message-ID: <104cilt3l9kgv0b@news.supernews.com> "Andreas Pauley" wrote in message 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. Well, first off every toolkit "supports" MVC in the sense that you can do that pattern without an inordinate amount of pain or bending the toolkit in ways it doesn't want to go. What you want, though, is something a little different. You want a layered architecture where you can install different UI front ends. The best way I know of doing this is to create an abstract UI, and then make each of the front ends a very thin facade on that UI. It's an interesting design problem, especially since the typical user of each of the UI's probably has different needs. Part of the utility of the abstract UI is that you can write FIT fixtures that will work with it directly so that you can test out the basic application logic from the UI perspective without having to mess with the last step of dealing with the screen rendering. John Roth > > Regards, > Andreas. > > From steve at ninereeds.fsnet.co.uk Fri Mar 5 09:57:02 2004 From: steve at ninereeds.fsnet.co.uk (Stephen Horne) Date: Fri, 05 Mar 2004 14:57:02 +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> <4119c4e0d1dd457d3637e1316d5513ac@news.teranews.com> <22af40pkcecubm2o76a7g6aknj89rq1psu@4ax.com> <0370d5ccac8adfc1054d7802ef3e0ba0@news.teranews.com> Message-ID: On Fri, 05 Mar 2004 12:35:01 GMT, Dang Griffith wrote: >I understand your idea. However, the difference between a statement >and a function is exactly my point, and I see it as relevant--if any >language change is to come from this discussion. New functions can be >added via modules, and do not require changes to the language itself. >New statements require changes to the language itself, which is what >the OP is asking for. > >The [in]ability to define "custom shortcuts", with regards to >statements, is especially relevant because Python doesn't support it. >Other languages do (Ruby? et al), so someone thinks it's relevant. >It's relevant because if Python *did* support it, this thread wouldn't >be happening. (Or at least would have ended after someone >replied with "oh, just do XYZZY to make a printraw statement".) OK - sorry I didn't get that. I suspect that advocating the ability to define custom statements would be a serious uphill battle. While it allows things to be written in a different syntax, it doesn't allow for any semantics that aren't already supportable through functions. I do see the attraction, though. I wonder what would be the implications if the brackets for functions were made optional when the function is used as a statement (in the sense of not being within an expression, so that the return value will be discarded). That is... printraw (a, b, c, d) # 'printraw' used as normal function print raw (a, b, c, d) # 'raw' used as normal function printraw a, b, c, d # legal - brackets optional print raw a, b, c, d # illegal - brackets required for # 'raw' as it is used in an # expression There is the obvious ambiguity - the parser doesn't know whether you intend a single tuple argument with the no-brackets form or a conventional list of parameters in brackets. The obvious workaround is simply to assume a conventional parameter list until proven otherwise, requiring that when tuple parameters are used the programmer must resolve the ambiguity (e.g. by reverting back to normal function syntax). Alternatively, simply ban tuple displays from being used in bracket-free function calls completely. Either way, I suspect that there is too much potential for surprises. -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From littlejohn.75 at news.noos.fr Sun Mar 7 13:02:17 2004 From: littlejohn.75 at news.noos.fr (F. Petitjean) Date: 07 Mar 2004 18:02:17 GMT Subject: machine control script ( parameterless method? ) References: <340a6b1b6f65b385490e5d818b2b6c9e@news.scbiz.com> <20040306123424.20326.00000892@mb-m04.aol.com> <404a1dcd$1_1@mk-nntp-1.news.uk.worldonline.com> Message-ID: <404b63a7$0$295$626a14ce@news.free.fr> On Sat, 06 Mar 2004 simon place wrote: > [snip] > that's why the question is actually only about > getting rid of the brackets. If the action is a property, simply writing someobject.someobject can trigger a get method whithout the brackets. Regards. From news2 at mystrobl.de Fri Mar 5 18:56:34 2004 From: news2 at mystrobl.de (Wolfgang Strobl) Date: Sat, 06 Mar 2004 00:56:34 +0100 Subject: wxpython appearance differs after py2exe References: Message-ID: Chad Haynes : >Hello, > >I have a wxPython application that I want to create an executable from. > Using py2exe produces a program that works very well, but the >appearance is slightly different than when it was run from the command >line. The py2exe version is a little more bland. Here are links to >some screenshots: > >http://linkage.rockefeller.edu/chaynes/dos.jpg >http://linkage.rockefeller.edu/chaynes/py2exe.jpg > >I'm runnin winXP, any ideas? I guess your program somehow lost its ability to use the current version of ComCtl32.dll. The visual style of the Windows XP controls is implemented in comctl32.dll version 6, which is not distributable. I just noticed that there is a python.exe.manifest and a pythonw.exe.manifest in in the python23 distro. Perhaps it is sufficient to copy one of these to your py2exe dist, renaming it to .exe.manifest, on the way. Not having done anything with comctl32 et al for years, I'm just guessing here from an article I've read on MSDN. But I can't do any harm, so why not just trying it. -- Thank you for observing all safety precautions From loic at fejoz.net Thu Mar 18 09:46:19 2004 From: loic at fejoz.net (Yermat) Date: Thu, 18 Mar 2004 15:46:19 +0100 Subject: attributes of Python classes In-Reply-To: References: <3064b51d.0403171605.75ec1ba0@posting.google.com><4058F086.490C215B@alcyone.com> Message-ID: Terry Reedy a ?crit : >>>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 :-) > > > An alternative is to give attributes a default value of None as class > attributes. This avoid time and space overhead of doing same on per > instance basis. Instances only need instance-specific value when there is > one. > > class C: > a = None # what a is > b = None # what b is > > Terry J. Reedy Ya right but then the documentation will not be very clear. I was thinking of two version of my class. Let say A that does not initialize its variable because it will be done later by the file reader. And B that inherit A and initialize instance variables. In the documentation it will be easier to understand which one to use. Just ideas... Yermat From bogus at bogus.net Sat Mar 20 10:22:43 2004 From: bogus at bogus.net (Paul McGuire) Date: Sat, 20 Mar 2004 09:22:43 -0600 Subject: parsing emails References: <95aa1afa.0403200029.6859e390@posting.google.com> Message-ID: "Michele Simionato" wrote in message news:95aa1afa.0403200029.6859e390 at posting.google.com... > I use Mozilla or Netscape, so my emails are stored in the nsmail > directory > or the Mozilla's equivalent. What's the simplest way to look at them > and > extract the mails with a given subject? In principle I could use a > regular expression, but I bet there are better solutions already > available. > Second question: are Mozilla and Netscape compatible, i.e. are the > emails stored with the same format and can I use the same extraction > method on both? > > TIA, > > > Michele Simionato Michele - Python 2.3 introduced a new email package, that has an email.Parser module. I've not used it myself, but it sounds worth looking into. -- Paul From and-google at doxdesk.com Tue Mar 30 13:30:01 2004 From: and-google at doxdesk.com (Andrew Clover) Date: 30 Mar 2004 10:30:01 -0800 Subject: A couple of Python CGI questions References: <9g8ac.65379$Bg.14309@fed1read03> <2z8ac.65499$Bg.26470@fed1read03> Message-ID: <2c60a528.0403301030.29a247fb@posting.google.com> "sean" wrote: > userid = form.getfirst("userid") Yes, this the the most convenient way of using FieldStorage, in Python 2.2 upwards. > can I collect post variables in the same fashion? Yes. In a POST request, name/value pairs are read from the body; any pairs in a query string are ignored. > Is there any way to access variables from within a string like perl cgi? Sort of. The basic substitution mechanism is: ' Hello %s %s! ' % (cgi.escape(title), cgi.escape(person.name)) Or you can use named substitutions by using a dictionary: ' Hello %(title)s %(name)s! ' % { 'title': cgi.escape(title), 'name ': cgi.escape(name) } And you can get a dictionary containing local variables using locals(): t= cgi.escape(title) n= cgi.escape(name) ' Hello %(t)s %(n)s! ' % locals() This is as far as Python goes, but there are of course a million templating languages that take things up from there and which are a sensible choice for anything more complicated. [insert standard PXTL plug here. ed.] -- Andrew Clover mailto:and at doxdesk.com http://www.doxdesk.com/ From devnull at example.com Wed Mar 31 21:10:07 2004 From: devnull at example.com (Derek Fountain) Date: Thu, 01 Apr 2004 10:10:07 +0800 Subject: Using bound variables in Tkinter events References: <4067a227$0$16577$5a62ac22@freenews.iinet.net.au> <106lsh9h08hbrfa@news.supernews.com> Message-ID: <406b79a8$0$16587$5a62ac22@freenews.iinet.net.au> >> I'm coming to Tkinter from Tcl/Tk. In Tcl I can get a variable in an >> event using the % substitution mechanism. For example, I can set up a >> command like: >> >> entry .e -validate 1 -vcmd "checkkey %d" >> >> knowing that the '%d' will be replaced by something useful - whether the >> entry widget has recieved an insert or deletion in this case. The >> checkkey procedure will recieve "insert", "delete" or whatever as its >> first parameter. >> >> What is the Tkinter way of getting that %d value? > > It's in the event object that's passed as the (only) parameter > to your event handler. Everything you ever wanted to know > about the event is an attribute. The validate command doesn't get an event. > There are a number of very good references to Tkinter on > the first page of the Python Library Reference section on > Tkinter. (That's section 16 in the Python 2.3 reference) Indeed, but I couldn't find anything which answered this question. From gherron at islandtraining.com Wed Mar 24 18:47:48 2004 From: gherron at islandtraining.com (Gary Herron) Date: Wed, 24 Mar 2004 15:47:48 -0800 Subject: sorting times In-Reply-To: <4af8e6c7.0403241450.74350e21@posting.google.com> References: <4af8e6c7.0403241450.74350e21@posting.google.com> Message-ID: <200403241547.48519.gherron@islandtraining.com> On Wednesday 24 March 2004 02:50 pm, Matt wrote: > > Results: > File: two columns, \t, > pow(10, 5) lines in file. > > Bubble Sort takes 32 - 35 minutes > Quick Sort takes 8 seconds Yes, I think this is reasonable for sorting 100,000 items. The bubble sort really is that bad. (As a *general* sorting algorithm -- there are some highly specialized places where it performs rather well -- such as several graphics algorithms where only a few items are likely to out of order by only a few places.) Gary Herron From dmq at gain.com Thu Mar 11 18:44:36 2004 From: dmq at gain.com (David MacQuigg) Date: Thu, 11 Mar 2004 16:44:36 -0700 Subject: Extending Python Syntax with @ References: <3g31501dfsut81gboa43qu6bj7n37ffumr@4ax.com> Message-ID: On Thu, 11 Mar 2004 21:42:54 +0100, Peter Maas wrote: Peter Maas: >>>- The advantage is also a disadvantage: a lowered barrier for >>> new semantics could bloat the language definition. Python's >>> strength is that it has *few* concepts that are usable in *many* >>> places. This could be compromised by your proposal. David MacQuigg: >> This is actually a separate issue. Adding a few @ mods to selected >> statements does not mean that users can add their own. Peter Maas: > I assumed that in my response but also GvR and the Python community > can do too much with @. I have enormous faith in GvR and the people working with him. I can't imagine them falling into the Perl trap (overuse of symbols in a syntax). ------- Peter Maas: - Python is a readable language. lambda says "function literal", yield says "generator", @ just says "different". Python would be less readable if this notation would be adopted. David MacQuigg: Readability, in this case, is in the eye of the beholder. 'lambda' to me says 'wavelength', which I know has nothing to do with programming. I suspect many users are like me, not enough computer science background to know that lambda means 'function literal'. Peter Maas: :-)) OK, of course I was talking about the semantics within the language framework. Otherwise you could claim that def says deaf and for says four ;-) I really wasn't trying to be clever with words in telling you what comes to my mind with 'lambda'. Thinking back on my experience learning Python, I can also say that this word, and the mystique around "lambda calculus" also conveyed a subtle meaning of "complex", or "advanced topic", which caused me to avoid lambdas for a few months. I took five years of calculus in college, and I still don't see the connection between lambda functions and calculus. Let's focus on users of Python, many of whom are technical professionals, but not computer scientists. All I'm saying is that new keywords like lambda can have the opposite of the intended simplifying effect. They can make things *seem* more complex. It all depends on users perceptions and their background. I was astonished to learn today that GvR himself called for the deprecation of lambda, citing "confusing" as one of the reasons. http://python.org/doc/essays/ppt/regrets/4 This guy is a language genious, yet he still understands the ordinary users perspective. A *rare* combination. -- Dave From ivoras at __geri.cc.fer.hr Thu Mar 4 15:52:50 2004 From: ivoras at __geri.cc.fer.hr (Ivan Voras) Date: Thu, 04 Mar 2004 21:52:50 +0100 Subject: maximum element? Message-ID: What is the 'most pythonic' way of searching the largest element in a list/tuple? My 'standard' idea is: max = list[0] # or -infinity, or whatever... for i in list: if i > max: max = i While this is ok, I somehow 'feel' there could be a more concise solution... :) From nid_oizo at yahoo.com_remove_the_ Wed Mar 17 09:24:49 2004 From: nid_oizo at yahoo.com_remove_the_ (Nicolas Fleury) Date: Wed, 17 Mar 2004 09:24:49 -0500 Subject: Compare recursively objects Message-ID: Hi everyone, Is there a way to compare recursively two objects (compare their members recursively)? I'm only interested in equality or non-equality (no need for lower-than...). Thx and Regards, Nicolas From jcb at iteris.com Sat Mar 13 16:28:26 2004 From: jcb at iteris.com (MetalOne) Date: 13 Mar 2004 13:28:26 -0800 Subject: Python style guidelines References: <3064b51d.0403101112.3449e987@posting.google.com> <4050EAA3.9010807@wberry.org.x> <92c59a2c.0403122308.35513650@posting.google.com> Message-ID: <92c59a2c.0403131328.54210c30@posting.google.com> > It's that "resources acquired" part that messes people up. I've > seen it over and over and over again. Memory leaks. Dangling > pointers. Unrecoverable file handles. Especially as functions > that acquire lots of resources evolve over time and someone adds > code to acquire another resource or detect another error condition > and then doesn't find all the subsequent exit points. It's less > of an issue with languages with proper garbage collection, but it > can be a real nightmare in (e.g.) C or assembler. Unit tests that > cover all possible resource leaks are difficult to construct > correctly. C++ partially addresses the problem with RIAA (if > coders use it properly) and a hodgepodge of "smart" objects that > do pseudo self-garbage collection. > > A single exit point also gives me a fighting chance to add > something to the logical end of a function, like setting the "I'm > done" flag or logging the result. > > If I know that my function only has one exit point, then it's also > easier to add "let's see what this function is returning" > debugging code, because I know exactly where to put it and where > to look for it later when I want to take it out. In some systems, > the fact that a given function reaches its (single) exit point is > extremely valuable information. > > OTOH, I'm usually the first one to stand up at a design review and > declare that some function or some method is too long or too > complex and should be broken up *before* such problems occur. > > And that all said, I agree that a bunch of pre-checks and a quick > exit, BEFORE DOING ANYTHING ELSE, near the top of a function can > make the rest of some functions much more clear. Again, I've seen > it a million times: I'll add one more validation down here, but > forget to release that memory we just acquired up there. > Good points. With resource acquistion, I was mainly thinking along the lines of int file_compare(const char *filename1, const char *filename2) { FILE *infile1 = fopen(filename1, "r"); FILE *infile2 = fopen(filename2, "r"); if (!infile1 || !infile2) { // error if (infile2) fclose(infile2); if (infile1) fclose(infile1); return FAILURE; } // compare files return SUCCESS } as opposed to int file_compare(const char *filename1, const char *filename2) { int result = SUCCESS; FILE *infile1 = fopen(filename1, "r"); if (infile1) { FILE *infile2 = fopen(filename2, "r"); if (infile2) { // compare files } else { result = FAILURE; } } else { result = FAILURE; } if (infile2) fclose(infile2); if (infile1) fclose(infile1); return result; } From imbosol at aerojockey.invalid Sat Mar 20 19:55:17 2004 From: imbosol at aerojockey.invalid (Carl Banks) Date: Sun, 21 Mar 2004 00:55:17 GMT Subject: [OT] Compilable Python-like language? References: Message-ID: Peter Hansen wrote: > > > 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. Asking for more information wasn't what bothered me. It seemed to me that Pinard's reply (whether he intended it or not) presumed that the OP didn't know what he was talking about, and was misguided for even asking it. I absolutely hate when people do that to me, and take offense when it happens to others. This case especially bothered me because the OP was clearly knowledgable about programming. I'm not against asking for more information to give a better answer, but just second guessing people and telling them they don't really want what they're asking for (which is the impression I got from Pinard's reply, whether he intended it or not) gets under my skin. > 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, No offense, but you appear to be presuming that simply answering the question he asked wasn't useful to him. > 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. I'm ok with that, and I'm all for helping people get their thinking right. I just don't like the "WE CAN'T HELP YOU UNLESS YOU TELL US WHAT YOU'RE TRYING TO DO" attitude, when all the guy wants is a simple answer to his question. You know what? I'd like to have a fast, compiled language that looks like Python, too. ok-rant-over-ly yr's -- 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 cookedm+news at physics.mcmaster.ca Tue Mar 30 15:09:41 2004 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Tue, 30 Mar 2004 15:09:41 -0500 Subject: warning: "_POSIX_C_SOURCE" redefined References: Message-ID: At some point, Marc Schellens wrote: > Including Python.h I got the following warining > > warning: "_POSIX_C_SOURCE" redefined > > in Python.h: > > #define _POSIX_C_SOURCE 200112L > > in features.h (included from string): > > # define _POSIX_C_SOURCE 199506L > > Is there a (potential) problem with this? There's no problem, but to get rid of the warning, check that "Python.h" is the _first_ thing included (before system headers, such as "stdio.h"). _POSIX_C_SOURCE is something that's defined by the user to tell the runtime what version of the POSIX standard to use. From the comments at the top of my features.h : /* These are defined by the user (or the compiler) to specify the desired environment: __STRICT_ANSI__ ISO Standard C. _ISOC99_SOURCE Extensions to ISO C89 from ISO C99. _POSIX_SOURCE IEEE Std 1003.1. _POSIX_C_SOURCE If ==1, like _POSIX_SOURCE; if >=2 add IEEE Std 1003.2; if >=199309L, add IEEE Std 1003.1b-1993; if >=199506L, add IEEE Std 1003.1c-1995 -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From jacek.generowicz at cern.ch Mon Mar 22 03:58:05 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 22 Mar 2004 09:58:05 +0100 Subject: [OT] Compilable Python-like language? References: Message-ID: Ed Cogburn writes: > I'm just curious if such a beast exists out there. That rather depends on what you mean by "Python-like". This could mean any of: - Has significant whitespace - Defined by an open source implementation - Dynamic - Multi-paradigm - Byte-code compiled - Highly portable - Simple, highly intuitive syntax - Ugly inconsistent syntax ... and lots more. Secondly, it also depends on what you mean by compilable. Any language is compilable. Perhaps you are asking whether a language meeting you requirements (whatever they be) already has an existing implementation with a compiler. (Python does. Oh, you didn't mean byte-compliation? ... well Python does have a binary compiler; it's called psyco. It has quite a number of limitations, but it does exist.) Assuming that you really _do_ mean "compiling to native binary", it's still not clear exactly what you mean by that. Do you mean "produce stand-alone binary executables"? If so, then you should note at least two things: a) Creating stand-alone executables is _not_ a necessary condition for compilation to native binary. b) Most "stand-alone binary executables" aren't stand-alone. > without the advanced dynamic and OO features would still be > interesting to me (indeed, it would really have to lose most of the > dynamic characteristics in order to make it a compilable language, > which is why we don't have compile-to-binary Python, right?). Nothing could be farther from the truth. Languages in the Lisp family have all the dynamicity of Python and then some, and have had native compilers for over 2 decades. (I recommend looking at Common Lisp, if you want to know more. Scheme would be another modern alternative, in that family.) > Is there such a thing? No way to answer your question without a clearer statement of what your question actually means. From lbates at swamisoft.com Tue Mar 2 11:40:48 2004 From: lbates at swamisoft.com (Larry Bates) Date: Tue, 2 Mar 2004 10:40:48 -0600 Subject: Modifying escape sequences in strings References: Message-ID: The problem is that the backslash (\) has special meaning to Python. It means that the next character is escaped (has special meaning). Try following: x=x.replace("\\n","\n") This works for me. -Larry "Thomas Philips" wrote in message news:b4a8ffb6.0403020814.283e64d6 at posting.google.com... > I have been playing around with reading strings with embedded escape > sequences from files both using readline() and codecs.open() and have > a question.I create a file "test.txt" with exactly one line: > 1\na\n\n2\n\n3 > > I then open test.txt and then read it using readline(): > >>> input_file=file("test.txt") > >>> x=input_file.readline() > > >>> x > >>> 1\\na\\n\\n2\\n\\n3 > >>> print x > >>> 1\na\n\n2\n\n3 > > The readline has escaped the backslashes, so that they print > correctly. I tried to replace the double backslashes with single > backslashes to escape the "n" > >>> x.replace("\\","\") > > SyntaxError: EOL while scanning single-quoted string > >>> > > How can I replace the escaped backslash with a backslash? I realize > that I can solve the problem by reading the file using > codecs.open("test.txt","r","string_escape") as suggested by Peter > Otten. I'm trying to do the same thing in different ways to better > understand Python > > Sincerely > Thomas Philips From barry at python.org Wed Mar 3 20:26:42 2004 From: barry at python.org (Barry Warsaw) Date: Wed, 03 Mar 2004 20:26:42 -0500 Subject: testing - please ignore Message-ID: <1078363602.7636.148.camel@anthem.wooz.org> This is a test message, please ignore. -Barry From dontbotherworld at yahoo.com Wed Mar 10 02:56:13 2004 From: dontbotherworld at yahoo.com (dont bother) Date: Tue, 9 Mar 2004 23:56:13 -0800 (PST) Subject: Okay Heres the problem: in Index In-Reply-To: Message-ID: <20040310075613.56450.qmail@web60806.mail.yahoo.com> Hey Miki, I have to do this for everyword that is occuring. Its not that , that I have to do this only for the word "syntax". How can I do this for every word. I want a general solution that can work. Any ones game for this? Thanks A ton though, Dont > > 1. The numbers 0, 1, 2, 3, that are in the output > of > > the vector.py are the corresponding position of > the > > words in the email_message, that I ran against the > > dictionary_index. I want the index of the > > corresponding word in the dictionary. For example: > If > > "syntax" was occuring in the dictionary at 500. I > want > > the 500 syntax instead of 6 syntax > > that I am getting right now. > When you load the dictionary just remember the line > of each "syntax" and > print it later. > > --- *not tested* --- > syntax = {} > lines = {} > for lnum, line in enumerate(open("dictionary.txt")): > val, syn = line.strip().split(":") > syntax[syn] = long(val) > lines[syn] = lnum > --- > > > 1 index value index value index value index value > > index value > I don't see the problem here. > > HTH. > Miki > -- __________________________________ Do you Yahoo!? Yahoo! Search - Find what you?re looking for faster http://search.yahoo.com From skip at pobox.com Tue Mar 23 12:02:06 2004 From: skip at pobox.com (Skip Montanaro) Date: Tue, 23 Mar 2004 11:02:06 -0600 Subject: PEP 318 - posting draft Message-ID: <16480.28046.500125.309554@montanaro.dyndns.org> Here's the current state of PEP 318. I have to take a break from this to get some real work done and may not get back to it in a major way for awhile. I received a significant rewrite of Kevin Smith's most recent version from Jim Jewett and incorporated much of what he wrote, modifying a lot of it along the way, but have still not digested everything he sent me. I've tried to reflect the concensus which seems to be emerging on the python-dev list, though I suspect I've done a poor job of that. The discussions there and on comp.lang.python have ranged far and wide and thus resist summary in a finite amount of time. I recommend interested comp.lang.python readers spend some time in the python-dev archives for February and March if they find major fault with the current state of the proposal. If you post corrections or comments to either list I should see them. Skip Montanaro ------------------------------------------------------------------------------ PEP: 318 Title: Function/Method Decorator Syntax Version: $Revision: 1.5 $ Last-Modified: $Date: 2004/03/23 16:41:17 $ Author: Kevin D. Smith , Jim Jewett , Skip Montanaro Status: Draft Type: Standards Track Content-Type: text/x-rst Created: 05-Jun-2003 Python-Version: 2.4 Post-History: 09-Jun-2003, 10-Jun-2003, 27-Feb-2004, 23-Mar-2004 Abstract ======== The current method for declaring class and static methods is awkward and can lead to code that is difficult to understand. Ideally, these transformations should be made at the same point in the code where the declaration itself is made. This PEP introduces new syntax for transformations of a declaration. Motivation ========== The current method of applying a transformation to a function or method places the actual translation after the function body. For large functions this separates a key component of the function's behavior from the definition of the rest of the function's external interface. For example:: def foo(self): perform method operation foo = classmethod(foo) This becomes less readable with longer methods. It also seems less than pythonic to name the function three times for what is conceptually a single declaration. A solution to this problem is to move the transformation of the method closer to the method's own declaration. While the new syntax is not yet final, the intent is to replace:: def foo(cls): pass foo = synchronized(lock)(foo) foo = classmethod(foo) with an alternative that places the decoration in the function's declaration:: def foo(cls) using [synchronized(lock), classmethod]: pass Background ========== There is general agreement that syntactic support is desirable to the current state of affairs. Guido mentioned `syntactic support for decorators`_ in his DevDay keynote presentation at the `10th Python Conference`_, though `he later said`_ it was only one of several extensions he proposed there "semi-jokingly". `Michael Hudson raised the topic`_ on ``python-dev`` shortly after the conference, attributing the bracketed syntax to an earlier proposal on ``comp.lang.python`` by `Gareth McCaughan`_. .. _syntactic support for decorators: http://www.python.org/doc/essays/ppt/python10/py10keynote.pdf .. _10th python conference: http://www.python.org/workshops/2002-02/ .. _michael hudson raised the topic: http://mail.python.org/pipermail/python-dev/2002-February/020005.html .. _he later said: http://mail.python.org/pipermail/python-dev/2002-February/020017.html .. _gareth mccaughan: http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&oe=UTF-8&selm=slrna40k88.2h9o.Gareth.McCaughan%40g.local Design Goals ============ The new syntax should * work for arbitrary wrappers, including user-defined callables and the existing builtins ``classmethod()`` and ``staticmethod`` * work with multiple wrappers per definition * make it obvious what is happening; at the very least it should be obvious that new users can safely ignore it when writing their own code * not make future extensions more difficult * be easy to type; programs that use it are expected to use it very frequently * not make it more difficult to scan through code quickly. It should still be easy to search for all definitions, a particular definition, or the arguments that a function accepts * not needlessly complicate secondary support tools such as language-sensitive editors and other "`toy parser tools out there`_" .. _toy parser tools out there: http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&oe=UTF-8&selm=mailman.1010809396.32158.python-list%40python.org Proposed Syntax =============== The currently proposed syntax is:: def func(arg1, arg2, ...) [dec1, dec2, ...]: pass The decorators are near the declaration of the function's API but are clearly secondary. The square brackets make it possible to fairly easily break long lists of decorators across multiple lines. Alternate Proposals =================== A few other syntaxes have been proposed:: def func(arg1, arg2, ...) as dec1, dec2, ...: pass The absence of brackets makes it cumbersome to break long lists of decorators across multiple lines. The keyword "as" doesn't have the same meaning as its use in the ``import`` statement. :: def [dec1, dec2, ...] func(arg1, arg2, ...): pass This form has the disadvantage that the decorators become visually higher priority than the function name and argument list. :: def func [dec1, dec2, ...] (arg1, arg2, ...): pass Quixote's Page Template Language uses this form, but only supports a single decorator chosen from a restricted set. For short lists it works okay, but for long list it separates the argument list from the function name. :: using: dec1 dec2 ... def foo(arg1, arg2, ...): pass The function definition is not nested within the using: block making it impossible to tell which objects following the block will be decorated. Nesting the function definition within the using: block suggests block structure that doesn't exist. The name ``foo`` would actually exist at the same scope as the using: block. Finally, it would require the introduction of a new keyword. Current Implementation ====================== Michael Hudson has posted a `patch`_ at Starship, which implements the proposed syntax and left-first application of decorators:: def func(arg1, arg2, ...) [dec1, dec2]: pass is equivalent to:: def func(arg1, arg2, ...): pass func = dec2(dec1(func)) though without the intermediate creation of a variable named ``func``. .. _patch: http://starship.python.net/crew/mwh/hacks/meth-syntax-sugar.diff Examples ======== Much of the discussion on ``comp.lang.python`` and the ``python-dev`` mailing list focuses on the use of the ``staticmethod()`` and ``classmethod()`` builtins. This capability is much more powerful than that. This section presents some examples of use. 1. Define a function to be executed at exit. Note that the function isn't actually "wrapped" in the usual sense. :: def onexit(f): import atexit atexit.register(f) return f def func() [onexit]: ... 2. Define a class with a singleton instance. Note that once the class disappears enterprising programmers would have to be more creative to create more instances. (From Shane Hathaway on ``python-dev``.) :: def singleton(cls): return cls() class MyClass [singleton]: ... 3. Decorate a function with release information. (Based on an example posted by Anders Munch on ``python-dev``.) :: def release(**kwds): def decorate(f): for k in kwds: setattr(f, k, kwds[k]) return f return decorate def classmethod(f) [release(versionadded="2.2", author="Guido van Rossum")]: ... 4. Enforce function argument and return types. :: def accepts(*types): def check_accepts(f): def new_f(*args, **kwds): for (a, t) in zip(args, types): assert isinstance(a, t), \ "arg %r does not match %s" % (a,t) return f(*args, **kwds) assert len(types) == f.func_code.co_argcount return new_f return check_accepts def returns(rtype): def check_returns(f): def new_f(*args, **kwds): result = f(*args, **kwds) assert isinstance(result, rtype), \ "return value %r does not match %s" % (result,rtype) return result return new_f return check_returns def func(arg1, arg2) [accepts(int, (int,float)), returns((int,float))]: return arg1 * arg2 Of course, all these examples are possible today, though without the syntactic support. Possible Extensions =================== The proposed syntax is general enough that it could be used on class definitions as well:: class foo(object) [dec1, dec2, ...]: class definition here Use would likely be much less than function decorators. The current patch only implements function decorators. Copyright ========= This document has been placed in the public domain. Local Variables: mode: indented-text indent-tabs-mode: nil sentence-end-double-space: t fill-column: 70 End: From fumanchu at amor.org Sat Mar 13 15:33:51 2004 From: fumanchu at amor.org (Robert Brewer) Date: Sat, 13 Mar 2004 12:33:51 -0800 Subject: need optimizing help Message-ID: rabbits77 wrote: > I have a dictionary with a very very large(possibly millions) of > key/value pairs. > The key is a tuple that looks like (id,date) > What is the fastest way to get out all of the values that match any > key given that they individual key elements are coming from two > seperate lists? > The approach of > for id in IDS: > for date in dates: > data=myDict[(id,date)] > > seems to just take too long. Is there a speedier, more pythonic, way > of doing this? Any help speeding this up would be much appreciated!! If you're willing to handle some minor side-effects, one common approach is an index layer via a nested dict; that is, instead of: myDict[(id, date)] = value ...you execute: myIndex.setdefault(id, {})[date] = value You would then grab values via: for id in IDS: bucket = myIndex[id] for date in dates: data = bucket[date] The proof is in the pudding: ----indextest.py---- def flatdict(): flat = {} for id in range(1000): for date in range(1000): flat[(id, date)] = 'notlob' return flat def grab_flat(myDict): for id in range(475, 525): for date in range(990, 1000): data = myDict[(id, date)] def indexdict(): index = {} for id in range(1000): for date in range(1000): index.setdefault(id, {})[date] = 'notlob' return index def grab_index(myDict): for id in range(475, 525): for date in range(990, 1000): data = myDict[id][date] PythonWin 2.3.2 (#49, Oct 2 2003, 20:02:00) [MSC v.1200 32 bit (Intel)] on win32. Portions Copyright 1994-2001 Mark Hammond (mhammond at skippinet.com.au) - see 'Help/About PythonWin' for further copyright information. >>> import timeit >>> t1 = timeit.Timer("fd = i.flatdict()", "import indextest as i") >>> t2 = timeit.Timer("idx = i.indexdict()", "import indextest as i") >>> t3 = timeit.Timer("i.grab_flat(fd)", "import indextest as i; fd = i.flatdict()") >>> t4 = timeit.Timer("i.grab_index(idx)", "import indextest as i; idx = i.indexdict()") >>> t1.timeit(1) 15.798860190331453 >>> t2.timeit(1) 1.3386880176111617 >>> t3.timeit(1000) 0.5080377534016236 >>> t4.timeit(1000) 0.36944779294577756 Robert Brewer MIS Amor Ministries fumanchu at amor.org From jsbenson at bensonsystems.com Sat Mar 6 16:29:53 2004 From: jsbenson at bensonsystems.com (John Benson) Date: Sat, 6 Mar 2004 13:29:53 -0800 Subject: ELF object file analysis tool in Python? Message-ID: <021c01c403c2$29e886e0$210110ac@jsbwxp3> Thanks, but I'm looking to analyze an ELF file from a Tandem Himalaya platform, but using Python on Windows XP. I'm hoping there's enough standardization to the ELF format that I can pick it apart with an existing tool regardless of the particular instruction set. Message: 12 Date: Wed, 03 Mar 2004 09:56:21 +0200 From: Miki Tebeka Subject: Re: ELF object file analysis tool in Python? To: python-list at python.org Cc: python-list at python.org Message-ID: <40458FA5.40807 at zoran.com> Content-Type: text/plain; charset=us-ascii; format=flowed Hello John, > I already googled and only turned up some references dating from 2000. > Anybody know of any current Python tool that can open up and dissect > information from an ELF (Executable and Linking Format) object file? I don't > care about machine language stuff, but goodies like what sources were used > in the compile, and what routines are used. Just parse the output of `objdump -g'. Note that some compiler (such as MSVC) save the debug information in a different file (.pdb). HTH. Miki From skip at pobox.com Wed Mar 3 12:14:36 2004 From: skip at pobox.com (Skip Montanaro) Date: Wed, 3 Mar 2004 11:14:36 -0600 Subject: Backing up objects in db file In-Reply-To: References: Message-ID: <16454.4732.377651.814955@montanaro.dyndns.org> Chris> I have a program that stores all its data as pickled objects Chris> inside a (berkeley) db file. Chris> Having been bitten a couple of times when the format changed Chris> across linux distribution upgrades, I'd like to write a simple Chris> program that dumps the objects to some kind of text format, which Chris> can then be reconstituted into objects later. It can't just dump Chris> out the pickle format, because that could change between python Chris> versions. Take a look at db2pickle.py and pickle2db.py in the Tools/scripts directory of the source distribution. I have no idea if they are included in the Windows installer. Here's the doc string from db2pickle.py: Synopsis: db2pickle.py [-h|-g|-b|-r|-a] dbfile [ picklefile ] Convert the database file given on the command line to a pickle representation. The optional flags indicate the type of the database (hash, btree, recno). The default is hash. If a pickle file is named it is opened for write access (deleting any existing data). If no pickle file is named, the pickle output is written to standard output. Looking at that I can see I need to update the doc string. The flags mean: -h - open as bsddb hash file -g - open as gdbm file -b - open as bsddb btree file -r - open as bsddb recno file -a - open using anydbm Skip From ark at acm.org Mon Mar 29 12:12:42 2004 From: ark at acm.org (Andrew Koenig) Date: Mon, 29 Mar 2004 17:12:42 GMT Subject: No built-in swap function? Message-ID: I am looking for the most effective way to exchange v[i] and v[j], and expected to find something like v.swap(i, j) but it doesn't seem to exist. Is there anything better than v[i], v[j] = v[j], v[i] (which I don't like particularly because it evaluates each of v[i] and v[j] twice)? From Mike at DeleteThis.Geary.com Sat Mar 13 00:24:37 2004 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Fri, 12 Mar 2004 21:24:37 -0800 Subject: drowning newbie References: Message-ID: <10556om5sfgic0@corp.supernews.com> elizabeth fletcher wrote: > Actually, I have the .pyd file (which I understand is basically a dll file) > and placed it in the DLL directory in the PYTHON23 directory. In the > interactive window I type "import calldll" and I get an error (ImportError: > DLL load failed: The specified module could not be found) I shoudn't if > the dll is installed correctly.....right? >From what I see on his site, Sam hasn't updated calldll.pyd in quite some time. The version available for download is linked against Python 2.1 and won't work with Python 2.3. There's a great free tool for Windows called Dependency Walker that will inspect any EXE or DLL file and show you all of the other DLLs that file depends on. Running Dependency Walker on calldll.pyd showed a dependency on PYTHON21.DLL. http://www.dependencywalker.com/ So back to the original problem, which you didn't mention: What is it you are trying to do? There may be other, more up to date approaches you could look at. -Mike From rogerb at rogerbinns.com Mon Mar 8 19:11:07 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Mon, 8 Mar 2004 16:11:07 -0800 Subject: Working around a lack of 'goto' in python References: Message-ID: > I believe you'd be able to get the same benefit from goto - > nearly identical solution, really. Yes, break and continue of one or more levels can be written using gotos. 'for' loops can be written using 'while'. > Of course it can be used > a lot of other ways, but you couldn't really argue that's a > bad thing, given your position stated above. I never did argue it is a bad thing. I am not the OP. The OP has a problem with a lack of goto in Python, when what they seemed to be trying to express was breaks and continues out of multiple levels of nested loops. I pointed out that instead of goto (which would require a new language features) break/continue with labels or numbers (which would require new language features) could be used and they more clearly express what the programmer is trying to do. I was also showing that the current situation (introducing variables, using exceptions) is an acceptable work around but is just as error prone as break/continue. goto is less error prone, but is considered a bad thing for many other reasons. > I mean, either > Python should incorporate all features that someone finds > useful, and leave taste and judgement to the user, or it > shouldn't. That is a tautology. Python has a set of features as determined by BDFL influenced by the community. It is very clear on helping the programmer directly express what they mean. That is why it has 'for' loops even though 'while' would suffice. That is why it has multiple-inheritance although that is not necessary. It doesn't have a way of direclty expressing break/continue out of multiple levels of nested loops. The OP is used to expressing that in C using goto. Python people are used to introducing extra variables and/or exceptions. Other languages let you use labelled or numbered break/continues. I do believe some standard code pattern would be useful, based on having needed to do it myself a non-trivial number of times in my own code. Other posters have also needed to do the same as they came out with their ways of expressing it (although most only showed break and not continue). I don't actually care what the code pattern is. Maybe it is introducing gotos, or named/labelled break/continue, or the status quo. I am still stuck with Python 2.2 code. Having this addressed would be nice, but sadly it will be a few years before I could use it. Roger From jcarlson at nospam.uci.edu Tue Mar 23 15:27:42 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Tue, 23 Mar 2004 12:27:42 -0800 Subject: Can this be done with python? In-Reply-To: <8ee9ed23.0403231007.5805e675@posting.google.com> References: <8ee9ed23.0403231007.5805e675@posting.google.com> Message-ID: > I found out python may be a good language to learn for a beginner. I > do wonder however if the following can be done in a created gui: > > -have a button opening a 'open file' dialog, eg when I need a user to > search for an image Yeah, this is a standard dialog for most GUI toolkits that work with Python. Check wxPython, tk, PyGTK and PyQT. > -create a tree that can be adjusted by the user (eg adding a branch) Of course. > -the gui builders, can they create windows xp style I can skin with eg > stylexp or another skinning program? Don't know, never needed to. - Josiah From mday at apple.com Wed Mar 24 19:03:25 2004 From: mday at apple.com (Mark Day) Date: Wed, 24 Mar 2004 16:03:25 -0800 Subject: State of Python scripting on Mac OS X? References: Message-ID: <240320041603254532%mday@apple.com> In article , Francis Avila wrote: > I just got a Mac, and I want to script it using Python. You ought to subscribe to the pythonmac list and ask again there. See . > Python needs an OSA scripting component to be an OSA-compliant language. Having an OSA scripting component would allow you to substitute a Pyhton-like syntax for the AppleScript syntax, and let them be used interchangeably wherever an AppleScript script could be used (for example, to attach to a menu item in an "attachable" application). It would make Python show up as a choice in Script Editor. That would be incredibly powerful, but may be more than you really need. If all you want to do is write Python scripts/applications that control other applications, that's a much easier problem. Python can access the AppleEvent APIs so you can send AppleEvents to other applications (to control them). There are two people pretty actively working on making AppleEvent scripting work more naturally with Python. Definitely ask on the pythonmac list. -Mark From crap1234 at hotmail.com Tue Mar 23 07:35:52 2004 From: crap1234 at hotmail.com (Stefan Axelsson) Date: Tue, 23 Mar 2004 13:35:52 +0100 Subject: [OT] Compilable Python-like language? In-Reply-To: References: Message-ID: Ed Cogburn wrote: > Or maybe its just > because I'm lazy and will fall in love with any lean, terse, yet > powerful language that comes along. :) However, we all know that for > some applications/purposes, Python isn't fast enough. Hi, well, since you didn't mention psyco it probably should. Doesn't rid you of the interpreter (and you mention that below), but increases the speed by a fair amount. It enabled me to keep the "algorithmic" code in Python without having to drop to 'C' or Pyrex, gaining a speedup of about a factor 100. (This for a bayesian classifier). Though typical speedup is more on the order of 2-4 times. > For me, ocaml is the > real surprise, it scores the same as gcc (on the Linux side, see the > link below). Its not Python-like, of course, but I'm surprised to see > any other language score as well as gcc on a *nix system (gcc being born > on *nix, being one of the oldest and most heavily used and beaten-on > languages, as well as being optimized to death). Well, depends on what you mean by "Python like" (here we go again). I'd say that it has quite a number of features that are similar to the ones that attracted me to Python (from O'Caml incidentally). Such as; mostly functional but with imperative support integral to the language (doesn't feel it's been bolted on afterwards), support for object oriented programming, relatively small and straightforward to learn. Differences are that it has pattern matching (plus imho), a type inferring type system (a plus imho, but you can have different opinions on that), and the syntax (which I don't much care for to be honest). And a compiler that produces native code that's quite good (though there's also a bytecode interpreter). You might want to give it a spin, there are several short tutorials available, and a book online as well (http://www.ocaml.org). If the type system upsets you, as it has a tendency to do to some, then Erlang might fit the bill. It's more similar to O'Caml than Python, but still shares (most of) the traits mentioned above, save for a dynamic type system. It's mostly a byte code language though, but there is a compiler (HiPE) included in the distribution. It's more akin to psyco than ocamlopt though. Industrial strength; at Ericsson we have several projects weighing in at a few million lines that outdo our competition. Has unique support for multi processing (loosely coupled) and fault tolerance. You might want to have a look: (http://www.erlang.org). Now, since we're into 'functional' languages (and you confess to mostly being anoyed by the LISP syntax than anything else), let me plug Haskell also, even though we've now moved quite far away from Python. Purely functional, lazy evaluation, nice (interactive) compiler available (GHC), though performance perhaps isn't as easy to achive as with O'Caml. If you're interested there's more at http://www.haskell.org. All these are freely avaliable (both as in gratis and libre; the latter more or less). Whether you'd call 'Python like' is an open question. They don't fit all of your original criteria, though there are perhaps more similarities than first meets the eye. Stefan, -- Stefan Axelsson From informlant at citenet.net Mon Mar 1 13:10:00 2004 From: informlant at citenet.net (jeuxal_com) Date: Mon, 1 Mar 2004 19:10:00 +0100 Subject: Minimal distro requirements for standalone python program.... Message-ID: Hi, I need to add a python program (web updater+extras) with a window application. The same thing as the Online Lord of the Ring game lotrtcg.decipher.com. When you install their application, it create a subdirectory with very few python files*.dll,*.pyd,*.pyc.: _socket.pyd _sre.pyd _tkinter.pyd (laucher.pyc) (lotrotcglaucher.exe) python22.dll PyWinTypes22.dll tcl83.dll tk83.dll win32api.pyd xlib.pyd _MEI\... Context: I want to add some python capabilities to my application, but not force the user to install the full python distro. Questions: 1- Are these files sufficient? (Too simple to be true!) 2- Is their some registry/path entries do perform to setup a minimal python runtime? Other ideas, examples of how to do it in a simple way? Thanks AL From wmwd2zz02 at sneakemail.com Thu Mar 11 22:50:43 2004 From: wmwd2zz02 at sneakemail.com (Greg Ewing (using news.cis.dfn.de)) Date: Fri, 12 Mar 2004 16:50:43 +1300 Subject: Newby Question: Python and A Nested Dictionary In-Reply-To: <_G84c.1393$P45.950@fe1.columbus.rr.com> References: <_G84c.1393$P45.950@fe1.columbus.rr.com> Message-ID: kbass wrote: > I am new to Python and I am attempting to retrieve data from a database and > I would like to place this data into a nested dictionary. After placing the > data into a dictionary, I would like to loop through the data using for > loops. How would I do this? It's hard to say exactly how to go about building the dictionary without knowing more about the format of the data and how you want to structure it. Posting some sample data together with the dict you want to build from it would help. As for looping over the dictionaries, some general facts you might find useful are: for key in dictionary: ... will loop over all the keys in the dictionary. for value in dictionary.values(): ... will loop over the values (but you won't know what their keys were). for key, value in dictionary.items(): ... will loop over all the key/value pairs in the dictionary. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From tdelaney at avaya.com Tue Mar 30 17:27:33 2004 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Wed, 31 Mar 2004 08:27:33 +1000 Subject: Prothon Prototypes vs Python Classes Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE01536140@au3010avexu1.global.avaya.com> > From: Carl Banks > > Right. Then we can have "does the brace go on the same line or the > next line" wars. int main (void) { if (true) { } return 0; } There is no other way. Tim Delaney From http Tue Mar 23 18:17:45 2004 From: http (Paul Rubin) Date: 23 Mar 2004 15:17:45 -0800 Subject: What's missing from python? References: <405ee0d0$0$63627$5a6aecb4@news.aaisp.net.uk> <405ff7f4$0$63620$5a6aecb4@news.aaisp.net.uk> Message-ID: <7xisgvcfvq.fsf@ruckus.brouhaha.com> Dennis Lee Bieber writes: > I could see government restrictions on what was allowed for > encryption... Too strong, and the implementation can't be "exported" out > of the US... Which puts you into the situation of having to > create/control a US-legal package vs an export-legal package. That problem went away about 5 years ago. There are no more separate domestic and export versions of Netscape or MSIE, for example. There appears to be concern about countries which aren't allowed to IMPORT cryptographic programs. Of course, those countries also aren't allowed to import most current web browsers, so downloading from python.org may be a little problematic for them. From nwirth at myrealbox.com Tue Mar 9 12:22:20 2004 From: nwirth at myrealbox.com (NWirth) Date: 9 Mar 2004 09:22:20 -0800 Subject: Python scripting for GNumeric Message-ID: 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. It might be possible to have them "cross the lines" and have them using Gnumeric if they would have a powerfull scripting language they could use along with Gnumeric to replace Excel and VBA. Since I am not experienced neither with Gnumeric nor with Pythion, I am posting my question here: How mature is the above mentioned combination (Gnumeric & Python) compared with Excel and VBA? Is it possible to run Gnumeric using Python extensions on Windows? Thank you for your time and effort replying to this post. NWirth From dmq at gain.com Tue Mar 16 20:55:46 2004 From: dmq at gain.com (David MacQuigg) Date: Tue, 16 Mar 2004 18:55:46 -0700 Subject: Result of ``a is b'' References: <40200384.0403151632.35496ee6@posting.google.com> <40200384.0403161255.7fca7a8c@posting.google.com> Message-ID: On Tue, 16 Mar 2004 18:00:04 -0500, cookedm+news at physics.mcmaster.ca (David M. Cooke) wrote: >Personally, almost all my uses of 'is' are of the form 'x is None' or >'x is not None'. Here are some more test results (averaging 10,000 evaluations in a tight loop): time (sec) % Test 1: 3.68E-007 100.0 F is False Test 2: 4.87E-007 132.1 F == False Test 3: 3.71E-007 100.0 N is None Test 4: 5.51E-007 148.6 N == None The '== None' test is 49% slower than 'is None', but in absolute time, the difference is only 180nec (on my new, but not top-speed PC). So it would take about 10 million of these comparisons in a short time to make a noticable difference to the user. I can't see where the 'is' test would *ever* be needed for the above comparisons. -- Dave From ZZZ-ialbert-ZZZ at mailblocks-ZZZ.com-ZZZ Fri Mar 12 13:53:56 2004 From: ZZZ-ialbert-ZZZ at mailblocks-ZZZ.com-ZZZ (Istvan Albert) Date: Fri, 12 Mar 2004 13:53:56 -0500 Subject: root password in a .py script In-Reply-To: References: Message-ID: 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: > > pass = "#$%^&@*#&*$^@" > instead of: > pass = "root-password" Why do you need it decoded? You could list the encrypted root password and then if the input password encrypts to the same thing then it means it was a valid one. i. From dippyd at yahoo.com.au Thu Mar 18 21:45:29 2004 From: dippyd at yahoo.com.au (Steve) Date: Fri, 19 Mar 2004 13:45:29 +1100 Subject: Result of ``a is b'' References: <38ec68a6.0403171642.7199763c@posting.google.com> Message-ID: <405A5EC9.6010503@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. In fact, that is the normal behaviour: >>> a = [1, 2] >>> b = [1] + [2] >>> (a == b, a is b) (1, 0) 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. So, assuming no bugs in the code, if a is not equal to b then a is not the same object as b. On the other hand, if a is equal to b, a may or may not be the same object as b. And on the third hand, if a is the same object as b, then a and b must be equal. -- Steven D'Aprano From mark at prothon.org Tue Mar 30 02:14:32 2004 From: mark at prothon.org (Mark Hahn) Date: Mon, 29 Mar 2004 23:14:32 -0800 Subject: A 'Python like' language References: <40645d8f$0$10775$afc38c87@news.easynet.co.uk> <95aa1afa.0403262049.4b2a6f78@posting.google.com> Message-ID: <779ac.68717$cx5.51149@fed1read04> > Stackless-type systems tend to make this rather more convoluted than just making a C function call. I define a function call as: call_func(ist, self, func_sym, parm_cnt, lbl_val_arr, dyn_locals); This call is the same for interpreted Prothon or internal C code. It has the self object, the symbol telling the function name, and the passed parameters. ist is a struct passed around everywhere to keep interpreter state and keep things re-entrant. dyn_locals is used for dynamic local compatilility in C (which has never been used and may be pulled). lbl_val_arr is a C array (length of parm_cnt) of object pairs of labels (sym objects) and value objects. The labels allow one to do func(x=value). Usually, internally the labels are NULL. This structure supports func(*list, **dict) even internally. You may call this convoluted if you wish. "Greg Ewing (using news.cis.dfn.de)" wrote in message news:c4am81$2ha0mj$1 at ID-169208.news.uni-berlin.de... > 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? > > A running Python program creates and discards certain kinds > of objects (e.g. integers, tuples, stack frames) at a very > high rate. Due to reference counting, the fact that these > objects have been discarded is discovered very quickly, and > their memory released. Subsequent allocations are likely to > re-use the same memory, which is likely to be in cache. > > A pure mark-and-sweep system, on the other hand, tends to > keep on allocating fresh memory and letting the garbage > objects pile up until there is no more fresh memory, only > then pausing to reclaim the garbage. This is a very bad > access pattern for cache purposes. > > Back when the addition of a mark-and-sweep collector to > Python was being debated, this argument was put forward as > a reason why replacing reference counting with mark-and-sweep > wouldn't obviously be an improvement, and could make things > worse. > > Python currently has both reference counting *and* mark > and sweep, which sounds redundant, but the combination seems > to work very well. > > > The interpreter supports C code calling Prothon code and vice versa. > > I don't doubt that it's possible, I was just wondering how > easy it is. Stackless-type systems tend to make this rather > more convoluted than just making a C function call. I'll take > a look at the code some time and find out. > > -- > Greg Ewing, Computer Science Dept, > University of Canterbury, > Christchurch, New Zealand > http://www.cosc.canterbury.ac.nz/~greg > From imbosol at aerojockey.invalid Sat Mar 20 23:18:25 2004 From: imbosol at aerojockey.invalid (Carl Banks) Date: Sun, 21 Mar 2004 04:18:25 GMT Subject: [OT] Compilable Python-like language? References: <105plk0tk9qk73b@news.supernews.com> Message-ID: Peter Hansen wrote: > > > John Roth wrote: > >> Actually, I believe he did specify what he wanted it for. He said, >> and I'm quoting from is message: >> >> [quote] > [snip quote] >> [end quote] >> >> The key phrase here is >> >> "just uses Python's basic syntax characteristics (no end-of-statement > > markers, use indentation to denote >> code blocks, less verbose syntax overall, etc) without the advanced dynamic >> and OO features would still be interesting to me" >> >> I certainly think that is clear enough. He wants a compiled language >> that has some of Python's ease of use features. Is that so hard to >> understand? > > Yes, it is. Compiling something is not only an ambiguous concept (Java > is compiled, but generally runs only on virtual machines and so does not > have some of the benefits of languages which are compiled to native > machine code), but does not have *inherent* benefits. On an abstract level, this is true. On a practical level, when someone asks for, or refers to, a language that "compiles to binary" (OP's exact words), we know what he's referring to. [snip] > Without any idea whether Ed wanted improved *packaging*, or > *performance*, or something else (an academic exercise?), it isn't > possible to provide a useful answer. I highly disagree. If he's smart enough to decide that the type of language he asked for is best for his needs, then a simple "yes, here it is" or "sorry, there isn't" would be useful to him. -- 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 mlh at furu.idi.ntnu.no Tue Mar 23 07:37:11 2004 From: mlh at furu.idi.ntnu.no (Magnus Lie Hetland) Date: Tue, 23 Mar 2004 12:37:11 +0000 (UTC) Subject: latin 1 in curses? Message-ID: I'm playing around with curses, and have had some problems with that... For example, I can't make colours work in Python, although several other curses-based programs use colours on my box. (ncurses, I suppose -- and some maybe slang?) Does Python use ncurses now -- or? But the colours aren't that important. More important is my inability to get latin 1 characters to work in Textpad objects. (I can't get the page up/down and backspace characters to work properly either; and not only in Textpad editing.) Is there some locale stuff I need to be setting? Some manual handling? Is there a limitation in the library? Does this depend on the curses implementation I'm using? Would I be better off with some packages such as py-ncurses? (Or even writing in C and embedding Python?) Any advice appreciated. -- Magnus Lie Hetland "The mind is not a vessel to be filled, http://hetland.org but a fire to be lighted." [Plutarch] From elmlish at netscape.net Wed Mar 3 13:24:58 2004 From: elmlish at netscape.net (elmlish) Date: Wed, 03 Mar 2004 18:24:58 GMT Subject: Efficiently test for positive re.match then use the result? Message-ID: <20040303102526934-0800@news.qwest.net> Hello all, I'm currently befuddled as to how to efficiently test for a positive re. match then use the results of that match in a function. 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. 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. 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, -- ~elmlish~ From skip at pobox.com Tue Mar 23 11:07:00 2004 From: skip at pobox.com (Skip Montanaro) Date: Tue, 23 Mar 2004 10:07:00 -0600 Subject: The problem with "as" [was "Re: PEP 318"] In-Reply-To: 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: <16480.24740.932094.590804@montanaro.dyndns.org> >> With no extension beyond the current PEP 318 proposal, you might >> postulate returns() and accepts() decorators: >> >> def foo(x, y) [accepts(int, float), returns(int)]: >> ... >> >> which extend foo() with code to enforce input and output types. >> Further, function attributes could be added which could be used by >> tools like pychecker for intermodule type checking. Joe> Not a big fan of that syntax - I have to keep the parameter names Joe> and types in sync by counting. Here's a dummy example from the in-progress version of the PEP: def accepts(*types): def check_accepts(f): def new_f(*args, **kwds): for (a, t) in zip(args, types): assert isinstance(a, t), \ "arg %r does not match %s" % (a,t) return f(*args, **kwds) assert len(types) == f.func_code.co_argcount return new_f return check_accepts def returns(type): def check_returns(f): def new_f(*args, **kwds): result = f(*args, **kwds) assert isinstance(result, type), \ "return value %r does not match %s" % (result,type) return result return new_f return check_returns def func1(arg1, arg2): return arg1 * arg2 func1 = accepts(int, (int,float))(func1) func1 = returns((int,float))(func1) print func1(5, 3.0) print func1(5, 3) def func2(arg1, arg2): return str(arg1 * arg2) func2 = accepts(int, (int,float))(func2) func2 = returns((int,float))(func2) try: print func2(5, 3.0) except AssertionError, msg: print msg def func3(arg1, arg2, *rest, **kwds): r = arg1 + arg2 print "r:", r print "rest:", rest print "kwds:", kwds if 'result' in kwds: return kwds['result'] return r func3 = accepts(int, int)(func3) func3 = returns(int)(func3) print func3(3,5,'a','b','c',other="47") print func3(3,5,'a','b','c',result=47) Note that check_accepts() does the counting for you. If you wanted type declarations in the language I agree it would be more natural for the arguments and their types to be side-by-side, but then it wouldn't be Python. ;-) Joe> For decorators in general, I like Joe> def foo() as [decor1, decor2, decor3]: Joe> You get an explicit list syntax, but it's set off by a keyword so Joe> they don't run together to the eye. Because the keyword keeps it Joe> unambiguous, you could even allow a tuple instead of a list: "def Joe> foo() as (x, y, z)". I don't understand how def foo() as [decor1, decor2, decor3]: is somehow less ambiguous than def foo() [decor1, decor2, decor3]: The language parser certainly wouldn't care. Joe> So I definitely favour a keyword, but perhaps "as" is to generic. Joe> What about "has" or "with"? I don't think any keyword adds enough to make it preferable over just a bracketed sequence of decorators. Python supports: import foo as f The use of "as" makes perfect sense in that context. I'd prefer prepositional keywords actually be consistent with their English usage. It's just line noise and is likely to provide some stumbling block of programmers whose command of the English language is not stellar. What we really would say in English is Define function foo taking no arguments as modified by decor1, decor2 and decor3. No single preposition is going to read correctly as a replacement for "as modified by", nor do we need all those other bits of English ("function", "taking no arguments") to tell us that this is a Python function definition. This isn't SQL or COBOL, and it's certainly not English. My vote is to dispense with the pseudo-keyword idea altogether. Skip From tjreedy at udel.edu Fri Mar 5 00:47:35 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 5 Mar 2004 00:47:35 -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><6ubf401c2qtarfoa36m03572dprj0h9kkl@4ax.com> <4pgf409lhtme32fb4gmdfdar8astq074jv@4ax.com> Message-ID: "David MacQuigg" wrote in message news:4pgf409lhtme32fb4gmdfdar8astq074jv at 4ax.com... > Actually, I think this is rather ugly. The string 'method' still looks > like a 'function'. We really need a 'join' method that takes a list > of strings as its 'front-door' object and the 'joiner' as its optional > 'side-door' input. A said in previous discussions, the second parameter of the join function is *any* iterable of strings, and not just lists. Your proposal would either cripple or omit this generality, depending on whether you meant it as a replacement of or redundant supplement to the current joiner.join(iterable_of_strings) method. Terry J. Reedy From mwilson at the-wire.com Fri Mar 12 10:17:20 2004 From: mwilson at the-wire.com (Mel Wilson) Date: Fri, 12 Mar 2004 10:17:20 -0500 Subject: loop scope References: Message-ID: In article , 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. > >I am not following this argument. The surprise, specifically, is >that I don't think of myself as having declared "t" as a variable. it >is don't magically, as a placeholder and for a very specific purpose. >So I would expect it to go away outside of the " [ " and " ] " by >equal and opposite magic. Well, you don't declare variables in Python. You use names to refer to objects. Python 2.4 may give each list comprehension its own namespace, but for now names used in a list comp. are used just as they would be in any other statement. Regards. Mel. From seberino at spawar.navy.mil Mon Mar 8 21:27:33 2004 From: seberino at spawar.navy.mil (Christian Seberino) Date: 8 Mar 2004 18:27:33 -0800 Subject: Fast way to send message between 2 child processes? (using a file is too slow?) Message-ID: process1_tuple = os.popen4("some code1") process2_tuple = os.popen4("some code2") ---- What is fast way to send a message between process1 and process2?? process2 cannot just write to STDIN of process1 because he doesn't have a reference to process1. (process2 does not have process1_tuple) ------ The only way I could think to do this was to write and read from a file but this is SLOW. Is there another way **without using a file**?? Thanks! Chris From noemail at noemail4u.com Mon Mar 22 07:36:30 2004 From: noemail at noemail4u.com (Dang Griffith) Date: Mon, 22 Mar 2004 12:36:30 GMT Subject: Syntax of 'in' : searching a list for a string References: <6d6b80e0.0403220202.356f62fc@posting.google.com> Message-ID: On 22 Mar 2004 02:02:51 -0800, robichon at esrf.fr (MarieR) wrote: >Hi, > >Sorry for my newbie question: > >I want to check whether the string 'Remove' is present in a list 'supportList', >but if I do > >if ('Remove') in supportList: > >or > >if 'Remove' in supportList: > >I get the error message > >'in ' requires character as left operand. > >Thanks in advance for your help, > >Marie What perfect timing--the question right before yours asked which version of Python added support for that syntax. You need to be using 2.3 or newer to use the 'in' operator to search for a string in a string. --dang From amleczko at icpnet.pl Sun Mar 14 18:59:45 2004 From: amleczko at icpnet.pl (Andrzej Mleczko) Date: Mon, 15 Mar 2004 00:59:45 +0100 Subject: INTRANET zope Message-ID: Hi I'm searching for an open-source, free Intranet solutions in Zope. From claird at lairds.com Sat Mar 27 10:14:39 2004 From: claird at lairds.com (Cameron Laird) Date: Sat, 27 Mar 2004 15:14:39 -0000 Subject: Python for email? References: Message-ID: <106b6ivetpf0bc0@corp.supernews.com> In article , Skip Montanaro wrote: > > sean> Is there a good module for sending out email? > >Check out smtplib in the standard library: > > http://www.python.org/doc/current/lib/module-smtplib.html > >Skip > 'Past time that I mention this: I'm a big fan of the smtplib module. In general, I think this is the direction Python-oriented developers should take, and NOT to "shell out" to sendmail or such. However, one benefit of sendmail and comparable MTAs that's often not immedi- ately apparent (and, with any luck, won't be for the life of any specific project) is their knowledge about retries. Projects that face erratic connectivity either need to exploit an installed MTA, or program their own retry management. smtplib presents a few other, even more marginal issues. If an installed MTA enforces institutional standards (disclaimers, archi- ving, ...), smtplib is likely to subvert those. Decide for yourself if that's a good or bad thing. -- Cameron Laird Business: http://www.Phaseit.net From lbates at swamisoft.com Mon Mar 1 11:43:13 2004 From: lbates at swamisoft.com (Larry Bates) Date: Mon, 1 Mar 2004 10:43:13 -0600 Subject: Concatenated numerical literals References: Message-ID: I took a function that I wrote to format floats with commas and currency symbol and hacked it a little to make it work with your spaces. You should be able to take it and with little modifications make it work for you. -Larry def fmt_currency(amount): import types, string ''' This function will take the number passed to it and format it as US Currency with floating $ sign, comma separators and two decimal places ''' thousands_sep=" " currency="$" # # Check to see if I got a number or a string # if type(amount) == types.StringType: # # Check to see if I got an empty string, return $0.00 # if amount == '': amount=0 else: amount=string.atof(amount) temp="%.2f" % amount outstring=temp[len(temp)-4:] if len(temp)==4: return currency+outstring digits=list(temp[0:len(temp)-4]) digits.reverse() #print digits cpos=1 for c in digits: outstring=c+outstring cpos=cpos+1 if cpos%3 == 0: outstring=thousands_sep+outstring # # Check to see if comma is first character of the formatted string # if it is strip it off. # if outstring.startswith(thousands_sep): outstring=outstring[1:] return currency+outstring if __name__=="__main__": print fmt_currency(0.12) print fmt_currency(123.45) print fmt_currency(123456789.01) "Per Erik Stendahl" wrote in message news:mailman.18.1078154586.22701.python-list at python.org... > Hi, > > I wish I could write large integers (and floats, etc) like > this in Python: > > 10 000 000 > > Kind of the same way I can write string literals today. > (As in 'This' 'is' 'one' 'string'.) > > Has there been any discussion on this? I find myself wishing > for this at least once a week, since it really helps readability. > It doesn't seem like a big implementation either. > > Any comments? > > Regards, > Per Erik Stendahl, > Uppsala, Sweden > From http Tue Mar 9 17:44:40 2004 From: http (Paul Rubin) Date: 09 Mar 2004 14:44:40 -0800 Subject: PEP 328: Imports: Multi-Line and Absolute/Relative References: Message-ID: <7xllm94p47.fsf@ruckus.brouhaha.com> Josiah Carlson writes: > from MODULE import NAMES as RENAME searching HOW > import NAMES as RENAME from MODULE searching HOW I like this. > Or for backwards compatibility: > from HOW.MODULE import NAMES as RENAME > import HOW.MODULE.NAMES as RENAME I don't see any need for this. Backwards compatibility doesn't require adding new stuff. Just leave those forms the way they were. > Where HOW is of the form: > -[.PACKAGE1[.PACKAGE2[...]]] > for HOW: > -1.sibling_package > maps to ../sibling_package/MODULE.(py|pyc|pyo|pyd|so|dll) > -2.uncle_package.cousin_package > maps to ../../uncle_package/cousin_package/MODULE.(ext) Ugh! What's wrong with ../sibling_package or ../../uncle_package/cousin_package instead of the -1,-2 stuff? > child_package.grandchild_package.great_grandchild_module > maps to ./child_package/grandchild_package/great_grandchild_module.(ext) > > I think such behavior is clear enough magical syntax, what do others think? I think it's ok to use slashes. From lbates at swamisoft.com Wed Mar 3 17:46:08 2004 From: lbates at swamisoft.com (Larry Bates) Date: Wed, 3 Mar 2004 16:46:08 -0600 Subject: insertion in lists References: Message-ID: l=[] l.append([]) now l=[[]] # That is this list contains a single empty list. l.append([]) now l=[[],[]] # That is this list contains two empty lists. l[0].append('a') now l=[['a'],[]] l[0].append('b') now l=[['a','b'],[]] l[0][0]='c' now l=[['c'],'b'],[]] You should be able to figure it out from here. What is interesting is that your list can have arbitrary elements that may be lists, strings, dictionaries, classes, etc. and they don't have to have anything in common. More complex example: class x: pass l=['test',{'key1':1,'key2':2}, 1.5, [1,2,3,5,6,7,8], x] Has string at l[0] Has dictionary at l[1] Has float at l[2] Has another list at l[3] Has a class reference at l[4] WARNING-Never use 'list' as a variable name (as you did in your example) , it is a keyword and will get redefined by the assignment (without warning). -Larry "Lupe" wrote in message news:c25bjd$1ollgu$1 at ID-202776.news.uni-berlin.de... > hi, > > 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. > > if I have: > element > > list [0] > and want to have list[0][0] > list[0][1] > > how can I insert the element to that list[0][0], for example? > just to put things clearer, if I wanted to insert the element in list[0] I > could do list.insert(0,element). > > I've tried list[0].insert(0,element) but gives me an error. > > > Luis From max at alcyone.com Mon Mar 15 19:55:44 2004 From: max at alcyone.com (Erik Max Francis) Date: Mon, 15 Mar 2004 16:55:44 -0800 Subject: Result of ``a is b'' References: <40200384.0403151632.35496ee6@posting.google.com> Message-ID: <40565090.81972BF2@alcyone.com> Axel Boldt wrote: > is there a rationale for the following behavior: Yes: It shouldn't matter to you what the implementation is doing. -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE \__/ I only regret that I have but one life to lose for my country. -- Nathan Hale From joe at notcharles.ca Sun Mar 28 06:49:51 2004 From: joe at notcharles.ca (Joe Mason) Date: Sun, 28 Mar 2004 11:49:51 GMT Subject: Newbie Class Questions References: <94CdnVqi7o8rn_vdRVn-vg@centurytel.net> Message-ID: In article , Peter Otten wrote: > 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? Actually, somebody pointed out in the other thread that Python has a __subclasses__ function, so AutoAll can just do "for i in AutoText.__subclasses__:". Joe From claird at lairds.com Tue Mar 23 17:00:02 2004 From: claird at lairds.com (Cameron Laird) Date: Tue, 23 Mar 2004 22:00:02 -0000 Subject: Decent way to trace resource leaks? References: <87r7vk7dnc.fsf@strauser.com> Message-ID: <1061cr2sis3f7d5@corp.supernews.com> In article <87r7vk7dnc.fsf at strauser.com>, Kirk Strauser wrote: . . . >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. . . . This question interests me intensely--which is why I'm taking so long to answer it. I'd love to write a book on resource- management techniques. However, you need an answer now, and it probably won't serve you even to wait for the well-crafted response I had in mind. Let me put your progress in your own hands: if you want "a way to dump the process's object hierarchy", it's probably a good time for you to read . Does that give you what you need, for now? -- Cameron Laird Business: http://www.Phaseit.net From webbsoft2 at alltel.net Sat Mar 20 23:29:54 2004 From: webbsoft2 at alltel.net (w) Date: 20 Mar 2004 20:29:54 -0800 Subject: Timeout on a UDP Socket Message-ID: I'm having problems with this program hanging on the revc(buf). I was trying to figure out a way to allow the socket to timeout. I'm have tried making the socket non-blocking but had on luck. Being very new to Python, could there be a better way to accomplish this task. The program works very well, but on occassion is will not receive the data from the server and hang. Thank, # Client program import os.path from socket import * from time import * # Set the socket parameters #host = "localhost" host = "10.0.0.20" port = 21567 buf = 1024 addr = (host,port) # Create socket UDPSock = socket(AF_INET,SOCK_DGRAM) # Send messages while(1): if not os.path.exists( "user1.inp" ) : sleep( 2 ) else: print "opening....." print "reading....." in_file = open("user1.inp", "r") data = in_file.readline() #print in_line in_file.close() if(UDPSock.sendto(data,addr)): print "Sending message '",data,"'....." if os.path.exists( "user1.inp" ) : os.remove( "user1.inp" ) print "Waiting for Response..." # Receive messages data = UDPSock.recv(buf) print "\nReceived message '", data,"'" #output result message from server f=open( "user1.out", "w" ) f.write( data ) f.close() # Close socket UDPSock.close() From jcarlson at nospam.uci.edu Fri Mar 19 19:35:34 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Fri, 19 Mar 2004 16:35:34 -0800 Subject: SHA-based subclass for random module In-Reply-To: <7xwu5g7a0i.fsf@ruckus.brouhaha.com> References: <7xptbgjpk4.fsf@ruckus.brouhaha.com> <5d83790c.0403190105.69ca83e7@posting.google.com> <7x8yhxtast.fsf@ruckus.brouhaha.com> <7xwu5g7a0i.fsf@ruckus.brouhaha.com> Message-ID: >>>What's Random.random(self) supposed to do? >> >>Generate a random number using the Mersenne Twister random number >>generator. > > According to the Random doc, Random.random() doesn't take an argument, > so I'm asking what the "self" is for. >>>But doesn't support all the operations specified in the Random API. >>>What's up with that? >> >>That is what the subclass was for: >> > class MD5Random(Random): > > But the methods in the superclass don't do anything to manage the state > of subclass instances. Perhaps you should spend some more time learning how Python classes work. Random is a class. Random.random is an unbound class method. Random.random(self) calls the unbound class method 'Random.random' with the first argument being the MD5Random instance. You should satisfy yourself that the below is correct behavior for Python classes. >>> class A: ... def blah(self): ... print self.__class__ ... >>> class B(A): ... def blah(self): ... print "I'm in B, calling A" ... A.blah(self) ... >>> a = A() >>> a.blah() __main__.A >>> b = B() >>> b.blah() I'm in B, calling A __main__.B Can you figure out why the following is also correct? >>> class C: ... def blah(self): ... print "I'm in C, calling A" ... A.blah(self) ... >>> c = C() >>> c.blah() I'm in C, calling A Traceback (most recent call last): File "", line 1, in ? File "", line 4, in blah TypeError: unbound method blah() must be called with A instance as first argument (got C instance instead) Perhaps now you understand why he can use Random.random(self) in the earlier version, and Random.getrandbits(self, 128) in the current version. - Josiah From garryknight at gmx.net Tue Mar 16 15:29:11 2004 From: garryknight at gmx.net (Garry Knight) Date: Tue, 16 Mar 2004 20:29:11 +0000 Subject: new to programming: suggestion References: <3d5e65ea.0403152115.3df7e8c1@posting.google.com> Message-ID: <1079468950.19949.0@nnrp-t71-02.news.uk.clara.net> In message <3d5e65ea.0403152115.3df7e8c1 at posting.google.com>, pius wrote: > i'm new in programming; i'd like to find a good programming book There are some good online books at Andamooka and FreeTechBooks: http://www.andamooka.org/ http://www.tcfb.com/freetechbooks/ Also, these are good books on programming with Python: http://www.ibiblio.org/obp/thinkCSpy/ http://diveintopython.org/ http://www.freenetpages.co.uk/hp/alan.gauld/ http://www.tcfb.com/freetechbooks/bookphyton.html -- Garry Knight garryknight at gmx.net ICQ 126351135 Linux registered user 182025 From gerrit at nl.linux.org Thu Mar 11 16:14:40 2004 From: gerrit at nl.linux.org (Gerrit) Date: Thu, 11 Mar 2004 22:14:40 +0100 Subject: Video module? In-Reply-To: References: Message-ID: <20040311211440.GC6377@nl.linux.org> Mickel Gr?nroos wrote: > 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 > stable enough for my purposes. I have also tried using Windows Media > Player with COM, but that is cumbersome. The module must work on Windows > (and preferably on Linux as well). Basically, what I need to be able to > do is play a selected interval of the movie and if possible also rip > the sound track from the movie file as a WAV file. > > Any ideas anybody? The Pygame library, based on SDL (crossplatform), has got a Movie module: http://www.pygame.org/docs/ref/pygame_movie.html http://www.pygame.org/docs/ref/Movie.html it's not very sophisticated, but is able to .play(), .rewind(), .skip(), etc. Gerrit. -- Weather in Twenthe, Netherlands 11/03 20:25 UTC: 2.0?C wind 2.7 m/s E (57 m above NAP) -- Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From deets_noospaam at web.de Sun Mar 7 18:48:39 2004 From: deets_noospaam at web.de (Diez B. Roggisch) Date: Mon, 08 Mar 2004 00:48:39 +0100 Subject: ImportError when trying to import own C++ module References: Message-ID: > % nm BClass.so | grep _ZNK6AClass5valueEv > U _ZNK6AClass5valueEv > >From the nm manpage: "U" The symbol is undefined. -- Regards, Diez B. Roggisch From mark at prothon.org Tue Mar 30 02:41:02 2004 From: mark at prothon.org (Mark Hahn) Date: Mon, 29 Mar 2004 23:41:02 -0800 Subject: A 'Python like' language References: <40645d8f$0$10775$afc38c87@news.easynet.co.uk> <95aa1afa.0403262049.4b2a6f78@posting.google.com> Message-ID: If you were designing a new interpreter, would you consider reference counting an evil pain for C coders (as I did) and use some other GC, or do you think I made a mistake? Is there a compromise? "Greg Ewing (using news.cis.dfn.de)" wrote in message news:c4am81$2ha0mj$1 at ID-169208.news.uni-berlin.de... > 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? > > A running Python program creates and discards certain kinds > of objects (e.g. integers, tuples, stack frames) at a very > high rate. Due to reference counting, the fact that these > objects have been discarded is discovered very quickly, and > their memory released. Subsequent allocations are likely to > re-use the same memory, which is likely to be in cache. > > A pure mark-and-sweep system, on the other hand, tends to > keep on allocating fresh memory and letting the garbage > objects pile up until there is no more fresh memory, only > then pausing to reclaim the garbage. This is a very bad > access pattern for cache purposes. > > Back when the addition of a mark-and-sweep collector to > Python was being debated, this argument was put forward as > a reason why replacing reference counting with mark-and-sweep > wouldn't obviously be an improvement, and could make things > worse. > > Python currently has both reference counting *and* mark > and sweep, which sounds redundant, but the combination seems > to work very well. > > > The interpreter supports C code calling Prothon code and vice versa. > > I don't doubt that it's possible, I was just wondering how > easy it is. Stackless-type systems tend to make this rather > more convoluted than just making a C function call. I'll take > a look at the code some time and find out. > > -- > Greg Ewing, Computer Science Dept, > University of Canterbury, > Christchurch, New Zealand > http://www.cosc.canterbury.ac.nz/~greg > From dmq at gain.com Thu Mar 25 15:48:24 2004 From: dmq at gain.com (David MacQuigg) Date: Thu, 25 Mar 2004 13:48:24 -0700 Subject: The problem with "as" [was "Re: PEP 318"] References: <7x1xnlqs77.fsf@ruckus.brouhaha.com> <8ef9bea6.0403221354.574ebdaf@posting.google.com> <1M-dnXrds_WKG8LdRVn-jw@comcast.com> <988460ht0bbbteu1ngq8sdrjm46ph8bjli@4ax.com> Message-ID: [Stephen Horne]: >>>Symbols (and worse, odd combinations of symbols where it's hard to >>>tell which symbols are part of the same syntax rule and which are not) >>>that you've not seen before tend not to suggest where in the manual to >>>look. [David MacQuigg]: >>We need a single unique symbol, one that doesn't conflict with >>existing syntax, and has no special meaning itself. By using this >>symbol for extensions of *many* statements, we minimize the amount of >>new words or syntax users have to learn. [Stephen Horne]: >So each statement will only ever be extended once, and for one >purpose? [David MacQuigg]: Using a symbol to introduce an extension doesn't mean we can't add more extensions later. If we extend the def statement now with $(staticmethod), that does not mean we can't later add $(accepts(int, int), returns(float)) If the concern is flexibility for future extensions, I would think we should *avoid* keywords like 'as' which tend to *limit* the options. Note: The keywords in the $(...) phrase are keywords *only* within this context, and do not limit the extension as a whole. Within this limited context, we can be as descriptive as we want with each keyword. A quick review of the discussion on PEP 318 shows quite a collection already (staticmethod, classmethod, onexit, singleton, accepts, returns, generator, ...). [Stephen Horne]: >>>If 'as' is too generic, then what about 'decorators'. That clearly >>>states what follows and can easily be looked up, making the 'RTFM' >>>attitude justifiable. [David MacQuigg]: >>"Decorators" is clear as to its meaning, but a little too long, >>especially if it causes statments with multiple decorators to run over >>one line. It also limits the syntax to this one statement. You would >>not want to extend the syntax of a print statement, for example, with >>decorators=(separator = ' ', terminator = '\n'). [Stephen Horne]: >If it's a secondary syntax, learned late and rarely used, then a long, >explicit keyword is just what is needed. You can look it up, of >course, but it is far better for readability if you don't need to - if >the explicit keyword is itself a sufficient reminder. [David MacQuigg]: The place for specific keywords is *inside* the general extension syntax. There we have no restrictions on how specific we can get. [Stephen Horne]: >After all, it's >not just newbies that we should worry about - what about people like >me, who use several languages and sometimes go months without using >Python at all? [David MacQuigg]: Our goals are the same. My clients are some of the best IC designers in the world, but they don't have time to learn another computer language. What I can't pack into a two-day course on Python, I want to "encapsulate" in a way that will not cause confusion later. I expect they will learn the basic syntax on most of the Python statements, but not the extensions. My "common-symbol-for-a statement-extension" proposal is a way to encapsulate complexity. Even if users never learn what is a 'generator', when they see that word as part of a common extension syntax on a def statement, they will not be discouraged from reading the def as they would a normal function. I think my recent experience in learning Python is typical of what we can expect from IC designers. I was put off by statements like "lambda", "yield", "staticmethod", even though from a users view, they are not fundamentally different than the basic statements. Instead of making lamda functions look like something new and wierdly different, and mystifying the discussion with references to lambda calculus, it would have been much better to use the standard function syntax and substitute a "modified syntax" symbol for the function name. Unglamorous, but very practical. The explanation would take about two sentences, and a simple example of its use would be about a half-page. I have high hopes for Python. If it continues to evolve in the right direction, I can see it becoming the ultimate computer language for non-programmer technical professionals. I've looked also at Ruby, and I see that as the second most likely to become the ultimate language. With a five-year hindsight advantage over Python, it has some syntactic benefits, but it just doesn't have yet the critical mass of libraries and general support enjoyed by Python and Perl. [Stephen Horne]: >As for the print statement, I wouldn't use a decorating approach at >all. And neither did you, for that matter - what you described could >not be implemented using decorator functions. [David MacQuigg]: I think I'm using the word 'decorator' in a more generic sense - anything that 'decorates' or 'adds to' the basic syntax of a statement. [Stephen Horne]: >What I might use is something like... > > pragma printoptions ( separator = ' ', terminator = '\n' ) : > print "whatever" > print "something else" > >...as a general way of providing standard-behaviour-overriding flags >for built-ins. [David MacQuigg]: I like this. It keeps the basic syntax of the print statement clean. It avoids a lot of typing in situations where there is a repetition of the same 'decoration' on many statemtents. The main drawback I see is that in many situations, the modifcation is 'one time only'. Then we have *three* statements instead of one. ( We need a statement to restore the default printoptions.) Using the "common-symbol-for-a statement-extension" syntax, we could modify multiple statements without too much clutter using something like: opts = printoptions( separator = ' ', terminator = '\n' ) print @(opts) "whatever" print @(opts) "something else" [Stephen Horne]: >Except that I don't see this as a real problem. Print works well as a >quick way to get results out of short scripts, where perfect >formatting of those results is unimportant. In more sophisticated >programs, other I/O mechanisms are better suited to the job. [David MacQuigg]: sys.stdout.write('%s %s %s\n' % (x, y, z) ) is enough of an inconvenience that many users are pushing for something more. And when each extension is added, like 'print >> ...' there are howls of protest from those who see it as a wart. Wouldn't it be better if we introduce just one 'wart', a new symbol, that can be used to solve this and many other problems. >> is a wart only because it is unique to this one situation. If we use a syntax that solves many similar problems, it becomes a feature, not a wart. [Stephen Horne]: >>>Not really. What happens when there are two different ways of >>>modifying the same syntax? When the first one was defined with no >>>awareness that another kind of modification might be needed later? [David MacQuigg]: >>I guess I'll need an example here. Seems like the potential for >>future incompatibilities is *greater* if the syntax itself has >>"special meaning" ( e.g. "decorators" instead of [] ). [Stephen Horne]: >If a statement has a 'decorators' extension syntax, it can always add >a 'widget' or 'blodget' extension syntax later, being clear to both >the parser and the reader. [David MacQuigg]: So to make the example more concrete, I assume you would do something like: def func1( x, y, z ) decorators(staticmethod), blodgett(gradoo): instead of: def func1( x, y, z ) [staticmethod, gradoo]: I think I'm missing something. [Stephen Horne]: >Contrast the case with a single extension-denoting symbol - '$' >perhaps. If it gets re-used for several extensions to the same >statement, you get the real possibility that the only way to tell the >different extensions apart is the ordering. Which, at the very least, >means a far greater probability of having to reread the documentation >to figure out what something means - ie bad readability. [David MacQuigg]: I would expect the def statement to grow the most number of extensions [staticmethod, accepts(int, int), ...]. Even with dozen or more, surely we can name them distinctly. Hey - I appreciate your time in giving these issues some real thought. -- Dave From peter at engcorp.com Tue Mar 30 13:23:03 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 30 Mar 2004 13:23:03 -0500 Subject: Global name "userid" not defined?? In-Reply-To: References: Message-ID: Sean Berry wrote: > #!/usr/local/bin/python > > def setUserid(value): > userid = value > > def getUserid(): > return userid > > How do I make a variable global? You need to use the "global" keyword (check the docs for more information) with the name of the variable at the top of each function which wants to *modify* the global variable (including by creating it in the first place). Although you don't need to include this ("global userid") in the second function, it would probably be considered "good style". Of course, using globals at all is pretty bad style, but as you're just learning it's not the worst thing to do. (Close, but not the worst... just consider learning how to avoid them, generally by making things more object-oriented.) -Peter From spamthisemail at mailinator.com Thu Mar 4 01:33:10 2004 From: spamthisemail at mailinator.com (David Shaw) Date: 3 Mar 2004 22:33:10 -0800 Subject: OFF-TOPIC:: Why Lisp is not my favorite programming language References: <165b3efa.0403030443.4d591f04@posting.google.com> Message-ID: <10cd2710.0403032233.4c8037b1@posting.google.com> The real question is as to why *Python* isn't your favorite programming language! - David // http://david.artoo.net/ From jcarlson at uci.edu Tue Mar 30 15:54:23 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Tue, 30 Mar 2004 12:54:23 -0800 Subject: asyncore deficiencies In-Reply-To: <8961ebe5.0403290143.4a2b9edb@posting.google.com> References: <99dce321.0403271928.69ef6eeb@posting.google.com> <99dce321.0403281816.4df96025@posting.google.com> <8961ebe5.0403290143.4a2b9edb@posting.google.com> Message-ID: > My personal appreciation: asyncore is the most perfect combination of > hard work and incompetence i have ever seen in my life. It is so > anti-pythonic that it should get out of the standard distribution. > > Just a personal opinion ... Funny thing is that asyncore (aka medusa) is one of the highest performing asyncronous socket libraries for Python that is available. It also compares nicely (performance-wise) with most anything you could find in non-interpreted languages. Honestly, I don't know what your issue is. It is event based, and in the realm of event driven frameworks, is reasonable. So what is your problem? - Josiah From m_schellens at hotmail.com Thu Mar 18 07:37:34 2004 From: m_schellens at hotmail.com (Marc Schellens) Date: Thu, 18 Mar 2004 21:37:34 +0900 Subject: problem embedding numpy Message-ID: My C++ application crashes at "import_libnumarray()", when I: 1. initalize python and numarray like: ... Py_Initialize(); import_libnumarray(); ... 2 . load another module like: PyObject* pModule = PyImport_Import(pName); 3. call Py_Finalize() and do 1. again. If I call import_libnumarray() only once, my app crashes at 2. at PyImport_Import(pName) Any suggestions? Thanks, marc From kdahlhaus at yahoo.com Wed Mar 3 12:52:29 2004 From: kdahlhaus at yahoo.com (Kevin Dahlhausen) Date: 3 Mar 2004 09:52:29 -0800 Subject: best way to read a configuration file References: <2dy8qimiwq.fsf@itl-pc87.hut.fi> Message-ID: <283adf56.0403030952.9ea2cc3@posting.google.com> I kept this sample from an ealier thread or website. I don't have the link nor can I give credit to the author. If you have some lattitude on the exact format of the config file, this may do the trick for you though: Python App Macro Lang class App: def __init__(self, name): self._name = name def name(self): return self._name i=123 macrosource = """ print app.name() i=1 if i==2: server="internal.blah.com" else: server="external.blah.com" """ code = compile(macrosource, '', "exec") anApp = App('Global App Object') context = {} # populate context with fun things context["app"] = anApp exec code in context print "The server is:" + context["server"] if i != 123: raise "local variable 'i' changed" output = """ c:\cygwin\bin\sh -c "python PyAsMacroLang.py" Global App Object The server is:external.blah.com """ From rmkrauter at yahoo.com Thu Mar 25 20:08:28 2004 From: rmkrauter at yahoo.com (Rich Krauter) Date: Thu, 25 Mar 2004 20:08:28 -0500 Subject: ftp mget In-Reply-To: References: Message-ID: <1080263308.6641.21.camel@vaio> On Thu, 2004-03-25 at 18:54, allanc wrote: > Anybody know if there's an ftp client in python that can do an mget? > > My current implementation of an mget uses ftpconnection.nlst() to retrieve > the list of filenames. Then iterates through this list with > retrlines('RETR ' + fname,callback). > > I'd like to eliminate a LIST command on the ftp server altogether. > > Thanks to all. You may want to look in the python distribution at the script Tools/scripts/ftpmirror.py. It's referenced on the module documentation page for ftplib. It basically does what you're doing - parsing text returned by the LIST command. It will probably give you some ideas, or let you know whether you're barking up the wrong tree. Rich From rmunn at pobox.com Tue Mar 23 17:00:50 2004 From: rmunn at pobox.com (Robin Munn) Date: Tue, 23 Mar 2004 22:00:50 GMT Subject: Need recommendations for installer setup tool References: Message-ID: Noah wrote: > Robin Munn wrote in message news:... >> Noah wrote: >> > I would like something that could put a GUI on this process. >> > Not that this would make it any easier to use, but it would make it >> > easier to market :-P Ideally the installer would allow for both GUI and >> > text based interfaces. >> > >> > Are there any Python based products that would help me build these installers? >> > I'm trying to move away from the bash scripts and go with 100% pure Python. >> >> Have you looked at SCons? Between SCons and anygui, you might be able to >> put together a good solution pretty easily. > > SCons looks great! At first glance it seem to be exactly what I was looking for. > > I thought that AnyGUI was a dead project. No? It may be; I actually meant easygui, not anygui. http://www.ferg.org/easygui/ Note that easygui is *not* meant to be a full-fledged GUI. It's meant to be a quick-and-easy way of popping up dialog boxes to get the user's input, instead of having to do it in the command line. In other words, instead of doing: print 'What is your name?' username = raw_input().rstrip() print 'Hello,' username You can do: username = easygui.enterbox('What is your name') easygui.msgbox('Hello, %s' % username) -- Robin Munn rmunn at pobox.com From ngps at netmemetic.com Mon Mar 22 21:56:56 2004 From: ngps at netmemetic.com (Ng Pheng Siong) Date: 23 Mar 2004 02:56:56 GMT Subject: OFF-TOPIC:: Why Lisp is not my favorite programming language References: <165b3efa.0403030443.4d591f04@posting.google.com> <40460dd5$0$5916$7a628cd7@news.club-internet.fr> Message-ID: According to Minti : > However when some one says that the code might be 31.? > times slower as compared to C, kinda of scares me. Could assert such > figures. I know speed is not the one and only goal but just wondering > if these figures are correct. Recently, some troll challenged c.l.lisp: "The best known non-stupid (real problem, any algorithm) benchmark is probably the Coyote Gulch test. There are many languages that it has been translated into. If you can produce (write or find) and post a Lisp version that is within 10% of C performance, I will admit that #1 is incorrect." http://home.comcast.net/~bc19191/blog/040308.html -- Ng Pheng Siong http://firewall.rulemaker.net -+- Firewall Change Management & Version Control http://sandbox.rulemaker.net/ngps -+- Open Source Python Crypto & SSL From talktojamesblair at yahoo.com Thu Mar 18 08:09:00 2004 From: talktojamesblair at yahoo.com (james blair) Date: 18 Mar 2004 05:09:00 -0800 Subject: Python,mysql question Message-ID: Hi I have a search page & the reults for the search are fetched from the database. I want that on the results page only first 25 results are shown & a link "next 25 results" be shown.Same for the 2nd result page. How do I do this? From bkelley at wi.mit.edu Wed Mar 24 19:48:25 2004 From: bkelley at wi.mit.edu (Brian Kelley) Date: Wed, 24 Mar 2004 19:48:25 -0500 Subject: wxNotebook In-Reply-To: References: Message-ID: <40622C59.7040603@wi.mit.edu> Gandalf wrote: > > Hi All! > > I would like to hide and show pages in a notebook. Here is what I do > right now: > > def SetVisiblePages(self,pages): > for index in range(self.notebook.GetPageCount()): > self.notebook.GetPage(index).Show(index in pages) > > But it does not work. All pages remain visible. Only their content will > be invisible. > I also tried this: > > self.notebook.Show(index in pages) > > but it hides the whole nootebook. How can I hide/show individual pages? > Thanks in advance. notebook.RemovePage will "hide" a notebook window without deleting it, you can add it back later. Here is a small example, you'll probably want to do better bookkeeping than I do. from wxPython.wx import * class MyNoteBook(wxNotebook): def __init__(self, *a, **kw): wxNotebook.__init__(self, *a, **kw) self.pages = {} def HidePage(self, pagenum, label): page = self.GetPage(pagenum) self.pages[label] = page, self.GetPageText(pagenum) self.RemovePage(pagenum) def ShowPage(self, label): if label not in self.pages: return page, text = self.pages[label] self.AddPage(page, text, select=True) if __name__ == "__main__": app = wxPySimpleApp() frame = wxFrame(None, -1, "test") sizer = wxBoxSizer(wxVERTICAL) notebook = MyNoteBook(frame, -1) sizer.Add(notebook, 1, wxEXPAND|wxALL) panel1 = wxPanel(notebook, -1) panel1.SetBackgroundColour("yellow") notebook.AddPage(panel1, "Foo") panel2 = wxPanel(notebook, -1) panel2.SetBackgroundColour("red") notebook.AddPage(panel2, "Bar") def hidepageone(evt, notebook=notebook): notebook.HidePage(1, "mylabel") def showpageone(evt, notebook=notebook): notebook.ShowPage("mylabel") button1 = wxButton(frame, -1, "Hide Page") button2 = wxButton(frame, -1, "Show Page") EVT_BUTTON(button1, button1.GetId(), hidepageone) EVT_BUTTON(button2, button2.GetId(), showpageone) sizer.Add(button1, 0, wxEXPAND) sizer.Add(button2, 0, wxEXPAND) frame.SetSizer(sizer) frame.Show() app.MainLoop() From antonmuhin at rambler.ru Wed Mar 31 11:01:13 2004 From: antonmuhin at rambler.ru (anton muhin) Date: Wed, 31 Mar 2004 20:01:13 +0400 Subject: Python Documentation Blows! In-Reply-To: References: <20040330181802.04141.00000304@mb-m17.aol.com> Message-ID: Michael wrote: > >> I have not yet contributed anything to the python documentation myself. >> >> > One thing I like about PHP's docs is that it allows users to post > comments, suggestions, extra information, etc to the docs online. Now > and then someone goes through and edits the useful bits into the > official documentation and flushes the comments all back out leaving > them clear for new people to post their own. Several times I've attached > comments as to how to compile a module or use some poorly documented > feature and have had lots of people write to thank me for how helpful > those comments were. I'd imagine the same process could be useful in > Python. > Maybe just start a wiki based on the current documentation? It shouldn't be too difficult, should it? regards, anton. From rhh at structurelabs.com Tue Mar 30 19:04:16 2004 From: rhh at structurelabs.com (r holland) Date: 30 Mar 2004 16:04:16 -0800 Subject: How to run another .py file w/o exec command? References: <406813DC.3010807@zoran.com> Message-ID: you can try this import os os.system("python example.py") From nhodgson at bigpond.net.au Tue Mar 2 15:52:55 2004 From: nhodgson at bigpond.net.au (Neil Hodgson) Date: Tue, 02 Mar 2004 20:52:55 GMT Subject: Speed Comparison Perl Python & C References: <3064b51d.0403011035.554e7731@posting.google.com> <3064b51d.0403020649.53866885@posting.google.com> Message-ID: beliavsky at aol.com: > Thanks. I am going to learn about Psyco. In this case, I assume that > doing the computations with floating point numbers and finally > converting the result to int gives the same values as the original > integer calculation. In other cases, integer arithmetic will need to > be done with integers to ensure correct results. Yes, in this case float has enough range. That is something you get to determine with any fixed length numeric representation. > Python is supposed to be easy (and in general I agree that it is), but > your solution requires some knowledge of > > (1) how integer and floating point calculations are done (which many > novices do not have) > (2) when Psycho can speed things up > > and the final result is still much slower than Fortran. For the > Fortran program, the only "trick" is the use of integer*8. With Fortran, you need to know how large your values are going to become. If you increased the number of iterations in your example sufficiently, Fortran's 64 bit integers would overflow requiring understanding of the concept of fixed range integers. Python avoids this by using unbounded integers. Python is oriented towards ease of use and correctness at the expense of speed. If the speed of the Python program is inadequate then you can take a working Python program and work on its speed. Or decide that the speed problem needs another language. Python does optimize integers that can be represented in 32 bits but larger than that and unbounded integers are used. For some applications, it would be better if Python also optimized integers that require between 32 and 64 bits. Neil From atmo at go2.pl Mon Mar 1 15:29:33 2004 From: atmo at go2.pl (Ringwraith) Date: Mon, 1 Mar 2004 21:29:33 +0100 Subject: tkFileDialog.askdirectory root directory ? Message-ID: Hello! I have the following problem. I use the tkFileDialog.askdirectory dialog to allow users of my application to pick some subfolder from 'C:/my_app' directory. I use initialdir='C:/my_app' option to set 'C:/my_app' as initial directory. But I want my initial directory to be also a root directory, so the user cannot pick any directory outside 'C:/my_app' folder. I have no idea how to do it using standard tkFileDialog.askdirectory. Is that possible? Thank you in advance for any hints. Best wishes, Niki From null at null.null Fri Mar 19 14:02:35 2004 From: null at null.null (SWright) Date: Fri, 19 Mar 2004 19:02:35 GMT Subject: Updating Widgets In-Reply-To: <405A9B0E.242E70EC@pobox.com> References: <405A9B0E.242E70EC@pobox.com> Message-ID: Thanks very much for the explanation. The actual program I'm working on has a lot of buttons so I was looking at different ways to control them. This will at least keep me from spending any more time on this path. From gary at fastlanenetworks.com Mon Mar 8 17:24:43 2004 From: gary at fastlanenetworks.com (Gary Braver) Date: Mon, 8 Mar 2004 17:24:43 -0500 Subject: Looking for general info on Python Message-ID: <000a01c4055c$2916d9b0$6702a8c0@eagleinvsys.com> Looking for general info on Python and comparisons to other programming languages. thanks gary braver fastlane networks www.fastlanenetworks.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From loic at fejoz.net Thu Mar 25 06:36:42 2004 From: loic at fejoz.net (Yermat) Date: Thu, 25 Mar 2004 12:36:42 +0100 Subject: PyPI Enhancements In-Reply-To: References: Message-ID: David McNab a ?crit : > Hi, > > I'm just looking through the PyPI tutorial, liking the fact that it's > now integrated with distutils, but seeing room for much more. > > Is any work being done to add some CPAN-like or apt-like features to PyPI? > > On first look, it doesn't appear that it would be too hard to add some > debian apt-like features such as: > > * ability to declare dependencies in the setup.py metadata > * a pypi directory inside the python directory tree, containing: > * package source trees > * cached list and dependency tree > * list of what's installed and what isn't > * an apt-like 'sources.list', whereby people can at their > discretion add supplementary download sources or mirrors > * a pypi command, which: > * searches/lists/downloads desired package(s) > * caches a dependency tree > * when trying to build or install a new package, builds a tree > of unfulfilled dependencies, and asks for permission to > download/build(/install) the dependencies > > I'd see it ideally working a bit like Debian's 'apt-get' and > 'apt-cache' commands. > > For instance: > > - pypi search [...] > - pypi download [...] > - pypi build [...] > - pypi install [...] > > The 'download', 'build' and 'install' commands would require root, and > would cause packages to get downloaded into a pypi directory within the > python lib. If these packages have unfulfilled dependencies, pypi (like > Debian's 'apt') would list the additional packages and ask for > permission to build/install these as well. > > Also: > - pypi enable-auto > > This would install dummy modules for all non-installed packages. When a > program tries to import an uninstalled package, pypi terminates the > program with a PypiNotInstalled exception, telling the user to become > root and install the missing packages (of course, listing the packages > needing to be installed. > > Thoughts? > > Cheers > David > That would be great ! Should also have an update command. Instead of installing dummy modules, you can add a hook on the import function... Yermat From uche at ogbuji.net Sun Mar 14 23:29:25 2004 From: uche at ogbuji.net (Uche Ogbuji) Date: 14 Mar 2004 20:29:25 -0800 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: richard at cogsci.ed.ac.uk (Richard Tobin) wrote in message news:... > > 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. My apoloies for the misattribution. --Uche From tismer at stackless.com Mon Mar 29 08:59:52 2004 From: tismer at stackless.com (Christian Tismer) Date: Mon, 29 Mar 2004 15:59:52 +0200 Subject: Tabbing probs (was: Prothon Prototypes vs Python Classes) In-Reply-To: <406829FF.5060304@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> <106g7r5nbg9ur16@news.supernews.com> <406829FF.5060304@mlug.missouri.edu> Message-ID: <40682BD8.3040501@stackless.com> Michael wrote: ... > Do people actually post and read a lot of source code on mail or > newsgroup lists? Is that the main reason for not using tabs in code? > That'd seem a bit odd to me. Never actually tried using OE to read code. > I really don't use OE. Why wouldn't you just open the code in your code > editor of choice? 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. -- 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 rganesan at myrealbox.com Wed Mar 3 07:09:40 2004 From: rganesan at myrealbox.com (Ganesan R) Date: Wed, 03 Mar 2004 17:39:40 +0530 Subject: Which Python module for PostgreSQL? References: Message-ID: >>>>> "David" == David M Cook writes: > In article , Ganesan R wrote: >>> python2.3-pgsql - A Python DB-API 2.0 interface to PostgreSQL v7.x >>> python2.3-popy - module providing access to PostgreSQL from Python2.3 >>> python2.3-psycopg - Python 2.3 module for PostgreSQL >>> python2.3-pygresql - PostgreSQL module for Python >> >> I prefer the first one - it's BSD licensed, actively maintained and >> supported. It's also very compatible with the python SQLite binding which I >> use regularly. I was referring to python2.3-pgsql which is the same as pyPgSQL. > PyGreSQL (the first one), doesn't seem to handle boolean's correctly in > Python 2.3. Is there a workaround (aside from translating back and forth > before saving)? This is the version that ships with Red Hat 9. I presume you meant to say "the last one" :-). Ganesan -- Ganesan R From olku at web.de Fri Mar 19 04:44:32 2004 From: olku at web.de (Oliver Kurz) Date: Fri, 19 Mar 2004 10:44:32 +0100 Subject: Best way to convert string a to utf-* Message-ID: Hello, could someone tell me the best way to convert a string to utf, for example to utf-8? The problem: I have no controll about the source where the string comes from. It could have any possible characterset. And I have to convert it for example to utf-8. Is there a good way to do this? And when, how? Is there a function which tell me, what is the characterset of the string at the moment? Would be create, when someone could help me! cu Oliver From trevp_spam at trevp.net Tue Mar 23 06:16:35 2004 From: trevp_spam at trevp.net (Trevor Perrin) Date: Tue, 23 Mar 2004 11:16:35 GMT Subject: SHA-based subclass for random module In-Reply-To: <5d83790c.0403230111.1a5137e8@posting.google.com> 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> Message-ID: Raymond Hettinger wrote: > [Trevor Perrin] > >>>Actually, Random could be made even easier to subclass. getrandbits >>>(which is new in 2.4) returns a long. It would be better for us if >>>there was a getrandstring() function that an underlying generator >>>could implement. This would also be a helpful addition to the API, at >>>least for cryptographic uses. > > > [Paul Rubin] > >>I agree with this, and was going to propose the same thing. >>getrandbits can be defined easily in terms of getrandstring, and the >>current sample sharandom implemenation at >> >> http://www.nightsong.com/phr/python/sharandom.py >> >>does something along those lines. > > > If you're sure you need this, please put a feature request on SF. It > needs to have a use case other than feeding message digest funtions -- > that need is readily met with str(x) or the faster hex(x). One use case is cryptographic things like symmetric keys, IVs, nonces, random padding, etc. > The new genrandbits() method was designed around the use case of > making randrange() work over very large intervals which was necessary > for creating large primes for RSA work. In addition, all of the > methods internal to the Random module work with numbers instead of > byte strings. Even still, I think getrandstring() would be a more convenient primitive than getrandbits(): - cryptographic generators (which you'll want for RSA) are more naturally defined in terms of byte strings - it's not hard to convert byte-strings to longs or floats, but it would be better for this conversion to be done in the Random base class, instead of forcing every subclass to do it - getrandstring() is a useful addition to the API, whereas getrandbits() is trivally done by calling randint(0, 2**k). Trevor From mike at zcentric.com Tue Mar 16 09:33:11 2004 From: mike at zcentric.com (Mike Zupan) Date: Tue, 16 Mar 2004 09:33:11 -0500 (EST) Subject: py2exe and urllib(2) errors In-Reply-To: References: Message-ID: <47778.66.193.31.32.1079447591.squirrel@www.zcentric.com> this was my command line c:\python23\python setup.py py2exe -pPIL --packages=encodings it was using py2exe 4.2. I also tried with no = to get the same results Mike > (From the py2exe homepage: > http://starship.python.net/crew/theller/py2exe/) > ..if your exe-file reports errors like LookupError: no codec search > functions registered: can't find encoding or LookupError: unknown > encoding, you should advise py2exe to include this package with the > '--packages encodings' command line option. > > Google turns up information very quickly. > > Larry Bates > > > "Mike Zupan" wrote in message > news:mailman.6.1079387105.742.python-list at python.org... > I had some problems with urllib and py2exe under pyton2.3. I works fine > until i try to use the exe file. > > Here is the error > > Error: 1 > LookupError Exception in Tk callback > Function: instance > at 0x00DF4058>> (type: ) > Args: () > Traceback (innermost last): > File "Pmw.pyc", line 1784, in __call__ > None > File "", line 270, in selectDir > None > File "", line 361, in grabAlbumDirs > None > File "", line 431, in addAlbumData > None > File "", line 469, in grabImage > None > File "urllib2.pyc", line 129, in urlopen > None > File "urllib2.pyc", line 326, in open > None > File "urllib2.pyc", line 306, in _call_chain > None > File "urllib2.pyc", line 901, in http_open > None > File "urllib2.pyc", line 884, in do_open > None > File "httplib.pyc", line 712, in endheaders > None > File "httplib.pyc", line 597, in _send_output > None > File "httplib.pyc", line 564, in send > None > File "httplib.pyc", line 532, in connect > None > LookupError: no codec search functions registered: can't find encoding > > > Here is the section of code that produces the error > > urllib.urlretrieve(imageURL, saveFile) > > imageURL and saveFile are correct > > > Here is my setup.py file > > # setup.py > from distutils.core import setup > > import py2exe > > setup( > scripts=["art.py"] > ) > > > and here is my batch file > > c:\python23\python setup.py py2exe -pPIL --packages=encodings > > > Thanks > Mike > > > > > -- > http://mail.python.org/mailman/listinfo/python-list From simoninusa2001 at yahoo.co.uk Thu Mar 4 00:08:40 2004 From: simoninusa2001 at yahoo.co.uk (simo) Date: 3 Mar 2004 21:08:40 -0800 Subject: ready to use python, need help with GUI decision References: Message-ID: <30260531.0403032108.3bfc4312@posting.google.com> If you've got some money to buy a Windows commercial license, or just want to program for Linux/GPL, then I'd say go with PyQt. The only thing that puts me off is the stupid licensing issues which even the PyQt/Qt/BlackAdder folks don't seem to grasp. If you don't want to pay anything and go with whatever license you want on Windows/Linux, then I'd say go with wxPython. What puts me off is that some of the dialogs are completely different between OSes, or have limited functionality on Linux. If you don't really mind how it looks and don't need a wide range of widgets and just want something easy, I'd say go for TKinter. From lbates at swamisoft.com Mon Mar 1 18:20:10 2004 From: lbates at swamisoft.com (Larry Bates) Date: Mon, 1 Mar 2004 17:20:10 -0600 Subject: NT Services and EventLog problems Message-ID: 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 From patois at calvix.org Fri Mar 19 13:12:03 2004 From: patois at calvix.org (Yannick Patois) Date: Fri, 19 Mar 2004 19:12:03 +0100 Subject: Package name with '.' in them: Python Bug ? In-Reply-To: References: Message-ID: 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. >>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. >>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 ? > 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. >>$ ./aTest.py >>None >>Renaming B.py to B.1.py made A unable to keeps the value of it's static >>variable. > > It seems to me that it *kept* its original value. However you called it, it doesnt behave the same (and doesnt behave the way python should work). The change is only a file name, no more. > I would put more print > statements into both A.A and B.B and maybe even aTest.py to see where > execution first differs. It breaks in B, if I remember well. >>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. > > import b.b1 would normally mean import file (module) b1 in the b package > directory. It's not the case here: would have it be that the import statement would have broke with "cant find that module". > But imp obviously did not find fine '1' in a 'B' directory. It didnt seek for it, it just loaded 'B.1' as asked. Everything seems to work, except that some internal python dictionnary has likely been corrupted. Correct behavior would either be "break on 'cant import module 1 from B'" or "correctly import B.1 without corrupting anything." To me, that's look to be a bug. 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 premshree_python at yahoo.co.in Wed Mar 10 02:45:39 2004 From: premshree_python at yahoo.co.in (=?iso-8859-1?q?Premshree=20Pillai?=) Date: Wed, 10 Mar 2004 07:45:39 +0000 (GMT) Subject: Python vs Perl (an example) Message-ID: <20040310074539.12029.qmail@web8309.mail.in.yahoo.com> Hello, I recently wrote a Perl version of pyAlbum.py [1] -- a Python script to create an image album from a given directory -- plAlbum.pl [2]. It made me realize how easy-to-use Python is. [1] http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/271246 [2] http://www.premshree.resource-locator.com/cgi-bin/source.pl?file=../perl/plAlbum.pl -Premshree Pillai ===== -Premshree [http://www.qiksearch.com/] ________________________________________________________________________ Yahoo! India Insurance Special: Be informed on the best policies, services, tools and more. Go to: http://in.insurance.yahoo.com/licspecial/index.html From fgeiger at datec.at Fri Mar 12 13:14:00 2004 From: fgeiger at datec.at (F. GEIGER) Date: Fri, 12 Mar 2004 19:14:00 +0100 Subject: UNC paths in file object open References: <4051f619$0$6547$ed9e5944@reading.news.pipex.net> Message-ID: What's the error? Can you provide a trceback? Regards Franz P.S.: Im not sure but accessing a share on a machine NOT connected to a network doesn't work since 2k and XP (worked on NT, though). "Graham" schrieb im Newsbeitrag 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 jacek.generowicz at cern.ch Mon Mar 15 03:44:50 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 15 Mar 2004 09:44:50 +0100 Subject: Static Typing in Python References: <67efcd4ccaf87ddf3c640aad5517017a@news.teranews.com> <7de2e74a623ae9f3ff3fe9ae4e1ec2b4@news.teranews.com> Message-ID: Dang Griffith writes: > >Not forcing variable initialization does have its problems. Here's > >what I mean: > >http://www.livejournal.com/users/premshree/10624.html?thread=53376#t53376 > > Yes, I agree. That is one reason I like Python. > It has forced variable *initialization*. You cannot use a variable > that has not been initialized. But there is nothing to prevent you from assigning to a previously non-existing variable, which is what Premshree is concerned about. > In fact, the act of initializing a variable is what makes the > variable exist. Exactly, make a typo, and the compiler won't notice. This can indeed be a minor annoyance in interactive exploration. However, the development of a real program, backed by a test suite, will catch the problem in no time. It's just one of the thousands of possible styles of bugs that you can introduce into the program ... ALL of which will be caught by a decent test suite. Adding restrictions to a language just to catch one of the many of styles of possible bugs is counterproductive. Support your development with a decent test suite, and use the most flexible language you can get your hands on. From donn at u.washington.edu Mon Mar 1 14:30:01 2004 From: donn at u.washington.edu (Donn Cave) Date: Mon, 01 Mar 2004 11:30:01 -0800 Subject: inetd script in python? References: <8ab78660.0402270403.6a36f7f3@posting.google.com> Message-ID: In article , Nick Craig-Wood wrote: > Jan wrote: > > So far I read about that I could use stdin and stdout for > > communication since inetd handles the socket. And I read that I > > could use socket.fromfd to get a socket object to work with. But > > both do not work, I tried to send just a greeting back to the > > client or getting some text - nothing. > > You should find something simple like this works - inetd is supposed > to make writing internet daemons easy! > > import sys > > while 1: > bfr = sys.stdin.read(1024) > sys.stdout.write(bfr) > > You can then test the code on the command line by typing stuff to it > and seeing it print its output. > > Beware buffering though! Indeed, to the point where the code you propose would not work when you test it the way you propose. Donn Cave, donn at u.washington.edu From tjreedy at udel.edu Wed Mar 10 12:28:01 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 10 Mar 2004 12:28:01 -0500 Subject: The Order Of Dictionary Entries References: Message-ID: "Tim Daneliuk" wrote in message news:in93i1-ctp1.ln1 at eskimo.tundraware.com... > I am aware that dictionary order is not guaranteed. But I ran into > something puzzling today. I filled a dictionary dynamically as a > program ran. Up to a certain point, the key order was the order > in which things were added. I am rather certain that this was an accident dependent on you adding the keys in the order in which they were going to displayed. Try adding the items in a different order and the display order should not change much if at all. Example: >>> {1:1, 2:2} {1: 1, 2: 2} >>> {2:2, 1:1} {1: 1, 2: 2} Terry J. Reedy From fey at parsytec.de Thu Mar 11 16:34:17 2004 From: fey at parsytec.de (Sebastian Fey) Date: Thu, 11 Mar 2004 22:34:17 +0100 Subject: pyXML:save changes made to DOM-tree, get entity-uri Message-ID: <53DD404D1B0B67479AD684BFFA54858B2429A8@srvac03.parsytec.local> (hope MSOWebAccess will send this message as plain text) 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) (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. ############# text'> ]> &intTxt; &intMarkup; &extParsed; ############ becomes: ############# some text text' text' ############# thx, Sebastian From jcarlson at nospam.uci.edu Tue Mar 9 15:14:31 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Tue, 09 Mar 2004 12:14:31 -0800 Subject: Fast way to send message between 2 child processes? (using a file is too slow?) In-Reply-To: <7xoer6i2s7.fsf@ruckus.brouhaha.com> References: <20040309032505.GA18682@unpythonic.net> <7xoer6i2s7.fsf@ruckus.brouhaha.com> Message-ID: > http://gigue.peabody.jhu.edu/~mdboom/omi/source/shm_source/shm.html > > But you will have to know what you're doing. OOO, that is nice. I've been using IP sockets for all local communication, sweet. - Josiah From fperez528 at yahoo.com Mon Mar 8 10:55:53 2004 From: fperez528 at yahoo.com (Fernando Perez) Date: Mon, 08 Mar 2004 08:55:53 -0700 Subject: Best way to run ipython inside of emacs shell? References: <692feddd.0403072229.7d1d4675@posting.google.com> Message-ID: Hi, Equis Uno wrote: > I use meta-x shell to start a shell and then once I see a shell > prompt I enter the python command and I get a well-behaved python > shell inside of emacs. > > I'm trying to figure out the best way to run ipython inside of emacs. Try instead putting the following in your .emacs file: (require 'ipython) Then, start the ipython shell via C-c ! (that is, Control-C followed by an exclamation mark), _from_ a python buffer. Don't do meta-x 'shell', because it won't initialize properly the color handling. Let me know if this works ok. Feel free to mail me directly to fperez-AT-colorado-DOT-edu, I'm the ipython main developer, or to the mailing lists. If I get stuck (I'm no emacs expert), we can ask Alex Schmolck, the original author of ipython support for emacs. cheers, f From __peter__ at web.de Thu Mar 25 05:18:33 2004 From: __peter__ at web.de (Peter Otten) Date: Thu, 25 Mar 2004 11:18:33 +0100 Subject: Split a string by length References: Message-ID: Pascal wrote: > 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'] >>> def chunks(s, chunklen): ... for i in range(0, len(s), chunklen): ... yield s[i:i+chunklen] ... >>> list(chunks("aabbcc", 2)) ['aa', 'bb', 'cc'] >>> list(chunks("aabbc", 2)) ['aa', 'bb', 'c'] >>> Peter From wweston at att.net Sat Mar 6 13:52:57 2004 From: wweston at att.net (wes weston) Date: Sat, 06 Mar 2004 18:52:57 GMT Subject: Question please In-Reply-To: References: Message-ID: Abe and Barb K. wrote: > I have a new HP computer that seems to have come with Python 2.2 with > win32 extensions software. > > I'm not a programmer or tech and would like to know if I can just remove > this software without affecting anything in my system as it is taking up > space if I'm not going to use it? > > Thanks so much. > Barbara K. Abe/Barb, It sounds like you are running a Dos/Windows variant so it is unlikely anything system crucial needs Python. You could probably move the Python to a new directory, say, \PythonTemp. Run for some time to check it out, move it back where it was, and uninstall. You could also check out the tutorial on python.org. Python may be the fastest growing language - due to its popularity. wes From Spam at ivonet.nl Thu Mar 4 14:07:18 2004 From: Spam at ivonet.nl (Ivo) Date: Thu, 4 Mar 2004 20:07:18 +0100 Subject: Download counter Message-ID: <40477e62$0$3895$3a628fcd@reader2.nntp.hccnet.nl> people why does this not work?? I have tried to write a download manager (counter) for my website called something like this: http:///cgi-bin/download.py?FileID=1 I do get a download popup but the download is broken. Someting is not right and I don't know what. Excuse my sloppy code... It is stil in test. Code below, help appreciated. === #!d:/python/python.exe #e:/python23/python.exe import cgi import os import glob import sys __author__ = "Ivo Woltring" __version__ = "00.01" __doc__=""" Enable download with additional features like counters, logging, no direct downloads, etc. """ #=============================================================== # Realmap is the reference to the physic location of the root map # of your site RealMap = "D:/IvoNet.nl" #=============================================================== def WriteError(titel,text): print('Content-Type: text/html\r\n\r\n') print """\
%s

%s

%s """ % (titel,titel,text) sys.exit(1) #=============== # Main stuff #=============== #GetFormulier...and check it form = cgi.FieldStorage() if not form: WriteError('Download error:', 'No download was specified...') else: if form.has_key("FileID"): FileID=form["FileID"].value try: int(FileID) except: WriteError('Download error:', 'No valid ID was entered: %s' % (FileID,)) else: WriteError('Download error:', 'No valid key specified...') from IvoNetdb import IvoNetSpufi # load My database settings try: data = IvoNetSpufi("""SELECT location,archive FROM download WHERE id=%s """ % (FileID,)) # Will return a tuple with tuples in it. except: WriteError('ERROR','SQL Error.') # update the counter if not IvoNetSpufi("""UPDATE download SET downloadcounter = downloadcounter+1 WHERE id = %s """ % (FileID,)): WriteError('ERROR','Could not update downloadcounter') if not data: WriteError('ERROR','Did not find a match for ID: %s' % (FileID,)) else: #WriteError('data',data) data = data[0] # list in list is returned so make it easy on yourself loc = os.path.join(RealMap+data[0],data[1]) if not os.path.isfile(loc): WriteError('ERROR','File does not appear to be there anymore...') else: fhandle = open(loc, 'r') file = fhandle.read() fhandle.close() print('Content-Type: application/octet-stream; name=%s' % data[1]) #print('Content-type: application/force-download') print('Content-length: %s' % len(file)) print('Content-Disposition: attachment; filename="%s"' % data[1]) print print file #sys.stdout.write(file) == From miki.tebeka at zoran.com Wed Mar 10 03:12:16 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Wed, 10 Mar 2004 10:12:16 +0200 Subject: How to read between xml tags? In-Reply-To: References: Message-ID: <404ECDE0.4060809@zoran.com> Hello Anthony, > 1. The read operation must either read a full tag or > ignore the tag. > > 2. If the read operation reads between

and

, > then it must reads the whole thing between those 2 > tags all at once. > > How can I achieve this please? I think the xml.sax module is what you're looking for. A small, briefly tested something might be: --- #!/usr/bin/env python from xml.sax.handler import ContentHandler from xml.sax import parse class ArticleHandler(ContentHandler): def __init__(self, *ignore): ContentHandler.__init__(self) self.data = "" # Data buffer self.get = 0 # Get flag # Ignore hash self.ignore = {}.fromkeys([i.lower() for i in ignore]) def startElement(self, name, attrs): if name.lower() in self.ignore: self.get = 0 else: self.get = 1 def endElement(self, name): self.get = 0 def characters(self, content): if self.get: self.data += content from sys import argv handler = ArticleHandler() parse(argv[1], handler) print handler.data # Will print full data handler = ArticleHandler("headline") parse(argv[1], handler) print handler.data # Will print data without headlines --- HTH. Miki From antonyliu2002 at yahoo.com Wed Mar 10 04:14:19 2004 From: antonyliu2002 at yahoo.com (Anthony Liu) Date: Wed, 10 Mar 2004 01:14:19 -0800 (PST) Subject: What is wrong? The minidom or the XML file? Message-ID: <20040310091419.56049.qmail@web13006.mail.yahoo.com> I copy-pasted the following sample xml document from http://slis-two.lis.fsu.edu/~xml/sample.html and saved it as samplexml.xml. Please note that I removed the following line from the original xml sample. Sample Document Brandon Voss The XML Pages This is element text and an entity follows:&Description; Then, I attempted to parse this xml document with the following python code, which is saved as xmltest.py. from xml.dom import minidom xmldoc = minidom.parse('sample.xml') print xmldoc.toxml() I got the following error message: >>> Traceback (most recent call last): File "C:\Python23\codes\xmltest.py", line 4, in -toplevel- xmldoc = minidom.parse('samplexml.xml') File "C:\Python23\lib\xml\dom\minidom.py", line 1919, in parse return expatbuilder.parse(file) File "C:\Python23\lib\xml\dom\expatbuilder.py", line 924, in parse result = builder.parseFile(fp) File "C:\Python23\lib\xml\dom\expatbuilder.py", line 207, in parseFile parser.Parse(buffer, 0) ExpatError: not well-formed (invalid token): line 1, column 5 >>> I have no clue why that xml document is not well-formed. Any hint please? __________________________________ Do you Yahoo!? Yahoo! Search - Find what you?re looking for faster http://search.yahoo.com From claird at lairds.com Tue Mar 2 12:24:30 2004 From: claird at lairds.com (Cameron Laird) Date: Tue, 02 Mar 2004 17:24:30 -0000 Subject: Lua Book References: <2ae25c6b.0403020006.6b99e590@posting.google.com> <1048rn8lpr0acde@corp.supernews.com> Message-ID: <1049gqe9n762hf6@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. -- Cameron Laird Business: http://www.Phaseit.net From mwilson at the-wire.com Tue Mar 30 11:38:10 2004 From: mwilson at the-wire.com (Mel Wilson) Date: Tue, 30 Mar 2004 11:38:10 -0500 Subject: ESR's fortune.pl redone in python - request for critique References: Message-ID: Or I could see (untested code) import random, sys def fortunes (infile): return infile.read().split ('\n%\n') def findfortune (filename): return random.choice (fortunes (file (filename, 'rt')) if __name__ == '__main__': print findfortune (sys.argv[1]) Regards. Mel. From mogmios at mlug.missouri.edu Tue Mar 30 19:32:21 2004 From: mogmios at mlug.missouri.edu (Michael) Date: Tue, 30 Mar 2004 16:32:21 -0800 Subject: Python Documentation Blows! In-Reply-To: <20040330181802.04141.00000304@mb-m17.aol.com> References: <20040330181802.04141.00000304@mb-m17.aol.com> Message-ID: <406A1195.5010908@mlug.missouri.edu> >I have not yet contributed anything to the python documentation myself. > > One thing I like about PHP's docs is that it allows users to post comments, suggestions, extra information, etc to the docs online. Now and then someone goes through and edits the useful bits into the official documentation and flushes the comments all back out leaving them clear for new people to post their own. Several times I've attached comments as to how to compile a module or use some poorly documented feature and have had lots of people write to thank me for how helpful those comments were. I'd imagine the same process could be useful in Python. From mwh at python.net Thu Mar 4 14:40:55 2004 From: mwh at python.net (Michael Hudson) Date: Thu, 4 Mar 2004 19:40:55 GMT Subject: OT(Slightly): Thanks to Python. References: <104emss6ca09l45@news.supernews.com> Message-ID: "John Roth" writes: > As far as I am concerned, 2 and 3 are so whats. 1 would be nice at > times, but there's no way it's going to happen in a language that > doesn't have static typing. Well, it's called multiple dispatch. Could be done, but it's quite a paradigm shift. Cheers, mwh -- Two things I learned for sure during a particularly intense acid trip in my own lost youth: (1) everything is a trivial special case of something else; and, (2) death is a bunch of blue spheres. -- Tim Peters, 1 May 1998 From artur_spruce at yahoo.com Wed Mar 24 03:39:22 2004 From: artur_spruce at yahoo.com (AdSR) Date: 24 Mar 2004 00:39:22 -0800 Subject: Voting (was Re: PEP 318 References: Message-ID: Ville Vainio wrote: > FWIW, I prefer > > def f(x,y) [wrapper,wrapper...]: > pass > > or > > def f(x,y) as iterable: > pass > > and would oppose > > def f [wrapper, wrapper...] (x,y): > pass > > Like others, I want to see the param list right next to the function > name. I like the "as iterable" form much better than any other. The "as" word says immediately what it means. Also, since in some situations tuples are written without parens ("a, b, c = three_elem_tuple"), you could allow for: def f(x, y) as decor1, decor2, decor3: pass Cheers, AdSR From jceasar at tmp.org Thu Mar 4 16:46:56 2004 From: jceasar at tmp.org (jceasar at tmp.org) Date: Thu, 04 Mar 2004 13:46:56 -0800 Subject: ^_^ meay-meay! Message-ID: Looking forward for a response :P ..btw, "80063" is a password for archive -------------- next part -------------- A non-text attachment was scrubbed... Name: Message.zip Type: application/octet-stream Size: 21304 bytes Desc: not available URL: From donn at u.washington.edu Mon Mar 15 12:30:31 2004 From: donn at u.washington.edu (Donn Cave) Date: Mon, 15 Mar 2004 09:30:31 -0800 Subject: Static Typing in Python References: Message-ID: 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 > strongly typed, i.e., variables are necessarily bound > to a particular type. Just a nit-picking annotation - static typing actually does not require explicit declaration. Some of very strongl statically typed languages, mainly functional languages like Haskell and ML, use type inference instead, and programs written in those languages will generally have declarations only to clarify or narrow the type of an expression when it suits the programmer. We now return you to our regularly scheduled debate over whether Python's typing is "strong" or not, with the observation that "strong" in "strongly statically typed" apparently is not the same "strong" as in "strongly typed." I guess it's fun to have something to wrangle over that doesn't have any real consequence, but let's be clear about that - "strongly typed" is a useless phrase. It may be correctly applied to Python, but only to someone who already understands what is being communicated, so of no value to anyone but language taxonomists. Are you folks sure you wouldn't rather talk about whether parameters are passed by value or by reference? Donn Cave, donn at u.washington.edu From JasonHarper at pobox.com Thu Mar 11 17:15:58 2004 From: JasonHarper at pobox.com (Jason Harper) Date: Thu, 11 Mar 2004 15:15:58 -0700 Subject: Exiting Tkinter when using IDLE References: Message-ID: <4050E31D.EEB18C9F@pobox.com> 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 2. Don't call mainloop() if IDLE already has one running. Try this: import sys if "idlelib" not in sys.modules: root.mainloop() Jason Harper From axelboldt at yahoo.com Tue Mar 16 15:55:59 2004 From: axelboldt at yahoo.com (Axel Boldt) Date: 16 Mar 2004 12:55:59 -0800 Subject: Result of ``a is b'' References: <40200384.0403151632.35496ee6@posting.google.com> Message-ID: <40200384.0403161255.7fca7a8c@posting.google.com> 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. 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. Axel From pinard at iro.umontreal.ca Mon Mar 22 20:18:18 2004 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Mon, 22 Mar 2004 20:18:18 -0500 Subject: 3D apps in Python? In-Reply-To: <338366A6D2E2CA4C9DAEAE652E12A1DE014C718C@au3010avexu1.global.avaya.com> References: <338366A6D2E2CA4C9DAEAE652E12A1DE014C718C@au3010avexu1.global.avaya.com> Message-ID: <20040323011818.GA14644@alcyon.progiciels-bpi.ca> [Delaney, Timothy C (Timothy)] > > From: Brandon J. Van Every > He's ba-ack ... :-). Indeed. The pattern is always the same. Some innocuous question or remark at the start, and the progressive build up of inflammatory contents as replies and exchanges go. Hoping that newcomers to the Python list will resist falling in the various traps, this time :-), it might nevertheless be interesting to observe the mechanics of the degradation, at least in the very beginnings of it. As usual, it will soon become annoying and noisy! Sigh! -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From trevp_spam at trevp.net Tue Mar 23 17:33:28 2004 From: trevp_spam at trevp.net (Trevor Perrin) Date: Tue, 23 Mar 2004 22:33:28 GMT Subject: SHA-based subclass for random module In-Reply-To: <5d83790c.0403230857.50e3bc73@posting.google.com> 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: Raymond Hettinger wrote: > [Trevor Perrin] > >> - getrandstring() is a useful addition to the API, whereas >>getrandbits() is trivally done by calling randint(0, 2**k). > > > Actually, randint() is implemented in terms of getrandbits() when > k>53. This saves needless conversions in and out of floating point. I'm proposing that getrandstring() (returning a string) is a better primitive than getrandbits() (returning a long). A generator should only have to implement getrandstring(), and the base class would synthesize everything else. That way, the conversion routines (from byte-strings to longs and floats) don't have to be replicated in each subclass. This would simplify Paul's sharandom class, and the platform-specific generators I'm thinking of: class devurandom(random.Random): def __init__(self): self.f = open("/dev/urandom", "rb") def getrandstring(n): return self.f.read(n) Also, the getrandstring() function would be useful for end-users (which was my point above): sslPreMasterSecret = secureRandom.getrandstring(48) This would be easy to implement with Mersenne Twister too. Though it would involve some rewriting. Do you think this is worthwhile? Trevor From cns at RedBrick.dcu.ie Wed Mar 3 10:56:16 2004 From: cns at RedBrick.dcu.ie (Cillian Sharkey) Date: Wed, 3 Mar 2004 15:56:16 +0000 Subject: XML-RPC server framework Message-ID: <20040303155616.GA28132@carbon.redbrick.dcu.ie> Hi, I'm trying to find any existing frameworks for writing an XML-RPC server that has the following features: - HTTPS - connection oriented (HTTP/1.1 persistent connections) - multiple concurrent connections - hooks for custom handling of HTTP basic authentication - dynamic documentation on GET requests a la DocXMLRPCServer I'm aware of xmlrpclib, M2Crypto, py-xmlrpc, Twisted but haven't found an existing implementation that does all of the above. I'd prefer not to have to write it myself :-) Any tips appreciated (please CC me on replies). Thanks, -- Cillian From jmiller at stsci.edu Fri Mar 19 17:58:38 2004 From: jmiller at stsci.edu (Todd Miller) Date: 19 Mar 2004 17:58:38 -0500 Subject: Tkinter focus under windows Message-ID: <1079737118.15162.266.camel@halloween.stsci.edu> I'm working on a Tkinter backend for the matplotlib plotting software. matplotlib can be run interactively from some form of Python shell while plotting to a Tk window. One annoyance we've noticed is that when we update the plot window, it steals the focus from the shell window, at least on a Win32 platform. I am very new to Tkinter so I am looking for insight into how the focus works on win32 and how to prevent the Tkinter window from stealing focus from the shell window. Any ideas? Thanks, Todd Miller From garryknight at gmx.net Sun Mar 14 18:30:23 2004 From: garryknight at gmx.net (Garry Knight) Date: Sun, 14 Mar 2004 23:30:23 +0000 Subject: getting size of gif References: <9L2dna_mgLuovNPd4p2dnA@comcast.com> <104se8bhc5rm477@corp.supernews.com> Message-ID: <1079307022.31907.0@nnrp-t71-02.news.uk.clara.net> In message , Fredrik Lundh wrote: > note that you don't need all of PIL to run the above example; it's enough > to install Image.py, ImageFile.py, ImagePalette.py, and the > *ImagePlugin.py files you need for your application. the binary > extensions are not needed. Gosh, what a payload! It might not be the Python way of doing things, but this should work just as well: f = open('x.gif', 'rb') gif = f.read(6) # 'gif89a' width = ord(f.read(1)) + 256 * ord(f.read(1)) depth = ord(f.read(1)) + 256 * ord(f.read(1)) print "width = %d, depth = %d" % (width, depth) You could just do f.seek(6) in the second line if you're not worried about checking that it's a valid gif file. Of course, this only works with single-image files, not with animated gifs. -- Garry Knight garryknight at gmx.net ICQ 126351135 Linux registered user 182025 From hungjunglu at yahoo.com Mon Mar 29 00:02:25 2004 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 28 Mar 2004 21:02:25 -0800 Subject: Prothon Prototypes vs Python Classes References: <106dukh7ncf9ad4@news.supernews.com> Message-ID: <8ef9bea6.0403282102.632ae427@posting.google.com> Harald Massa wrote in message news:... > 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? It is possible, but you will not be able to retroactively apply it to many existing objects. You will only be able to do things with your new customized objects. For instance, there is a class called 'module', and in Python you cannot add attributes to it. Similary, there is a metaclass 'type', and you cannot add attributes nor insert hooks to it. Either you start afresh with prototypes from ground up, or you won't be able to modify the behavior of existing Python objects. I believe there was already some previous attempts along the line that you have said. > 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". Sure, adding an attribute to *your* objects is not an issue. Adding attributes and modify the behavior of other people's objects is the issue. These "other people's objects" include system objects, and objects created by third-party. The "other people" often include yourself. It is hard to explain. Maybe I can suggest reading my previous posting: http://groups.google.com/groups?q=g:thl1486542349d&dq=&hl=en&lr=&ie=UTF-8&oe=UTF-8&selm=8ef9bea6.0403260837.72a8fade%40posting.google.com&rnum=27 There are quite a few software development needs that one only discovers when one goes to large projects, with various components, maybe even in different languages. It is only when things get complex that you wish you had a clean and pure foundation. When your projects are small, deficiencies and impurities in your language don't matter too much. ----------------------- I think the current way how OOP is taught is kind of bad. The lectures would start with definition of classes, inheritance, virtual functions, etc. As I have mentioned a few times in this mailing list, software engineering, and all human intellectual activities, ultimately come down to factorization (of code, or of tasks). From simple algebra to supersymmetric quantum field theory, it has been so. From goto statements to OOP to metaclasses to AOP to prototype-based, it has been so. Instead of starting with dogmas and axioms, people can probably better focus on factorization and how it happened. People don't just invent OOP or prototype-based language out of blue, nor did they come up with database normalization rules out of blue. People arrived at these devices because they observed: (1) similar tasks or code spots all over places, that is, they discovered a symmetry, a repetitive pattern, which often was becoming painful to deal with, (2) they then figured out a way to factorize the code or organize the tasks, so to factor out the common part and make their lives less painful. It's only after (2) that they invent a new concept or technology, and from then on they know that in the future they can start right away with the new approach, instead of writing the same code in two spots and later having to factorize them out. ------------------ I often don't know how to take it when I see people talking about OOP by using definitions like: polymorphism, data hiding, etc. As if these definitions were something of utmost importance. To me, OOP is just a tool for factorizing code, just like using for-loops and using functions to factor out repetitive code. Polymorphism, data hiding, etc. are all secondary features: code factorization is the heart and soul of OOP. Class-based OOP is a way of factorizing. Prototype-based is just another way of factorizing, which seems to be more elegant: instead of two concepts (classes and instances), you unify them and have only one concept (objects). Moreover, in a prototype-based language like Io, even scopes and objects are unified. In C++, many new programmers get confused about the usage of macros, templates (generics in Java in C#) and multiple inheritance (mix-in). Sure, they are harder to read. But behind each device, the simple and ultimate goal is nothing but code factorization. Metaprogramming in Python? The same thing. A CS professor friend of mine once said: "all problems in CS are solved by just one more level of indexing," which has been very true in my experience. I would like to say further that if someone truly understands factorization and applies it at every moment, then he/she should not only be awarded a Ph.D. in CS but perhaps also a Nobel Prize. :) Hung Jung From mark at prothon.org Mon Mar 29 04:50:08 2004 From: mark at prothon.org (Mark Hahn) Date: Mon, 29 Mar 2004 01:50:08 -0800 Subject: A 'Python like' language References: <40645d8f$0$10775$afc38c87@news.easynet.co.uk> Message-ID: <2jS9c.58187$cx5.18518@fed1read04> > What does stacklessness do for me as an application programmer? The first thing is lack of recursion limits. Later you will find continuations and other cool things. Mark Hahn (Prothon Author) "Roy Smith" wrote in message news:roy-2A7F76.07570527032004 at reader1.panix.com... > "Jon Franz" wrote: > > What I found interesting was: > > - the stackless-ness > > What does stacklessness do for me as an application programmer? From claird at lairds.com Tue Mar 16 09:21:36 2004 From: claird at lairds.com (Cameron Laird) Date: Tue, 16 Mar 2004 14:21:36 -0000 Subject: Tkinter3000 References: <105cr4i7evg2gce@news.supernews.com> Message-ID: <105e3bgll8cpq23@corp.supernews.com> In article <105cr4i7evg2gce at news.supernews.com>, John Roth wrote: > >"Batista, Facundo" wrote in message . . . >> What a pitty. Is there some project to document Tkinter? > >"Python and Tkinter Programming" by Grayson (Manning 2000) >is still availible. It's a bit long in the tooth, but it's still a very >good guide. . . . 'Couple of us were just talking about setting up a Tkinter mailing list and Wiki. Should we? -- Cameron Laird Business: http://www.Phaseit.net From jepler at unpythonic.net Sun Mar 14 14:46:19 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Sun, 14 Mar 2004 13:46:19 -0600 Subject: Is reverse reading possible? In-Reply-To: <20040314191047.15699.qmail@web13012.mail.yahoo.com> References: <20040314180105.GB7397@unpythonic.net> <20040314191047.15699.qmail@web13012.mail.yahoo.com> Message-ID: <20040314194619.GE7397@unpythonic.net> 4M files are not that big these days. def reversed_file(name, encoding): contents = codecs.open(name, "r", encoding).read() contents = list(contents) contents.reverse() return "".join(contents) Example: >>> codecs.open("utf-example.txt", "r", "utf-8").read() u'60: CJK UNIFIED IDEOGRAPHS (0x4E00 - 0x9FFF) | \u4e25\u5f25\u6f25\n' >>> reversed_file("utf-example.txt", "utf-8") u'\n\u6f25\u5f25\u4e25 | )FFF9x0 - 00E4x0( SHPARGOEDI DEIFINU KJC :06' This assumes that you know the encoding for each file in advance, and that Python has a codec for it. Jeff From simon_place at whsmithnet.co.uk Sat Mar 6 07:53:57 2004 From: simon_place at whsmithnet.co.uk (simon place) Date: Sat, 06 Mar 2004 12:53:57 +0000 Subject: Writing dictionary output to a file In-Reply-To: References: Message-ID: <4049c9ea_2@mk-nntp-1.news.uk.worldonline.com> i use this to save and reload a dict, slower than pickling but you get a human readable file and its soooo simple. a={1:'one',2:'two'} >>> a {1: 'one', 2: 'two'} # to save to dict.txt >>> print >>file('dict.txt','w+'),str(a) # to reload >>> exec('b=dict('+file('dict.txt','r').read()+')') >>> b {1: 'one', 2: 'two'} >>> From google at neilson.sent.com Sun Mar 7 20:48:49 2004 From: google at neilson.sent.com (Daniel H Neilson) Date: 7 Mar 2004 17:48:49 -0800 Subject: Question on loops Message-ID: I am a newcomer to python, and am not really much more than a hack at the other languages I speak, so forgive me if this is an easy question. I am processing a text file, taking an action based on what I find in each line. Independently of what the file contains, I need to take another action every 100 lines. Currently I am using something to the effect of: i = 0 for line in file: if i == 100: action i = 0 else: i += 1 process(line) But this doesn't feel like a very python-esque solution to me, and is not very elegant in any case. What would be a better way to do it? Thanks. From whamblen at yahoo.com Wed Mar 24 13:44:53 2004 From: whamblen at yahoo.com (Bill Hamblen) Date: 24 Mar 2004 10:44:53 -0800 Subject: Python newbie asking for help Message-ID: Hi, I'm teaching myself Python for fun. I've picked a little project that is interesting to me. I've made some progress over the last couple nights, mostly reading Guido's tutorial, but I think it would go a lot more quickly if I had some advice from experienced Python programmers. I think what I really need is a suggestion on the best data structure(s) to use. Here's what I am doing. I have three files with csv records (lines). We can have column headers at the top of each file if that helps. The first field in each record is a name; otherwise the files mostly contain different data. I'd like to create unique id numbers (in a new column) so that names which appear in more than one file have the same id number in each file. And of course every line in every file should end up with an id number. The catch is that while most names will appear in every file, some will not. Worse yet, there are names that will have different forms in different files (e.g. Smith_Bill and Smith_William). That last group I would like to "manually" process. Maybe by popping up a tkinter listbox with all records that match "Smith". Then I could select the ones which *really* match and give them a uniform id number. The good news is that I have already made sure that there are no duplicate name fields in any one file. Speed is a total non-issue here since it only has to run once for a given set of files. And no, this is not for merging spam lists! :-) I'm trying to make it easier to merge sets of projected statistics for fantasy baseball every spring. I do most of the processing in a spreadsheet but I thought indexing the sets of projections would be a fun way to learn Python. I read each file into a list of lists (using a csv module for Python 2.2). I've already added a new first column to hold the id number (so name is now in the second column). For example, lst1 looks like this: [['', 'name1_fname', 'team', 'pos, ...],['', 'name2_fname', ...], ...] I've got two search functions: one which looks for exact name matches and one which looks for last name matches (which I now notice needs to be made insensitive to capitalization). def search_exact(l, c, v): result=[] for r in l: if r[c] == v: result.append(r) return result def search_lastname(l, c, v): result=[] for r in l: if split(r[c],'_')[0] == v: result.append(r) return result The main loop id = 0 for lst in [lst1, lst2, lst3]: for row in lst: if row[0] <> '': #if it already has an id, skip it continue else: match=[] for ls in [lst1, lst2, lst3]: tmp = search_exact(ls, 1, row[1]) if tmp <> []: match.append(tmp) if len(match) == 3: #every file had one exact match #so assign an id number for i in match: i[0] = id id = id + 1 else: match = [] for ls in [lst1, lst2, lst3]: tmp = search_lst(ls, 1, split(row[1],'_')[0]) if tmp <> []: match.append(tmp) #pop up a tkinter window and manually select matches #assign an id number to selected entries #write out modified files The problem I ran into is that the objects in "match" are not references to the actual data in the lstX structures but copies. So I cannot just change the id field the way I have things written. Based on my reading I thought all the operations I used worked with references but I clearly missed something. So, I'm getting the feeling that there is probably a *much* better way to do this. :-) Any suggestions? - Bill From jcarlson at nospam.uci.edu Fri Mar 19 13:01:04 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Fri, 19 Mar 2004 10:01:04 -0800 Subject: SHA-based subclass for random module In-Reply-To: <7x8yhxtast.fsf@ruckus.brouhaha.com> References: <7xptbgjpk4.fsf@ruckus.brouhaha.com> <5d83790c.0403190105.69ca83e7@posting.google.com> <7x8yhxtast.fsf@ruckus.brouhaha.com> Message-ID: > What's Random.random(self) supposed to do? Generate a random number using the Mersenne Twister random number generator. >> ciphertxt = md5.new(plaintxt).digest() > > I think you mean update. Perhaps yes, perhaps no. Certainly the digest of both are dependant on two inputs (the current internal state of MD5 and the random number generated by MT). However, unless you can store the series of updates to MD5, then getstate() followed by setstate() would not be sufficient to get the same series of random numbers. This is also a "possible issue" shared by the double-sha algorithm. > But doesn't support all the operations specified in the Random API. > What's up with that? That is what the subclass was for: > class MD5Random(Random): - Josiah From fma at doe.carleton.ca Sat Mar 27 23:43:22 2004 From: fma at doe.carleton.ca (Fred Ma) Date: 28 Mar 2004 04:43:22 GMT Subject: Choosing Perl/Python for my particular niche References: <40652B0D.7C313F77@doe.carleton.ca> <196cb7af.0403270606.520c617@posting.google.com> Message-ID: <406658F5.9F62DF55@doe.carleton.ca> Jim Keenan wrote: > > You are at Carleton University, which was the site of Yet > Another Perl Conference::Canada in May 2003. So you have an excellent > pool of local Perl experts to draw upon -- and there are many more not > far away in Montreal, Toronto and Kitchener/Waterloo. Look them up > via http://www.pm.org/groups/north_america.html . Thanks for the pointer, Jim. Fred From skip at pobox.com Tue Mar 30 22:43:40 2004 From: skip at pobox.com (Skip Montanaro) Date: Tue, 30 Mar 2004 21:43:40 -0600 Subject: tabbing probs In-Reply-To: <4068AD29.6020907@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> <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> Message-ID: <16490.15980.814876.690888@montanaro.dyndns.org> Michael> An editor is crappy if it inserts anything other than what you Michael> type into the code. If I press tab and four spaces are Michael> inserted that is crap. 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). Michael> If I press 'A' and 'a' is inserted that is crap. not if I placed my editor in e.e. cummings mode... Michael> To me, it sounds as if this entire issue is caused by crappy Michael> editors that think they know better than the programmers. 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. Skip From miki.tebeka at zoran.com Thu Mar 4 01:53:53 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Thu, 04 Mar 2004 08:53:53 +0200 Subject: design pattern In-Reply-To: <11c08e94.0403031832.5050dad8@posting.google.com> References: <11c08e94.0403031832.5050dad8@posting.google.com> Message-ID: <4046D281.9010503@zoran.com> franz wrote: > http://baseportal.com/cgi-bin/baseportal.pl?htx=/krauth/pattern_survey/pattern_survey I get: [ Error: Unable to open template /usr/local/httpd/baseportal/kr/au/krauth/pattern_survey/pattern_survey.htx. Reasons: The specified template does not exist or you don't have the rights to access it. Maybe you have just mistyped the name? Solutions: 1. Correct the name. 2. Log into your private domain, choose the appropriate template, click on 'Management' and change the rights settings. ] powered by baseportal.com Get your own Web Database - for FREE! Miki From Pieter.Claerhout at Creo.com Thu Mar 25 11:31:35 2004 From: Pieter.Claerhout at Creo.com (Pieter Claerhout) Date: Thu, 25 Mar 2004 17:31:35 +0100 Subject: Decoding numerical and name based HTML entities Message-ID: <490316A24CC5D411ACD700B0D078F7F0068A10A4@cseexch01.cse.creoscitex.com> Hi all, what would be the easiest way in Python to decode HTML entities to a unicode string? I would need a function that supports both numerical as well as name based HTML entities. I already did some googling, but I only found a function that decoded numerical ones, and this function didn't support unicode... Cheers, pieter -------------- next part -------------- An HTML attachment was scrubbed... URL: From theller at python.net Mon Mar 8 09:50:11 2004 From: theller at python.net (Thomas Heller) Date: Mon, 08 Mar 2004 15:50:11 +0100 Subject: py2exe - COM Server problem References: Message-ID: paul.kemp at standardbank.com (Paul) writes: > Hi all > > I've been trying to build a COM Server as an executable using Py2exe. > I had a few problems, so I came back to using Thomas Heller's basic > example (copied below). When I build this, I still get an error. I > can register Python.TestServer (testcomserver.exe --register), > however, when I try to create an instance of it (e.g. using VBA), a > command prompt window appears with the title: > > d:\...\testcomserver.exe /automate > > And the command prompt window just sits there! Eventually, VBA times > out. > > I really don't understand, because I've succeeded with COM servers and > Py2Exe in the past, and have never seen this before. > > Can anyone help? I guess that recent changes in pywin32 have broken this (very old) code you mention. You should upgrade to Python 2.3 (if you haven't already), a recent pywin32 build, and to py2exe 0.5. This version of py2exe contains an example COM server in the samples\advanced directory - it builds an exe and dll server from the win32com.servers.interp com example code. Basically, this 3-line setup script is all that you need, there are no changes needed to the com server code: from distutils.core import setup import py2exe setup(com_server = ["win32com.servers.interp"]) You can most certainly make the dist folder much smaller by excluding the pywin package from the build: python setup.py py2exe --excludes pywin Thomas From kbk at shore.net Sat Mar 13 02:16:57 2004 From: kbk at shore.net (Kurt B. Kaiser) Date: Sat, 13 Mar 2004 07:16:57 GMT Subject: Exiting Tkinter when using IDLE References: <4050E31D.EEB18C9F@pobox.com> <40520D71.C267B44@pobox.com> Message-ID: <87u10t2p3q.fsf@hydra.localdomain> Jason Harper writes: > Here's a little inconsistency that had me really confused for a > while: IDLE, when run from the Start menu (Win2K Pro, Python 2.3.3), > uses a subprocess. IDLE, when run via "Open in IDLE" in a .py* > file's right-click menu, does NOT use a subprocess. I haven't > tracked down just where this difference is coming from. Right now, we only allow one copy of the IDLE subprocess, because the socket port is hard coded. The specification of the -n switch is in the Windows Explorer File Types assignment. We did that deliberately because people often click on several .py files to view them and that tried to start several copies of IDLE + subprocess, which failed. You can have as many copies of IDLE without the subprocess as you like, but they aren't nearly as useful for code development. The plan is to remove the hard coding of the port so several copies of IDLE + subprocess can run simultaneously. I am delaying that until I'm pretty sure that the subprocess is well behaved under all conditions. -- KBK From jepler at unpythonic.net Sat Mar 20 10:06:43 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Sat, 20 Mar 2004 09:06:43 -0600 Subject: Regular Expression AND mach In-Reply-To: <8089854e.0403200303.5eae6726@posting.google.com> References: <8089854e.0403190721.6bdcbfbe@posting.google.com> <8089854e.0403200303.5eae6726@posting.google.com> Message-ID: <20040320150642.GA24288@unpythonic.net> You didn't tell us you were looking for full-text indexing. This may be what you want, as your database grows: http://www.divmod.org/Home/Projects/Lupy/ I haven't used it. The only two full-text indexing packages I've used are Glimpse and Swish-E. I still use Swish-E daily to search in a 2.5 million line software product. On a reasonably fast machine, it can find 37 instances of the phrase "int main" in 1.2 seconds. It's no google, but it works great. Calling out to it from Python should pose no great difficulty. Jeff From steve at ninereeds.fsnet.co.uk Sun Mar 7 13:10:53 2004 From: steve at ninereeds.fsnet.co.uk (Stephen Horne) Date: Sun, 07 Mar 2004 18:10:53 +0000 Subject: Need better string methods References: <0d4k40987t6d70bahqil3geth640bufgoc@4ax.com> Message-ID: <87dm4019o6hmjjgj8cpe1m41fk353mj0ig@4ax.com> On Sat, 06 Mar 2004 12:01:16 -0700, David MacQuigg wrote: ># 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('|')] So what you are saying is that non-programmers just naturally understand what "/\s*\|\s*/" means! I kind of agree with you about the join method - I far prefer the now deprecated function. But it's not much of a problem - you don't _have_ to use method-call syntax for Python, just get the unbound method from the class and call it with the object as the first parameter... >>> str.join (' ', ['a', 'b', 'c']) 'a b c' I guess I see the advantage in the Ruby form. It can of course be replicated in Python using a library, but being able to handle the task as neatly by default would be a plus. So, how about this... >>> line.lstrip ('.'); re.sub (' +', ' ', _).strip (); re.split (' ?\| ?', _) '/bgref/stats.stf| SPICE | 3.2.7 | John Anderson \n' '/bgref/stats.stf| SPICE | 3.2.7 | John Anderson' ['/bgref/stats.stf', 'SPICE', '3.2.7', 'John Anderson'] Using ';' and '_', you can chain any functions or methods you want. The downsides are (1) it only works at the command line, and (2) you get intermediate results displayed. A temporary variable can handle both issues, of course... >>> t=line.lstrip('.'); t=re.sub(' +', ' ', t).strip(); re.split(' ?\| ?', t) ['/bgref/stats.stf', 'SPICE', '3.2.7', 'John Anderson'] or, to save some hassle... >>> def squeeze (p) : ... return re.sub (' +', ' ', p) ... >>> t=line.lstrip('.'); t=squeeze(t).strip(); re.split(' ?\| ?', t) ['/bgref/stats.stf', 'SPICE', '3.2.7', 'John Anderson'] On this basis, perhaps it would be useful to support the '_' variable outside of the command line, and maybe to suppress all but the last result when ';' is used on the command line. OTOH, as you suggest, maybe we could use some extra string methods. With an equivalent to the Ruby 'squeeze' and support for regular expression methods, we could write... line.strip().lstrip('.').squeeze().resplit(' ?\| ?') Which is very much like the Ruby example. Finally, it seems to me that this kind of tidy-and-split is probably a common requirement. The split is easy enough, but after pondering Robert Brewers argument I wondered if maybe a specialised tidying class could do the job... import re class cleaner : steps = [] def lstrip (self, *args) : self.steps.append (lambda s : s.lstrip (*args)) return self def rstrip (self, *args) : self.steps.append (lambda s : s.rstrip (*args)) return self def strip (self, *args) : self.steps.append (lambda s : s.strip (*args)) return self def squeeze (self) : pat = re.compile (' +') self.steps.append (lambda s : pat.sub (' ', s)) return self def resub (self, regex, rep) : pat=re.compile (regex) self.steps.append (lambda s : pat.sub (rep, s)) return self def clean (self, p) : for i in self.steps : p = i (p) return p line = "..../bgref/stats.stf| SPICE | 3.2.7 | John Anderson \n" mycleaner = cleaner().lstrip(".").strip() \ .squeeze().resub(' ?\| ?','|') print mycleaner.clean(line).split("|") -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From skip at pobox.com Mon Mar 1 09:08:51 2004 From: skip at pobox.com (Skip Montanaro) Date: Mon, 1 Mar 2004 08:08:51 -0600 Subject: Determining the encoding of a text file In-Reply-To: <85b5e3f8.0403010224.939e8f8@posting.google.com> References: <85b5e3f8.0403010224.939e8f8@posting.google.com> Message-ID: <16451.17395.56056.567475@montanaro.dyndns.org> rajorshi> How do I determine the encoding of a text file ? That is, rajorshi> given a text file I want to know the encoding it is in UTF8 or rajorshi> UTF16 or Latin etc. It would be very helpful if you could tell rajorshi> me how to do this in python on Linux. But just the method is rajorshi> acceptable. In general this is not possible. You can guess using heuristics, but there is no predefined file attribute that indicates a file's encoding. If you have a small set of candidate encodings you can generally do a decent job guessing the encoding of a string by considering them in order. I placed an example on my Python Bits page: . I don't claim it's perfect and it's really only concerned with distiguishing utf-8 and a few encodings which are similar to iso-8859-1, but it does a decent job for me given the types of inputs I see. Skip From axel.koehler at tu-berlin.de Sun Mar 14 09:21:45 2004 From: axel.koehler at tu-berlin.de (Axel Koehler) Date: Sun, 14 Mar 2004 15:21:45 +0100 Subject: Start and control an extern program References: <4051087D.1050409@zoran.com> Message-ID: Helo Miki, thank you for your help. Miki Tebeka writes: > Hello Axel, > >> I want to start an extern program and simple stop it, after a >> given time, if not succesfull finished. OS is Linux > Use a Timer object and os.kill. But what is a timer objekt? Can't find it in my documentation of the python library. Axel -- ___________________________________________________________________________ Dipl. Ing. Axel K"ohler, axel.koehler at tu-berlin.de Tel: 030-314 73141 TU Berlin, FAK I, Sekr. FR 3-15, Franklinstr. 28-29 10587 Berlin From rawbobb at hotmail.com Fri Mar 5 09:51:07 2004 From: rawbobb at hotmail.com (bobb) Date: Fri, 05 Mar 2004 14:51:07 GMT Subject: MySQL/PYTHON References: <30260531.0403032110.35425635@posting.google.com> Message-ID: same here. "Michael" wrote in message news:mailman.7.1078461675.19534.python-list at python.org... > I've used MySQLdb with Python for quite some time and have been very > pleased with it. It is quite easy to use and I've had no stability > issues with using it. > > >>From what I've seen, PostgreSQL is more widely supported than MySQL under Python. > > > > > > From lilyth at umich.edu Thu Mar 18 18:07:58 2004 From: lilyth at umich.edu (Lilith) Date: 18 Mar 2004 15:07:58 -0800 Subject: Is there a map or graph module? Message-ID: <75200cbc.0403181507.350feeb7@posting.google.com> Is there a python module somewhere (been searching today, no luck) which has efficiently coded various graph-handling routines, such as finding the shortest path through a graph, or the set of all paths through a graph? I'm not a compsci-educated person, so coding my own would be less parsimonious. Thanks for any suggestions! D From niurka.perez at cimex.com.cu Fri Mar 19 13:09:00 2004 From: niurka.perez at cimex.com.cu (niurka.perez at cimex.com.cu) Date: Fri, 19 Mar 2004 13:09:00 -0500 Subject: static variables? Message-ID: <0403191079.AA1079721270@ws3.cimex.com.cu> How can I have a static variable in a python class in a similar fashion as I have them in Java? I just want a share the same information in all the instances of a class and if one of the instances changes this information, the rest of them will notice the changes. I've been looking for this for a while and I'll appreciate your help Niurka From nhodgson at bigpond.net.au Fri Mar 12 03:54:11 2004 From: nhodgson at bigpond.net.au (Neil Hodgson) Date: Fri, 12 Mar 2004 08:54:11 GMT Subject: Question concerning Unicode and or Shift-JIS References: <4050f410$0$40740$c3e8da3@news.astraweb.com> Message-ID: Antioch: > however the problem is I don't know how to "decode" the UTF and then > recode it into Shift-JIS so that I can compare the dictionary values with > the input values. I don't have a Shift-JIS codec installed so this breaks but should work if you have the codec installed: y = '\xe3\x81\x8b\xe3\x82\x8f\xe3\x81\x95\xe3\x81\x8d' print y print repr(y) u = unicode(y, "utf-8") print repr(u) s = u.encode("shift-jis") print s Neil From peter at engcorp.com Fri Mar 5 10:24:37 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 05 Mar 2004 10:24:37 -0500 Subject: is perl better? In-Reply-To: References: Message-ID: <9oSdnRDo7cgrBtXdRVn-sQ@powergate.ca> jon c wrote: > some idoit wrote a perl script that executes a java program using the > system command. > > All seemed fine, except when I run I find that the character string is > too long? > > the identical command can be run by perls system call. > why does perl work and not python? Post code samples, so people have a clue what you are talking about. How long is the character string? How long is the command line limit on the operating system you are using? -Peter From bogus at bogus.net Wed Mar 3 06:22:56 2004 From: bogus at bogus.net (Paul McGuire) Date: Wed, 03 Mar 2004 11:22:56 GMT Subject: best way to read a configuration file References: <2dy8qimiwq.fsf@itl-pc87.hut.fi> Message-ID: "Karthikesh Raju" wrote in message news:2dy8qimiwq.fsf at 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 newsgroups at jhrothjr.com Wed Mar 31 08:05:34 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Wed, 31 Mar 2004 08:05:34 -0500 Subject: proper use of braces in Python (was: Prothon Prototypes vs Python Classes) References: Message-ID: <106lgippu0ovc36@news.supernews.com> "Jim Benson" wrote in message news:mailman.152.1080695131.20120.python-list at python.org... > On Tue, 30 Mar 2004, Michael wrote: > > > > > >>Right. Then we can have "does the brace go on the same line or the > > >>next line" wars. > > >> > > >> > > > > > > int main (void) > > > { > > > if (true) > > > { > > > } > > > > > > return 0; > > > } > > > > > >There is no other way. > > > > > > > > No way, that wastes an entire line of code with a single brace! > > > > int main ( void ) { > > if ( true ) { > > return 1; > > } > > return 0; > > } > > > > This is clearly better. Compact yet easy to read. I try formatting my > > Python code exactly like this and it always complains about my braces.. > > clearly wrong. > > > > > > Hi, > > ...just a food for thought from a Python list lurker. > I have always been a strong adherent to the > > if (true) { > > } > > form. Not too long ago on this list (i think it was), > someone pointed out that you never see: > > If (true) BEGIN: > > END > > humm...i thought, your right, in that case i guess > i would probably write the BEGIN on a different > line...not sure what indention of the END > i would choose. You don't need the BEGIN. Seriously. This is one of the things Metz got right in Ruby: except for one special case, the compiler can tell when you start a block -- as long as your language doesn't special case such things as empty blocks and single statements that, somehow, aren't blocks. You do need the semantic equivalent of END, though. Whether that's indentation or a keyword is a language issue. The special case is, of course, the literal block where the syntax allows a function reference. That does need to be distinguished somehow. John Roth > Jim > > > From claird at lairds.com Wed Mar 17 19:04:53 2004 From: claird at lairds.com (Cameron Laird) Date: Thu, 18 Mar 2004 00:04:53 -0000 Subject: Help on Tkinter installation References: Message-ID: <105hpt53kagaj67@corp.supernews.com> In article , John Slimick wrote: >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 . . . More pertinent than your source code, which, to the best of my understanding, has multiple difficulties, is information about the host on which you're attempting to run it. I'm guessing it's a RedHat Linux ... I'd think easiest for you would be to rely on ActivePython . I'm curious about how you decided to start with the program you've exhibited above. -- Cameron Laird Business: http://www.Phaseit.net From newsgroups at jhrothjr.com Sat Mar 20 07:30:21 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 20 Mar 2004 07:30:21 -0500 Subject: Package name with '.' in them: Python Bug ? References: Message-ID: <105oecrlrm4r9e9@news.supernews.com> "Yannick Patois" wrote in message news:c3frti$2v88$1 at biggoron.nerim.net... > Stephen Robert Norris wrote: > > On Fri, 19 Mar 2004 19:12:03 +0100, Yannick Patois wrote: > > The only potential bug here is that perhaps python should have raised an > > error when the import happened. Actually, I tend to agree this would be a nice thing. This part of import isn't executed so frequently that it would pose a performace issue. John Roth From http Sun Mar 21 18:16:02 2004 From: http (Paul Rubin) Date: 21 Mar 2004 15:16:02 -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> <7x8yhvnfba.fsf@ruckus.brouhaha.com> <5d83790c.0403211310.15764495@posting.google.com> Message-ID: <7x4qshn64t.fsf@ruckus.brouhaha.com> python at rcn.com (Raymond Hettinger) writes: > > If we're selecting a PRNG for a third > > time, let's stop cutting corners and take care of the problem once and > > for all. > > No corners were cut. MT is a state-of-the-art psuedo random number > generator. The problem is that you want encryption. This sha prng module was motivated partly by your own remark in sf bug #901285 that MT output may not be sufficiently correlation-free if you take pairs of 16-bit integers from it, in a context having nothing to do with encryption. Anyway, despite how it may sound, I don't have any desire to use the random module for encryption (I'd use different API's for that). I just want to be able to write applications that use random numbers without having any doubts about whether the random numbers are good enough. Teukolsky et al in "Numerical Recipes", which is not a cryptography book, explain that a good way to do that is to use cryptographic primitives, so I'm proposing a module that does it that way. The application in numerics could be something like: I run some half-hour simulation using MT, and get results that subjectively seem a bit peculiar. So I run it again using the crypto-based generator and maybe that takes three hours, but if I still see similarly peculiar-looking results, I now can be pretty confident that it's not some consequence of the RNG internals. It subjectively seems to me that the Gnome version of Freecell is easier to play than the Windows version (i.e. it deals easier hands), so that's a semi-real-world example of this situation. (In this instance I suspect Freecell is using some pathetic linear PRNG or something like that, but I haven't yet bothered to look at the code). There's also some applications (like online games) that need secure random numbers, as mentioned in 917055. The people implementing these things usually aren't even thinking about cryptography. > > No, I wanted cryptographic strength to both the left and right, > > That makes sense. Still, the hashing step protects you. Given a > series of 10,000 bits from the generator, do you have any means of > deducing either a) the state of MT, b) what came before, or c) what > comes after? Cryptographic strength to the left means I shouldn't be able to recover what came before, even given the current output of getstate() on the generator (see the Yarrow paper for some rationale for wanting this protection). I haven't seen any claim that MT was designed to resist that. I'm not adamant that this is a crucial property of a deterministic PRNG; I implemented it because I saw it as straightforward to do and figured it might as well be included, so that we can say that we did the most thorough possible job, followed the Yarrow paper's prescriptions, etc. If there's a deliberate decision to abandon the property, that can make the generator a bit simpler and faster, and I'm willing to code one that way for purposes of comparison. I just don't think such decisions should be driven by implementation accidents. (They should also be documented). > I'm keeping an open mind but will abandon this patch unless the tone > improves. I don't mean to bash anyone and I'm sorry if it came across that way. As I see it, the Random module provides an extensible API so that it's easy to add different kinds of generators that the user can select from depending on his or her needs. It then supplies the WH generator (I guess for backwards compatibility) and the MT generator (for reasonably good output and very high performance). The philosophy of this sha module (as I see it) is to supply a third alternative in that same flexible spirit: one that goes all-out to make the best possible output, even if that results in only reasonable performance, while also having increased portability through use of a standard underlying primitive. Do you also see that as an appropriate goal? If not, we should try to identify exactly what we're trying to do instead. From rzantow at ntelos.net Mon Mar 1 23:50:10 2004 From: rzantow at ntelos.net (rzed) Date: Tue, 02 Mar 2004 04:50:10 GMT 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> Message-ID: Josiah Carlson wrote in news:c209n0$cit$1 at news.service.uci.edu: >> I've wondered, though, whether there couldn't be a different >> character instead of a ',' to alter the behavior of print. >> Maybe a trailing '+' to indicate that what follows is to >> concatenate directly. >> >> And yet I've been able to work around that little annoyance; >> it's not that there is no way to format output the way you >> want. > > > It seems that you are saying: > > print "hello ", "world" + #-> "hello world" > > That looks like "magic syntax", and should rightfully return a > syntax error, because + already has a meaning for most all data > types in Python. Changing the behavior of print when a syntax > error is present, is the wrong thing to do. > > The right thing to do (if it were to happen at all) is to make > fileobject.softspace "sticky" under some condition, perhaps > after a call to fileobject.SetSoftSpace(False) (which doesn't > currently exist). > I'm not sure I agree with this entirely. The comma following a print statement is a sort of magic syntax as it is; it changes the behavior of the unadorned print statement in a way that has very little to do with any syntactical meaning a comma would normally have. The idle thought I mentioned above would just use a different symbol to alter the behavior of print in a slightly different fashion. What I actually had in mind, adapting your example, was something a little different: print "hello" + print "nwheels" #-> "hellonwheels" If a '+' is problematic, it could be some other character. If I use a print statement in a Python program, from my viewpoint, a trailing comma signals suppression of newline and adding a space. In this scenario, a trailing would suppress the newline but not add a space. There's not much difference there. Having said all that, I'll add that I don't see this as a big issue, and I don't find it a burden to use an alternative syntax to achieve the same effect. I don't know how to tell if it's a right or wrong thing to do. If it were a feature of the language, I'd probably use it. I've never really understood what it is about the print statement that bothers some people; it's always seemed reasonably useful and reasonably intuitive to me. Maybe every language is destined to have irregular verbs. -- rzed From lbates at swamisoft.com Fri Mar 26 19:12:12 2004 From: lbates at swamisoft.com (Larry Bates) Date: Fri, 26 Mar 2004 18:12:12 -0600 Subject: Python & Optical Mark Recognition Message-ID: Anybody out there done anything with Optical Mark Recognition (OMR)? I have a potential project that requires OMR add-in for existing Windows based Python application. Thanks in advance. Larry Bates Syscon, Inc. From likwoka at yahoo.com Mon Mar 1 22:21:12 2004 From: likwoka at yahoo.com (Alex Li) Date: 1 Mar 2004 19:21:12 -0800 Subject: Multi-user quiz show game References: <20040301161835.20170.00000686@mb-m27.aol.com> Message-ID: > > I'll let the experts answer this one. But I have a question. Do you rule out a > http server ? If I were doing this I would avoid the apparent complexity > wxpython and just use standard html and javascript to pass the answers to the > server. The python script could record time it got the "get" and return it with > the validation. > > > allen Thanks, Allen! Your solution is actually quite attractive, as it just simplify the whole thing a lot.... I would consider it very seriously... Thanks again, Alex From jsbenson at bensonsystems.com Thu Mar 11 23:37:31 2004 From: jsbenson at bensonsystems.com (John Benson) Date: Thu, 11 Mar 2004 20:37:31 -0800 Subject: put your money where your mouse is, or why I prefer Spanish to English: a proposal Message-ID: <082d01c407eb$bb8dfc10$210110ac@jsbwxp3> Everybody talks about how much better Python is than Lisp, C++, Java or whatever else because it's so much cleaner, looks like pseudocode only it's executable and all the cool guys are using it because of this and other advantages. I propose that we change the language of this board to Spanish, as long as we're so vocally committed to using best-of-breed languages. Derived from the Iberian dialect of vulgar Latin, Spanish has many important advantages over English: 1) It's executable phonetic code: how it's written is how you pronounce it. English suffers from a bewildering array of rules and counterexamples in matters of pronunciation. 2) It's a widely supported standard. A Spanish speaker from Tierra del Fuego can understand somebody from Madrid with little difficulty. Many dialects of English, however, are often incomprehensible to other English speakers, like Cockney, 'Strine and HBHE (High-Baudrate Hindustani English). 3) Spanish has less monosyllabic words than English. Programmers paid by the hour should be intrigued by this opportunity to augment their income. Also, the same amount of actual progress will take longer to report, conveying the impression that more has actually been accomplished. 4) It hasn't been thrown together from the motley of influences that make English such a potpourri (from the French for "rotten stew"). Oops! Like I said, English is too much a patchwork of other languages to qualify as a natural venue for Pythonic discourse. & cetera. Thinly-veiled threat: If this board doesn't immediately cut over to Spanish because it is obviously superior to English, I shall be forced to consider its badmouthing of other computer languages as just so much small-minded special pleading. P.S. The fact that I have an M.A. in Spanish has nothing to do with the fact that Spanish is the best language for this board. I have recommended it solely on its obvious and indisputable merits. In the spirit of magnanimity, however, I will state in advance that anyone who disagrees with me is more to be pitied than censured. From No.Spam.mc at No.Spam.mclaveau.No.Spam.com Thu Mar 25 16:03:33 2004 From: No.Spam.mc at No.Spam.mclaveau.No.Spam.com (Michel Claveau/Hamster) Date: Thu, 25 Mar 2004 22:03:33 +0100 Subject: How to import a module based on an argument References: Message-ID: Hi ! No nice, but : def functionname( module, var1): exec("import "+module) print string.upper(var1) functionname('string', 'azerty') From fumanchu at amor.org Sat Mar 13 16:44:43 2004 From: fumanchu at amor.org (Robert Brewer) Date: Sat, 13 Mar 2004 13:44:43 -0800 Subject: need optimizing help Message-ID: rabbits77 wrote: > > I have a dictionary with a very very large(possibly millions) of > > key/value pairs. > > The key is a tuple that looks like (id,date) > > What is the fastest way to get out all of the values that match any > > key given that they individual key elements are coming from two > > seperate lists? > > The approach of > > for id in IDS: > > for date in dates: > > data=myDict[(id,date)] > > > > seems to just take too long. Is there a speedier, more pythonic, way > > of doing this? Any help speeding this up would be much appreciated!! and I replied: > If you're willing to handle some minor side-effects, one > common approach is an index layer via a nested dict; > that is, instead of: > > myDict[(id, date)] = value > > ...you execute: > > myIndex.setdefault(id, {})[date] = value Postscript: it may be that your 'id' and 'date' values are properties of whatever objects you're putting into the dictionary. If so, and you want such a beast which does the indexing semi-automatically, try the Index class I just made last week (ignore the Chain class--that solves a different problem): http://www.aminus.org/rbre/python/index.html -> buckets.py It uses parallel dictionaries, not nested ones...in your example, you might write: >>> import buckets >>> import datetime >>> class Thing(object): ... def __init__(self, id, date): ... self.id = id ... self.date = date ... >>> myDict = buckets.Index('id', 'date') >>> myDict.store(Thing(0, datetime.date(2004, 12, 25))) >>> myDict.store(Thing(1, datetime.date(2004, 12, 26))) >>> print myDict {'date': {datetime.date(2004, 12, 25): [<__main__.Thing object at 0x01170390>], datetime.date(2004, 12, 26): [<__main__.Thing object at 0x011708B0>]}, 'id': {0: [<__main__.Thing object at 0x01170390>], 1: [<__main__.Thing object at 0x011708B0>]}} By the way, if any gurus out there have recommendations for improving the Index class (even rewriting it in C), I'd love to hear them and see something like it included in the Library. Robert Brewer MIS Amor Ministries fumanchu at amor.org From steve at ninereeds.fsnet.co.uk Mon Mar 22 05:45:40 2004 From: steve at ninereeds.fsnet.co.uk (Stephen Horne) Date: Mon, 22 Mar 2004 10:45:40 +0000 Subject: PEP 318 References: Message-ID: On Sun, 21 Mar 2004 14:45:39 -0500, Nicolas Fleury wrote: >- Give a warning for all methods with first parameter not named "self" >in next versions of Python. >- In a future major version of Python, 3 or 4, self becomes a keyword >and a first parameter named otherwise implies a class method (I >understand it could mean a lot of changes in code not using self). The main problem I have with that is that some people find typing 'self.' over and over in member functions pretty annoying. I have quite recently voiced the opinion that because 'self' is just a convention, that it can reasonably be abbreviated to become something like 's' or 'm', so that 'm.' in Python code plays much the same role as 'm_' in common use as a prefix for member variable names in C++. As I said then, I'm not that bothered about 'self.' - keeping to the well-known convention and the principle of least surprise is to me well worth pressing a few more keys. But I may have to deal with a few grumpy people if that suggestion turns out bad :-( If a more radical change is needed, then I would say we need an alternative to the 'def' keyword. It could be justified as 'def just defines normal functions - we can define them as class members and we have a convenient system for using them as if they were methods but that doesn't mean they really are methods'. 'True' methods would then be defined using a 'method' keyword, and within a method 'self' might be a pseudo-keyword. In Python 3000, 'def' for member functions might then be deprecated. Very unlikely, though. -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From marklists at mceahern.com Thu Mar 25 15:53:06 2004 From: marklists at mceahern.com (Mark McEahern) Date: Thu, 25 Mar 2004 15:53:06 -0500 Subject: How to import a module based on an argument In-Reply-To: References: Message-ID: <406346B2.6030709@mceahern.com> Sean Berry wrote: >I don't know that this partilarily bad programming, >but I was interested in doing the following. > >def functionname( module, var1, var2 ): > import module > >I would like to be able to pass the module name >as an argument and have the module imported as a result. > >For instance... functionname( os, "1", 234) > >Thanks for any help. > > Checkout __import__. // m From ketulp_baroda at yahoo.com Wed Mar 24 08:43:45 2004 From: ketulp_baroda at yahoo.com (ketulp_baroda at yahoo.com) Date: 24 Mar 2004 05:43:45 -0800 Subject: sorting the list by inner elements Message-ID: Hi, all I want to sort the list,the form of my list is name_city_list=[['jack','new york'],['mac','london'],['alice','paris']] all inner list has same format i.e first is name and second is city. now I want to sort it by the second element of the inner list(by city name). i.e after sorting my list should be like this name_city_list=[['mac','london'],['jack','new york'],['alice','paris']] how can I do this, any way out ? From jcarlson at nospam.uci.edu Thu Mar 18 23:57:43 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Thu, 18 Mar 2004 20:57:43 -0800 Subject: [snip too-long subject] In-Reply-To: References: Message-ID: >>> import this The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those! **end quote** [snip attached file information and comments] > now, about the requests. i want to see python more symmetrical and > consistent. this way it could be advertised/marketed easier to places > with serious portability AND maintainability thinking, over other > pure-procedural languages. Is anyone is interested in that? I'm all for Python being used in more places (as are most people here), but I am not for changing the language to suit someone's arbitrary opinion on what it should be. You'll likely find others who are also against arbitrary changes that seem to suit an individual's sense of 'what should happen'. Read some of the "suggested changes" to syntax and behavior that others have offered here, and you'll notice a strong tendency for the suggestions to be generally disliked (if not loathed). Guido and others in python-dev seem to be doing a pretty good job of keeping things together. While Guido has some regrets (in terms of Python's behavior), he seems much happier than regretful, and I doubt many (if any) of your "suggestions" will go far, because I don't believe that /any/ of your suggestions are Pythonic. > - i want the documentation to be fully interlinked (in current > hierarchy) and to have another alternative hierarchy - from usage-point > of view - if i say list, ALL about lists should be there, and not > separated in 3+ different places, so either a lot bookmarks are to be > kept, or 10+ clicks to get the next piece of info. Same goes for most > data/execution things. it can be done as simple links-only-layer - i > dont mind. Probably data-model and execution model are best to follow as > template. I find that the documentation index (http://www.python.org/doc/current/lib/genindex.html) to be quite useful, as well as google. > - order of variable assignments in class namespace to be offered/passed > to the metaclass, as separate argument or the (now dict) namespace > argument to be properly ordered iterable (moving the dict creation from > C into python metaclass - well, if any. type(name,bases,dictiterable) > can still do it in C). Order can be safely ignored if not needed. I understand that for some reason this is important to you. However, previous to your initial post about it, I've never heard of anyone having a need for the assignment order of class variables. This suggests that very few people have a need for it, further shown by the fact that no one replied to your post saying, "hey, I've wanted to do this too, tell me if you figure it out". I did reply to your post, if only because I thought you wanted /instance/ variable assignment order, which /has/ been brought up in other contexts. > - i want somehow to turn the { MY order of dict values here } syntax > into as-is-ordered thing! Could be even with some pragma switch that > would create my dictOrder (or some builtin one) instead of internal > hashed mapping! This is equivalent to above, but for plain value dicts > (and not the attribute namespaces, represented as dicts). Function > keyword args can be another thing to keep order of - if required. (a > sort of execution-namespace control pragma) Ordered mappings are probably not currently supported in Python because: "Special cases aren't special enough to break the rules." Dictionaries are great. Dictionaries are fast. Lets not mess them up by slowing them down. > - the notion of iterators/ generators, and notion of interfaces are so > powerful but so poorly advertised - and used. Now there is itertools - > PERFECT! but i have to import it while waster things like map() are > still sitting at plain view - hence - from lamer's point of view - > easier to use. Perhaps you didn't mean "lamer", such a term is quite rude. If you /did/ mean "lamer", then that would make you a "troll". There are 12 functions in itertools. Adding 1 built-in function takes the word of Guido. Adding 12 built-in functions would likely take the word of most of the core developers of Python, and god. The itertools module is the proper location, as determined by Guido and others in python-dev. As for map and other builtins being in plain view, even if they are not iterators/generators, they are still useful. > - what about try: finally: over generators? PEP288. gee, 50 lines of > iterator class instead of 5 with yield just becasue i _have_ to close a > file... If it takes you 50 lines to close a file after yielding it, you're doing something wrong. Checking the source code that you attached, you use yield once, which doesn't seem like it is iterating over file handles or file names. Post the code in a reply, and I'm sure someone will show you how to clean it up. > - all builtin functions that do not add value to the language as > language should move into separate module (e.g. map, zip, sum etc... vs > callable, isinstance, builtin type-constructors) and not be so > over-emphasized. map, zip, sum, etc. are used in a large amount of production code. Moving them somewhere else would break every piece of code that uses them. This is not going to happen soon, possibly ever. If you don't like their location, create a module that modifies __builtins__ that gets imported by site.py. Something like the following would work... #my_confused_builtins.py move_me = ['map', ...] for i in move_me: exec("%s = __builtins__.%s"%(i,i)) exec("del __builtins__.%s"%i) #include the following line in site.py import my_confused_builtins > - all interfaces (not types!) - e.g. containers (__get/set/delitem) - > should be named 'interfaces' - now this is vaguely called 'customization'. I don't know why they initially decided on "customization" for a name, perhaps it is because we are customizing the behavior of various operations on new objects. FYI, almost all of the __ops__ are listed in the documentation for the operator module. > - how do i check if x is iterable? try: iter(x) except: #x is not iterable > - (i see this goes in python2.4, PEP289) [snip comments] PEP 289 has been accepted, so your comments on it are late. > - IMO most funcs now needing a list or dict should be happy with proper > iterable. ( Eventualy funcs needing only iterable over single values may > have *args instead, and for key-balue tuples **kargs instead. but this > isnt that important.) Where any iterable makes sense (and not just a list), the Python is moving that direction, and if all goes well, (I believe), that will be the case in the future. For objects that need a dictionary, usually it is because they use a dictionary for its primary purpose, looking up and storing arbitrary values. Certainly any arbitrary sequence or iterable can be used as a dictionary, but when people say dictionary, they usually mean something with (approximately) O(1) access time for any element, that can be queried and written to multiple times (you can only search an iterable once, and can't write at all). > - i would like to be able to control somehow what constructors are > available for example to eval() - so i can patch them (operator *) - so > things like [snip limitation argument] Check the compiler module. When you have an AST, you can do all the checks your heart desires. There may be a project to create a restricted python execution environment for such tasks, but a better idea is to not allow eval() and exec() statements at all. > - i want the list head/tail notation: > a, b, *c = somelisthere > apart of all else, it helps future maintenance and readability of the > program, and this IS important if python is to be used for serios things > in serios places. ah, i might like simmetrical thing for dicts but you > will not like it: > 'a':var1, 'b':var2, **rest = dictionaryhere I doubt Python is going here. If you want head/tail of a list... def head_tail_list(lst, count=1): return tuple([lst[i] for i in xrange(count)] + lst[count:]) a,b,c = head_tail_list(somelisthere, 2) If you want the head/tail of a dict... def head_tail_dict(dct, *items): return tuple([dct.pop(i) for i in items] + [dct]) var1, var2, rest = head_tail_dict(dictionaryhere, 'a', 'b') Personally, I think that the syntax you give is ugly, and have had little need to do anything close to what you describe. I've also not seen anyone who uses lisp-like car/cdr operations in Python. One thing you should remember is that Python lists are actually arrays. Pulling an element off the front is very wasteful (computationally). Also considering that the functional equivalent to what you want is a 1-liner in either case, I see little reason for any of this functionality to be included with Python now or in the future. > [btw, anyone interested in very thin framework for UI-via-html-forms? > all is in python, even the form description, html etc. > it's 75%-done, with most things showable.] Sounds neat. Perhaps you should create a sourceforge.net project for it. - Josiah From john at neggie.net Wed Mar 24 13:20:04 2004 From: john at neggie.net (John Belmonte) Date: Wed, 24 Mar 2004 13:20:04 -0500 Subject: portable /dev/null again Message-ID: <4061D154.8090809@neggie.net> Hello, A few months ago, someone suggested the need for a portable equivalent to /dev/null in Python's libraries. He was told it was too trivial an addition to the library, and to use something like: class nullFile: def write(self, data): pass However, as the above does not present a full Python file object, it can't go everywhere that say, sys.stdout can go. More specifically, it doesn't provide a file descriptor that may be required by low-level interfaces. I wish an os.nullfile (or at least, os.nullfilename) was available so that I wouldn't have to think about this. -John Belmonte -- http:// if ile.org/ From claird at lairds.com Sat Mar 27 12:26:02 2004 From: claird at lairds.com (Cameron Laird) Date: Sat, 27 Mar 2004 17:26:02 -0000 Subject: Choosing Perl/Python for my particular niche References: <40652B0D.7C313F77@doe.carleton.ca> <40657D14.3FBE7E82@doe.carleton.ca> <106b7k2s8af5c3c@corp.supernews.com> Message-ID: <106be9aroogdq77@corp.supernews.com> In article , zatoichi wrote: >Cameron Laird wrote: >> In article <40657D14.3FBE7E82 at doe.carleton.ca>, > >> My current instinct is that you'll be happiest with Perl-- >> but it's a close choice, all around. I'm most accomplished >> in Tcl, and would happily use it, or Perl, or Python. It >> seems to me, though, that it's crucial that you be able >> to exploit libraries that pertain to your domain, and, in >> particular, optimized engines for linear algebra, graph >> theory, and linear and mathematical programming. Tcl >> lacks the weight that Perl and, to an increasing extent, >> Python can boast in their libraries. >Since you happily use Perl, Python or Tcl, I have a question. How do you >decided which one to use? :-) > >Robert Most often, whatever is already at hand. It'll be interesting some day to come across an organization that doesn't already have a standard in place. -- Cameron Laird Business: http://www.Phaseit.net From tjreedy at udel.edu Sat Mar 13 08:49:46 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 13 Mar 2004 08:49:46 -0500 Subject: Static Typing in Python References: <20040313064925.57149.qmail@web8308.mail.in.yahoo.com> Message-ID: "Premshree Pillai" wrote in message > Anyway, what I want is to force variable declaration. > In perl we have the "use strict vars" pargma...I need > something like that... For those of us who do not know Perl, and there are many, I suspect, on this Python newsgroup, that means nothing ;-). tjr From gnupeaker at yahoo.com Tue Mar 23 09:26:28 2004 From: gnupeaker at yahoo.com (Eyal Lotem) Date: Tue, 23 Mar 2004 06:26:28 -0800 (PST) Subject: explicit variable scoping In-Reply-To: Message-ID: <20040323142628.95427.qmail@web61102.mail.yahoo.com> --- Jacek Generowicz wrote: > Actually, I think that "referencing" works fine as > it is. The problem > is that "setting" (at the moment) can either be > "creating a new binding" or "rebinding an existing name". > All this can be achieved by the simple expedient of > distinguishing > binding and re-binding. (Though I have no truly > convincing suggestion > of how this distinction should be spelt in Python.) One of the main things I am after, is eliminating the heuristic by which Python "guesses" whether a variable is global/local, according to whether any assignment was seen. This confuses novices and annoys experts that stumble upon it, and it is definitely a problem. If explicit differentation between new bindings and rebindings solves that, I'm all for it. I have only recently noticed that when calling the module's functions, or when using imported modules, and perhaps in many other cases, you don't typically want to have to explicitly name the global scope and thus I take back my "global" syntax suggestion. Explicit "let"s do seem to get rid of the local-vs-global issue, while providing an elegant solution to the nested-functions variable access problems. d=1 e=9 def f(): def a=None,b=3 # Since locals are typically # created via an assignment # it makes much sense to allow # unifying the creation of their # scope [def] with the assignment # to eliminate some redundancy b=4 # rebinding d=5 # raise error, neither local or global global e def g(): e=10 # global assignment b=5 # rebinding def a=7 # new local binding print a, b, e # will print None, 5, 10 __________________________________ Do you Yahoo!? Yahoo! Finance Tax Center - File online. File on time. http://taxes.yahoo.com/filing.html From fumanchu at amor.org Sun Mar 28 20:14:52 2004 From: fumanchu at amor.org (Robert Brewer) Date: Sun, 28 Mar 2004 17:14:52 -0800 Subject: How To capture an id into an array.. Message-ID: BALAJI RAMAN wrote: > 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.. 'check' is actually a list, not an array, but they're similar. You have declared 'check' inside a function, and have not provided a means of returning or accessing it; once the function ends, 'check' disappears. You have to declare 'check' in a namespace which will persist. Try this in a module: # See how we declare 'check' outside the class? # That means it exists in the namespace of the module, # not the namespace of class V or its __init__ function. check=[] class V(E): """ This is a variable for MPY""" def __init__(self): print id(self) check.append(id(self)) self.val = None Hope that helps, Robert Brewer MIS Amor Ministries fumanchu at amor.org From peter at engcorp.com Mon Mar 15 11:15:52 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 15 Mar 2004 11:15:52 -0500 Subject: Static Typing in Python In-Reply-To: <4055cb43$0$7558$afc38c87@news.easynet.co.uk> References: <4055a71e$0$28265$afc38c87@news.easynet.co.uk> <4055cb43$0$7558$afc38c87@news.easynet.co.uk> Message-ID: Peter Hickman wrote: > Jacek Generowicz wrote: > > 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. There's no indication there that Guido would have preferred to use the term "strongly typed" in this case, as the choice to use strong/weak as the focus of the article seems to have been the interviewer's, not the interviewee's. Rather than your last sentence above, what you should write is "So there we have it, Guido is quoted using the term "strongly typed" in an interview in reference to languages which most comp.lang.python participants would now refer to as "statically typed", and in the same article referred to Python as "runtime typed", in contrast, probably in an attempt to avoid the usual confusion about whether or not Python is actually strongly typed (which certainly it is)." Or something like that... ;-) -Peter From mickel at csc.fi Tue Mar 23 04:16:46 2004 From: mickel at csc.fi (=?ISO-8859-1?Q?Mickel_Gr=F6nroos?=) Date: Tue, 23 Mar 2004 11:16:46 +0200 (EET) Subject: Windows Media Player 9 with win32com.client.Dispatch? Message-ID: Hi! Anybody tried using Windows Media Player 9 via win32com? (And more precisely, combining that with a Tkinter application.) I found a few earlier threads on Windows Media Player and Python, but it seems nobody has really got it to work, e.g. the below does not work: wmp = win32com.client.Dispatch("MediaPlayer.MediaPlayer.1") wmp.FileName = "C:/Path/To/Some/Media/File.wav" wmp.Play() Is "MediaPlayer.MediaPlayer.1" really the progid to use for Windows Media Player 9? Is there some other way to use Windows Media Player from Python? Embedding C++ in Python? Any code examples? Thanks in advance. /Mickel G. -- Mickel Gr?nroos, application specialist, linguistics, Research support, CSC PL 405 (Tekniikantie 15 a D), 02101 Espoo, Finland, phone +358-9-4572237 CSC is the Finnish IT center for science, www.csc.fi From kkto at csis.hku.hk Thu Mar 18 21:18:38 2004 From: kkto at csis.hku.hk (Isaac To) Date: Fri, 19 Mar 2004 10:18:38 +0800 Subject: '1' + 1 ==> True ??? References: <7ifzc62ovr.fsf@enark.csis.hku.hk> Message-ID: <7iish1bmv5.fsf@enark.csis.hku.hk> >>>>> "Peter" == Peter Maas writes: Peter> The mapping of '1' to 0x31 is defined by ASCII which is used by Peter> C. If a C instruction retrieves a char it reads data from an Peter> adress and if there is a 0x31 stored at the adress C treats it as Peter> '1'. My short form of this is "'1' is 0x31 in memory". In the original post, the literal '1' need not be (and probably is not) stored in memory at all. In this case you have no "address". But that is subtle details. The main point is still that, in the world of C, '1' and 49 are completely indistinguishable *values*. Or put it in another way, in C, a character literal does *not* represent a "character". Instead, the literal '1' is just "the *number* which, by the most common convention used by the computer hardware, is interpreted as the character representing the arabic numeral 'one'". It is a *number*. That's the reason why you can add up 1 and '1'. Not because C "ignores type information and care only the memory". (Try adding up 2.5 and "1"). It is an important distinction: even in C we talk about the abstraction of expression, and the abstraction of character literal is a number, not a "character" in the eye of a regular Python programmer. Peter> I didn't talk about different programs but different machines Peter> (architecture). Python Standard Library (Comparison) has this Peter> Implementation note: Objects of different types except numbers Peter> are ordered by their type names; As you said, it is "implementation note". Also, about C your argument is that different platforms can have different encoding in their characters, and thus different ordering. Since type names are expressed in characters, it follows directly that names of types in Python also has such dependency. Regards, Isaac. From miki.tebeka at zoran.com Sun Mar 14 06:28:18 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Sun, 14 Mar 2004 13:28:18 +0200 Subject: root password in a .py script In-Reply-To: References: Message-ID: <405441D2.1040100@zoran.com> Hello Bart, >> What is preventing you from prompting for the password on execution? > The script must run automaticly/programmaticly on 200 machines. Use `setuid' instead? HTH. Miki From cs1spw at bath.ac.uk Mon Mar 8 21:47:02 2004 From: cs1spw at bath.ac.uk (Simon Willison) Date: Mon, 8 Mar 2004 20:47:02 -0600 Subject: Sending bulk email from a Python script References: <104qbdi22opnib8@corp.supernews.com> Message-ID: <2004030820470233617%cs1spw@bathacuk> On 2004-03-08 20:36:34 -0600, claird at lairds.com (Cameron Laird) said: > You didn't mention how often you're doing this. If it's only daily, there's no problem looping through smtp.send() > as you describe. Really. You're doing the right thing. Excellent. We'll only be doing this once (or at most twice) a day. It sounds like smtp.send() is the way to go. I can always re-examine our options if we run in to performance problems. Thanks a lot for the advice, Simon From scott.b.drummonds.nospam at intel.com Mon Mar 8 12:19:46 2004 From: scott.b.drummonds.nospam at intel.com (Scott Brady Drummonds) Date: Mon, 8 Mar 2004 09:19:46 -0800 Subject: Initializing Member Variables Message-ID: Hi, everyone, I'm a Python novice and just diagnosed a problem that is confusing me. I wrote a class that looks like this: class Keys: __dict = {} def __init__(self, key): self.__dict[key] = key print('keys are now: %s' % self.__dict.keys()) When I test this class from my Python interpreter (interactive), I see the following strange behavior: >>> import keys >>> k1 = keys.Keys('1') keys are now: ['1'] >>> k2 = keys.Keys('2') keys are now: ['2', '1'] >>> k3 = keys.Keys('4') keys are now: ['4', '2', '1'] >>> Maybe this isn't strange for a Python developer, but it sure is for me. I thought that the "__dict = {}" line after the class declaration was supposed to initialize that member variable for each object. Obviously, that's not happening. Instead, that variable is retaining its value from one object to the next, like a static member variable. For what it's worth, it seems that this static variable behavior is not observed when using scalar variables. Just with dictionaries. Where have I gone wrong? What is the purpose of that "initialization" in the Keys class? What is the correct was to initialize a class's member variable and guarantee that it is properly initialized for all objects? Thanks, Scott -- Remove ".nospam" from the user ID in my e-mail to reply via e-mail. From jcarlson at nospam.uci.edu Sat Mar 27 02:02:12 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Fri, 26 Mar 2004 23:02:12 -0800 Subject: Beginner Threaded file reading access In-Reply-To: <4im76054evpqbgkk2ja96rq66t1rm9r2uk@4ax.com> References: <2835a96b.0403230909.35be2b7b@posting.google.com> <4im76054evpqbgkk2ja96rq66t1rm9r2uk@4ax.com> Message-ID: > 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. It is even worse than that. In windows, Python is really a single process, and no amount of threading is going to let one instance of Python use more than 100% of a single CPU. I'm not sure if this is also the case with linux or OS X. - Josiah From do.not at spam.me Tue Mar 2 00:21:59 2004 From: do.not at spam.me (Keith Bowes) Date: Tue, 02 Mar 2004 00:21:59 -0500 Subject: Python as replacement for PHP? In-Reply-To: <403fa54b@news.zianet.com> References: <403fa54b@news.zianet.com> Message-ID: Erik Johnson wrote: > CAUTION: I'm replying as a non-Python programmer. > 1) I think Python is cool. > 2) We can do system administration type scripts (currently > implemented in Perl), web page generation (PHP), and (potentially) > client-side applications (including GUI's that make socket and/or external > HTTP requests) in one language. You can do client-side apps in PHP too. Pass the -q option to the CGI version or just use the CLI version. GUI - PHP-GTK Sockets - The socket extension or fsockopen() to treat it as a regular file. > 3) Python's interactive interpreter makes it easy to try things out. ? Like the -r option? > 4) PyUnit - we would like to develop a robust set of tests and be > able to do regression testing. I'm not aware of a JUnit/PyUnit analog in > PHP. Are you? > 5) Python has better code support for complex native data types > (e.g., tuples, dictionaries, sequences, etc. and being able to write these > directly in a hierarchical structure rather than building them up piecewise > with function calls and assignments as in PHP). In PHP, all these things are essentially arrays and that works fine. Even the PHP developers say that classes are just syntactic sugar for associative arrays (that'll change in PHP 5, though). So PHP is procedural; there's nothing wrong with that. > Not to sound like I hate everything which isn't PHP. It's just that PHP does have a wide range of functionality and is moving toward command-line/administration capabilities, and is quite easy to learn if you know other C-like languages. But if you think that Python better serves your purpose, then you should use it. Surely, it would be possible to write a strtotime() implementation in Python; someone may have already done so. From guy at NOSPAM.r-e-d.co.nz Wed Mar 24 20:31:42 2004 From: guy at NOSPAM.r-e-d.co.nz (Guy Robinson) Date: Thu, 25 Mar 2004 13:31:42 +1200 Subject: monitoring a directory In-Reply-To: References: Message-ID: dw wrote: > Guy Robinson wrote: > >> Hello, >> >> What would be the most efficient or 'clever' way to monitor a >> directory for file additions/ modifications on windows? >> >> Currently I'm looping through the directory with a 1 sec delay. But >> doesn't seem that clever. >> >> Guy > > > This page might give you some hints: > > http://www.sysinternals.com/ntw2k/source/filemon.shtml > > -Don Cheers Don, looks like I can just read the text file. Guy From rogerb at rogerbinns.com Wed Mar 10 13:14:27 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Wed, 10 Mar 2004 10:14:27 -0800 Subject: Working around a lack of 'goto' in python References: Message-ID: leeg wrote: > On the subject of kernel hacking and Python, why can't kernel programming be > considered in Python? Some people share your opinion. Using this toolkit you can write filesystems in Python. Admittedly the framework is all in C, but the actual methods end up being in Python. http://www.freenet.org.nz/python/lufs-python/ Roger From maxm at mxm.dk Wed Mar 10 06:51:37 2004 From: maxm at mxm.dk (Max M) Date: Wed, 10 Mar 2004 12:51:37 +0100 Subject: Zippping a directory recursively from Python script on Windows Message-ID: <404f0141$0$183$edfadb0f@dread12.news.tele.dk> I guess that the best approach is calling a shell tool with something like os.popen(). But I cannot seem to find any free tools. Winzip has a command line option, but for registered users only. That is bothersome if I want to install the script on other machines. The same for pkwares zip. At least I cannot seem to find a free version of it. gzip seems able to do the trick, but I need to install Cygwin, that's also a bother ;-) Can it really be that there is no free .zip command line tool for Windows, or are my Googling skills just to poor? Ideally it should just be a single .exe file that I can put in the folder with my script, for easy distribution. Or is there a more Pythonic approach? regards Max M From joe at notcharles.ca Mon Mar 15 17:46:10 2004 From: joe at notcharles.ca (Joe Mason) Date: Mon, 15 Mar 2004 22:46:10 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 <4055ec40$0$15725$afc38c87 at news.easynet.co.uk>, Peter Hickman wrote: >> He's actually contrasting _statically_ typed languages with >> Python. Unfortunately he is using the word "strongly" where he should >> be using "statically". > > So you are saying the Guido van Rossum doesn't know what he is talking > about and I should take it from you what he really meant? And you said > that I was resorting to 'argument from authority' when you are positing > to know what he really meant. Or you could look it up and find out which one of them is right. Here's a good place to start: http://en.wikipedia.org/wiki/Static_typing#Type_checking Joe From kirk at strauser.com Fri Mar 12 14:35:06 2004 From: kirk at strauser.com (Kirk Strauser) Date: Fri, 12 Mar 2004 19:35:06 GMT Subject: root password in a .py script References: Message-ID: <87y8q5g8sg.fsf@strauser.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 At 2004-03-12T19:11:53Z, Bart Nessux writes: > Why am I doing this? Because users turn off ssh and change the root > password. Mac OSX allows "administrative" users to do this. This script > undoes their changes. 1) Why do you ever use the root password under OS X? There's really nothing that you can't do using 'sudo'. I literally *never* log in as root on an OS X machine. 2) Out of curiosity, why are your users disabling ssh? If they're smart enough to do that, aren't they smart enough to disable your script? 3) Why would you store the unencrypted root password? The 'chpass -a' command lets (actually, requires) you to specify an encrypted password. Store that in your script if you must. 4) Get a 2x4, paint it black and write the word "LART" on it in blood red, and tell your users to quick changing stuff or you'll have to schedule them for "an adjustment". Follow through once or twice if necessary. - -- Kirk Strauser The Strauser Group Open. Solutions. Simple. http://www.strausergroup.com/ -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.4 (GNU/Linux) iD8DBQFAUhCD5sRg+Y0CpvERAqhCAJ9fBYCjzxfHWuaLuFgM9RprGn8DYQCbBo3h BuavPglSNdK1E+9HHmbA0TY= =7Ic8 -----END PGP SIGNATURE----- From alimoe at hornet.berlios.de Fri Mar 12 19:03:39 2004 From: alimoe at hornet.berlios.de (ali moe at BerliOS) Date: Sat, 13 Mar 2004 01:03:39 +0100 Subject: thin4py 0.0.1 ann Message-ID: <40524FDB.mailGS11NABJU@hornet.berlios.de> A non-text attachment was scrubbed... Name: not available Type: application/octet-stream Size: 146 bytes Desc: not available URL: From CaptainN at altel.net Wed Mar 3 22:34:28 2004 From: CaptainN at altel.net (CaptainN at altel.net) Date: Wed, 3 Mar 2004 22:34:28 -0500 Subject: OT(Slightly): Thanks to Python. References: Message-ID: I hear that quite a few people who were working with Java in the past are now switching to Python, especially as Java code balloons in size when compared to Python. "Adonis" wrote in message news:rfw1c.32179$hm4.7868 at newsread3.news.atl.earthlink.net... > This is my .02 as to why Python is excellent for academic use for > upcoming CS graduates. Since I have been 14 I have been programming, mainly > BASIC/VB/C/C++ so I was familiarized with basic programming concepts. Then > up until more than 1 1/2yr ago I stumbled into Python, looking for a C/C++ > compiler for windows, and Python kept coming up, so I go to check it out > (this was on www.downloads.com) I download it, installed it, and ran to the > all common newbie problem of running IDLE and thinking that this is all that > Python had to offer, I naivly deleted it, thinking it was probably some > novelty language, that had no support for it. I check out python.org and > notice it was very active, and there was a more up to date version out, so I > download it again, this time I read the documentation and followed the > tutorial, within 15 minutes I already had enough under my belt to start on > small projects, which within a week I already had made a great deal, I was > hooked! Cutting to the chase, Python introduced me to the world of OOP, > which in VB I mildy touched its pseudo OOP methods, but have not been fully > exposed to it. > Now Python being a fully OOP language, it made it easier for me to > understand what all this OOP stuff was, from generating events to > inheritance, and organizing my code into reusable modules and the such. > Also, the clarity in which Python syntax is presented made it MUCH easier to > understand any source, this was a big plus as I was studying other persons > works to enhance my knowledge of Python. > Then this year I started in a local university to persue my CS degree > after undergoing a 2yr college, in my university the language of choice for > the CS program is Java which I was actually dissappointed as I wanted to > expand my knowledge of C/C++ which I already had some prior knowledge about, > but nevertheless 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. > > Sincerely, > Adonis > > From jon_couchman at hotmail.com Fri Mar 5 10:45:59 2004 From: jon_couchman at hotmail.com (jon c) Date: Fri, 05 Mar 2004 15:45:59 +0000 Subject: is perl better? Message-ID: well the cammand is java -hotspot -showversion ...... -classpath loads of entries application-name the total string is 6809 characters long. I do not know the allowed character length (I am using windows 2000) but perl just runs the command fine, whereas python results in The following character string is too long: ........ _________________________________________________________________ Use MSN Messenger to send music and pics to your friends http://www.msn.co.uk/messenger From francisgavila at yahoo.com Wed Mar 3 16:05:07 2004 From: francisgavila at yahoo.com (Francis Avila) Date: Wed, 03 Mar 2004 21:05:07 -0000 Subject: A 'raw' codec for binary "strings" in Python? References: Message-ID: <20040303160504411-0500@news.shentel.net> In Bill Janssen wrote: >> You could use >> "\xc0".decode("iso-8859-1").encode('US-ASCII', 'replace') > > Yes, this is what I'm doing at the moment. But it seems a real hack. > The string *isn't* in Latin-1; it's binary, it's data, and there > should be a way of saying that. Maybe a third kind of string type? > > Bill > The "raw binary" datatype is the str object. The "text" datatype is the unicode object. Yes, I know that str is more often than not also used for ascii text, but this is historical and ideally should go away. Probably Python 3k will replace str with unicode (possibly calling it "string"), and grow a new datatype for raw binary stuff, with appropriate methods. But no one has really given enough thought to this yet. You can sorta get this now, by running python with the -U flag: destaco:~ favila$ python -U Python 2.3 (#1, Sep 13 2003, 00:49:11) [GCC 3.3 20030304 (Apple Computer, Inc. build 1495)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> type('') >>> It breaks all over the place, though. -- Francis Avila From newsgroups at jhrothjr.com Sun Mar 28 14:27:57 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Sun, 28 Mar 2004 14:27:57 -0500 Subject: Prothon Prototypes vs Python Classes References: <569c605ld1cj8fc1emolk08ete0s1prls1@4ax.com><106cc1f2rsnaoe2@news.supernews.com><406635AB.9050803@mlug.missouri.edu><106ceeeqc8ph126@news.supernews.com> <106dukh7ncf9ad4@news.supernews.com> Message-ID: <106e9tjr1nae8a1@news.supernews.com> "David MacQuigg" wrote in message news:bi1e601vsm4qtqaieqdo69bco64m7naupa at 4ax.com... > On Sun, 28 Mar 2004 11:15:34 -0500, "John Roth" > wrote: > > > > >The difficulty here is simply that there is no way of > >isolating a base object that is supposed to be the platform > >for other objects from objects that are supposed to be > >updatable with new behavior. > > > >The higher a tower you want to build, the firmer the > >foundation. Conventions help, but if the conventions > >are helped along by the language, that's even better. > > In Ruby you can freeze() any object. But it seems like in this case, > just giving your base object a distinct name, like PrototypePolygon > will remind you not to change its definition later as you create > triangles, rectangles, etc. > > I also would have no objection to some syntactic lock, like any object > name ending in an underscore is an immutable object. We could also do > this the other way around. Objects, by default are immutable. That > would take care of most uses. If you want a mutable object, give it a > name ending in ! (bang). A lock would be useful, but the _ to *declare* it immutable probably won't work in practice: it makes it difficult to initialize properly before it's locked. Likewise, the ! (borrowed from Ruby) doesn't work because the vast majority of objects are, in fact, mutable. John Roth > > -- Dave > From ruud.de.jong at consunet.nl Fri Mar 5 09:52:09 2004 From: ruud.de.jong at consunet.nl (Ruud de Jong) Date: Fri, 05 Mar 2004 15:52:09 +0100 Subject: reg exp and octal notation In-Reply-To: References: Message-ID: <4048938a$0$41754$5fc3050@dreader2.news.tiscali.nl> Lucas Branca schreef: > Could someone explain me the difference between the results below? > > ## $cat octals.txt > ## \006\034abc > > import re > > a= "\006\034abc" > preg= re.compile(r'([\0-\377]*)') > res = preg.search(a) > print res.groups() > > loader = open('./octals.txt', 'r') > b = loader.readline() Look at the value of b at this point, you'll see: >>> b '\\006\\034abc\n' In other words, the backslashes are seen as literal backslashes. readline() does no evaluation of the string, it just copies the characters. Regards, Ruud > preg= re.compile(r'([\0-\377]*)') > res = preg.search(b) > print res.groups() > > > RESULTS > > ('\x06\x1cabc',) > > ('\\006\\034abc\n',) > > > Many thanks > Lucas > > From alessandro at sephiroth.it Thu Mar 11 14:10:08 2004 From: alessandro at sephiroth.it (Alessandro Crugnola *sephiroth*) Date: Thu, 11 Mar 2004 19:10:08 GMT Subject: compile exe with anydbm module Message-ID: Hi all I'm trying to compile a python app with py2exe (not the 0.5.0.. i think 0.4.1) which uses the anydbm module But when i launch the exe file created it raise this error: exceptions.ImportError, no dbm clone found; tryed ["dbhash","gdbm","dbm","dumbdbm"] Is there a way to use the anydbm module anyway? thanks in advance From mogmios at mlug.missouri.edu Sun Mar 28 18:41:45 2004 From: mogmios at mlug.missouri.edu (Michael) Date: Sun, 28 Mar 2004 15:41:45 -0800 Subject: Where to offer simple apps In-Reply-To: References: Message-ID: <406762B9.3000401@mlug.missouri.edu> Got a website? Post your code on there and create links from Freshmeat and places such as that? If you don't have a website then why not create one? From ko-admin at li.org Sun Mar 28 08:25:02 2004 From: ko-admin at li.org (ko-admin at li.org) Date: Sun, 28 Mar 2004 13:25:02 +0000 Subject: Your message to ko awaits moderator approval Message-ID: <20040328132502.21548.1870.Mailman@zaphod.alt.org> Your mail to 'ko' with the subject is that criminal? Is being held until the list moderator can review it for approval. The reason it is being held: Post by non-member to a members-only list Either the message will get posted to the list, or you will receive notification of the moderator's decision. From bdelmee at advalvas.REMOVEME.be Fri Mar 5 15:34:54 2004 From: bdelmee at advalvas.REMOVEME.be (=?ISO-8859-1?Q?Bernard_Delm=E9e?=) Date: Fri, 05 Mar 2004 21:34:54 +0100 Subject: is perl better? In-Reply-To: References: Message-ID: <4048e530$0$1112$6c56d894@feed0.news.be.easynet.net> jon c wrote: > well the cammand is > > java -hotspot -showversion ...... -classpath loads of entries > application-name > > the total string is 6809 characters long. > Maybe a workaround would be to use the CLASSPATH environment variable instead of the command line -classpath parameter (using os.environ from python). Hopefully this would make your command line short enough not to hit any hard limit. os.environ[ 'CLASSPATH' ] = 'lib1.jar:...:libN.jar' os.system ( 'java -hotspot -showversion application-name' ) Hope this helps, Bernard. From okyoon at stanford.edu Wed Mar 17 07:31:08 2004 From: okyoon at stanford.edu (Oh Kyu Yoon) Date: Wed, 17 Mar 2004 04:31:08 -0800 Subject: entropy References: Message-ID: I am only a newbie in python, but I can say a few things about entropy. Since a gaussian distribution is a continuous random variable, you have to use "differential entropy" instead of "entropy". They are very similar except that for "differential entropy", you need to integrate rather than sum. If 'f'' is the gaussian distribution, differential entropy h(X) = - integrate(f*log(f) dx). The distribution has to be normalized by the area( integrate(f dx) = 1). I think if you normalize by the area, you'll get similar results. Ohkyu "John Hunter" wrote in message news:mailman.27.1079374026.12241.python-list at python.org... > > I am trying to compute the entropy of a time series (eg, > http://en.wikipedia.org/wiki/Information_theory) using > > S = - sum p_i log2(p_i) > > According to the text I am using, the entropy of a gaussian > distribution should be > > 1/2 log2(2 pi e sigma^2) > > so I am using this result to test my algorithm. Unfortunately, I am > not getting the results to agree. > > Can anyone tell me where I am going wrong? > > > > from Numeric import searchsorted, concatenate, arange, nonzero, log, \ > sum, multiply, sort, greater, take, pi, exp > > from MLab import diff, randn > > def hist(y, bins): > n = searchsorted(sort(y), bins) > n = diff(concatenate([n, [len(y)]])) > return n > > # generate some gaussian numbers > mu = 0.0 > sigma = 2.0 > x = mu + sigma*randn(100000) > > delta = 0.001 > bins = arange(-12.0, 12.0, delta) > > n = hist(x, bins) > > ind = nonzero(greater(n, 0.0)) > n = take(n, ind) # get the positive > n = 1.0/len(n)*n # norm for probability; is this the right normalization > #n = 1.0/len(bins)*n # or this? or something else? > > Scomputed = -1.0/log(2.0) * sum(multiply(n, log(n))) > Sanalytic = 0.5/log(2.0) * log(2*pi*exp(1.0)*sigma**2) > > print Scomputed, Sanalytic > > > > Thanks! > John Hunter > From lamote1 at netscape.net Mon Mar 8 10:53:59 2004 From: lamote1 at netscape.net (chads) Date: 8 Mar 2004 07:53:59 -0800 Subject: How to implement a union (C data type) in Python? Message-ID: <2c22d0af.0403080753.f17a7e0@posting.google.com> How would one implement a union (C data type) in Python, given this simple example? union { struct { int size; float time; } var1; struct { char initial; float time; } var2; }; From mike at nospam.com Fri Mar 26 17:15:45 2004 From: mike at nospam.com (Mike Rovner) Date: Fri, 26 Mar 2004 14:15:45 -0800 Subject: Can I access perl application API's from python References: Message-ID: > Chris Kacoroski wrote: >> I would like to use Python for several scripting tasks I have, but >> the applications I am scripting against only export a set of Perl >> API's. Is there any package that makes it easy to use an >> application's Perl APIs from Python. Essentially I am looking for a >> package that would read a perl module and allow me to access the >> functions in that module from Python. See also http://www.python.org/cgi-bin/moinmoin/PyPerl HTH, Mike From peter at engcorp.com Mon Mar 15 19:03:07 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 15 Mar 2004 19:03:07 -0500 Subject: Static Typing in Python In-Reply-To: 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: Joe Mason wrote: > In article <4055ec40$0$15725$afc38c87 at news.easynet.co.uk>, Peter Hickman wrote: > >>>He's actually contrasting _statically_ typed languages with >>>Python. Unfortunately he is using the word "strongly" where he should >>>be using "statically". >> >>So you are saying the Guido van Rossum doesn't know what he is talking >>about and I should take it from you what he really meant? And you said >>that I was resorting to 'argument from authority' when you are positing >>to know what he really meant. > > Or you could look it up and find out which one of them is right. Here's > a good place to start: > http://en.wikipedia.org/wiki/Static_typing#Type_checking Even looking there (or anywhere) won't really tell you "which is right" (although that particular page is certainly an excellent _description_ of a common usage). Here are some more links to explain this: http://www.dict.org/bin/Dict?Form=Dict2&Database=*&Query=prescriptive and http://www.dict.org/bin/Dict?Form=Dict2&Database=*&Query=descriptive :-) -Peter From k.robert at gmx.de Fri Mar 19 05:26:57 2004 From: k.robert at gmx.de (Robert) Date: 19 Mar 2004 02:26:57 -0800 Subject: Python doesn't know class of function ? : class C:def f():pass; l=[f]; print C.l[0].im_class Message-ID: <19804fd8.0403190226.4a060ed0@posting.google.com> Python doesn't know the class of a method when container not direct class attribute: >>> class X: ... def f():pass ... g=f ... l=[f] ... >>> X.g >>> X.l[0] >>> X.l[0].im_class Traceback (most recent call last): File "", line 1, in ? AttributeError: 'function' object has no attribute 'im_class' >>> why is l[0] a . Any possibility to find the class of this beast dynamically? Robert From antonyliu2002 at yahoo.com Sun Mar 14 15:53:52 2004 From: antonyliu2002 at yahoo.com (Anthony Liu) Date: Sun, 14 Mar 2004 12:53:52 -0800 (PST) Subject: Is reverse reading possible? In-Reply-To: <20040314194619.GE7397@unpythonic.net> Message-ID: <20040314205352.89296.qmail@web13009.mail.yahoo.com> Hmm, it looks cool. I actually don't know what encoding is used for those Chinese documents. How can I know? Can I do something like file.getEncoding() to get its encoding? --- Jeff Epler wrote: > 4M files are not that big these days. > > def reversed_file(name, encoding): > contents = codecs.open(name, "r", > encoding).read() > contents = list(contents) > contents.reverse() > return "".join(contents) > > Example: > >>> codecs.open("utf-example.txt", "r", > "utf-8").read() > u'60: CJK UNIFIED IDEOGRAPHS (0x4E00 - 0x9FFF) | > \u4e25\u5f25\u6f25\n' > >>> reversed_file("utf-example.txt", "utf-8") > u'\n\u6f25\u5f25\u4e25 | )FFF9x0 - 00E4x0( > SHPARGOEDI DEIFINU KJC :06' > > This assumes that you know the encoding for each > file in advance, and > that Python has a codec for it. > > Jeff __________________________________ Do you Yahoo!? Yahoo! Mail - More reliable, more storage, less spam http://mail.yahoo.com From beliavsky at aol.com Thu Mar 4 10:59:05 2004 From: beliavsky at aol.com (beliavsky at aol.com) Date: 4 Mar 2004 07:59:05 -0800 Subject: how fast is object-oriented Python code? Message-ID: <3064b51d.0403040759.452953ea@posting.google.com> I am reading about object-oriented programming in "Learning Python", 2nd. ed. by Lutz and Ascher. On p299, they write "... most of the OOP story in Python boils down to the expression object.attribute. [...] In fact, when classes are involved, the Python expression above translates to the following in natural language: 'Find the first occurrence of attribute by looking in an object, and all classes above it, from bottom to top and left to right'" It seems to me that doing this in a scripting language, at run-time, could be slow, compared to an equivalent code not using classes. How fast is Python OO code compared to non-OO code? I know that object-oriented numerical code in C++ can be much slower than the procedural C or Fortran equivalent, unless one is careful. To what extent is this true with OO and non-OO Python? From stewart at midtoad.homelinux.org Tue Mar 2 22:23:12 2004 From: stewart at midtoad.homelinux.org (midtoad) Date: Wed, 03 Mar 2004 03:23:12 GMT Subject: Graphing library for Tkinter / Pmw? Message-ID: I've installed blt but Pmw can't find it. Yes, I've got tcl and tk installed as well. I went looking for help on the blt site at sourceforge, and notice that the last blt update was in 2002. Has the package been abandoned? If so, are there are other alternatives worth considering? thanks S From tdelaney at avaya.com Tue Mar 2 20:06:49 2004 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Wed, 3 Mar 2004 12:06:49 +1100 Subject: Speed Comparison Perl Python & C Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE013E6A70@au3010avexu1.global.avaya.com> > From: ciw42 > > Compiled optimised code will (should) always be significantly > faster than > interpreted code, but you lose all of the benefits of using a > language such > as Python in the process, so it's all rather pointless > comparing languages > in this way. Of course, it's possible to create some *really* bad code in Python. I've just spent a day finding and fixing an algorithm which turned out to be O(n^3) in some legacy code (in-memory representation of an XML file for network topologies). It was fine for the small, initial topologies that it was developed for. Unfortunately, it didn't scale overly well to the somewhat larger topologies I'm dealing with now ... like 21000 devices ... Put it this way. One single function call was taking an hour to return. After doing some major refactoring - mainly sticking stuff into dictionaries as the file is parsed - that same function call now takes one second. Loading the file has been reduced from 3-4 hours down to 5 minutes. Finding and fixing this bottleneck would have been a *lot* nastier in a lower-level language than Python. In Python however, the optimised algorithm is clear and understandable - in fact, moreso than the original code IMO ;) Tim Delaney From s.mountNOSPAM at REALLYNOSPAMcoventry.ac.uk Tue Mar 23 07:42:37 2004 From: s.mountNOSPAM at REALLYNOSPAMcoventry.ac.uk (Sarah Mount) Date: Tue, 23 Mar 2004 12:42:37 -0000 Subject: Problem using py2exe References: Message-ID: "Tim Golden" wrote in message news:mailman.274.1080042213.742.python-list at python.org... > At the very serious risk of teaching my grandmother to suck eggs, have you > read Pete Shinner's own intro to pygame / py2exe? > > http://www.pygame.org/docs/tut/Executable.html Yeah, interestingly I tried Pete's script which *really* didn't work (didn't even produce and executable), I believe because it's based on an older version of py2exe. My script is based on the examples in the py2exe distribution and does produce an .exe, just not one that works! Ho-hum, Sarah From and-google at doxdesk.com Mon Mar 15 04:39:56 2004 From: and-google at doxdesk.com (Andrew Clover) Date: 15 Mar 2004 01:39:56 -0800 Subject: pyXML beginner questions References: Message-ID: <2c60a528.0403150139.1b9c09ce@posting.google.com> Sebastian Fey wrote: > actually, is nodetype entityReference implemented in pyXML. Yes, but you won't ever see them from a parse operation. Print() will happily serialise an entity reference as &e; providing you can get one into the document in the first place. Using Document.createEntityReference() is the only way I know. > (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. The standard DOM way of doing it is to use the DocumentType.entities interface: doctype= entref.ownerDocument.doctype entdecl= doctype.entities.getNamedItem(entref.nodeName) uri= entdecl.systemId # see also baseURI if using DOM Level 3 Core This isn't any use for 4DOM as you won't get any Entity objects from its parse stage and you can't create your own. In DOM Level 3 Load/Save, control of whether Entity and EntityReference objects are kept in the document is achieved with the DOMConfiguration parameter 'entities': parser= implementation.createLSParser(1, None) parser.domConfig.setParameter('entities', True) # False by default doc= parser.parseURI('file:///in.xml') serialiser= implementation.createLSSerializer() serialiser.domConfig.setParameter('entities', True) serialiser.writeToURI(doc, 'file:///out.xml') DOM 3 LS is still at Proposed Recommendation stage and isn't supported by 4DOM yet. (Insert customary pxdom plug here.) -- Andrew Clover mailto:and at doxdesk.com http://www.doxdesk.com/ From xholcik1 at fi.muni.cz Tue Mar 23 08:32:33 2004 From: xholcik1 at fi.muni.cz (Lukas Holcik) Date: Tue, 23 Mar 2004 13:32:33 GMT Subject: question on charset conversion Message-ID: Hi all there! Would you mind answering a question to a Python newbie?:) Here it is: I have to download a page with windows-1250 and parse it and convert it to iso-8859-2. It there some easy way to acomplish this task using the standard distribution built-in modules? Or do I have to get some extra? Thanks, Lukas Holcik (I'm using Python-2.3.3 on Linux) From rogerb at rogerbinns.com Sun Mar 14 18:36:51 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Sun, 14 Mar 2004 15:36:51 -0800 Subject: Question on making names visible in packages References: Message-ID: > However, I'm only able to get this behavior when I leave the > class definitions in the __init__.py file. When in other files, > they of course have to be referenced as : Make your init.py be like this: from filename1 import * from filename2 import * from filename3 import * If you don't want lots of namespace pollution, you can import only the symbols you want to export in the package namespace. Roger From mwh at python.net Thu Mar 11 08:41:12 2004 From: mwh at python.net (Michael Hudson) Date: Thu, 11 Mar 2004 13:41:12 GMT Subject: Python style guidelines References: <3064b51d.0403101112.3449e987@posting.google.com> <3064b51d.0403110452.4e79fe5a@posting.google.com> Message-ID: beliavsky at aol.com writes: > Skip Montanaro wrote in message news:... > > beliavsky> Is there a more recent set of Python style guidelines than > > beliavsky> PEP 8, "Style Guide for Python Code", by van Rossum and > > beliavsky> Warsaw, at http://www.python.org/peps/pep-0008.html , which > > beliavsky> is dated July 5, 2001? > > > > Is there something missing you think should be there? There's no particular > > reason a PEP needs to be continually updated. In particular, notions of > > good Python style haven't changed a lot over the past ten years. > > > > Skip > > I am not qualified to say what should be in Python style guidelines. I > have now read the PEP 8 style guidelines and see that Python versions > up to 2.3 are covered. I think the Post-History date of July 5, 2001 > is incorrect and should be updated. How so? It hasn't been posted to comp.lang.python since then, and that's what the Post-History: records. Cheers, mwh -- If I had wanted your website to make noise I would have licked my finger and rubbed it across the monitor. -- signature of "istartedi" on slashdot.org From bla at libero.it Thu Mar 18 01:13:15 2004 From: bla at libero.it (Nicola Mingotti) Date: Thu, 18 Mar 2004 07:13:15 +0100 Subject: '1' + 1 ==> True ??? References: <405915F2.BE5ADDF3@alcyone.com> <1079589031.945449@yasure> Message-ID: On Thu, 18 Mar 2004 05:50:33 +0000, Donn Cave wrote: > My guess is that the most important benefit is that any list > of Python objects can be sorted. OH , YES !! This is a sufficient reason ,for me, to admit what seemed a very crazy feature . No i can sleep happy ;) Thank you all , and good night from Italy . bye . From nospam-deets at web.de Thu Mar 4 06:15:55 2004 From: nospam-deets at web.de (Diez B. Roggisch) Date: Thu, 04 Mar 2004 12:15:55 +0100 Subject: Calling C programs References: Message-ID: Use module popen2. -- Regards, Diez B. Roggisch From russelllear at earthlink.net Sun Mar 7 12:43:47 2004 From: russelllear at earthlink.net (Russell Lear) Date: Sun, 07 Mar 2004 17:43:47 GMT Subject: CUPS or IPP in Python? Message-ID: I'm interested in doing printing from within Python. If someone has wrapped the CUPS library in Python, that'd be great. Unfortunately, I can't find such a beast. PyCUPS sounded good, but it seems to have evaporated. If there isn't a CUPS wrapper, perhaps someone has implemented an IPP stack in Python? Since CUPS uses IPP I should be able to use the printer's URI to submit jobs. Right?? Any thoughts out there? Thanks, Russell. From sean_berry at cox.net Sun Mar 28 00:36:01 2004 From: sean_berry at cox.net (sean) Date: Sat, 27 Mar 2004 21:36:01 -0800 Subject: os module question References: Message-ID: <7vt9c.49985$Bg.5493@fed1read03> You might try for line in os.popen("fortune -f").readlines(): print line.strip() os.system() always seems to return all output so I don't know why that doesn't work. I am sure someone better versed in Python will shed some light. "Rasputin" wrote in message news:pan.2004.03.28.04.16.59.189016 at nowhere.net... > On the bash shell if I type "fortune -f" it outputs: > ___% /usr/share/games/fortunes > ___% zippy > ___% fortunes > ___% fortunes2-o > ___% limerick-o > ___% startrek > ___% fortunes2 > ___% unamerican-o > ___% fortunes-o > ___% linuxcookie > > When I type os.system("fortune -f") in python it outputs: > ___% fortunes > '' > > How do I bypass it and get the orginal output? From steve at ninereeds.fsnet.co.uk Sun Mar 14 23:56:46 2004 From: steve at ninereeds.fsnet.co.uk (Stephen Horne) Date: Mon, 15 Mar 2004 04:56:46 +0000 Subject: Is reverse reading possible? References: <20040314180105.GB7397@unpythonic.net> Message-ID: On Sun, 14 Mar 2004 11:10:47 -0800 (PST), Anthony Liu wrote: >The files (nearly 4M each)I am gonna read are a >mixture of Chinese and English, where each Chinese >character has 2 bytes and each English (ASCII) has 1 >byte, although the majority of the texts is Chinese. Four MB isn't much when typical machines have from 256MB to 1GB of RAM. Though maybe this isn't the case in China? Still, if you are concerned, it is possible to read the file line-by-line backwards. But it will be very difficult to impossible to do it straight off when you have non-uniform character sizes as character encodings aren't designed to allow this - it is not generally possible to find the start-byte of each character scanning backwards from the end-byte, only to find the end-byte scanning forward from the start-byte. Solution - do an initial pass reading the file, and keep a list of the start positions of each line. The following code is untested and probably wrong, but should show the general idea of how to do this without knowing the encoding method... f = file ("r") starts = [] while 1 : starts.append (f.tell ()) t = f.readline () if t == '' : break At the end of the loop, starts contains one position for the start of each line plus one extra for the end of the file. The for line no. i, the line can be read as follows... f.seek (starts [i]) t = f.readline () And given that the purpose is reverse reading, the following generator might be useful... def backward_read (p_File) : l_Starts = [] p_File.seek (0) # probably paranoia # First pass, recording line start positions # (no end-of-file pos this time) while 1 : l_Pos = starts.append (p_File.tell ()) if p_File.readline () == '' : break l_Starts.append (l_Pos) l_Starts.reverse () # Second pass, yielding the lines of text for i in l_Starts : p_File.seek (i) yield p_File.readline () If you really want to avoid the initial read too, the general approach would have to be... 1. Derive a grammar (basically a regular expression) for a single character using the character encoding on your machine, such that a match would recognise the sequence of bytes for any single character. The general form might be something like... CHAR : 0x41 # ASCII character 'A' CHAR : 0x42 # ASCII character 'B' ... CHAR : 0x80 0x01 # A wide character CHAR : 0x80 0x02 # Another wide character ... 2. From this, derive the grammar for a whole text file - without using common regular expression shortcuts such as '*'. The general form will be something like... FILE : FILE : CHAR FILE 3. Reverse every rule in the grammar. 4. Generate a parser from the grammar. 5. Run the parser, using line end characters to figure out the 'starts' of new lines. Step 1 is a bit of a killer already - it's a pain having to find out the details of an encoding when you're used to things just working ;-) Step 4 is a much more serious killer. Traditional LL and LR techniques (let alone regular expressions) simply won't cope as the grammar will be full of shift/reduce conflicts. This is the parser-generators way of saying that it can't determine the end token of a rule (in this case CHAR) by scanning from the start token (remember the grammar is reversed, so the start token of a CHAR is the end byte of a character). It is possible to handle this though. Tomita parsers are based on LR techniques, but resolves conflicts at run time - they use 'stack duplication' to keep track of different possible interpretations arising due to LR conflicts. Step 5 is then at least attemptable. As long as the degree of ambiguity (ie the number of stack duplications) stays within reasonable bounds, it should be possible to read the file backwards. This will use a lot of memory, though, even with quite modest files. And it is always possible that in a worst-case runs none of the ambiguities won't get resolved until the whole file is read (and maybe not even then, if the file isn't in the expected encoding). This isn't intended as a practical how-to-do-it, obviously, but rather as an explanation of why you don't want to have to do it! Personally, I'd just read the text lines into a list and iterate the list backwards. -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From gandalf at geochemsource.com Thu Mar 11 03:13:21 2004 From: gandalf at geochemsource.com (Gandalf) Date: Thu, 11 Mar 2004 09:13:21 +0100 Subject: psycopg problem Message-ID: <40501FA1.6030801@geochemsource.com> 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 m_schellens at hotmail.com Wed Mar 10 05:00:15 2004 From: m_schellens at hotmail.com (Marc Schellens) Date: Wed, 10 Mar 2004 19:00:15 +0900 Subject: NumPy (numarray) problem with C code Message-ID: 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 // ... BaseGDL* FromPython( PyObject* pyObj) { PyObject *object; // following is line 225 if( !PyArg_ParseTuple(pyObj, "O!", &PyArray_Type, &object)) // please forget the rest or have a look and tell me if that will work // like I expect or if there is an obvious mistake // its my first time to interface to python { // 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.") ; } // 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.") ; 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; idimensions[ i]; dimArr[ MAXRANK-1] = lastDim; nDim = MAXRANK; } else { for( size_t i=0; idimensions[ i]; } dimension dim( dimArr, nDim); 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 premshree_python at yahoo.co.in Tue Mar 16 07:58:29 2004 From: premshree_python at yahoo.co.in (=?iso-8859-1?q?Premshree=20Pillai?=) Date: Tue, 16 Mar 2004 12:58:29 +0000 (GMT) Subject: Static Typing in Python In-Reply-To: <4056c450$0$305$626a14ce@news.free.fr> Message-ID: <20040316125829.74774.qmail@web8310.mail.in.yahoo.com> --- Bruno Desthuilliers wrote: > Premshree Pillai wrote: > > --- Jacek Generowicz > > wrote: > > > > >>On 13 Mar 2004, at 08:07, Premshree Pillai wrote: > >> > >> > >>>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. > >> > >>I'm no Perler ... but by reading a bit of > >>documentation, I get the > >>impression that you are a bit confused about what > >>"use strict 'vars'" > >>really does. It seems to be some mish-mash of > >>concepts: it imposes the > >>necessity to fully qualify names, to declare (the > >>existence, not the > >>type of) variables with "our", and does some > control > >>of scoping rules. > >> > > > > > > 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). > > I beg your pardon ? Why do you thinks it is called > 'static *typing*'? > Static typing has to do with compile-time *type* > checking, not with > variables declaration. Believe it or no, there are > statically (and > strongly) typed languages that does not enforce > variable declaration nor > even type declaration - this is called type > inference, and you can have > an exemple in OCaml. > > > > Like in C, C++, etc, Python too is > > strongly typed, > > C is certainly not what I'd call a 'strongly' typed > langage, since you > can cast *any* variable to *any* type without the > compiler complaining. > If you want *strong* static typing, go for Ada. In an earlier post, when I mentioned that C/C++ are stongly typed, I had explicitly mentioned - not cosidering casting. -Premshree Pillai ===== -Premshree [http://www.qiksearch.com/] ________________________________________________________________________ Yahoo! India Insurance Special: Be informed on the best policies, services, tools and more. Go to: http://in.insurance.yahoo.com/licspecial/index.html From rpm1deleteme at direcway.com Mon Mar 29 19:18:29 2004 From: rpm1deleteme at direcway.com (RPM1) Date: Mon, 29 Mar 2004 19:18:29 -0500 Subject: Britney Spears nude References: Message-ID: "Jon Perez" wrote in message news:c49rqo$2ebolk$1 at ID-180326.news.uni-berlin.de... > John J. Lee wrote: > > > "celebsrus" writes: > > > > > >>Britney Spears nude Britney Spears nude Britney Spears nude Britney Spears nude > >>Britney Spears nude Britney Spears nude Britney Spears nude Britney Spears nude > > > > [...] > > > > I see Britney has branched out from Semiconductor Physics into Python > > tutoring... > > > > > > John > > With Britney promoting Python, we are UNSTOPPABLE!! Perl, C#, Java, and > Ruby, eat your heart out! 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? Patrick From merkosh at hadiko.de Thu Mar 11 06:38:49 2004 From: merkosh at hadiko.de (Uwe Mayer) Date: Thu, 11 Mar 2004 12:38:49 +0100 Subject: new python syntax: concatenation of functions Message-ID: Hi, I know the python community is not very receptive towards extending the python syntax. Nevertheless I'd like to make a suggestion and hear your pro and cons. I want so suggest a concatenation operator like in mathematics: ? such that: a(b(c(d))) <=> a?b?c(d) Now, why do you think such an extension would be completely useless? ;) Ciao Uwe From alan.gauld at btinternet.com Sat Mar 6 14:16:32 2004 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 06 Mar 2004 19:16:32 +0000 Subject: ready to use python, need help with GUI decision References: <20040303181544.GB74292@dogma.freebsd-uk.eu.org> <4046EE84.9080700@rebirthing.co.nz> Message-ID: <698k40p4rmrvuoq76c8evj1fmj40a2mb3m@4ax.com> On Fri, 05 Mar 2004 08:32:27 -0500, Ed Cogburn 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". :) I've tried both and wxPython is more similar in my view to traditional GUI toolkits like MFC on Windows etc. Any heavy duty GUI work I do in Delphi and so my Python GUI work tends to be fairly simple. Since I was already familiar with Tk then Tkinter is a far easier system to learn. There are fewer widgets and copious documentation. THe wxPython alternatoive offers more widgets but less documentation, and much of that in C++ - and its not as easy to translate as some would have you believe! OTOH wxPython does produce slightly nicer looking windows at the end of the day. > What does PMW do for Tkinter? Add a bunch of missing widgets and dialogs. And again these are actually documented, even in a book - Grayson's Tkinter book. AboutDialog, Ballon, ButtonBox, ComboBox(and variants), Counters, EntryField(inc validation), MenuBar, MessageBar, Notebook(tabbed, with variants), ScrolledCanvas, ScrolledField, ScrolledFrame, etc... > 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? PMW closes the gap but if you are in the business of producing commercial quality GUI apps using Python I guess wxPython would be better than Tkinter (but not necessarily pyQt/pyGTk). Alan G. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld From ruud.de.jong at consunet.nl Fri Mar 19 06:00:59 2004 From: ruud.de.jong at consunet.nl (Ruud de Jong) Date: Fri, 19 Mar 2004 12:00:59 +0100 Subject: ld.so.1: fatal ImportError: ld.so.1 No such file or directory In-Reply-To: <86b5da9a.0403180001.3115ff55@posting.google.com> References: <86b5da9a.0403171153.496e59ed@posting.google.com> <4058b6d6$0$41758$5fc3050@dreader2.news.tiscali.nl> <86b5da9a.0403180001.3115ff55@posting.google.com> Message-ID: <405ad249$0$41762$5fc3050@dreader2.news.tiscali.nl> o'seally schreef: > i'm Not trying to find a solution for a python problem, i'm in fact > posting a solution to the notorius "ld.so.1: fatal ImportError: > ld.so.1 No such file or directory" error that many people are > complaining about on the newsgroups/internet. when they search on > google for this kind of error, they'll find a link to my > comments/advice/suggestions. i would think that would be very helpful > to them. Well, This was not obvious from a first reading. I read your original post again, and basically you say: Problem: fatal ImportError: xx.so.n No such file or directory Solution: make the file xx.so.n visible through LD_LIBRARY_PATH Duh. This is essentially identical to the solutions that have been offered time and again whenever this or a similar problem is reported. Your post differs from most others because: * it was not in response to a problem, making it more difficult to discover the intention of the post; * you needed over 100 lines of text to provide this solution; * the liberal use of CAPITALS (which gives your post a rather spam-like appearance); * the digression on irrelevant subjects (why bring free or open source software in the discussion?) Because of the low signal/noise ratio, I did not recognize this to be a solution for a problem that happens from time to time. On the contents of your post: you suggest to create symbolic links in one of the directories in LD_LIBRARY_PATH to make the required files visible, instead of appending their directory to LD_LIBRARY_PATH. Be aware that symbolic links make the files visible to *all* applications -- you may not always want that. Manipulating the LD_LIBRARY_PATH environment variable gives you more flexibility, and you also don't need root privileges to do so. You can also choose to manipulate LD_LIBRARY_PATH via a shellscript wrapper for the actual program you want to run; this is especially useful when there are naming collisions. Regards, Ruud. From mogmios at mlug.missouri.edu Mon Mar 29 11:03:25 2004 From: mogmios at mlug.missouri.edu (Michael) Date: Mon, 29 Mar 2004 08:03:25 -0800 Subject: tabbing probs (was: Prothon Prototypes vs Python Classes) In-Reply-To: <106gg1jifa2n9c2@news.supernews.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> <106gg1jifa2n9c2@news.supernews.com> Message-ID: <406848CD.5070100@mlug.missouri.edu> >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. > > No, I just fail to see why it matters. A tab could be 4 columns, 8 columns, 15 columns, or whatever on a particular editor and code blocks will still line up. >It matters. 8 columns is much too wide for indents in readable code. >People do differ on that, but that seems to be the concensus. > > So rather than switch editors or change your editors settings you'd rather everyone be forced to use spaces? I presume four spaces? If someone uses eight spaces to indent will that also break the code? It seems to me that it'd be easier to configure an editor to show tabs as four columns, if you so desire, than to configure an editor to show eight spaces as four columns. Eight spaces is no easier to read than a tab that takes eight columns. It's just more typing to correct the problem. By my own preference, if I'm forced to use spaces to indent rather than tabs, then I'll most likely use a single space to indent because I don't want to deal with pressing the space and backspace keys multiple times (trying to keep count) to make blocks line up correctly. I also don't find it acceptable to use an editor which kludges together such space using behavior for me to do what tabs would have done in the first place. Overall, I think I find code that uses a single tab, rather than a single space, to be easier to read. From davecook at nowhere.net Thu Mar 4 04:04:59 2004 From: davecook at nowhere.net (David M. Cook) Date: Thu, 04 Mar 2004 09:04:59 GMT Subject: Which Python module for PostgreSQL? References: Message-ID: In article , Gandalf wrote: > Hmm, this is why I use C-style booleans (e.g. an integer where 0 means > false and not 0 means true). You mean in your SQL schema? I guess I could start doing that. I'm moving to sqlite anyway, which doesn't have datatypes at all. Dave Cook From noah at noah.org Thu Mar 25 13:09:28 2004 From: noah at noah.org (Noah) Date: 25 Mar 2004 10:09:28 -0800 Subject: monitoring a directory References: Message-ID: Guy Robinson wrote in message news:... > Cheers Tim, that's the ticket. Perfect!!! > Regards, > Guy > >>What would be the most efficient or 'clever' way to monitor a > >>directory > >>for file additions/ modifications on windows? > >>Currently I'm looping through the directory with a 1 sec delay. But > >>doesn't seem that clever. > > There are two methods that I know of (apart from the simple approach you > > describe). One is described in this recipe: > > > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/156178 Now how do I do this for UNIX? I always did the 1 second looping thing and felt somewhat ashamed that I couldn't think of anything better... It seems like there should be some sort of blocking system call that will return when a directory or file changes -- something like "select". Yours, Noah From joe at notcharles.ca Tue Mar 23 03:28:54 2004 From: joe at notcharles.ca (Joe Mason) Date: Tue, 23 Mar 2004 08:28:54 GMT 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: In article , Skip Montanaro wrote: > > DH> Possible future Python example that uses "as" differently: > > DH> def foo(x as int, y as float) as int: > DH> "this function returns an integer, and takes an int & float params" > > With no extension beyond the current PEP 318 proposal, you might postulate > returns() and accepts() decorators: > > def foo(x, y) [accepts(int, float), returns(int)]: > ... > > which extend foo() with code to enforce input and output types. Further, > function attributes could be added which could be used by tools like > pychecker for intermodule type checking. 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"? Joe From http Wed Mar 3 14:40:42 2004 From: http (Paul Rubin) Date: 03 Mar 2004 11:40:42 -0800 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> <4045a616.8831515@news.t-online.de> Message-ID: <7xishlsoqt.fsf@ruckus.brouhaha.com> m.bless at gmx.de (Martin Bless) writes: > I'd really like to. But unfortunately I've discovered the weak point > in my own argumentation: a new keyword could and probably would break > existing code. Therefore I can't go for a PEP until I have a better > idea. You could suggest adding an "attribute" to the existing keyword: print foo,bar # print with spaces print.n foo,bar # print without spaces I don't care too much for this idea but it would solve your immediate concern. From wilkSPAM at OUTflibuste.net Fri Mar 19 18:16:21 2004 From: wilkSPAM at OUTflibuste.net (Wilk) Date: Sat, 20 Mar 2004 00:16:21 +0100 Subject: Python Tic Tac Toe References: Message-ID: <87lllwpgvu.fsf@blakie.riol> Premshree Pillai writes: > Hello folks, > > I wrote a web-based Tic Tac Toe game in Python. Source > at > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/275150 > > A lot of the code is redundant, but I don't have the > mind to optimize it now. Could you improve it to play with bigger board and 5 stones to win ? We could fight together ;-) http://flibuste.net/libre/morpyon http://flibuste.net/libre/morpyon/Morpyon-2.0.tar.gz it works on console or with pygame -- Wilk - http://flibuste.net From steve at ninereeds.fsnet.co.uk Sun Mar 7 13:35:50 2004 From: steve at ninereeds.fsnet.co.uk (Stephen Horne) Date: Sun, 07 Mar 2004 18:35:50 +0000 Subject: Working around a lack of 'goto' in python References: Message-ID: <9gpm405d952ooq37bmeilacks37o4on086@4ax.com> On Sat, 06 Mar 2004 18:18:28 GMT, "Brett" wrote: >Two areas where I've found 'goto' two be useful in other languages are in >(untested examples in C++) > >(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; > >END: /* continue */; > >and (2) repeating a while or for loop from the beginning: > >BEGIN: >for (n=0; n < 20; ++n) > if (/* some test */) goto BEGIN; > >What are the techniques in python for simulating these algorithms without a >'goto' command? I've been using C++ quite a while and never needed either of those patterns. I have used a goto in C++ not too long ago, but not for anything close to your examples, and its my first time in any language for at least 10 years. The reason for it was what I call a 'short running state machine' - a state machine which needs to run to completion when invoked. I could have used a loop with an embedded switch statement, but that just didn't fit what was happening and would have made the code less readable and maintainable - a goto is the natural representation of a transition between states. Once in ten years of doing a lot of programming. I don't think many people need to worry about this use case ;-) The normal reason for needing to exit deep loops (or any deep set of structures), and a common reason for using goto in C, is due to an error condition. In that case, throw an exception. This is a much better way to handle errors as the code that throws the exception doesn't need to know how (or if) the exception will be handled. The only other common case where I've seen C's goto considered a good thing is in search algorithms. The easy exit from the (probably nested) loops can be useful. But when doing searches I tend to regard success as the exceptional case and throw an exception for it, though I don't think I've used the technique in Python to date. If you have a use case for the loop restarting, I'd like to see it. With a use case it is much easier to provide an alternative, and there isn't any that strikes me as obvious as it stands. -- Steve Horne steve at ninereeds dot fsnet dot co dot uk