From ktilton at nyc.rr.com Fri Oct 3 09:52:07 2003 From: ktilton at nyc.rr.com (Kenny Tilton) Date: Fri, 03 Oct 2003 13:52:07 GMT Subject: Python syntax in Lisp and Scheme In-Reply-To: References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> Message-ID: Kenny Tilton wrote: > > > Toni Nikkanen wrote: > >> It's be interesting to know where people got the idea of learning >> Scheme/LISP from (apart from compulsory university courses)? > > > We wonder alike. That's why I started: > > http://alu.cliki.net/The%20Road%20to%20Lisp%20Survey > > That recently got repotted from another cliki and it's a little mangled, > but until after ILC2003 I am a little too swamped to clean it up. Me and my big mouth. Now that I have adevrtised the survey far and wide, and revisited it and seen up close the storm damage, sh*t, there goes the morning. :) Well, I needed a break from RoboCells: http://sourceforge.net/projects/robocells/ I am going to do what I can to fix up at least the road categorization, and a quick glance revealed some great new entries, two that belong in my Top Ten (with apologies to those getting bumped). kenny From bokr at oz.net Wed Oct 8 18:12:31 2003 From: bokr at oz.net (Bengt Richter) Date: 8 Oct 2003 22:12:31 GMT Subject: Python syntax in Lisp and Scheme References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> <92c59a2c.0310031345.57d20631@posting.google.com> <3ce3cvhz.fsf@ccs.neu.edu> Message-ID: On Wed, 08 Oct 2003 16:41:44 -0400, Joe Marshall wrote: >David Rush writes: > >> You know I think that this thread has so far set a comp.lang.* record >> for civilitiy in the face of a massively cross-posted language >> comparison thread. I was even wondering if it was going to die a quiet >> death, too. >> >> Ah well, We all knew it was too good to last. Have at it, lads! >> >> Common Lisp is an ugly language that is impossible to understand with >> crufty semantics >> >> Scheme is only used by ivory-tower academics and is irerelevant to >> real world programming >> >> Python is a religion that worships at the feet of Guido vanRossum >> combining the syntactic flaws of lisp with a bad case of feeping >> creaturisms taken from languages more civilized than itself >> >> There. Is everyone pissed off now? > >No, that seems about right. LOL ;-) Regards, Bengt Richter From mspight at dnai.com Fri Oct 24 16:10:01 2003 From: mspight at dnai.com (Marshall Spight) Date: Fri, 24 Oct 2003 20:10:01 GMT Subject: Python from Wise Guy's Viewpoint References: <_8Ekb.7543$pT1.318@twister.nyc.rr.com> <87k76v9531.fsf@thalassa.informatimago.com> Message-ID: "Pascal Bourguignon" wrote in message news:87k76v9531.fsf at thalassa.informatimago.com... > > The only untyped languages I know are assemblers. (ISTR that even > intercal can't be labelled "untyped" per se). > > Are we speaking about assembler here? BCPL! Marshall From dietz at dls.net Sat Oct 18 13:58:58 2003 From: dietz at dls.net (Paul F. Dietz) Date: Sat, 18 Oct 2003 12:58:58 -0500 Subject: Why don't people like lisp? In-Reply-To: References: <1A8kb.67406$pv6.3464@twister.nyc.rr.com> Message-ID: Lulu of the Lotus-Eaters wrote: > In my own mind, the biggest impediment to really liking Lisp is not the > annoying parentheses and awful syntax... it's many Lispers (especially > those like Tilton). Do you often let the behavior of others control how you think about technical topics? Paul From dthierbach at gmx.de Fri Oct 24 19:50:29 2003 From: dthierbach at gmx.de (Dirk Thierbach) Date: Sat, 25 Oct 2003 01:50:29 +0200 Subject: Python from Wise Guy's Viewpoint References: <3f972315$1@news.unimelb.edu.au> <3638acfd.0310230039.306b14f@posting.google.com> <3638acfd.0310232246.64fa09ed@posting.google.com> <65fn61-b61.ln1@ID-7776.user.dfncis.de> <3F994597.7090807@ps.uni-sb.de> <1j5o61-co2.ln1@ID-7776.user.dfncis.de> <1xt2gt7c.fsf@comcast.net> Message-ID: <5fqo61-dg7.ln1@ID-7776.user.dfncis.de> prunesquallor at comcast.net wrote: > I don't understand why you think that most of them will be `dead code'. Because otherwise the code will be executed, and this will result in a crash -- there must be a reason why the type checker complains. > I don't understand why a smart type checker would complain about dead > code. Because in general, it is not decidable if some part of the code will be executed or not (halting problem). - Dirk From noemail at noemail4u.com Thu Oct 30 08:39:25 2003 From: noemail at noemail4u.com (Dang Griffith) Date: Thu, 30 Oct 2003 13:39:25 GMT Subject: PEP 322: Reverse Iteration (second revision, please comment) References: <3fa0ea04$1@brateggebdc5.br-automation.co.at> Message-ID: <05c42d8fbc5d95ce3638ebabdfbbe0f5@news.teranews.com> On Thu, 30 Oct 2003 11:38:42 +0100, Werner Schiendl wrote: >Raymond Hettinger wrote: > >> * reversed() is being preferred to ireverse() as the best name. > >I cannot remember to ever having had a need for reverse enumerate... > But if you did, how about 'remunerate()' as the name for it? --dang "artificially intelligent" From op73418 at mail.telepac.pt Wed Oct 1 12:16:28 2003 From: op73418 at mail.telepac.pt (Gonçalo Rodrigues) Date: Wed, 01 Oct 2003 17:16:28 +0100 Subject: appending to list References: Message-ID: On Wed, 1 Oct 2003 08:49:20 -0700 (PDT), sud jag wrote: >Hi, > Iam a newbie to python. So any help on this is >deeply appreciated > > If I append an instance of a class to a list will >the list have a copy of the instance or just a >reference to that instance ? If it is only a reference >is there something similar to deep copy in case of >append ? > Only a reference. Note though that within the bounds of pure Python de-referencing is automatic, you can never get hold of the reference as a Python object. If you want a copy you mst explicitely ask for it -- check out the copy module, in particular the deepcopy function. >Thanks, >quent > With my best regards, G. Rodrigues From mwilson at sarcastic-horse.com Fri Oct 3 15:29:29 2003 From: mwilson at sarcastic-horse.com (Matthew Wilson) Date: Fri, 3 Oct 2003 15:29:29 -0400 (EDT) Subject: negative numbers and integer division In-Reply-To: References: <36085.199.169.240.132.1065206568.squirrel@svr1.turboweb.net> Message-ID: <42304.199.169.240.132.1065209369.squirrel@svr1.turboweb.net> > Not really, but because the intended connection between (-1, 2001) and > (11, > 2000) escapes me. That is, I have no idea how to generalize that. For > example, is (0, 2001) OK as-is, or should that become (12, 2000), or ...? I should have spelled out the goal. I want to do stuff like this: >>> dec99 = mdate(12,1999) >>> jan00 = dec99+1 >>> nov99 = jan00 - 1 >>> nov99 (11,1999) I want to add and subtract integers from my date structure as if they were months. From mrfaro at libero.it Fri Oct 31 02:48:32 2003 From: mrfaro at libero.it (Gabriele Farina) Date: Fri, 31 Oct 2003 07:48:32 GMT Subject: Implementing a scripting language in Python Message-ID: I guys I planned to create a new programming language to use to develop web applications for my company. I'd like to develop it using Python, but I don't know if python is fast enaught. Someone could help me and give me some ideas? tnx, Gabriele From jockc at mail.com Mon Oct 20 19:07:38 2003 From: jockc at mail.com (Jock Cooper) Date: 20 Oct 2003 16:07:38 -0700 Subject: Why don't people like lisp? References: <3f9302d7.170372828@news.eircom.net> Message-ID: Alex Martelli writes: > Pascal Costanza wrote: >snip > What's "considerably more complicated" in, say, > my_frobazzer = frobaz_compiler(''' > oh my pretty, my beauteous, > my own all my own special unique frambunctious *LANGUAGE*!!! > ''') > and later on call my_frobazzed(bim. bum, bam) at need? The complexity > of the frobaz_compiler factory callable depends exclusively on the > complexity of the language you want it to parse and compile, and you > of course have total choice ("Python doesn't give you a choice" MY > LEFT FOOT) on how to apportion the work between the factory and the > __call__ method of the resulting my_frobazzer. Just imagine if your embedded language also used white space to denote program structure.. cut and paste would get a little more tricky... From ktilton at nyc.rr.com Sat Oct 18 15:13:13 2003 From: ktilton at nyc.rr.com (Kenny Tilton) Date: Sat, 18 Oct 2003 19:13:13 GMT Subject: Why don't people like lisp? In-Reply-To: References: <1A8kb.67406$pv6.3464@twister.nyc.rr.com> Message-ID: Pascal Costanza wrote: > I haven't actually ever used Python in practice, so I can't really tell > whether the syntax or some other features of Python will make me go > eureka when I use them. FWIW, I have used Python in anger, and the textual clarity of my code was indeed remarkable. -- http://tilton-technology.com What?! You are a newbie and you haven't answered my: http://alu.cliki.net/The%20Road%20to%20Lisp%20Survey From tfb at famine.OCF.Berkeley.EDU Wed Oct 8 02:24:35 2003 From: tfb at famine.OCF.Berkeley.EDU (Thomas F. Burdick) Date: 07 Oct 2003 23:24:35 -0700 Subject: Python syntax in Lisp and Scheme References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> <92c59a2c.0310031345.57d20631@posting.google.com> <3F82EF06.F3D7A10@setf.de> <3f835157@news.sentex.net> Message-ID: hs at heaven.nirvananet (Hartmann Schaffer) writes: > In article , > tfb at famine.OCF.Berkeley.EDU (Thomas F. Burdick) writes: > > Marcin 'Qrczak' Kowalczyk writes: > > > >> I find the Lisp syntax hardly readable when everything looks alike, > >> mostly words and parentheses, and when every level of nesting requires > >> parens. I understand that it's easier to work with by macros, but it's > >> harder to work with by humans like I. > > > > You find delimited words more difficult than symbols? For literate > > people who use alphabet-based languages, I find this highly suspect. > > Maybe readers of only ideogram languages might have different > > preferences, but we are writing in English here... > > well, there are a few occasions where symbols are preferrable. just > imagine mathematics with words only Oh, certainly. Unlike most languages, Lisp lets you use symbols for your own names (which is easily abused, but not very often). A bad example: ;; Lets you swear in your source code, cartoonishly (define-symbol-macro $%^&! (error "Aw, $%^&! Something went wrong...")) ;; An example use (defun foo (...) (cond ... (t $%^&!))) And, although you generally use symbols from the KEYWORD package for keyword arguments, you don't have to, and they don't have to be words: (defgeneric convert-object (object new-type) (:documentation "Like an extensible COERCE.")) (defun convert (object &key ((-> to))) "Sugary" (convert-object object to)) (defconstant -> '-> "More sugar") ;; Example usage (convert *thing* -> (class-of *other-thing*)) Of course, these are lame examples, but they show that Lisp *can* incorporate little ascii-picture-symbols. Good examples would necessarily be very domain-dependant. -- /|_ .-----------------------. ,' .\ / | No to Imperialist war | ,--' _,' | Wage class war! | / / `-----------------------' ( -. | | ) | (`-. '--.) `. )----' From FBatista at uniFON.com.ar Tue Oct 21 10:06:14 2003 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Tue, 21 Oct 2003 11:06:14 -0300 Subject: searching structures Message-ID: #- I'd like to know how many 'arrays' start with ABCD like ABCD* #- (ABCD,ABCDE,ABCDEF) You mean filtering by the NAME of the object? . 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 harry.g.george at boeing.com Mon Oct 27 03:00:15 2003 From: harry.g.george at boeing.com (Harry George) Date: Mon, 27 Oct 2003 08:00:15 GMT Subject: Newbie Questions: Swithing from Perl to Python References: Message-ID: "Luther Barnum" writes: > I am a new Python programmer and I am having a few difficulties. I love Perl > and I am just trying to learn Python because it is used heavily at work. It > looks pretty cool so I am diving in. I'm sure they are easy but I not sure > how to proceed. > > 1. How can I run a program and modify the output on the fly then send it to > standard output. > > Example in Perl: > > ex. open(LS_PIPE, "/usr/bin/ls |"); > while() { > s/this/that/g; > print; > } > close(LS_PIPE); > > > 2. How can I sort and print out a hash. > > Example in Perl: > > ex. foreach $string (sort keys %hash) { > print("$string = $hash{$string}\n"); > } > > In Perl these are very easy tasks, but I am finding it a little difficult to > understand. > > Like most perl-to-python migrants, yoiu are still thinkiing in perl. Here is a module to show how to do the std sorts of things: http://www.seanet.com/~hgg9140/comp/pyperlish-1.2/doc/manual.html available at: http://www.seanet.com/~hgg9140/comp/index.html -- harry.g.george at boeing.com 6-6M31 Knowledge Management Phone: (425) 342-5601 From nholtz at docuweb.ca Tue Oct 21 14:20:03 2003 From: nholtz at docuweb.ca (Neal Holtz) Date: 21 Oct 2003 11:20:03 -0700 Subject: [OT] Inuit? Eskimo? References: <20031020163642.GA5539@nl.linux.org> <4vre61-ku2.ln1@beastie.ix.netcom.com> Message-ID: <639f17f8.0310211020.53f31dbe@posting.google.com> Skip Montanaro wrote in message news:... > >> Yes, but it's sort of like the Eskimos ("arctic native americans"?) > So, I guess the [OT] pop quiz of the day is (fill > in the blank): > > "Native American" is to "American Indian" as ______ is to "Eskimo". > > Anyone in the .ca domain care to educate the .us folks? I think 'Inuit' would be best here. For a decent definition, see http://dictionary.reference.com/search?q=inuit We also use 'aboriginal', but that is a broader term that also includes southerners. From mark at markroseman.com Tue Oct 14 07:01:24 2003 From: mark at markroseman.com (Mark Roseman) Date: Tue, 14 Oct 2003 07:01:24 -0400 Subject: Tkinter isn't permanently ugly (was: python applications deployement) References: <607d8200.0310130551.13bf2fa5@posting.google.com> Message-ID: Yeah, we're definitely hoping to get there soon in terms of bringing Tk into the modern era. As you say, it certainly is customizable enough... probably so customizable that people have been able to make do by tweaking, and nobody has bothered to go in and fix the default behavior so everyone can take advantage of it without pain! With the Tk revitalization work, we're trying to address that. Out of the box, we want Tk to look more modern out of the box (no more Motif look), which is mostly achievable now via option settings but needs to be baked in by default. Also adding a bunch more widgets like comboboxes, since it is ridiculous for everyone to need to do it differently. And yes, the tearoff menus being on by default are definitely on my personal hit list. :-) Mark (see http://tcl.projectforum.com/tk/ to help out or just try out the latest demos that we have available!) > Hey, nice! Tk is definitely the path of least resistance for me with GUI > coding, but there definitely is a distinct Tk look that might have been > fashionable back when Motif was popular but now looks weird or dated to > most people. However, a lot of this has to do with defaults; on one project, > I was able to produce a Tk app that looked exactly like a typical Windows > interface, with IE-style toolbar buttons and everything. Tk is very > customizable. > > The major deficiencies, in my opinion, are: > > - way too many ways to make a combobox, the standard one being the > ugliest, and the nonstandard ones being difficult to customize and debug > - tearoff menus by default - probably sounded like a good idea at the time =) > - text areas + word wrap + scrollbar = bizarre > - slow rendering (IDLE is a testament to this) From tzot at sil-tec.gr Fri Oct 24 08:58:32 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Fri, 24 Oct 2003 15:58:32 +0300 Subject: Introspection: expression evaluation order - precedence Message-ID: <634ipvk5c4q860kacb99i05cmieda5kcgd@4ax.com> Hi all, this post contains at the end a handy module that I've used quite often when I wanted to analyse the occasional complex expression and how it was to be evaluated. The function analyse_expression is called with a single string argument containing an expression. Names are allowed (actually, preferred over numbers ;-), since the function eval's in a protected dictionary, where names are generated as needed. The output is a string containing many lines, where each line is of the format: [] and 1st are missing for unary operators. There are only a few exception checks, since basically the function is to be called with expressions pasted from actual syntactically correct code. Hope this helps other people, esp. newcomers in the python world. Next step will be an tree-structured expression editor, allowing easy editing (eg exchange the first argument of a function with the second onei, even if these are complex expressions themselves, for people who don't break down complex expressions as much as the Python spirit would suggest), which could find a use inside Idle if done OK; but that will be RSN :) In case you find any flaws in this module, I would be glad to know and correct them. Improvements are accepted without any arguments! Examples: >>> print analyse_expression('x+y-sqrt(5/-z.real*6)') x + y z . real - z.real 5 / -z.real 5/-z.real * 6 sqrt ( 5/-z.real*6 ) x+y - sqrt(5/-z.real*6) Why names are preferred over numbers (a bug, actually ;-): >>> print analyse_expression('5+sin(angle=.6*x)') Traceback (most recent call last): File "", line 1, in -toplevel- print analyse_expression('5+sin(angle=.6)') File "analexpr.py", line 68, in analyse_expression eval(code_object, namespace) File "", line 0, in -toplevel- TypeError: unsupported operand type(s) for +: 'int' and 'str' but, substituting z for 5 >>> print analyse_expression('z+sin(angle=.6*x)') 0.6 * x sin ( angle=0.6*x ) z + sin(angle=0.6*x) Don't use expressions without any names in it: >>> analyse_expression('6+7-8*4') '' cause it doesn't work... use at least one name: >>> print analyse_expression('6+7-z*4') z * 4 13 - z*4 Using 'and', 'or' keywords will always behave as if their first operand was True: >>> print analexpr.analyse_expression('z+7 and x+1 or y') z + 7 x + 1 The module (no copyrights, public domain): class EvaluationObject(object): """A helper class for analysing expressions""" __slots__ = "_datum", def __init__(self, datum): self._datum = datum def __str__(self): return self._datum def __call__(self, *args, **kwargs): reply= [] reply.append(self._datum) reply.append("(") if args: out_arg_list1= [] for arg in args: out_arg_list1.append(str(arg).replace(' ', '')) reply.append(','.join(out_arg_list1)) if kwargs: out_arg_list2= [] for arg, value in kwargs.iteritems(): out_arg_list2.append("%s=%s" % (arg, value)) reply.append(','.join(out_arg_list2).replace(' ', '')) reply.append(")") rc = " ".join(reply) EvaluationObject.order.append(rc) return rc # create all the (EvaluationObject.__method__)s def _make_binary_method(operator, reverse=False): "Binary arithmetic operator factory function for EvaluationObject" def _dummy(self, other): if reverse: self, other = other, self rc = "%s %s %s" % (str(self).replace(' ',''), operator, str(other).replace(' ','')) EvaluationObject.order.append(rc) return EvaluationObject(rc) return _dummy # mass-make the arithmetic methods for function in "add,+ sub,- mul,* floordiv,// mod,%" \ " pow,** lshift,<< rshift,>>" \ " and,& xor,^ or,| div,/ truediv,/" \ " getattr,.".split(): name, operator= function.split(",") setattr(EvaluationObject, "__%s__" % name, _make_binary_method(operator)) setattr(EvaluationObject, "__r%s__" % name, _make_binary_method(operator, reverse=True)) def _make_unary_method(operator): "Unary arithmetic operator factory function for EvaluationObject" def _dummy(self): rc = "%s %s" % (operator, str(self).replace(' ', '')) EvaluationObject.order.append(rc) return EvaluationObject(rc) return _dummy for function in "neg,- pos,+ invert,~".split(): name, operator = function.split(",") setattr(EvaluationObject, "__%s__" % name, _make_unary_method(operator)) # cleanup del _make_binary_method, _make_unary_method, function, name, operator def analyse_expression(expr): '''Return as string a list of the steps taken to evaluate expr''' code_object = compile(expr, "", "eval") namespace = {'__builtins__': {}} # namespace should be a dict subclass that creates items # on demand. # exec and eval assume that the namespaces are dict objects # and bypass any __getitem__ methods of the subclass # to overcome this limitation, keep trying to eval the expression # until no more name errors occur. while True: try: EvaluationObject.order = [] eval(code_object, namespace) except NameError, exc: # exc.args[0] is of the form: # name 'x' is not defined # use hardcoded slice to get the missing name name = exc.args[0][6:-16] namespace[name] = EvaluationObject(name) else: break result = '\n'.join(EvaluationObject.order) del EvaluationObject.order return result -- TZOTZIOY, I speak England very best, Ils sont fous ces Redmontains! --Harddix From qrczak at knm.org.pl Sun Oct 19 14:38:13 2003 From: qrczak at knm.org.pl (Marcin 'Qrczak' Kowalczyk) Date: Sun, 19 Oct 2003 20:38:13 +0200 Subject: Python from Wise Guy's Viewpoint References: Message-ID: On Sun, 19 Oct 2003 20:01:03 +0200, Joachim Durchholz wrote: > The longer answer: Multimethods have modularity issues (if whatever domain > they're dispatching on can be extended by independent developers: > different developers may extend the dispatch domain of a function in > different directions, and leave undefined combinations; This doesn't matter until you provide an equally powerful mechanism which fixes that. Which is it? -- __("< Marcin Kowalczyk \__/ qrczak at knm.org.pl ^^ http://qrnik.knm.org.pl/~qrczak/ From aleax at aleax.it Mon Oct 27 08:20:25 2003 From: aleax at aleax.it (Alex Martelli) Date: Mon, 27 Oct 2003 13:20:25 GMT Subject: PEP 289: Generator Expressions (please comment) References: <5d83790c.0310231158.65595858@posting.google.com> Message-ID: Holger Krekel wrote (answering Raymond Hettinger): ... >> sum(x*x for x in roots) ... >> bestplayer, bestscore = max( (p.score, p.name) for p in players ) Actually I think RH meant "bestscore, bestplayer = ..." here... > Although most people on python-dev and here seems to like this PEP I > think it generally decreases readability. The above constructs seem > heavy and difficult to parse and thus i am afraid that they interfere > with the perceived simplicity of Python's syntax. Let's see: today, I could code: sum([x*x for x in roots]) In 2.4, I will be able to code instead: sum(x*x for x in roots) with some performance benefits. Could you please explain how using the lighter-weight simple parentheses rather than today's somewhat goofy ([ ... ]) bracketing "generally decreases readability"...? Similarly, today's: bestscore, bestplayer = max([ (p.score, p.name) for p in players ]) I'll be able to code as a somewhat faster: bestscore, bestplayer = max( (p.score, p.name) for p in players ) Again, I don't see how the proposed new construct is any more "heavy and difficult to parse" than today's equivalent -- on the contrary, it seems somewhat lighter and easier to parse, to me. It may be a different issue (as you appear, from a later message, to be particularly enamoured of Python's current 'fp' corner) to claim that, say, yesteryear's (and still-usable): reduce(operator.add, map(lambda x: x*x, roots)) "increases readability" compared to the proposed sum(x*x for x in roots) It boggles my mind to try thinking of the latter as "heavy and difficult to parse" compared to the former, to be honest. And when I'm thinking of "the sum of the squares of the roots", I DO find the direct expression of this as sum(x*x for x in roots) to be most immediate and obvious compared to spelling it out as total = 0 for x in roots: total = total + x*x which feels more like a series of detailed instructions on how to implement that "sum of squares", while the "sum(x*x"... DOES feel like the simplest way to say "sum of squares". > Sometimes it seems that introducing new syntax happens much easier > than improving or adding stdlib-modules. What a weird optical illusion, hm? In Python 2.3 *NO* new syntax was introduced (the EXISTING syntax for extended slices is now usable on more types, but that's not "introducing" any NEW syntax whatsoever), while HUNDREDS of changes were done that boil down to "improving or adding standard library modules". So, it's self-evidently obvious that the "happens much easier" perception is pure illusion. In 2.4, _some_ syntax novelties are likely to be allowed -- most PEPs under consideration are already in the PEP repository or will be there shortly, of course (e.g., syntax to support some variation of PEP 310, possibly closer to your own interesting experiments that you reported back in February). But once again there is absolutely no doubt that many more changes will be to standard library modules than will "introduce new syntax". > At least I hope that generator expressions will only be introduced > via a __future__ statement in Python 2.4 much like it happened with > 'yield' and generators. Maybe the PEP should have an "implementation > plan" chapter mentioning such details? I don't think __future__ has EVER been used for changes that do not introduce backwards incompatibilities, nor do I see why that excellent tradition should be broken for this PEP specifically. Alex From prouleau at impathnetworks.com Fri Oct 3 15:06:50 2003 From: prouleau at impathnetworks.com (Pierre Rouleau) Date: Fri, 03 Oct 2003 15:06:50 -0400 Subject: python 2.3.1 issues DeprecationWarning for FCNTL when importing tempfile In-Reply-To: References: Message-ID: <7Fjfb.6796$op2.764671@news20.bellglobal.com> > > It's curious that your Python executable is apparently in D:\dev\python\, > but that fcntl.py is getting loaded from c:\python23\lib\. Your setup may > be too complicated to understand . > I know that /dev is a bad name (in my case on Windows its the directory for development, not device). The but i have a set of pathon scripts under development. The PYTHONPATH environment variable is set to make sure that it looks into it. If i remove d:/dev/python from the PYTHONPATH and import tempfile i get the same results. C:\Python23\Lib>set PYTHONPATH= C:\Python23\Lib>python Python 2.3.1 (#47, Sep 23 2003, 23:47:32) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import tempfile fcntl.py:7: DeprecationWarning: the FCNTL module is deprecated; please use fcntl DeprecationWarning) >>> > >>... >>I am starting to wonder if the problem is caused by a package that was >>installed on one set of machines and not the other. > > > Do what you did above but add -vv to the command line, like so: > > python -vv > > Then "import tempfile" when a prompt finally appears. -vv sprays an > enormous amount of info to the screen about (among other things) the steps > Python takes to try to satisfy imports. I did that. Helped solve the problem: fcntl.pyc was present and that was causing the problem! Before deleting fcntl.pyc: python -vv .... .... >>> import tempfile # trying tempfile.pyd # trying tempfile.dll # trying tempfile.py # tempfile.pyc matches tempfile.py import tempfile # precompiled from tempfile.pyc import errno # builtin # trying random.pyd # trying random.dll # trying random.py # random.pyc matches random.py import random # precompiled from random.pyc import math # builtin import _random # builtin import time # builtin # trying fcntl.pyd # trying fcntl.dll # trying fcntl.py # trying fcntl.pyw # trying fcntl.pyc import fcntl # precompiled from fcntl.pyc fcntl.py:7: DeprecationWarning: the FCNTL module is deprecated; please use fcntl DeprecationWarning) import thread # builtin Then I deleted fcntl.pyc: C:\Python23\Lib>del fcntl.pyc C:\Python23\Lib>python Python 2.3.1 (#47, Sep 23 2003, 23:47:32) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import tempfile >>> The problem is SOLVED! ^^^^^^^^^^^^^^^^^^^^^^ Now, I looked at the C/Python23/Lib files before deleting fcntl.pyc and this is what i had: C:\Python23\Lib>lt -l [fF]*.py* -rwxrwxrwa 1 Administrators None 4709 Jan 21 2001 fpformat.py -rwxrwxrwa 1 Administrators None 418 May 9 2001 FCNTL.py -rwxrwxrwa 1 Administrators None 27589 Jun 3 2002 ftplib.py -rwxrwxrwa 1 Administrators None 12732 Jan 8 2003 fileinput.py -rwxrwxrwa 1 Administrators None 15548 Feb 27 2003 formatter.py -rwxrwxrwa 1 Administrators None 3126 Jul 13 18:06 fnmatch.py -rwxrwxrwa 1 Administrators None 10173 Sep 2 07:47 filecmp.py -rwxrwxrwa 1 Administrators None 3637 Sep 29 12:01 fnmatch.pyc -rwxrwxrwa 1 Administrators None 11652 Sep 29 12:01 filecmp.pyc -rwxrwxrwa 1 Administrators None 583 Sep 30 10:28 fcntl.pyc What is strange is that it seems that the import of FCNTL.py is case insensitive, where my system does not make it case insensitive (i dont have PYTHONCASEOK set). > > Also > > import sys > print sys.path > > C:\Python23\Lib>python Python 2.3.1 (#47, Sep 23 2003, 23:47:32) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> for theDir in sys.path: print theDir ... C:\WINNT\System32\python23.zip C:\Python23\lib\site-packages\Pythonwin C:\Python23\lib\site-packages\win32 C:\Python23\lib\site-packages\win32\lib C:\Python23\lib\site-packages c:\python23\DLLs c:\python23\lib c:\python23\lib\plat-win c:\python23\lib\lib-tk c:\python23 >>> So, the problem got solved by deleting the fcntl.pyc. I don't really understand why it solved the problem unless the .pyc was from an old version (however when i installed Python 2.3 and 2.3.1, I created a new directory). Tim and Michael, Thanks for your help! From bjorn.pettersen at comcast.net Fri Oct 24 05:11:18 2003 From: bjorn.pettersen at comcast.net (Bjorn Pettersen) Date: Fri, 24 Oct 2003 04:11:18 -0500 Subject: Why don't people like lisp? References: <3f9302d7.170372828@news.eircom.net> <3f96b046$0$556$b45e6eb0@senator-bedfellow.mit.edu> <20031022234546.GS1454@mapcar.org> <3f97eb1f$0$573$b45e6eb0@senator-bedfellow.mit.edu> <5627c6fa.0310230919.d2eb49a@posting.google.com> <3f9823b7$0$565$b45e6eb0@senator-bedfellow.mit.edu> <864qxz2if5.fsf@raw.grenland.fast.no> Message-ID: Raymond Wiker wrote in news:864qxz2if5.fsf at raw.grenland.fast.no: > "Rainer Deyke" writes: > >> Jon S. Anthony wrote: >>> Brian Kelley writes: >>>> Now the usage is: >>>> >>>> f = SafeFileWrapper(open(...)) >>>> print >> f, "A couple of lines" >>>> f.close() >>> ... >>>> I still have to explicitly close the file though when I am done >>>> with >>> >>> It's just this sort of monotonous (yet important) book keeping >>> (along with all the exception protection, etc.) that something like >>> with-open-file ensures for you. >> >> Personally I'd prefer guaranteed immediate destructors over >> with-open-file. More flexibility, less syntax, and it matches what >> the CPython implementation already does. > > Right... all along until CPython introduces a more elaborate > gc scheme. ... which is highly unlikely to happen without preservation of reference counting semantics for files... google if you're _really_ interested :-/ > Note that reference-counting has problems with cyclic > references; probably not something that will bite you in the case of > open files, but definitely a problem you need to be aware of. (a) true (by definition of cycle/ref.counting?) (b) no relevance to CPython (which uses a generational collector to reclaim reference cycles [with the regular finalizer problems]). (c) why are open file objects special (are you saying objects with no internal references are less likely to be reachable from a cycle, or that there is something intrinsically special about (open?) files)? -- bjorn From deets_noospaam at web.de Mon Oct 27 13:34:58 2003 From: deets_noospaam at web.de (Diez B. Roggisch) Date: Mon, 27 Oct 2003 19:34:58 +0100 Subject: which re a|l|t|e|r|n|a|t|i|v|e matched? References: Message-ID: > pat = reduce(lambda acc, key: "%s|(%s)" % (acc, key), d.keys())[1:] Oops, forgot the first argument for acc, its "" of course: pat = reduce(lambda acc, key: "%s|(%s)" % (acc, key), d.keys(), "")[1:] Diez From floyd at barrow.com Fri Oct 24 04:29:31 2003 From: floyd at barrow.com (Floyd Davidson) Date: Fri, 24 Oct 2003 00:29:31 -0800 Subject: [OT] Inuit? Eskimo? References: <20031020163642.GA5539@nl.linux.org> <4vre61-ku2.ln1@beastie.ix.netcom.com> <8765ii53yf.fld@barrow.com> <87wuaxymjz.fld@barrow.com> <3F970150.B48835B3@engcorp.com> <87k76wzy5b.fld@barrow.com> <3F971A95.C4C8B300@engcorp.com> <877k2wzk02.fld@barrow.com> <3F97B245.683BED86@engcorp.com> <87brs8xc84.fld@barrow.com> <3F986023.4EE284CD@engcorp.com> <87llrbwhrp.fld@barrow.com> <3F98876D.93279AFB@engcorp.com> Message-ID: <87ekx3vy1g.fld@barrow.com> Peter Hansen wrote: >Floyd Davidson wrote: >> >> Peter Hansen wrote: >> >Floyd Davidson wrote: >> >> >> >> In Canada and Greenland Inuit people will not appreciate the >> >> term "Eskimo" as a specific term for them when used by locals. >> >> That is particularly true of Canadians. They do not seem to >> >> mind the general (correct) use of the term by others who do not >> >> have any intent to insult them. >> > >> >Okay, thanks for taking the time to clarify, Floyd! >> > >> >The impression I get then is that because some people (although >> >I think more so in the distant past than in recent years?) >> >might hold ill will towards their northern neighbours, the >> >rest of us with nothing against them might as well avoid the >> >term Eskimo entirely, to minimize the risk of someone making false >> >assumptions about us and how we feel about them. >> >> That doesn't follow, logically, from the facts. No other word >> in the English language can be used in place of the term >> "Eskimo", and therefore if you want to correctly refer to the >> group of people known as Eskimos, you have no choice but to use >> that term. > >Hmm... I was unclear. I meant to refer only to the Inuit >living in Canada above. If it wasn't clear in the past, I'm >in Canada and all comments I've made apply only to the situation >in Canada. I can only respond to what you actually do say. I've never been able to read your mind, or anyone else's. You did *not* said a word about restricting your comments to Canada and Canadian users. When you address me about Eskimos, after I've made it clear as a bell from word one that I'm talking about Eskimos from Greenland to Siberia, it is absurd to suggest that I would know you are a Canadian or that I would know you are limiting your comments to the usage by Canadians. However, it is also true that the point doesn't change even then. Would you like me to find a list of appropriate uses of the term Eskimo by Canadians? The difference is just that in Canada you have a less frequent need for that term than we do in Alaska. But you still have occasion to use it. >> >> Note that in Canada and Greenland, *all* Eskimos are Inuit, >> >> hence there is little need to use that term to describe those >> >> people. >> > >> >Probably where the institutionalized advice comes from in the first >> >place. If all Eskimos in Canada are Inuit, and all Inuit can be >> >called Eskimos (but only by those who don't have intent to insult >> >them, apparently :-), then it's best to avoid the whole issue and >> >just use the term Inuit. >> >> But you *cannot* correctly call all Eskimos Inuit. > >Certainly not, as you've made clear. You've also made it clear >that "in Canada ..., all Eskimos are Inuit", and once again I The inverse is also true. In Canada, all Inuit are Eskimos. >point out that my only interest in this matter is in relation >to the situation in Canada, and the (what I called) institutionalized >advisory not to use the term Eskimo in relation to them. > >In light of this clarification, I think my comments do follow >logically from the facts as you've described them. I can't >tell whether the fact you keep confusing what I say results >from my poor way of expressing myself, or perhaps from your >certain knowledge that you know more than anyone living (or >at least anyone else present here) about this stuff, and that >therefore any comment from others containing the words Eskimo >or Inuit must surely therefore contain factual errors. I hope >it's just the former, and if so I apologize again. And I don't >intend to post here again, as I think I've understood you quite >well, even if it's not clear to you that I have. > >Cheers, >-Peter Sounds like you have an ego problem, not one of how to express it. I am _not_ sorry to have abused you with the facts though. -- Floyd L. Davidson Ukpeagvik (Barrow, Alaska) floyd at barrow.com From max at alcyone.com Sun Oct 26 01:47:09 2003 From: max at alcyone.com (Erik Max Francis) Date: Sat, 25 Oct 2003 23:47:09 -0700 Subject: Like a matrix References: Message-ID: <3F9B6DED.C1089FAB@alcyone.com> Yazar Yolait wrote: > I have a string of numbers in a file like so: > 0 3 23.3 352 45 4 > 4 45 23 54 4 5.4 .6 > > I need to average them horizontally and vertically. Horizontally is > easy > since I'm reading one line at a time, but how can I do it vertically > like 0 > and 4, 3 and 45, etc. Why not read it into a list of lists, and then iterate both ways? > I was thinking of a dictionary but how do you add entries to a > dictionary, > you can't can you? Sure you can: >>> d = {} >>> d[0] = 'zero' >>> d {0: 'zero'} >>> d[1] = 'one' >>> d {0: 'zero', 1: 'one'} >>> d[10] = {'a': 1, 'b': 2, 'c': 3} >>> d {0: 'zero', 1: 'one', 10: {'a': 1, 'c': 3, 'b': 2}} -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ The price of eternal vigilance is indifference. \__/ Marshall McLuhan From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Wed Oct 22 18:00:27 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Thu, 23 Oct 2003 00:00:27 +0200 Subject: ANN: Snakelets 1.5 (simple-to-use web app server with dynamic pages) Message-ID: <3f96fdfb$0$58698$e4fe514c@news.xs4all.nl> I'm happy to say that Snakelets 1.5 is now available. You can download it from http://snakelets.sourceforge.net (go to the SF project site, and then the file section). Changes since 1.4: - global URL prefix added - @inherit and @pagemethod for Ypages, incl. test/example - redirects/include with POST requests work - better page output encoding handling (escaping) - fixed specially encoded (UTF-8) form submits, added test/example - query args are parsed better Snakelets is a simple Python web application server. This project provides a threaded web server, Ypages (HTML+Python language, similar to Java's JSPs) and Snakelets: code-centric page request handlers (similar to Java's Servlets). Before you all rightfully scream "not another Python web server and HTML- language" let me say that Snakelet's focus is on understanding the way dynamic web sites are created (the code is very compact and easy to understand), and make this process as easy as possible. Snakelets is not meant to be a true platform to develop applications on (altough bugs and stability issues will be addressed ofcourse, and that is seems to be fast and stable as it is ;-) The download includes a few example web applications: - mp3 indexer and streamer - user login/account demo app - online shop - powerful server/webapp management tool to manage itself :-) To start, just start the 'serv.py' script. Snakelets is released under the open-source MIT Software license. --Irmen de Jong From rzantow at ntelos.net Thu Oct 23 20:46:06 2003 From: rzantow at ntelos.net (rzed) Date: Thu, 23 Oct 2003 20:46:06 -0400 Subject: PEP 289: Generator Expressions (please comment) References: <5d83790c.0310231158.65595858@posting.google.com> Message-ID: <1066956387.364126@cache1> "Raymond Hettinger" wrote in message news:5d83790c.0310231158.65595858 at posting.google.com... > Peter Norvig's creative thinking triggered renewed interest in PEP 289. > That led to a number of contributors helping to re-work the pep details > into a form that has been well received on the python-dev list: > > http://www.python.org/peps/pep-0289.html > > In brief, the PEP proposes a list comprehension style syntax for > creating fast, memory efficient generator expressions on the fly: > > sum(x*x for x in roots) > min(d.temperature()*9/5 + 32 for d in days) > Set(word.lower() for word in text.split() if len(word) < 5) > dict( (k, somefunc(k)) for k in keylist ) > dotproduct = sum(x*y for x,y in itertools.izip(xvec, yvec)) > bestplayer, bestscore = max( (p.score, p.name) for p in players ) > > Each of the above runs without creating a full list in memory, > which saves allocation time, conserves resources, and exploits > cache locality. > > The new form is highly expressive and greatly enhances the utility > of the many python functions and methods that accept iterable arguments. > I like it! How about in conjunction with the print statement? print "%s\n" % (s for s in strlist) ?? -- rzed From max at alcyone.com Tue Oct 21 23:15:03 2003 From: max at alcyone.com (Erik Max Francis) Date: Tue, 21 Oct 2003 20:15:03 -0700 Subject: ANN: fauxident 1.2.1 -- A simple, faked ident daemon Message-ID: <3F95F637.F6DD30F3@alcyone.com> Overview fauxident is a small Python script that will act as an extremely naive ident server, answering all ident requests with a consistent response -- either an ERROR or a USERID response. This can be advantageous on systems where running a true identd is unavailable, where it would be a security risk, or when masquerading firewalls are in use, where multiple machines are involved behind the firewall and running a proper ident system is not an option. Getting the software The current version of fauxident is 1.2.1. The latest version of the software is available in a tarball here: http://www.alcyone.com/software/fauxident/fauxident-latest.tar.gz. The official URL for this Web site is http://www.alcyone.com/software/fauxident/. Requirements fauxident requires Python 2.x or greater and a Unix or Unix-like operating system. License This code is released under the GPL. ... Release history [since 1.2] - 1.2.1; 2003 Oct 21. User name permuting was accidentally on by default; corrected missing -m entry in usage information. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ We're the stars on Earth \__/ Des'ree From Rigga at noemail.com Fri Oct 10 14:36:25 2003 From: Rigga at noemail.com (Rigga) Date: Fri, 10 Oct 2003 18:36:25 +0000 Subject: Newbie Needs help!! References: <6SAhb.831$gj2.684@news-binary.blueyonder.co.uk> <3f86ebd8$1@nntp0.pdx.net> Message-ID: Scott David Daniels wrote: > Bryano wrote: > > ... >> FileCon = InFile.read() > At this point you have read the entire file. >> FileLines = InFile.readline() > So there is nothing to read here. > -- Oh, I see, you expect readline() to return the line number. > It returns the next line in the file (which is empty). > > You need to count the lines yourself, if you want a count. > > -Scott David Daniels > Scott.Daniels at Acm.Org Thanks for your reply, I was under the misunderstanding that I could read the contents of the file and get the total number of lines the file contains in one go. Any pointers to how I can count the lines manually?? Regards From fumanchu at amor.org Tue Oct 28 18:30:16 2003 From: fumanchu at amor.org (Robert Brewer) Date: Tue, 28 Oct 2003 15:30:16 -0800 Subject: odbc and accessing database results by field Message-ID: If you already have separate code for MySQL and ODBC, you should consider accessing MS SQL Server via ADO instead of odbc. Check out: http://www.e-coli.net/pyado.html Interface to ADO via Mark Hammond's win32com.client module. This will give you a more direct, specific, and yes, more MS-approved interface to MS SQL Server. Once you run makepy on your version of ADO (read the docs), access can be as simple as: import win32com.client adOpenDynamic = 2 adLockOptimistic = 3 connection = win32com.client.Dispatch(r'ADODB.Connection') connection.Open("DSN=MSSQL13") anRS = win32com.client.Dispatch(r'ADODB.Recordset') anRS.Open("SELECT ID FROM Directory", connection, adOpenDynamic, adLockOptimistic) while not anRS.EOF: anID = anRS.Fields.Item(u'ID') do_something_with(anID) anRS.MoveNext() connection.Close() If you're using ODBC for both Win and Lin, I pity you. :) Robert Brewer MIS Amor Ministries fumanchu at amor.org > -----Original Message----- > From: JZ [mailto:jroznfgre at jngpugbjreXEBCXNbet.cy] > Sent: Tuesday, October 28, 2003 3:20 PM > To: python-list at python.org > Subject: Re: odbc and accessing database results by field > > > On Tue, 28 Oct 2003 13:57:05 -0800, "Robert Brewer" > wrote: > > >Does it have to be odbc? > > Have I a better choice? I am using MSSQL2000 and Win32 system. My > application works on MySQL/Linux RedHat, but it has to works under > MSSQL2000/Win32 as well. For Linux I use MySQLdb. For Win32 I use > odbc. > > -- > JZ ICQ:6712522 > -- > http://mail.python.org/mailman/listinfo/python-list > From tdelaney at avaya.com Tue Oct 28 23:39:07 2003 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Wed, 29 Oct 2003 15:39:07 +1100 Subject: Python slow for filter scripts Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DED6B32D@au3010avexu1.global.avaya.com> > From: Alex Martelli [mailto:aleax at aleax.it] > > What kind of files do your scripts most often process? For me, a > textfile of 4.4 MB is larger than typical. How much do those few > tens of milliseconds' difference matter? You know your apps, I > don't, but I _would_ find it rather strange if they "disqualified" > either language. Anything below about a second is typically fine > with me, so even the slowest of these programs could still handle > files of about 6 MB, assuming the 50% CPU it got is pretty typical, > while still taking no more than about 1 second's elapsed time. Personally, I used a python script the other day to process a 550MB text file. Total processing took about an hour. Note that this is not just a case of *copying* the file - there was some real serious processing going on there. It's a fairly unoptimised program, and peaked at about 800MB RAM. My work machine has the grunt to handle it, so there's no need to optimise the code further for now. Just doing a simple line-by-line copy of the same file, excluding some lines (keeping about 90%) which included a search in each line, took about 2-3 minutes. Tim Delaney From aleaxit at yahoo.com Sun Oct 12 13:06:52 2003 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 12 Oct 2003 17:06:52 GMT Subject: Python syntax in Lisp and Scheme References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> <6CZgb.3273$dn6.860@newsread4.news.pas.earthlink.net> <%hihb.4368$dn6.2921@newsread4.news.pas.earthlink.net> Message-ID: Andrew Dalke wrote: > Pascal Costanza: >> [quantum programming] > > While an interesting topic, it's something I'm not going to worry about. Me neither, for now. > And if I did, it would be in Python ;) I suspect no existing language would be anywhere near adequate. But if any current programming concept could stretch there, it might be that of "unrealized until looked-into set of things", as in, Haskell's "lazy" (nonstrict) lists. Now lists are sequential and thus quantumly inappropriate, but perhaps it's a start. > I bring it up as a counter-example to the idea that all modes of > programming have been and can be explored in a current Lisp. > I conjectured one interesting possibility -- that of handling ensembles > of possible solutions to a given problem. I suspect we may have to map the 'ensembles' down to sets of items, just as we generally map concurrency down to sets of sequential actions, in order to be able to reason about them (though I have no proof of that conjecture). IF you have to map more complicated intrinsics down to sequential, deterministic, univocal "things", I'm sure you could do worse than Lisp. As to whether that makes more sense than dreaming up completely different languages having (e.g.) nondeterminism or multivocity as more intrinsic concepts, I pass: it depends mostly on what human beings will find they need to use in order to reason most effectively in this new realm -- and quite likely different humans will find they have different needs in this matter. > In retrospect I should have given a more obvious possibility. > As some point I hope to have computer systems I can program > by voice in English, as in "House? Could you wake me up > at 7?" That is definitely a type of programming, but Lisp is Yeah, well, I fear the answer will be yes (it could), but it won't do so since you haven't _asked_ it to wake you up, only if it could. ME, I definitely don't want to use natural language with all of its ambiguity for anything exept communicating with other human beings, thankyouverymuch. > a language designed for text, not speed. *blink* what does THAT doubtful assertion have to do with anything else we were discussing just now...? I think lisp was designed for lists (as opposed to, say, snobol, which WAS "designed for text") and that they're a general enough data structure (and supplemented in today's lisps with other good data structures) that they'll be quite good for all kinds of 'normal' (deterministic &c) programming. As for speed, I'm sure it's easier to get it out of lisp than out of python right now. So what's your point, and its relation to the above...? > Pascal Costanza: >> I believe it is an accepted fact that uniformity in GUI design is a good >> thing because users don't need to learn arbitrarily different ways of >> using different programs. You only need different ways of interaction >> when a program actually requires it for its specific domain. Yes, I agree this IS generally accepted (with, of course, some dissenters, but in a minority). > My spreadsheet program looks different from my word processor Sure, so do mine, but their menus are quite similar -- in as much as it makes sense for them to have similar operations -- and ditto ditto for their toolbars, keyboard shortcuts, etc etc. I.e. the differences only come "when needed for a specific domain" just as Pascal just said. So I don't know what you're intending with this answer. > is more in common. Still, the phrase "practicality beats purity" is > seems appropriate here. Uniformity is more practical than diversity: e.g. ctrl-c as the Copy operation everywhere means my fingers, even more than my brain, get used to it. If you assign ctrl-c to some totally different operation in your gui app "because you think it's more practical" you're gonna drive me crazy, assuming I have to use your app. (That already happens to me with the -- gnome based i think -- programs using ctrl-z for minimize instead of undo -- I'm starting to have frayed nerves about that even for GVIM, one of the programs I use most often...:-). >> > I firmly believe people can in general easily handle much more >> > complicated syntax than Lisp has. There's plenty of room to >> > spare in people's heads for this subject. >> >> Sure, but is it worth it? > > Do you have any doubt to my answer? :) Given the difficulty I'm having understanding your stance[s] in this post, I do. My own answer would be that syntax sugar is in people's head anyway because of different contexts -- infix arithmetic taught since primary school, indentation in outlines and pseudocode, etc etc -- so, following that already-ingrained set of conventions takes no "room to spare in people's heads" -- indeed, the contrary -- it saves them effort. If people's head started as "tabula rasa" it might be different, but they don't, so that's a moot issue. That much being said, I _do_ like prefix syntax. In some cases I need to sum a+b+c+d and repeating that silly plus rather than writing (+ a b c d) grates. Or I need to check a> Convenience is what matters. If you are able to conveniently express >> solutions for hard problems, then you win. In the long run, it doesn't My APL experience tells me this is false: conveniently expressing solutions is HALF the problem -- you (and others!) have to be able to read them back and maintain and alter them later too. >> matter much how things behave in the background, only at first. > > Personally, I would love to write equations on a screen like I > would on paper, with integral signs, radicals, powers, etc. and > not have to change my notation to meet the limitations of computer > input systems. So jot your equations on a tablet-screen and look for a good enriched text recognition system. What's programming gotta do with it? > For Lisp is a language tuned to keyboard input and not the full > range of human expression. (As with speech.) Python even more so on the output side -- try getting a screen-reader to do a halfway decent job with it. But what does this matter here? > (I know, there are people who can write equations in TeX as > fast as they can on paper. But I'm talking about lazy ol' me > who wants the covenience.) > > Or, will there ever be a computer/robot combination I can > teach to dance? Will I do so in Lisp? You may want to teach by showing and having the computer infer more general rules from example. Whether the inference engine will be best built in lisp, prolog, ocaml, mozart, whatever, I dunno. I don't think it will be optimally done in Python, though. "Horses for courses" is my philosophy in programming. >> It seems to me that in Python, just as in most other languages, you >> always have to be aware that you are dealing with classes and objects. Given the "everything is an object" (classes included) and every object belongs to a class, you could indeed say that -- in much the same sense as you may be said to always be aware that you're breathing air in everyday life. Such awareness is typically very subconscious, of course. >> Why should one care? Why does the language force me to see that when it >> really doesn't contribute to the solution? I'm not sure in what sense "python forces you to see" that, e.g., the number 2 is an object -- or how can that fail to "contribute to the solution". Care to exemplify? > Hmmm.. Is the number '1' an object? Is a function an object? > What about a module? A list? A class? Yes to all of the above, in Python. I don't get your point. >>>> print sum(range(100)) > 4950 > > Where in that example are you aware that you are dealing with classes > and objects? Me? At every step -- I know 'sum' names a builtin object that is a function (belonging to the class of builtin functions) taking one argument which is a sequence, 'range' names another builtin object returning a list object, etc. I'm not directly dealing with any of their classes -- I know they belong to classes, like any object does, but I have no need to think about them in this specific statement (in fact, I hardly ever do; signature-based polymorphism is what I usually care about, not class membership, far more often than not). But I don't get your points -- neither Andrew's nor Pascal's. How does this differ from the awareness I might have in some macro-enhanced lisp where I would type (print (sum (range 100))) or the like? > conjecture is that additional syntax can make some things easier. > That a problem can be solved without new syntax does not > contradict my conjecture. But even if we provisionally concede your conjecture we are still left wondering: is the degree of easing so high that it overcomes the inevitable increase in complication, needed for a language to have N+1 syntax forms where previously it only had N? I.e., it's in general a difficult engineering tradeoff, like many in language design -- which is why I'd rather delegate the decisions on these tradeoffs to individuals, groups and processes with a proven track record for making a lot of them with complexive results that I find delightful, rather than disperse them to myself & many others (creating lots of not-quite-congruent language dialects). Alex From mcherm at mcherm.com Wed Oct 15 19:46:38 2003 From: mcherm at mcherm.com (Michael Chermside) Date: Wed, 15 Oct 2003 16:46:38 -0700 Subject: Express What, not How. Message-ID: <1066261598.3f8ddc5e4bb18@mcherm.com> gt5163b at prism.gatech.edu (Brian McNamara!) wrote previously: | nat :: Parser Int | nat = do {c <- digit; return charToInt c} | `chainl1` (return \x y -> 10*x+y) |If I understand you correctly, you would insist I write something like | nat :: Parser Int | nat = do {c <- digit; return charToInt c} | `chainl1` combineDigits | where combineDigits = return \x y -> 10*x+y David Mertz writes: > Even if looking through your library documentation to find the name > 'combineDigits' is the one used is extra work, it's much less work for > other programmers to read your definition of 'nat' if it uses a > descriptive name. (admittedly, for a silly and trivial function, the > difference is small; but I think the stipulation applies that > 'combineDigits' is a proxy in the discussion for a more complex > real-world function). No, I think that what Brian was saying was that in this exact case, naming a function like combineDigits is worse than useless. It forces the programmer to memorize the name. To me, I find the string "\x y -> 10*x+y" to be MORE readable than the string "combineDigits". Admitedly, it is one character longer, but unlike "combineDigits", it states CLEARLY and UNAMBIGUOUSLY exactly what is being done. If you had a complex 5-line function, then I would prefer the name every time. But sometimes a thing is so simple that it's EASIER to write it out. Hmm... what's another example? We laud a language like Python for having only a few simple constructs (one branch statement, two kinds of loops, assignments, function and class definitions, plus a few others) which are combined to create any program imaginable. If there were 20 different kinds of loops instead of 2, it would not make the language more expressive, or more readable... it would probably be LESS readable. There would just be too much unnecessary vocabulary to keep track of. Similarly, when defining a program, it's important to maintain the proper level of abstraction. Sometimes, it's better to write out a function anonymously if it's (1) has limited or no re-use value, (2) does not represent an important concept which needs to be identified, and (3) is short enough to be groked as a unit. -- Michael Chermside From mertz at gnosis.cx Thu Oct 16 00:14:58 2003 From: mertz at gnosis.cx (David Mertz) Date: Thu, 16 Oct 2003 00:14:58 -0400 Subject: Python syntax in Lisp and Scheme References: <3cea3gqq.fsf@comcast.net> <87ekxfmhhl.fsf@thalassa.informatimago.com> <1cucnY9twevVdxGiU-KYhA@comcast.com> <1eaf81aa.0310150533.265145b9@posting.google.com> <8765iplt91.fsf@thalassa.informatimago.com> Message-ID: |> Here's a quick rule that is pretty damn close to categorically true for |> Python programming: If you use more than five levels of indent, you are |> coding badly. Something is in desperate need of refactoring. Pascal Bourguignon wrote previously: |Here is an histogram of the depths of the top level sexps found in my |emacs sources: |((1 . 325) (2 . 329) (3 . 231) (4 . 163) (5 . 138) (6 . 158) (7 . 102) | (8 . 94) (9 . 63) (10 . 40) (11 . 16) (12 . 20) (13 . 9) (14 . 4) | (15 . 5) (16 . 4) (17 . 2) (19 . 2) (23 . 1)) |Am I depraved in writting code with depths down to 23? As I've written lots of times in these threads, I haven't really used Lisp. In fact, I really only did my first programming in Scheme (for an article on SSAX) in the last couple weeks; I know Scheme isn't Common Lisp, no need to point that out again. However, I -have- read a fair number of snippets of Lisp code over the years, so my familiarity runs slightly deeper than the couple weeks. All that said, my gut feeling is that depth 23 is, indeed, ill-designed. Even the more common occurrences of 12 or 13 levels seems like a lot more than my brain can reason about. I'm happy to stipulate that Bourguignon is smarter than I am... but I'm still confident that I can do this sort of thinking better than 95% of the people who might have to READ his code. And the purpose of code, after all, is to COMMUNICATE ideas: firstly to other people, and only secondly to machines. |Ok, in Python, you may have also expressions that will further deepen |the tree, but how can you justify an artificial segregation between |indentation and sub-expressions? Because it's Python! There is a fundamental syntactic distinction between statments and expressions, and statements introduce blocks (inside suites, bare expressions can occur though--usually functions called for their side effects). It is the belief of the BDFL--and of the large majority of programmers who use Python--that a syntactic distinction between blocks with relative indention and experessions that nest using parens and commas AIDS READABILITY. I can say experientially, and from reading and talking to other Pythonistas, that my brain does a little flip when it finishes identifying a suite, then starts identifying the parts of an expression. And conveniently, in Python, the sort of thinking I need to do when I read or write the lines of a suite is a bit different than for the parts of an expression. Not just because I am deceived by the syntax, but because the language really does arrange for a different sort of thing to go on in statements versus expressions (obviously, there are SOME overlaps and equivalences; but there's still a useful pattern to the distinction). Still, for a real comparison of depth, I suppose I'd need to look at the combined depth of indent+paren-nesting. Even for that, well-designed Python programs top out at 7 or 8, IMO. Maybe something a little deeper reasonably occurs occassionally, but the histogram would sure look different from Pascal's ("Flat is better than nested"). Yours, David... -- ---[ to our friends at TLAs (spread the word) ]-------------------------- Iran nuclear neocon POTUS patriot Pakistan weaponized uranium invasion UN smallpox Gitmo Castro Tikrit armed revolution Carnivore al-Qaeda sarin ---[ Gnosis Software ("We know stuff") ]--------------- From mcfletch at rogers.com Mon Oct 13 17:35:47 2003 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Mon, 13 Oct 2003 17:35:47 -0400 Subject: Speaking Python In-Reply-To: References: Message-ID: <3F8B1AB3.20304@rogers.com> David Mertz wrote: >In the endless Lisp/macro threads, Alex Martelli mentioned something a >bit interesting about screen-reading applications. Specifically, he >expressed reservations about whether Python would be a good language for >visually impaired or blind programmers. > >The concern, I think, is that pronouncing >'space-space-space-space-space-space-space-space' isn't all that easy to >follow if spoken with every line. Even a reduced form like >"eight-spaces' isn't perfect either. Actually, a symmetric concern is >with voice recognition applications--perhaps for people with motor >disabilities. > > True, which is why we use for indents religiously, right ;) . There's at least a few of us who use voice dictation for writing Python, and on those rare instances where the editor doesn't automatically indent for me, saying "tab" is quite doable. >My feeling is that a good vocal Python programming editor would need to >know a bit about the structure of the language. > This is definitely true. A "good" vocal editor is a ways off still, likely. >Maybe to a greater >degree than would one with explicit delimiters (although I have trouble >imagining blind programmers being all that happy with hearing >'close-paren-close-paren-close-paren-close-paren-close-paren-close-paren' >either). > I'd have a similar imagining... > Perhaps this same hypothetical editor would speak code and >recognize spoken code using the same format. > > That's a good first level, for very precise debugging. If you want to make the thing comfortable for reading blocks of text, however, you'll want to include a mode (really, dozens of graduated modes) where landmarks are included in the spoken text, preferably without breaking up the textual stream, more below on this... >So quick test, how do you say: > > def range_sum(N): > > "py-def range underscore sum open-paren number close-paren colon new-line" I don't use single-character variable names because they're more pain to dictate than regular English words. The editor (Pythonwin) indents automatically, so I never actually say the tab-keys below, instead what I say is "backspace" to dedent from where Pythonwin sets the indentation (which only needs to occur once in the entire function here, as Pythonwin auto-dedents for returns) but since we're worried about the dictation. What I'd prefer to say is: "function range sum, parameter number, new-line" but that's not happening today :) . > if N < 0: > > "tab-key if number less-than zero colon new-line" > return None > > "tab-key tab-key return cap None new-line" > elif N == 1: > > "tab-key elif number py-equal one colon new-line" > return 1 > > "tab-key tab-key return one new-line" > else: > > "tab-key else colon new-line" > tot = 0 > > "tab-key tab-key total equal-sign zero new-line" > for n in range(1,N+1): > > "tab-key tab-key for counter in range open-paren one comma number plus-sign one close-parent colon new-line" > tot += n > > "tab-key tab-key tab-key total plus-sign equal-sign counter new-line" > return tot > > "tab-key tab-key return total new-line" The thing is, you wouldn't want that being spat back at you if you couldn't *see* the code and wanted to know what a function does, that's how you dictate it, but it's only useful for very low-level debugging to *hear* it that way. What you'd want is something like: c> function range sum u> read that c> deaf range sum number colon if number less-than zero colon return None ... where each < > item is a configurable sound-effect, likely with different levels of abbreviation, so that at the slowest (most careful) reading you'd hear "open paren", while at the most cursory reading level you'd hear a very short sound-effect that bracketed the words in the parenthesis. Of course, it would be nice if you could change the tonality of the voice as well (as humans do when reading parenthesised text), but you'd need to be able to handle something like this: [ (a.this.them.there(), c.those()) for (a,c) in somewhat.items() ] without the voice turning into a squeak :) . Thing is, that even that level still leaves you unable to enjoy most of the benefits of Python code (which, really, is a visual thing, letting you pick out features so easily from the representation of the text). You'd want even more subtle audio clues to do that, whispers in the background of the voice giving context e.g. for ifs and elifs, and for current indentation levels (really you'd want it naming a suite and using that), you'd want the system to properly describe the open and close of a parameter list (versus tuple start/end), to point out where there are unmatched braces, to generally act as your eyes in interpreting the text. You'd need summary "views" for finding/skimming the text, auditory bookmarks and conversational interfaces for defining focus... More abstractly, you want to increase the bandwidth of the audio channel so that, as an HCI mechanism, it more closely approximates the richness of the WIMP video channel. That's going to require fairly sophisticated control mechanisms for interacting with the system and altering it's attempts to present the information. Of course, I'd guess most blind programmers are *very* good at keeping large blocks of text in their head (given current levels of support in editors), so they may not want all that at all, a simple "indent" and "dedent" might be fine... at least as good as with any of the curly-braced languages... seems to me that delimiter/no-delimiter is a comparatively minor question once you start wanting to provide a useful system. It's a wonderfully complex HCI design challenge, and comparatively, hooking up a Python parser is probably a no-brainer. $0.02 CDN, Mike _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From crescent_au at yahoo.com Tue Oct 14 21:34:42 2003 From: crescent_au at yahoo.com (Ben) Date: 14 Oct 2003 18:34:42 -0700 Subject: assigning values to array element Message-ID: Hi all, This may sound easy but I'm having trouble assigning values to array element. My problem is as follows: m = ['Peter', 'Sam', 'Dave', 'Carl'] for o in m: # Here first o is 'Peter'.. I want to do something like this: Peter = 10 # if i do %s %o = 10, it gives me error... How can I do it? Thanks Ben From carljohan.rehn at chello.se Sun Oct 12 12:31:55 2003 From: carljohan.rehn at chello.se (carljohan.rehn at chello.se) Date: Sun, 12 Oct 2003 18:31:55 +0200 Subject: Tkinter, wxPython, PyGtk, or PyQt... Message-ID: I would like like to start doing some GUI-programming in Python, but don't know which library to choose. Tkinter seems a bit old. Correct me if I am wrong! The layout doesn't look as nice as for the others. wxPython seems to be the first-hand choice for people doing W32-programming (with MFC-experience). PyGtk seems to be a modern, very clean and nice approach, but with poor W32-support. Is PyGtk a mature library with respect to version stability and documentation. PyQt is a huge library (thanks to Qt), but not free on W32, or? Is there any possibility that any of the above-mentioned libraries will be included as a standard library in any of the near-future Python distributions? I myself program on W32 at work, but use Linux at home. So, which one should I start with in order to reduce the effort of learning something new and to be productive in the shortest time possible? By the way, how do I most easily include plotting capabilities to my Python-apps? Carl From nigel_sim at yahoo.com Tue Oct 7 10:21:21 2003 From: nigel_sim at yahoo.com (Nigel) Date: Wed, 08 Oct 2003 00:21:21 +1000 Subject: python-gnome2 panel applet Message-ID: Hi, I'm after a sample python program which is a gnome2 panel app. I've looked at the example applet which comes with the python-gnome2 package, but I don't understand how to launch it into the panel. It doesn't show up in the "add to panel" menu and it has no methods to invoke. I've also searched for docs on this to no avail. Once again any assistance would be most appreciated. regards nigel. From costanza at web.de Thu Oct 9 09:59:24 2003 From: costanza at web.de (Pascal Costanza) Date: Thu, 09 Oct 2003 15:59:24 +0200 Subject: Python syntax in Lisp and Scheme In-Reply-To: <3F854DCC.1030900@ps.uni-sb.de> References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> <92c59a2c.0310031345.57d20631@posting.google.com> <3F82EF06.F3D7A10@setf.de> <3F83FA7C.4030400@ps.uni-sb.de> <5mfd51-lu3.ln1@ID-7776.user.dfncis.de> <3F854DCC.1030900@ps.uni-sb.de> Message-ID: Andreas Rossberg wrote: > Dirk Thierbach wrote: > >> >>>> you can use macros to do everything one could use HOFs for (if you >>>> really want). >> >> >> I should have added: As long as it should execute at compile time, of >> course. >> >>> Really? What about arbitrary recursion? >> >> >> I don't see the problem. Maybe you have an example? I am sure the >> Lisp'ers here can come up with a macro solution for it. > > > I'm not terribly familiar with the details of Lisp macros but since > recursion can easily lead to non-termination you certainly need tight > restrictions on recursion among macros in order to ensure termination of > macro substitution, don't you? Or at least some ad-hoc depth limitation. The Lisp mindset is not to solve problems that you don't have. If your code has a bug then you need to debug it. Lisp development environments provide excellent debugging capabilities out of the box. Don't guess how hard it is when you don't have the experience yet. Pascal -- Pascal Costanza University of Bonn mailto:costanza at web.de Institute of Computer Science III http://www.pascalcostanza.de R?merstr. 164, D-53117 Bonn (Germany) From christian.lynbech at ericsson.com Fri Oct 10 07:26:56 2003 From: christian.lynbech at ericsson.com (Christian Lynbech) Date: Fri, 10 Oct 2003 13:26:56 +0200 Subject: Cross-posting is good References: Message-ID: >>>>> "mike420" == mike420 writes: mike420> C is inherently insecure Surely we can agree on this being a fact. ;-) ------------------------+----------------------------------------------------- Christian Lynbech | christian #\@ defun #\. dk ------------------------+----------------------------------------------------- Hit the philistines three times over the head with the Elisp reference manual. - petonic at hal.com (Michael A. Petonic) From http Sat Oct 18 09:38:06 2003 From: http (Paul Rubin) Date: 18 Oct 2003 06:38:06 -0700 Subject: prePEP: Money data type References: Message-ID: <7xbrse3bup.fsf@ruckus.brouhaha.com> Alex Martelli writes: > > 1. I've seen lots of strange rounding policies in various nooks > > and crannies. Is there any way of specifying a rounding policy > > that would be used and inherited by the result money object? > > Amen, Hallelujah. I've followed up to Batista's similar post to > python-dev by pointing out chapter and verse of EU regulations that > _mandate_ "rounding to nearest and always round exactly-halfway > UPWARDS", for example. Are you serious about this? I thought financial computations with decimal arithmetic had been done in Cobol since the 1950's. They haven't gotten this stuff figured out by now? Can you crunch some calculation through a Cobol program and get an answer thtat's correct in the US and wrong in the EU? From fgeiger at datec.at Tue Oct 21 01:55:50 2003 From: fgeiger at datec.at (F. GEIGER) Date: Tue, 21 Oct 2003 07:55:50 +0200 Subject: wxPython: Notebook page content disappears when ntb. event defined References: Message-ID: <3f94ca72@news.swissonline.ch> "Martin Zuber" schrieb im Newsbeitrag news:bn2fhh$12jr$1 at news.nextra.cz... > Hello, > > I have found following problem: When I define event handler for > EVT_NOTEBOOK_PAGE_CHANGED for wxNotebook, the content of the wxNotebook > disappears (on all pages). For ex. I have two pages - one with some > wxTextCtrls, second with some wxGrid. > > The dialog has been created using the Boa Constructor (0.2.3 and 0.2.7). > I have two files: > - SomeDialog.py - there is only look and events defined (we can say it > is something like interface, but it defines look), so there is: > > def OnNotebook1NotebookPageChanged(self, event): > event.Skip() > > > - SomeDialog_Impl.py - here is my code, separated from the dialog look > and events > > def OnNotebook1NotebookPageChanged(self, event): > doSomeMethod1() > doSomeMethod2() > doSomeMethod3() > > I use Python 2.2 and wxWindows 2.4.2.4 on MS Windows (non Unicode wxPython) > > Any idea? > > Martin > That's not just an interface, the event.Skip() is necessary: def OnNotebook1NotebookPageChanged(self, event): doSomeMethod1() doSomeMethod2() doSomeMethod3() event.Skip() Regards Franz GEIGER From wilkSPAM at OUTflibuste.net Sun Oct 5 15:32:54 2003 From: wilkSPAM at OUTflibuste.net (Wilk) Date: Sun, 05 Oct 2003 21:32:54 +0200 Subject: SpamAssassin in Python? References: Message-ID: <87ad8fv5sp.fsf@blakie.riol#flibuste.net> Roman Suzi writes: > Is there SpamAssassin-like app (well, maybe just rule-based > part of it) written in Python? I do not need any fancities > just liked to know if it will be faster than Perl version. http://spambayes.sourceforge.net/ -- William Dode - http://flibuste.net From tom_evans_a at uk.co.yahoo.reverse Tue Oct 28 07:16:58 2003 From: tom_evans_a at uk.co.yahoo.reverse (Tom Evans) Date: Tue, 28 Oct 2003 12:16:58 +0000 Subject: Pythonic Abstract Base Class / Interface Message-ID: <3F9E5E3A.A0643CC6@eng.cam.ac.uk> My basic question: If I have a specific interface which I know is going to be implemented by a number of classes, but there is no implementation commonality between them, what is the preferred form for this in Python? In a staticly typed language like c++ or java, I'd describe the interface first, then create the classes eithered derived from that ABC or implementing that interface (same thing really). This was the first thing I thought to do in python, but then rapidly realised I didn't actually need to write anything in the base class - as long as code using one of the implemented classes just tries to do things with it it would just work. In fact, I didn't even need to make a base class at all if the calling code never checks for type (as seems normal). So, as I see it I could: a) create a base class with stubs for all the interface and derive from that. b) create an empty base class and derive from that. c) just make the concrete classes directly with no inheritance commonality. Is there a clear pythonic way, or does it depend a bit more on the design of the specific program? Tom From joachim.durchholz at web.de Sat Oct 25 16:58:12 2003 From: joachim.durchholz at web.de (Joachim Durchholz) Date: Sat, 25 Oct 2003 22:58:12 +0200 Subject: Python from Wise Guy's Viewpoint In-Reply-To: References: <_8Ekb.7543$pT1.318@twister.nyc.rr.com> <3f972315$1@news.unimelb.edu.au> <3638acfd.0310230039.306b14f@posting.google.com> <3638acfd.0310232246.64fa09ed@posting.google.com> <65fn61-b61.ln1@ID-7776.user.dfncis.de> Message-ID: prunesquallor at comcast.net wrote: > Are they happy with something like this? > > (defun black-hole (x) > #'black-hole) > > (for non lispers, the funny #' is a namespace operator. > The black-hole function gobbles an argument and returns > the black-hole function.) Now *that* is a real challenge, and Haskell indeed doesn't allow this (it says "black_hole has an infinite type", which is not a surprise: the literal transliteration of the above function would be black_hole _ = black_hole and the only solution to the above equation would require that black_hole has a countably infinite number of _ parameters). However, what purpose would the function serve? I'm pretty sure that there's an equivalent idiom in Haskell, but I can't tell unless I know what black_hole is good for. Regards, Jo From eppstein at ics.uci.edu Tue Oct 21 23:33:23 2003 From: eppstein at ics.uci.edu (David Eppstein) Date: Tue, 21 Oct 2003 20:33:23 -0700 Subject: Science is a human activity (was: Python syntax in Lisp and Scheme) References: <3yGhb.197125$hE5.6672583@news1.tin.it> <1jclovopokeogrdajo6dfmhm090cdllfki@4ax.com> Message-ID: In article <1jclovopokeogrdajo6dfmhm090cdllfki at 4ax.com>, Michele Dondi wrote: > >It's certainly true that mathematicians do not _write_ > >proofs in formal languages. But all the proofs that I'm > >aware of _could_ be formalized quite easily. Are you > >aware of any counterexamples to this? Things that > >mathematicians accept as correct proofs which are > >not clearly formalizable in, say, ZFC? > > I am not claiming that it is a counterexample, but I've always met > with some difficulties imagining how the usual proof of Euler's > theorem about the number of corners, sides and faces of a polihedron > (correct terminology, BTW?) could be formalized. Also, however that > could be done, I feel an unsatisfactory feeling about how complex it > would be if compared to the conceptual simplicity of the proof itself. Which one do you think is the usual proof? http://www.ics.uci.edu/~eppstein/junkyard/euler/ Anyway, this exact example was the basis for a whole book about what is involved in going from informal proof idea to formal proof: http://www.ics.uci.edu/~eppstein/junkyard/euler/refs.html#Lak -- David Eppstein http://www.ics.uci.edu/~eppstein/ Univ. of California, Irvine, School of Information & Computer Science From francisgavila at yahoo.com Wed Oct 22 20:25:48 2003 From: francisgavila at yahoo.com (Francis Avila) Date: Wed, 22 Oct 2003 20:25:48 -0400 Subject: regexp search question References: <7xsmlk97pt.fsf_-_@ruckus.brouhaha.com> Message-ID: "Francis Avila" wrote in message news:vpe7egpsru87b at corp.supernews.com... > > Alternative 3: > You could probably combine p and q into a single regexp specifying that you > match p, then q, with anything inbetween. Using groups (p is grp 1, q is > grp 2), get your offset with matchpq.end(1) + matchpq.start(2) Gah, that's wrong: the offset of q will be in matchpq.start(2). -- Francis Avila From merman at snafu.de Wed Oct 15 09:57:38 2003 From: merman at snafu.de (T. Kaufmann) Date: Wed, 15 Oct 2003 15:57:38 +0200 Subject: question: documentation systems Message-ID: <3F8D5252.5080804@snafu.de> Hi, I'm looking for a Python documentation system (but not happydoc). I know *doxygen* for C++ - is there for Python a similar solution? Thanks for help. o-o Thomas From madhobbit at geocities.com Thu Oct 9 10:39:29 2003 From: madhobbit at geocities.com (Darryl) Date: 9 Oct 2003 07:39:29 -0700 Subject: Embedding Python in Python References: Message-ID: JCM wrote in message news:... > (...) What we did was parse the users' code > (take a look at the compiler module) and statically analyze it for > anything "dangerous". Ugh...I had considered this approach but was hoping I didn't have to do it :) I've only been hacking Python for a couple weeks, so I don't know all the ins and outs of what I'd need to watch for...in my experience, most languages seem to have obscure ways of doing things that you wouldn't think of normally, and Python seems no exception. >From a more pragmatic perspective though, this is just a toy project, so it's not too important if I miss something. > (...) anything of the form __ident__ Now that's an interesting idea...from what I've seen of Python, that should catch most of the really obscure ways of doing things. I haven't looked, but I can only assume that Python has regexp matching in it somewhere, so some of the simple checks should be only a few lines of code. A blacklist of keywords seems like a good first start (it's a fairly restrictive context, so even common things like def and lambda can probably be blocked). I also just tested and noticed that syntax errors seem to be thrown as exceptions (rather than causing the interpreter to gasp and die), so I shouldn't have to worry about a badly-written script crashing the whole app. Thanks for the input, - Darryl From km-news2 at onlinehome.de Thu Oct 2 11:05:49 2003 From: km-news2 at onlinehome.de (Klaus-G. Meyer) Date: Thu, 02 Oct 2003 17:05:49 +0200 Subject: Where are "What's new" for 2.0, 2.1? References: Message-ID: > The docs for 2.2 and 2.3 contain a "What's new" section. > > Are there any such sections for 2.0 and 2.1? If so, where are they? http://www.amk.ca/python/ Gru? - regards Klaus :-) From dthierbach at gmx.de Fri Oct 24 13:46:54 2003 From: dthierbach at gmx.de (Dirk Thierbach) Date: Fri, 24 Oct 2003 19:46:54 +0200 Subject: Static typing References: <90fk61-j71.ln1@ID-7776.user.dfncis.de> Message-ID: Pascal Costanza wrote: >> I don't have pattern matching to use them efficiently, > http://www.cliki.net/fare-matcher Certainly an improvement, but no way to declare datatypes (i.e., pattern constructors) yet: There also needs be improvements to the infrastructure to build pattern constructors, so that you may build pattern constructors and destructors at the same time (much like you do when you define ML types). The following might also be a show-stopper (I didn't test it, but it doesn't look good): ; FIXME: several branches of an "or" pattern can't share variables; ; variables from all branches are visible in guards and in the body, ; and previous branches may have bound variables before failing. ; This is rather bad. The following comment is also interesting: Nobody reported using the matcher -- ML/Erlang style pattern matching seemingly isn't popular with LISP hackers. Again, the way to get the benefits of "more expressive languages" like ML in Lisp seems to be to implement part of them on top of Lisp :-) >> and there is no automatic test generation (i.e., type checking) for >> my datatypes. > http://www.plt-scheme.org/software/mrflow/ I couldn't find any details on this page (it says "coming soon"), but the name suggest a dataflow analyzer. As I have already said, the problem with attaching static typing and inference to an arbitrary language is that it is difficult to get it working without changing the language design. Pure functional features make type inference easy, imperative features make them hard. Full dataflow analysis might help, but I'd have to look more closely to see if it works out. - Dirk From aleax at aleax.it Sat Oct 4 15:48:54 2003 From: aleax at aleax.it (Alex Martelli) Date: Sat, 04 Oct 2003 19:48:54 GMT Subject: Python syntax in Lisp and Scheme References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> <92c59a2c.0310031345.57d20631@posting.google.com> <8b9e2260.0310032317.72abd86a@posting.google.com> <8b9e2260.0310040524.229dfd9f@posting.google.com> Message-ID: Bengt Richter wrote: ... > I like the Bunch class, but the name suggests vegetables to me ;-) Well, I _like_ vegetables... > BTW, care to comment on a couple of close variants of Bunch with > per-object class dicts? ... > > def mkNSC(**kwds): return type('NSC', (), kwds)() Very nice (apart from the yecchy name;-). > or, stretching the one line a bit to use the instance dict, > > def mkNSO(**kwds): o=type('NSO', (), {})(); o.__dict__.update(kwds); > return o I don't see the advantage of explicity using an empty dict and then updating it with kwds, vs using kwds directly. > I'm wondering how much space is actually wasted with a throwaway class. Is > there a lazy copy-on-write kind of optimization for class and instance > dicts that prevents useless proliferation? I.e., I strongly doubt there's any "lazy copy-on-write" anywhere in Python. The "throwaway class" will be its dict (which, here, you need -- that's the NS you're wrapping, after all) plus a little bit (several dozen bytes for the typeobject, I'd imagine); an instance of Bunch, probably a bit smaller. But if you're going to throw either away soon, who cares? >>but I think the "purer" (more extreme) versions are >>interesting "tipizations" for the languages, anyway. >> > Oh goody, a new word (for me ;-). Would you define "tipization"? I thought I was making up a word, and slipped by spelling it as in Italiano "tipo" rather than English "type". It appears (from Google) that "typization" IS an existing word (sometimes mis-spelled as "tipization"), roughly in the meaning I intended ("characterization of types") -- though such a high proportion of the research papers, institutes, etc, using "typization", seems to come from Slavic or Baltic countries, that I _am_ left wondering...;-). Alex From francisgavila at yahoo.com Tue Oct 28 07:07:43 2003 From: francisgavila at yahoo.com (Francis Avila) Date: Tue, 28 Oct 2003 07:07:43 -0500 Subject: itertools.flatten()? and copying generators/iterators. References: Message-ID: "Alex Martelli" wrote in message news:Tesnb.57573$e5.2124916 at news1.tin.it... > Peter Otten wrote: > ... > > def keepstrings(seq): > > if isinstance(seq, basestring): > > raise TypeError > > return iter(seq) > ... > > The above handles strings in a way that is nonintrusive on client code. > > Yes, very nice. I'd make keepstrings the default (one RARELY wants > to treat strings as nonatomic) AND replace the typetest with an > attempt to do a seq+'' (if it doesn't raise, seq ain't a string), > but that's just me:-). > > Alex > try: seq+'' seems more expensive. Is it just to handle the case where someone makes a string-alike that doesn't derive from str? (Actually, I guess that's about all pre-2.2 code.) Is it expensive enough to even matter? -- Francis Avila From llafba_NOSPAM_ at gmx.net Tue Oct 28 11:56:49 2003 From: llafba_NOSPAM_ at gmx.net (Chris) Date: Tue, 28 Oct 2003 17:56:49 +0100 Subject: manipulate string Message-ID: I heard that strings are immutable, but isn't there regardless a way to manipulate a string? I have a string that looks like this: a = '0123456789' But I want it to look like this: a = '0 - 2 - 4 - 6 - 8 - ' I want whitespace between every number and I want to fade out every second number. It is funny that I can explicitly read parts of that string, print a[3] works perfectly, but I can't remove it, delete it or what ever. I would appreciate any hint on how to solve my little "problem". Thanks a lot. Regards, Tom From BjornPettersen at fairisaac.com Sat Oct 4 21:04:33 2003 From: BjornPettersen at fairisaac.com (Pettersen, Bjorn S) Date: Sat, 4 Oct 2003 20:04:33 -0500 Subject: How do I display unicode-paths? Message-ID: <1DAECE9E8F34E04AA0E5699AF7D9FF090801BC7D@stpmsg00.corp.fairisaac.com> I've been trying to stay blissfully unaware of Unicode, however now it seems like it's my turn. From the outside it seems like a rather massive subject, so any pointers as to where I should _start_ reading would be appreciated. The usecase is a class: class path(object): ... def __str__(self): return self.pathstr.encode(???) the question is what to put at ??? to be most useful to programmers/end users? Background: I've got a directory with a file called 'b?', B-AE, (which everyone knows is what Norwegian sheep say :-). If I type u'b?' at the Python command prompt, it returns: u'b\x91' (WinXP, 2.3.2, regular command window). With a little trial and error I found: >>> print u'b\x91'.encode('latin1') b? although >>> print u'b\x91' Traceback (most recent call last): File "", line 1, in ? File "e:\python23\lib\encodings\cp437.py", line 18, in encode return codecs.charmap_encode(input,errors,encoding_map) UnicodeEncodeError: 'charmap' codec can't encode character '\u91' in position 1: character maps to not sure I'm understanding this, and when I call: os.listdir(os.getcwdu()) I get back u'b\xe6' which isn't making much sense either... help?! -- bjorn From richardshea at fastmail.fm Tue Oct 14 19:10:39 2003 From: richardshea at fastmail.fm (Richard Shea) Date: 14 Oct 2003 16:10:39 -0700 Subject: Simple Question : files and URLLIB References: <282f826a.0310140203.d890865@posting.google.com> Message-ID: <282f826a.0310141510.5212aa16@posting.google.com> Thanks to everyone for the info/feedback. In particular I didn't know you could that ... type(finA) ... business (which shows you how new to Python I am probably) but it'll come in handy. As I think you realised I had misunderstood exactly what urllib was offering however the blah.read() approach is quite good enough. Just out of curiousity though if 'tidy' demanded a file (rather than being prepared to take a string as it is)would the only sure approach be to ... f1=open('C:\\workfile.html','w') strHTML= urllib.urlopen('http://www.python.org/').read() f1.write(strHTML) tidy(f1,strOut,None) ... that is to take the string that results from the read on urllib file-like object and write it back out to a file ? Just wondering ... Thanks again for the information on my original question. regards richard. richardshea at fastmail.fm (Richard Shea) wrote in message news:<282f826a.0310140203.d890865 at posting.google.com>... > Hi - I'm new to Python. I've been trying to use URLLIB and the 'tidy' > function (part of the mx.tidy package). There's one thing I'm having > real difficulties understanding. When I did this ... > > finA= urllib.urlopen('http://www.python.org/') > foutA=open('C:\\testout.html','w') > tidy(finA,foutA,None) > > I get ... > > Traceback (most recent call last): > File "", line 1, in ? > File "mx\Tidy\Tidy.py", line 38, in tidy > return mxTidy.tidy(input, output, errors, kws) > TypeError: inputstream must be a file object or string > > ... what I don't understand is surely the result of a urllib is a file > object ? Isn't it ? To quote the manual at : > > http://www.python.org/doc/current/lib/module-urllib.html > > "If all went well, a file-like object is returned". I can make the > tidy function happy but changing the code to read ... > > finA= urllib.urlopen('http://www.python.org/').read() > > ... I haven't had time to look into this properly yet but I suspect > finA is now a string not a file handle ? > > Anyway if anyone can throw light on this I would be grateful. > > thanks > > richard.shea. From floyd at barrow.com Wed Oct 22 23:54:37 2003 From: floyd at barrow.com (Floyd Davidson) Date: Wed, 22 Oct 2003 19:54:37 -0800 Subject: [OT] Inuit? Eskimo? References: <20031020163642.GA5539@nl.linux.org> <4vre61-ku2.ln1@beastie.ix.netcom.com> <8765ii53yf.fld@barrow.com> <87wuaxymjz.fld@barrow.com> <3F970150.B48835B3@engcorp.com> <87k76wzy5b.fld@barrow.com> <3F971A95.C4C8B300@engcorp.com> Message-ID: <877k2wzk02.fld@barrow.com> Peter Hansen wrote: >Floyd Davidson wrote: >> >> Like I said, it is mistaken to believe the term Eskimo is >> not pc, > >I guess I need that spelled out more clearly. Are you saying >unequivocally that there is not a *single* group of Inuit anywhere >on the planet who have expressed a strong desire to be known as >"Inuit" rather than as "Eskimos"? If that's the case, my apologies, >as I must have missed that part of your posts in my skimming. OK, so you don't understand what "pc" means. -- Floyd L. Davidson Ukpeagvik (Barrow, Alaska) floyd at barrow.com From bbiro at netian.com Fri Oct 24 04:24:16 2003 From: bbiro at netian.com (Bart Simpson) Date: 24 Oct 2003 01:24:16 -0700 Subject: E_ACCESSDENIED problem with win32 disk quota Message-ID: <10093a06.0310240024.27719278@posting.google.com> Hi, I'm testing to control Windows disk quota by PythonWin on win2003 and winXP. But ther is some problem.. This is the test code: import win32com.client qutoa=win32com.client.Dispatch('Microsoft.DiskQuota.1') quota.Initialize('c:\\',1) test=quota.AddUser('test') ## 'test' is real account name in my machine. test.QuotaLimit=10000000 # 10MB However, If I run it within PythonWin, I get this returned error message: >>> t.QuotaLimit=10000000 Traceback (most recent call last): File "", line 1, in ? File "C:\Python22\Lib\site-packages\win32com\client\__init__.py", line 355, in __setattr__ apply(self._oleobj_.Invoke, args + (value,) + defArgs) com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2147024891), None) I have known error code -2147024891 (0x80070005) means E_ACCESSDENIED by someone's kind help. (Thanks Roger :) But I run PythonWin on Administrator privilege and I couldn't find any related method for setting permission in 'Microsoft.DiskQuota.1' object. Does anyone have any ideas? Thanks! -- Y.H. Rhiu From fake at not-a-real-address.net Sat Oct 25 13:44:15 2003 From: fake at not-a-real-address.net (Bruce Wolk) Date: Sat, 25 Oct 2003 17:44:15 GMT Subject: Addition and multiplication puzzle In-Reply-To: References: Message-ID: Mark Dickinson wrote: > Can anyone either reproduce or explain the following > apparently inconsistent behaviours of __add__ and > __mul__? The class Gaussian provides a sub-bare-bones > implementation of Gaussian integers (a Gaussian > integer is a complex number x+yi for which both x and > y are > integers): > > class Gaussian(object): > """class representing Gaussian integers""" > > def __init__(self, x, y = 0): > self.real, self.imag = x, y > > def __repr__(self): > return repr(self.real) + "+" + repr(self.imag) > + "*i" > > def __add__(self, other): > if type(other) != Gaussian: > other = Gaussian(other) > return Gaussian(self.real + other.real, > self.imag + other.imag) > > def __mul__(self, other): > if type(other) != Gaussian: > other = Gaussian(other) > return Gaussian(self.real * other.real - > self.imag * other.imag, \ > self.real * other.imag + > self.imag * other.real) > > Under Python 2.3.2 I get: > > >>>>i = Gaussian(0, 1) >>>>i * 3 > > 0+3*i > >>>>3 * i # surprise! > > 0+3*i > >>>>i + 3 > > 3+1*i > >>>>3 + i > > Traceback (most recent call last): > File "", line 1, in ? > TypeError: unsupported operand type(s) for +: 'int' > and 'Gaussian' > > In other words, I can *multiply* an int by a Gaussian > in either order, but I can only *add* a Gaussian to an > int, not the other way around. The surprise is that > multiplying an int by a Gaussian works---I'd expect it > to complain since there's no __rmul__ method defined, > in just the same way that 3+i produced an exception > above. Why do addition and multiplication behave > differently? > > Yours hoping for enlightenment, > > Mark > > > __________________________________ > Do you Yahoo!? > The New Yahoo! Shopping - with improved product search > http://shopping.yahoo.com > 3*i gives the expected error under Python 2.2.2. Curious indeed. From deets_noospaam at web.de Thu Oct 23 15:32:29 2003 From: deets_noospaam at web.de (Diez B. Roggisch) Date: Thu, 23 Oct 2003 21:32:29 +0200 Subject: iterating bit-by-bit across int? References: Message-ID: > I'm thinking about writing a function that eats integers and poops out > lists of bools; and then I can iterate through that, and change values > in there. But before I do that, does anyone have a better idea? For speed, you should use shift and boolean ops - like this: def mutate(seq, n=32, prob=0.05): for bit in xrange(n): if random.random() <= prob: seq ^= 1 << bit return seq Regards, Diez From LittleDanEhren at yahoo.com Fri Oct 17 20:00:37 2003 From: LittleDanEhren at yahoo.com (Daniel Ehrenberg) Date: 17 Oct 2003 17:00:37 -0700 Subject: teaching programming to children References: Message-ID: <711c7390.0310171600.8f4768c@posting.google.com> > A young friend of me (12 years old) has asked me to teach him programming (after > I shortly described my programming job as telling the computer what to do and > not the other way arround). I choose python because I personally like it but I > was wondering to what extent is it appropriate for this task. > > a) Its interpreter is very nice but it hides some basic truths about computers. > Namely, the need to compile and the differences between the languages of humans > and languages of computers. Underlying truth that all programs have to be compiled? That's a reason not to use any scripting languages? Compilation is not that big a step, and scripting languages are gaining ground. You like Python, so you probably use it for many things. Why can't your friend? Python is not exactly like English. > > b) Most simple tasks can be achieved so easily that "there's nothing to learn". > What do you think would be our first programming assignments? And what language > constructs should we start with? > There is stuff to learn, and if there truly is "nothing to learn", then you can move on to advanced things faster. > c) Should we run to "cool" things (GUI, networking, other proposals?) or should > we first make a good hold of "algorithms" (which in my opinion is at the heart > of programming). > IMHO you shouldn't fixate on algorithms because it will bore him/her. Maybe you could teach algorithms and "cool" things at the same time? From jjl at pobox.com Sun Oct 26 10:37:09 2003 From: jjl at pobox.com (John J. Lee) Date: 26 Oct 2003 15:37:09 +0000 Subject: AI and cognitive psychology rant (getting more and more OT - tell me if I should shut up) References: <9XVib.214859$hE5.7243121@news1.tin.it> <3ovpovc9hmahv5g373jm2oo7mk3i83ldtb@4ax.com> <29cjb.218983$hE5.7379913@news1.tin.it> <5tksov8r4c3caoatfoslfi87q61dupaq81@4ax.com> <2askpv0sqrv7k9hbpis3ig4iqclpl24ojc@4ax.com> <3f8lpvsddmeltg69vkl2uu8u8cei7bb2cg@4ax.com> Message-ID: <87znfovwm2.fsf@pobox.com> Robin Becker writes: > In article <3f8lpvsddmeltg69vkl2uu8u8cei7bb2cg at 4ax.com>, Stephen Horne > writes > >As I already mentioned, if a primitive person observes a car and > >theorises that there is a demon under the hood, that does not become > >true. Reality does not care about anyones perceptions as it is not > >dependent on them in any way - perceptions are functionally dependent > >on reality, and our perceptions are designed to form a useful model of > >reality. > > We observe electrons and make up mathematical theories etc etc, but in > reality little demons are driving them around. :) That's basically my model, too :-) > Your assertion that there is an objective reality requires proof as > well. It does not. > Probably it cannot be proved, but must be made an axiom. The > scientific method requires falsifiability. It's the whole project of science to understand reality, so the concept is outside of science. I guess the phrase 'existence of reality' means pretty much the same as 'the degree of success of science'. > The fact is we cannot perceive well enough to determine reality. The > physicists say that observation alters the result so if Heisenberg is Those physicists are wrong, and Stephen is right. It's a bit of an embarrassment to Physics that some physicists apparently still believe in the Copenhagen interpretation. > right there is no absolute reality. Perhaps by wishing hard I can get my > batteries to last longer 1 time in 10^67. No, but you can get them to last arbitrarily long by being *extremely* lucky ;-) > Awareness certainly mucks things up in socio-economic systems which are > also real in some sense. But there's no mystery or deep philosophical problem there. > I hear people putting forward the view that > time is a construct of our minds; does time flow? No, 'the flow of time' doesn't really mean anything. Any more deep mysteries you want me to clear up for you while I'm about this? ;-) > This is a bit too meta-physical, but then much of modern physics is like > that. Since much of physics is done by counting events we are in the > position of the man who having jumped out of the top floor observes that > all's well after falling past the third floor as falling past floors > 10,9,... etc didn't hurt. We cannot exclude exceptional events. There's rather a big difference between the probabilities involved there, Robin. We *could* be in a "Harry Potter Universe" of the sort you hint at, but the word 'unlikely' hardly begins to describe the magnitude of it! I highly recommend David Deutsch's book "The Fabric of Reality", which covers most of the stuff discussed in this thread. John From larry_Goodman at yahoo.com Wed Oct 15 17:22:09 2003 From: larry_Goodman at yahoo.com (Larry goodman) Date: Wed, 15 Oct 2003 17:22:09 -0400 Subject: reasonably priced reporting solution References: <7x7k36td9p.fsf@ruckus.brouhaha.com> Message-ID: <2ferov40tvrbejgg20ic27l5pm9mteh1q8@4ax.com> >See http://www.reportlab.org for example. But this is free for only GPL apps right? My app will be closed source. The only price i see there is 25,000 for their enterprise SDK and that is way out of my range. From aleaxit at yahoo.com Sun Oct 12 13:18:18 2003 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 12 Oct 2003 17:18:18 GMT Subject: for loop counting backward? References: Message-ID: Eric Wichterich wrote: > Hello, > > I am converting a perl-script to python and have problems with this > simple perl-statement: > > for ( $i = 100; $i > 2; $i-- ) {do something } > > Does anyone know how to write this in python? I did not find any > documentation about counting backward in a for loop... for i in range(100, 2, -1): dosomething(i) Alex From aleax at aleax.it Tue Oct 14 07:45:25 2003 From: aleax at aleax.it (Alex Martelli) Date: Tue, 14 Oct 2003 11:45:25 GMT Subject: AI and cognitive psychology rant (was Re: BIG successes of Lisp...) References: <7xvfqs66v6.fsf@ruckus.brouhaha.com> Message-ID: Stephen Horne wrote: > On Tue, 14 Oct 2003 07:45:40 GMT, Alex Martelli > wrote: > >>Personally, I first met Rev. Bayes in high school, together with the >>rest of the foundations of elementary probability theory, but then I >>did admittedly go to a particularly good high school; neither of my >>kids got decent probability theory in high school, though both of >>them met it in their first college year (in totally different fields, >>neither of them connected with "AI" -- financial economics for my >>son, telecom engineering for my daughter). > > Sorry - missed this bit on the first read. > > I never limited my education to what the school was willing to tell Heh, me neither, of course. > me, partly because having Asperger syndrome myself meant that the > library was the best refuge from bullies during break times. Not for me, as it was non-smoking and I started smoking very young;-). But my house was always cluttered with books, anyway. However, interestingly enough, I had not met Bayes' theorem _by that name_, only in the somewhat confusing presentation known as "restricted choice" in bridge theory -- problem is, Borel et Cheron's "Theorie Mathematique du Bridge" was out of print for years, until (I think) Mona Lisa Press finally printed it again (in English translation -- the French original came out again a while later as a part of the reprint of all of Borel's works, but always was much costlier), so my high school got there first (when I was 16). My kids' exposure to probability theory was much earlier of course (since I taught them bridge when they were toddlers, and Bayes' Theorem pretty obviously goes with it). > I figure I first encountered Bayes in the context of expert systems > when I was about 14 or 15. I imagine that fits roughly into the high > school junior category, but I'm not American so I don't know for sure. I'm not American either -- I say "high school" to mean what in Italy is known as a "Liceo" (roughly the same age range, 14-18). Alex From aahz at pythoncraft.com Sun Oct 26 01:40:15 2003 From: aahz at pythoncraft.com (Aahz) Date: 26 Oct 2003 01:40:15 -0400 Subject: Newbie Questions: Swithing from Perl to Python References: Message-ID: In article , Roy Smith wrote: > >My personal opinion is that you should be able to do the simplier: > >for key in myDict.keys().sort() > print key > >but unfortunately, sort doesn't work like that. It sorts the list >in-place and does NOT return the sorted list. Yup. Guido doesn't want you copying the list each time you sort; it's easy enough to make your own copy function. Nevertheless, it appears likely that 2.4 will grow list.sorted() (yes, a static method on the list type). -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From bokr at oz.net Sun Oct 19 12:43:47 2003 From: bokr at oz.net (Bengt Richter) Date: 19 Oct 2003 16:43:47 GMT Subject: AST Manipulation and Common Subexpression Elimination References: Message-ID: On Sat, 18 Oct 2003 07:09:51 +0000 (UTC), Robert Kern wrote: >I'm in the middle of writing a scientific program with a number of very, very >long formulae. You can see a typical one below. What I would like to do is to >parse this code to yield an AST, identify identical subtrees, replace them in >the AST with a dummy variable to which I will assign the common subexpression. > > v21c = ((1-2*nu)*((2*(1-nu)ctB*ctB-nu)*log(Ry3bar) - \ ^--missing * ? > (2*(1-nu)*ctB*ctB+1-2*nu)*cB*log(Rz3bar)) - \ > (1-2*nu)/Ry3bar*(y1*ctB*(1-2*nu-a/Rbar) + nu*ybar3 - a + \ > y2*y2/Ry3bar*(nu+a/Rbar)) - \ > (1-2*nu)*zbar3*ctB/Rz3bar*(cB+a/Rbar) - \ > a*y1*(ybar3-a)*ctB/Rbar3 + \ > (ybar3-a)/Ry3bar*(-2*nu+((1-2*nu)*y1*ctB-a)/Rbar + \ > y2*y2/Rbar/Ry3bar*(2*nu+a/Rbar)+a*y2*y2/Rbar3) + \ > (ybar3-a)/Rz3bar*(cB*cB-((1-2*nu)*zbar1*ctB+a*cB)/Rbar + > a*ybar3*zbar1*ctB/Rbar3 - \ > (y2*y2*cB*cB-a*zbar1*ctB/Rbar*(Rbar*cB+ybar3))/Rbar/Rz3bar))/(4*pi*( >1-nu)) > >For example, I would like to globally replace (1-2*nu) with, say, the variable >nu12=(1-2*nu). Some of these variables are already the evaluations of Do you want to recognize that (-2*nu+1) is an equivalent expression in one sense, though the AST's differ at one level of interpretation, e.g., >>> compiler.transformer.parse('(2*nu-1)') Module(None, Stmt([Discard(Sub((Mul((Const(2), Name('nu'))), Const(1))))])) vs >>> compiler.transformer.parse('(-1+2*nu)') Module(None, Stmt([Discard(Add((UnarySub(Const(1)), Mul((Const(2), Name('nu'))))))])) And are you considering your integer literal coefficients as abbreviations of their floating point equivalent? Are you concerned with order of evaluation at all? I presume so if some of your variables are matrices, but how about the non-matrices? Could you use distinctive names for the matrices, to make that part? Is it a given that there are no aliases? It might be interesting to take Martin's suggestion and generate a hash by way of using canonicalized string representations and letting the hashing be done by adding them to subexpression dict. E.g., sort the elements of same-level operator terms from the bottom leaves up. I had an idea to do that by canonicalizing to a prefix notation with sign-tagged atoms, so 2*nu-1 becomes (+ (* 2 nu) -1). BTW, what is your evaluation precedence for * and / ? I.e., is a*b/c*d ((a*b)/c)*d or (a*b)/(b*c) ? Python is left->right unless something binds tighter, I believe. >subexpressions I found convenient when typing in these formulae (or the original >authors when deriving them). > >Each of these variables is either a float or a Numeric array (or the log() >function). No variables changes value during the computation, nor are there >branches or loops, so the CSE algorithm doesn't have to be sophisticated enough >to account for these. > >Before you start on about "premature optimization," note that I'm more concerned >with keeping the formulae readable, manageable, and debuggable than anything >else. Heck, with the size of the arrays I'm thinking about, doing lots of CSE >will probably kill my memory. > I tried a hack using the text of repr(compiler.transformer.parse(your_formula) and re-evaluating it to rewrite the tree in prefix format. I got '((1-2*nu)*((2*(1-nu)*ctB*ctB-nu)*log(Ry3bar) -\n (2*(1-nu)*ctB*ctB+1-2*nu)*cB*log(Rz3bar )) -\n (1-2*nu)/Ry3bar*(y1*ctB*(1-2*nu-a/Rbar) + nu*ybar3 - a + \n y2*y2/Ry3ba r*(nu+a/Rbar)) - \n (1-2*nu)*zbar3*ctB/Rz3bar*(cB+a/Rbar) - \n a*y1*(ybar3-a)*ctB/ Rbar3 + \n (ybar3-a)/Ry3bar*(-2*nu+((1-2*nu)*y1*ctB-a)/Rbar + \n y2*y2/Rbar/Ry 3bar*(2*nu+a/Rbar)+a*y2*y2/Rbar3) +\n (ybar3-a)/Rz3bar*(cB*cB-((1-2*nu)*zbar1*ctB+a*cB)/R bar + \n a*ybar3*zbar1*ctB/Rbar3 - \n (y2*y2*cB*cB-a*zbar1*ctB/Rbar*(Rbar* cB+ybar3))/Rbar/Rz3bar))/(4*pi*( 1-nu))' => "Module(None, Stmt([Discard(Div((Add((Add((Sub((Sub((Sub((Mul((Sub((Const(1), Mul((Const(2), Nam e('nu'))))), Sub((Mul((Sub((Mul((Mul((Mul((Const(2), Sub((Const(1), Name('nu'))))), Name('ctB')) ), Name('ctB'))), Name('nu'))), CallFunc(Name('log'), [Name('Ry3bar')], None, None))), Mul((Mul( (Sub((Add((Mul((Mul((Mul((Const(2), Sub((Const(1), Name('nu'))))), Name('ctB'))), Name('ctB'))), Const(1))), Mul((Const(2), Name('nu'))))), Name('cB'))), CallFunc(Name('log'), [Name('Rz3bar')] , None, None))))))), Mul((Div((Sub((Const(1), Mul((Const(2), Name('nu'))))), Name('Ry3bar'))), A dd((Sub((Add((Mul((Mul((Name('y1'), Name('ctB'))), Sub((Sub((Const(1), Mul((Const(2), Name('nu') )))), Div((Name('a'), Name('Rbar'))))))), Mul((Name('nu'), Name('ybar3'))))), Name('a'))), Mul(( Div((Mul((Name('y2'), Name('y2'))), Name('Ry3bar'))), Add((Name('nu'), Div((Name('a'), Name('Rba r'))))))))))))), Mul((Div((Mul((Mul((Sub((Const(1), Mul((Const(2), Name('nu'))))), Name('zbar3') )), Name('ctB'))), Name('Rz3bar'))), Add((Name('cB'), Div((Name('a'), Name('Rbar'))))))))), Div( (Mul((Mul((Mul((Name('a'), Name('y1'))), Sub((Name('ybar3'), Name('a'))))), Name('ctB'))), Name( 'Rbar3'))))), Mul((Div((Sub((Name('ybar3'), Name('a'))), Name('Ry3bar'))), Add((Add((Add((Mul((U narySub(Const(2)), Name('nu'))), Div((Sub((Mul((Mul((Sub((Const(1), Mul((Const(2), Name('nu')))) ), Name('y1'))), Name('ctB'))), Name('a'))), Name('Rbar'))))), Mul((Div((Div((Mul((Name('y2'), N ame('y2'))), Name('Rbar'))), Name('Ry3bar'))), Add((Mul((Const(2), Name('nu'))), Div((Name('a'), Name('Rbar'))))))))), Div((Mul((Mul((Name('a'), Name('y2'))), Name('y2'))), Name('Rbar3'))))))) )), Mul((Div((Sub((Name('ybar3'), Name('a'))), Name('Rz3bar'))), Sub((Add((Sub((Mul((Name('cB'), Name('cB'))), Div((Add((Mul((Mul((Sub((Const(1), Mul((Const(2), Name('nu'))))), Name('zbar1'))) , Name('ctB'))), Mul((Name('a'), Name('cB'))))), Name('Rbar'))))), Div((Mul((Mul((Mul((Name('a') , Name('ybar3'))), Name('zbar1'))), Name('ctB'))), Name('Rbar3'))))), Div((Div((Sub((Mul((Mul((M ul((Name('y2'), Name('y2'))), Name('cB'))), Name('cB'))), Mul((Div((Mul((Mul((Name('a'), Name('z bar1'))), Name('ctB'))), Name('Rbar'))), Add((Mul((Name('Rbar'), Name('cB'))), Name('ybar3'))))) )), Name('Rbar'))), Name('Rz3bar'))))))))), Mul((Mul((Const(4), Name('pi'))), Sub((Const(1), Nam e('nu'))))))))]))" => s_push: parser stack overflow exceptions.MemoryError: Traceback (most recent call last): File "C:\pywk\parse\cse.py", line 224, in ? print 'cksrc returned ok ==%s' % cksrc(src, verbose) File "C:\pywk\parse\cse.py", line 176, in cksrc v = eval(ast_repr, env) MemoryError when I tried the whole thing. On a tail part of your expression, it seems to work, so I wonder what I have to set higher. (I have 320 mb RAM so I hope it's not really out of memory). I got (input, parse, prefix-notation): '(\n (ybar3-a)/Ry3bar*(-2*nu+((1-2*nu)*y1*ctB-a)/Rbar + \n y2*y2/Rbar/Ry3bar*( 2*nu+a/Rbar)+a*y2*y2/Rbar3) +\n (ybar3-a)/Rz3bar*(cB*cB-((1-2*nu)*zbar1*ctB+a*cB)/Rbar + \n a*ybar3*zbar1*ctB/Rbar3 - \n (y2*y2*cB*cB-a*zbar1*ctB/Rbar*(Rbar*cB+yba r3))/Rbar/Rz3bar))/(4*pi*( 1-nu))' => "Module(None, Stmt([Discard(Div((Add((Mul((Div((Sub((Name('ybar3'), Name('a'))), Name('Ry3bar')) ), Add((Add((Add((Mul((UnarySub(Const(2)), Name('nu'))), Div((Sub((Mul((Mul((Sub((Const(1), Mul( (Const(2), Name('nu'))))), Name('y1'))), Name('ctB'))), Name('a'))), Name('Rbar'))))), Mul((Div( (Div((Mul((Name('y2'), Name('y2'))), Name('Rbar'))), Name('Ry3bar'))), Add((Mul((Const(2), Name( 'nu'))), Div((Name('a'), Name('Rbar'))))))))), Div((Mul((Mul((Name('a'), Name('y2'))), Name('y2' ))), Name('Rbar3'))))))), Mul((Div((Sub((Name('ybar3'), Name('a'))), Name('Rz3bar'))), Sub((Add( (Sub((Mul((Name('cB'), Name('cB'))), Div((Add((Mul((Mul((Sub((Const(1), Mul((Const(2), Name('nu' ))))), Name('zbar1'))), Name('ctB'))), Mul((Name('a'), Name('cB'))))), Name('Rbar'))))), Div((Mu l((Mul((Mul((Name('a'), Name('ybar3'))), Name('zbar1'))), Name('ctB'))), Name('Rbar3'))))), Div( (Div((Sub((Mul((Mul((Mul((Name('y2'), Name('y2'))), Name('cB'))), Name('cB'))), Mul((Div((Mul((M ul((Name('a'), Name('zbar1'))), Name('ctB'))), Name('Rbar'))), Add((Mul((Name('Rbar'), Name('cB' ))), Name('ybar3'))))))), Name('Rbar'))), Name('Rz3bar'))))))))), Mul((Mul((Const(4), Name('pi') )), Sub((Const(1), Name('nu'))))))))]))" => (/ (+ (* (/ (+ ybar3 -a) Ry3bar) (+ (* -2 nu) (/ (+ (* (+ 1 (* -2 nu)) y1 ctB) -a) Rbar) (* (/ ( * y2 y2) Rbar Ry3bar) (+ (* 2 nu) (/ a Rbar))) (/ (* a y2 y2) Rbar3))) (* (/ (+ ybar3 -a) Rz3bar ) (+ (* cB cB) (- (/ (+ (* (+ 1 (* -2 nu)) zbar1 ctB) (* a cB)) Rbar)) (/ (* a ybar3 zbar1 ctB) Rbar3) (- (/ (+ (* y2 y2 cB cB) (* (- (/ (* a zbar1 ctB) Rbar)) (+ (* Rbar cB) ybar3))) Rbar Rz3 bar))))) (* 4 pi (+ 1 -nu))) It certainly isn't the most efficient way, but it was kind of interesting. I made a step toward canonicalizing by transforming everything (very alpha here ;-) to (+ ...) or (* ...), where of course the latter can be elements of the former, and parens make for some rewrites here and there, e.g., Expr> (a+b)-(c-d) (+ a b -c d) Expr> -(a+b+c)-(d*e*f) (+ -a -b -c (* -d e f)) Expr> -(a+b+c)-(d*e*f)*(x*y) (+ -a -b -c (* -d e f x y)) Expr> -(a+b+c)-(d*e*f)+(x*y) (+ -a -b -c (* -d e f) (* x y)) Expr> foo(1,2,3) (foo 1 2 3) Expr> foo(2*nu-1)+3*bar-4 (+ (foo (+ (* 2 nu) -1)) (* 3 bar) -4) Expr> foo(2*nu-1, 'another')+3*bar-4 (+ (foo (+ (* 2 nu) -1) 'another') (* 3 bar) -4) Now if I sort the (+ ...) and (* ...) depth first then I think in the string representations I might have some keys for a dict of CSE's. At least that's the hunch ;-) But that stack overflow makes me wonder ... >My questions are: > >1. Can I do better than brute-force traversing the AST and trying to match each >subtree to the other subtrees (using something like the match() function given >in the parser module example)? The question in my mind would be what kind of source transformations are valid given that you have perhaps arbirary scalar and matrix mixes in your formulae? Are you expecting the system to discover equivalent subexpressions that are not typed verbatim in the same token order? Need to know the constraints on that. I borrowed the output of compiler.transformer.parse and let it repr itself to text, so that it would just look like a giant bunch of nested function calls, and then wrote some functions to generate scheme-like code (represented by a subclass of tuple with just a __repr__ override as the only method. And then exec'd the string in an environment that would call my functions according to the big nest. It would be faster for the computer (but not me at the moment ;-), to use the actual tree and walk it to do what I did. I think I saw a tree visitor example someplace, so maybe it's practically on a silver platter already. Will have to look for it. It's just that seeing the nested function call representation gave me a simple idea to hack ;-) > >2. Are there good tools out there for doing AST transformations like this? Are >there any GUI tools for messing with the AST? I know that I will want to >interactively select which subexpressions are eliminated in this fashion. > I suspect there are at least some useful helper functions to solve the problem, but I haven't looked yet. Nor GUI. But I can visualize a Tkinter thing ;-) >3. Is there any example code around showing how to output Python code from the >AST? I can probably figure out, then, how to do the same for >Maxima/Yacas/Maple/Mathematica as I'm sure I'm going to want to slap these >formulae into a CAS and play around with them. > Hm, I guess what I did kind of models that, since the output is almost scheme. (sorry I didn't get to pretty-printing it). >4. And as a corollary to that last thought: are there any automatic >differentiation tools for Python that operate directly on the AST and generate >new code? Symbolic? Like (+ (* x x ) 3) => (* 2 x) ? > >Googling hasn't come up with much for me, but my brain is fried from typing in >these $%&@! formulae. Pointers to introductory compiler technique references >(online or dead tree) or other useful resources are welcome. > Sorry. SICP and Dragon book I guess. But the above was just an idea using a variant of the technique I posted the other day as a possible way to detect unsafe code, which The code is very grotty right now, so I won't post it as is. BTW, scheme wasn't my goal, but I find it interesting that that is the direction things went in the process of representing expressions and manipulating them for the purpose of generating a canonical representation. (This doesn't mean I don't prefer Python to write the manipulation code with ;-) I haven't taken the next step yet, which is to generate the sorted sub-expressions and track them (count occurrences of canonicalized string representations of them) in a dict. They could be shown and be selectable for giving names (if there's better names than CSE_1, CSE2, etc.) and choosing which to use for a rewrite or the overall formula. I think it's doable. ;-) Regards, Bengt Richter From glingl at aon.at Tue Oct 21 17:10:42 2003 From: glingl at aon.at (Gregor Lingl) Date: Tue, 21 Oct 2003 23:10:42 +0200 Subject: a little bit of recursion In-Reply-To: References: <62e9c66e.0310211147.64f2200c@posting.google.com> Message-ID: <3F95A0D2.2010308@aon.at> rzed schrieb: > Dominik Kaspar wrote: > >>I'm trying to write a quite big recursive function, but the baseline >>is the following: >> >>def rek(N, L): >> N = N + 1 >> if N >= 9: return L >> else: return rek(N, L = L.append(N)) >> >>print rek(0, []) >> >>Why isn't this working? >>In my opinion it should return [1, 2, ..., 9] >> >>Thanks for any answers. > > > > One problem is that L = L.append(N) does not have the effect you want. > Try it on its own. > Another is that it won't return [1,2,...,9] even when that is > corrected. That certainly depends on the way one corrects it. However Dominik first has to notice, that append is a method, which *changes* L but doesn't return L. Instead it returns None. So it may be ok to call L.append(N), but not on the right side of an assignment statement. You can obsrve what I mean here: >>> L = [1,2,3] >>> print L.append(4) None >>> L [1, 2, 3, 4] >>> HTH, Gregor > > > > From alan at cawNOtech.freeSPAMserve.co.uk Sat Oct 4 07:31:45 2003 From: alan at cawNOtech.freeSPAMserve.co.uk (Alan Crowe) Date: 04 Oct 2003 12:31:45 +0100 Subject: Python syntax in Lisp and Scheme References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> <92c59a2c.0310031345.57d20631@posting.google.com> Message-ID: <8665j5dyse.fsf@cawtech.freeserve.co.uk> MetalOne wrote > If a set of macros could be written to improve LISP > syntax, then I think that might be an amazing thing. An > interesting question to me is why hasn't this already been > done. I think the issue is the grandeur of the Lisp vision. More ambitious projects require larger code bases. Ambition is hard to quantify. Nevertheless one must face the issue of scaling. Does code size go as the cube of ambition, or is it the fourth power of ambition? Or something else entirely. Lisp aspires to change the exponent, not the constant factor. The constant factor is very important. That is why CL has FILL :-) but shrinking the constant factor has been done (and with C++ undone). Macros can be used to abbreviate code. One can spot that one is typing similar code over and over again. One says "whoops, I'm typing macro expansions". Do you use macros to tune the syntax, so that you type N/2 characters instead of N characters, or do you capture the whole concept in macro and eliminate the repetition altogether? The point is that there is nowhere very interesting to go with syntax tuning. It is the bolder goal of changing the exponent, and thus seriously enlarging the realm of the possible, that excites. Alan Crowe From tcronj at ananzi.co.za Wed Oct 15 16:57:00 2003 From: tcronj at ananzi.co.za (Tertius) Date: Wed, 15 Oct 2003 22:57:00 +0200 Subject: OT... In-Reply-To: References: Message-ID: <9s2dnYeaeJ-HKRCiU-KYvA@is.co.za> Dennis Lee Bieber wrote: > Tertius Cronje fed this fish to the penguins on Tuesday 14 October 2003 > 12:40 pm: > > >>I am unable to register a new email on the jython user-list. Seems the >>mailserver tries to verify my sending email when tringing to confirm. >> > > As I read the message, it is trying to verify that > > postmaster at ananzi.co.za > > exists and receives mail -- probably for purposes of reporting > violations by subscribers. > > >>550-Several RFCs state that you are required to have a postmaster >>550-mailbox for each mail domain. > > > If "ananzi.co.za" is your own registered machine, you need to > create/accept email sent to "postmaster at ..." > > If the machine is not your own, but part of some service provider > company, the complaint will need to be taken up with their management, > as they are violating common practice. > Thanks From find at my.address.elsewhere Wed Oct 22 15:55:45 2003 From: find at my.address.elsewhere (Matthias Blume) Date: 22 Oct 2003 14:55:45 -0500 Subject: Python from Wise Guy's Viewpoint References: <_8Ekb.7543$pT1.318@twister.nyc.rr.com> Message-ID: Pascal Costanza writes: > ...because static type systems work by reducing the expressive power > of a language. It depends a whole lot on what you consider "expressive". In my book, static type systems (at least some of them) work by increasing the expressive power of the language because they let me express certain intended invariants in a way that a compiler can check (and enforce!) statically, thereby expediting the discovery of problems by shortening the edit-compile-run-debug cycle. > (Now you could argue that current sophisticated type systems cover 90% > of all cases and that this is good enough, but then I would ask you > for empirical studies that back this claim. ;) In my own experience they seem to cover at least 99%. (And where are _your_ empirical studies which show that "working around language restrictions increases the potential for bugs"?) Matthias From john at rygannon.com Fri Oct 24 07:28:28 2003 From: john at rygannon.com (John Dean) Date: Fri, 24 Oct 2003 11:28:28 GMT Subject: ANN: Rekall V2.1.0 stable is released Message-ID: <3f990cc4$0$12697$fa0fcedb@lovejoy.zen.co.uk> Hi We are pleased to announce the release of Rekall V2.1.0 stable for Linux and Windows Please note, the stable release of Rekall V2.1.0 is only available from either http://www.totalrekall.co.uk and http://www.rygannon.com What is Rekall? Rekall is a programmable (using Python of course), database independant, GUI database client. Rekall, includes Form, Report and Query Designers, a Python Script editor and debugger, Macros, Wizards, re-useable components, and lots more. Included with the standard edition are drivers for MySQL, PostgreSQL and xBase. Drivers for DB2, Oracle, and ODBC are available separately -- Best Regards John From ingvar at cathouse.bofh.se Thu Oct 9 07:16:09 2003 From: ingvar at cathouse.bofh.se (Ingvar Mattsson) Date: 09 Oct 2003 12:16:09 +0100 Subject: Python syntax in Lisp and Scheme References: Message-ID: <873ce2k6fa.fsf@gruk.tech.ensign.ftech.net> cstacy at dtpq.com (Christopher C. Stacy) writes: > >>>>> On Wed, 08 Oct 2003 16:51:44 -0400, Joe Marshall ("Joe") writes: > Joe> "Carlo v. Dango" writes: > > >> method overloading, > > Joe> Now I'm *really* confused. I thought method overloading involved > Joe> having a method do something different depending on the type of > Joe> arguments presented to it. CLOS certainly does that. > > He probably means "operator overloading" -- in languages where > there is a difference between built-in operators and functions, > their OOP features let them put methods on things like "+". > > Lisp doesn't let you do that, because it turns out to be a bad idea. > When you go reading someone's program, what you really want is for > the standard operators to be doing the standard and completely > understood thing. Though if one *really* wants to have +, -, * and / as generic functions, I imagine one can use something along the lines of: (defpackage "GENERIC-ARITHMETIC" (:shadow "+" "-" "/" "*") (:use "COMMON-LISP")) (in-package "GENERIC-ARITHMETIC") (defgeneric arithmetic-identity (op arg)) (defmacro defarithmetic (op) (let ((two-arg (intern (concatenate 'string "TWO-ARG-" (symbol-name op)) "GENERIC-ARITHMETIC")) (cl-op (find-symbol (symbol-name op) "COMMON-LISP"))) `(progn (defun ,op (&rest args) (cond ((null args) (arithmetic-identity ,op nil)) ((null (cdr args)) (,two-arg (arithmetic-identity ,op (car args)) (car args))) (t (reduce (function ,two-arg) (cdr args) :initial-value (car args))))) (defgeneric ,two-arg (arg1 arg2)) (defmethod ,two-arg ((arg1 number) (arg2 (number))) (,cl-op arg1 arg2))))) Now, I have (because I am lazy) left out definitions of the generic function ARITHMETIC-IDENTITY (general idea, when fed an operator and NIL, it returns the most generic identity, when fed an operator and an argument, it can return a value that is more suitable) and there's probably errors in the code, too. But, in principle, that should be enough of a framework to build from, I think. //Ingvar -- My posts are fair game for anybody who wants to distribute the countless pearls of wisdom sprinkled in them, as long as I'm attributed. -- Martin Wisse, in a.f.p From joachim.durchholz at web.de Mon Oct 20 07:13:45 2003 From: joachim.durchholz at web.de (Joachim Durchholz) Date: Mon, 20 Oct 2003 13:13:45 +0200 Subject: Python from Wise Guy's Viewpoint In-Reply-To: References: Message-ID: Pascal Costanza wrote: > Joachim Durchholz wrote: > >> Oh, you're trolling for an inter-language flame fest... >> well, anyway: >> >>> 3. no multimethods (why? Guido did not know Lisp, so he did not know >>> about them) You now have to suffer from visitor patterns, etc. like >>> lowly Java monkeys. >> >> Multimethods suck. > > Do they suck more or less than the Visitor pattern? Well, the visitor pattern is worse. Generics would be better though. > So how do you implement an equality operator correctly with only single > dynamic dispatch? Good question. In practice, you don't use dispatch, you use some built-in mechanism. Even more in practice, all equality operators that I have seen tended to compare more or less than one wanted to have compared, at least for complicated types with large hidden internal structures, or different equivalent internal structures. I have seen many cases where people implemented several equality operators - of course, with different names, and for most cases, I'm under the impression they weren't even aware that it was equality that they were implementing :-) Examples are: Lisp with its multitude of equality predicates nicely exposes the problems, and provides a solution. Various string representations (7-bit Ascii, 8-bit Ascii, various Unicode flavors). Do you want to compare representations or contents? Do you need a code table to compare? Various number representation: do you want to make 1 different from 1.0, or do you want to have them equal? I think that dynamic dispatch is an interesting answer, but not to equality :-) Regards, Jo From tweedgeezer at hotmail.com Wed Oct 29 17:17:04 2003 From: tweedgeezer at hotmail.com (Jeremy Fincher) Date: 29 Oct 2003 14:17:04 -0800 Subject: On PEP 322 (ireverse) References: <4xQnb.373812$R32.12367046@news2.tin.it> Message-ID: <698f09f8.0310291417.a2895bc@posting.google.com> Is there any reason this PEP is of so limited scope? Why not a more comprehensive PEP defining a reverse iteration protocol similar the protocol we have now for forward iteration? It just seems that if this is implemented as-is, it'll be one of those warts left around when Python gets a reverse (or even more general) iteration protocol that will almost certainly operate in a different manner. It just seems to be fodder for supercession. Jeremy From roedy at seewebsite.com Wed Oct 22 19:40:45 2003 From: roedy at seewebsite.com (Roedy Green) Date: Wed, 22 Oct 2003 23:40:45 GMT Subject: approx 100 assorted computer/ math/other books References: <3F9531FE.F1381691@nomail.com> <3F969C4E.3CF6CA2F@yahoo.com> <55rdpvcniuskhqu9qah0j7q2u18knt04pe@4ax.com> Message-ID: <9n4epv4924c531f10pa8c0voulgnp4jre0@4ax.com> On Wed, 22 Oct 2003 23:52:03 +0100, Mark McIntyre wrote or quoted : >>The blast is against those who complain about top posting. Top posting >>is GOOD on one respect. > >Its evil. Period. I disagree. I would say it is very rare that I actually read rather than skip over quoted material. It is just a nuisance. If people get to the point right away they save me time. If I need to refresh myself on the quoted material I can look it up myself. If they put all the quoted junk at the end, at least is easier to ignore. I think it is a superior system, but I don't use it myself because it gets people too angry. Perhaps a compromise would be to simply label a top post with something like "quotes follow" or "top posted" to let you know where to find context if you need it. Who gets annoyed by what may have to do with the features of newsreader . Agent does not have a single key "jump to the meat" and my hand is on the mouse during most reading. There is no quick page down by mouse. I have to spin the scroll wheel to get to the point. I also have to drag the mouse from the button panel where it is usually parked to a different region of the screen to scroll. Agent also puts those cutsie "X twirled his moustache spun around three times and uttered ..." things in the same font as meat. I get quite annoyed reading some of those convoluted headers to discover they are just someone being cute. -- Canadian Mind Products, Roedy Green. Coaching, problem solving, economical contract programming. See http://mindprod.com/jgloss/jgloss.html for The Java Glossary. From edi at agharta.de Sun Oct 19 12:40:20 2003 From: edi at agharta.de (Edi Weitz) Date: 19 Oct 2003 18:40:20 +0200 Subject: Why don't people like lisp? References: <1A8kb.67406$pv6.3464@twister.nyc.rr.com> <874qy5ear5.fsf@bird.agharta.de> Message-ID: <87ekx92nbf.fsf@bird.agharta.de> On Sun, 19 Oct 2003 12:12:37 -0400, "Terry Reedy" wrote: > Last night I accepted the repeated suggestion to download and read > (some of) OnLisp. Problem: I *don't* know the arglist structure of > every form Graham uses, and since Graham assumes such knowledge, I > had to count parens to reverse engineer function prototypes and > determine what is an argument to what. A Python beginner would more > easily do this with Python code. Well, "On Lisp" is not a book for beginners. It's a book about the power of CL macros and was written for people who alread know Common Lisp. > What is ILISP. > Is there a usable online CL reference that would let me lookup, for > instance, DO and get the prototype and short description? Yes, definitely. Common Lisp has an ANSI standard and the ANSI standard is available online.[1] Be warned that this is a language standard, though. It's not a textbook written for people who want to learn the language. Tools like ILISP will allow you do put your cursor on a symbol and open the corresponding page of the HyperSpec with one keystroke. Or try something like . > Lisp-aware editors do not solve the problem of reading Lisp code > embedded in text, as with OnLisp formatted .ps or .pdf. Yes, but experience does. Edi. [1] Well, technically this is not the ANSI standard (you have to pay money to ANSI to get it - it's a printed document) but for all practical purposes it is. From aleax at aleax.it Thu Oct 16 07:54:23 2003 From: aleax at aleax.it (Alex Martelli) Date: Thu, 16 Oct 2003 11:54:23 GMT Subject: inner classes in python as inner classes in Java References: Message-ID: Carlo v. Dango wrote: > On Wed, 15 Oct 2003 21:52:32 GMT, Alex Martelli wrote: > >> You'll have to decide what semantics you want to obtain when an >> attribute is set on an instance of the "inner class" -- I sure can't do >> it on your behalf. > > I want the semantics of java's inner classes and the semantics of inner > methods... that the inner class shares the fields and methods of its outer > class instance.. But I've come to realize I can't do this in python, as I don't understand what you mean. "inner methods" (? presumably you mean nested functions ?) cannot re-bind names in outer scope -- you say you want these semantics, and you also seem to say you DO want assignments on the innerobject's attribute to re-bind attributes on the outer. There is a contradiction here in what you say. Neither in Python nor with any other tools whatsoever can you implement contradictory requirements. Give non-contradictory requirements about what you want to happen upon "inner.i = 23" and you will be able to implement them (whether they will be at all useful or sensible is quite another issue, of course). > the statement in some method in the inner class "self.i = 42" can be > interpreted as "create i in the inner class instance" or "lookup i in the > 'outer scope' and set it" It can be interpreted to mean any non-contradictory set of requirements you want to be interpreted as. Having as yet no idea of what you may hope to accomplish, that is useful at all, I can't guess what those hypothetical requirements could possibly be. >> There's a reason the official Python style guidelines have been >> amended to prefer spaces instead of tabs, you know. Sure, there >> will be some programs who display tabs in a way compatible with >> your preferences, but others won't; be conservative in what you >> generate -- spaces are ensured to be displayed as you intend, tabs >> are NOT, so don't use the latter in any code you send to others. > > hmm depends on which font people are using.. if it's not monospace, the > layout will also change.. This assertion is false. Since the _significant_ whitespace is only that which occurs at the start of a line, as long as each occurrence of a space character is displayed with the same width X, it cannot possibly matter in terms of code meaning what witdths x1, x2, ... xN are used to display other, non-whitespace characters. In particular it cannot matter whether x1==x2==...==xN or not, nor whether any one, several or all xi's happen to equal X. If you want your code's meaning to be unaltered, always indent it with spaces, NOT tabs. It does NOT matter which fonts people are using. If you indent with spaces, they'll see your code meaning the same thing. If you indent with tabs, there's no guarantee. This is part of the reason PEP 8, "Style Guide for Python Code", was updated by Guido van Rossum to read "For new projects, spaces-only are strongly recommended over tabs" and similar phrasings. > I doubt that there are many news readers where > you cannot set TAB == 4 spaces Two might suffice, when they're among the most widely used: Microsoft Outlook Express, and KDE's KNode. And no, of course I'm not going to change my favourite newsreader to accomodate people who choose to violate the official Python style guide. >>> actually its forwarding or consultation, as self is re-bound when you >>> invoke the outer.. >> >> In your Python code (and mine), it is false that "self is re-bound" >> (only an instruction such as "self = ..." would do that, and there is >> no such instruction in that code). Sure, when a method A of >> object B calls a method X of object Y, the local name 'self' is >> bound to Y in the execution of X while the same name is bound >> to B in the execution of A. But that is not re-binding -- just the >> distinction between lexically-same names in different scopes. > > well, I disagree... there is a difference between virtual and non-virtual > methods. Not in Python: absolutely no difference, since there's no such thing as a "non-virtual" method. > The first does not re-bind self, when doing super calls or when > casting an object to some super class and invoking methods on it (like > using C++'s :: ) There is no "casting" in Python. If you refer to such notation as, e.g.: class mydict(dict): def __getitem__(self, key): return dict(self)[key] I'll inform you that the dict(self) DOES return an object with an id different from that of self, which would mean (if dict were coded in Python) that the 'self' received by the superclass's __getitem__ would be a different one from that in the subclass. That is different from the "superclass call" usage return dict.__getitem__(self, key) where an _unbound_ method is extracted from class dict, exactly in order to be able to pass to it an 'unmodified' self explicitly (the main advantage being one of efficiency). >> Anyway, the term "delegation" is common for the operation in >> question - it is for example used in the "gang of 4"'s Design >> Pattern book. > > well, 'delegation' is cited in OOPSLA, ECOOP, AOSD etc litterature of > being defined in the seminal 1986 OOPSLA paper "Using Prototypical Objects > to Implement Shared Behavior in Object-Oriented Systems" by H. Lieberman. > the GOF book came out around 9 years later. ...and became an instant best-seller, cementing the usage. So, e.g., a proxy is equally well said to provide _delegation_ to an object it proxies for, as to provide _forwarding_ to that object. Yes, I know Szyperski tries to draw a fine distinction -- that "subsequently delegated messages are dispatched back to the original delegator", which isn't true in forwarding (the difference would appear in cases of what the gang of 4 call the 'Template Method' design pattern). What I'm saying is that this terminology distinction has little practicel currency -- look, for example, at what C# calls 'delegates' and tell me how delegating to them could `dispatch back` to the delegator (caller) [answer: it won't]. Or see how Fowler uses the terms in his "Refactoring" for the "Replace Delegation with Inheritance" and "Replace Inheritance with Delegation" refactorings (p. 325 ff). Alex From mspight at dnai.com Fri Oct 24 17:12:18 2003 From: mspight at dnai.com (Marshall Spight) Date: Fri, 24 Oct 2003 21:12:18 GMT Subject: Python from Wise Guy's Viewpoint References: <_8Ekb.7543$pT1.318@twister.nyc.rr.com> <3f972315$1@news.unimelb.edu.au> <3638acfd.0310230039.306b14f@posting.google.com> <3638acfd.0310232246.64fa09ed@posting.google.com> Message-ID: "Pascal Costanza" wrote in message news:bnarks$v7k$1 at f1node01.rhrz.uni-bonn.de... > > >>>For one thing, type declarations *cannot* become out-of-date (as > >>>comments can and often do) because a discrepancy between type > >>>declaration and definition will be immidiately flagged by the compiler. > >> > >>They same holds for assertions as soon as they are run by the test suite. > > > > That is not true unless your test suite is bit-wise exhaustive. > > Assertions cannot become out-of-date. If an assertion doesn't hold > anymore, it will be flagged by the test suite. This is only correct if all assertions receive coverage from the test suite, which requires significant discipline, manual testcase writing, and recurring manual verification, and even then, it is only true at runtime. And assertions only verify what you manually specify. The benefits of a type system require significantly less manual work, and find errors at compile time. Also, they verify that type errors provable do not occur anywhere in the program, vs. just where you manually specify. Marshall From usenet at consulting.net.nz Sun Oct 19 03:22:13 2003 From: usenet at consulting.net.nz (Adam Warner) Date: Sun, 19 Oct 2003 20:22:13 +1300 Subject: Why don't people like lisp? References: <1A8kb.67406$pv6.3464@twister.nyc.rr.com> Message-ID: Hi David Mertz, > Sure... but just imagine how badly matched my parentheses would have > been had I attempted to post Lisp code. I suspect you pasted in validly formatted Python code: def categorize_compose(filters, iter): results = tuple([[] for _ in len(filters)]) for x in iter: results[compose(filters)(x)].append(x) return results Before proceeding to indent it for display: ....def categorize_compose(filters, iter): .... results = tuple([[] for _ in len(filters)]) .... for x in iter: .... results[compose(filters)(x)].append(x) return results Making this mistake will not affect the semantics of Lisp code. If you had attempted to indent valid Lisp code you could not have made the same mistake. Even if you ultimately remember to indent everything correctly for display you are still changing the semantics of the program with every interim indentation change (and an interim failure could leave you with invalid code). A related issue is moving a block of Python code within a program and having to fix indentation of every line in the block to avoid changing its original semantics. Lisp parentheses combined with form analysis provide enough information to automatically reformat any arbitrary block of code. Lisp's parentheses and syntax are one of Lisp's greatest assets (and they also support effortless code generation). One could say Lisp's syntax is essential for achieving these aims. One could also say Python's syntax is essential for achieving its aesthetic aims and markedly distinguishing it from other programming languages. Regards, Adam From edi at agharta.de Thu Oct 16 17:08:43 2003 From: edi at agharta.de (Edi Weitz) Date: 16 Oct 2003 23:08:43 +0200 Subject: Python syntax in Lisp and Scheme References: <8CVgb.8$KR3.1846@typhoon.nyu.edu> <20031014050046.GM1454@mapcar.org> <87fzhtlvni.fsf@thalassa.informatimago.com> Message-ID: <87fzhsoppg.fsf@bird.agharta.de> On Thu, 16 Oct 2003 11:43:06 -0700, David Eppstein wrote: > For simple use of built-in libraries, > http://online.effbot.org/2003_08_01_archive.htm#troll > looks like a good test case. Quick hack follows. edi at bird:/tmp > cat troll.lisp (asdf:oos 'asdf:load-op :aserve) (asdf:oos 'asdf:load-op :cl-ppcre) (defparameter *scanner* (cl-ppcre:create-scanner "([^<]+)\\s* [^<]+\\s* [^<]+\\s* \\d+\\s* (\\d+)\\s* (\\d+)\\s* \\d+\\s* (\\d+)\\s*")) (defun troll-checker (name) (let ((target (net.aserve.client:do-http-request (format nil "http://netscan.research.microsoft.com/Static/author/authorprofile.asp?searchfor=~A" name) :protocol :http/1.0))) (cl-ppcre:do-scans (match-start match-end reg-starts reg-ends *scanner* target) (flet ((nth-group (n) (subseq target (aref reg-starts n) (aref reg-ends n)))) (let* ((group (nth-group 0)) (posts (parse-integer (nth-group 1))) (replies (parse-integer (nth-group 2))) (threads-touched (parse-integer (nth-group 3))) (reply-to-post-ratio (/ replies posts)) (threads-to-post-ratio (/ threads-touched posts))) (unless (< posts 10) (format t "~55A R~,2F T~,2F ~:[~;TROLL~:[?~;!~]~]~%" (subseq group 0 (min 55 (length group))) reply-to-post-ratio threads-to-post-ratio (and (> reply-to-post-ratio .8) (< threads-to-post-ratio .4)) (< threads-to-post-ratio .2)))))))) (compile 'troll-checker) edi at bird:/tmp > cmucl ; Loading #p"/home/edi/.cmucl-init". CMU Common Lisp 18e, running on bird.agharta.de With core: /usr/local/lib/cmucl/lib/lisp.core Dumped on: Thu, 2003-04-03 15:47:12+02:00 on orion Send questions and bug reports to your local CMUCL maintainer, or see . Loaded subsystems: Python 1.1, target Intel x86 CLOS 18e (based on PCL September 16 92 PCL (f)) * (load "troll") ; loading system definition from /usr/local/lisp/Registry/aserve.asd into ; # ; registering # as ASERVE ; loading system definition from /usr/local/lisp/Registry/acl-compat.asd into ; # ; registering # as ACL-COMPAT ; loading system definition from /usr/local/lisp/Registry/htmlgen.asd into ; # ; registering # as HTMLGEN ; loading system definition from /usr/local/lisp/Registry/cl-ppcre.asd into ; # ; registering # as CL-PPCRE ; Compiling LAMBDA (NAME): ; Compiling Top-Level Form: T * (troll-checker "edi at agharta.de") comp.lang.lisp R0.93 T0.63 NIL * (troll-checker "eppstein at ics.uci.edu") rec.photo.digital R1.00 T0.76 rec.arts.sf.written R0.99 T0.57 comp.lang.python R0.98 T0.64 rec.photo.equipment.35mm R1.00 T0.73 sci.math R1.00 T0.77 rec.puzzles R1.00 T0.75 comp.theory R1.00 T0.56 comp.graphics.algorithms R1.00 T0.87 comp.sys.mac.apps R1.00 T0.69 NIL * (troll-checker "spam at thalassa.informatimago.com") comp.lang.lisp R0.91 T0.44 fr.comp.os.unix R1.00 T0.70 es.comp.os.linux.programacion R1.00 T0.67 fr.comp.lang.lisp R1.00 T0.40 TROLL? comp.unix.programmer R1.00 T0.92 sci.space.moderated R1.00 T0.43 gnu.emacs.help R0.95 T0.84 sci.space.policy R1.00 T0.33 TROLL? alt.folklore.computers R1.00 T0.43 comp.lang.scheme R0.83 T0.58 fr.comp.os.mac-os.x R0.92 T0.83 NIL Granted, Portable AllegroServe[1] and CL-PPCRE[2] aren't "built-in" (but freely available, compatible with various CL compilers, and easy to install) and Python might have a bit more syntactic sugar but it wasn't _too_ hard to do that in Lisp. Edi [1] [2] From peter at engcorp.com Mon Oct 6 12:30:39 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 06 Oct 2003 12:30:39 -0400 Subject: Accessing global namespace References: Message-ID: <3F8198AF.AD746CF0@engcorp.com> Tongu? Yumruk wrote: > > I'm trying to build a completely plug-in based system. One of my > problems is importing a package dynamically. I'm trying to emulate the > import command. The __import__() function or imp module doesn't help me > much because they only return the module. I want to register the module > with it's name in the current namespace. I can do it by: > > globals()[module_name] = __import__(module_name) > > But I don't think it's a good thing to access the global namespace > directly. There's nothing wrong with "accessing the global namespace directly" like that. In fact, that's pretty much the only way (though it's not in itself sufficient) to emulate the "import" statement when you want a dynamic import. In general, you need to (a) import with __imoprt__, (b) insert name into sys.modules dictionary, and (c) insert name into globals(). What you are doing above is the proper way to do that, IMHO. -Peter From b_orcutt at pobox.com Fri Oct 17 17:21:26 2003 From: b_orcutt at pobox.com (Bill Orcutt) Date: 17 Oct 2003 14:21:26 -0700 Subject: Forgetful Interpreter Message-ID: <4ecaae91.0310171321.1f40facb@posting.google.com> Having seen the number of lost souls asking questions about embedding Python in the archives of this group, I hesitate to add myself to their number, but I've hit a problem I can't quite get my head around. I have a simple C program that embeds a python interpreter to execute python commands and return stdout, and to a point everything works as intended. The problem that each command seems to be executed in its own context and knows nothing of what's come before. So if enter "print 2+2", I get back "4", but if I enter "a=2+2" then enter "print a", I get back the error, "a is undefined." My guess is that this has something to calling PyRun_SimpleString inside of a child process, but I can't get much further than this. Any assistance is appreciated. thanks -Bill //call this once at the beginning to initialize void * nyptho_doinit(t_gogo* x, short flag) { Py_Initialize(); char capture_stdout[] ="import sys, StringIO\n\sys.stderr=sys._capture=StringIO.StringIO()\n"; int rc = PyRun_SimpleString(capture_stdout); return x; } //this executes the command FILE * nyptho_exec(t_gogo* x, char * cmd, short bflag, short fflag) { int pfd[2],i,z=0; pid_t pid; FILE *fp; extern int errno; if (pipe(pfd) < 0) return(NULL); // errno set by pipe() if ( (pid = fork()) < 0) return(NULL); // errno set by fork() else if (pid == 0) // child { close(pfd[0]); // close all descriptors in childpid[] if (x->childpid[0] > 0) close(0); PyRun_SimpleString(cmd); //PyRun_SimpleString("import sys"); PyObject* sysmod = PyImport_ImportModule("sys"); PyObject* capobj = PyObject_GetAttrString(sysmod,"_capture"); PyObject* strres = PyObject_CallMethod(capobj,"getvalue",0); char * dodo = PyString_AsString(strres); strcpy(globalBuf,dodo); write(pfd[1], globalBuf, (long)strlen(globalBuf)); globalBuf[0]='\0'; _exit(127); //child exits } // parent close(pfd[1]); if ( (fp = fdopen(pfd[0], "r")) == NULL) return(NULL); x->childpid[fileno(fp)] = pid; // remember child pid for this fd return(fp); } From jegenye2001 at fw.hu Wed Oct 29 20:11:11 2003 From: jegenye2001 at fw.hu (Jegenye 2001 Bt) Date: Thu, 30 Oct 2003 02:11:11 +0100 Subject: Python versus VB References: <3fa057e2.14061399@news.dsl.pipex.com> Message-ID: Text processing with VB? Dear me... Well, try to explain to them how nice Python is and how ugly VB is. :-) Python is portable, VB is not. Python is easily readable -> maintainable vs VB which is.. my two cents... Mikl?s -- PRISZNY?K Mikl?s --- Jegenye 2001 Bt. ( mailto:jegenye2001 at parkhosting.com ) Egyedi szoftverk?sz?t?s, tan?csad?s Custom software development, consulting http://jegenye2001.parkhosting.com Simon Foster wrote in message news:3fa057e2.14061399 at news.dsl.pipex.com... > > I am meeting with a potential client next week to > discuss starting a new project. His preference is for > VB whereas I would prefer Python for obvious reasons ;-) > > Could anybody come up with a short list of the pros and > cons of the two languages (I am not terribly familiar > with the strengths/weaknesses of VB). This will be a > general-purpose text-processing type application with no > GUI required. > > -- > Simon Foster > Somewhere in the West of England From martin at v.loewis.de Thu Oct 2 16:11:15 2003 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 02 Oct 2003 22:11:15 +0200 Subject: Thread Safety In-Reply-To: <92c59a2c.0310021020.663d4cf2@posting.google.com> References: <92c59a2c.0310021020.663d4cf2@posting.google.com> Message-ID: MetalOne wrote: > Are atomic operations thread safe in Python? I don't understand the question. Atomic operations, by nature, can either completely succeed or completely fail - otherwise it would not be atomic. This is independent of Python. In general, you cannot cause inconsistency of Python's internal representation of objects by pure Python code executed in multiple threads, so Python itself is thread-safe. > Can immutable objects, > such as, strings, be created on one thread and then accessed by > another thread, without using locks? Yes. > Such operations are not guaranteed thread safe in Java due to caching > optimizations. But then, in Java, strings are not immutable, no? Regards, Martin From newsgroups at jhrothjr.com Fri Oct 17 19:39:52 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Fri, 17 Oct 2003 19:39:52 -0400 Subject: prePEP: Money data type References: Message-ID: I've made a few edits for spelling and grammar, but I haven't cleaned up everything, and I haven't made any substantive changes to the text. Do with it what you will. Substantive issues: 1. I've seen lots of strange rounding policies in various nooks and crannies. Is there any way of specifying a rounding policy that would be used and inherited by the result money object? 2. Money objects are presumably immutable, the same as all other numeric objects. I've edited item 4 to presume this. 3. I haven't looked at Tim Peter's fixed point module, so I don't know how he handled this. Formatting characters should come from the current locale, or else should be supplied by an extended format method. In fact, I'd make this a requirement: there should be a formatting method that would handle the most common commercial formatting requirements, including zero and asterisk fill, floating and fixed currency symbol, and blanking the entire output field when it is zero. Also trailing minus sign, and so forth. 4. Repr should round trip. That's basic Python. This means that repr() should return something that the money() constructor understands regardless of the current locale setting. Making it human readable is the responsibility of either str(), the % operator or a hypothetical .printf() method. 6. On operators. What happens to precision on multiplication and division? John Roth "Batista, Facundo" wrote in message news:mailman.183.1066424190.2192.python-list at python.org... Here I send it. Suggestions and all kinds of recomendations are more than welcomed. If it all goes ok, it'll be a PEP when I finish writing the code. Thank you. . Facundo ------------------------------------------------------------------------ PEP: XXXX Title: Money data type Version: $Revision: 0.1 $ Last-Modified: $Date: 2003/10/17 17:34:00 $ Author: Facundo Batista Status: Draft Type: Standards Track Content-Type: text/x-rst Created: 17-Oct-2003 Python-Version: 2.3.3 Abstract ======== The idea is to make a Money data type, basically for financial uses, where decimals are needed but floating point is too inexact. The Money data type should support the Python standard functions and operations. Rationale ========= The detail of the requeriments are in the `Requirements`_ section. Here I'll include all the decisions made and why, and all the subjects still being discussed. The requirements will be numbered, to simplify discussion on each point. As an XP exercise, I'll write the test cases before the class itself, so it'll comply exactly the requeriments of those tests. Please see them for an exact specification (and if you propose a different behaviour, please propose the corresponding test case if possible, thanks). Why Not Use Tim Peters' FixedPoint? -------------------------------------- As we'll see in Requeriments, there are items that FixedPoint does not satisfy, either because it doesn't do something or does it differently. It could be extended or modified to comply with the Requeriments, but some needs are specific to currency, and some features of FixedPoint are unnecessarilly complex for Money, so taking them out will make this class simplier. Anyway, sometime maybe one could be made subclass of the other, or just make one from both. The code of the Money class is based in large part on the code of Tim Peters' FixedPoint: thank you for your (very) valuable ideas. Open Issues ------------------- 6. About repr(). Should ``myMoney == eval(repr(myMoney))``? Requirements ============ 1. The syntax should be ``Money(value, [precision])``. 2. The value is one of the following: - another money (if you don't include *precision*, it will be inheritated) - int or long (default *precision*: 0):: Money(45): 45 Money(45, 2): 45.00 Money(5000000000,3): 5000000000.000 - float (*precision* is required):: Money(50.33, 3): 50.330 - string (*precision* is extracted from the string):: Money('25.32'): 25.32 Money('25.32', 4): 25.3200 - any other object that could be input to the long() or float() constructors. 3. Strings with floats in engineering notation will not be supported. This is an unecessary complication. 4. Precision must be a non negative integer. 5. Attributes ``decimalSeparator``, ``currencySymbol`` and ``thousandSeparator`` could be overloaded, just to easy change them subclassing. This same *decimalSeparator* is that used by the constructor when receives a string. Defaults are:: decimalSeparator = '.' currencySimbol = '$' thousandSeparator = '' 6. Calling repr() should not return str(self), because if the subclass indicates that ``decimalSeparator=''``, this could carry to a confusion. So, repr() should show a tuple of three values: IntPart, FracPart, Precision. 7. To comply the test case of Mark McEahern:: cost = Money('5.99') percentDiscount = 10 months = 3 subTotal = cost * months discount = subTotal * (percentDiscount * 1.0) / 100 total = subTotal - discount assertEqual(total, Money('16.17')) 8. To support the basic aritmetic (``+, -, *, /, //, **, %, divmod``) and comparison (``==, !=, <, >, <=, >=, cmp``) operators in the following cases: - Money op Money - Money op otherType - otherType op Money - Money op= otherType OtherType could be int, float or long. Automaticlly will be converted to Money, inheritating the precision from the other component of the operation (and, in the case of the float, maybe losing precision **before** the operation). When both are Moneys, the result has the larger of the two precisions. 9. To support unary operators (``-, +, abs``). 10. To support the built-in methods: - min, max - float, int, long (int and long are rounded by Money) - str, repr - hash - copy, deepcopy - bool (0 is false, otherwise true) 11. To have methods that return its components. The value of Money will be ``(int part) + (frac part) / (10 ** precision)``. - ``getPrecision()``: the precision - ``getFracPart()``: the fractional part (as long) - ``getIntPart()``: the int part (as long) 12. The rounding to be financial. This means that to round a number in a position, if the digit at the right of that position is bigger than 5, the digit at the left of that position is incremented by one, if it's smaller than 5 isn't:: 1.123 --> 1.12 1.128 --> 1.13 But when the digit at the right of that position is ==5. There, if the digit at the left of that position is odd, it gets incremented, otherwise isn't:: 1.125 --> 1.12 1.135 --> 1.14 Reference Implementation ======================== To be included later: - code - test code - documentation Copyright ========= This document has been placed in the public domain. From bromden at gazeta.pl.no.spam Sun Oct 19 03:16:39 2003 From: bromden at gazeta.pl.no.spam (bromden) Date: Sun, 19 Oct 2003 09:16:39 +0200 Subject: BaseHTTPRequestHandler - bypassing browser cache In-Reply-To: References: Message-ID: add to your response self.send_header('Cache-Control', 'no-cache') -- bromden[at]gazeta.pl From dave at 3dex.com Wed Oct 8 23:01:02 2003 From: dave at 3dex.com (Dave Benjamin) Date: Thu, 09 Oct 2003 03:01:02 GMT Subject: Code block literals In-Reply-To: References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> <92c59a2c.0310031345.57d20631@posting.google.com> Message-ID: Mike Rovner wrote: > Dave Benjamin wrote: > >>For instance, I always thought this was a cooler alternative to the >>try/finally block to ensure that a file gets closed (I'll try not to >>mess up this time... ;) : >> >>open('input.txt', { |f| >> do_something_with(f) >> do_something_else_with(f) >>}) >> >>Rather than: >> >>f = open('input.txt') >>try: >> do_something_with(f) >> do_something_else_with(f) >>finally: >> f.close() > > "Explicit is better than implicit" In that case, why do we eschew code blocks, yet have no problem with the implicit invocation of an iterator, as in: for line in file('input.txt'): do_something_with(line) This is not to say that I dislike that behavior; in fact, I find it *beneficial* that the manner of looping is *implicit* because you can substitute a generator for a sequence without changing the usage. But there's little readability difference, IMHO, between that and: file('input.txt').each_line({ |line| do_something_with(line) }) Plus, the first example is only obvious because I called my iteration variable "line", and because this behavior is already widely known. What if I wrote: for byte in file('input.dat'): do_something_with(byte) That would be a bit misleading, no? But the mistake isn't obvious. OTOH, in the more explicit (in this case) Ruby language, it would look silly: open('input.txt').each_line { |byte| # huh? why a byte? we said each_line! } I think this is important to point out, because the implicit/explicit rule comes up all the time, yet Python is implicit about lots of things! To name a few: - for loops and iterators - types of variables - dispatching via subclass polymorphism - coercion (int->float, int->long...) - exceptions (in contrast with Java's checked exceptions) - __magic_methods__ - metaclasses - nested scopes (compared to yesteryear's lambda x, y=y, z=z: ...) - list comprehensions In all of the above cases (with a bit of hesitation toward the voodoo of metaclasses) I think Python is a better language for it. On the other hand, Perl's implicit $_ variable is a good example of the hazards of implicitness; that can be downright confusing. So, it's not cut and dry by any means. If all you're saying is that naming something is better than not naming something because explicit is better than implicit, I'd have to ask why: a = 5 b = 6 c = 7 d = a + b e = c / 2 result = d + e return result Is any better than: ... return (a + b) + (c / 2) To me, it's the same issue. Why should I have to name something that I'm just going to return in the next statement, or pass as a parameter, and then be done with it? Does that really increase either readability or understandability? Why should I name something that I'm not going to ask for later? > Even your example clearly shows that try block is much more readable and > understandable. > That's why it's being considered evil by majority of python developers. Readability is a moving target. I think that the code block syntax strikes a nice balance between readability and expressiveness. As far as what the majority of Python developers consider evil, I don't think we've got the stats back on that one. >>But the anonymous version still looks more concise to me. > > Python prioritize things diferently than other languages. > It's not an APL. "Readability counts" This is nothing like APL... if anything, it's like Smalltalk, a language designed to be readable by children! I realize that APL sacrificed readability for expressiveness to an uncomfortable extreme, but I really think you're comparing apples and oranges here. List comprehensions are closer to APL than code blocks. Dave From Raymond.Wiker at fast.no Mon Oct 6 07:09:00 2003 From: Raymond.Wiker at fast.no (Raymond Wiker) Date: Mon, 06 Oct 2003 13:09:00 +0200 Subject: Python syntax in Lisp and Scheme References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> <92c59a2c.0310031345.57d20631@posting.google.com> <36wr81qfxg9.fsf@chagall.ti.uni-mannheim.de> Message-ID: <8665j2k4hf.fsf@raw.grenland.fast.no> Matthias writes: > 1.) Inventing new control structures (implement lazy data structures, > implement declarative control structures, etc.) > => This one is rarely needed in everyday application programming and > can easily be misused. This is, IMHO, wrong. One particular example is creating macros (or read macros) for giving values to application-specific data structures. > You have to know if you want a sharp knife (which may hurt you when > misused) or a less sharper one (where it takes more effort to cut > with). It is easier to hurt yourself with a blunt knife than a sharp one. -- Raymond Wiker Mail: Raymond.Wiker at fast.no Senior Software Engineer Web: http://www.fast.no/ Fast Search & Transfer ASA Phone: +47 23 01 11 60 P.O. Box 1677 Vika Fax: +47 35 54 87 99 NO-0120 Oslo, NORWAY Mob: +47 48 01 11 60 Try FAST Search: http://alltheweb.com/ From keflimarcusx at aol.comNOSPAM Fri Oct 24 21:16:47 2003 From: keflimarcusx at aol.comNOSPAM (KefX) Date: 25 Oct 2003 01:16:47 GMT Subject: Strange Hotshot problem... References: <20031024204631.28274.00000067@mb-m27.aol.com> Message-ID: <20031024211647.28132.00000064@mb-m27.aol.com> Well, I found a rather unhelpful non-solution (just posting about it so nobody else suggests it). I figured that the Work() function (being called the most often given the architecture of the plugin, and the only one called from the C++ code while outputting sound) would probably have the biggest bottleneck, so I renamed my Work function to Work_Impl, and added a new Work function with this: def Work(num_samples): if _profiler is not None: return _profiler.runcall(Work_Impl, num_samples) else: return Work_Impl(num_samples) This technically worked (my code finally produced a readable log in the proper place). However, it was a failure in that this seemed to circumvent Psyco completely (making my code WAY too slow), and the results weren't too helpful in any case. An obvious solution is to make sure to call psyco.bind(Work_Impl), and while this did speed it up I get no information on the functions that Work_Impl called. Is there any other way to profile code that uses Psyco? (Other than the older 'profile' module, which is probably even less likely to work well...) From jjl at pobox.com Wed Oct 15 16:24:47 2003 From: jjl at pobox.com (John J. Lee) Date: 15 Oct 2003 21:24:47 +0100 Subject: General Numerical Python question References: <500a4565.0310112113.a0840e8@posting.google.com> <500a4565.0310131915.148ce3f5@posting.google.com> <500a4565.0310140541.4f4fd35f@posting.google.com> <%xVib.26249$gi2.16759@fed1read01> Message-ID: <87y8vm6ygg.fsf@pobox.com> Michael Ressler writes: > In article <%xVib.26249$gi2.16759 at fed1read01>, Tim Hochberg wrote: [...] > You are right, of course, but I was trying to be clear, not fast. The > point is that you could replace that sum with the sum of the squares > and crossproducts, and thus get a running standard deviation, for > example. The trick of Numeric is thinking about problems in new ways > which are far different from what the original author is used to with > loops. [...] Perhaps part of the trick is to know when to leave Numeric behind and use Pyrex. John From steve at ninereeds.fsnet.co.uk Thu Oct 30 21:10:26 2003 From: steve at ninereeds.fsnet.co.uk (Stephen Horne) Date: Fri, 31 Oct 2003 02:10:26 +0000 Subject: Reverting (key, value) pairs in a dictionary References: <3f9ec63f$1@brateggebdc5.br-automation.co.at> <3f9f9d2a$1@brateggebdc5.br-automation.co.at> <3FA1795B.5000601@bu.edu> Message-ID: On Thu, 30 Oct 2003 16:27:13 -0500, Shu-Hsien Sheu wrote: >Hi, > >How do you turn a dictionary of : into >: , when there is no duplicate values? >For instance, I have a dictionary kk: >kk = {'abc': ['B', 'C', 'D', 'E'], 'def':['G', 'H']} > >and I want a new dictionary newkk which looks like: >newkk = {'B':'abc', 'C':'abc', 'D':'abc', 'E':'abc', 'G':'def', 'H':'def'} There will be loads of ways of doing this. I would probably use a list comprehension such as... result = dict( [(d, k) for k, l in .items () for d in l] ) Generator comprehensions may make this a tad neater in Python 2.4 ;-) List comprehensions aren't to everyones taste, though, so some people would probably find the following clearer... result = {} for k, l in .items () : for d in l : result [d] = k The only flaw in your own code is that creating the list of lists in 'new' is redundant - it is more efficient to create the dictionary directly. -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From mikit at zoran.co.il Wed Oct 15 04:55:32 2003 From: mikit at zoran.co.il (Miki Tebeka) Date: 15 Oct 2003 01:55:32 -0700 Subject: waiting for a program run by popen3() to end References: Message-ID: <6250403b.0310150055.422a18ad@posting.google.com> Hello Rajarshi, > o,i,e = os.popen3('/usr/local/adapt/bin/descmng -g') > o.write('\n%s\n\n' % (redpick)) > o.close() > time.sleep(1) > os.system('mv set5 gendes.in && rm set? outputdesc.txt') If you're not reading the program output you can use os.system which will wait for it to end. > Is there any other way out (apart from dumping commands to a file and > piping them to my program in a fork())? On Unix like systems there is popen2.Popen3 (or Popen4) --- from popen2 import Popen3 print "Running child" p = Popen4("my_process arg1 arg2") print "Waiting" p.wait() # Will wait for process to end print "And we got:" print p.fromchild.read() --- HTH. Miki From peter at engcorp.com Thu Oct 2 14:08:18 2003 From: peter at engcorp.com (Peter Hansen) Date: Thu, 02 Oct 2003 14:08:18 -0400 Subject: question to start_new_thread in thread References: Message-ID: <3F7C6992.69B05F18@engcorp.com> Thomas Schmid wrote: > > I wrote a tcp server which listens on a port. When he gets a new > connection, he starts a new thread like this: > thread.start_new_thread(self.ConnectionHandler, (conn,)) > where conn is the socket for the connection. > > After I started the server, I can see one running process under Linux, > which is ok. But once I connected to the Server, I always see two > processes where one is the parent of the other. I think this should be > normal behavier as long as the connection is established. But I also > see two processes when the connection is finished. So I thought that I > don't quit the thread for the connection correctly. Then I should see > three processes after I started a second connection, but I don't. > There are alwys just the two of them. > > My question now is: does python make a thread pool where it does not > really quit the threads but instead reuses them if necessary? Or does > it need a second process to administrate threads? I can't answer this other than to say stop using "thread" and start using "threading". If you are using "threading" and your threads stop, they disappear as you would expect. I don't think anyone is supposed to use "thread" anymore... and it might solve your problems. -Peter From corey.coughlin at attbi.com Fri Oct 10 20:00:48 2003 From: corey.coughlin at attbi.com (Corey Coughlin) Date: 10 Oct 2003 17:00:48 -0700 Subject: Python syntax in Lisp and Scheme References: <4ullrtrdoq.fsf@vex.net> Message-ID: You are mostly correct about Japanese, I took a year of it in college and it is a fairly standard SOV language. (Like Latin, oddly enough.) And I'm sure you're right about RPN vs. PN, I always get those confused. Which is kind of the point, really, having studied math since I was a kid I got used to stuff like "y = mx + b", can you blame me if I have an easier time with "y = m*x + b" as opposed to "(let y (+ (* m x) b))" (Forgive me if the parenthesis on that are off, the newsreader editor doesn't match them, and maybe I need a 'setq' instead of a 'let' or some other thing, I'm not entirely sure.) (And again, is the point getting more clear?) And thanks for backing me up on car's and cdr's, I never could understand why a language ostensibly designed for 'list processing' has such a bizarre way to reference items in a list. But is (nth 10 mylist) really as easy as mylist[10]? My intuition says no, not really. Sure, I can appreciate looking at things in different ways, and it is nice to learn new things and see how they apply. But if John Grisham learns Japanese, does that mean he should write all his books in Japanese? Or should he stick to English? I suppose if I were a real CS guy (I'm actually an electrical engineer, the scheme course was one of the two CS courses I took in college, so I'm mostly self taught) or if I worked within a big group of Lisp programmers, I would probably feel more comfortable with it. Since I now mostly work as an isolated programmer for other engineers, and the last language I was using for everything was C, Python is a huge improvement, and it doesn't give me too much of a headache. Sure, it's not perfect. But there's no way I'm going to adopt Lisp as a perfect language anytime soon. That is, if I want to keep hitting my deadlines and getting paid. And sure, I may get comfortable and miss out on cool stuff, but on the upside, I'll be comfortable. Oh, and if I'm writing in this thread, I suppose I should comment on how bad lisp macros are. Except I know nothing about them. But it seems like most languages have dark corners like that, where you can do thing above and beyond your standard programming practices. Python has metaclasses, which give me a headache most of the time, so I don't really use them at all. But I seem to get plenty of stuff done without using them, so it works for me. If you really have to use macros in Lisp to get things done, that sounds kind of troublesome, but it would be consistent, it always seemed like really working well in Lisp requires you to really know how everything works all at once, which always kind of struck me as kind of a downside. But as I said, I'm not the big CS guru, so Lisp just may not be for me in general. Ah well, I suppose I'll get by with Python. :D Albert Lai wrote in message news:<4ullrtrdoq.fsf at vex.net>... > corey.coughlin at attbi.com (Corey Coughlin) writes: > > > (Not to mention car, cdr, cadr, and > > so on vs. index notation, sheesh.) > > Yes, that is a real regret. It should have been useful to support > a kind of (nth 10 mylist) straight from the Scheme standard library. > > > Using parentheses and rpn everywhere makes lisp very easy > > to parse, but I'd rather have something easy for me to understand and > > That's why I prefer python, you > > get a nice algebraic syntax with infix and equal signs, and it's easy > > understand. > > Python is > > intuitive to me out of the box, and it just keeps getting better, so I > > think I'll stick with it. > > First, a minor correction: Lisp/Scheme is like (* 1 2) and that is > Polish Notation or prefix; Reverse Polish Notation or postfix would be > like (1 2 *). > > From what I heard about the Japanese language I have formed the > possibly oversimplified impression that it is largely postfix. > Whereas in English we say "I beat you", they may say something like "I > you beat". So I suppose all of the existing programming notations - > Lisp's and Cobol's (* 1 2) and MULTIPLY 1 BY 2, Fortran's "intuitive" > 1+2, and OO's one.add(two) - are very counterintuitive to them, and > they would really like the way of HP calculators, no? > > And I suppose the ancient Romans (and even the modern Vaticans) would > laugh at this entire dilemma (or trilemma?) between ___fixes. > > Intuition is acquired. It is purely a product of education or > brainwashing. There is nothing natural about it. And since it is > acquired, you may as well keep acquiring new intuitions and see more > horizons, rather than keep reinforcing old intuitions and stagnate. > Appreciating a foreign language such as Japanese some day is not a bad > idea. From jrm at ccs.neu.edu Thu Oct 23 12:11:30 2003 From: jrm at ccs.neu.edu (Joe Marshall) Date: Thu, 23 Oct 2003 12:11:30 -0400 Subject: Why don't people like lisp? References: <8Nnlb.619$I04.380@newsread4.news.pas.earthlink.net> Message-ID: "Andrew Dalke" writes: > As an example, here's a quick hack of a way to parse a simple > stack-based language and make a native Python function out > of it.... [code elided] Let's take on something more complicated. A lot more complicated. Suppose I am solving problems that are best expressed non-deterministically, and I need a domain language that has the following non-deterministic constructs: EITHER -- Used as a mechanism to combine expressions non-deterministically as in (either ...) or, if you prefer infix either either or possibly either: Whatever the syntax, EITHER introduces a choice-point. It begins by attempting evaluation of the first subexpression. If that subexpression returns a value, EITHER returns that value. If the subexpression `fails', EITHER attempts to evaluate the next subexpression. The first subexpression to produce a value is the value of the whole expression. If all subexpressions `fail', then the EITHER form itself `fails'. FAIL -- Causes an expression to `fail'. This means that control is immediately returned to the nearest enclosing EITHER form (backtracking) which will then proceed to attempt to evaluate the next subexpression. If the current subexpression is the last form in the enclosing EITHER, the EITHER form propagates the failure up to the next enclosing EITHER. ALL-VALUES -- Used to collect all possible values returned by a non-deterministic expression. If all possible choice-points in the expression yield failure, then ALL-VALUES deterministically returns an empty collection. Thus failures cannot propagate past an ALL-VALUES form. Syntax could be something like (all-values ) or all-values or all-values { } ONE-VALUE -- Returns the first possible value returned by a non-deterministic expression, or some sort of distinguished token if no value can be found. Also blocks propagation of `failure'. Since I am unsure of the entire details of the problem I am solving, I also wish to have these forms integrated into a reasonably complete computer language. Obviously this new language will have syntactic differences from anything other language (via the introduction of these forms), but by and large, the subexpressions of this new language ought to be something familiar. So if we extended Lisp, for example, I could write: (defun an-integer-between (low high) (if (> low high) (fail) (either low (an-integer-between (+ low 1) high)))) (defun pythagorean-triples (n) (all-values (let ((opposite (an-integer-between 1 n)) (adjacent (an-integer-between 1 n)) (hypotenuse (an-integer-between 1 n))) (if (= (+ (* opposite opposite) (* adjacent adjacent)) (* hypotenuse hypotenuse)) (list opposite adjacent hypotenuse) (fail))))) and (pythagorean-triples 10) would return ((3 4 5) (4 3 5) (6 8 10) (8 6 10)) on the other hand, if we extended Python, I could write: def anIntegerBetween(low, high): if(low > high): fail either: return low return anIntegerBetween(low + 1, high) def pythagoreanTriples(n): all-values: opposite = anIntegerBetween(1, n) adjacent = anIntegerBetween(1, n) hypotenuse = anIntegerBetween(1, n) if(hypotenuse * hypotenuse == opposite * opposite + adjacent * adjacent): return [opposite, adjacent, hypotenuse] fail and I'd get back something like [[3, 4, 5], [4, 3, 5], [6, 8, 10], [8, 6, 10]] ----------------- This is a tricky problem, but one approach in Lisp is to make ALL-VALUES and EITHER be rather complicated macros. The advantage of doing this is that the rest of the language, LET, DEFUN, *, +, conditionals, strings, CLOS, i.e. everything, is pretty much intact. Since I know that Lisp is a `reasonably complete' substrate, I don't have to worry about designing and parsing an entire non-deterministic language. I can just graft my extension on to something people will be familiar with. Yes, I know that adding non-determinism to the language is going to mean a change in how people would program (how could it not?!) but I'm attempting to *minimize* the intellectual burden by making the non-deterministic language very similar to one that already exists. How would one approach this in Python? If Python had macros, then one could take exactly the same approach as Lisp. What does a Pythonista do when encountering a problem like this? (I'm actually curious, not raising rhetorical questions. I assume that there is *something* one would do, but not being a python hacker, I don't know what it is.) From peter at engcorp.com Tue Oct 21 14:11:30 2003 From: peter at engcorp.com (Peter Hansen) Date: Tue, 21 Oct 2003 14:11:30 -0400 Subject: writing code over several lines References: <62e9c66e.0310170556.328072e8@posting.google.com> <3F9531F6.3D1DD233@engcorp.com> <3F9556A3.92F1106C@engcorp.com> <7xd6cqinpn.fsf@ruckus.brouhaha.com> <3F9558D9.E7F720A5@engcorp.com> <7x1xt6bksk.fsf@ruckus.brouhaha.com> Message-ID: <3F9576D2.5BF5AF45@engcorp.com> Paul Rubin wrote: > > Peter Hansen writes: > > > Tuples probably aren't faster, but they do use less memory. > > > > Again, as I recall the past discussions, not significantly so. > > > > They still have only four bytes (a pointer) per element, and surely for > > any tuple or list where one could possibly be concerned about memory > > consumption the number of elements far outweighs the overhead associated > > with the structure itself (which is probably on the order of a few bytes > > anyway). > > Lists allocate memory for extra elements, so list.append doesn't have > to copy the whole list around every time you call it. Ah, I see. How much would that consume in, say, the example as given? Is that a significant amount, enough to be concerned about? Is there a published algorithm behind this, or is it just some magic of the Timbot's that would be found only in the source? -Peter From Jon.Kare.hellan at uninett.no Fri Oct 17 02:45:10 2003 From: Jon.Kare.hellan at uninett.no (Jon =?iso-8859-1?q?K=E5re?= Hellan) Date: 17 Oct 2003 08:45:10 +0200 Subject: xls to txt References: Message-ID: "Enrique" writes: > Hello all, > I`m searching in www, win32com docs, o'really examples, ... and i can?t find > anything that i can use. > > i wan`t to make a simple script to pass an excel file to txt file. > > where can i find the methods to work, or sample code?? > > Thanks For people who want to do this in a Unix environment, Gnumeric 1.2.1 comes with the "ssconvert" utility. It is able to convert between the various formats supported by Gnumeric, including Excel, text and XML. Regards Jon K?re From raffael at mediaone.net Sun Oct 12 15:54:59 2003 From: raffael at mediaone.net (Raffael Cavallaro) Date: 12 Oct 2003 12:54:59 -0700 Subject: Python syntax in Lisp and Scheme References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> <%hihb.4368$dn6.2921@newsread4.news.pas.earthlink.net> Message-ID: Pascal Costanza wrote in message news:... > Lispniks are driven by the assumption that there is always the > unexpected. No matter what happens, it's a safe bet that you can make > Lisp behave the way you want it to behave, even in the unlikely event > that something happens that no language designer has ever thought of > before. And even if you cannot find a perfect solution in some cases, > you will at least be able to find a good approximation for hard > problems. This I believe is the very crux of the matter. The problem domain to which lisp has historically been applied, artificial intelligence, more or less guaranteed that lisp hackers would run up against the sorts of problems that no one had ever seen before. The language therefore evolved into a "programmable programming language," to quote John Foderaro (or whoever first said or wrote this now famous line). Lisp gives the programmer who knows he will be working in a domain that is not completely cut and dried, the assurance that his language will not prevent him for doing something that has never been done before. Python gives me the distinct impression that I might very well run up against the limitations of the language when dealing with very complex problems. For 90% of tasks, even large projects, Python will certainly have enough in its ever expanding bag of tricks to provide a clean, maintainable solution. But that other 10% keeps lisp hackers from using Python for exploratory programming - seeking solutions in problem domains that have not been solved before. From peter at engcorp.com Thu Oct 23 19:11:31 2003 From: peter at engcorp.com (Peter Hansen) Date: Thu, 23 Oct 2003 19:11:31 -0400 Subject: [OT] Inuit? Eskimo? References: <20031020163642.GA5539@nl.linux.org> <4vre61-ku2.ln1@beastie.ix.netcom.com> <8765ii53yf.fld@barrow.com> <87wuaxymjz.fld@barrow.com> <3F970150.B48835B3@engcorp.com> <87k76wzy5b.fld@barrow.com> <3F971A95.C4C8B300@engcorp.com> <877k2wzk02.fld@barrow.com> <3F97B245.683BED86@engcorp.com> <87brs8xc84.fld@barrow.com> Message-ID: <3F986023.4EE284CD@engcorp.com> Floyd Davidson wrote: > > In Canada and Greenland Inuit people will not appreciate the > term "Eskimo" as a specific term for them when used by locals. > That is particularly true of Canadians. They do not seem to > mind the general (correct) use of the term by others who do not > have any intent to insult them. Okay, thanks for taking the time to clarify, Floyd! The impression I get then is that because some people (although I think more so in the distant past than in recent years?) might hold ill will towards their northern neighbours, the rest of us with nothing against them might as well avoid the term Eskimo entirely, to minimize the risk of someone making false assumptions about us and how we feel about them. > Note that in Canada and Greenland, *all* Eskimos are Inuit, > hence there is little need to use that term to describe those > people. Probably where the institutionalized advice comes from in the first place. If all Eskimos in Canada are Inuit, and all Inuit can be called Eskimos (but only by those who don't have intent to insult them, apparently :-), then it's best to avoid the whole issue and just use the term Inuit. -Peter From ianb at colorstudy.com Mon Oct 20 21:41:38 2003 From: ianb at colorstudy.com (Ian Bicking) Date: Mon, 20 Oct 2003 20:41:38 -0500 Subject: prePEP: Money data type In-Reply-To: Message-ID: On Monday, October 20, 2003, at 01:49 PM, Batista, Facundo wrote: > #- As a side note, it's quite possible to spend inordinate > #- amounts of attention on formatting. I would suggest that > #- a fundamental 'money' class should first of all nail down > #- the *computation* issues (just that variety of rounding > #- specs is gonna be SUCH a bear...!) and receiving and > > It's very temptating to str() just represent the number, and if you > want > something else, overload it. > > The problem is that decimalSeparator and thousandSeparator are > important to > parse the string in the constructor (if I need str() to give me a ',' > as > decimal point, I also need to supply a ',' as decimal point to the > constructor). Such a "smarter" constructor should perhaps be a separate class method, or be explicitly controlled with extra arguments. Subclasses could still add this functionality, but the generic Money class would remain generic. For instance, Money.parse('$100.00'), Money.parse('$100.00', decimalSeparator='.'), Money.parse('100Y', currency='Y'), etc. Also, while you can use potentially ambiguous heuristics for this parse constructor, the main constructor can be more strict -- it's hard to add strictness, but easier to take it away. I would expect that the main constructor take only a string or a number-like-object (int, float, fixed point, etc), with other information passed through keyword arguments. I would prefer the string be a Python style of number, i.e., unambiguously and strictly with '.' for decimals, and no thousands-separator. But then that matches my locale, so I suppose I'm biased -- but I see the sole reason for using that string to be that Python float literals cannot precisely express a fixed-point number. If a fixed-point literal existed, then I would prefer that no string be allowed -- the parse constructer better highlights what is being done in that case. (A fixed-point literal would be quite nice... a fixed-point builtin would be quite nice...) -- Ian Bicking | ianb at colorstudy.com | http://blog.ianbicking.org From FBatista at uniFON.com.ar Mon Oct 27 13:33:27 2003 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Mon, 27 Oct 2003 15:33:27 -0300 Subject: list behavior Message-ID: #- Not what I expected, then I came to the conclusion that #- [].append(value) returns 'None', why? Because it's the defined behaviour, ;) >>> help([].append) Help on built-in function append: append(...) L.append(object) -- append object to end It just modifies the object, return None: >>> l = [3] >>> a = l.append(5) >>> l [3, 5] >>> a >>> repr(a) 'None' . Facundo From goodger at python.org Fri Oct 17 10:26:43 2003 From: goodger at python.org (David Goodger) Date: Fri, 17 Oct 2003 10:26:43 -0400 Subject: For variables outside loop causes exception In-Reply-To: <000701c394b9$f3a1e580$6805e640@amd950> References: <000701c394b9$f3a1e580$6805e640@amd950> Message-ID: <3F8FFC23.6050609@python.org> Gordon Williams wrote: > for i, obsData in enumerate(epochData): > Pcor[i] = obsData[3] > Xs[i] = obsData[4] > > Asub, Lsub= Solve_all.model_matrix(Xs[:i+1], Pcor[:i+1],Xr) > > The exception is: > > Asub, Lsub= Solve_all.model_matrix(Xs[:i+1], Pcor[:i+1],Xr) > UnboundLocalError: local variable 'i' referenced before assignment Could epochData be empty? If so, i and obsData will not be declared for that call. Local variables are not kept between function calls. -- David Goodger From adalke at mindspring.com Sat Oct 4 02:56:01 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Sat, 04 Oct 2003 06:56:01 GMT Subject: Iteration on file reading References: <3f7ca9ea$1_1@themost.net> Message-ID: <5aufb.1528$gA1.1193@newsread3.news.pas.earthlink.net> Paul McGuire: > def lineReader( strm ): > while 1: > yield strm.readline().rstrip("\n") > > for f in lineReader( stdin ): > print ">>> " + f You can simplify that with the iter builtin. for f in iter(stdin.readline, ""): print ">>> " + f (Hmm... maybe I should test it? Naaaaahhh.) Andrew dalke at dalkescientific.com From pwatson at redlinec.com Mon Oct 20 12:30:10 2003 From: pwatson at redlinec.com (Paul Watson) Date: Mon, 20 Oct 2003 11:30:10 -0500 Subject: boot script References: <3f931146$0$9523$79c14f64@nan-newsreader-02.noos.net> <3F93E3E8.F29C69B0@engcorp.com> Message-ID: <3f940d9f$1_1@themost.net> "Peter Hansen" wrote in message news:3F93E3E8.F29C69B0 at engcorp.com... > ataraxia2500 wrote: > > > > I wrote a tiny python script and I'd like to execute it on boot time and > > I'd like to execute it after all the boot script and services have been > > started if u see what I mean. > > Great to hear! Let us know how it works out... ;-) > > -Peter This sounds like an operating system question rather than a Python question. Are you asking a question about using the UNIX init process or integrating into the Windows registry startup settings? If so, those are not Python questions. From jatwood at cvpjaws03.dhcp.cv.hp.com Mon Oct 27 13:10:57 2003 From: jatwood at cvpjaws03.dhcp.cv.hp.com (John Atwood) Date: Mon, 27 Oct 2003 18:10:57 +0000 (UTC) Subject: Static typing References: Message-ID: Pascal Costanza wrote: >John Atwood wrote: >> Pascal Costanza wrote: >>>No, you definitely can do a lot of things with macros in Lisp that are >>>impossible to do in other languages. There are papers that show this >>>convincingly. Try >>>ftp://publications.ai.mit.edu/ai-publications/pdf/AIM-453.pdf for a >>>start. Then continue, for example, with some articles on Paul Graham's >>>website, or download and read his book "On Lisp". >> >> That's a great paper; however, see Steele's later work: >> http://citeseer.nj.nec.com/steele94building.html > >Yes, I have read that paper. If you want to work with monads, you >probably want a static type system. > >(And I think he still likes Scheme and Lisp. ;) Perhaps, but the paper shows convincingly that statically typed languages can do a lot of things that Lispers use macros for. Work in meta-programming, aka mult-stage programming, shows how to more finely control the power of macros, reflection, etc. See, e.g.: http://citeseer.nj.nec.com/sheard00accomplishments.html http://citeseer.nj.nec.com/taha99multistage.html John From keflimarcusx at aol.comNOSPAM Mon Oct 27 02:07:04 2003 From: keflimarcusx at aol.comNOSPAM (KefX) Date: 27 Oct 2003 07:07:04 GMT Subject: Newbie: Classes References: <20031027015216.27688.00000195@mb-m04.aol.com> Message-ID: <20031027020704.27688.00000199@mb-m04.aol.com> >Yeah, that's right. Do it like this instead: >def __mul__(self, m): > r *= m > i *= m > return Complex(r, m) err...I meant this for the last line: return Complex(r, i) - Kef From ianb at colorstudy.com Mon Oct 6 11:15:00 2003 From: ianb at colorstudy.com (Ian Bicking) Date: Mon, 06 Oct 2003 10:15:00 -0500 Subject: Webware vs. PHP - performance comparision!!! In-Reply-To: <478105403.20031006125530@murator.com.pl> References: <1065429559.11620.12.camel@lothlorien> <478105403.20031006125530@murator.com.pl> Message-ID: <1065453299.12684.21.camel@lothlorien> On Mon, 2003-10-06 at 05:55, JZ wrote: > Hello Ian, > > Monday, October 6, 2003, 10:39:19 AM, you wrote: > > > I don't think this testing code is reliable. When I use ab > > (ApacheBench, comes with the Apache distribution) > > Hmm, I am trying to solve problem with my Webware application. It's > behavior is strange. It works quite good.... but sometime it hangs for > several seconds and I do not why. I changed max. nr of concurent > servlets from 20 to 100 but it did not helped? :( I am finding > solution so I check the problem from different points of view. There was also a problem in your code, if 0 < i < 100: ... This isn't proper Python, it's interpreted as (0 < i) < 100. Since you are using wget with the mirror option, the stalling is probably in how wget interprets the pages -- does it mirror 100 pages (the loop size in PHP), or does it mirror until it decides there's an infinite depth of pages? > > I get something like 130 requests/sec for the Python servlet, and > > 250 requests/sec for the PHP script (though without MMCache). > > But PHP is still faster, isn't it? MMCache can speed up PHP to 10x. Yes, PHP is faster in this instance. As some other people have noted, Webware has more intermediary steps for each request. I don't know much about MMCache, but I doubt it can do anything close to 10x when presented with a trivial script, and I expect the benchmarking of significant applications give much different results than this benchmarking of a trivial application. A trivial application only measures the basic connection overhead. > But the real problem is as I wrote abowe. My Webware&Cheetah > application hangs for several seconds. It appears from time to time. > It is confusing. > > > To do the tests I run "ab -n 1000 http://localhost/whatever" > > Where can I find binary version? It comes with Apache. Since you are on Windows, I don't know where in the Apache distribution it would be. Debian puts it in /usr/sbin/ab > > To test *Python's* speed vs. PHP, you'd have to use mod_python -- it's > > the only Python *environment* that is equivalent to PHP (well, PHP as > > CGI is like Python as CGI, but that's not a realistic test > > I am using mod_webkit.dll which is even faster than mod_python > acordint to manual: > http://webware.sourceforge.net/Webware-0.8.1/WebKit/Docs/InstallGuide.html#mod-python That's in the context of Webware. Webware's ModPythonAdapter doesn't actually run servlets in the Apache process, it just uses a mod_python handler to connect to the separate Webware process. mod_webkit does the same thing, only written in C. Ian From bokr at oz.net Wed Oct 1 18:43:40 2003 From: bokr at oz.net (Bengt Richter) Date: 1 Oct 2003 22:43:40 GMT Subject: PEP-0263 and default encoding References: <3f782aef-bdbbd6f1-a72a-4a6c-8b23-c4915b89a61f@news.szn.dk> Message-ID: On 30 Sep 2003 23:40:53 +0200, martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) wrote: >Klaus Alexander Seistrup writes: > >> And while I understand the problem, I cannot fathom why Python >> doesn't simply rely on the encoding I have specified in site.py, >> which then calls sys.setdefaultencoding(). > >There are several reasons. Procedurally, there was no suggestion to do >so while the PEP was being discussed, and it was posted both to >comp.lang.python and python-dev several times. At the time, the most >common comment was that Python should just reject any user-defined >encoding, and declare that source code files are always UTF-8, >period. The PEP gives some more flexibility over that position. > >Methodically, requiring the encoding to be declared in the source code >is a good thing, as it allows to move code around across systems, >which would not be that easy if the source encoding was part of the >Python installation. Explicit is better than implicit. > How about letting someone in Klaus' situation be explicit in another way? E.g., python -e iso-8859-1 the_unmarked_source.py Hm, I guess to be consistent you would have to have some way to pass -e info into any text-file-opening context, e.g., import, execfile, file, open, etc. In such case, you'd want a default. Maybe it could come from site.py with override by python -e, again with override by actual individual file-embedded encoding info. But being the encoding guru, you have probably explored all those thoughts and decided what you decided ;-) Care to comment a little on the above, though? >> Would anyone care to explain why the community has chosen to >> inconvenience the user for each python script with non-ASCII >> characters, rather than using the default encoding given in the >> site.py configuration file? > >It is not clear to my why you want that. There are several >possible rationales: > >1. You are have problem with existing code, and you are annoyed > by the warning. Just silence the warning in site.py. That's not the same as giving a proper encoding interpretation, is it? (Though in comments it wouldn't matter much). > >2. You are writing new code, and you are annoyed by the encoding > declaration. Just save your code as UTF-8, using the UTF-8 BOM. YMMV with the editor you are using though, right? > >In neither case, relying on the system default encoding is necessary. Hm, for python -e to work, I guess all the library stuff would have to be explicitly marked, or the effect would have to be deferred. Hm2, is all internal text representation going to wind up wchar at some point? Regards, Bengt Richter From jacek.generowicz at cern.ch Fri Oct 17 06:39:09 2003 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 17 Oct 2003 12:39:09 +0200 Subject: [OT] Knuth's rewards [Was: Python syntax in Lisp and Scheme] References: Message-ID: mertz at gnosis.cx (David Mertz) writes: > Jacek Generowicz wrote previously: > |> Could you afford to pay $327.68 for every bug found in your glorious > |> software? > |Anyone know how Knuth arrives at the amounts he offers ? > |(He also offers $2.56 for errors in his books.) > > Surely you recognize powers of two? :-). Yes, but not, apparently, if you add a little noise, such as a "." (as I already mentioned elsewhere). > Apparently, so far 8 errors have been found in AoCP, and 15 in TeX.... What? It can't be ... he can't be _that_ confident? That's insane. Well, I guess that he's under no obligation to keep it up, should things get out of hand. (I was thinking that he maybe doubles it after a year in which no bugs were found, and maybe halves it when one is found ... or similar) Does he state anywhere what his policy is ? How do we persuade Microsoft to adopt the same strategy ? From adalke at mindspring.com Thu Oct 9 14:45:47 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Thu, 09 Oct 2003 18:45:47 GMT Subject: Python syntax in Lisp and Scheme References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> <92c59a2c.0310031345.57d20631@posting.google.com> <6CZgb.3273$dn6.860@newsread4.news.pas.earthlink.net> <3F853D60.9E133724@setf.de> Message-ID: james anderson: > i realize that this thread is hopelessly amorphous, but this post did > introduce some concrete issues which bear concrete responses... Thank you for the commentary. > i got only as far as the realization that, in order to be of any use, unicode > data management has to support the eventual primitive string operations. which > introduces the problem that, in many cases, these primitive operations > eventually devolve to the respective os api. which, if one compares apple and > unix apis are anything but uniform. it is simply not possible to provide them > with the same data and do anything worthwhile. if it is possible to give some > concrete pointers to how other languages provide for this i would be grateful. Python does it by ignoring the respective os APIs, if I understand your meaning and Python's implementation correctly. Here's some more information about Unicode in Python http://www.python.org/peps/pep-0100.html http://www.python.org/peps/pep-0261.html http://www.python.org/peps/pep-0277.html http://www.python.org/doc/current/ref/strings.html http://www.python.org/doc/current/lib/module-unicodedata.html http://www.python.org/doc/current/lib/module-codecs.html > and i have no idea what people do with surrogate pairs. See PEP 261 listed above for commentary, and you may want to email the author of that PEP, Paul Prescod. I am definitely not the one to ask. > yes, there are several available common-lisp implementations for http clients > and servers. they offer significant trade-offs in api complexity, > functionality, resource requirements and performance. And there are several available Python implementations for the same; Twisted's being the most notable. But the two main distributions (and variants like Stackless) include a common API for it, which makes it easy to start, and for most cases is sufficient. I fully understand that it isn't part of the standard, but it would be useful if there was a consensus that "packages X, Y, and Z will always be included in our distributions." > if one needs to _port_ it to a new lisp, yes. perhaps you skipped over the > list of lisps to which it has been ported. if you look at the #+/- > conditionalization, you may observe that the differences are not significant. You are correct, and I did skip that list. Andrew dalke at dalkescientific.com From tayss_temp at yahoo.com Sat Oct 11 03:48:39 2003 From: tayss_temp at yahoo.com (Tayss) Date: 11 Oct 2003 00:48:39 -0700 Subject: Cross-posting is good References: Message-ID: <5627c6fa.0310102348.6e5d885b@posting.google.com> Alex Martelli wrote in message news:... > > OTOH, such idea exposure could have prevented such big > > mistakes like C#, Mozart/Oz, XML++, ARC and others. > > You think Paul Graham's ARC is "a big mistake"? Why, > specifically? What specific criticisms are you leveling > at it? And why do you think Graham was lacking in "idea > exposure"? I'm not saying I agree with the underlying > design decisions &c, but I don't understand your point. It appears to be a sarcastic bigoted comment, based on his earlier paragraph: "(like Python is very slow, C is inherently insecure, Lispers are stupid, etc.) That's why there are usually more balanced and less bigoted opinions expressed in such threads." From jcb at iteris.com Wed Oct 15 14:05:16 2003 From: jcb at iteris.com (MetalOne) Date: 15 Oct 2003 11:05:16 -0700 Subject: Express What, not How. References: Message-ID: <92c59a2c.0310151005.37701b8c@posting.google.com> Raffael Cavallaro I don't know why but I feel like trying to summarize. I initially thought your position was that lambdas should never be used. I believe that Brian McNamara and Ken Shan presented powerful arguments in support of lambda. Your position now appears to have changed to state that lambdas are ok to use, but their use should be restricted. One point would appear to desire avoiding duplicate lambdas. This makes sense. Duplication of this sort is often found in "if statment" conditional tests also. The next point would be to name the function if a good name can be found. I believe that sometimes the code is clearer than a name. Mathematical notation was invented because natural language is imprecise. Sometimes a name is better than the code. The name gives a good idea of the "how" and perhaps you can defer looking at the "how". Sometimes I think using code in combination with a comment is better. A comment can say a little more than a name, and the code gives the precision. So as Marcin said, it is a balancing act to create readable code. I would like to say that I have found this entire thread very comforting. I have been programming for 18 years now. For the most part, when I read other peoples code I see nothing but 300+ line functions. I have come to feel like most programmer's have no idea what they are doing. But when you're writing small functions and everybody else is writing 300+ line functions you begin to wonder if it is you that is doing something wrong. It is nice to see that other people actually do think about how to write and structure good code. From garry at sage.att.com Wed Oct 29 13:50:34 2003 From: garry at sage.att.com (Garry Hodgson) Date: Wed, 29 Oct 2003 18:50:34 GMT Subject: Python from Wise Guy's Viewpoint In-Reply-To: References: Message-ID: <2003102913501067453434@k2.sage.att.com> raffael at mediaone.net (Raffael Cavallaro) wrote: > With lisp, you only add as much type checking as you need, *when* you > need it. if you knew how much you needed and when, you wouldn't need it. ---- Garry Hodgson, Technology Consultant, AT&T Labs Be happy for this moment. This moment is your life. From clifford.wells at comcast.net Sat Oct 4 17:03:50 2003 From: clifford.wells at comcast.net (Cliff Wells) Date: Sat, 04 Oct 2003 14:03:50 -0700 Subject: newbie needs help with GUI In-Reply-To: <200310041345.01708.scott_list@mischko.com> References: <3F7F1F51.D7976752@easystreet.com> <1065296088.11913.16.camel@devilbox.homelinux.net> <200310041345.01708.scott_list@mischko.com> Message-ID: <1065301429.11913.46.camel@devilbox.homelinux.net> On Sat, 2003-10-04 at 13:45, Scott Chapman wrote: > This has been a major problem at Microsoft that their engineers have been > wringing their hands over for a long time. When the computer temporarily > runs out of characters through this leakage, it makes a blue screen and gives > you a cryptic error message that doesn't mention character loss at all, while > it digs around through the font packs trying to find some unused ones. Well, if you think about it, the cryptic error message is practically self-explanatory. If it had more characters it wouldn't have to be so cryptic. Cliff -- When I die, don't bury me alone -These Immortal Souls From tjreedy at udel.edu Tue Oct 14 18:48:12 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 14 Oct 2003 18:48:12 -0400 Subject: pickle format References: Message-ID: "Jerome Alet" wrote in message news:pan.2003.10.14.22.19.50.444187 at librelogiciel.com... > I'd want to pickle a complex Python data structure and save it as > a blob in a relationnal database. > > Now I do that, and I can retrieve it with no problem and then unpickle it. > > But if I upgrade Python some day, will I still be able to unpickle datas > which were pickled with old versions and stored in my database ? In short, yes. Lib Ref 3.14.2 Data stream format There are currently 3 different protocols which can be used for pickling. Protocol version 0 is the original ASCII protocol and is backwards compatible with earlier versions of Python. Protocol version 1 is the old binary format which is also compatible with earlier versions of Python. Protocol version 2 was introduced in Python 2.3. It provides much more efficient pickling of new-style classes. Refer to PEP 307 for more information. ----- >From the PEP: To date, each release of Python has been able to read pickles written by all previous releases. Protocol 1 is kept precisely for this reason. I am sure that Guido intends for this to remain true at least thru the 2.x series. I believe this would only change if the Python object system were changed enough (in Python 3 or beyond) that unpickling old objects in the new system were to make no sense. If that were to happen, you would want to upgrade by addition rather than replacement. Terry J. Reedy From bbiro at netian.com Tue Oct 14 21:49:50 2003 From: bbiro at netian.com (Bart Simpson) Date: 14 Oct 2003 18:49:50 -0700 Subject: Z in ZOPE References: Message-ID: <10093a06.0310141749.6a4bdf0d@posting.google.com> I heard ZOPE was just last .com domain of 4-characters at that time. :) I think Z would not have special meaning. Olaf Salchow wrote in message news:... > Hi, ZOPE-gurus > > i have a little bit a dumb question. I am searching for the meaning of the Z > in ZOPE. From google i know that ZOPE means "Z Object Publishing > Environment", but then the question rises: what is a Z Object? > > I guess, its not a new question and sorry, if it is answered before, but i > couldnt find it yet. > Thanks > Olaf From tweedgeezer at hotmail.com Tue Oct 21 02:47:59 2003 From: tweedgeezer at hotmail.com (Jeremy Fincher) Date: 20 Oct 2003 23:47:59 -0700 Subject: Searching PyPI? References: <698f09f8.0310190732.2b8c458@posting.google.com> <7h38ynflxyh.fsf@pc150.maths.bris.ac.uk> Message-ID: <698f09f8.0310202247.4f8e0219@posting.google.com> Michael Hudson wrote in message news:<7h38ynflxyh.fsf at pc150.maths.bris.ac.uk>... > What does > > http://www.python.org/pypi?:action=search_form > > not provide? Are you just thinking of writing a front-end to that? Sure, I could whip up some regexps to snag the information I need from that. But that's usually pretty error-prone, and if someone else has already written the code, I'd be happy to use it :) It's by nice if PyPI provided some SOAP or xmlrpc server to support requests, though... :) Jeremy From ville.spammehardvainio at spamtut.fi Mon Oct 20 08:57:47 2003 From: ville.spammehardvainio at spamtut.fi (Ville Vainio) Date: 20 Oct 2003 15:57:47 +0300 Subject: Why don't people like lisp? References: <3f9302d7.170372828@news.eircom.net> Message-ID: Pascal Costanza writes: > So why is it that Python is continuously evolving as a language? Do > you think this is going to stop at some stage? Python is not only the language, it's also the implementation (or implementations). I don't know whether the evolution is ever going to stop, you've got to ask Guido :-). Obviously I wouldn't mind if the language reached Perfection within, say, 10 years, after which it could be standardized and only the libraries and the implementation would evolve. > Wouldn't it be better if everyone could contribute to the evolution of > a language, and then let the community decide what the best approaches > are? Possibly. But personally, I trust the guys in charge. Lisp might the very essence of programming, built into the DNA of computer science, but Python is the channeling of that quintessential truth into a form that is *easily* writeable and esp. readable by mere mortals. It might lose some of the power, but improved productivity in 90% of the situations complements this nicely. > With Python, you have to stick to the constructs the languages give > you. When you want to add domain-specific abstractions on the language Yes, and it gives me all I need. You can do a whole lot with dynamically typed OO and powerful data types. > > Meanwhile, people are voting with their feet: a lot (thousands? don't > And as a sidenote, if you are seriously considering to learn and maybe > use Lisp in practice, you should take a look at _both_ major dialects, > i.e. Common Lisp and Scheme. They are very different in several I only use Emacs Lisp. I have Python for the problem domains that CL and Scheme would cover. I guess I might start hacking CL if/when XEmacs switched their Lisp implementation, which I believe is in the roadmaps... -- Ville Vainio http://www.students.tut.fi/~vainio24 From newsgroups at jhrothjr.com Sat Oct 18 15:00:38 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 18 Oct 2003 15:00:38 -0400 Subject: prePEP: Money data type References: Message-ID: "Alex Martelli" wrote in message news:S9fkb.308725$R32.10140453 at news2.tin.it... > Ian Bicking wrote: > > > On Friday, October 17, 2003, at 06:39 PM, John Roth wrote: > >> 1. I've seen lots of strange rounding policies in > >> various nooks and crannies. Is there any way of > >> specifying a rounding policy that would be used > >> and inherited by the result money object? > > > > Does the rounding policy belong to the money, or to the context in > > which the money is used? I would expect it belongs to the context, > > which would imply the policy should be specified by method name or an > > argument to a method. > > So you think y=x/2 should not work when x is an instance of Money, > nor should y=x*z when x is an instance of Money and z is e.g. 0.5? > That seems pretty limiting to me. > > > > No, the only places where repr() round trips is for Python literals. > > Not true: > > >>> from sets import Set > >>> a = Set('ciao') > >>> print a > Set(['i', 'a', 'c', 'o']) > >>> therep = repr(a) > >>> b = eval(therep) > >>> print b > Set(['i', 'a', 'c', 'o']) > >>> > > repr + eval "round-trips" for many types that don't have Python > literals, net of the issue of whether the type's name as given > by repr includes the module name (and thus roundtrips after an > import statement) or doesn't (and thus roundtrips after a from > statement) -- it seems that it more often doesn't. > > > > This article lays out some common requirements for money: > > > > http://www.martinfowler.com/ap2/quantity.html > > Good reference, thanks. In particular, it bluntly states its > disagreement with your point 1 above: > """ > A money object, however, can encode its own rules for rounding, > which means that most of the time you don't have to be aware > of the rounding rules while you are working with money. > """ > > Fowler's Money class includes the currency unit, just as any > of his Quantity classes includes the unit of measure. The > Money class under discussion is specifically designed to NOT > include the currency unit. I'm not sure which design is > more suitable here, though. Without devoting a huge amount of thinking time to it, I'd be tempted to go with solving the larger problem: basic financial calculations. Sometimes what looks like a small problem is difficult to solve because you don't have enough context. Integer division is a great case in point: there are at least three different ways of defining what the remainder should be, and they are all right - in different domains. There is, by the way, a great example of a rounding policy that I bet you don't want to program: how do you round the tip when you go out to eat? John Roth > > Alex > From tzot at sil-tec.gr Mon Oct 27 12:59:37 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Mon, 27 Oct 2003 19:59:37 +0200 Subject: Simple Problems: Caps and Commas References: <20031027040605.18093.00000128@mb-m03.aol.com> Message-ID: On 27 Oct 2003 09:06:05 GMT, rumours say that keflimarcusx at aol.comNOSPAM (KefX) might have written: >>I keep looking, but I don't see any "extra spaces". > >Then either you don't understand what I mean, or you're not looking hard >enough. Mu (which in this case it could mean, "The choices you offer aren't sufficient to cover what happens here, because you are overlooking something." :) Google for "jargon mu". >print "this, ", "that, ", "and the other" > >The "extra spaces" are the spaces after each comma in the first two >double-quoted strings. It prints out: >this, that, and the other > >instead of: >this, that, and the other KefX, the OP used the line: >print "Address: ",saddy, ",",city, ",",state, ",",zip This is what you are overlooking: the comma operator in the print argument list inserts spaces between arguments, therefore also between the variables and the literal commas (","). saddy, city and state don't end in a space, and there is no space in ",". The cryptic way to solve this is to fiddle with sys.stdout.softspace. The /preferably obvious/ way is to use string interpolation, which is definitely not overkill, if you do some benchmarking. Cheers :) -- TZOTZIOY, I speak England very best, Ils sont fous ces Redmontains! --Harddix From vimakefile at yahoo.com Fri Oct 10 18:04:58 2003 From: vimakefile at yahoo.com (Mike) Date: Fri, 10 Oct 2003 22:04:58 GMT Subject: generator testing and attrs References: <6250403b.0310091611.5bdd5b6d@posting.google.com> Message-ID: "Miki Tebeka" wrote in message > You'll see that g has many attributes that f doesnt. Maybe you can use one of them. Hmm - doesn't seem so here: >>> def g(): yield None >>> dir(g) ['__call__', '__class__', '__delattr__', '__dict__', '__doc__', '__get__', '__getattribute__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', 'func_closure', 'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_name'] >>> def f(): return None >>> dir(f) ['__call__', '__class__', '__delattr__', '__dict__', '__doc__', '__get__', '__getattribute__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', 'func_closure', 'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_name'] >>> > IMO a better way is letting the caller passing you ONLY functions. > In case of a generator if should pass the .next of the generator. > ...code... As I said, I can't do that becuase I'm saving the items to be scheduled (evaluated lazily) -- I don't want to call f() or f.next() right right away. (The code sample could have included the comment "# much later..." between getting the funarg and calling it.) Ahh -- Looks like the original PEP (255) held the key: >>> hex(f.func_code.co_flags) '0x43' >>> hex(g.func_code.co_flags) '0x63' >>> --- mike From doctor at doctor.nl2k.ab.ca Fri Oct 10 11:07:25 2003 From: doctor at doctor.nl2k.ab.ca (The Doctor) Date: Fri, 10 Oct 2003 09:07:25 -0600 Subject: Problems with a programme called CyberChair In-Reply-To: <3F859829.D7F0C822@engcorp.com> References: <20031009140951.GA23061@doctor.nl2k.ab.ca> <20031009142118.GB5735@nl.linux.org> <3F859829.D7F0C822@engcorp.com> Message-ID: <20031010150725.GA11439@doctor.nl2k.ab.ca> On Thu, Oct 09, 2003 at 01:17:29PM -0400, Peter Hansen wrote: > The Doctor wrote: > > > > On Thu, Oct 09, 2003 at 04:21:18PM +0200, Gerrit Holl wrote: > > > The Doctor wrote: > > > > Hello. I am running a Python-based programme called cyberChair. > > > > > > This newsgroup/mailinglist is about programming in Python, not about > > > application written in Python. It is unlikely that we are able to > > > help you. You may want to contact the author of cyberChair with your > > > problem. > > > > Question: How do you debug procedures in python? > > The same way you debug procedures in many other languages. > > (If you ask such a general question, you can expect such a general > answer, or a lot of shots-in-the-dark as people attempt to read your > mind.) > > If this is in reference to your original question, you might want > to consider whether there's a remote chance that, maybe, this isn't > a Python issue, but something to do with your server permissions or > whatnot... > > For further help, check out the "pdb" module for the Python debugger. > Also consider inserting "print" statements to help you understand > where the problem is occurring. > > Inserting this code snippet just before the faulty code can help: > > import pdb > pdb.set_trace() > > That way you get dropped into the interactive debugger and can > single-step through the rest of the code, etc. > Shall try. In the mean time, I adjusted the #! to include the more stable version and added -d -v at the end. I got: Your server is not allowed to access this script. import struct # dynamically loaded from /usr/local/lib/python2.1/lib-dynload/struct.so import fcntl # dynamically loaded from /usr/local/lib/python2.1/lib-dynload/fcntl.so # /usr/local/lib/python2.1/plat-freebsd4/FCNTL.pyc matches /usr/local/lib/python2.1/plat-freebsd4/FCNTL.py import FCNTL # precompiled from /usr/local/lib/python2.1/plat-freebsd4/FCNTL.pyc import submit_save # from /usr/local/www/data/naiso/cgi-bin/submit_save.py # can't create /usr/local/www/data/naiso/cgi-bin/submit_save.pyc import submit_phase1 # from /usr/local/www/data/naiso/cgi-bin/submit_phase1.py # can't create /usr/local/www/data/naiso/cgi-bin/submit_phase1.pyc What should I do next? > -Peter > -- > http://mail.python.org/mailman/listinfo/python-list -- Member - Liberal International On 11 Sept 2001 the WORLD was violated. This is doctor at nl2k.ab.ca Ici doctor at nl2k.ab.ca Society MUST be saved! Extremists must dissolve. Newfoundland on 21 Oct 2003, VOTE LIBERAL!! From emile at fenx.com Tue Oct 7 17:49:07 2003 From: emile at fenx.com (Emile van Sebille) Date: Tue, 7 Oct 2003 14:49:07 -0700 Subject: Copying/Moving File Trees References: <6ee58e07.0310071314.684537f4@posting.google.com> Message-ID: Lothar Scholz asks: > I think i have overseen the API functions to copy and move files and > complete file trees, because i can't find them in the standart > library. > > Can anybody give me a hint in which module this is implemented. shutil -- Emile van Sebille emile at fenx.com From qrczak at knm.org.pl Thu Oct 23 15:25:32 2003 From: qrczak at knm.org.pl (Marcin 'Qrczak' Kowalczyk) Date: Thu, 23 Oct 2003 21:25:32 +0200 Subject: Why don't people like lisp? References: <3f96b046$0$556$b45e6eb0@senator-bedfellow.mit.edu> <20031022234546.GS1454@mapcar.org> <3f97eb1f$0$573$b45e6eb0@senator-bedfellow.mit.edu> <20031023160206.GW1454@mapcar.org> <3f981fc4$0$575$b45e6eb0@senator-bedfellow.mit.edu> Message-ID: On Thu, 23 Oct 2003 14:37:57 -0400, Brian Kelley wrote: > Python's lambda is fairly awkward to start with, it is also slower than > writing a new function. I fully admit that I have often wanted lambda > to be able to look up variables in the calling frame. They can since Python 2.1 (in 2.1 with from __future__ import nested_scopes, in 2.2 and later by default). This applies to nested functions as well. -- __("< Marcin Kowalczyk \__/ qrczak at knm.org.pl ^^ http://qrnik.knm.org.pl/~qrczak/ From aleax at aleax.it Wed Oct 1 13:34:18 2003 From: aleax at aleax.it (Alex Martelli) Date: Wed, 01 Oct 2003 17:34:18 GMT Subject: Fun with fancy slicing References: <7h3isnaz6qw.fsf@pc150.maths.bris.ac.uk> Message-ID: Dave Benjamin wrote: ... > of the trademark quicksort implementation in Haskell, ie. it may not be > great in practice, but you can see the algorithm at a high level which > makes it easier to figure out what's going on. Hmmm, you mean as in...: def quicksort(alist): head = alist[0] return quicksort([ x in alist[1:] if x<=head ]) + [ head ] + quicksort([ x in alist[1:] if x>head ]) ...? Alex From jjl at pobox.com Sun Oct 19 19:49:31 2003 From: jjl at pobox.com (John J. Lee) Date: 20 Oct 2003 00:49:31 +0100 Subject: AST Manipulation and Common Subexpression Elimination References: Message-ID: <87ismkokj8.fsf@pobox.com> Robert Kern writes: [...] > 3. Is there any example code around showing how to output Python code from the > AST? I can probably figure out, then, how to do the same for > Maxima/Yacas/Maple/Mathematica as I'm sure I'm going to want to slap these > formulae into a CAS and play around with them. > > 4. And as a corollary to that last thought: are there any automatic > differentiation tools for Python that operate directly on the AST and generate > new code? [...] Why not just use Maple / Mathematica / whatever? Why does Python have to be involved? John From apicard+die-spammer-die at optushome.com.au Thu Oct 30 03:28:14 2003 From: apicard+die-spammer-die at optushome.com.au (Alain Picard) Date: Thu, 30 Oct 2003 19:28:14 +1100 Subject: Explanation of macros; Haskell macros References: <87brs2tjut.fsf@memetrics.com> Message-ID: <87he1rdt9d.fsf@memetrics.com> Joachim Durchholz writes: > Alain Picard wrote: > >> More precisely: "macros make control of when, if, and how often, >> something is evaluated _possible_." Functions >> (your only other option) give you no choice. > > This statement is wrong if left in full generality: higher-order > functions can control quite precisely what gets evaluated when. If the > language offers both lazy and strict parameters, evaluation time > control extends to the parameter expressions as well. My apologies to the functional guys. I was responding from a lisp newsgroup: so let me amend the above to end with "IN LISP". [We do not have lazy evaluation by default.] From prunesquallor at comcast.net Fri Oct 24 21:18:25 2003 From: prunesquallor at comcast.net (prunesquallor at comcast.net) Date: Sat, 25 Oct 2003 01:18:25 GMT Subject: Python from Wise Guy's Viewpoint References: <_8Ekb.7543$pT1.318@twister.nyc.rr.com> <3f972315$1@news.unimelb.edu.au> <3638acfd.0310230039.306b14f@posting.google.com> <3638acfd.0310232246.64fa09ed@posting.google.com> <65fn61-b61.ln1@ID-7776.user.dfncis.de> <3F994597.7090807@ps.uni-sb.de> Message-ID: <3cdif734.fsf@comcast.net> "Andreas Rossberg" writes: > Sorry, but that reply of yours somewhat indicates that you haven't really > used modern type systems seriously. > > All decent type systems allow you to define your own types. You can express > any domain-specific abstraction you want in types. Hence the type language > gives you additional expressive power wrt the problem domain. Cool! So I can declare `Euclidean rings' as a type an ensure that I never pass a non-Euclidean ring to a function? From francisgavila at yahoo.com Wed Oct 22 17:23:36 2003 From: francisgavila at yahoo.com (Francis Avila) Date: Wed, 22 Oct 2003 17:23:36 -0400 Subject: 'while' in list comprehension? References: <20031022175924.GA10716@jsaul.de> Message-ID: "Emile van Sebille" wrote in message news:bn6k9i$tftt3$1 at ID-11957.news.uni-berlin.de... > jsaul asks... > > would then turn into > > > > foo = [ i for i in bar while len(i)>0 ] > > > > Is there any reason for not having this kind of thing? I actually > > miss it pretty often. > > > > > How is this different from: > > foo = [ i for i in bar if len(i) ] > > Emile van Sebille > emile at fenx.com > The idea is that 'while' stops iterating through the list when the condition isn't met. 'if' just doesn't output anything. e.g.: >>> bar = ['this', 'is', 'a', 'list', '', 'see?'] >>> [i for i in bar if len(i)] ['this', 'is', 'a', 'list', 'see?'] >>> [i for i in bar while len(i)] # Pretend ['this', 'is', 'a', 'list'] What's your typical use for this? I guess I see nothing really wrong with it, although I thought list comprehensions were supposed to make the iteration transparent--'while' kinda destroys the illusion. But these are the only two looping constructs that make sense in a list comprehension, so why not support both? OTOH, 'while' makes no sense in a dictionary comprehension (and presumably we'll have those one day.) From simon_place at whsmithnet.co.uk Tue Oct 14 17:25:43 2003 From: simon_place at whsmithnet.co.uk (simon place) Date: Tue, 14 Oct 2003 22:25:43 +0100 Subject: closing a server socket In-Reply-To: <3F8C05FF.49524CDF@engcorp.com> References: <3f8b0de5_3@mk-nntp-1.news.uk.worldonline.com> <3F8C05FF.49524CDF@engcorp.com> Message-ID: <3f8c69dc_2@mk-nntp-1.news.uk.worldonline.com> Peter Hansen wrote: > simon place wrote: > >>Spent some very frustrating hours recoding to find a way of closing a server >>socket, i'd not thought it would be any problem, >> >>however, after complete failure and as a last resort, i looked at the python >>wrapper module for sockets, and found that the close command doesn't actually >>call the underlying close! this didn't seem right, so i added it, and my code >>now works simply and as expected. >> >> def close(self): >> self._sock.close() # added 2003-oct-13 >> self._sock = _closedsocket() >> self.send = self.recv = self.sendto = self.recvfrom = self._sock._dummy >> close.__doc__ = _realsocket.close.__doc__ >> >>Probably only on win32, the comments in the socket module seem to indicate >>different codings on different platforms. > > > None of this should be necessary! > > What problems were you having that led you to try the above abomination in > your effort to resolve them? > > -Peter The problem is i couldn't find anyway, in 'normal' code, to close a server socket, ie unblock an accept. tried to use non-blocking mode, but not allowed on a server socket, which makes sense, but isn't documented. tried to use time-outs, which was close, but seems to close the accepted connection sockets on a server socket time-out. tried to fire a dummy connection to unblock the accept, which works, but if your ip changes, i.e. a dialup, you can't do that. i only hacked the module because of frustration, but it took about a minute to spot, and now every thing works the original way i tried, and i've been doing some thrashing and had no problems. From FBatista at uniFON.com.ar Mon Oct 20 16:57:27 2003 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Mon, 20 Oct 2003 17:57:27 -0300 Subject: prePEP: Money data type Message-ID: #- Alex Martelli wrote: #- Excellent. You can also provide a .divideBy(N) method that returns #- an N-items list, distributing the excess pennies (or whatever units); #- an URL by Martin Fowler that was quoted on the thread shows that. Very interesting (and useful). Adding to the PEP. . Facundo From my-first-name.my-last-name at jpl.nasa.gov Mon Oct 6 15:19:54 2003 From: my-first-name.my-last-name at jpl.nasa.gov (Erann Gat) Date: Mon, 06 Oct 2003 12:19:54 -0700 Subject: Python syntax in Lisp and Scheme References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> <92c59a2c.0310031345.57d20631@posting.google.com> Message-ID: In article , David Eppstein wrote: > In article > v>, > my-first-name.my-last-name at jpl.nasa.gov (Erann Gat) wrote: > > > > : Here's another example of what you can do with macros in Lisp: > > > > > > : (with-collector collect > > > : (do-file-lines (l some-file-name) > > > : (if (some-property l) (collect l)))) > > > > > > : This returns a list of all the lines in a file that have some property. > > > > > > OK, that's _definitely_ just a filter: filter someproperty somefilename > > > Perhaps throw in a fold if you are trying to abstract "collect". > > > > The net effect is a filter, but again, you need to stop thinking about the > > "what" and start thinking about the "how", otherwise, as I said, there's > > no reason to use anything other than machine language. > > Answer 1: literal translation into Python. The closest analogue of > with-collector etc would be Python's simple generators (yield keyword) > and do-with-file-lines is expressed in python with a for loop. So: > > def lines_with_some_property(some_file_name): > for l in some_file_name: > if some_property(l): > yield l You left out the with-collector part. But it's true that my examples are less convincing given the existence of yield (which I had forgotten about). But the point is that in pre-yield Python you were stuck until the langauge designers got around to adding it. I'll try to come up with a more convincing short example if I find some free time today. E. From aleax at aleax.it Fri Oct 17 11:48:55 2003 From: aleax at aleax.it (Alex Martelli) Date: Fri, 17 Oct 2003 15:48:55 GMT Subject: Trivial performance questions References: Message-ID: Brian Patterson wrote: ... > newbie, but I really like the trapping facilities. I just worry about the > performance implications and memory usage of such things, especially since > I'm writing for Zope. > > And while I'm here: Is there a difference in performance when checking: > datum is None > over: > datum == None > > and similarly: > if x is None or y is None: > or: > if None in (x,y): > > I appreciate that these are trivial in the extreme, but I seem to be > writing dozens of them, and I may as well use the right one and squeeze > what performance I can. I see you've already been treated to almost all the standard "performance does not matter" arguments (pretty well presented). They're right (and I would have advanced them myself if others hadn't already done so quite competently), *BUT*... ...but, when you're wondering which of two equivalently readable and maintainable idioms is "the one obvious way to do it", there is nothing wrong with finding out the performance to help you. After all, which one is right is not necessarily obvious unless you're Dutch! To put it another way: there is nothing wrong in getting into the habit of always using one idiom over another when they appear to be equivalent; such stylistic uniformity can indeed often be preferable to choosing haphazardly in each case. And all other things being equal it IS better to choose, as one's habitual style, the microscopically faster one -- why not, after all? So, for this kind of tasks as well as for many others, what you need is timeit.py from Python 2.3. I'm not sure it's compatible with Python 2.1.3, which I understand you're constrained to use due to Zope -- I think so, but haven't tried. It's sure quite compatible with Python 2.2. I've copied it into my ~/bin and done a chmod+x, and now when I wonder about performance it's easy to check it (sometimes there are tricky parts, but not often); if I need to check for a specific release, I can explicitly say e.g. $ python2.2 ~/bin/timeit.py ... or whatever. So, for Python 2.3 on my machine: [alex at lancelot clean]$ timeit.py -c -s'datum=23' 'datum==None' 1000000 loops, best of 3: 0.47 usec per loop [alex at lancelot clean]$ timeit.py -c -s'datum=23' 'datum is None' 1000000 loops, best of 3: 0.29 usec per loop [alex at lancelot clean]$ timeit.py -c -s'datum=None' 'datum is None' 1000000 loops, best of 3: 0.29 usec per loop [alex at lancelot clean]$ timeit.py -c -s'datum=None' 'datum == None' 1000000 loops, best of 3: 0.41 usec per loop no doubt here, then: "datum is None" wins hands-down over "datum == None" whether datum is None or not. And indeed, it so happens that experienced Pythonistas generally prefer 'is' for this specific test (this also has other reasons, such as the preference for words over punctuation, and the fact that if datum is an instance of a user-coded class there are no bounds to the complications its __eq__ or __cmp__ might cause, while 'is' doesn't run ANY such risk). Similarly: [alex at lancelot clean]$ timeit.py -c -s'x=1' -s'y='2 'None in (x,y)' 1000000 loops, best of 3: 1 usec per loop [alex at lancelot clean]$ timeit.py -c -s'x=1' -s'y='2 'x is None or y is None' 1000000 loops, best of 3: 0.48 usec per loop again, the form with more words and no punctuation (the more readable one by Pythonistas' usual tastes) is faster -- confirming it's the preferable style. These measurements also help put such things in perspective: we ARE after all talking about differences of 120 to 500 nanoseconds (on my 30-months-old box, a dinosaur by today's standards). Still, if they're executed in some busy inner loop, it MIGHT easily pile up to several milliseconds' worth, and, who knows - given that after all choosing a consistent style IS preferable, and that often the indications you get from these measurements will push you towards readability and Pythonicity, it doesn't seem a bad idea to me. Now, about the hasattr vs getattr issue...: [alex at lancelot clean]$ timeit.py -c 'hasattr([], "pop")' 1000000 loops, best of 3: 0.95 usec per loop [alex at lancelot clean]$ timeit.py -c 'getattr([], "pop", None)' 1000000 loops, best of 3: 1.11 usec per loop [alex at lancelot clean]$ timeit.py -c 'hasattr([], "pok")' 100000 loops, best of 3: 2.4 usec per loop [alex at lancelot clean]$ timeit.py -c 'getattr([], "pok", None)' 100000 loops, best of 3: 2.6 usec per loop you can see that three-args getattr always takes a tiny little bit longer than hasattr -- about 0.2 microseconds. More time for both when getting non-existent attributes, of course, since the exception is raised and handled in that case. But in any case, given that getattr has already done all the work you needed, while hasattr may be just the beginning (you still need to get the attribute if it's there), you also need to consider: [alex at lancelot clean]$ timeit.py -c '[].pop' 1000000 loops, best of 3: 0.48 usec per loop and that attribute fetch consumes 2-3 times longer than the speed-up of hasattr vs 3-args getattr. So, if the attribute will be present at least 30%-50% of the time, we could expect 3-attribute getattr to be a winner; for rarely present attributes, though, hasattr may still be faster (by a tiny little bit). We can also measure the try/except approach: [alex at lancelot clean]$ timeit.py -c ' try: [].pop except AttributeError: pass ' 1000000 loops, best of 3: 0.6 usec per loop [alex at lancelot clean]$ timeit.py -c ' try: [].pok except AttributeError: pass ' 100000 loops, best of 3: 8.1 usec per loop If the exception doesn't occur try/except is quite fast, but, if it does, it's far slower than any of the others. So, if performance matters, it should only be considered if the attribute is _overwhelmingly_ more likely to be present than absent. We can put together these solutions in small functions, e.g. a.py: def hasattr_pop(obj=[]): if hasattr(obj, 'pop'): return obj.pop else: return None def getattr_pop(obj=[]): return getattr(obj, 'pop', None) def tryexc_pop(obj=[]): try: return obj.pop except AttributeError: return None and similarly for pok instead of pop. Now: [alex at lancelot clean]$ timeit.py -c -s'import a' 'a.hasattr_pop()' 100000 loops, best of 3: 2.1 usec per loop [alex at lancelot clean]$ timeit.py -c -s'import a' 'a.getattr_pop()' 100000 loops, best of 3: 1.9 usec per loop [alex at lancelot clean]$ timeit.py -c -s'import a' 'a.tryexc_pop()' 1000000 loops, best of 3: 1.46 usec per loop for an attribute that's present, small advantage to the try/except, getattr by a nose faster than the hasattr check. But: [alex at lancelot clean]$ timeit.py -c -s'import a' 'a.hasattr_pok()' 100000 loops, best of 3: 3.4 usec per loop [alex at lancelot clean]$ timeit.py -c -s'import a' 'a.getattr_pok()' 100000 loops, best of 3: 3.5 usec per loop [alex at lancelot clean]$ timeit.py -c -s'import a' 'a.tryexc_pok()' 100000 loops, best of 3: 12.3 usec per loop here, by the tiniest of margin, hasattr beats getattr -- and try/except is the pits. So, in this case, I don't think a single approach can be universally recommended. getattr is most compact; but you should also keep in your quiver the try/except, for those extremely performance-sensitive cases where the attribute will almost always be present, AND the hasattr as the best compromise for attributes that are absent some resonable percentage of the time AND the default value takes effort to construct (by using None as the default we've favoured the getattr approach, which always constructs the default object, by giving it a very cheap-to-construct one -- try with some default object that DOES take work to build, and you'll see). That much being said, you'll almost always see me using getattr for this -- it's just too compact, handy, readable -- I'll optimize it out only when dealing with a real bottleneck, or avoid using it when the effort of constructing the default object is "obviously" quite big. Alex From zr7m08j02 at sneakemail.com Sun Oct 12 13:46:24 2003 From: zr7m08j02 at sneakemail.com (Doug) Date: Sun, 12 Oct 2003 17:46:24 GMT Subject: Python based http server In-Reply-To: References: Message-ID: <3F8993AD.4080404@sneakemail.com> I thought the yield thing in Python 2.3 was a couritine implementation. Is there a difference between generators and coroutines? Alex Martelli wrote: > Doug wrote: > > >>I am thinking of using a Python based HTTP server instead of Apache. >> >>I would be interested in one that employed generators and coroutines. I >>know those are fairly new features of python, so maybe nothing is >>available yet. > > > coroutines are not a part of Python. Twisted, the best way to write > standalone Python HTTP servers, can use generators productively, > see e.g. http://twistedmatrix.com/documents/howto/flow (but it will > make little sense to you until you understand more about Twisted). > > > Alex > From overdrive_ss at yahoo.com Tue Oct 7 16:26:10 2003 From: overdrive_ss at yahoo.com (Todd Johnson) Date: Tue, 7 Oct 2003 13:26:10 -0700 (PDT) Subject: Class instantiation question In-Reply-To: <20031007200119.4011.76888.Mailman@mail.python.org> Message-ID: <20031007202610.90997.qmail@web41205.mail.yahoo.com> Thanks Carl, def some_function(a,b): try: thisInstance = MyClass(a,b) except ValueError: handler_error() else: do_something_useful(thisInstance) that is exactly what I was looking for. It has been a while since I have had to do some exception handling. Thanks for the refresher. Todd __________________________________ Do you Yahoo!? The New Yahoo! Shopping - with improved product search http://shopping.yahoo.com From tim.hochberg at ieee.org Fri Oct 17 15:14:45 2003 From: tim.hochberg at ieee.org (Tim Hochberg) Date: Fri, 17 Oct 2003 12:14:45 -0700 Subject: wait until change In-Reply-To: References: <3F90399E.AA2AF998@engcorp.com> Message-ID: Tom wrote: > Peter Hansen wrote: > >> Use time.sleep(). >> >> -Peter >> > If I use sleep, I have to know how long the process should sleep, but > sometimes it should sleep for seconds and sometimes for minutes. So it > would be good if I can put it to sleep and somehow wake it up if the > file changed. If you use something like:: ctime = os.stat(file).st_ctime while True: if os.stat(file).st_ctime > ctime: break time.sleep(1.0) # Do stuff... The load on your CPU will be negligible and your program will wake up at most 1 second after the modification -tim From prunesquallor at comcast.net Sat Oct 25 17:10:40 2003 From: prunesquallor at comcast.net (prunesquallor at comcast.net) Date: Sat, 25 Oct 2003 21:10:40 GMT Subject: Python from Wise Guy's Viewpoint References: <8yn9ce2k.fsf@comcast.net> Message-ID: <4qxxyqeq.fsf@comcast.net> gt5163b at prism.gatech.edu (Brian McNamara!) writes: > prunesquallor at comcast.net once said: >>The other problem is that monads don't compose. > > I disagree. See the discussion of "monad transformers" in part 3 of > > http://www.nomaware.com/monads/html/index.html > > I have even implemented a few of the monad transformers in C++. > Composing monads is terrific! The problem is when you combine several monads in a stack. You have to decide on an order, even if the monads are orthogonal. Then you have to create lifting code to get at the monad you want. If you re-order the stack, you have to re-order the lifting code, too. I think monads are pretty cool, but they still have their problems. From g2h5dqi002 at sneakemail.com Sun Oct 12 22:28:57 2003 From: g2h5dqi002 at sneakemail.com (Greg Ewing (using news.cis.dfn.de)) Date: Mon, 13 Oct 2003 15:28:57 +1300 Subject: Car and cdr (Re: Python syntax in Lisp and Scheme) In-Reply-To: References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> <92c59a2c.0310031345.57d20631@posting.google.com> <6CZgb.3273$dn6.860@newsread4.news.pas.earthlink.net> Message-ID: Andrew Dalke wrote: > It has sometimes been said that Lisp should use first and > rest instead of car and cdr I used to think something like that would be more logical, too. Until one day it occurred to me that building lists is only one possible, albeit common, use for cons cells. A cons cell is actually a completely general-purpose two-element data structure, and as such its accessors should have names that don't come with any preconceived semantic connotations. From that point of view, "car" and "cdr" are as good as anything! -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From dietz at dls.net Fri Oct 24 04:34:25 2003 From: dietz at dls.net (Paul F. Dietz) Date: Fri, 24 Oct 2003 03:34:25 -0500 Subject: Python from Wise Guy's Viewpoint In-Reply-To: <3638acfd.0310231647.16db77b4@posting.google.com> References: <_8Ekb.7543$pT1.318@twister.nyc.rr.com> <3f972315$1@news.unimelb.edu.au> <3638acfd.0310230039.306b14f@posting.google.com> <3638acfd.0310231647.16db77b4@posting.google.com> Message-ID: Ralph Becket wrote: > Here's the way I see it: > (1) type errors are extremely common; > (2) an expressive, statically checked type system (ESCTS) will identify > almost all of these errors at compile time; > (3) type errors flagged by a compiler for an ESCTS can pinpoint the source > of the problem whereas ad hoc assertions in code will only identify a > symptom of a type error; > (4) the programmer does not have to litter type assertions in a program > written in a language with an ESCTS; > (5) an ESCTS provides optimization opportunities that would otherwise > be unavailable to the compiler; > (6) there will be cases where the ESCTS requires one to code around a > constraint that is hard/impossible to express in the ESCTS (the more > expressive the type system, the smaller the set of such cases will be.) However, (7) Developing reliable software also requires extensive testing to detect bugs other than type errors, and (8) These tests will usually detect most of the bugs that static type checking would have detected. So the *marginal* benefit of static type checking is reduced, unless you weren't otherwise planning to test your code very well. BTW, is (3) really justified? My (admittedly old) experience with ML was that type errors can be rather hard to track back to their sources. Paul From d95-bli at nada.kth.se Fri Oct 10 10:16:42 2003 From: d95-bli at nada.kth.se (=?iso-8859-1?q?Bj=F6rn_Lindberg?=) Date: 10 Oct 2003 16:16:42 +0200 Subject: startup time (was: Python syntax in Lisp and Scheme) References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> <92c59a2c.0310031345.57d20631@posting.google.com> <6CZgb.3273$dn6.860@newsread4.news.pas.earthlink.net> <%hihb.4368$dn6.2921@newsread4.news.pas.earthlink.net> Message-ID: Bruce Lewis writes: > j-anthony at rcn.com (Jon S. Anthony) writes: > > > If your problems are trivial, I suppose the presumed lower startup > > costs of Python may mark it as a good solution medium. > > I find no significant difference in startup time between python and > mzscheme. My preliminary results in this very important benchmark indicates that python performs equally well to the two benchmarked Common Lisps: 200 bjorn at nex:~> time for ((i=0; i<100; i++)); do lisp -noinit -eval '(quit)'; done real 0m2,24s user 0m1,36s sys 0m0,83s 201 bjorn at nex:~> time for ((i=0; i<100; i++)); do lisp -noinit -eval '(quit)'; done real 0m2,24s user 0m1,39s sys 0m0,82s 202 bjorn at nex:~> time for ((i=0; i<100; i++)); do clisp -q -x '(quit)'; done real 0m2,83s user 0m1,74s sys 0m1,03s 203 bjorn at nex:~> time for ((i=0; i<100; i++)); do clisp -q -x '(quit)'; done real 0m2,79s user 0m1,67s sys 0m1,09s 204 bjorn at nex:~> time for ((i=0; i<100; i++)); do python -c exit; done real 0m2,41s user 0m1,85s sys 0m0,52s 205 bjorn at nex:~> time for ((i=0; i<100; i++)); do python -c exit; done real 0m2,41s user 0m1,89s sys 0m0,52s Bj?rn From R.Livsey at cache-22.co.uk Tue Oct 21 05:42:37 2003 From: R.Livsey at cache-22.co.uk (Richard Livsey) Date: Tue, 21 Oct 2003 10:42:37 +0100 Subject: CD Writing Modules? Message-ID: <3F94FF8D.1020906@cache-22.co.uk> Hi, I'm fairly new to python but am liking what I see so far. I'm in the process of writing a network controlled mp3 player based on Twisted and I want to add the ability for it to write CDs (so you would queue up a selection of songs and be able to play or burn them etc..) but I cannot find much out there on how to do this with python. The mp3 player will be running Linux (not sure of the distro yet, its currently working with Windows but I want to change that ASAP) but ideally I would like it to be as cross platform as possible. Thanks in advance. -- R.Livsey Incutio Web Developer www.cache-22.co.uk www.incutio.com From jacek.generowicz at cern.ch Wed Oct 15 12:04:46 2003 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 15 Oct 2003 18:04:46 +0200 Subject: Python syntax in Lisp and Scheme References: <8CVgb.8$KR3.1846@typhoon.nyu.edu> <20031014050046.GM1454@mapcar.org> Message-ID: mertz at gnosis.cx (David Mertz) writes: > HOFs are not a special Lisp thing. Haskell does them much better, > for example... and so does Python. mertz at gnosis.cx (David Mertz) writes: > the alpha and omega of HOFs is that functions are first class > objects that can be passed and returned. How do you reconcile these two statements ? [Hint: functions in Lisps are "first class objects that can be passed and returned"; how does Python (or Haskell) do this "alpha and omega of HOFs" "much better" ?] From ktilton at nyc.rr.com Sat Oct 11 21:26:39 2003 From: ktilton at nyc.rr.com (Kenny Tilton) Date: Sun, 12 Oct 2003 01:26:39 GMT Subject: Python syntax in Lisp and Scheme In-Reply-To: References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> <92c59a2c.0310031345.57d20631@posting.google.com> Message-ID: Alex Martelli wrote: > Kenny Tilton wrote: > ... > >>>The very 'feature' that was touted by Erann Gat as macros' killer >>>advantage in the WITH-CONDITION-MAINTAINED example he posted is the >>>crucial difference: functions (HO or not) and classes only group some >>>existing code and data; macros can generate new code based on examining, >>>and presumably to some level *understanding*, a LOT of very deep things >>>about the code arguments they're given. >> >>Stop, your scaring me. You mean to say there are macros out there whose >>output/behavior I cannot predict? And I am using them in a context where >>I need to know what the behavior will be? What is wrong with me? And >>what sort of non-deterministic macros are these, that go out and make >>their own conclusions about what I meant in some way not documeted? > > > Let's start with that WITH-CONDITION-MAINTAINED example of Gat. Remember > it? No, and Google is not as great as we think it is. :( I did after extraordinary effort (on this my second try) find the original, but that was just an application of the macro, not its innards, and I did not get enough from his description to make out what it was all about. Worse, I could not find your follow-up objections. I had stopped following this thread to get some work done (and because I think the horse is dead). All I know is that you are trying to round up a lynch mob to string up WITH-MAINTAINED-CONDITION, and thet Lisp the language is doomed to eternal damnation if we on c.l.l. do not denounce it. :) No, seriously, what is your problem? That the macro would wlak the code of the condition to generate a demon that would not only test the condition but also do things to maintain the condition, based on its parsing of the code for the condition? You got a problem with that? Anyway, this is good, I was going to say this chit chat would be better if we had some actual macros to fight over. [Apologies up front: I am guessing left and right at both the macro and your objections. And ILC2003 starts tomorrow, so I may not get back to you all for a while.] kenny ps. Don't forget to read Paul Grahams Chapter's 1 & 8 in On Lisp, from now on I think it is pointless not to be debating what he said, vs what we are saying. The whole book is almost dedicated to macros. From the preface: "The title [On Lisp] is intended to stress the importance of bottom-up programming in Lisp. Instead of just writing your program in Lisp, you can write your own language on Lisp, and write your program in that. "It is possible to write programs bottom-up in any language, but Lisp is the most natural vehicle for this style of programming. In Lisp, bottom-up design is not a special technique reserved for unusually large or difficult programs. Any substantial program will be written partly in this style. Lisp was meant from the start to be an extensible language. The language itself is mostly a collection of Lisp functions, no different from the ones you define yourself. What?s more, Lisp functions can be expressed as lists, which are Lisp data structures. This means you can write Lisp functions which generate Lisp code. "A good Lisp programmer must know how to take advantage of this possibility. The usual way to do so is by defining a kind of operator called a macro. Mastering macros is one of the most important steps in moving from writing correct Lisp programs to writing beautiful ones. Introductory Lisp books have room for no more than a quick overview of macros: an explanation of what macros are,together with a few examples which hint at the strange and wonderful things you can do with them. "Those strange and wonderful things will receive special attention here. One of the aims of this book is to collect in one place all that people have till now had to learn from experience about macros." Alex, have you read On Lisp? -- http://tilton-technology.com What?! You are a newbie and you haven't answered my: http://alu.cliki.net/The%20Road%20to%20Lisp%20Survey From aahz at pythoncraft.com Sun Oct 12 11:15:45 2003 From: aahz at pythoncraft.com (Aahz) Date: 12 Oct 2003 11:15:45 -0400 Subject: use make and version control system for every project? References: <87wubi4ix9.fsf@pobox.com> <3F81BE4A.8B084E4B@alcyone.com> Message-ID: In article <3F81BE4A.8B084E4B at alcyone.com>, Erik Max Francis wrote: > >Sure. But source control (CVS or not; for personal use I use Perforce) >makes this process streamlined and automatic. Without it, if you want >incremental diffs you have to remember to make a copy of each revision >of each file you edit, naming them meaningfully for future. Source >control gets you this automatically, as well as allowing you to do >things like conveniently create branches, merge them back in to the main >line, etc. Why Perforce? Isn't that $$$ code? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From prunesquallor at comcast.net Wed Oct 22 11:05:06 2003 From: prunesquallor at comcast.net (prunesquallor at comcast.net) Date: Wed, 22 Oct 2003 15:05:06 GMT Subject: Why don't people like lisp? References: <8Nnlb.619$I04.380@newsread4.news.pas.earthlink.net> Message-ID: "Andrew Dalke" writes: > I was never any good at Intel assembly, and I thankfully haven't > touched it in about 15 years. I was trying to figure out if it > optimized the additions into 15**a, but I could see neither the > sequence 1, 2, 3, 4, 5 nor the value 15 (octal 17, hex F) anywhere > in the code. Pointers? When you read the raw machine code you have to remember that entities are tagged. I believe line 52 52: b0 3c movb al,$60 is the relevant one. 60 = 15 * 4, so it seems that this implementation represents fixnums by shifting left by two. From edi at agharta.de Sun Oct 26 05:40:58 2003 From: edi at agharta.de (Edi Weitz) Date: 26 Oct 2003 11:40:58 +0100 Subject: Whoa! Do Python and Lisp really have LAMBDA ? References: Message-ID: <87znfouvr9.fsf@bird.agharta.de> On Sun, 26 Oct 2003 11:08:12 +0100, Marcin 'Qrczak' Kowalczyk wrote: > On Sun, 26 Oct 2003 00:11:05 -0700, mike420 wrote: > > [...] > > I'm sure Haskell does this right. What about Scheme and ML? > > Indeed Haskell does this right. > > OCaml does this right. Just for the record: Common Lisp also does it right. The fact that it doesn't do what someone "expects" who hasn't read the spec doesn't make its behaviour wrong. As others have pointed out you can choose if you want all the closures to capture the same binding or if you want each closure to capture a new binding. This is a feature, not a bug. Edi. From stevewilliams at wwc.com Sun Oct 26 20:48:01 2003 From: stevewilliams at wwc.com (Steve Williams) Date: Mon, 27 Oct 2003 01:48:01 GMT Subject: Why Python style guide (PEP-8) says 4 space indents instead of 8 space??? 8 space indents ever ok?? In-Reply-To: References: <3F970FBF.85974E79@alcyone.com> Message-ID: Stephen Horne wrote: [snip] > Are there any tools which can intelligently redo the indentation in a > Python source file? Preferably respecting other formatting conventions > where practical, though of course I accept that no program could > replace a programmer with an eye for readability in this respect. > > .../Python.../Tools/Scripts/reindent.py From jmiller at stsci.edu Wed Oct 29 17:27:50 2003 From: jmiller at stsci.edu (Todd Miller) Date: Wed, 29 Oct 2003 17:27:50 -0500 Subject: gc assertion failure References: Message-ID: <3FA03EE6.7020805@stsci.edu> Todd Miller wrote: > Tim Peters wrote: > >> [Todd Miller] >> >>> I recently discovered an assertion failure in the Python garbage >>> collection system when scripts using our C extension (numarray) exit. >>> The assertion is activated for Pythons configured using >>> --with-pydebug. I have a feeling I may be doing something wrong >>> with garbage collection support for some of our c types, but I'm not >>> sure exactly what. >>> >>> Here is the assertion output: >>> >>> python: Modules/gcmodule.c:231: visit_decref: Assertion >>> `gc->gc.gc_refs != 0' failed. >>> Abort (core dumped) >> >> >> >> Looking at the source code should clarify: >> >> assert(gc->gc.gc_refs != 0); /* else refcount was too small */ >> >> That is, gc found more pointers to an object than that object's refcount >> believes exists. A missing Py_INCREF or an extra Py_DECREF are plausible >> causes; so is a bad tp_traverse function that passes a single containee >> multiple times (although I've only see that once in real life). A >> missing >> Py_INCREF is (IME) the most common cause for this assertion. >> >> >>> ... >>> #5 0x080e9222 in visit_decref (op=0x405adc74, data=0x0) at >>> Modules/gcmodule.c:231 >>> #6 0x0808cebf in tupletraverse (o=0x40a62f74, visit=0x80e9194 >>> , arg=0x0) at Objects/tupleobject.c:398 >> >> >> >> So it's complaing about an object that happens to be in a tuple. >> Displaying >> more info about op would tell you more about the kind of object it's >> complaining about. >> > > Thanks Tim! It turns out to be one of the objects numarray uses to > represent data type, Int64. I also noticed that the problem goes away > when I switch on the "Python prototype" for some C code, which is > further evidence that the problem is a ref count error since the code in > question just touches type objects, it doesn't implement them. > > I haven't found the bug yet, but I'm out of wheel lock. Definitely > makes my day... FWIW, here's what my bug looked like: < key = Py_BuildValue("(NNsNN)", _digest(in1), _digest(out), cumop, thread_id, type --- > key = Py_BuildValue("(NNsNO)", _digest(in1), _digest(out), cumop, thread_id, type Since I used "N" for type in the Py_BuildValue, it stole a reference to type which it shouldn't have. Switching to "O" made the Py_BuildValue reference count neutral for type and the problem was solved. Thanks for the help, Todd From sross at connectmail.carleton.ca Wed Oct 29 18:58:03 2003 From: sross at connectmail.carleton.ca (Sean Ross) Date: Wed, 29 Oct 2003 18:58:03 -0500 Subject: Dynamically creating attributes and methods References: Message-ID: wrote in message news:a783b99c09d1dabeb8dbc9841103767c at news.teranews.com... > Hi, > > I'm writing a DBI for my company's database. > I will have one class for each of the tables > in the database. > > I would then like each class, once instantiated, > to be able to read the field list from it's table, > and create properties based on each field, with > get/set methods created for accessing. > > The get/set methods could be the same for every > field, provided that I can determine the name > of the field(property) being accessed. > > Given a field name such as 'phone', how can I > give the class a home property, and then attach > that property to the get/set methods on the fly? > > Thanks, > > Toby > Hi. You may find this relevant: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/157768 HTH, Sean From terebinthus at go.com Wed Oct 1 17:41:44 2003 From: terebinthus at go.com (Penna Elabi) Date: 1 Oct 2003 14:41:44 -0700 Subject: Google newsgroup "Unable to find thread" message? References: Message-ID: <77081966.0310011341.7b8b2285@posting.google.com> steve at ferg.org (Stephen Ferg) wrote in message news:... > > I use the newsgroup mainly via my Web browser and Google. > > Over the last few days, when I click on a link to a thread, I've been > frequently getting the message "Unable to find thread." Google Groups is having problems, see this thread from the google.public.support.general newsgroup: http://groups.google.com/groups?&threadm=77081966.0309291030.125fdfe5%40posting.google.com From aleax at aleax.it Fri Oct 10 13:33:04 2003 From: aleax at aleax.it (Alex Martelli) Date: Fri, 10 Oct 2003 17:33:04 GMT Subject: Python syntax in Lisp and Scheme References: <8CVgb.8$KR3.1846@typhoon.nyu.edu> Message-ID: Kenny Tilton wrote: ... >>>But methinks a number of folks using Emacs Elisp and Autocad's embedded >>>Lisp are non-professionals. >> >> Methinks there are a great many more people using the VBA >> interface to AutoCAD than its Lisp interface. In fact, my friends >> (ex-Autodesk) told me that's the case. > > Sheesh, who hasn't been exposed to basic? From my generation, that is. > :) But no matter, the point is anyone can handled parens if they try for > more than an hour. Yes, but will that make them most happy or productive? The Autocad case appears to be relevant, though obviously only Autodesk knows for sure. When I was working in the mechanical CAD field, I had occasion to speak with many Autocad users -- typically mechanical drafters, or mechanical or civil engineers, by training and main working experience -- who HAD painfully (by their tales) learned to "handle parens", because their work required them occasionally to write Autocad macros and once upon a time Autolisp was the only practical way to do it -- BUT had jumped ship gleefully to the VBA interface, happily ditching years of Autolisp experience, just as soon as they possibly could (or earlier, i.e. when the VBA thingy was very new and still creaky in its integration with the rest of Autocad -- they'd rather brave the bugs of the creaky new VBA thingy than stay with the Autolisp devil they knew). I don't know if syntax was the main determinant. I do know that quite a few of those people had NOT had any previous exposure to any kind of Basic -- we're talking about mechanics-junkies, more likely to spend their spare time hot-rodding their cars at home (Bologna is, after all, about 20 Km from Ferrari, 20 Km on the other side from Minardi, while the Ducati motorcycle factory is right here in town, etc -- *serious* mechanics-freaks country!), rather than playing with the early home computers, or program for fun. So, I think Autocad does prove that non-professional programmers (mechanical designers needing to get their designs done faster) CAN learn to handle lisp if no alternatives are available -- and also that they'd rather not do so, if any alternatives are offered. (I don't know how good a lisp Autolisp is, anyway -- so, as I mentioned, there may well be NON-syntactical reasons for those guys' dislike of it despite years of necessarily using it as the only tool with which they could get their real job done -- but I have no data that could lead me to rule out syntax as a factor, at least for users who were OCCASIONAL users anyway, as programming never was their REAL, MAIN job, just means to an end). >>>You (Alex?) also worry about groups of programmers and whether what is >>>good for the gurus will be good for the lesser lights. >> >> If you ever hear me call anyone who is not an expert programmer >> a "lesser light" then I give you -- or anyone else here -- permission >> to smack me cross-side the head. > > Boy, you sure can read a lot into a casually chosen cliche. But can we > clear up once and for all whether these genius scientists are or are not > as good a programmer as you? I thought I heard Python being recommended > as better for non-professional programmers. Dunno 'bout Andrew, but -- if the scientists (or their employers) are paying Andrew for programming consultancy, training, and advice, would it not seem likely that they consider that he's better at those tasks than they are...? Otherwise why would they bother? Most likely the scientists are better than him at _other_ intellectual pursuits -- be it for reasons of nature, nurture, or whatever, need not interest us here, but it IS a fact that some people are better at some tasks. There is too much programming to be done, to let ONLY professional programmers do it -- just like there's too much driving to be done, to let only professional drivers do it -- still, the professionals can be expected to be better at their tasks of specialistic expertise. Alex From tim.ronning at start.no Thu Oct 30 15:03:56 2003 From: tim.ronning at start.no (Tim Ronning) Date: Thu, 30 Oct 2003 21:03:56 +0100 Subject: best GUI toolkit for python: tkinter, wxPython or what? Message-ID: >> for somebody who wants tostart small/medium GUI apps with python: >> what's the best toolkit: tkinter, wxPython or what? stability, ease of >> use >> and portability between mac and windows are the main criteria. > Portability is fine with all the main xplatform toolkits afaik, so NP > there. > In terms of ease of use and stability it's hard to beat tkinter, which > is barely changed since YEARS (can't get much stabler than that) -- and > quite easy for elementary tasks, too. > If you'd asked for looks, speed, screenpainters & suchlike tools, or > functional richness (particularly in terms of variety of widgets), the > answer might be different (and Qt, wx or GTK might then be preferred). > > Alex I myself is a novice in this game. But I couldn't help myself, so in paralell with learning the basics I fetched the Eric IDE, PyQt wrapper and the latest QT. Within minutes I was actually generateing really nice UI's. And the best thing of all, just compile your forms from within ERIC and, voila you have a python script including all the QT stuff. This is RAD. Best regards Tim Ronning -- Using M2, Opera's revolutionary e-mail client: http://www.opera.com/m2/ From itamarst at yahoo.com Tue Oct 28 13:47:31 2003 From: itamarst at yahoo.com (Itamar Shtull-Trauring) Date: 28 Oct 2003 10:47:31 -0800 Subject: Concurrency models (was: Timer) References: <3f9c9cdb$0$23610$5a62ac22@freenews.iinet.net.au> <3f9d1775$0$23584$5a62ac22@freenews.iinet.net.au> <3F9D77C4.A22FA169@hotmail.com> <3F9E74DB.3148DFD1@hotmail.com> Message-ID: <637b94bc.0310281047.59da9f26@posting.google.com> Alan Kennedy wrote in message news:<3F9E74DB.3148DFD1 at hotmail.com>... > My understanding is that using SSL in non-blocking mode is problematic > because SSL-level packets can trigger readiness notification on an SSL > socket when in fact there is no application-level data available. > > Here is a link that discusses the problem > > http://www.openssl.org/support/faq.html#PROG9 Twisted does the right thing and makes sure the user doesn't have to worry about this. Using SSL is just as easy as using TCP in Twisted. There are other issues with event loops, like the fact the RSA handshake is very expensive so you want to run it in another thread. If Twisted ever has performance issues due to this I'll probably change the code to do just that, move the handshake stage to a threadpool. From newsgroups at jhrothjr.com Thu Oct 30 20:05:06 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Thu, 30 Oct 2003 20:05:06 -0500 Subject: sorting a list of tupples References: Message-ID: "David Bear" wrote in message news:m3ptgegrp6.fsf at moroni.pp.asu.edu... > I have a list of tupples. Each tupple has 3 items. The first item is > an integer. I'd like to sort the list(of tupples), based on the first > element of the tupple. I thought about stringifying the tupples, then sorting > those, but thought there must be a better way. any idea's? .sort() should do the job, as long as you want the result to be a list in ascending order by the value of the first element of the tuple. John Roth > > --David Bear > phone: 480-965-8257 > fax: 480-965-9189 > College of Public Programs/ASU > Wilson Hall 232 > Tempe, AZ 85287-0803 > "Beware the IP portfolio, everyone will be suspect of trespassing" From p at trick.lu Wed Oct 15 13:52:09 2003 From: p at trick.lu (Patrick Useldinger) Date: Wed, 15 Oct 2003 19:52:09 +0200 Subject: newbie question! References: Message-ID: <562rovk3hrbpibv83q8j2e2p0edbk1v168@4ax.com> On Wed, 15 Oct 2003 18:33:22 +0100, "Brian" wrote: >Hi, im new to python and have a simple question... > >i want too have a list of values - say numbers of tables in a restaurant... >1,2,3,4,5. i want to associate a value with each of these numbers... eg. yes >or no. when a person books table 2, the value corresponding to 2 turns to no >[not available] etc... > usa a dictionnary, and boolean values True/False: # initialize tables = { 1:True, 2:True, 3:True } # customer reserves table 2 tables[2]=False # tables is now {1: True, 2: False, 3: True} From jegenye2001 at fw.hu Mon Oct 27 18:27:13 2003 From: jegenye2001 at fw.hu (Jegenye 2001 Bt) Date: Tue, 28 Oct 2003 00:27:13 +0100 Subject: SQL recordset -> XML References: <282f826a.0310271500.62fe7a5a@posting.google.com> Message-ID: Once I saw something like this... Sorry can't remember where and when.. They advocated a very simple shallow representation like this: dataetc.. and there was even an acronym for that. :) Best, Mikl?s -- PRISZNY?K Mikl?s --- Jegenye 2001 Bt. ( mailto:jegenye2001 at parkhosting.com ) Egyedi szoftverk?sz?t?s, tan?csad?s Custom software development, consulting http://jegenye2001.parkhosting.com Richard Shea wrote in message news:282f826a.0310271500.62fe7a5a at posting.google.com... > Hi - Not sure if this is a really stupid question or not ... so I > thought I'd ask it anyway ;-) > > I want to take data from a SQL generated recordset and represent it as > XML. > > I can think of *very* straightforward ways (as I'm sure all you can) > to do that (please excuse rough/weird pseudo code) ... > > if you had a recordset resulting from a query something like : > > select > Suburb_Value,City_Value > from > Table_Locations > ORDER BY CITY_VALUE,SUBURB_VALUE > > ... and you then did something like this (only a lot tidier) ... > > do while no_more_records > if Suburb_Value <> CurrentSuburb > output Closing_City_Tag > output Opening_City_Tag(City_Value) > end if > output Opening_Suburb_Tag > output Suburb_Value > output Closing_Suburb_Tag > end do > > ... you'd get what I'm after but it's all a bit clunky and of course > very specific the current recordset. > > I just wondered if anyone had written anything to at least help this > process a bit ? > > I'm in the process of reading the O'Reilly "XML and Python" book and > there's any amount of support for 'input XML' but nothing really to > assist with output. > > Is there a smart way to do this ? > > thanks > > richard shea. From mertz at gnosis.cx Wed Oct 22 12:47:42 2003 From: mertz at gnosis.cx (David Mertz) Date: Wed, 22 Oct 2003 12:47:42 -0400 Subject: [OT] Inuit? Eskimo? References: <20031020163642.GA5539@nl.linux.org> <4vre61-ku2.ln1@beastie.ix.netcom.com> <87vfqhri0b.fld@barrow.com> Message-ID: |Floyd Davidson: |> The term "Native American" is a coined word that the US Federal |> government came up with to reference *all* indigenous people in |> the US and its territories. Hence it includes American Indians, |> Eskimos, Aleuts, Hawaiians, Puerto Ricans, Guamanians "Andrew Dalke" wrote previously: |When did the phrase come into use? |also suprised about Puerto Rico in that list. I've never heard/read Native American used as widely as Floyd suggests. Only applying to the native peoples of the Americas. In the case of Puerto Rico, Columbus was thoroughly exterminationist; and likewise the rest of the Spanish conquistidor's in the Carribean after him. So the ENTIRE native population (Boricuas Indians) of Puerto Rico were slaughtered outright, or died of disease. And similarly in most of the Western Carribean. Yours, Lulu... -- Keeping medicines from the bloodstreams of the sick; food from the bellies of the hungry; books from the hands of the uneducated; technology from the underdeveloped; and putting advocates of freedom in prisons. Intellectual property is to the 21st century what the slave trade was to the 16th. From billspat at msu.edu Mon Oct 27 12:51:32 2003 From: billspat at msu.edu (Pat Bills) Date: 27 Oct 2003 17:51:32 GMT Subject: Best way to use Python to make 2d XY scatter graphs? Will TKinter do it? References: <616fccba.0310200250.22d55351@posting.google.com> Message-ID: rh4170056 at juno.com (rhmd) wrote in news:616fccba.0310200250.22d55351 @posting.google.com: > I need to create image files (eg bmp or jpeg) of xy scatter graphs > (i.e., graphs in which markers denote individual points; the markers > need to be small polygons of various sizes, shapes, colors, shadings, > etc. and there are thousands on them on each graph). Have been using > MS Excel, but its limitations are unbelievable (only whole number > sizes, no way around a 56 color palette, only low quality jpeg files > so that when I publish the graphs I have to print and scan them all to > get a decent image, no more than 32K markers in a single series). > From a programming point of view, Python is perfect to set up > something like this, but MY QUESTION IS: Will TKinter do this? Or > will it be necessary to learn OpenGL? Or is another Python compatible > package best? Thanks for your help. I would like to add a possible solution to those suggested. This may be off-topic and I don't know the context of the question. I, too, abandoned Excel as my graphing platform. If you are automating research processes and not writing software for distribution then I think the R environment (http://r-project.org) is worth a look. I've used it for several research projects and created graphs for publication. There are Python packages to call R from python, although complete programs can be written in R, which to my newbie eyes is very Python-like. The graphs can written to several formats (see below) and can paste into your favorite word/presentation processor. The added bonus is you get a wealth of statistical processes along with plotting (although you didn't mention this requirement in your post). There are several downsides: your program would require R to be installed on the system; batching R on windows does not work (for me); there is a learning curve; and parameters are a bit quirky (work like globals). http://r-project.org http://www.omegahat.org/RSPython/index.html http://rpy.sourceforge.net/ description from the R site: R is a language and environment for statistical computing and graphics. It is a GNU project which is similar to the S language and environment... One of R's strengths is the ease with which well-designed publication- quality plots can be produced, including mathematical symbols and formulae where needed. from the R help: The following graphics devices are currently available: * `postscript' Writes PostScript graphics commands to a file * `pdf' Write PDF graphics commands to a file * `pictex' Writes LaTeX/PicTeX graphics commands to a file * `windows' The graphics driver for Windows (on screen, to printer and to Windows metafile). * `png' PNG bitmap device * `jpeg' JPEG bitmap device * `bmp' BMP bitmap device * `xfig' Device for XFIG graphics file format * `bitmap' bitmap pseudo-device via `GhostScript' (if From mis6 at pitt.edu Wed Oct 22 11:06:36 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 22 Oct 2003 08:06:36 -0700 Subject: extending the break statement Message-ID: <2259b0e2.0310220706.142bf8cb@posting.google.com> Is there a way of "ending" a module? I would like something like this: # mod.py print 'something here' end() # some mysterious function print 'you should not get here' # main.py import mod print 'it works' I cannot use 'sys.exit' in place of ``end()``, since it would exit from the whole program and the line 'it works' would not be printed. I know that I can modify the main program to catch the SystemExit exception: # main.py try: import mod except SystemExit: pass print 'it works' but I find it really ugly, since I am forced to change by hand all the scripts importing 'mod'. Moreover, I am abusing ``SystemExit``; I should add instead a new built-in exception ``EndModule``, but this requires even more lines of code for something that should be trivial. On the other hand, I don't like the ``if 0:`` option, i.e. writing ``mod.py`` in the form # mod.py print 'something here' end() # some mysterious function if 0: print 'you should not get here' since it requires re-indenting by hand the (potentially long) block of code to be commented out. Yes, I know about C-c->, but honestly it is a PITA. Typically, I would like to comment out portions of experimental code during debugging; that code will enter in the final program at the end, so I must indent and re-indent it until it works (which means lots of times). More in general, one could think of an ``end()`` function with the ability of stopping the execution of the current frame and going back to the previous frame. One could even terminate classes in this way, i.e. skipping all the methods defined after the ``end()`` ... (some time passes) ... BTW, I have just realized that we don't need a new ``end()`` function: it would be enough to extend the ``break`` statement. Currently, it works only inside loops, why not to extend it to terminate classes and modules? IMHO, it would be very useful during debugging and refactoring. What do you people think? Or is there already same magic which can do what I ask for? If not, take it as a feature request ;-) Michele Simionato, Ph. D. MicheleSimionato at libero.it http://www.phyast.pitt.edu/~micheles/ ---- Currently looking for a job ---- From gat at jpl.nasa.gov Sun Oct 12 22:04:09 2003 From: gat at jpl.nasa.gov (Erann Gat) Date: Sun, 12 Oct 2003 19:04:09 -0700 Subject: Python syntax in Lisp and Scheme References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> <92c59a2c.0310031345.57d20631@posting.google.com> Message-ID: In article , Alex Martelli wrote: > Let's start with that WITH-CONDITION-MAINTAINED example of Gat. Remember > it? OK, now, since you don't appear to think it was an idiotic example, > then SHOW me how it takes the code for the condition it is to maintain and > the (obviously very complicated: starting a reactor, operating the reactor, > stopping the reactor -- these three primitives in this sequence) program > over which it is to maintain it, and how does it modify that code to ensure > this purpose. Surely, given its perfectly general name, that macro does not > contain, in itself, any model of the reactor; so it must somehow infer it > (guess it?) from the innards of the code it's analyzing and modifying. It is not necessary to exhibit a theory of how WITH-CONDITION-MAINTAINED actually works to understand that if one had such a theory one can package that theory for use more attractively as a macro than as a function. It is not impossible to package up this functionality as a function, but it's very awkward. Control constructs exist in programming languages for a reason, despite the fact that none of them are really "necessary". For example, we can dispense with IF statements and replace them with a purely functional IF construct that takes closures as arguments. Or we can do things the Java way and create a new Conditional object or some such thing. But it's more convenient to write an IF statement. The claim that macros are useful is nothing more and nothing less than the claim that the set of useful control constructs is not closed. You can believe that or not. To me it is self-evidently true, but I don't know how to convince someone that it's true who doesn't already believe it. It's rather like arguing over whether the Standard Model of Physics covers all the useful cases. There's no way to know until someone stumbles across a useful case that the Standard Model doesn't cover. > For example, the fact that Gat himself says that if what I want to write > are normal applications, macros are not for me: only for those who want > to push the boundaries of the possible are they worthwhile. Do you think > THAT is idiotic, or wise? Please explain either the reason of the drastic > disagreements in your camp, or why most of you do keep trying pushing > macros (and lisp in general) at those of us who are NOT particularly > interested in "living on the edge" and running big risks for their own sake, > accordingly to your answer to the preceding question, thanks. I can't speak for anyone but myself of course, but IMO nothing worthwhile is free of risks. I also think you overstate the magnitude of the risk. You paint nightmare scenarios of people "changing the language" willy-nilly in all sorts of divergent ways, but 1) in practice on a large project people tend not to do that and 2) Lisp provides mechanisms for isolating changes to the language and limiting the scope of their effect. So while the possibility exists that someone will change the language in a radical way, in practice this is not really a large risk. The risk of memory corruption in C is vastly larger than the risk of "language corruption" in Lisp, and most people seem to take that in stride. > ...and there's another who has just answered in the EXACTLY opposite > way -- that OF COURSE macros can do more than HOF's. So, collectively > speaking, you guys don't even KNOW whether those macros you love so > much are really necessary to do other things than non-macro HOFs allow > (qualification inserted to try to divert the silly objection, already made > by others on your side, that macros _are_ functions), or just pretty things > up a little bit. But all any high level language does is "pretty things up a bit". There's nothing you can do in any language that can't be done in machine language. "Prettying things up a bit" is the whole point. Denigrating "prettying things up a bit" is like denigrating cars because you can get from here to there just as well by walking, and all the car does is "speed things up a bit". E. From mike at nospam.com Mon Oct 13 16:26:59 2003 From: mike at nospam.com (Mike Rovner) Date: Mon, 13 Oct 2003 13:26:59 -0700 Subject: User comments on python.org References: <16266.63037.503883.538848@montanaro.dyndns.org> Message-ID: Skip Montanaro wrote: > amk> 1) Fitting the comments into the page design -- a page with > a lot amk> of comments would be really, really lengthy. > > I would prefer to see a little icon next to paragraphs with comments. > That minimizes the change in length. Click 'em to pop up a window > (or something) with the relevant comments. Given that we start with wiki comments, I'd prefer to have page coments rather than paragraph comments. Something like DocumentationComments/ref/imaginary for doc/current/ref/imaginary.html with page autocreation feature for new comments (with just back reference to the doc page and short invitation). > amk> 2) What if people post obscenities or harmful material? > pages, or at least to the RecentChanges page, so they are alerted > quickly to changes. Juergen, Guido and I have all reverted Wiki > changes. Wiki is being maintained, it's easy to undo changes, sofar this was not a problem. > I'd be against anything which actually modified the content of a page > as a result of adding a comment, if for no other reason than it would > have to integrate with ht2html+CVS, at least for the forseeable > future. I second that. Wiki is too volatile, let's doc maintainer to incorporate (valuable) wiki content into the real doc page (and update/remove wiki comments ;)) Mike From r.steffensen at c2i.net Fri Oct 17 03:45:42 2003 From: r.steffensen at c2i.net (Rune Steffensen) Date: Fri, 17 Oct 2003 07:45:42 GMT Subject: In need of c.l.p.discussion References: Message-ID: David M. Cook meditated and wrote something like this: > In article , Rune Steffensen wrote: > >> I've been lurking c.l.p for a while now, and find the amount of messages >> a bit annoying. > > I don't see the need. Most posts here are on topic. You just need the > discipline to ignore threads once they start to drift, or to hit "mark > all > read" (slrn uses the 'c' key which stands for "catch up", I believe) now > and > then. Believe me, I do have that discipline, I just find it a bit tiresome. Also, one of the weaknesses of my client (Opera, m2), is that you have to do this kind of deletion one time for each level of a thread. >> To solve this, I suggest the creation of the new group >> "comp.lang.pyhon.discussions". >> So when people post questions to c.l.p, they will get all the (more or >> less) helpfull answers there, but as soon as a discussion arise over an >> issue, one can Xfut to c.l.p.d. > > It simply wouldn't happen. Some people would not know how to do this, > some would forget, and some wouldn't bother. And where is the dividing > line? Well, I think that this view is a bit pessimistic, if only "a bit". Since I can count the support for my suggestion on NO hands, I can promise you that I will suggest this never again! On this group, that is. And maybe. :) -- -rune Incognito, ergo sum. From mike420 at ziplip.com Mon Oct 13 19:23:46 2003 From: mike420 at ziplip.com (mike420 at ziplip.com) Date: Mon, 13 Oct 2003 16:23:46 -0700 (PDT) Subject: BIG successes of Lisp (was ...) Message-ID: In the context of LATEX, some Pythonista asked what the big successes of Lisp were. I think there were at least three *big* successes. a. orbitz.com web site uses Lisp for algorithms, etc. b. Yahoo store was originally written in Lisp. c. Emacs The issues with these will probably come up, so I might as well mention them myself (which will also make this a more balanced post) a. AFAIK Orbitz frequently has to be shut down for maintenance (read "full garbage collection" - I'm just guessing: with generational garbage collection, you still have to do full garbage collection once in a while, and on a system like that it can take a while) b. AFAIK, Yahoo Store was eventually rewritten in a non-Lisp. Why? I'd tell you, but then I'd have to kill you :) c. Emacs has a reputation for being slow and bloated. But then it's not written in Common Lisp. Are ViaWeb and Orbitz bigger successes than LATEX? Do they have more users? It depends. Does viewing a PDF file made with LATEX make you a user of LATEX? Does visiting Yahoo store make you a user of ViaWeb? For the sake of being balanced: there were also some *big* failures, such as Lisp Machines. They failed because they could not compete with UNIX (SUN, SGI) in a time when performance, multi-userism and uptime were of prime importance. (Older LispM's just leaked memory until they were shut down, newer versions overcame that problem but others remained) Another big failure that is often _attributed_ to Lisp is AI, of course. But I don't think one should blame a language for AI not happening. Marvin Mins ky, for example, blames Robotics and Neural Networks for that. From donn at u.washington.edu Fri Oct 24 17:23:35 2003 From: donn at u.washington.edu (Donn Cave) Date: Fri, 24 Oct 2003 14:23:35 -0700 Subject: Why don't people like lisp? References: <3f9302d7.170372828@news.eircom.net> <3f96b046$0$556$b45e6eb0@senator-bedfellow.mit.edu> <20031022234546.GS1454@mapcar.org> <3f97eb1f$0$573$b45e6eb0@senator-bedfellow.mit.edu> <5627c6fa.0310230919.d2eb49a@posting.google.com> <3f9823b7$0$565$b45e6eb0@senator-bedfellow.mit.edu> <864qxz2if5.fsf@raw.grenland.fast.no> Message-ID: In article , "Rainer Deyke" wrote: > Peter Seibel wrote: >> But--and this is the bit I think you may have missed--if that's *not* >> what you want you don't use WITH-OPEN-FILE. Lisp also provides OPEN >> and CLOSE, that act as you'd expect and allow you to explicitly >> control the lifetime of the file stream. > > Which leads us back to having to manually close files. > > I DON'T want to manually close files. I DON'T want to deal with the > limitations of with-open-file. And, here's the important bit, I DON'T WANT > TO COMBINE OR CHOOSE BETWEEN THESE TWO METHODS, BOTH OF WHICH ARE FLAWED. > > What I want to open a file and have it close automatically when I am done > with it. I can do that in C++. Why can't I do it in Python? None of the above makes a whole lot of sense to me, and judging by the use of upper case I'm inclined to believe that discussing this with comp.lang.lisp participants has caused you to become disturbed. I am accordingly posting this only to comp.lang.python. You can have files close automatically in Python, but automatically isn't by itself a rather vacuous term, and `when I am done with it' doesn't help a bit. In C Python, when a file object is no longer referenced by any part of the program, it closes. If it's local to a function, including bound only to a function parameter or some such thing, that will occur when control returns from the function. Unless the file becomes involved in a circular reference, in which case the close will be deferred until the references are discovered and broken by the garbage collector. Unless the garbage collector is unable to do so because of some property of the members, such as a __del__ method. No doubt there is a great deal of C++ arcana that I have missed out on, but the basic finalization issues are the same as far as I know. C++ programmers aren't subject to the above exceptions only because they don't get any of the functionality to which these are exceptions! Function local objects are always deleted on return from the function regardless - and any other part of the program that retains a pointer to such an object will become unsound. Objects allocated on the heap have to be deleted explicitly, after which other parts of the program that reference them will become unsound. If you do a fraction of the explicit management that C++ requires, you can get reliable finalization. I am not familiar with with-open-file, but I imagine if you decide to write your software in Lisp, you will probably want to give it a try. There is also nothing wrong with closing a file explicitly. There are reasons for it that have nothing to do with the language, and then there is a school of thought (actually the party line for Python) that says you should explicitly close files in any case because the memory management rules are different for Java Python and could in theory change in a later release of C Python. Apparently Java's finalization is not immediate. Donn Cave, donn at u.washington.edu From mwh at python.net Thu Oct 2 11:47:43 2003 From: mwh at python.net (Michael Hudson) Date: Thu, 2 Oct 2003 15:47:43 GMT Subject: Where are "What's new" for 2.0, 2.1? References: <7h33cebu1b6.fsf@pc150.maths.bris.ac.uk> Message-ID: <7h3y8w3skuy.fsf@pc150.maths.bris.ac.uk> "Edward K. Ream" writes: > Thanks for these links. > > > How hard did you look? > > Interesting question. I looked where one would, I think, expect to > find these sections, namely in the documentation page at: > > http://www.python.org/doc/ > > and in particular, the "Previous versions" page at: > > http://www.python.org/doc/versions.html > > Are you suggesting that one should have to do a Google search to > find this stuff? Well, I'm not sure about "should have to", but it's what I did and I found the pages in about 10 seconds. > Did I miss a link from these pages that should have been obvious? No. What you perhaps didn't know is that the 2.0 and 2.1 versions of the documentation were not part of the official Python documentation but rather semi-independent efforts, and so *I*, knowing this, wouldn't have expected them to be on python.org. It would probably make sense if they or links to them did appear where you looked. Most of the pages for specific versions has links to the what's new document (http://www.python.org/2.1.3/ even has a link to both). The fact that the python.org site is not optimally organised is not news, I thought, though it's getting much better. Cheers, mwh -- [1] If you're lost in the woods, just bury some fibre in the ground carrying data. Fairly soon a JCB will be along to cut it for you - follow the JCB back to civilsation/hitch a lift. -- Simon Burr, cam.misc From amk at amk.ca Mon Oct 13 14:07:25 2003 From: amk at amk.ca (A.M. Kuchling) Date: Mon, 13 Oct 2003 13:07:25 -0500 Subject: User comments on python.org References: Message-ID: [CC'ing to pydotorg-redesign, and setting followups there, too.] On Sat, 11 Oct 2003 19:19:41 -0500, Ian Bicking wrote: > I don't really know how the Python site is set up now, but could > comments be included inline as an SSI? Like I don't think SSIs are currently enabled, but it wouldn't be hard to turn them on. However, I have two worries about this: 1) Fitting the comments into the page design -- a page with a lot of comments would be really, really lengthy. 2) What if people post obscenities or harmful material? Showing comments by default would be embarrassing; if you have to explicitly choose to view them, this is less worrying. Python.org has a really good Google PageRank, I expect, making it a good target for link spam, so this is something to worry about. The Wiki has mostly escaped such vandalism; presumably it's unobtrusive enough that spammers haven't noticed it. > the page content and the barest of controls). I think it would be best > done as a separate wiki, maybe with a namespace that fits the library > documentation structure better. Or maybe both are possible. It would Perhaps. Wiki names can contain '/', so we can have annotations for every single page on the site by just using the full path name. The question is whether we need that level of support; perhaps the docs are the only place where comments are valuable. I do think that comments on the reference manual or the Distutils manuals would be useful. (Possibly PEPs, too?) I did a bit of experimenting with the separate page, adding JavaScript to ht2html's output and adding an ugly 'view comment' link. If we're interested in pursuing this, I'm willing to do the following: 1) Make a set of experimental pages with comment links, so we can see what they look like and how they work in practice. 2) If 1) looks worthwhile, then I'll make a new Wiki for user notes that has minimal styling. What I'd really need is presentation suggestions: *how* to show the comment link? --amk From dokaspar at student.ethz.ch Tue Oct 28 14:36:29 2003 From: dokaspar at student.ethz.ch (Dominik Kaspar) Date: 28 Oct 2003 11:36:29 -0800 Subject: getopt, i don't get it Message-ID: <62e9c66e.0310281136.2248099b@posting.google.com> I tried to use getopt and copied the example from: http://www.python.org/doc/current/lib/module-getopt.html but nothing is working... getopt.GetoptError doesn't seem to exist and when i run the program commenting this out, none of "-v", "-h" and "-o" wants to be recognized... what's the matter?! Dominik import getopt, sys def usage(): print "Use it like this: bla bla bla" def main(): try: opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="]) except: # getopt.GetoptError: # print help information and exit: usage() sys.exit(2) output = None verbose = False for o, a in opts: if o == "-v": verbose = True if o in ("-h", "--help"): usage() sys.exit() if o in ("-o", "--output"): output = a # ... if __name__ == "__main__": main() From hans at zephyrfalcon.org Sat Oct 11 20:42:57 2003 From: hans at zephyrfalcon.org (Hans Nowak) Date: Sat, 11 Oct 2003 20:42:57 -0400 Subject: Python syntax in Lisp and Scheme In-Reply-To: <3f889589.2526891@news.syd.ihug.com.au> References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> <92c59a2c.0310031345.57d20631@posting.google.com> <3f889589.2526891@news.syd.ihug.com.au> Message-ID: dewatf wrote: > On Wed, 08 Oct 2003 18:28:36 +1300, "Greg Ewing (using news.cis.dfn.de)" > wrote: > > >>Hans Nowak wrote: >> >> >>>Hmm, if I recall correctly, in Latin the plural of 'virus' is 'virus'. >> >>Actually, the last discussion of this that I saw (can't remember where) >>came to the conclusion that the word 'virus' didn't *have* a plural >>in Latin at all, because its original meaning didn't refer to something >>countable. > > > 'virus' (slime, poison, venom) is a 2nd declension neuter noun and > technically does have a plural 'viri'. Doesn't it belong to the group that includes 'fructus'? Of course this has nothing to do with the plural used in English, but still... :-) This page, which has a lot of info on this issue, seems to think so: http://www.perl.com/language/misc/virus.html -- Hans (hans at zephyrfalcon.org) http://zephyrfalcon.org/ From john_bradbury at ___cableinet.co.uk Thu Oct 9 04:18:55 2003 From: john_bradbury at ___cableinet.co.uk (John Bradbury) Date: Thu, 9 Oct 2003 08:18:55 +0000 (UTC) Subject: WEBDEBUG PROXYSERVER References: Message-ID: Thanks I have not tried that program. I have tried Patel's proxy servers, but can not get them to work with 2.2. John Bradbury "JanC" wrote in message news:Xns940F4F5A527FAJanC at 213.118.75.228... > "John Bradbury" schreef: > > > Has anyone been able to get Webdebug or any of the various Proxy > > servers to work with Python 2.2 and WIN2K? > > I have used "tcpwatch" on Win98SE (not 2K) with both Python 2.2.x & 2.3.x. > > > -- > JanC > > "Be strict when sending and tolerant when receiving." > RFC 1958 - Architectural Principles of the Internet - section 3.9 From dsilva at ccs.neu.edu Wed Oct 8 12:50:39 2003 From: dsilva at ccs.neu.edu (Daniel P. M. Silva) Date: Wed, 08 Oct 2003 12:50:39 -0400 Subject: Python syntax in Lisp and Scheme References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> <92c59a2c.0310031345.57d20631@posting.google.com> Message-ID: Alex Martelli wrote: > Daniel P. M. Silva wrote: > ... >> You still can't add new binding constructs or safe parameterizations like >> a with_directory form: >> >> with_directory("/tmp", do_something()) >> >> Where do_something() would be evaluated with the current directory set to >> " tmp" and the old pwd would be restored afterward (even in the event of >> an exception). > > Right: you need to code this very differently, namely: > with_directory("/tmp", do_something) > *deferring* the call to do_something to within the with_directory > function. Python uses strict evaluation order, so if and when you > choose to explicitly CALL do_something() it gets called, > > So, I would code: > > def with_directory(thedir, thefunc, *args, **kwds): > pwd = os.getcwd() > try: return thefunc(*args, **kwds) > finally: os.chdir(pwd) > > this is of course a widespread idiom in Python, e.g. see > unittest.TestCase.assertRaises for example. > > The only annoyance here is that there is no good 'literal' form for > a code block (Python's lambda is too puny to count as such), so you > do have to *name* the 'thefunc' argument (with a 'def' statement -- > Python firmly separates statements from expressions). That was my point. You have to pass a callable object to with_directory, plus you have to save in that object any variables you might want to use, when you'd rather say: x = 7 with_directory("/tmp", print "well, now I'm in ", os.getpwd() print "x: ", x x = 3 ) >> Last year -- I think at LL2 -- someone showed how they added some sort of >> 'using "filename":' form to Python... by hacking the interpreter. > > A "using" statement (which would take a specialized object, surely not > a string, and call the object's entry/normal-exit/abnormal-exit methods) > might often be a good alternative to try/finally (which makes no provision > for 'entry', i.e. setting up, and draws no distinction between normal > and abnormal 'exits' -- often one doesn't care, but sometimes yes). On > this, I've seen some consensus on python-dev; but not (yet?) enough on > the details. Consensus is culturally important, even though in the end > Guido decides: we are keen to ensure we all keep using the same language, > rather than ever fragmenting it into incompatible dialects. The point is that the language spec itself is changed (along with the interpreter in C!) to add that statement. I would be happier if I could write syntax extensions myself, in Python, and if those extensions worked on CPython, Jython, Python.Net, Spy, etc. > > >> Some people use Python's hooks to create little languages inside Python >> (eg. to change the meaning of instantiation), which are not free of >> problems: >> >> class Object(object): >> def __init__(this, *args, **kwargs): > > [invariably spelt as 'self', not 'this', but that's another issue] > >> this.rest = args >> this.keys = kwargs >> >> def new_obj_id(count=[0]): >> count[0] = count[0] + 1 >> return count[0] >> >> def tag_obj(obj, id): >> obj.object_id = id >> return obj >> >> def obj_id(obj): return obj.object_id >> >> type.__setattr__(Object, "__new__", staticmethod(lambda type, *args: >> tag_obj(object.__new__(type), new_obj_id()))) > ... >> # forgot to check for this case... >> print Object(foo="bar") > > It's not an issue of "checking": you have written (in very obscure > and unreadable fashion) a callable which you want to accept (and > ignore) keyword arguments, but have coded it in such a way that it > in fact refuses keyword arguments. Just add the **kwds after the > *args. This bug is not really related to "little languages" at all: > you might forget to specify arguments which you do want your callable > to accept and ignore in a wide variety of other contexts, too. I think changing the meaning of __new__ is a pretty big language modification... - Daniel From timr at probo.com Sat Oct 18 23:43:19 2003 From: timr at probo.com (Tim Roberts) Date: Sat, 18 Oct 2003 20:43:19 -0700 Subject: For variables outside loop causes exception References: Message-ID: <0v14pv0snbii1c8igqjidm4ivnvf53mpf3@4ax.com> "Gordon Williams" wrote: > >I have been using this code for a number of weeks without problems. Now I >am getting an exception after the program has run a short while. It has >already passed through this function several hundred time before the >exception. > >The code in the function is (exactly as shown): > > for i, obsData in enumerate(epochData): > Pcor[i] = obsData[3] > Xs[i] = obsData[4] > > Asub, Lsub= Solve_all.model_matrix(Xs[:i+1], Pcor[:i+1],Xr) > >The exception is: > > Asub, Lsub= Solve_all.model_matrix(Xs[:i+1], Pcor[:i+1],Xr) >UnboundLocalError: local variable 'i' referenced before assignment > >What is the problem here? It appears that i has gone out of scope. The most likely problem is that epochData is empty. If the range is empty, the for variables do not get assigned. You can check for that via "if not epochData", if you need to. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From gilham at snapdragon.csl.sri.com Tue Oct 14 22:27:16 2003 From: gilham at snapdragon.csl.sri.com (Fred Gilham) Date: 14 Oct 2003 19:27:16 -0700 Subject: BIG successes of Lisp (was ...) References: Message-ID: John Thingstad writes: > You all seem to forget www.google.com > One of the most used distributed applications in the world. > Written in Common Lisp (xanalysis) Nah, google runs on 10K (yes, ten thousand) computers and is written in C++. Norvig in his talk at the last Lisp conference explained all this. He said this gave them the ability to patch and upgrade without taking the whole system down --- they'd just do it machine-by-machine. -- Fred Gilham gilham at csl.sri.com The density of a textbook must be inversely proportional to the density of the students using it. --- Dave Stringer-Calvert From mwh at python.net Mon Oct 13 08:03:58 2003 From: mwh at python.net (Michael Hudson) Date: Mon, 13 Oct 2003 12:03:58 GMT Subject: type checking References: <1065938227.288329@yasure> <8eaib.269339$R32.8774481@news2.tin.it> Message-ID: <7h3y8vp9whu.fsf@pc150.maths.bris.ac.uk> Stephen Horne <$$$$$$$$$$$$$$$$$@$$$$$$$$$$$$$$$$$$$$.co.uk> writes: > In Python, it doesn't seem to be an issue - presumably because Pythons > garbage collection is based on reference counting so destruction > happens immediately when the last reference has gone. I'm not sure > what happens when there are reference cycles, though - I know Python > handles them, but I'm not sure if they delay the garbage collection. They do. By how much, well, depends. Cheers, mwh -- I'm okay with intellegent buildings, I'm okay with non-sentient buildings. I have serious reservations about stupid buildings. -- Dan Sheppard, ucam.chat (from Owen Dunn's summary of the year) From drush at aol.net Mon Oct 6 16:49:08 2003 From: drush at aol.net (David Rush) Date: Mon, 06 Oct 2003 21:49:08 +0100 Subject: Python syntax in Lisp and Scheme References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> <92c59a2c.0310031345.57d20631@posting.google.com> <8b9e2260.0310032317.72abd86a@posting.google.com> <8b9e2260.0310040524.229dfd9f@posting.google.com> Message-ID: On Sat, 04 Oct 2003 17:02:41 GMT, Alex Martelli wrote: > Guido's generally adamant stance for simplicity has been the > key determinant in the evolution of Python. Simplicity is good. I'm just finding it harder to believe that Guido's perception of simplicity is accurate. > Anybody who doesn't value simplicity and uniformity is quite > unlikely to be comfortable with Python I would say that one of the reasons why I program in Scheme is *because* I value simplicity and uniformity. The way that Python has been described in this discussion make me think that I would really *hate* Python for it's unecessary complications if I went back to it. And I have spent years admiring Python from afar. The only reason I didn't adopt it years ago was that it was lagging behind the releases of Tk which I needed for my cross-platform aspirations. At the time, I actually enjoyed programming in Python as a cheaper form of Smalltalk (literally, Unix Smalltalk environments were going for $4000/seat). Probably the most I can say now is that I think that Python's syntax is unecessarily reviled (and there are a *lot* of people who think that Python's syntax is *horrible* - I am not one of them mind you), in much the same way that s-expressions are a stumbling block for programmers from infix-punctuation language communities. david rush -- (\x.(x x) \x.(x x)) -> (s i i (s i i)) -- aki helin (on comp.lang.scheme) From fumanchu at amor.org Wed Oct 8 19:40:39 2003 From: fumanchu at amor.org (Robert Brewer) Date: Wed, 8 Oct 2003 16:40:39 -0700 Subject: Newbie needs to see a large project Message-ID: > > Unfortunately, people (especially management) have caught the meme > > that says "using multiple languages is bad".... [snip] > > Why don't business users understand these arguments, or believe > > people's experiences? Alan Gauld: > Because they believe high powered consultancies, like Gartner, > Forester etc... rather than their own people! > And because they live in hpe of finding the silver bullet that > will cut their IT spend... Hmmm. Ask around. I think you'll find they're looking rather to make programmers a commodity that can be fired and hired at will; this leads to the use of "language experience" rather than "coding experience" as a metric. They believe programming is the use of someone else's tool, not the creation of a new one. Certain large software development houses feed this notion at every opportunity. Robert Brewer MIS Amor Ministries fumanchu at amor.org From mis6 at pitt.edu Tue Oct 28 08:29:33 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 28 Oct 2003 05:29:33 -0800 Subject: AI and cognitive psychology rant (getting more and more OT - tell me if I should shut up) References: <0KRib.213549$hE5.7197672@news1.tin.it> <7id6cz7rl4.fsf@enark.csis.hku.hk> <9XVib.214859$hE5.7243121@news1.tin.it> <3ovpovc9hmahv5g373jm2oo7mk3i83ldtb@4ax.com> <29cjb.218983$hE5.7379913@news1.tin.it> <5tksov8r4c3caoatfoslfi87q61dupaq81@4ax.com> Message-ID: <2259b0e2.0310280529.19b75504@posting.google.com> anton at vredegoor.doge.nl (Anton Vredegoor) wrote in message news:... > There *is* no fixed past. George Orwell's "1984" makes always a great reading. Michele From aleaxit at yahoo.com Wed Oct 15 17:52:32 2003 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 15 Oct 2003 21:52:32 GMT Subject: inner classes in python as inner classes in Java References: Message-ID: Carlo v. Dango wrote: >> Do you TRULY want to delegate all >> attribute settings, performed on an instance of the innerclass, to the >> corresponding 'outer' -- _except_ self.outer? > > No, what a strange idea ;-) All attributes not found in the class should > be forwarded to it's outer instance (as I want to simulate that the inner > class instance is within the scope of its outer class instance. What does "found" have to do with attribute setting? In Python: class X: pass x=X() x.foo=23 sets attribute named 'foo' to the value of 23 on x. "found"...?! What can you possibly mean? You'll have to decide what semantics you want to obtain when an attribute is set on an instance of the "inner class" -- I sure can't do it on your behalf. >> tabs (your post was indented with tabs thus unreadable with such >> newsreaders as KDE's KNode, Outlook Express, et al: please do >> NOT post code indented with tabs, thanks). > > why is that? has TAB-technology not reached linux yet? :) I try to > remember it, I just prefer tabs over spaces.. There's a reason the official Python style guidelines have been amended to prefer spaces instead of tabs, you know. Sure, there will be some programs who display tabs in a way compatible with your preferences, but others won't; be conservative in what you generate -- spaces are ensured to be displayed as you intend, tabs are NOT, so don't use the latter in any code you send to others. >> class B, but, in any case, this is how to do this kind of >> automatic delegation in Python. > > actually its forwarding or consultation, as self is re-bound when you > invoke the outer.. In your Python code (and mine), it is false that "self is re-bound" (only an instruction such as "self = ..." would do that, and there is no such instruction in that code). Sure, when a method A of object B calls a method X of object Y, the local name 'self' is bound to Y in the execution of X while the same name is bound to B in the execution of A. But that is not re-binding -- just the distinction between lexically-same names in different scopes. Anyway, the term "delegation" is common for the operation in question - it is for example used in the "gang of 4"'s Design Pattern book. Alex From aleaxit at yahoo.com Fri Oct 10 05:12:12 2003 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 10 Oct 2003 11:12:12 +0200 Subject: Python syntax in Lisp and Scheme In-Reply-To: <2753A5C8-FAD5-11D7-9416-000A95AF1FAE@dberlin.org> References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> <2753A5C8-FAD5-11D7-9416-000A95AF1FAE@dberlin.org> Message-ID: <200310101112.12374.aleaxit@yahoo.com> On Friday 10 October 2003 05:52 am, Daniel Berlin wrote: > On Oct 9, 2003, at 5:33 PM, Alex Martelli wrote: > > Rainer Deyke wrote: > >> Pascal Costanza wrote: > >>> Pick the one Common Lisp implementation that provides the stuff you > >>> need. If no Common Lisp implementation provides all the stuff you > >>> need, write your own libraries or pick a different language. It's as > >>> simple as that. > >> > >> Coming from a C/C++ background, I'm surprised by this attitude. Is > >> portability of code across different language implementations not a > >> priority for LISP programmers? > > > > Libraries distributed as binaries are not portable across different C++ > > implementations on the same machine (as a rule). > > This isn't true anymore (IE for newer compilers). Wow, that IS great news! Does it apply to 32-bit Intel-oid machines (the most widespread architecture) and the newest releases of MS VC++ (7.1) and gcc, the most widespread compilers for it? I can't find any docs on what switches or whatever I should give the two compilers to get seamless interop. Specifically, the standard Python on Windows has long been built with MSVC++ and this has given problems to C-coded extension writers who don't own that product -- it IS possible to use other compilers to build the extensions, but only with much pain and some limitations (e.g on FILE* arguments). If this has now gone away there would be much rejoicing -- with proper docs on the Python side of things and/or use of whatever switches are needed to enable this, if any, when we do the standard Python build on Windows. > Mangling, exception handling, etc, is all covered by the ABI. > > IBM's XLC 6.0 for OSX also follows this C++ ABI, and is thus compatible > with G++ 3.x on OSX. I'm not very familiar with Python on the Mac but I think it uses another commercial compiler (perhaps Metrowerks?), so I suspect the same question may apply here. It's not as crucial on other architectures where Python is more normally built with free compilers, but it sure WOULD still be nice to think of possible use of costly commercial compilers with hypothetically great optimizations for the distribution of some "hotspot" object files, if that sped the interpreter up without giving any interoperability problems. Alex From godoy at metalab.unc.edu Wed Oct 1 07:39:04 2003 From: godoy at metalab.unc.edu (Jorge Godoy) Date: Wed, 01 Oct 2003 08:39:04 -0300 Subject: [SOLVED] Re: Threading and Windows. References: Message-ID: bokr at oz.net (Bengt Richter) writes: >>OK... I tracked it down and found the 'P_NOWAIT' didn't work. I >>replaced it with '1' (no quotes) and everything went fine on bot OSs. >> > What is os.P_NOWAIT on your system? It looks like '1' (no quotes) on my system: > > >>> import os > >>> os.name > 'nt' > >>> os.P_NOWAIT > 1 It is '1', just as in yours. I was saying that there's no 'P_NOWAIT' (with quotes and no 'os.' prefix). :-) > So one would think > > os.spawnv(os.P_NOWAIT, 'c:/python22/pythonw.exe', > ['c:/python22/pythonw.exe', 'another.py', parameter]) Exactly. In fact it ended up as (this is in a separate method on the main program): if (sys.platform == 'win32'): python = 'c:/python22/pythonw.exe' os.spawnv(os.P_NOWAIT, python, [python, program, parameter]) else: os.spawnv(os.P_NOWAIT, program, [program, parameter]) > would work, except I note that os.P_NOWAIT is not defined in Python 1.5.2 on Linux (slackware). > Gotta upgrade one of these days... My nt python is 2.3 though, but I don't suppose that's changed > since the 2.2 you are apparently running on windows?? I'm running 2.2 on both platforms and with the 'os.' prefix everything worked. :-) Thanks, -- Godoy. From rossberg at ps.uni-sb.de Tue Oct 28 07:12:12 2003 From: rossberg at ps.uni-sb.de (Andreas Rossberg) Date: Tue, 28 Oct 2003 13:12:12 +0100 Subject: Python from Wise Guy's Viewpoint References: <6dnq61-kl.ln1@ID-7776.user.dfncis.de> <87oew33h8t.fsf@sidious.geddis.org> <3F9D5D21.2060408@ps.uni-sb.de> <20031027184024.GO1454@mapcar.org> Message-ID: <3F9E5D1C.3050103@ps.uni-sb.de> Matthew Danish wrote: >> >>Here is a very trivial example, in SML: >> >> 20 * 30 >> >>Multiplication, as well as literals, are overloaded. Depending on >>whether you type this expression as Int8.int (8-bit integers) or >>IntInf.int (infinite precision integer) the result is either 600 or an >>overflow exception. > > May I point out that the correct answer is 600, not overflow? No, it's not. If I choose type Int8 then I do so precisely for the reason that I want to be signalled if some computation overflows the intended value domain. Otherwise I had chosen IntInf or something. You see, this is exactly the reason why I say that the type system gives you expressiveness. > Something that annoys me about many statically-typed languages is the > insistence that arithmetic operations should return the same type as the > operands. I should note in this context is that static types usually express different things than dynamic ones, especially when it comes to number types. In Lisp, the runtime tag of a number will usually describe the representation of the number. This may well change between operations. But static typing, at least in high-level languages, is about semantics. If I choose a certain integer type I do so because it has the desired domain, which I want to have checked - I'm not at all interested in its representation. In fact, values of IntInf are likely to have multiple representations depending on their size, but the type is invariant, abstracting away from such low-level representation details. Actually, I think dynamic typing should abstract from this as well, but unfortunately this does not seem to happen. > 2 / 4 is 1/2, not 0. Integer division is not real division (and should not use the same name). > Arithmetically, 1 * 1.0 is > well-defined, so why can I not write this in an SML program? Because the designers decided (rightly so, IMHO) that it is best to avoid implicit conversions, since they might introduce subtle bugs and does not coexist well with type inference. But anyway, this has nothing to do with static vs dynamic typing - C allows the above, and there might well be dynamic languages that raise a runtime error if you try it. > I do believe Haskell does it right, though, with its numeric tower > derived from Lisp. Yes, in Haskell you can write the above, but for slightly different reasons (integer literals are overloaded for floating types). - Andreas -- Andreas Rossberg, rossberg at ps.uni-sb.de "Computer games don't affect kids; I mean if Pac Man affected us as kids, we would all be running around in darkened rooms, munching magic pills, and listening to repetitive electronic music." - Kristian Wilson, Nintendo Inc. From visionary25 at _nospam_hotmail.com Fri Oct 17 15:48:47 2003 From: visionary25 at _nospam_hotmail.com (Vis Mike) Date: Fri, 17 Oct 2003 12:48:47 -0700 Subject: Express What, not How. References: <9d140b81.0310151301.4b811dfa@posting.google.com> Message-ID: "Luke Gorrie" wrote in message news:lhad81igl6.fsf at dodo.bluetail.com... > ketil+news at ii.uib.no writes: > > > Anonymous functions *can* be more clear than any name. Either because > > they are short and simple, because it is hard to come up with a good > > name, and/or becuase they are ambigous. > > > > Say I want to attach an index to elements of a list. I could write > > > > integers = [1..] > > attach_index ls = zip integers ls > > > > or just > > > > attach_index ls = zip [1..] ls > > If we're arguing to eliminate names that don't say very much, then > > attach_index = zip [1..] I think dynamic scoping within blocks really trims down on duplication and make the code easier to read. For example: employees sort: [ | a b | a date < b date ] A lot of typing for a simple concept: employees sort: [ < data ] I'm not against too much typing to be clear, but rather too much typping that makes the concept unclear. -- Mike > > Whether you want to give an explicit name to the list of integers is > > not given. If the indexed list is local, it is better to use the > > definition directly; I don't want to look up the definition of > > integers (perhaps in a different module) to check whether it is [1..] > > or [0..]. > > And for the exact same reason you might like to just write "zip [1..]" > instead of using a separate "attach_index" function. > > Cheers, > Luke > From mwh at python.net Fri Oct 31 10:13:24 2003 From: mwh at python.net (Michael Hudson) Date: Fri, 31 Oct 2003 15:13:24 GMT Subject: syntax highlightening References: <2259b0e2.0310310704.bbc1ce9@posting.google.com> Message-ID: <7h3k76lla2b.fsf@pc150.maths.bris.ac.uk> mis6 at pitt.edu (Michele Simionato) writes: > I would like to change the pre-defined colors in the Emacs > python mode, but I don't have any clue on how to do it. > Somebody can help here? Move point over the color you want to change. Execute "M-x customize-face", hit return and play around. There may be a more systematic way of doing this, but I don't know what... Cheers, mwh -- > Look I don't know. Thankyou everyone for arguing me round in > circles. No need for thanks, ma'am; that's what we're here for. -- LNR & Michael M Mason, cam.misc From gerrit at nl.linux.org Wed Oct 15 07:17:56 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Wed, 15 Oct 2003 13:17:56 +0200 Subject: else on the same line - howto In-Reply-To: References: Message-ID: <20031015111756.GA3189@nl.linux.org> Helmut Jarausch wrote: > Sorry for this trivial question > > Since Python lacks conditional expression > > like > > k+= (dy >= 0 ? 1 : -1) See PEP 308 and google for PEP 308 (on Google groups) for background information. > I would like to write > if dy >= 0 : k+= 1; else: k-= 1 You can't. > instead of > if dy >= 0 : k+= 1 > else : k-= 1 Why do you want to obscure you're own code? Gerrit Holl. -- 40. He may sell field, garden, and house to a merchant (royal agents) or to any other public official, the buyer holding field, house, and garden for its usufruct. -- 1780 BC, Hammurabi, Code of Law -- Asperger Syndroom - een persoonlijke benadering: http://people.nl.linux.org/~gerrit/ Kom in verzet tegen dit kabinet: http://www.sp.nl/ From peter at engcorp.com Sat Oct 4 21:29:25 2003 From: peter at engcorp.com (Peter Hansen) Date: Sat, 04 Oct 2003 21:29:25 -0400 Subject: socket.bind References: Message-ID: <3F7F73F5.D402A3C7@engcorp.com> sashan wrote: > > I'm writing a program using sockets. I'm binding to a port like this: > > PORT = 5000 # Arbitrary non-privileged port > s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > s.bind((HOST, PORT)) > s.listen(1) > > Now sometimes the rest of the program crashes later for whatever reason. > As a result this leaves a socket bound to port 5000. When I try to run > my program again it crashes at > > s.bind((HOST, PORT)) > > saying that the port is still in use. How do I unbind that port? I've > killed the previous program using the system monitor in Gnome. You need to use setsockopt() to set the SO_REUSE_ADDR option: yourSock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) -Peter From whumeniu at nospamtelus.net Tue Oct 14 16:39:33 2003 From: whumeniu at nospamtelus.net (Wade Humeniuk) Date: Tue, 14 Oct 2003 20:39:33 GMT Subject: Why don't people like lisp? In-Reply-To: <86ecnT2RX9nDxhGiXTWJlg@comcast.com> References: <86ecnT2RX9nDxhGiXTWJlg@comcast.com> Message-ID: <9aZib.4$pt4.1610@news1.telusplanet.net> Terry Reedy wrote: > My contemporaneous impression, correct or not, as formed from > miscellaneous mentions in the computer press and computer shows, was > that they were expensive, slow, and limited -- limited in the sense of > being specialized to running Lisp, rather than any language I might > want to use. I can understand that a dedicated Lisper would not > consider Lisp-only to be a real limitation, but for the rest of us... > Well its not true. Symbolics for one supported additional languages, and I am sure others have pointed out that are C compilers for the Lisp Machines. See http://kogs-www.informatik.uni-hamburg.de/~moeller/symbolics-info/symbolics-tech-summary.html Section: Other Languages It says that Prolog, Fortran and Pascal were available. Wade From seberino at spawar.navy.mil Thu Oct 23 02:51:58 2003 From: seberino at spawar.navy.mil (Christian Seberino) Date: 22 Oct 2003 23:51:58 -0700 Subject: Why Python style guide (PEP-8) says 4 space indents instead of 8 space??? 8 space indents ever ok?? References: Message-ID: Ian I thought about your example and adjusted last line to fit in 80 columns... class Whatever: def method(self, someArg, someOtherArg): for smallerPiece in someArg: if smallerPiece.isValid(): newSmallerPiece = someOtherArg.doSomethingWith(smallerPiece) Here is the 4 space indent version: class Whatever: def method(self, someArg, someOtherArg): for smallerPiece in someArg: if smallerPiece.isValid(): newSmallerPiece = someOtherArg.doSomethingWith(smallerPiece) Each has trade offs.... I don't like breaking last line into 2 pieces but at least "class", "def", "for" and "if" don't blend into each other as easily as in the 2nd example. I'm not convinced yet of 4 space tabs but your point is well taken. Thanks, Chris Ian Bicking wrote in message news:... > On Wednesday, October 22, 2003, at 05:31 PM, Christian Seberino wrote: > > Linux kernel style guide, Guido's C style guide and (I believe) old > > K&R style recommends 8 SPACES for indent. > > > > I finally got convinced of wisdom of 8 space indentation. > > > > Guido also likes 8 space indentation FOR C CODE. > > > > Why style guide (PEP-8) for Python says 4 space indents??? > > > > Is breaking rule to use 8 space indents everywhere > > a REALLY bad idea?? > > > > I REALLY WANT TO DO MY OPEN SOURCE PYTHON PROJECT > > WITH 8 SPACE IDENTS!!!! > > You can, it's just kind of annoying. Typically I work with two indents > at a minimum, because most (of my) code is in a method of a class. > With 8 spaces that's 20% of the space gone. And when using long names, > that means I can end up with word wrapping problems pretty quickly. > Even if I do as little nesting as possible, consider this (quite > reasonable) level of nesting: > > class Whatever: > def method(self, someArg, someOtherArg): > for smallerPiece in someArg: > if smallerPiece.isValid(): > newSmallerPiece = > someOtherArg.doSomethingWith(smallerPiece) > > I hope that turns out okay, since my mail client wrapped it (but then > that was the point ;). I would not consider this level of nesting to > be bad programming, or programming that is in need of refactoring. I > didn't even do tuple unpacking in that assignment... > > Maybe I would be more concerned with too much nesting if I was > programming in C. C is more apt to have subtle and dangerous problems, > so you want to avoid even localized complexity. You do a lot more > things in place in C, while Python uses more return values. Because of > exceptions you don't have to use the small chunks of code that C > requires for error detection. > > But that's just my own opinion, you can do what you want (just don't > use tabs ;). From rainerd at eldwood.com Fri Oct 3 16:03:12 2003 From: rainerd at eldwood.com (Rainer Deyke) Date: Fri, 03 Oct 2003 20:03:12 GMT Subject: negative numbers and integer division References: Message-ID: <4Ckfb.30189$%h1.17332@sccrnsc02> Matthew Wilson wrote: > I thought that -1 // 12 would be 0 also. I'm writing a simple monthly > date class and i need (-1,2001) to be translated to (11,2000). Any > ideas? Luckily for you, Python integer division does the right thing. You *want* -1 // 12 to be -1 for your application. def normalize_date(month, year): return (month % 12, year + month // 12) normalize_date(-1, 2001) # Returns (11, 2000) 'normalize_date' as given assumes 'month' is in the range from 0 to 11; use this if your months are in the range from 1 to 12: def normalize_date(month, year): return ((month - 1) % 12 + 1, year + (month - 1) // 12) -- Rainer Deyke - rainerd at eldwood.com - http://eldwood.com From FBatista at uniFON.com.ar Thu Oct 23 09:20:41 2003 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Thu, 23 Oct 2003 10:20:41 -0300 Subject: need advices... accessing a huge collection Message-ID: GrelEns wrote: #- having almost 1,000 tar.gz files in different directories #- (could not change #- that) and these archives contain over 1,000,000 text files. #- I would like to #- build a tool to access as quickly as possible any or #- sub-collection of these #- text files to serve them by http upon user request. Two general questions: 1. How long is each text file? 2. Based in what information you serve what data? Are you asked for the name of the file? You serve the full file? . 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 maney at pobox.com Fri Oct 17 17:18:16 2003 From: maney at pobox.com (Martin Maney) Date: Fri, 17 Oct 2003 21:18:16 +0000 (UTC) Subject: question: usage of __slots__ References: <3F89620C.4080605@snafu.de> <698f09f8.0310132012.738e22fc@posting.google.com> <698f09f8.0310151939.5692369a@posting.google.com> Message-ID: Aahz wrote: > In article <698f09f8.0310151939.5692369a at posting.google.com>, > Jeremy Fincher wrote: >>Are you claiming that Guido would, without exception, call __slots__ a >>"premature optimization"? > No, but I don't think he would disagree with that statement in casual > conversation. I dunno, greeny. That bit about being surprised (and perhaps appalled) at its popularity with novices suggests he might prefer to call it an optimization for the post-mature programmer... -- Some kinds of waste really are disgusting. SUVs, for example, would arguably be gross even if they ran on a fuel which would never run out and generated no pollution. SUVs are gross because they're the solution to a gross problem. (How to make minivans look more masculine.) -- Paul Graham From raffaelcavallaro at junk.mail.me.not.mac.com Wed Oct 15 22:50:28 2003 From: raffaelcavallaro at junk.mail.me.not.mac.com (Raffael Cavallaro) Date: Thu, 16 Oct 2003 02:50:28 GMT Subject: Express What, not How. References: <9d140b81.0310151301.4b811dfa@posting.google.com> Message-ID: In article <9d140b81.0310151301.4b811dfa at posting.google.com>, ddarius at hotpop.com (Darius) wrote: > The reason people are attacking your posts is because the above has > NOTHING to do with anonymous functions. This advice should be > followed independent of anonymous functions. You're misreading those who have argued against me. They seem to think that this advice should _not_ be followed in the case of anonymous functions. I.e., the anonymous function camp seem to think that anonymous functions are such a wonderfully expressive tool that they are more clear than _actual desriptive function names_. I agree with you; this advice should be followed, period (well, it is _my_ advice, after all). But advocates of a particular functional style think it is perfectly alright to use the same unnamed functional idiom over and over throughout source code, because functional abstractions are so wonderfully expressive. They think it is just fine to expose the implementation details in code locations where it is completely unnecessary to know the implementation specifics. How else can this be construed? In article , Marcin 'Qrczak' Kowalczyk wrote: > A name is an extra level of indirection. You must follow it to be > 100% sure what the function means, or to understand what does it really > mean that it does what it's named after. The code also gets longer - not > only more verbose but the structure of the code gets more complex with > more interdependent parts. When you have lots of short functions, it's > harder to find them. There are many names to invent for the writer and > many names to rememner for a reader. Function headers are administrative > stuff, it's harder to find real code among abstractions being introduced > and used. In other words, don't use names _at all_ if you can avoid them. Just long, rambling tracts of code filled with anonymous functions. After all, you'd just have to go look at the named function bodes anyway, just to be _sure_ they did what they said they were doing. (I wonder if he disassembles OS calls too, you know, just to be sure). Really I personally think they are often just enamored of their own functional l33tness, but you'll always have a hard time convincing programmers that their unstated preference is to write something so dense that only they and others equally gifted in code decipherment can grasp it. Many programmers take it badly when you tell them that their job should be much more about communicating intent to other human beings than about being extremely clever. As a result of this clever agenda, an unmaintainably large proportion of the code that has ever been written is way too clever for its own good. From vze4rx4y at verizon.net Wed Oct 29 11:43:51 2003 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Wed, 29 Oct 2003 16:43:51 GMT Subject: PEP 322: Reverse Iteration (REVISED, please comment) References: <5d83790c.0310281022.6264aa16@posting.google.com> <3f9ec63f$1@brateggebdc5.br-automation.co.at> Message-ID: > The static method approach would clearly document that the > result is an iterator (which none of the other names proposed > really does IMHO) Better name are welcome! Moving it somewhere else is not open. It is proposed as a builtin for a reason -- it is a core looping tool like zip() or enumerate() and it is meant to simplify rather than complicate code. Static methods, class methods, and weird descriptors be darned, this is not an exercise in how weirdly it can be implemented just to avoid having a builtin. Would everything be somehow better if Alex's wonderful sum() had been implemented as a int.sum() classmethod or was tucked way in another module? Of course not! Likewise, would zip() or enumerate() be successful solutions to lock-step iteration and the loop-counter problems if they were iter.zip() and iter.enumerate()? No, of course not. Let's put an end to this silliness right now. The idea is offered as a builtin or not at all; otherwise, the existing [::-1] starts to look better. > In general, I'm +1 on the PEP Thanks! I certain it will make code more readable and reviewable. The challenge with a PEP this simple is that experts feel this overpowering urge to apply all their know-how and transform in to something other than a clean, fast, simple solution. Raymond Hettinger From eichin at metacarta.com Wed Oct 1 23:02:02 2003 From: eichin at metacarta.com (eichin at metacarta.com) Date: 01 Oct 2003 23:02:02 -0400 Subject: Python os.popen in Linux References: Message-ID: <7g8yo4nxzp.fsf@pikespeak.metacarta.com> perhaps you'd find commands.getoutput useful instead? From mertz at gnosis.cx Sat Oct 18 01:55:50 2003 From: mertz at gnosis.cx (Lulu of the Lotus-Eaters) Date: Sat, 18 Oct 2003 01:55:50 -0400 Subject: Confusing performance results for prime References: Message-ID: bokr at oz.net (Bengt Richter) wrote previously: |In doing some testing of different but simple algorithms for getting a |list of prime numbers This general topic came up quite recently. I myself wrote a bunch about various data structures to cache primes and the like. But that was all fairly idle. If you want to test primality quickly, using the sieve of erotosthenes is pretty terrible. At least if you only want to check relatively few numbers, rather than assemble all the primes. Orders of magnitude better is to use Miller-Rabin pseudoprimality tests (well, complexity orders really). Pick the right algorithm before worrying about micro-optimizations. Yours, Lulu... From jmeile at hotmail.com Wed Oct 15 14:38:56 2003 From: jmeile at hotmail.com (Josef Meile) Date: Wed, 15 Oct 2003 20:38:56 +0200 Subject: Accessing a USB Device? References: <7b454334.0310112020.290273ce@posting.google.com> <6250403b.0310120139.2c68a81@posting.google.com> <3f8d8ef0$1@pfaff2.ethz.ch> Message-ID: <3f8d927a$1@pfaff2.ethz.ch> Sory for the early reply. Now I think I know why it doesn't works. From the readme I saw: "But be aware that the (USB) device file disappears as soon as you unplug the USB adapter." So I guess it doesn't recognize the port if you don't have anything connected to it (Serial ports are listed even if nothing is connected to them). First I have to get the cables, then if it still doesn't work, I will reply again. Thanks, Josef "Josef Meile" wrote in message news:3f8d8ef0$1 at pfaff2.ethz.ch... > > > I have a MP3 and I want to access the songs in them. I was wondering > > > if Python could help me do that. I understand that this can be done > > > using Linux by mountig it as a file system, but I am not on Linux and > > > this is mainly for a Windows platform. Can anyone shed some light? > > I think it's configured just like a serial port. If I'm right try > pyserial. > > I'm also interested, but instead of an MP3 device, I want to connect two > PCs. The problem is that one of the PCs has only a serial port, which must > be > used by another application. However, it has lots of USB ports, so I could > use > either one USB adapter to RS-232 or a USB to USB cable. As suggested in a > message from this newsgroup, I tried COM3, which was supposed to be the usb > port, but it fails, it shows: > > Traceback (most recent call last): > File "", line 1, in ? > File "C:\Python23\Lib\site-packages\serial\serialwin32.py", line 70, in > __init__ > raise serialutil.SerialException, "could not open port: %s" % > msg serial.serialutil.SerialException: could not open port: > (2, 'CreateFile', 'The system cannot find the file specified.') > > Then I tried the scan example from the pyserial site, but it only shows: > (0) COM1 > (1) COM2 > > So I guess it's either not possible or you have to do something else. > > Does anybody have a clue? > > Thanks in advanced, > Josef > > From usenet at jasoegaard.dk Sat Oct 18 19:03:49 2003 From: usenet at jasoegaard.dk (=?ISO-8859-1?Q?Jens_Axel_S=F8gaard?=) Date: Sun, 19 Oct 2003 01:03:49 +0200 Subject: Why don't people like lisp? References: <1A8kb.67406$pv6.3464@twister.nyc.rr.com> <2hfzhqnoeq.fsf@vserver.cs.uit.no> Message-ID: <3f91c709$0$69910$edfadb0f@dread12.news.tele.dk> Frode Vatvedt Fjeld wrote: > Kenny Tilton writes: > > >>what is sophistry? > > > The story goes that in ancient Greece the sophists were recognized > experts on public speaking, who took pride in being able to sway their > audience into any point of view they liked, or got paid for. (Much > like todays "spin doctors", I believe.) This in contrast to the > philosophers, who were the experts on what is True, regardless of > popularity or any pragmatics. > > So sophistry usually means something like a lot of fancy talk that > isn't very helpful in establishing what is true, or important, or > right, or bestest of parens and white-space. And it often involved asking questions, whose answers were already known. -- Jens Axel S?gaard From mnations at airmail.net Fri Oct 3 12:18:38 2003 From: mnations at airmail.net (Marc) Date: 3 Oct 2003 09:18:38 -0700 Subject: New to COM (Excel). Need a little help. Message-ID: <4378fa6f.0310030818.65086abe@posting.google.com> Hi all, I am trying to write an application where I need the ability to open an Excel spreadsheet and do basic read/write, insert rows, and hide/unhide rows. Using win32com I have been able to get the basics down as well as some examples displaying how to simply read and write. But the next step appears exponential. I haven never done anything in VB, so any and all concepts and commands are completely foreign. I have been digging through the VB help and also bought a book specifically for Python and COM. But I don't really have time to learn VB before I can finish my script. Would there happen to be any pre-existing examples of the stuff I need to do out there? Basically I need to do the things I listed above - insert rows and columns and hide/unhide rows. I think with a few examples of sheet manipulation I could figure out the rest. Thanks ahead of time, Marc From pythonguy at Hotpop.com Sun Oct 5 09:13:36 2003 From: pythonguy at Hotpop.com (Anand Pillai) Date: 5 Oct 2003 06:13:36 -0700 Subject: Find out if a host is alive References: <84fc4588.0310040735.6c503d5c@posting.google.com> Message-ID: <84fc4588.0310050513.205095b0@posting.google.com> Thank You Alex. What I want is actually answered by you. I would like to find if the server is answering HTTP requests at port 80. I checked out pyheartbeat, but I think it is useful only for computers in the local area network and not the internet. -Anand Alex Martelli wrote in message news:... > Anand Pillai wrote: > > > I would like to add a feature to one of my network programs. > > The requirement is to find out if a server is alive by sending > > it requests. I know of the standard ICMP ping, and searched > > for python modules able to 'PING'. The only hit I got was Jeremy > > Hiltons ping package, written for Python 1.4, and it does not > > work with the latest Python versions (2.0 upwards). > > http://pynms.sourceforge.net/ does appear to support ICMP, among > many other things, and to support Python 2.2 (I'd be quite amazed > if it worked with 2.2 and not with 2.3). > > > Are there other ways of finding out (in a few lines of code) > > whether a server is alive, apart from the ICMP protocol? > > If you know what services the server is supposed to be running, > sure. If you have no idea whatsoever, no way. It's quite > imaginable, for example, that a server does not serve ICMP > (doesn't WANT to be pinged nor tracerouted etc) but only, > strictly HTTP on port 80/TCP _period_. If you know that, then > 'pinging' the server is useless as a way to determine whether > the server 'is alive'; rather, you would try to bind a socket > to its TCP port 80, and, depending on your definition of "being > alive", might claim that just managing to bind that socket is > enough (or, you might try some short HTTP transaction on the > socket). > > I've noticed an analogy between people wanting their programs > to check if "a server is alive" and ones wanting their programs > to check if "a file exists": the question they pose is rarely > the one they really need to get answered; for example, the > mere existence of a file is often of no real interest if the > program does not have permission to _read_ the file -- and > the mere "aliveness" of a host is often of no real interest > if the program does not have permission to _talk_ to the host > along at least one protocol that's of actual _use_... > > > Alex From mfranklin1 at gatwick.westerngeco.slb.com Thu Oct 2 05:56:13 2003 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Thu, 02 Oct 2003 10:56:13 +0100 Subject: Issues migrating from Solaris to RedHat 9? In-Reply-To: <3F7B3521.C160F2DC@somewhere.cornell.edu> References: <3F7B3521.C160F2DC@somewhere.cornell.edu> Message-ID: <1065088572.1033.8.camel@m-franklin> On Wed, 2003-10-01 at 21:12, Tom Loredo wrote: > Hi folks- > > I'm about to move from a Solaris 8/SPARC environment to a Dell running > RedHat 9. Are there any issues I need to be aware of in bringing my > Python code over (mostly scientific computation)? In particular, I know > earlier versions of RH shipped with an "old" Python installed as "python" > and that installation of more recent versions should not overwrite > "python" (e.g., install as "python2.3"). Is this still the case in RH9? > Any other issues? I will be simultaneously developing for multiple > platforms, so avoiding something like having to have "/bin/env python2.3" > at the top of scripts is highly desirable. > > Also, if I send scripts to other RH users, will there be issues > (in particular with RH8, since that is still widely used)? > Tom, RedHat 9 ships with python 2.2.2 in /usr/bin/python (also /usr/bin/python2 and /usr/bin/python2.2 - they are all the same thing! RedHat 8 has the same setup but it is version 2.2.1 so no problems with that If you are going to install 2.3.* then I would (and have) put it into /usr/local/ as this will not cause any problems with the RedHat applications that use python. If you put it into /usr/bin as python or python2 you will end up having to compile all the extensions that RedHat ships with python (PyGTK, M2Crypto... and a whole lot more) All in all it may be worth sticking to the RedHat python (2.2.2 / 2.2.1) for the short term (till RedHat 10?) especially if you are releasing these programs to other people/platforms.... HTH Martin -- Martin Franklin From niemeyer at conectiva.com Thu Oct 9 09:33:03 2003 From: niemeyer at conectiva.com (Gustavo Niemeyer) Date: Thu, 9 Oct 2003 10:33:03 -0300 Subject: [ANN] python-dateutil 0.1 In-Reply-To: <877k3e4y7j.fsf@blakie.riol#flibuste.net> References: <20031009003838.GA27680@ibook.distro.conectiva> <877k3e4y7j.fsf@blakie.riol#flibuste.net> Message-ID: <20031009133303.GB30421@ibook> > > What is it? > > ----------- > > The dateutil module provides powerful extensions to the standard > > datetime module, available in Python 2.3+. > > Do you plan to propose it to the core python ? It would be great to > don't have again to change API when the same fonction will be > integrated in the core like it was with mx I don't quite understand. Are you're complaining that someone took his time to build an internal datetime type? Or are you complaining that M.-A. Lemburg has written mx.DateTime? :-) The internal datetime is not the same thing as the mx.DateTime module. If you're using mx.DateTime, you can keep using it. Answering your question, yes, I do plan to propose the inclusion in the core. If it will be included or not, I have no idea. -- Gustavo Niemeyer http://niemeyer.net From BjornPettersen at fairisaac.com Mon Oct 20 07:47:00 2003 From: BjornPettersen at fairisaac.com (Pettersen, Bjorn S) Date: Mon, 20 Oct 2003 06:47:00 -0500 Subject: newbie: Windows os.getenv(... Message-ID: <1DAECE9E8F34E04AA0E5699AF7D9FF09085DAA5B@stpmsg00.corp.fairisaac.com> > From: Martin [mailto:info12 at webmail.link-m.de] > > Hi there, > > i?d like to use environment variables within an python script. > I can read with > >>>t1 = os.getenv("temp") > but not > >>>d1 = os.getenv("%date%") date doesn't seem to be an environment variable (check output of the 'set' command in a dos window or hit Windows+break -> Advanced -> environment variables in a recent version of windows). The fact that 'echo %date%' gives a result is "interesting"... > Also I cannot change environment variables with > os.putenv("any" , "something") try os.environ['any'] = 'something' hth, -- bjorn From paulpaterson at users.sourceforge.net Tue Oct 14 20:26:09 2003 From: paulpaterson at users.sourceforge.net (Paul Paterson) Date: Wed, 15 Oct 2003 00:26:09 GMT Subject: ANN: vb2py online code conversion In-Reply-To: References: <1RMib.25623$X66.10435@twister.austin.rr.com> Message-ID: Will Stuyvesant wrote: >>[Paul Paterson] >>The Online Version of vb2py has been released. >>... >>vb2py :: A Visual Basic to Python Conversion Toolkit >>http://vb2py.sourceforge.net > > > Nice work! Thanks! > I am not a VB person, but I always like to see people using python > CGI. But on sourceforge they only have Python 1.5.2 last time I > checked! Did you install your own python on sourceforge (if so, how > did you do that, I failed in an earlier attempt), or do they finally > have a new python version installed? The Shell is now at 2.2 but cgi is still using 1.5.2, which was rather puzzling for a while as things appeared to be working but weren't. I had to install my own copy of Python. I'm not very literate on Unix/Linux so this was a interesting and I'm sure there are better ways to do it. Anyway, here is how I managed to hack it to get it to work ... 1. Make a little work area on your web space to put Python 2. Copy the python 2.2 executable across to the work area 3. Verify that you can run this from the Shell (you'll get warnings about not being able to find lots of libraries but it should run). 4. Copy all the basic Python libraries (../lib) into the same place you put the python executable 5. Copy the "../lib/lib-dynload" contents to your new python directory 6. Change the #! line in your .py files to point to the new python executable Now there has to be a better way than this but ... 7. Add the following lines to your script: import sys sys.path.append("path to your python folder") sys.path.append("path to your lib-dynload") sys.path.append("path to where your other 'site-packages' will live") 8. For me, "socket.py" was failing when importing "_socket" so I modified it not to import "_socket" and it worked fine (I don't think you will be able to use sockets anyway). Anyway, this worked for my application which uses library and non-library packages. Good luck! Paul From brian at sweetapp.com Fri Oct 17 18:20:23 2003 From: brian at sweetapp.com (Brian Quinlan) Date: Fri, 17 Oct 2003 15:20:23 -0700 Subject: xmlrpc server In-Reply-To: <200310172106.h9HL6C026172@gsoa.net> Message-ID: <020e01c394fc$e46ffdc0$21795418@dell1700> > The xmlrpclib has the flag allow_none. There does not seem to be a > similar flag for the the Server. Is this for a particular reason? It was probably an oversight by however submitted the fix. > I am trying > to export some code that sometimes returns None. The only way around > it seems require reimplementing _marshaled_dispatch. You might want to just fix SimpleXMLRPCServer and submit a patch. Cheers, Brian From jfabiani at yolo.com Mon Oct 6 18:00:37 2003 From: jfabiani at yolo.com (John Fabiani) Date: Mon, 06 Oct 2003 22:00:37 GMT Subject: Newbie needs to see a large project Message-ID: <9Clgb.12141$sw6.8259@newssvr25.news.prodigy.com> Hi everyone, I have been checking Python recently and have presented what little I know to mangement. They have asked if there is any large business apps (like an accounting system) using python and what the performance is like. We would be running on Linux with a large database (maybe postgres or mysql) of 3-5 Gbytes. We would be moving from a windows platform(foxpro apps) to Linux (python). About 50 users total. Thanks in advance.... -- John Fabiani From benjamin-hepp at t-online.de Thu Oct 9 11:17:36 2003 From: benjamin-hepp at t-online.de (Benjamin Hepp) Date: Thu, 09 Oct 2003 17:17:36 +0200 Subject: String to ASCII values Message-ID: Hello, How do I convert a string like 'A' to its ASCII value(s) ? Greets, Benjamin From newsgroups at jhrothjr.com Sat Oct 25 14:03:53 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 25 Oct 2003 14:03:53 -0400 Subject: Addition and multiplication puzzle References: Message-ID: "Mark Dickinson" wrote in message news:mailman.90.1067096689.702.python-list at python.org... > Can anyone either reproduce or explain the following > apparently inconsistent behaviours of __add__ and > __mul__? The class Gaussian provides a sub-bare-bones > implementation of Gaussian integers (a Gaussian > integer is a complex number x+yi for which both x and > y are > integers): > > class Gaussian(object): > """class representing Gaussian integers""" > > def __init__(self, x, y = 0): > self.real, self.imag = x, y > > def __repr__(self): > return repr(self.real) + "+" + repr(self.imag) > + "*i" > > def __add__(self, other): > if type(other) != Gaussian: > other = Gaussian(other) > return Gaussian(self.real + other.real, > self.imag + other.imag) > > def __mul__(self, other): > if type(other) != Gaussian: > other = Gaussian(other) > return Gaussian(self.real * other.real - > self.imag * other.imag, \ > self.real * other.imag + > self.imag * other.real) > > Under Python 2.3.2 I get: > > >>> i = Gaussian(0, 1) > >>> i * 3 > 0+3*i > >>> 3 * i # surprise! > 0+3*i > >>> i + 3 > 3+1*i > >>> 3 + i > Traceback (most recent call last): > File "", line 1, in ? > TypeError: unsupported operand type(s) for +: 'int' > and 'Gaussian' > > In other words, I can *multiply* an int by a Gaussian > in either order, but I can only *add* a Gaussian to an > int, not the other way around. The surprise is that > multiplying an int by a Gaussian works---I'd expect it > to complain since there's no __rmul__ method defined, > in just the same way that 3+i produced an exception > above. Why do addition and multiplication behave > differently? > > Yours hoping for enlightenment, > > Mark I vaguely remember a discussion a while back about getting rid of the 'r' operators. I don't remember what ever came of it, though, and I agree that the inconsistent treatment of __mul__ and __add__ is strange. I suspect something may have gotten lost in the boolean implementation. The Python Reference Manual doesn't say anything about it, though. John Roth > > > __________________________________ > Do you Yahoo!? > The New Yahoo! Shopping - with improved product search > http://shopping.yahoo.com > From donn at u.washington.edu Thu Oct 2 16:20:27 2003 From: donn at u.washington.edu (Donn Cave) Date: Thu, 02 Oct 2003 13:20:27 -0700 Subject: Using TCP/IP References: <3F7B100D.5260350C@engcorp.com> <3F7C66EB.3842D0D9@engcorp.com> Message-ID: In article , jblazi wrote: > So I shall do this. When I call ipconfig, I see two ip adresses: > > > Ethernetadapter LAN-Verbindung: > > Verbindungsspezifisches DNS-Suffix: > IP-Adresse (Autokonfig.). . . . . : xxx.xxx.xxx.xxx > Subnetzmaske. . . . . . . . . . . : xxx.xxx.0.0 > Standardgateway . . . . . . . . . : > > PPP-Adapter XXXXXX: > > Verbindungsspezifisches DNS-Suffix: > IP-Adresse. . . . . . . . . . . . : xxx.xxx.xxx.xxx > Subnetzmaske. . . . . . . . . . . : 255.255.255.255 > Standardgateway . . . . . . . . . : xxx.xxx.xxx.xxx > > Python returns the first ip number but I should need the second one. (I > replaced the digits by 'x'. I imagine that more generally you will need the address associated with the network you're using. One fairly simple way to arrive at this is to connect to some well known service on that network, and then get the bound connection's IP with getsockname(). Donn Cave, donn at drizzle.com From kosh at aesaeion.com Mon Oct 6 01:02:43 2003 From: kosh at aesaeion.com (kosh) Date: Sun, 5 Oct 2003 23:02:43 -0600 Subject: Webware vs. PHP - performance comparision!!! In-Reply-To: References: Message-ID: <200310052302.43789.kosh@aesaeion.com> On Sunday 05 October 2003 18:46, JZ wrote: > My hardware and software settings are: > > WindowsXP Pro, Athlon XP2800+, 512DDRdual, > > Python 3.3.2 stable > Webware & WebKit & mod_webkit.dll CVS 2003-09-19 > Cheetah CVS 2003-09-19 > Spyce 3.11 > vs. > PHP 4.3.3 stable > MMCache 2.4.1 > > For page request I used wget. > > My testing code is > ============= > import os, time > url = [ > r'http://localhost/WK/test/test1/testpython.py', > r'http://localhost/WK/test/test1/testcheetah.tmpl', > r'http://localhost/WK/test/test1/testcheetah.py', > r'http://localhost/WK/test/test1/testpsp.psp', > r'http://localhost/testphp.php', > r'http://localhost/testspyce.spy', > ] > for u in url: > t1=time.time() > print '>>>%s' % u, > os.system('wget -m %s -o stress.log' % u) > t = time.time()-t1 > print ' => time: %f s' % t > > testpython.py: > =========== > from WebKit.Page import Page > class testpython(Page): > def writeHTML(self): > cpunter = 100 > i=int(self.request().field('c', 0)) > self.write('

Try: %d

' % i) > if 0 < i <100: > i += 1 > self.write("next" %\ > (self.request().serverURL(), i)) > else: > self.write("next" %\ > self.request().serverURL()) Okay I modified this code to this: cpunter = 100 i=int(context.REQUEST.form.get('c', 0)) print '

Try: %d

' % i if 0 < i <100: i += 1 print "next" % (context.REQUEST.URL, i) else: print "next" % context.REQUEST.URL return printed Which I used in a zope python script and modified your test script to just use only the one url I have. I tested it on an athlon xp 2000 with 1G of ram under linux with zope 2.6.2 running python 2.2.3 and I got time: 0.679494 s That places it at about 5.8x faster then your php mcache version on a slower cpu and with no caching. I have also profiled zope before doing very simple pages like this and it seems to spend about 95% of it time in security checks which make almost no impact on the speed of a real page. I find it very hard to believe that I have slower ram, a slower cpu and am running zope and manage to beat all of your tests by such an extreme margin. Overall considering all the security checks that zope makes just about anything should be faster that is not performing security checks. I suspect your setup is flawed somewhere or that windows xp as got to be the most aweful os to do web stuff on ever to have seen the light of day which I admit is certainly possible and even likely. :) You should look at your test results again and how you ran the test since there is probably a major flaw somewhere. Also the zope solution I have shown is certainly not optimized and I could make it faster. Python is not the slow part in this test. From bnet at ifrance.com Fri Oct 31 05:56:13 2003 From: bnet at ifrance.com (Benoit Dejean) Date: Fri, 31 Oct 2003 11:56:13 +0100 Subject: timeoutsocket.py References: Message-ID: Le Fri, 31 Oct 2003 11:29:52 +0100, Gilles Lenfant a ?crit?: > Hi, > > I'm looking for the "official" timeoutsocket.py by Timothy O'Malley (maybe > he'll read this :) > > I got this in my bookmarks... > > http://www.timo-tasi.org/python/timeoutsocket.py google -> http://vsbabu.org/tools/viewcvs.cgi/pyblagg/timeoutsocket.py From frithiof.jensen at removethis.ted.ericsson.dk Tue Oct 28 05:08:01 2003 From: frithiof.jensen at removethis.ted.ericsson.dk (Frithiof Andreas Jensen) Date: Tue, 28 Oct 2003 11:08:01 +0100 Subject: Iterative numerical optimizaiton routines? References: Message-ID: "Cousin Stanley" wrote in message news:bnjcia$126n0l$1 at ID-130333.news.uni-berlin.de... > The Enthought Python 2.3 distribution contains SciPy .... > http://www.enthought.com/ Yes, indeed it does - but it *also* contains every science/numeric tool on the planet; For my part I just need the SciPy tools not an entirely new universe ;-) From jatwood at cvpjaws03.dhcp.cv.hp.com Tue Oct 21 20:25:01 2003 From: jatwood at cvpjaws03.dhcp.cv.hp.com (John Atwood) Date: Wed, 22 Oct 2003 00:25:01 +0000 (UTC) Subject: Python from Wise Guy's Viewpoint References: <4i78pvgpmiih1bohm1o9u6tumksmuoosc1@4ax.com> <87ekx7fz9d.fsf@thalassa.informatimago.com> Message-ID: Andrew Dalke wrote: >The best examples of resilent architectures I've seen come from >genetic algorithms and other sorts of feedback training; eg, >subsumptive architectures for robotics and evolvable hardware. >There was a great article in CACM on programming an FPGA >via GAs, in 1998/'99 (link, anyone?). It worked quite well (as >I recall) but pointed out the hard part about this approach is >that it's hard to understand, and the result used various defects >on the chip (part of the circuit wasn't used but the chip wouldn't >work without it) which makes the result harder to mass produce. something along these lines? http://www.cogs.susx.ac.uk/users/adrianth/cacm99/node3.html John From keflimarcusx at aol.comNOSPAM Mon Oct 27 00:26:31 2003 From: keflimarcusx at aol.comNOSPAM (KefX) Date: 27 Oct 2003 05:26:31 GMT Subject: newbie question, when __call__ method is used? References: <6143ac23.0310261956.3107061c@posting.google.com> Message-ID: <20031027002631.06171.00000205@mb-m11.aol.com> >I have read other's code, and found it contains the __call__. But I >don't know when its code will be executed. It will be executed when a class instance is executed as a function. For example: foobar = MyClass() foobar(2) This is the same as: foobar = MyClass() foobar.__call__(2) One way of looking at it is that it's simple shorthand, but there's also another advantage (which is the real reason it's there): it turns your class instance into a 'callable', that is, almost anything that requires a function can also take your class instance (in general). - Kef From usenet at soraia.com Mon Oct 27 20:50:15 2003 From: usenet at soraia.com (Joe Francia) Date: Tue, 28 Oct 2003 01:50:15 GMT Subject: GMT is off In-Reply-To: References: Message-ID: Michael Loomington wrote: > GMT time is off by like 10 minutes when I call > strftime("%I:%S", gmtime()) > How do you correct it? My windows time is set correctly. Also can you make > it report time in the EST time zone? > %S == seconds. You probably are looking for %I:%M (or %I:%M:%S). Peace, Joe From stuart at bmsi.com Tue Oct 28 14:28:26 2003 From: stuart at bmsi.com (Stuart D. Gathman) Date: Tue, 28 Oct 2003 14:28:26 -0500 Subject: Getting real argv[0] in python References: Message-ID: On Tue, 28 Oct 2003 13:52:26 -0500, Stuart D. Gathman wrote: > I need to be able to obtain the real argv[0] (not the script name). > The application is writing a CUPS backend in python. For some reason, > CUPS decided to pass the URI as argv[0] (perhaps to ensure that CUPS > will only ever run on Unix, since CUPS stands for Common *Unix* > Printing System). The only solution I can think of is to write a C > wrapper that inserts the original argv[0] before execing python with > the script. > > Is there already a way to do this that I have missed? Here is the simple C wrapper I am using: #include #include #include static const char scriptdir[] = "/usr/lib/cups/python/"; int main(int argc,char **argv) { char *nargv[10]; char script[256]; const char *p; int i; int slen,len; if (argc > 7) { fputs("Usage: pycups uri ...",stderr); return 1; } p = strchr(argv[0],':'); if (p) len = p - argv[0]; else len = strlen(argv[0]); slen = strlen(scriptdir); strcpy(script,scriptdir); if (len + slen + 4 > sizeof script) len = sizeof script - slen - 4; strncat(script,argv[0],len); script[slen + len] = 0; strcat(script,".py"); nargv[0] = "python2"; nargv[1] = script; for (i = 0; i < argc; ++i) nargv[i+2] = argv[i]; nargv[i+2] = 0; execvp("python2",nargv); perror("exec"); return 1; } -- Stuart D. Gathman Business Management Systems Inc. Phone: 703 591-0911 Fax: 703 591-6154 "Confutatis maledictis, flamis acribus addictis" - background song for a Microsoft sponsored "Where do you want to go from here?" commercial. From mailund at birc.dk Wed Oct 22 12:12:22 2003 From: mailund at birc.dk (Thomas Mailund) Date: Wed, 22 Oct 2003 18:12:22 +0200 Subject: Why = = (and not just =) References: <3f92eb51$0$259$cc9e4d1f@news.dial.pipex.com> Message-ID: On Mon, 20 Oct 2003 00:59:30 +0200, Carlo v. Dango wrote: >> expression syntax to boot. The original language in the Algol family, >> Algol 60, used ":=" as the assignment operator as I recall, a tradition >> followed by Pascal. >> >> Frankly, I'd rather have the assignment operator be something >> like a left arrow: "<-" perhaps. I think it makes more sense, >> and it avoids the confusion between one = and two. > > actually Algol was meant to have the <- rather than the := but due to > problems writting the lexer/parser, it became := > > if you want a language which uses the <- operator then have a look at the > language "Beta" it takes a little getting used to, when used nested ;) > Actually, if I recall correctly, BETA uses the "->" operator--assignment goes the other way. In BETA there's syntactical difference between assignment and equality tests (= for testing equality, -> for assigning), but assignment and method calls uses the same syntax. So assigning to variable x, and calling function f, uses the same operator: 5 -> x; 5 -> f; Just nitpicking... /mailund From gh at ghaering.de Thu Oct 9 16:17:25 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Thu, 09 Oct 2003 22:17:25 +0200 Subject: A query about list In-Reply-To: References: Message-ID: <3F85C255.6070407@ghaering.de> Santanu Chatterjee wrote: > Hello everybody, > > I am very new to python. I have a query about > list in python. > > Suppose I have a list > a = [1,[2,3,4],5,6,7,[8,9,10],11,12] > I want to know if there is any simple python > facility available that would expand the above list > to give > a = [1,2,3,4,5,6,7,8,9,10,11,12] > > I know I can do that with a type() and a for/while loop, > but is there any simpler way? Why do you have such a data structure in the first place? Can't it be avoided? If for example you made the mistake of .append()-ing lists to a list, then you can .extend() it instead. -- Gerhard From raffaelcavallaro at junk.mail.me.not.mac.com Tue Oct 14 20:41:28 2003 From: raffaelcavallaro at junk.mail.me.not.mac.com (Raffael Cavallaro) Date: Wed, 15 Oct 2003 00:41:28 GMT Subject: Express What, not How. References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> <92c59a2c.0310031345.57d20631@posting.google.com> Message-ID: In article , Marcin 'Qrczak' Kowalczyk wrote: > Sometimes a function is so simple that its body is more clear than any > name. A name is an extra level of indirection. You must follow it to be > 100% sure what the function means, or to understand what does it really > mean that it does what it's named after. Your argument is based on the assumption that whenever people express _what_ a function does, they do so badly, with an inappropriate name. We should choose our mode of expression based on how things work when used correctly, not based on what might happen when used foolishly. We don't write novels based on how they might be misread by the semi-litterate. Anonymous functions add no clarity except to our understaning of _implementation_, i.e., _how_ not _what_. Higher level abstractions should express _what_. Implementation details should remain separate, both for clarity of exposition, and for maintanence and change of implementation. > The code also gets longer No, it gets shorter, because you don't repeat your use of the same abstraction over and over. You define it once, then reference it by name everywhere you use it. > - not > only more verbose but the structure of the code gets more complex with > more interdependent parts. No, there are _fewer_ interdependent parts, because the parts that correspond to the anonymous function bodies are _completely gone_ from the main exposition of what is happening. These formerly anonymous function bodies are now elswhere, where they will only be consulted when it is necessary to modify them. You seem to take the view that client code can't trust the interfaces it uses, that you have to see how things are implemented to make sure they do what they represent to do. This is a very counterproductive attitude. Code should provide high level abstractions, and clients of this code should be able to tell what it does just by looking at the interface, and maybe a line of documentation. It shouldn't be necessary to understand the internals of code one uses just to use it. And it certainly isn't necessary to include the internals of code one uses where one is using it (i.e., anonymous functions). That's what named functions and macros are for. Inlining should be done by compilers, not programmers. Anonymous functions are a form of unnecessary information overload. If I don't need to see how something works right here, in this particular context, then don't put its implementation here. Just refer to it by name. > When you have lots of short functions, it's > harder to find them. There are many names to invent for the writer and > many names to rememner for a reader. Which is why names should be descriptive. Then, there's little to remember. I don't need to remember what add-offset does, nor look up it's definition, to understand its use in some client code. Anonymous functions are sometimes used as a crutch by those who can't be bothered to take the time to attend to the social and communicative aspects of programming. Ditto for overly long function bodies. How to express intent to human readers is just as important as getting the compiler to do what you want. These same programmers seem enamored of crack-smokingly short and cryptic identifier and function names, as if typing 10 characters instead of 3 is the real bottleneck in modern software development. (Don't these people know how to touch type?) > Function headers are administrative > stuff, it's harder to find real code among abstractions being introduced > and used. Seemingly to you, the only "real code" is low level implementation. In any non-trivial software, however, the "real code" is the interplay of high level abstractions. At each level, we craft a _what_ from some less abstract _how_, and the _what_ we have just defined, is, in turn used as part of the _how_ for an even higher level of abstraction or functionality. > Why do you insist on naming *functions*? You could equally well say that > every list should be named, so you would see its purpose rather than its > contents. I think this concept is called variable bindings ;^) > Perhaps every number should be named, so you can see what it > represents rather than its value. Actually, they are _already_ named. The numerals we use _are_ names, not numbers themselves. I'm surprised you aren't advocating the use of Church Numerals for all numerical calculation. > You could say that each statement of > a compound statement should be moved to a separate function, so you can > see what it does by its name, not how it does it by its contents. It's > all equally absurd. In the Smalltalk community the rule of thumb is that if a method body gets to be more than a few lines, you've failed to break it down into smaller abstractions (i.e., methods). > A program should balance named and unnamed objects. Both are useful, > there is a continuum between cases where one or the other is more clear > and it's subjective in border cases, but there is place for unnamed > functions - they are not that special. Most high level languages have > anonymous functions for a reason. Yes, but they should live inside the bodies of named functions. Not lie exposed in the middle of higher level abstractions. Please also see my reply to Joe Marshall/Prunesquallor a few posts up in this thread. From shelsen at computer.org Thu Oct 23 11:58:24 2003 From: shelsen at computer.org (Simon Helsen) Date: Thu, 23 Oct 2003 11:58:24 -0400 Subject: Python from Wise Guy's Viewpoint In-Reply-To: <87znfsvuqh.dlv@wanadoo.fr> References: <_8Ekb.7543$pT1.318@twister.nyc.rr.com> <3f972315$1@news.unimelb.edu.au> <3638acfd.0310230039.306b14f@posting.google.com> <87ekx4xaym.dlv@wanadoo.fr> <87znfsvuqh.dlv@wanadoo.fr> Message-ID: On Thu, 23 Oct 2003, Remi Vanicat wrote: >> How does ocaml make sure that you don't get a message-not-understood >> exception at runtime then? > >It make the verification when you call the test. I explain : > >you could define : > >let f x = x #foo > >which is a function taking an object x and calling its method >foo, even if there is no class having such a method. > >When sometime latter you do a : > >f bar > >then, and only then the compiler verify that the bar object have a foo >method. you might want to mention that this is possible because of 'extensible record types'. Well, there is a good chance the pyhton/lisp community will not understand this, but it illustrates that a lot of the arguments (probably on both sides in fact) are based on ignorance. One more thing I remembered from a heavy cross-group fight between comp.lang.smalltalk and c.l.f. quite a while ago, is that so-called 'dynamically typed' languages are useful because they allow you to incrementally develop ill-typed programs into better-typed programs (the XP-way), where the ill-typed programs already (partially) work. OTOH, with a static type system, you have to think more in advance to get the types right. XP-people consider this a hindrance and that is what people mean with 'the type system getting the way'. With a Haskell-style or even Ocaml-style type system, you cannot seriously argue that you can write a program which cannot be easily(!) converted into one that fits such type systems. By program, I mean 'a finished production-reade piece of software', not a 'snapshot' in the development cycle. The arguments from the smalltalk people are arguably defendable and this is why this kind of discussion will pop up again and again. Using either static or dynamic (Blume: untyped) type systems is not the point at all. What actually matters is your development style/phylosophy and this is more an issue of software engineering really. Ok, I am phasing out again. Regards, Simon From rodrigob at elo.utfsm.cl Thu Oct 9 19:12:43 2003 From: rodrigob at elo.utfsm.cl (Rodrigo Benenson) Date: 9 Oct 2003 16:12:43 -0700 Subject: Unicode troubles Message-ID: <607d8200.0310091512.58c4f617@posting.google.com> Hi! I'm finishing a multiplatform collaborative realtime text editor (something like SubEthaEdit but multiplatform and opensource) develloped using Python+Twisted as a plugin for Leo. Of course as the software run in different platforms in different places, text encoding compatibility is an issue. So the obvious choice was Tkencoding for client gui, unicode for system internals and utf-8 for web outputs. But I'm getting serious trouble using Tk and Unicode internals. The system, being a text editor use string lenghts and position in the text widget as parameters of most of the function critical algorithms. Unfortunatelly I had discovered recently that some encoding does not provide and equivalence between num_of_chars/length_of_string/position_in_text_widget. As a result each time someone press a non ascii key, the references are lose and the other clients receive a soup of letters. I had read on internet that Unicode was supposed to keep the relation num_of_char/string_lenght (and thus the relation string_length/num_of_char/position_in_text_widget). But this relation does not occurs on all my machines. Sometimes I get len(u"el?") = 3 (the good result) and other times len(u"el?") = 4 (wrong result). These seems indiferent of the OS. Could someone explain me this issue ? How I'm supposed to manage this problem ? Do I have to compile python with special params to get unicode chars and one length unit ? Thanks. Rodrigo Benenson. From j-anthony at rcn.com Mon Oct 13 12:48:18 2003 From: j-anthony at rcn.com (Jon S. Anthony) Date: 13 Oct 2003 12:48:18 -0400 Subject: Python syntax in Lisp and Scheme References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> <92c59a2c.0310031345.57d20631@posting.google.com> Message-ID: Alex Martelli writes: > At the moment the only thing I am willing to denounce as idiotic are > > your clueless rants. > > Excellent! I interpret the old saying "you can judge a man by the quality > of his enemies" differently than most do: I'm _overjoyed_ that my enemies > are the scum of the earth, and you, sir [to use the word loosely], look as > if you're fully qualified to join that self-selected company. Whatever. /Jon From tedNOSPAM94107 at yahoo.com Fri Oct 10 03:46:23 2003 From: tedNOSPAM94107 at yahoo.com (ted) Date: Fri, 10 Oct 2003 00:46:23 -0700 Subject: How to remove empty lines with re? Message-ID: I'm having trouble using the re module to remove empty lines in a file. Here's what I thought would work, but it doesn't: import re f = open("old_site/index.html") for line in f: line = re.sub(r'^\s+$|\n', '', line) print line Also, when I try to remove some HTML tags, I get even more empty lines: import re f = open("old_site/index.html") for line in f: line = re.sub('<.*?>', '', line) line = re.sub(r'^\s+$|\n', '', line) print line I don't know what I'm doing. Any help appreciated. TIA, Ted From rainerd at eldwood.com Fri Oct 24 12:13:40 2003 From: rainerd at eldwood.com (Rainer Deyke) Date: Fri, 24 Oct 2003 16:13:40 GMT Subject: Why don't people like lisp? References: <3f9302d7.170372828@news.eircom.net> <3f96b046$0$556$b45e6eb0@senator-bedfellow.mit.edu> <20031022234546.GS1454@mapcar.org> <3f97eb1f$0$573$b45e6eb0@senator-bedfellow.mit.edu> <5627c6fa.0310230919.d2eb49a@posting.google.com> <3f9823b7$0$565$b45e6eb0@senator-bedfellow.mit.edu> <864qxz2if5.fsf@raw.grenland.fast.no> Message-ID: Raymond Wiker wrote: > "Rainer Deyke" writes: >> Personally I'd prefer guaranteed immediate destructors over >> with-open-file. More flexibility, less syntax, and it matches what >> the CPython implementation already does. > > Right... all along until CPython introduces a more elaborate > gc scheme. > > Note that reference-counting has problems with cyclic > references; probably not something that will bite you in the case of > open files, but definitely a problem you need to be aware of. I'm all for more elaborate gc schemes. In particular, I want one that gives me guaranteed immediate destructors even in the presence of reference cycles. And I want to language specification to guarantee it. Having to explicitly close files is something I'd expect in C or assembly, but it has no place in high-level languages. And "with-open-file" is too limiting. Let the computer do the work, not the programmer. -- Rainer Deyke - rainerd at eldwood.com - http://eldwood.com From brian at sweetapp.com Sat Oct 18 22:23:56 2003 From: brian at sweetapp.com (Brian Quinlan) Date: Sat, 18 Oct 2003 19:23:56 -0700 Subject: xmlrpclib In-Reply-To: Message-ID: <010001c395e8$0c8e75c0$21795418@dell1700> > I'm having trouble using xmlrpclib. I register a function (or class) > with the SimpleXMLRPCServer and initiate the server. I then create a > ServerProxy object and connect to the xml-rpc server. When I call a > registerd function or class member function I get the follwoing error. > I've attached the server and client source files. > > > File "D:\Python23\lib\xmlrpclib.py", line 742, in close > raise Fault(**self._stack[0]) > xmlrpclib.Fault: unless allo > w_none is enabled'> Both of your registered functions implicitly return None. None is not a valid XML-RPC type (though there is an extension with a NULL type). You can fix your code by adding "return 1" to the end of your functions. Cheers, Brian From aleax at aleax.it Tue Oct 28 08:06:11 2003 From: aleax at aleax.it (Alex Martelli) Date: Tue, 28 Oct 2003 13:06:11 GMT Subject: PEP 289: Generator Expressions (please comment) References: <5d83790c.0310231158.65595858@posting.google.com> <2I9nb.360782$R32.11877162@news2.tin.it> Message-ID: <7Rtnb.366605$R32.12088099@news2.tin.it> Daniel Dittmar wrote: > Alex Martelli wrote: >>> counter proposal: >>> g[(p.score, p.name) for p in players ] >> >> Looks like it's indexing g. >> >>> This works similar to r'\' for raw strings and u'x' for unicode >>> strings. >> >> Nope, it's ambiguous, while adjacent to '...' isn't. > > Although I admit my proposal is flawed, the principle behind is is sound, > namely that syntax constructs should be recognisable at the start. Avoiding lookahead is a good principle, but not an absolute. For example, when I see a literal that starts with the characters: 1233445 I do NOT start grumbling that, since it violates the Dittmar Principle, I'm desperate by not yet knowing after reading the first few characters whether it's going to be an integer literal, such as 123344567 or a float literal, such as 1233445.67 Your "should" is just too weak to make this notation other than perfectly fine. A language designed strictly by your principle, thus forcing initial stropping of digit sequences to distinguish e.g. integer literals from float ones, would be a syntax disaster. >>> p[$*-=%/sd/!] allows to embed perl code >> >> If you want perl, you know where to find it. > > See how difficult it is even for you to recognize something if it isn't > introduced by the proper markers, in this case ? "Introduced" matters not a whit (just like the fact that, in English, "sarcasm" is spelled with a c and not with a k). If you had chosen to indicate your dubious sarcasm (against your own proposal?!) by a trailing parenthetical such as "(just kidding)" I would not have wasted the time to respond. Don't take the _complete_ lack of any clarifying denotation (which is definitely a stupid choice) obscuring the message, as any proof that the clarifying denotation must be BEFORE rather than AFTER -- it just doesn't follow. As your proposal DOES look distinctly perlish (cfr q/foo/ vs qq/foo/ etc), it's quite reasonable to form the working hypothesis that you LIKE perl syntax, rather than being engaged in sarcasm against your own proposals (which is a form of split personality one rarely comes upon). Alex From bvdpoel at kootenay.com Sun Oct 12 20:50:54 2003 From: bvdpoel at kootenay.com (Bob van der Poel) Date: Sun, 12 Oct 2003 17:50:54 -0700 Subject: unintuitive dict timings In-Reply-To: References: Message-ID: <3f89f812_1@dns.sd54.bc.ca> Tim Peters wrote: > [Bob van der Poel] > >>There was a thread a few days ago about populating a dict/list. I've >>got a bit of bottleneck in my program so grabbed the ideas and did a >>timing test.... >> >>---------- >> >>import time >>import random >> >># Test of various methods to add an item to a list in a dict. >> >>def ifelse(key, val): >> if d.has_key(key): > > > That's faster as "if key in d". d.has_key needs an extra step to look up the > method named "has_key" in the d object. Yes, I tried the "if key in d" and discarded that. Guess it should have stayed in the test data. > Ouch. You're timing lots of things besides what you're trying to time here. Yes, you are 100%. Guess it doesn't pay to rush timing tests. Really, I was doing a quick and dirty test ... and I shouldn't have. As we all (should) know. > def getorset(key, val): > d.setdefault(key, []).append(val) Okay, this is faster than get1() and get2(). Just in case anyone is interested :) Function: Keycount 1000 Time 1.05 Function: Keycount 1000 Time 1.44 Function: Keycount 1000 Time 1.31 Function: Keycount 1000 Time 1.68 So, that still leaves the most readable as the quickest... -- Bob van der Poel ** Wynndel, British Columbia, CANADA ** EMAIL: bvdpoel at kootenay.com WWW: http://www.kootenay.com/~bvdpoel From bignose-hates-spam at and-benfinney-does-too.id.au Mon Oct 20 02:13:09 2003 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 20 Oct 2003 16:03:09 +0950 Subject: DeprecationWarning: Cookie/SmartCookie class is insecure Message-ID: Howdy all, I'm using a library that uses SmartCookie. In Python 2.3, that gives this warning: /usr/lib/python2.3/Cookie.py:712: DeprecationWarning: Cookie/SmartCookie class is insecure; do not use it What should the library be using instead of SmartCookie? -- \ "If it ain't bust don't fix it is a very sound principle and | `\ remains so despite the fact that I have slavishly ignored it | _o__) all my life." -- Douglas Adams | Ben Finney From adalke at mindspring.com Sat Oct 11 13:27:02 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Sat, 11 Oct 2003 17:27:02 GMT Subject: Python syntax in Lisp and Scheme References: <8CVgb.8$KR3.1846@typhoon.nyu.edu> <87brspzsg3.fsf@thalassa.informatimago.com> <7k3c4r0i.fsf@comcast.net> Message-ID: Alex Martelli: > What do I want of the OS running my firewall? Security, security, security. > It's nice if it can run on very scant resources, offers solid and usable > packet filtering, and has good, secure device drivers available for the > kind of devices I may want in a computer dedicated to firewalling -- all > sorts of ethernet cards, wifi thingies, pppoe and plain old ppp on ISDN for > emergency fallback if cable service goes down, UPS boxes, a serial console > of course, perhaps various storage devices, and that's about it. > > I see no reason why I should use anything but OpenBSD for that. I'm running a Linksys box as my primary firewall. I like the feeling of security that the OS is in firmware and can't be updated (I hope) except through the USB connector. I like that the box is portable (I've taken it to a couple of conferences), low power (I leave it on all the time), and quiet. I do have a network -> dialup box as well when I needed to do dialup to one of my clients, but I've not needed that feature as a backup to my DSL in over a year. > (DHCP, DNS, ntp, Squid for proxying, ...). It does DHCP but not the rest. Would be nice, but I would prefer those features to be on this side of my firewall. Yes, I know about OpenBSD's "only one remote hold in the default install, in more than 7 years" claim to fame. Andrew dalke at dalkescientific.com But is it a sense of security or real security? Hmm.... :) From alan_salmoni at yahoo.com Thu Oct 9 21:28:43 2003 From: alan_salmoni at yahoo.com (Alan James Salmoni) Date: 9 Oct 2003 18:28:43 -0700 Subject: newbie needs help with GUI References: <3F7F1F51.D7976752@easystreet.com> <1065296088.11913.16.camel@devilbox.homelinux.net> Message-ID: Scott Chapman wrote in message news:... > On Saturday 04 October 2003 12:34, Cliff Wells wrote: > > On Sat, 2003-10-04 at 12:28, achrist at easystreet.com wrote: > > > The messages might go to a secret place, IDK. > > > I can imagine that when this computer reaches its final reward, > > > the recycler will smash some component deep in the guts of this > > > machine and all of that previously unseen print output will splill > > > out all over the floor. > > > > That's just silly. Everyone knows computers recycle unused characters > > for later use. Unix often stores them in /dev/null which is why so many > > scripts send unwanted characters there. Windows, of course, leaks > > characters, which is why all MS applications ship with something called > > a "font pack" which is really just extra characters so it doesn't run > > out. > > This has been a major problem at Microsoft that their engineers have been > wringing their hands over for a long time. When the computer temporarily > runs out of characters through this leakage, it makes a blue screen and gives > you a cryptic error message that doesn't mention character loss at all, while > it digs around through the font packs trying to find some unused ones. Ahhh! So that's what all that "gunk" on the blue screen of death was - it was all the forgotten characters trying to get back out into the world!!! They must be real lonely, poor things... I heard a while ago that some of them form together into loose bands and squirt themselves through the nearest network, multiplying rapidly. Maybe that is where spam comes from??? Alan James Salmoni SalStat Statist... etc From jaws at ericsson.ca Tue Oct 14 15:43:24 2003 From: jaws at ericsson.ca (JAWS) Date: Tue, 14 Oct 2003 15:43:24 -0400 Subject: Unittest and dynamically created methods Message-ID: <3F8C51DC.73CF03A7@ericsson.ca> I get this error message when trying to run a unittest test with a dynamically created test method: Traceback (most recent call last): File "unittest.py", line 215, in __call__ testMethod() TypeError: ?() takes no arguments (1 given) I have no clue as to where the 1 given argument comes from... I am using python 2.2 and here is a copy of the code generating this: #! /bin/env python import unittest, commands, new class Test(unittest.TestCase): done = None def initialization(self): Test.port = 11000 Test.host = 'meadow' def setUp(self): if not Test.done: Test.done = 1 Test.initialization(self) def tearDown(self): pass def testCommandFailure(self): status, output = commands.getstatusoutput('python ../bin/uimClient.py' + ' -p ' + str(Test.port) + ' -h ' + Test.host) self.assertEqual(256, status) def testCommandFailure3(self): status, output = commands.getstatusoutput('python ../bin/uimClient.py' + ' -p ' + str(Test.port) + ' -h ' + Test.host) self.assertEqual(256, status) #====================================BASE TEST================================== if __name__ == '__main__': base = 'def testCommandFailure2(self):\n\t""" Testing test1 method """' +\ '\n\tstatus, output = commands.getstatusoutput("python " +' + \ '" ../bin/uimClient.py -p " + str(Test.port) + " -h " + Test.host)'+\ '\n\tself.assertEqual(status, 256)\n' code = compile(base, 'uimClientFT.py', 'exec') testf = new.function(code, Test.__dict__, 'testCommandFailure2') setattr(Test, 'testCommandFailure2', testf) print Test.__dict__ print type(Test.testCommandFailure2) unittest.main() J-P thankx -------------- next part -------------- An HTML attachment was scrubbed... URL: From CousinStanley at hotmail.com Wed Oct 22 11:59:02 2003 From: CousinStanley at hotmail.com (Cousin Stanley) Date: Wed, 22 Oct 2003 08:59:02 -0700 Subject: Trailing comma (was: Re: structure in Python) References: <3F95585C.3EDF3364@engcorp.com> Message-ID: Peter .... Thanks for the reply .... I usually format long lists as one item per line as well .... I only stuck Alex' example on a single line since it was short and I was using the interpreter .... The style that looks the most natural and seems the easiest to extend and edit to me is .... x = [ 'fe' , 'fi' , 'fo' , 'fum' ] -- Cousin Stanley Human Being Phoenix, Arizona From james.anderson at setf.de Mon Oct 20 10:56:40 2003 From: james.anderson at setf.de (james anderson) Date: Mon, 20 Oct 2003 16:56:40 +0200 Subject: Python from Wise Guy's Viewpoint References: Message-ID: <3F93F6DF.252011AC@setf.de> that was a bizarre post. the author begins by describing problematic experiences with a dialect of lisp which, by his own qualification was "poor (by today's standards)," then he continues with a characterization of the behaviour of method qualification, which characterization he then deprecates in the next sentence. then, after having indicated that he may well not have acquaited himself with the language documentation, he proceeds to express skepticism about how much one can infer from immediate method definitions. it is evident that he does have direct experience with these issues in broader terms, which makes it a shame that he perfers to conjecture about the performance of the lower 50% rather than to state the issues concretely. ... Joachim Durchholz wrote: > > ... > > Actually, my experiences with Lisp come from several pre-Scheme > encounters. They include a rather poor (by today's standards) dialect > called Interlisp, which worked OK but was a little restricted, and a > Lisp machine that offered no protection whatsoever for the system > internals and, consequently, crashed in ways that make even Windows ME > look like the incarnation of stability. > When I looked at Scheme and CLOS, I found lots of new added mechanism, > but no attempts at fixing the old problems. (Which, probably, wasn't > even on the agenda. Maybe it's just me who sees problems.) > > > Multimethods and before/after/around-methods are among the things > > that make me really happy as a lisp programmer, and with them I've > > done things to systems - with a few lines of code - that would have > > required a complete rewrite with more limited languages. > > before/after/around don't offer anything that a simple call to an > ancestor method wouldn't offer, and with less linguistic requirements. > It looks as if somebody reimplemented Simula features without thinking > about available improvements. > Unless, of course, Lisp before/after/around semantics is different than > a simple super/precursor/whatever call; in which case a more visible > warning in the descriptions of before/after/around semantics would have > been in order... > > Multimethods, on the other hand, are indeed powerful, but they are also > dangerous. Just like GOTO - you can use it to make code better, but > often enough it's making it worse. Multimethods are just a case where > problems disguise themselves as coding errors - looking at the > sophisticated user-definable machinery for selecting the right method > during multimethod dispatch, it seems like these problems indeed showed > up, and were "solved" by adding further baroqueness to the language. To > the point that reading the source code of a function will not reveal > what's actually happening, because some quirk in multimethod resolution > strategy may select entirely different subfunctions than those that the > reader would have expected. > From a software maintenance perspective, this is pure disaster. > > >>unsafe-but-powerful stuff. In my eyes, Lisp is a valuable > >>experimentation lab for new language mechanisms, but not fit for > >>production use. > > > > Hmm. I wonder why my CLOS-infested server software keep running for > > MONTHS? > > Maybe because you're one of those above-average bright guys? > > And, maybe, because you're not working in a team of a dozen or more > people, so you know exactly what combinations of types are safe to use > with a multimethod, and which aren't? And if a problem indeed shows up, > you don't attribute this to multimethods per se, but to some stupid > coding error, and you simply fix the problem? (C programmers don't see C > as a dangerous language, they just consider race conditions and buffer > overruns as stupid programming mistakes as well... deficits of a > language are easier to see if you take an outside perspective.) > > >>In other words: Lisp is too powerful and dangerous, C++ is too tricky, C > >>is too low-level, Java is too slow (even when compiled) and slightly too > >>restricted, [add your favourite language and its deficits here] - choose > >>your evil... > > > > But of all evils, Common Lisp is the least, since it gives you the > > most reliable code (yes it DOES!), gives good programmmers the > > opportunity to write wonderfully readable code, is wonderfully > > expressive and is Great Fun to work with. > > In practice, most programmers aren't great, they are average. Assuming a > halfways sane distribution, 50% of all programmers are even /below/ > average - and their services are still very much in need. > How should they get their work done? > Educating them isn't an option - if that were a possibility, it would > have long been done. > > Regards, > Jo From aleaxit at yahoo.com Sun Oct 12 14:34:39 2003 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 12 Oct 2003 18:34:39 GMT Subject: Python syntax in Lisp and Scheme References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> <92c59a2c.0310031345.57d20631@posting.google.com> <6WKdnf4hoZxoRRWiXTWJig@comcast.com> Message-ID: <39hib.205605$hE5.6914649@news1.tin.it> Pascal Costanza wrote: ... >>>Does Python allow local function definitions? ... >>>Can they shadow predefined functions? ... >> Yes, named objects, including functions can (locally) shadow >> (override) builtins. It is considered a bad habit/practice unless >> done intentionally with a functional reason. > > Well, this proves that Python has a language feature that is as > dangerous as many people seem to think macros are. Indeed, a chorus of "don't do that" is the typical comment each and every time a newbie falls into that particular mis-use. Currently, the --shadow option of PyChecker only warns about shadowing of _variables_, not shadowing of _functions_, but there's really no reason why it shouldn't warn about both. Logilab's pylint does diagnose "redefining built-in" with a warning (I think they mean _shadowing_, not actually _redefining_, but this may be an issue of preferred usage of terms). "Nailing down" built-ins (at first with a built-in warning for overriding them, later in stronger ways -- slowly and gradually, like always, to maintain backwards compatibility and allow slow, gradual migration of the large existing codebase) is under active consideration for the next version of Python, expected (roughly -- no firm plans yet) in early 2005. So, yes, Python is not perfect today (or else, we wouldn't be planning a 2.4 release...:-). While it never went out of its way to give the user "as much rope as needed to shoot oneself in the foot", neither did it ever spend enormous energy in trying to help the user avoid many possible errors and dubious usage. Such tools as PyChecker and pylint are a start, and some of their functionality should eventually be folded back into the core, just as tabnanny's was in the past with the -t switch. I don't think the fundamental Python will ever nag you for missing comments or docstrings, too-short names, etc, the way pylint does by default (at least, I sure hope not...!-), but there's quite a bit I _would_ like to have it do in terms of warnings and, eventually, error messages for "feechurs" that only exist because it was once simple to allow than to forbid them, not by a deliberate design decision to have them there. Note that SOME built-ins exist SPECIFICALLY for the purpose of letting you override them. Consider, for example, __import__ -- this built-in function just exposes the inner mechanics of the import statement (and friends) to let you get modules from some other place (e.g., when your program must run off a relational database rather than off a filesystem). In other word, it's a rudimentary hook in a "Template Method" design pattern (it's also occasionally handy to let you import a module whose name is in a string, without going to the bother of an 'exec', so it will surely stay for that purpose even though we now have a shiny brand-new architecture for import hooks -- but that's another story). Having a single hook of global effect has all the usual downsides, of course (which is exactly why we DO have that new architecture;-): two or more complicated packages doing import-hooks can't necessarily coexist within the same Python application program (the only saving grace which let us live with that simplistic hook for so many years is that importing from strange places is typically a need of a certain deployment of an overall application, not of a package -- still, such packages DO exist, so the previous solution was far from perfect). Anyway, back to your contention: I do not think that the fact that the user can, within his functions, choose very debatable names, such as those which shadow built-ins, is anywhere as powerful, and therefore as dangerous, as macros. My own functions using 'sum' will get the built-in one even if yours do weird things with that same name as a local variable of their own. The downsides of shadowing are essentially as follows... a newbie posts some fragment of his code asking for guidance, and among other things that fragment has for i in range(length(thenumbers)): total = total + thenumbers[i] he will receive many suggestions on how to make it better, including the ideal one: total = sum(thenumbers, total) But then he tries it out and reports "it breaks" (newbies rarely are clueful enough to just copy and paste error messages). And we all waste lots of time finding out that this is because... the hapless newbie had named HIS OWN FUNCTION 'sum', so this was causing runaway recursion. Having met similar issues over and over, one starts to warn newbies against shadowing and get sympathetic with the idea of forbidding it:-). That doesn't really compare to an extra feature in the language that is deliberately designed to let reasonably-clueful users do their thing, isn't deprecated nor warned against by anybody at all (with a few isolated voices speaking about "abuse" of macros in this thread, but still with an appreciation for macros when _well_ used), and is MEANT to do what newbies _accidentally_ do with shadowing & much more besides;-). Alex From ianb at colorstudy.com Fri Oct 24 01:00:59 2003 From: ianb at colorstudy.com (Ian Bicking) Date: Fri, 24 Oct 2003 00:00:59 -0500 Subject: MOPs (warning: LONG) In-Reply-To: Message-ID: <0ECECB65-05DF-11D8-A49B-000393C2D67E@colorstudy.com> On Thursday, October 23, 2003, at 08:30 PM, Joachim Durchholz wrote: > What is dynamic metaprogramming good for? [...] > - Dynamic fields > Frankly, I don't understand why on earth one would want to have > objects with a variant set of fields. I could do the same easily by > adding a dictionary to the objects, and be done with it (and get the > additional benefit that the dictionary entries will never collide with > a field name). > Conflating the name spaces of field names and dictionary keys might > offer some syntactic advantages (callers don't need to differentiate > between static and dynamic fields), but I fail to imagine any good use > for this all... (which may, of course, be lack of imagination on my > side, so I'd be happy to see anybody explain a scenario that needs > exactly this - and then I'll try to see how this can be done without > MOP *g*). I happily do just this in SQLObject. Subclasses define columns, but columns are fairly complicated and can entail secondary methods, in addition to the getter/setter methods. More complex might be a class built from a XML schema, which again has a clearly defined set of attributes, but those attributes vary. Both instances could be done with dictionary access, but frankly that's just dumb -- they aren't dictionaries. Maybe it's okay for a generalized XML object, but if you are building off a schema it's more appropriate to use the restricted namespace that classes attributes generally imply. Both cases could be done with __getattr__, but that's kind of wasteful as well -- why are you trapping every attribute that isn't found, when you know at the time of class creation time exactly what attributes you want? In both cases, however, you can "build" the class -- i.e., create the class, then add class variables to do whatever you need to do. This doesn't look as nice, but it's really the same sort of thing. Many kinds of metaclasses wouldn't be necessary is there was something like a __cls_init__ method, called on class instantiation. Hmmm... in another case I use a __call__ in a metaclass so that calling a class subclasses it instead of instantiating it. Good fun, but a little obscure in purpose. -- Ian Bicking | ianb at colorstudy.com | http://blog.ianbicking.org From hankc at nospam.com Mon Oct 6 11:50:47 2003 From: hankc at nospam.com (HankC) Date: Mon, 06 Oct 2003 15:50:47 GMT Subject: Python/Wx dot net References: <3f7fafa6.52380188@news.la.sbcglobal.net> <3F801EF6.5D27230D@engcorp.com> <3f80ab5f.30293589@news.la.sbcglobal.net> Message-ID: <3f818cd7.6422224@news.la.sbcglobal.net> On Mon, 6 Oct 2003 00:45:17 -0700, "Carl Waldbieser" wrote: >To me, it seems like it would be a very extreme position for Microsoft to >disallow native code on their future operating systems. I find myself >asking, "what would be the point?" If someone wanted to write a program >that they couldn't write using managed code, they couldn't use Windows. Why >would you want to shut out a potential customer? Also, not all the tools >Microsoft is putting out focus entirely on managed code. The Visual C++ >tools seem (at least to me) to have been designed with an emphasis on >integrating native and managed code for mixed projects. > Carl, thanks for your comments - they're actually a little reassuring. Not really to argue, but just to comment on the points above: extreme position - yes indeed, but I can see it happening if it would increase the control/power of MS. the point? - Well, two quick ones: 1) controlling a framework that is written to by a huge number of developers gives them a huge amount of power; 2) if Windows runs managed code only the security of the platform would increase substantially. they couldn't use Windows - I think as .net matures there will be very few apps that won't be capable of running as managed code. Drivers and other low level stuff may be excepted with an MS certification or something. integration - Yeah, but it's still early, you would have to expect integration at this point. I also understand that there will be no thunking layer to run 32 bit native code from 64 bit managed code so writing to Win64 will require either a 64bit compiler or managed code exclusively. I know some of those points are a little far fetched - I'm just feeling a little bleak about the future lately :-) From costanza at web.de Tue Oct 28 18:37:14 2003 From: costanza at web.de (Pascal Costanza) Date: Wed, 29 Oct 2003 00:37:14 +0100 Subject: Python from Wise Guy's Viewpoint In-Reply-To: References: <3F9D5D21.2060408@ps.uni-sb.de> <20031027184024.GO1454@mapcar.org> <20031028093713.GQ1454@mapcar.org> Message-ID: Matthias Blume wrote: >>we both don't have the necessary empirical data to back our claims) > > > Speak for yourself. You too. This: > I have worked on projects where people worried about *every cycle*. ^^^^^^^^ > (Most of the time I agree with you, though. Still, using infinite > precision by default is, IMO, a mistake. Having it around and at your ^^^^^^ > fingertips, though, is nice. That's why I added the long-missing > compiler support for IntInf to SML/NJ recently.) is by any scientifical standard not enough evidence to back this: > The problem > is that for many algorithms people want to be sure that the compiler > represents their values in machine words. Infinite precision is > needed sometimes, but in the majority of cases it is overkill. If you > need infinite precision, specify the type (IntInf.int in SML's case). > A clever compiler might optimize that like a Lisp compiler does. In > most other cases, why take any chances? Pascal From ngps at netmemetic.com Wed Oct 8 01:47:18 2003 From: ngps at netmemetic.com (Ng Pheng Siong) Date: 8 Oct 2003 05:47:18 GMT Subject: Python syntax in Lisp and Scheme References: <8765j0akfk.fsf@thalassa.informatimago.com> <87y8vw7imp.fsf@thalassa.informatimago.com> Message-ID: According to Pascal Bourguignon : > Well, I would say that kanji is badly designed, compared to latin > alphabet. The voyels are composed with consones (with diacritical > marks) and consones are written following four or five groups with > additional diacritical marks to distinguish within the groups. It's > more a phonetic code than a true alphabet. Kanji are ideograms borrowed from Chinese. Kanji literally means "Han character". I think the diacritical marks you mention are pronunciation guides, much like Hanyu Pinyin is a Mandarin pronunciation guide for Chinese. In Hanyu Pinyin, Kanji (read as a Chinese word phrase) is rendered "han4 zi4". In Korean, Kanji is pronounced Hanja. Same two-character word phrase, different pronunciations. -- Ng Pheng Siong http://firewall.rulemaker.net -+- Manage Your Firewall Rulebase Changes http://sandbox.rulemaker.net/ngps -+- Open Source Python Crypto & SSL From skip at pobox.com Tue Oct 28 11:10:43 2003 From: skip at pobox.com (Skip Montanaro) Date: Tue, 28 Oct 2003 10:10:43 -0600 Subject: CSV Dialect Example Requested - NEWBIE In-Reply-To: References: Message-ID: <16286.38147.467609.401342@montanaro.dyndns.org> Doug> import csv Doug> import csv Doug> class dialect(csv.dialect): Doug> delimiter = '|' Doug> skipinitialspace = True Doug> quotechar = '"' Doug> doublequote = True Doug> reader = csv.reader(file("c:\\Temp\\test.csv"), dialect=dialect) Doug> for row in reader: Doug> print row Doug, As others pointed out you want to subclass csv.Dialect. It's probably easier to subclass csv.excel instead though. csv.Dialect is a base class which doesn't define any of the required attributes. If you subclass csv.Dialect using just the attributes you indicated, you will get: >>> class dialect(csv.Dialect): ... delimiter = '|' ... skipinitialspace = True ... quotechar = '"' ... doublequote = True ... >>> reader = csv.reader(file("support-list.csv"), dialect=dialect) Traceback (most recent call last): File "", line 1, in ? File "/Users/skip/local/lib/python2.4/csv.py", line 39, in __init__ raise Error, "Dialect did not validate: %s" % ", ".join(errors) _csv.Error: Dialect did not validate: lineterminator not set, quoting parameter not set because csv.Dialect doesn't define a lineterminator attribute. By subclassing csv.excel you start out with a valid dialect and only need to override the attributes which differ. Here's a working example: >>> class dialect(csv.excel): ... delimiter = '|' ... skipinitialspace = True ... quotechar = '"' ... doublequote = True ... >>> reader = csv.reader(file("support-list.csv"), dialect=dialect) >>> for row in reader: ... print row ... ['"', '1', '2', '3', '4'] ['"Happy Days"', 'a', 'b', 'c', '4'] which uses """"|1|2|3|"4" """Happy Days"""|a|b|c|"4" as the input file. Here's an example of registering a dialect with the module: >>> csv.register_dialect("", dialect) >>> reader = csv.reader(file("support-list.csv"), dialect="") >>> for row in reader: ... print row ... ['"', '1', '2', '3', '4'] ['"Happy Days"', 'a', 'b', 'c', '4'] Skip From gscott2112 at hotmail.com Thu Oct 2 23:16:20 2003 From: gscott2112 at hotmail.com (Gordon Scott) Date: Fri, 03 Oct 2003 03:16:20 GMT Subject: Need help with struct module References: Message-ID: <8S5fb.7718$YO5.4197151@news3.news.adelphia.net> hmmm, I'll try that. I'm not exactlly transferring the file over a socket. Just writing a binary file and manually copying it up to the device. Did the same thing in Java, dumped a binary file on my desktop and copied it over to the device without any problem. "Richard Brodie" wrote in message news:blhc7f$l18 at newton.cc.rl.ac.uk... > > "Gordon Scott" wrote in message > news:D1Web.6875$YO5.4091894 at news3.news.adelphia.net... > > > why in this example are the packing of 9 and 10 not showing '\x00\x09' and > > '\x00\x0a' respectively? > > It's the canonical representation of that string, after round tripping the > escaping/unescaping. No different to: > >>> ('\x41') > 'A' > > > On the target device when I read the file into a memory buffer and examine > > the contents, the value of 10 ('\x00\n') that I am expecting is litterally 00 0D > > and NOT 00 0A. > > I guess at some point you've read/written/transferred the file without the binary flag. > Try dumping the file on each platform to see where it got converted. Then go back > and add a few '\x62's. > > From aleax at aleax.it Fri Oct 3 12:44:57 2003 From: aleax at aleax.it (Alex Martelli) Date: Fri, 03 Oct 2003 16:44:57 GMT Subject: Thread Safety References: <92c59a2c.0310021020.663d4cf2@posting.google.com> Message-ID: "Martin v. L?wis" wrote: ... > But then, in Java, strings are not immutable, no? Nope: strings ARE immutable in Java . Alex From CousinStanley at hotmail.com Mon Oct 27 10:17:18 2003 From: CousinStanley at hotmail.com (Cousin Stanley) Date: Mon, 27 Oct 2003 08:17:18 -0700 Subject: Iterative numerical optimizaiton routines? References: Message-ID: | SciPy contains many numeric optimisation algorithms | - not written in Python, but as extention modules | - unfortunately SciPy is still Python 2.2. The Enthought Python 2.3 distribution contains SciPy .... http://www.enthought.com/ -- Cousin Stanley Human Being Phoenix, Arizona From pfleonard at hotmail.com Mon Oct 20 00:40:27 2003 From: pfleonard at hotmail.com (peter leonard) Date: Sun, 19 Oct 2003 21:40:27 -0700 Subject: Beginner question : skips every second line in file when using readline() Message-ID: Thanks for point out my error. This works fine now : datafile ="C:\\Classifier\Data\\test.txt" dataobject = open(datafile,"r") line = dataobject.readline() while line.strip(): print line line = dataobject.readline() I get the following desired output : line 1 line 2 line 3 line 4 line 5 Thanks again Peter >From: Hans Nowak >To: peter leonard >Subject: Re: Beginner question : skips every second line in file when using > readline() >Date: Mon, 20 Oct 2003 00:15:25 -0400 > >peter leonard wrote: > >>Hi, >>I having a problem with reading each line from a text file. For example, >>the file is a text file named 'test.txt' with the following content : >> >>line 1 >>line 2 >>line 3 >>line 4 >>line 5 >> >>The following script attempts to print out each line : >> >>datafile ="C:\\Classifier\Data\\test.txt" >>dataobject = open(datafile,"r") >> >>while dataobject.readline() !="": >> >> line = dataobject.readline() >> print line > >You're calling readline() twice. Use something like: > >line = dataobject.readline() >while : > ...do stuff... > line = dataobject.readline() > >or: > >for line in dataobject: > if : > break > ...do stuff... > >I'm writing , because you might want to revise >dataobject.readline() != "" as well. If you read from a text file, lines >will end in \n, so comparing them to "" will always return false. To check >for an empty line, not counting the trailing newline, use something like > >if not line.rstrip(): > # line is empty > >HTH, > >-- >Hans (hans at zephyrfalcon.org) >http://zephyrfalcon.org/ > _________________________________________________________________ Fretting that your Hotmail account may expire because you forgot to sign in enough? Get Hotmail Extra Storage today! http://join.msn.com/?PAGE=features/es From indigomoon at bonbon.net Wed Oct 1 14:49:22 2003 From: indigomoon at bonbon.net (Indigo Moon Man) Date: Wed, 1 Oct 2003 12:49:22 -0600 Subject: Extracting text from .png images References: Message-ID: Henrik Berg Nielsen spake thusly: > > I need to extract some text (well numbers actually) from a bunch of > similarly looking .png images. After extraction the numbers will be fed > to a Python script for further processing. Any good ideas on how to go > about with this? I have no idea whatsoever about how to extract the > numbers out of the images... > This might help you out... http://www.pricelessware.org/2003/PL2003TEXT.htm#Convert-OCR I'm not sure if it does PNG, you might have to convert the file to tiff or bmp or something. -- Audio Bible Online: http://www.audio-bible.com/ From bscholln at mac.com Tue Oct 28 20:47:51 2003 From: bscholln at mac.com (benjamin schollnick) Date: Wed, 29 Oct 2003 01:47:51 GMT Subject: Converting from VB? Partial success... Message-ID: <281020032047527850%bscholln@mac.com> I am attempting to convert the following VB Script code to Python, but with limited success. I appear to be connecting fine, but I can't get the registry information out... I can get the manifest, and I do have the correct permissions with the user account that I am using... The VB code works, so it is a issue with the python implementation... ------------------------ VB Code ----------------------------- Const HKEY_CURRENT_USER = &H80000001 Set objLocator = CreateObject("WbemScripting.SWbemLocator") Set objWMIService = objLocator.ConnectServer("13.1.99.43", "root\default", "operator", "spire") objWMIService.Security_.ImpersonationLevel = 3 set objRegister = objWMIService.get("StdRegProv") Dim arrValues strKeyPath = "Software\SCITEX\GUI" strKey = "Version" objRegister.GetStringValue HKEY_CURRENT_USER, strKeyPath, strKey, value Wscript.Echo value ------------------------------------------------------------------------- - import _winreg import win32com.client HostName = "remote_ip" # local host login_account = "account name" account_pass = "password" strKeyPath = r"\HKEY_LOCAL_MACHINE\SOFTWARe\Microsoft\DrWatson" strKey = r"AppendToLogFile" HKLM = 0x80000001L objLocator = win32com.client.Dispatch ("WbemScripting.SWbemLocator") print dir(objLocator) objWMIService = objLocator.ConnectServer (HostName, "root\default", login_account, account_pass) objWMIService.Security_.ImpersonationLevel = 3 print dir(objWMIService.__class__) # # Dir is showing a "generic" dynamic listing??? Why? # #print objWMIService.__doc__ objRegister = objWMIService.Get ("StdRegProv") test = objRegister.GetObjectText_ ( 1 ) #test2 = objRegister.GetStringValue_ ( "SOFTWARE\Microsoft\DrWatson", "AppendToLogFile" ) print test2 # Print's the manifest #print test From jjl at pobox.com Thu Oct 2 21:29:38 2003 From: jjl at pobox.com (John J. Lee) Date: 03 Oct 2003 02:29:38 +0100 Subject: A startup puzzle References: Message-ID: <87k77nyupp.fsf@pobox.com> "Edward K. Ream" writes: > The problem isn't so much the present namespace pollution, the problem is > that the technique doesn't extend well. There comes a point at which there > are just too many names to keep track of. So if I were managing a group of [...] Um, that *is* a form of namespace pollution, isn't it, Edward? > Still, I don't see a perfect alternative. For sure I wouldn't like to put a > g. in front of hundreds or thousands of function calls. I suppose that this > is the kind of thing one would be forced to do in slightly larger > projects...Any other ideas? Qt names everything with an initial Q (QWidget, QObject, QLineEdit, ...), so from qt import * with PyQt works very well. Only one saved character, I know, and it doesn't help you given that you've already named everything without such a convention... John From mrroach at okmaybe.com Wed Oct 22 16:54:23 2003 From: mrroach at okmaybe.com (Mark Roach) Date: Wed, 22 Oct 2003 20:54:23 GMT Subject: Return variables from modules ?? References: Message-ID: On Wed, 22 Oct 2003 17:09:54 +0100, Rigga wrote: > I have tried the code you supplied however it still does not return the > reply as expected, I have even tried the following code but I just cant get > it to return a variable from a module: > > My module: we will call it filechk.py > ******************************************************************** > import sys > import os > > def myfunction(): > reply = 'repeat' > FilePath = raw_input("Enter path to files: ") > > def chkpth(FilePath): Here you define chkpth, but you never call it... Why have you made this into a separate function inside of myfunction? It seems you should remove this def and unindent everything under it. -Mark From http Wed Oct 8 18:02:15 2003 From: http (Paul Rubin) Date: 08 Oct 2003 15:02:15 -0700 Subject: Book Recommendation References: Message-ID: <7xd6d7e6c8.fsf@ruckus.brouhaha.com> Anthony writes: > Ok you guys are the best I'm going to stop bugging you now and get to work > there is just one more question i have to ask. "Michael Geary" said read > the tutorial on python.org, but Core Python Programming covers everything > should i read the tutorial on python.org anyway or just the book? First, read the tutorial. Then, if you're still confused, go look at the book in the store and see if it answers your questions. If it does, buy it and read it. If it doesn't, look for another group, ask questions on the newsgroup, etc. In my opinion, if you have solid experience programming in other languages, then the tutorial and reference manual are probably all you need to get going with Python, and you needn't bother with any books. But if you're less experienced, you may benefit from a Python book. Also, I'm not familiar with "Core Python Programming" but if you feel you need a book, the first one I'd look at is "Python in a Nutshell". From dthierbach at gmx.de Mon Oct 27 06:43:31 2003 From: dthierbach at gmx.de (Dirk Thierbach) Date: Mon, 27 Oct 2003 12:43:31 +0100 Subject: Python from Wise Guy's Viewpoint References: Message-ID: <30dv61-ni5.ln1@ID-7776.user.dfncis.de> Pascal Costanza wrote: > Dirk Thierbach wrote: >> Maybe. It sure would help if you'd tell me your view instead of having >> me guess :-) For me, a type is a certain class of values, and a static >> type is given by a limited language describing such classes. A >> dynamic type is a tag that is associated with a value. Arbitrary >> classes of values (like "all reals less than 200") are not a type. > > What are "non-arbitrary classes of values"? Those that can be described by the language available for static types e.g. in Haskell or OCaml. > According to your criteria, (real * 200) is > - a certain class of values > - given in a limited language describing that class Yes, but you will have a hard time developing a static type checker that will work with such a language. > I would be interesting to see a convincing definition of the term "type" > that precludes (real * 200), and similar type specifications. Look at the definition for type in Haskell or OCaml, for example. > (Maybe it helps to explain that CHECK-TYPE doesn't check a value per se. > (check-type 5 (real * 200)) doesn't work. CHECK-TYPE checks a property > of the variable it is being passed.) Yes, I know. What does that explain? > "very rare situations" > "never a show-stopper" > > How do you know? > > If you are only talking about your personal experiences, that's fine, > but you should say so. Of course I am talking from personal experience, like everyone does. There is not other way. But in this case, I think my experience is sufficient to say that. > The only claim I make is that static type systems need to reject > well-behaved programs. That's an objective truth. This depends on the definition of "well-behaved". The claim I make is that for a suitable definition of "well-behaved", it is not an objective truth. And even if you stick to your definition of "well-behaved", it doesn't really matter in practice. > All I hear is that you (and many others) say that the disadvantages > of static typing are negligible. However, I haven't found any > convincing arguments for that claim. What kind of arguments would you like to have? I have tried to show with a few examples that even programs that you think should be rejected with static typing will be accepted (if you allow for the fact that they are written in a different language). What else is there I could possibly do? The simplest way is probably that you just sit down and give it a try. No amount of talking can replace personal experience. Get Haskell or OCaml and do a few simple examples. You will find that they have many things that you won't like, e.g. no good IDE, no "eval", and (as every language) they require a slightly different mindset compared to what you're used to. They might also not have the library functions that you are used to. But it might give you a good idea what programs are statically typeable and what are not. > But I am interested in the question why you (or others) think that > almost all software should be developed like that. I didn't say that. Please do not put up a strawman. In fact, I explicitely said "you use whatever tool you like best". > I have chosen to illustrate examples in which a dynamic approach might > be considerably better. And you didn't convince me; all your examples can be statically typed. > Again, to make this absolutely clear, it is my personal experience > that dynamic type checking is in many situations superior to static > type checking. That's maybe the important point. HOW DO YOU KNOW IF YOU HAVE NEVER TRIED IT? (In a language with good static typing, not in a language with lousy static typing). And obviously you haven't tried it, otherwise you wouldn't give examples that can be easily statically typed, or confuse exceptions or dynamic checks with static type checks. So it cannot come from your personal experience. > But I don't ask anyone to unconditionally use dynamically typed > languages. But you insist that dynamically typed languages are "better" or "superior to" statically typed, because you claim you cannot do things in a statically typed language that you can do in a dynamically typed one. That's the point where I disagree. I don't ask you to use a statically typed language, I just want you to give admit that both are equally good in this respect, or at least you should sit down and verify that yourself before saying it. - Dirk From ville.spammehardvainio at spamtut.fi Thu Oct 23 01:23:43 2003 From: ville.spammehardvainio at spamtut.fi (Ville Vainio) Date: 23 Oct 2003 08:23:43 +0300 Subject: Why don't people like lisp? References: <3f9302d7.170372828@news.eircom.net> Message-ID: > > Some people (academics) are paid for being clever. Others (engineers) > > Ville Vainio http://www.students.tut.fi/~vainio24 > ^^^^^^^^ > Tee hee! :) Yes, I have an account at a university. I prefer to use it instead of that of my ISP (because ISP's come and go) or my work account (to avoid associating my company with any of my opinions, which I think should be a standard policy.. also, they don't provide web publishing space for obvious reasons). -- Ville Vainio http://www.students.tut.fi/~vainio24 From aleax at aleax.it Thu Oct 9 08:10:12 2003 From: aleax at aleax.it (Alex Martelli) Date: Thu, 09 Oct 2003 12:10:12 GMT Subject: What method does slice notation call? References: Message-ID: Robert Brewer wrote: >>>> class A(types.DictType): > ... def __getitem__(self, key): > ... return types.DictType.__getitem__(self, key) > ... >>>> a = A() >>>> a[0] = 3 >>>> a.__getitem__ = lambda x: "w00t" >>>> a.__getitem__(0) > 'w00t' >>>> a > {0: 3} >>>> a[0] > 3 > > Can anyone tell me why a[0] doesn't return "w00t", like I thought it > would? What method is a[0] calling? Is there a way to override it? For all except "classic classes" (which have to do lots of hacking behind the scenes for backwards compatibility, sigh), a[0] means roughly the equivalent of: getattr(type(a), '__getitem__')(a, 0) so, if you want to have a[0] invoke something different, you must change type(a) accordingly, e.g.: def changeindexing(a, newgetitem): class x(type(a)): __getitem__ = newgetitem a.__class__ = x so, for example: def changeindexing(a, newgetitem): class x(type(a)): __getitem__ = newgetitem a.__class__ = x class A(dict): def __getitem__(self, key): return dict.__getitem__(self, key) a = A() a[0] = 3 a.__getitem__ = lambda x: "w00t" print a.__getitem__(0) print a print a[0] changeindexing(a, lambda self, x: 'blaap') print a.__getitem__(0) print a print a[0] prints: w00t {0: 3} 3 w00t {0: 3} blaap Note that the function you pass to changeindexing does need a 'self', just like any other method. If you don't want that, you can use a staticmethod, of course (but then the function won't have access to the specific instance it's being called on). Alex From bokr at oz.net Sat Oct 4 01:01:11 2003 From: bokr at oz.net (Bengt Richter) Date: 4 Oct 2003 05:01:11 GMT Subject: php squirrelmail out of memory at ISP's webmail :-( Message-ID: I guess there's python at the bottom of php? Anyway, is someone here familiar with the message that looks like """ Please purge your trash folder regularly. You can do this by clicking on the (purge) link on the left. Fatal error: Allowed memory size of 8388608 bytes exhausted (tried to allocate 42 bytes) in /vhome/common/webmail/squirrelmail-1.4.1/functions/imap_general.php on line 735 """ IMO this is not so nice. I can't get to my mail. I can get to it via my normal Eudora, so they suggested webmail, which worked once, and hasn't worked several times. I wonder if there is a memory leak or mis-counting, and I just lucked out once to hit it soon after a re-start. I could filter the mail, but I can't get the stream to filter it :-( Sorry about the OT, but I thought maybe it could be on topic sort of if there were a python memory leak behind it. Anyway, not happy with this, sorry. I would imagine this has happened to a few people, so before I go chasing sourceforge squirrelmail bug stuff, has anyone been there already and have more clue than I? TIA. Regards, Bengt Richter From aleax at aleax.it Fri Oct 31 03:49:18 2003 From: aleax at aleax.it (Alex Martelli) Date: Fri, 31 Oct 2003 08:49:18 GMT Subject: alwayssortedlist (was Re: On PEP 322 (ireverse)) References: <4xQnb.373812$R32.12367046@news2.tin.it> <7f9e1817.0310301253.7bfde49b@posting.google.com> Message-ID: Ian McMeans wrote: > Not only is it not effective, but heaps don't keep their elements in > sorted order... so if you wanted a list to stay sorted, heaps aren't Please don't "top-post": somebody reading your reply can't see what you ARE responding to. Putting your comments AFTER the phrase you're commenting on is much kinder to readers. I said a heap is "not effective" (as a way to sort, in Python) because the sort method of lists is so much faster. You CAN use a heap to sort, it's just not an _effective_ way to perform sorting in Python. Alex From a.schmolck at gmx.net Sun Oct 12 13:25:04 2003 From: a.schmolck at gmx.net (Alexander Schmolck) Date: 12 Oct 2003 18:25:04 +0100 Subject: Python syntax in Lisp and Scheme References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> <92c59a2c.0310031345.57d20631@posting.google.com> <6CZgb.3273$dn6.860@newsread4.news.pas.earthlink.net> <%hihb.4368$dn6.2921@newsread4.news.pas.earthlink.net> Message-ID: "Andrew Dalke" writes: > The smartest people I know aren't programmers. What does > that say? I think this is vital point. CL's inaccessibility is painted as a feature of CL by many c.l.l denizens (keeps the unwashed masses out), but IMO the CL community stunts and starves itself intellectually big time because CL is (I strongly suspect) an *extremely* unattractive language for smart people (unless they happen to be computer geeks). Apart from the fact that this yields a positive feedback loop, I'd think that even the smart computer geeks are likely to suffer from this incestuousness in the midrun. 'as From shuvit at 127.0.0.1 Thu Oct 16 15:12:55 2003 From: shuvit at 127.0.0.1 (Dave) Date: Thu, 16 Oct 2003 12:12:55 -0700 Subject: pyuic AttributeError in RedHat 9 Message-ID: I just upgraded to Redhat 9, and I'm now seeing problems with PyQt programs that worked in Redhat 8. Here is an example from a simple demo program created with qt-designer, compiled with pyuic, and run under python2.2: [macquigg at saguaro foodx]$ python2.2 food.py Traceback (most recent call last): File "food.py", line 34, in ? win = MainWindow() File "mainwindow.py", line 22, in __init__ self.fileNewAction.setIconSet(QIconSet(QPixmap.fromMimeSource(""))) AttributeError: fromMimeSource It was a rough upgrade, with lots of files failing the verification test, so first thing I did is force upgrade qt-designer, PyQt, sip, and python. [root at saguaro lib]# rpm -Uvh /home/macquigg/rpm/redhat/qt-designer-3.1.1-6.i386.rpm --replacepkgs Preparing... ##################################[100%] 1:qt-designer ##################################[100%] [root at saguaro lib]# rpm -V qt-designer [root at saguaro lib]# rpm -Uvh /home/macquigg/rpm/redhat/python-2.2.2-26.i386.rpm --replacepkgs Preparing... ##################################[100%] 1:python ##################################[100%] [root at saguaro lib]# rpm -V python [root at saguaro lib]# rpm -Uvh /home/macquigg/rpm/redhat/PyQt-3.5-5.i386.rpm --replacepkgs Preparing... ##################################[100%] 1:PyQt ##################################[100%] [root at saguaro lib]# rpm -V PyQt [root at saguaro lib]# rpm -Uvh /home/macquigg/rpm/redhat/sip-3.5-2.i386.rpm --replacepkgs Preparing... ##################################[100%] 1:sip ##################################[100%] [root at saguaro lib]# rpm -V sip [root at saguaro lib]# I also re-opened the project in the new qt-designer, and resaved the .ui files, then recompiled the .py files. The new .py files are definitely different, but I suppose this is to be expected. --> Old mainwindow.py: self.fileNewAction = QAction(self,"fileNewAction") self.fileNewAction.setIconSet(QIconSet(uic_load_pixmap_MainWindow(""))) --> New mainwindow.py: self.fileNewAction = QAction(self,"fileNewAction") self.fileNewAction.setIconSet(QIconSet(QPixmap.fromMimeSource(""))) The AttributeError remains. Any suggstions what to try next? Note: I have also installed python2.3 (from python.org). They say they have been careful not to step on previous files, but I suppose there is a possibility. -- Dave From mjackson at alumni.caltech.edu Fri Oct 10 12:18:27 2003 From: mjackson at alumni.caltech.edu (Mark Jackson) Date: 10 Oct 2003 16:18:27 GMT Subject: Nuclear Python? References: <84fc4588.0310070918.2201e1ac@posting.google.com> <6agdovovc8uq23it7joq76tq6sekolkl9v@4ax.com> Message-ID: Stephen Horne <$$$$$$$$$$$$$$$$$@$$$$$$$$$$$$$$$$$$$$.co.uk> writes: > If anyone can find a description for antisocial personality disorder > which gives the acronym 'BAD', please send the suggestion to the > American Psychiatric Association ;-) How about Bytecode Aversion Disorder, for those who insist that any language that is not compiled to machine code is worthless? -- Mark Jackson - http://www.alumni.caltech.edu/~mjackson There are two kinds of fool. One says, "This is old, and therefore good." And one says, "This is new, and therefore better." - Dean William Inge From eppstein at ics.uci.edu Tue Oct 14 11:33:02 2003 From: eppstein at ics.uci.edu (David Eppstein) Date: Tue, 14 Oct 2003 08:33:02 -0700 Subject: Python syntax in Lisp and Scheme References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> <6CZgb.3273$dn6.860@newsread4.news.pas.earthlink.net> <%hihb.4368$dn6.2921@newsread4.news.pas.earthlink.net> Message-ID: In article , Jacek Generowicz wrote: > However, please _do_ tell me if you hear of anyone implementing Python > in Lisp[*]. > > Having Python as a front-end to Lisp[*] (as it is now a front-end to > C, C++ and Java) would be very interesting indeed. It is now also a front-end to Objective C, via the PyObjC project. -- David Eppstein http://www.ics.uci.edu/~eppstein/ Univ. of California, Irvine, School of Information & Computer Science From BjornPettersen at fairisaac.com Wed Oct 1 16:03:27 2003 From: BjornPettersen at fairisaac.com (Pettersen, Bjorn S) Date: Wed, 1 Oct 2003 15:03:27 -0500 Subject: intercepting smtp email Message-ID: <1DAECE9E8F34E04AA0E5699AF7D9FF0907B5A0A7@stpmsg00.corp.fairisaac.com> > From: Peter Hansen [mailto:peter at engcorp.com] > > Scott Hathaway wrote: > > > > I want to write an NT service that will intercept any outgoing smtp > > traffic, like Norton Antivirus does. Can anyone tell me > > how I can do something like this in Python? I do not know > > how to intercept the outgoing traffic, specifically. > > Normally a mail program does not connect directly to the receiving > server, but sends all mail via a "relay" server which talks SMTP. > For example, if you have an ISP connection, your mail would go through > their server, which would forward it to the appropriate final > destination. [..] Although some "programs" have their own embedded smtp servers that attempt to connect directly to the recipients 'domain' before sending its payload... A small service that could catch this use-case would be useful for a number of friends of mine . (I think I know just the way to distribute it to get maximum effect too ). just-barely-joking'ly -- bjorn From jjl at pobox.com Fri Oct 31 16:40:10 2003 From: jjl at pobox.com (John J. Lee) Date: 31 Oct 2003 21:40:10 +0000 Subject: HTMLParser problems. References: Message-ID: <87y8v1krwl.fsf@pobox.com> Peter Otten <__peter__ at web.de> writes: > Sean Cody wrote: [...] > The simplest solution is to replace the above line with > > parser.feed(socket.read().replace(" ", "NaN") [...] That's platform-dependent, if you're relying on float("NaN"). John From ws-news at gmx.at Thu Oct 30 06:29:44 2003 From: ws-news at gmx.at (Werner Schiendl) Date: Thu, 30 Oct 2003 12:29:44 +0100 Subject: PEP 322: Reverse Iteration (second revision, please comment) In-Reply-To: References: Message-ID: <3fa0f5fb@brateggebdc5.br-automation.co.at> Alex Martelli wrote: > > A built-in iterator irange -- with an optional "reverse=" argument, > just like the very useful one you recently added to list.sort -- would be > just as useful as revrange for the latter's use cases, AND be very handy to > me in many more cases in which I currently use xrange and cringe each and > every time. Plus, specifically, I have some uses cases where: > > if mustbereversed(...): > seq = xrange(N-1, -1, -1) > else: > seq = xrange(N) > for item in seq: > ... > > and those would get a somewhat minor benefit from either reverse OR > revrange, since the if/else to prepare seq would still be there, > albeit more readable along one of the two branches. However, for this > kind of use case, an irange with an optional reverse= would be PERFECT: > > for item in irange(N, reverse=mustbereversed(...)): > ... > > now THAT would be blissful indeed. > +1 I'd definitely prefer such a general approach to having "revrange" However, I think it's no direct replacement for "reversed" regards Werner From whumeniu at nospamtelus.net Tue Oct 14 12:16:52 2003 From: whumeniu at nospamtelus.net (Wade Humeniuk) Date: Tue, 14 Oct 2003 16:16:52 GMT Subject: BIG successes of Lisp (was ...) In-Reply-To: References: Message-ID: As to Lisp Successes I would like to add just a few: Macsyma and Maxima http://maxima.sourceforge.net/ Powercase and Watson http://www.xanalys.com/solutions/powercase.html AutoCAD http://www.autocad.com Wade From mfranklin1 at gatwick.westerngeco.slb.com Mon Oct 27 05:24:13 2003 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Mon, 27 Oct 2003 10:24:13 +0000 Subject: Python is Considered Harmful In-Reply-To: References: Message-ID: <1067250252.1284.2.camel@m-franklin> On Mon, 2003-10-27 at 07:28, Lulu of the Lotus-Eaters wrote: > mike420 at ziplip.com wrote previously: > |All this Python bashing is starting to feel like mocking > |a retarded child... > > Y'know... a few dozen letters to 'abuse at ziplib.com' certainly couldn't > do any harm in troll management. It might not help... but it might. Perhaps that should read abuse at ziplip.com -- Martin Franklin From fumanchu at amor.org Fri Oct 10 04:19:12 2003 From: fumanchu at amor.org (Robert Brewer) Date: Fri, 10 Oct 2003 01:19:12 -0700 Subject: Could a single web framework popularize Python? Message-ID: Alan Little wrote: > > I see no real likelihood of python ever eating a > significant chunk of > > the corporate big systems market - there's too much > already invested > > in J2EE (not to mention older architectures that are still heavily > > used like CORBA and CICS). Java is more than good enough for the job > > and the skills are readily available. Why would anybody risk their > > company and their job on a completely unproven environment just > > because it happens to use a nicer programming language? Well, I did both; risked my company and my job. I worked for two years to get management to agree I needed to rewrite our core business app: a web app written in VB4!! I was then told to "do it in ASP". I refused, and am now rewriting it in Python. I risked my job because I felt, given our IT management history, that betting our systems on ASP or .Net would be a medium-to-long-term disaster from which we would not recover. Granted, we are a smallish business, developing our own software for our own use. However, you did ask. ;) Ian Bicking wrote: > Of course, as a Free Software advocate in general, I (we) shouldn't > really celebrate their loss. Java would be a more appealing > opponent. > Or more appealing yet, if we could be the alternative for people who > might use ColdFusion or ASP. Glad to appeal. :) > Eh, I don't worry too much about that. As long as the > framework isn't > insular (which might rule out Zope and asynchronous Twisted > programming) it's easy to translate knowledge into another > framework. > Python is Python, and that's really where your application is written. > > But if there was some sort of standardization, I personally feel > strongly it should support the current frameworks running on top of > that standard. The early adopters don't deserve to be jilted, and > that's no way to build confidence in the standard either. FWIW, I am writing my own framework. I have to integrate with a third party's proprietary CRM product, and I simply felt better about adapting my own framework to it than trying to add components onto Twisted or Zope or the framework du jour. Regardless, I make every effort to give others the freedom to use my code and *easily* replace/extend what doesn't work for them. It may never have another developer, but it makes my future brighter to be so maintainable. I like to think I could rip out a good chunk and replace it with Twisted, etc. in a short time if the need arose. Had to provide an anecdote. Robert Brewer MIS Amor Ministries fumanchu at amor.org From john_taylor_1973 at yahoo.com Mon Oct 13 21:48:25 2003 From: john_taylor_1973 at yahoo.com (John Taylor) Date: 13 Oct 2003 18:48:25 -0700 Subject: packing jython program with py2exe or to a jar Message-ID: I have a jython program which uses both .py and .class (also 2 other standalone .jar files). Is it possible to create a .exe file with py2exe? When I try I get this error message: warning: py2exe: * The following modules were not found: warning: py2exe: * java.awt warning: py2exe: * java.awt.event warning: py2exe: * ldapview ldapview.class is the program that I wrote. My jython program, which is how everthing starts, imports this module. If this is not possible, can I somehow convert my .py file to java and then jar everything? Thanks, John Taylor From mwh at python.net Fri Oct 17 09:17:23 2003 From: mwh at python.net (Michael Hudson) Date: Fri, 17 Oct 2003 13:17:23 GMT Subject: Trivial performance questions References: Message-ID: <7h3ad80m2ho.fsf@pc150.maths.bris.ac.uk> "Brian Patterson" writes: > I have noticed in the book of words that hasattr works by calling > getattr and raising an exception if no such attribute exists. If I > need the value in any case, am I better off using getattr within a > try statement myself, or is there some clever implementation > enhancement which makes this a bad idea? > > i.e. should I prefer: > if hasattr(self,"datum"): > datum=getattr("datum") > else: > datum=None > self.datum=None > > over: > try: > datum=self.getattr("datum") > except: Don't do that, do "except AttributeError:" instead. > self.datum=None > datum=None > > The concept of deliberately raising an error is still foreign to > this python newbie, but I really like the trapping facilities. I > just worry about the performance implications and memory usage of > such things, especially since I'm writing for Zope. The answer to which of these runs the fastest depends on how often you expect the attribute to exist. If it's not that often, the first form will probably be quicker, if not the second. However, there's a third form: datum = getattr(self, "datum", None) which is what you want here. > And while I'm here: Is there a difference in performance when checking: > datum is None > over: > datum == None Yes (I think...), but you shouldn't care much about it. > and similarly: > if x is None or y is None: > or: > if None in (x,y): Pass. Time it if you really care (my bet's on the former being quicker). > I appreciate that these are trivial in the extreme, but I seem to be > writing dozens of them, and I may as well use the right one and > squeeze what performance I can. This is an unhelpful attitude. You're writing in Python after all! If profile shows some of this code to be a hotspot, *then* and only then is it an appropriate time to worry about such trivial performance gains. Cheers, mwh -- The only problem with Microsoft is they just have no taste. -- Steve Jobs, (From _Triumph of the Nerds_ PBS special) and quoted by Aahz on comp.lang.python From prochak at netzero.net Tue Oct 28 23:54:52 2003 From: prochak at netzero.net (Erik Lechak) Date: 28 Oct 2003 20:54:52 -0800 Subject: plotting and diagramming library Message-ID: <1f0bdf30.0310282054.2f4103fa@posting.google.com> Hello All, I am creating a visual programming environment for python (similar to Matlab's simulink, but for python). For several reasons I have decided not to go with OGL. I am writing a wxOGL replacement library for wxPython. My first thought was to create an exact drop in replacement for OGL, but the more I look at the OGL api the more I hesitate to do it. The current library/test application is here (need python2.3 and wxPython): http://home.bellsouth.net/p/PWP-dande Please try it out and look at the code. You can connect pieces, zoom, tab to different shapes, add shapes to container blocks, and add code to code blocks. Eventually I would like this library to be used for complex diagrams as well as plotting. This means the library will have primitive shapes (no resize, no selection ...). It will also have complex shapes (resize, intelligent connections, selections). OGL does not really have this distinction. While working on this library I also noticed that it would be possible to make this library work with pygame. Here are my questions: 1) Should I model my api on OGL or the Tk::Canvas (I think it's Canvas). 2) Should I make it an exclusively wxPython library or should I put the time in now to make it work with wxPython and the pygame library? Are there other graphics libraries it should work with? 3) Would there be any interest if it could load and save in SVG format? 4) Should I go the OGL route and make the base class "Shape" fairly heavyweight like OGL, or should I make it lightweight (like I want). Lightweight means that the primitive shapes will hold their x,y data and know how to draw themselves and that's about it. Lightweight shapes would be great for plotting. On the other hand there has to be a reason why OGL and Tk give their basic shapes so much functionality. 5) wxDiagram is basically a list. I want my "Diagram" to take advantage of that fact and either have it inherit from list or delegate list-methods to its main list member. After all, this is python, and it would be cool to be able to insert,pop,append,extend,...,and iterate over a wxDiagram. My problem is wxPython/wxOGL api already has some naming conventions that don't look like the python list functions. Which one of these choices do you like a) Only implement the python list functions (or inherit from list, decorate when necessary) b) Only implement the wxDiagram api. (python list functionality lost) c) Implement both. (this kind of violates python's "one way to do it") Any one out there using (or wants to use) python for plotting or diagramming? I would like to hear from you. Thanks, Erik Lechak prochak at netzero.net From tim.one at comcast.net Sat Oct 4 13:01:52 2003 From: tim.one at comcast.net (Tim Peters) Date: Sat, 4 Oct 2003 13:01:52 -0400 Subject: Windows 2.3.2 install corrupt on python.org? In-Reply-To: Message-ID: [Bert Hyman] > ... > I've had no other problems with files downloaded via IE6 either > before or after this incident, and as I said, I repeated the exercise > three times and received identical results. > > Ah well... Since I'm the only one it's happening to, let's chalk this > one up as another Windoze Mystery. There are other, nastier possibilties, which have happened before: + Some machine on the path you take to python.org has broken HW or SW, corrupting some files passing thru it. + You have a virus that damages downloaded .exe files. Afraid the only thing we know for sure here is that *something* is broken for you. At least do a virus scan. A good, free, one-shot virus scan can be gotten here: http://housecall.trendmicro.com/ From see at my.signature Wed Oct 29 22:33:05 2003 From: see at my.signature (Jacques Garrigue) Date: 30 Oct 2003 12:33:05 +0900 Subject: Python from Wise Guy's Viewpoint References: <3F994597.7090807@ps.uni-sb.de> <87oew33h8t.fsf@sidious.geddis.org> <3F9D5D21.2060408@ps.uni-sb.de> <6dnq61-kl.ln1@ID-7776.user.dfncis.de> Message-ID: Pascal Costanza writes: > Matthias Blume wrote: > > >>No, it's not. There's a class of programs that exhibit a certain > >>behavior at runtime that you cannot write in a statically typed > >>language _directly in the language itself_. > > > > This is simply not true. See above. > > OK, let's try to distill this to some simple questions. > > Assume you have a compiler ML->CL that translates an arbitrary ML > program with a main function into Common Lisp. The main function is a > distinguished function that starts the program (similar to main in C). > The result is a Common Lisp program that behaves exactly like its ML > counterpart, including the fact that it doesn't throw any type errors at > runtime. > > Assume furthermore that ML->CL retains the explicit type annotations in > the result of the translation in the form of comments, so that another > compiler CL->ML can fully reconstruct the original ML program without > manual help. > > Now we can modify the result of ML->CL for any ML program as follows. We > add a new function that is defined as follows: > > (defun new-main () > (loop (print (eval (read))))) > > (We assume that NEW-MAIN is a name that isn't defined in the rest of the > original program. Otherwise, it's easy to automatically generate a > different unique name.) > > Note that we haven't written an interpreter/compiler by ourselves here, > we just use what the language offers by default. > > Furthermore, we add the following to the program: We write a function > RUN (again a unique name) that spawns two threads. The first thread > starts the original main function, the second thread opens a console > window and starts NEW-MAIN. > > Now, RUN is a function that executes the original ML program (as > translated by ML->CL, with the same semantics, including the fact that > it doesn't throw any runtime type errors in its form as generated by > ML->CL), but furthermore executes a read-eval-print-loop that allows > modification of the internals of that original program in arbitrary > ways. For example, the console allows you to use DEFUN to redefine an > arbitrary function of the original program that runs in the first > thread, so that the original definition is not visible anymore and all > calls to the original definiton within the first thread use the new > definition after the redefinition is completed. [1] > > Now here come the questions. > > Is it possible to modify CL->ML in a way that any program originally > written in ML, translated with ML->CL, and then modified as sketched > above (including NEW-MAIN and RUN) can be translated back to ML? For the > sake of simplicity we can assume an implementation of ML that already > offers multithreading. Again, for the sake of simplicity, it's > acceptable that the result of CL->ML accepts ML as an input language for > the read-eval-print-loop in RUN instead of Common Lisp. The important > thing here is that redefinitions issued in the second thread should > affect the internals of the program running in the first thread, as > described above. You have an interesting point here, but it is only partly related to static typing. It is more about static binding vs. dynamic binding. That is, are you able to dynamically change the definition of any identifier in the language. One must recognizes that dynamically typed systems, in particular Lisp and Smalltalk, also give you full dynamic binding, and that this is an incredibly powerful feature, at least for developpers. Now, would it be possible to do it in a statically typed language? I don't see why not. Some parts are relatively easy: allowing you to change function definitions, as long as you don't change the type. I say only relatively, because polymorphism may get in your way: you would have to replace any polymorphic function by a function at least as polymorphic as it, whether this polymorphism is really needed by the rest of the program or not. Some parts are much more difficult: how to change the data representation dynamically. This is already difficult in dynamically typed language (you must introduce lots of kludges to convert the data on the fly, probably on an as-needed basis), but in a statically typed language this must be expressed at the level of types. Matthias' argument would be that anyway you need to do some formal reasonning to prove that, knowing the dataflow of your program, you have indeed introduced all the needed conversions and kludges in you dynamically typed program, and that this reasonning could be converted to some kind of types, but this is going to be very hard. The most I know about this is some work on data versionning, but it doesn't consider modifications inside a running program. I'm willing to concede you the point: there may be applications where you want this ability to dynamically modify the internals of your program, and, while knowing this is just going to be damned dangerous, a fully dynamic (both types and binding) language is your only way to be sure that you will be able to do all and every possible changes. But these applications strike me as being of the high availability kind, so that the very fact this is so dangerous may be a major concern. On the other hand, in the huge majority of cases, this feature is only used during program development, and once you're done you compile and optimize, and optimizing actually means loosing most of the dynamic binding to allow inlining. In those cases, clever statically typed languages like ML compensate for their staticness in various ways, for instance by allowing efficient separate compilation as long as interfaces do not change. You may have to restart your program, but do not loose much time for that. And since more bugs are caught by the type system, the need to correct them is less frequent. You are also provided with an interactive toplevel, which lets you change some of the definitions at runtime, at least those functions and variables you have explicitly declared as mutable. Static typing does not prevent you from running and modifying interactively a GUI application, it just restricts the extent of the modifications you can do. (Contrary to Matthias I'm a purely static guy, but I've always been attracted by those fancy dynamic development environments.) --------------------------------------------------------------------------- Jacques Garrigue Kyoto University garrigue at kurims.kyoto-u.ac.jp JG From webmaster at beyond-thoughts.com Thu Oct 23 20:58:03 2003 From: webmaster at beyond-thoughts.com (Christoph Becker-Freyseng) Date: Fri, 24 Oct 2003 02:58:03 +0200 Subject: PEP 289: Generator Expressions (please comment) In-Reply-To: <5d83790c.0310231158.65595858@posting.google.com> References: <5d83790c.0310231158.65595858@posting.google.com> Message-ID: <3F98791B.8080301@beyond-thoughts.com> Raymond Hettinger wrote: > creating fast, memory efficient generator expressions on the fly: > > sum(x*x for x in roots) +3.1415 Especially I like the boost of use of many python-standard-functions -- like min, max, ... :-) Furthermore the syntax is quite clear and readable. However I'm a bit worried if some could get into trouble because of the difference between using Generator Expressions in function-call with one argument and a call with more than one arguments. Christoph Becker-Freyseng BTW: Python is getting more and more stuff. So I fear that some code might get harder to read for newbies (not knowing all the new stuff). Would it be possible to make an expression-/statement-parser that can analyse a code snippet (one line of python-code maybe more) and tell the user what syntax-constructs were used. This might be a big help when reading code and if you don't know some special construct. e.g.: newstuff.py: ... sum(x*x for x in roots) ... ??? Mmmm What's that pyscryer "sum(x*x for x in roots)" () Then you can search the Internet to close your knowledge gap (you can't search for "sum(x*x for x in roots)", but "python Generator Expression" might be succesful) From mike420 at ziplip.com Wed Oct 22 14:52:24 2003 From: mike420 at ziplip.com (mike420 at ziplip.com) Date: Wed, 22 Oct 2003 11:52:24 -0700 (PDT) Subject: Python from Wise Guy's Viewpoint Message-ID: Pascal Costanza wrote: > > ...because static type systems work by reducing the expressive power of > a language. It can't be any different for a strict static type system. > You can't solve the halting problem in a general-purpose language. You keep repeating the same ignorant BS for gazillionth time! You sound like Martelli talking about macros. Learn Haskell for fuck's sake! You'll find that even though it's statically typed, it's also more expressive than Lisp (you get more programming logic for each byte of code) and it's easier to glue components together (because of purity and monads) (All-in-all, I prefer Lisp though. Not because it's more expressive, but because I like Lisp REPL more than Haskell's) From enrico_morelli at yahoo.com Wed Oct 15 05:40:01 2003 From: enrico_morelli at yahoo.com (Enrico Morelli) Date: Wed, 15 Oct 2003 11:40:01 +0200 Subject: Read long int from binary file References: <3F8C243B.EEFA8259@engcorp.com> Message-ID: On Wed, 15 Oct 2003 08:06:56 +0000, Alex Martelli wrote: > Enrico Morelli wrote: > ... >> I do know the format (in advance). >> I have some binary files coming from SGI boxes and other from Linux boxes. >> These files contains 32 bit long integer data that I need to read and >> display in some graphic format. >> In some cases I have to reverse the byte order in other not. >> >> I'm unable to read these files and put the data in some array. >> I tried to use f.read(4), but I have 4 numbers not one. > > > import array > > x1 = array('l') > f1 = file('file_ok.dat', 'rb') > x1.fromfile(f1) > f1.close() > > x2 = array('l') > f2 = file('file_toswap.dat', 'rb') > x2.fromfile(f2) > x2.byteswap() > f2.close() > > > Alex Thanks Alex!!! A question, the fromfile syntax wants the n items to read. x1.fromfile(f1,1) read exactly one 32 bit long integer? Enrico PS. Sei sempre 'r mejo!! From jrm at ccs.neu.edu Fri Oct 24 15:27:55 2003 From: jrm at ccs.neu.edu (Joe Marshall) Date: Fri, 24 Oct 2003 15:27:55 -0400 Subject: Static typing References: <_8Ekb.7543$pT1.318@twister.nyc.rr.com> <90fk61-j71.ln1@ID-7776.user.dfncis.de> <5Cdmb.18630$Fm2.9443@attbi_s04> Message-ID: "Marshall Spight" writes: > "Pascal Costanza" wrote in message news:bnbds3$uui$1 at f1node01.rhrz.uni-bonn.de... >> >> Expressive power is not Turing equivalence. > > Agreed. > > So, does anyone have a formal definition of "expressive power?" > Metrics? Examples? Theoretical foundations? http://citeseer.nj.nec.com/felleisen90expressive.html It's a start. From edcjones at erols.com Sun Oct 12 11:21:19 2003 From: edcjones at erols.com (Edward C. Jones) Date: Sun, 12 Oct 2003 11:21:19 -0400 Subject: [Howto] Compiling debug Python extensions for non-debug Python In-Reply-To: References: Message-ID: Mike C. Fletcher wrote: > Every few months I get to working on a Python C extension (built with > distutils) and discover a pointer error or the like where I'd like to be > able to step into my DLL and see where the extension is going wonky. ... I have had the same problem in Linux. In the old DOS Borland Debugger, I could tell the debugger to display a particular source code file. Then I could set a breakpoint in it. Is this possible in gdb or some other UNIX debugger? Has anyone ported the Borland Debugger to Linux? From fuerte at sci.fi Mon Oct 13 16:18:12 2003 From: fuerte at sci.fi (Harri Pesonen) Date: Mon, 13 Oct 2003 23:18:12 +0300 Subject: private variables/methods In-Reply-To: <17bkov48ob18hbg959r8o8vr8q17md8373@4ax.com> References: <3F856275.C884CE5@engcorp.com> <3ogib.657$cT6.27058@news20.bellglobal.com> <8Nkib.272892$R32.8895469@news2.tin.it> <17bkov48ob18hbg959r8o8vr8q17md8373@4ax.com> Message-ID: Christopher Koppler wrote: > On Sun, 12 Oct 2003 22:42:12 GMT, Alex Martelli > wrote: > >>Sean Ross wrote: >> >>>Hi. >>>I'm not sure I'm clear on what behaviour "import __current_module__" is >>>expected to have. >> >>Just like any other import, it binds the name to a module object -- except >>that it specifically binds said name to the module containing the function >>that executes this import statement. The use case is: deprecating the >>global statement. Setting a global variable would instead use: >> import __current_module__ >> __current_module__.thevariable = 23 > > Hmmm, asking naively: why not make global (or some better name, I > don't have any good ideas however) the self of the current module - > i.e. instead of > > def fun(): > global x > x = somevalue > > or your import, you'd use > > def fun(): > global.x = somevalue > > And every module would set it's __global__ to itself by default... > > Just a naive idea, of course... Sounds good to me. So if you have now a = 1 def b(): a = 2 This would cause a compiler warning that a global "a" already exists. So the programmer should write either def b(): global.a = 2 or def b(): local.a = 2 The latter of course creates a new local variable with the same name. After this it is OK to use just "a" without "local" prefix? def b(): local.a = 2 a = 3 How about the following: def b(): global.a = 2 a = 3 Is the second "a" still global? The idea with "Option Explicit" gets around this differently. The following creates a new local variable: def b(): var a = 2 While the following refers to the global variable, if there is no local variable with the same name: def b(): a = 2 This would be more beautiful. Harri From paul.kemp at standardbank.com Sat Oct 18 09:05:16 2003 From: paul.kemp at standardbank.com (Paul) Date: 18 Oct 2003 06:05:16 -0700 Subject: How to implement COM class attributes? Message-ID: Would anyone be able to show me an example of how to implement and use class attributes on a COM component implemented in Python? I've experimented using these directives: _public_attrs_ = ['server', 'user'] or _readonly_attrs = ['server', 'user'] ...but I never seem to be able to retrieve them (or set them) from a client. Thanks Paul From peter at engcorp.com Mon Oct 6 19:19:31 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 06 Oct 2003 19:19:31 -0400 Subject: Pure Python XML parser References: Message-ID: <3F81F883.7CFE9C95@engcorp.com> "Ellinghaus, Lance" wrote: > > Does anyone have a pure python XML parser? http://www.fourthought.com (I *think* it's pure XML...) -Peter From raffaelcavallaro at junk.mail.me.not.mac.com Fri Oct 17 08:03:49 2003 From: raffaelcavallaro at junk.mail.me.not.mac.com (Raffael Cavallaro) Date: Fri, 17 Oct 2003 12:03:49 GMT Subject: Express What, not How. References: <3f8e1312@news.sentex.net> Message-ID: In article <3f8e1312 at news.sentex.net>, hs at heaven.nirvananet (Hartmann Schaffer) wrote: > map is an abstraction that > specifies that you want to apply a certain operation to each element > of a collection, with adding the offset being the desired operation. Sorry to reply so late - I didn't see this post. In the context in which the offsets are added, it isn't necessary to know that the offsets are added using map, as opposed, for example, to an interative construct, such as loop. Since we don't need to know _how_ the adding of offsets is done at every location in the source where we might want to add an offset to the elements of a list or vector, we should _name_ this bit of functionality. This is an even bigger win should we ever decide to switch from map to loop, or do, or dolist, etc. Then we write a single change, not one for every time we use this bit of functionality. From smm at ibl.bm Sun Oct 12 20:45:27 2003 From: smm at ibl.bm (Sean Moore) Date: 12 Oct 2003 17:45:27 -0700 Subject: Numerical Python question References: <500a4565.0310112107.22275705@posting.google.com> Message-ID: "Neil Hodgson" wrote in message news:... > 2mc: > > > Assume an array in Numerical Python, the contents of which are the > > daily open, high, low, and last prices of the DOW Jones Industrial > > Average for its entire history. How would one iterate throughout the > > entire array calculating the 10 day average of daily high price or the > > daily low price? > > The common technique for moving averages is to maintain a single > accumulator value over the last n points. For each new point, remove (by > subtracting) the value at the beginning of the window and add in the value > at the end of the window. The value of the accumulator divided by n is the > moving average. You will need to define what you want as output, if any, > before the nth point. > > Neil While this is common in c/c++, it is not the most efficient way in python when you have numpy around to do the loops in c if used correctly. I use the following setup from Numeric import array, cumsum def movavg(s, n): ''' returns an n period moving average for the time series s s is a list ordered from oldest (index 0) to most recent (index -1) n is an integer returns a numeric array of the moving average ''' s = array(s) c = cumsum(s) return (c[n-1:] - c[:-n+1]) / float(n) This should run in near constant time with regard to n (of course, O(n) to the length of s). At least one person has said yuk becuase of the numerical issue of losing precission in the cumsum, but for small n's, and values like you will see in stock prices and indices, I don't think this is too much of a problem. Someone may have a more numerically stable version, but then you could just implement the c-code version and wrap it for python. Sean From etjo at freenet.de Tue Oct 28 09:30:58 2003 From: etjo at freenet.de (etjo) Date: Tue, 28 Oct 2003 15:30:58 +0100 Subject: Installing Python in an separat area Message-ID: Dear All, I'd like to install python1.5.2 (version that is used for production here) and python2.3.2 together with tcl/tk8.3 and tcl/tk8.4 and the related tix packages in an separat area, i.e. somewhere on a NFS partition in order to allow everyone in the department to mount it and have it available. For instance... I have a disk named /raid02 with a directory /raid02/opt where I would like to keep everything... /raid02/opt/bin /raid02/opt/lib /raid02/opt/include /raid02/opt/... so everyone can add /raid02/opt/bin to his PATH entry and has the dedicated python versions available. Unfortunately I have problems in setting up Tkinter installation, i.e. tcl/tk properly, since I always receive an error that make can't find teh propper tcl, tk and tix libraries. Please, could someone tell me what ar the right options to use with/in ./configure, make, Makefile Module/Setup? Thanks in advance, joe From aleaxit at yahoo.com Fri Oct 10 18:22:04 2003 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 10 Oct 2003 22:22:04 GMT Subject: private variables/methods References: <3F856275.C884CE5@engcorp.com> Message-ID: Harri Pesonen wrote: ... > Because it has been asked 4000 times probably means that there is a > great need for the feature... I can't think of ANY "feechur" from other popular languages that hasn't been asked for, thousands of times. Does this mean that "there is a great need" for each and all of them? Not at all: it just means that people hanker for what they're familiar with. If Python were to satisfy even 1/10th of this incessant barrage of requests, it would devolve to a large amorphous blob -- like many other languages have. The people requesting these features are typically NOT experienced with Python: they haven't experienced how the LACK of these features in fact makes it easier and more productive to write application programs. > "Python" doesn't want a "private" keyword? If Python can be said to have a will -- embodied in Guido or spread as community consensus -- it definitely doesn't. > I have quite a limited Python > experience but I would like to have the following features in Python > that are common in other languages: Not 'but', but rather, THEREFORE. Reread your words with this change and with some luck you may get it. > * Option Explicit > * variable type declaration (optional) > * private variables/methods > > Most of these are handy for large projects, where you want to be sure > that a class is not misused (by other developers). These also mean that > it is much harder to create bugs. I like Python a lot, but with these > features it would be much better for serious development of complex > applications, not just for scripting. You are wrong. I used to harbor similar illusions (to a lesser degree, because I _did_ have SOME experience with other dynamic languages, but not in using them for really large apps) back when the language I most used was C++. I was wrong, too. Other developers aren't any likelier to "misuse" your class than you are to misdesign it in the first place -- and you'll NEVER "be sure" anyway, as restrictions can be worked around. _ADVISORY_ indications of "privacy" -- the convention of starting the name with a single underscore -- are much simpler and equally effective for your purposes. Python is wonderfully effective for programming large applications, exactly as it is today. > One thing I have noticed that the keyword "global" is very confusing. You are right. It would be better if the current module could be imported -- by using some reserved special module name in a perfectly ordinary 'import' instruction -- so that global variables could then be re-bound as attributes of this module. Just to give you an idea, in today's Python you could add this feature as: # part to be executed once, e.g. in site.py import __builtin__, sys _base_import = __builtin__.__import__ def __import__(name, *args): if name == '__current_module__': name = sys._getframe(1).f_globals['__name__'] return _base_import(name, *args) __builtin__.__import__ = __import__ # end of part to be executed once # example use x = 23 def set_the_global(): import __current_module__ __current_module__.x = 45 print x set_the_global() print x emits 23 45 > For example, the following is syntactically valid Python: > > a = 1 > def b(): > a = 2 > def c(): > return a > > But it does not work as expected. Function b just creates a new local > variable "a" inside function b! The correct function is of course: > > def b(): > global a > a = 2 > > On the other hand, function c refers to the same global variable just > fine without any extra "global" keyword. Why on earth?? :-) In every Because reading is different from writing. Reading globals is (more or less) all right; writing globals is a delicate decision that is well worth emphasizing. So, anything that's written (any name that's re-bound, to be precise) is deemed to be local -- unless explicitly mentioned in a global statement. The problem with global is that it's not clear enough. If there simply was NO way at all to have any assignment to a bare name, such as "a=2", EVER affect anything BUT a local, things would be much clearer; the need to import __current_module__ would emphasize what a serious, think-twice-about-it decision it is to choose to rebind module-global names. It would also emphasize that 'global' means 'of this module', not in any way of ALL modules -- a misconception that often affects newbies. Hmmm -- maybe THIS is worth proposing for 2.4 (with a pending deprecation warning for the global statement)... > other language I know you don't need "global". It is ugly. Problem is, it's not quite ugly enough (nor quite clear enough). Discouraging you from affecting globals is a swell idea, but I think the 'global' statement may not be enough for that, whence my newly conceived suggestion about importing... Alex From hanzspam at yahoo.com.au Mon Oct 27 08:26:52 2003 From: hanzspam at yahoo.com.au (Hannu Kankaanp??) Date: 27 Oct 2003 05:26:52 -0800 Subject: Python is not [yet] Considered Harmful References: Message-ID: <840592e1.0310270526.75a99bb0@posting.google.com> mike420 at ziplip.com wrote in message news:... > It was an honest mistake, not a troll! Still, I think it should > be [1, 2, 3] instead of [3, 3, 3] I don't think you understand what a troll is. Troll is someone who posts any of the following: 1. "Python is Considered Harmful" (given it's highly readable syntax, great libraries and high dynamicity, I can't see how a single feature could make Python 'harmful'. The title could've just been "Unexpected behaviour of closures inside list comprehensions") 2. "I present to you the final and ultimate proof of Python's brain-damage" (again, a needless attack.. which turned against yourself though) 3. "All this Python bashing is starting to feel like mocking a retarded child..." (this doesn't need explanation, I hope) And look, you posted all three of them in a single message! Well, your typo gave us a good laugh nevertheless ;) If you want [1, 2, 3], try: map(lambda f: f(1), [lambda x, i=i: x + i for i in range(3)]) i=i will make a local variable i within the lambda so that each lambda will refer to their own i instead of sharing the same i from the outer scope. From ianb at colorstudy.com Wed Oct 22 12:37:40 2003 From: ianb at colorstudy.com (Ian Bicking) Date: Wed, 22 Oct 2003 11:37:40 -0500 Subject: Unittest - How do I code lots of simple tests In-Reply-To: <87r815tobq.fsf@pobox.com> Message-ID: <0D85EAFF-04AE-11D8-AF55-000393C2D67E@colorstudy.com> On Wednesday, October 22, 2003, at 08:05 AM, John J. Lee wrote: > Ian Bicking writes: > [grumbles about unittest] > > BTW, Ian, did you notice that somewhere on one of the Zope sites > there's a reference to your blog entry about this? Looked like they > have a unittest.main-replacement. Yes, I've been experimenting with it. (For others, the URL is http://cvs.zope.org/Zope/test.py ) -- it's a bit hard to figure out, it has some documentation but only about how to run the script, not how to organize your tests. After much struggling I've gotten it to run -- it seems picky about where you put your tests, and it just ignored my tests until I more carefully pointed the script to where they were (but there's several ways to point the script to a directory, only --libdir seemed to work for me). I'm still not sure how to specify which tests I want to run -- it has some regex control there, which seems like both overkill and underkill (I don't need the flexibility of regexes to match modules, but I want better ways to indicate specific tests in those modules). I actually *like* the basic interface of unittest.main. What appealed to me about Zope's test.py was pychecker and pdb options (ontop of code coverage, which several frameworks have). Though once I looked at how pychecker is invoked, that's easy to add to any framework. Code coverage is supported by several frameworks -- I added it to my own unittest-based tests pretty easily too. Maybe if I looked at pdb it would also be easy enough as well, at which point I may or may not find the Zope test.py appealing enough to try to figure out how it finds (or does not find) files (though now that I've gotten this far...) -- Ian Bicking | ianb at colorstudy.com | http://blog.ianbicking.org From brian at zope.com Mon Oct 27 23:29:54 2003 From: brian at zope.com (Brian Lloyd) Date: Mon, 27 Oct 2003 23:29:54 -0500 Subject: Python for .NET 1.0 beta 1 released Message-ID: Python for .NET 1.0 beta 1 has been released - you can download it from: http://www.zope.org/Members/Brian/PythonNet/ Python for .NET is a near-seamless integration of Python with the .NET common language runtime. For more details, see the README: http://www.zope.org/Members/Brian/PythonNet/README.html With the 1.0 b1 release, it is nearly feature-complete and is now usable for real applications (some simple demos are included). There is also now a mailing list for discussion, questions and issues related to Python for .NET at: pythondotnet at python.org. To subscribe to the mailing list or read the online archives, see: http://mail.python.org/mailman/listinfo/pythondotnet Brian Lloyd brian at zope.com V.P. Engineering 540.361.1716 Zope Corporation http://www.zope.com From j-anthony at rcn.com Thu Oct 9 16:26:50 2003 From: j-anthony at rcn.com (Jon S. Anthony) Date: 09 Oct 2003 16:26:50 -0400 Subject: Python syntax in Lisp and Scheme References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> <92c59a2c.0310031345.57d20631@posting.google.com> <6CZgb.3273$dn6.860@newsread4.news.pas.earthlink.net> <8765iy2wt3.fsf@thalassa.informatimago.com> Message-ID: "Andrew Dalke" writes: > Ahhh, so make the language easier for computers to understand and > harder for intelligent users to use? ;) Spoken like a true Python supporter... /Jon From gh at ghaering.de Thu Oct 9 19:13:05 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Fri, 10 Oct 2003 01:13:05 +0200 Subject: distutils: How handle header files??? Got any examples? In-Reply-To: References: Message-ID: <3F85EB81.5070702@ghaering.de> Christian Seberino wrote: > (distutils question) > I know how to configure C code with Extension class in setup.py. > > But, how do you handle header files??.. Do you mention them in your > Extension(...) line?? [...] No, just use them in your C files with #include "myheader.h" and put them in the same directory where your C files and your setup.py are located. Nothing more to worry about. -- Gerhard From SBrunning at trisystems.co.uk Mon Oct 6 11:44:08 2003 From: SBrunning at trisystems.co.uk (SBrunning at trisystems.co.uk) Date: Mon, 6 Oct 2003 16:44:08 +0100 Subject: another fp problem Message-ID: <31575A892FF6D1118F5800600846864D014B2A00@intrepid> > From: Michael Hall [SMTP:office at ninti.com] > I'm wondering what is the best way or numerical data type to do simple > monetary > calculations in Python? http://www.google.com/search?q=python+money Cheers, Simon Brunning, TriSystems Ltd. ----------------------------------------------------------------------- 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 peter at engcorp.com Fri Oct 10 12:46:27 2003 From: peter at engcorp.com (Peter Hansen) Date: Fri, 10 Oct 2003 12:46:27 -0400 Subject: Problems with a programme called CyberChair References: <20031009140951.GA23061@doctor.nl2k.ab.ca> <20031009142118.GB5735@nl.linux.org> <3F859829.D7F0C822@engcorp.com> Message-ID: <3F86E263.D6C7F88F@engcorp.com> The Doctor wrote: > > In the mean time, I adjusted the #! > to include the more stable version and added -d -v at the end. > > I got: > > Your server is not allowed to access this script. import struct # dynamically loaded from /usr/local/lib/python2.1/lib-dynload/struct.so import fcntl # dynamically loaded from /usr/local/lib/python2.1/lib-dynload/fcntl.so # /usr/local/lib/python2.1/plat-freebsd4/FCNTL.pyc matches /usr/local/lib/python2.1/plat-freebsd4/FCNTL.py import FCNTL # precompiled from /usr/local/lib/python2.1/plat-freebsd4/FCNTL.pyc import submit_save # from /usr/local/www/data/naiso/cgi-bin/submit_save.py # can't create /usr/local/www/data/naiso/cgi-bin/submit_save.pyc import submit_phase1 # from /usr/local/www/data/naiso/cgi-bin/submit_phase1.py # can't create /usr/local/www/data/naiso/cgi-bin/submit_phase1.pyc > > What should I do next? I suggest finding where the error message is coming from. What evidence is there that this is a Python issue, and not an error message from the operating system? Once you find the line in the script which produces that error message, you should be able to look backwards to find the conditions which would cause it to be printed. -Peter From adalke at mindspring.com Thu Oct 9 15:52:47 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Thu, 09 Oct 2003 19:52:47 GMT Subject: Python syntax in Lisp and Scheme References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> <92c59a2c.0310031345.57d20631@posting.google.com> <6CZgb.3273$dn6.860@newsread4.news.pas.earthlink.net> Message-ID: Me: > > Note that I did not at all make reference to macros. Your statements > > to date suggest that your answer to the first is "no." Doug Tolton: > That's not exactly my position, rather my position is that just about > anything can and will be abused in some way shape or fashion. It's a > simple fact of working in teams. However I would rather err on the side > of abstractability and re-usability than on the side of forced restrictions. You are correct. I misremembered "Tolton" as "Tilton" and confused you with someone else. *blush* My answer, btw, that the macro preprocessor in C is something which is useful and too easily prone to misuse. Eg, my original C book was "C for native speakers of Pascal" and included in the first section a set of macros like #define BEGIN { #define END } It's not possible to get rid of cpp for C because the language is too weak, but it is something which takes hard experience to learn when not to use. As for a language feature which should never be used. Alex Martelli gave an example of changing the default definition for == between floats, which broke other packages, and my favorite is "OPTION BASE 1" in BASIC or its equivalent in Perl and other langauges. That is, on a per-program (or even per-module) basis, redefine the 0 point offset for an array. Andrew dalke at dalkescientific.com From dave at pythonapocrypha.com Tue Oct 7 16:18:40 2003 From: dave at pythonapocrypha.com (Dave Brueck) Date: Tue, 7 Oct 2003 14:18:40 -0600 Subject: wxPython log/print question In-Reply-To: References: Message-ID: <200310071418.40653.dave@pythonapocrypha.com> On Tuesday 07 October 2003 02:02 pm, Edward K. Ream wrote: > Creating a wxApp object in wxPython causes all calls to print go to a fake > console window. This is most inconvenient if errors during startup causes > the fake window to go away. How can I disable this "feature" so that > Python's print statement continues to send its output to the xp console? Yeah, I remember that. Short-term: start with "python -i" so that the interpreter stays running and the messages don't go away. There *is* a way to disable this - I don't remember exactly where but do remember it wasn't too painful to find - check the source for the wxApp class (in wx.py I think). Try wxApp(None). -Dave From dougrams at comcast.net Thu Oct 23 11:53:21 2003 From: dougrams at comcast.net (Doug R) Date: 23 Oct 2003 08:53:21 -0700 Subject: using PIL for anti-automation in ASP References: <525cbda1.0310221014.4e5ed50c@posting.google.com> <878yncbyhi.fsf@pobox.com> Message-ID: <525cbda1.0310230753.5543df32@posting.google.com> Thanks for the suggestions, and the reference site. Doug From adalke at mindspring.com Sat Oct 11 00:07:50 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Sat, 11 Oct 2003 04:07:50 GMT Subject: Jython, GILs and object locking. References: Message-ID: Carl Banks: > Your big computer science words frighten me. "I/O bound" == "tied up doing I/O instead of using the processor" If something is I/O bound then faster code won't make a difference; using an optimizing compiler or rewriting the algorithm won't give a speedup. If something is CPU bound then a faster network/disk drive/etc. won't make a difference There's also memory bound, where the time to access memory is the limiting factor. Most programs don't have this problem (the main exception I know of is quantum chemical programs, but that's a big chemistry word ;). Andrew dalke at dalkescientific.com From gabor at z10n.net Thu Oct 9 03:42:29 2003 From: gabor at z10n.net (gabor) Date: Thu, 9 Oct 2003 09:42:29 +0200 Subject: private variables/methods Message-ID: <20031009074229.GA28529@core.realtime.sk> hi, as far as i know in python there aren't any private (i mean not accessible from the outside of the object) methods/fields. why? in java/c++ i can make a method private, this way unaccessible for the outside world. i think it helps a lot to make for example a library more robust. i know that there is some kind of notation to make a method/field private, but one can still overwrite it's value. what's the reason for this? i'l mostly interested in the design reasons. thanks, gabor -- That's life for you, said McDunn. Someone always waiting for someone who never comes home. Always someone loving something more than that thing loves them. And after awhile you want to destroy whatever that thing is, so it can't hurt you no more. -- R. Bradbury, "The Fog Horn" From jch at pps.jussieu.fr Thu Oct 30 14:33:20 2003 From: jch at pps.jussieu.fr (Juliusz Chroboczek) Date: 30 Oct 2003 20:33:20 +0100 Subject: Whoa! Do Python and Lisp really have LAMBDA ? References: Message-ID: Q> Scheme doesn't have a for loop either, It's called DO and it does the right thing. Juliusz From edi at agharta.de Fri Oct 10 05:13:03 2003 From: edi at agharta.de (Edi Weitz) Date: 10 Oct 2003 11:13:03 +0200 Subject: Python syntax in Lisp and Scheme References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> <92c59a2c.0310031345.57d20631@posting.google.com> <6CZgb.3273$dn6.860@newsread4.news.pas.earthlink.net> <3F853D60.9E133724@setf.de> <3F85CEC3.D17BE65E@setf.de> Message-ID: <8765ixmp5s.fsf@bird.agharta.de> On Thu, 09 Oct 2003 23:31:46 GMT, "Andrew Dalke" wrote: > Conjecture: Is it that the commericial versions of Lisp pull away > some of the people who would otherwise help raise the default > functionality of the free version? I don't think so... but then > why? I'm pretty sure this is the case. If you lurk in c.l.l for a while you'll see that a large part of the regular contributors aren't what you'd call Open Source zealots. Maybe that's for historical reasons, I don't know. But of course that's different from languages which have always been "free" like Perl or Python. To give one example: One of the oldest dynamic HTTP servers out there is CL-HTTP.[1] I think it is very impressive but it has a somewhat dubious license which doesn't allow for commercial deployment - it's not "free." Maybe, I dunno, it would have a much higher market share if it had been licensed like Apache when it was released. I'm sure there's much more high-quality Lisp software out there that hasn't even been released. Edi. [1] Don't be fooled by the "Last updated" line. There's still active development - see . From aleax at aleax.it Fri Oct 31 05:42:15 2003 From: aleax at aleax.it (Alex Martelli) Date: Fri, 31 Oct 2003 10:42:15 GMT Subject: Removing Unicode from Python? References: Message-ID: Brian Quinlan wrote: >> All MS products use unicode strings. All the time. Its integral to >> the OS and all its libraries. > > This statement is obviously false. It's slightly exaggerated, yes. But it's basically true of COM and dotNET (just as it is of Java). >> VB and other MS offspring allow you to ignore that fact, but they >> don't make it go away. >> >> Python is just doing what it should do: handle unicode strings as > unicode >> strings. > > But the SQL Server "text" type is not a Unicode type. When you access SQL Server via a COM interface, you'll get BSTR's (which are COM's most normal "strings", and VB's) -- i.e., Unicode. Alex From klappnase at web.de Fri Oct 31 06:39:34 2003 From: klappnase at web.de (klappnase) Date: 31 Oct 2003 03:39:34 -0800 Subject: win2k sound control References: Message-ID: "ken" wrote in message news:... > I'm trying to write a simple app to enable/disable (mute) the audio from a > command line control for a win2K machine. Can someone point me to the right > library(s) that have entries for audio controls. I've looked at the "set > (channel, (left, right))" function in the mixer device object document but > this controls the volume (up/down) and I need to be able to mute the volume. > > TIA, > Ken Erickson May be you might have a look at www.speech.kth.se/snack Cheers Michael From a.schmolck at gmx.net Tue Oct 7 16:25:53 2003 From: a.schmolck at gmx.net (Alexander Schmolck) Date: 07 Oct 2003 21:25:53 +0100 Subject: Python syntax in Lisp and Scheme References: <3cea3gqq.fsf@comcast.net> Message-ID: Joe Marshall writes: > Alexander Schmolck writes: > > > prunesquallor at comcast.net writes: > (I'm ignoring the followup-to because I don't read comp.lang.python) Well, I supposed this thread has spiralled out of control already anyway:) > Indentation-based grouping introduces a context-sensitive element into > the grammar at a very fundamental level. Although conceptually a > block is indented relative to the containing block, the reality of the > situation is that the lines in the file are indented relative to the > left margin. So every line in a block doesn't encode just its depth > relative to the immediately surrounding context, but its absolute > depth relative to the global context. I really don't understand why this is a problem, since its trivial to transform python's 'globally context' dependent indentation block structure markup into into C/Pascal-style delimiter pair block structure markup. Significantly, AFAICT you can easily do this unambiguously and *locally*, for example your editor can trivially perform this operation on cutting a piece of python code and its inverse on pasting (so that you only cut-and-paste the 'local' indentation). Prima facie I don't see how you loose any fine control. > Additionally, each line encodes this information independently of the other > lines that logically belong with it, and we all know that when some data is > encoded in one place may be wrong, but it is never inconsistent. Sorry, I don't understand this sentence, but maybe you mean that the potential inconsitency between human and machine interpretation is a *feature* for Lisp, C, Pascal etc!? If so I'm really puzzled. > There is yet one more problem. The various levels of indentation encode > different things: the first level might indicate that it is part of a > function definition, the second that it is part of a FOR loop, etc. So on > any line, the leading whitespace may indicate all sorts of context-relevant > information. I don't understand why this is any different to e.g. ')))))' in Lisp. The closing ')' for DEFUN just looks the same as that for IF. > Yet the visual representation is not only identical between all of these, it > cannot even be displayed. I don't understand what you mean. Could you maybe give a concrete example of the information that can't be displayed? AFAICT you can have 'sexp'-movement, markup and highlighting commands all the same with whitespace delimited block structure. > > Is this worse than C, Pascal, etc.? I don't know. I'm pretty near certain it is better: In Pascal, C etc. by and large block structure delimitation is regulated in such a way that what has positive information content for the human reader/programmer (indentation) has zero to negative information content for the compiler and vice versa. This is a remarkably bad design (and apart from cognitive overhead obviously also causes errors). Python removes this significant problem, at as far as I'm aware no real cost and plenty of additional gain (less visual clutter, no waste of delimiter characters ('{','}') or introduction of keywords that will be sorely missed as user-definable names ('begin', 'end')). In Lisp the situtation isn't quite as bad, because although most of the parens are of course mere noise to a human reader, not all of them are and because of lisp's simple but malleable syntactic structure a straighforward replacement of parens with indendation would obviously result in unreadable code (fragmented over countless lines and mostly in past the 80th column :). So unlike C and Pascal where a fix would be relatively easy, you would need some more complicated scheme in the case of Lisp and I'm not at all sure it would be worth the hassle (especiallly given that efforts in other areas would likely yield much higher gains). Still, I'm sure you're familiar with the following quote (with which I most heartily agree): "[P]rograms must be written for people to read, and only incidentally for machines to execute." People can't "read" '))))))))'. > Worse than Lisp, Forth, or Smalltalk? Yes. Possibly, but certainly not due to the use of significant whitespace. 'as From kenrose at tfb.com Thu Oct 23 11:57:32 2003 From: kenrose at tfb.com (Ken Rose) Date: Thu, 23 Oct 2003 08:57:32 -0700 Subject: Python from Wise Guy's Viewpoint In-Reply-To: References: <_8Ekb.7543$pT1.318@twister.nyc.rr.com> Message-ID: <3F97FA6C.2020704@tfb.com> Pascal Costanza wrote: > Joachim Durchholz wrote: > >> Pascal Costanza wrote: >> >>> For example, static type systems are incompatible with dynamic >>> metaprogramming. This is objectively a reduction of expressive power, >>> because programs that don't allow for dynamic metaprogramming can't >>> be extended in certain ways at runtime, by definition. >> >> >> What is dynamic metaprogramming? > > > Writing programs that inspect and change themselves at runtime. Ah. I used to do that in assembler. I always felt like I was aiming a shotgun between my toes. When did self-modifying code get rehabilitated? - ken From jockc at mail.com Mon Oct 6 21:02:16 2003 From: jockc at mail.com (Jock Cooper) Date: 06 Oct 2003 18:02:16 -0700 Subject: Python syntax in Lisp and Scheme References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> <92c59a2c.0310031345.57d20631@posting.google.com> Message-ID: my-first-name.my-last-name at jpl.nasa.gov (Erann Gat) writes: > In article , David > Eppstein wrote: > > > In article > > > v>, > > my-first-name.my-last-name at jpl.nasa.gov (Erann Gat) wrote: > > > > > > : Here's another example of what you can do with macros in Lisp: > > > > > > > > : (with-collector collect > > > > : (do-file-lines (l some-file-name) > > > > : (if (some-property l) (collect l)))) > > > > > > > > : This returns a list of all the lines in a file that have some property. > > > > > > > > OK, that's _definitely_ just a filter: filter someproperty somefilename > > > > Perhaps throw in a fold if you are trying to abstract "collect". > > > > > > The net effect is a filter, but again, you need to stop thinking about the > > > "what" and start thinking about the "how", otherwise, as I said, there's > > > no reason to use anything other than machine language. > > > > Answer 1: literal translation into Python. The closest analogue of > > with-collector etc would be Python's simple generators (yield keyword) > > and do-with-file-lines is expressed in python with a for loop. So: > > > > def lines_with_some_property(some_file_name): > > for l in some_file_name: > > if some_property(l): > > yield l > > You left out the with-collector part. > > But it's true that my examples are less convincing given the existence of > yield (which I had forgotten about). But the point is that in pre-yield > Python you were stuck until the langauge designers got around to adding > it. > > I'll try to come up with a more convincing short example if I find some > free time today. > I'm afraid it's very hard to give any convincing examples of the utility of macros -- as long as you are sticking to trivial examples. On the other hand, you can't exactly post real world complex examples of how macros saved you time and LOC (we all have em) because reader's eyes would just glaze over. I think macros are just another one of CL's features that some most people just don't get until they actually use them. But here's a small one: I wrote about 60 lines worth of macro based code (including a few reader macros) that allows me to write things like: (with-dbconnection (sql-loop-in-rows "select col1, col2 from somewhere where something" :my-package row-var "pfx" ... ...some code... ...)) In the "some code" section, the result columns' values are accessed by #!pfx-colname (eg #!pfx-col1), or directly from row-var using #?pfx-colname (which returns the position). Also, error handling code can be automatically included by the macro code. How much time and effort (and possible bugs) has this saved me? Well at least 60+ lines or more of boilerplate every time I use this pattern.. Plus the expansions for #!colname include error checks/warnings etc. -- all hidden from view. Jock --- www.fractal-recursions.com From marcoxa at cs.nyu.edu Fri Oct 10 12:33:31 2003 From: marcoxa at cs.nyu.edu (Marco Antoniotti) Date: Fri, 10 Oct 2003 12:33:31 -0400 Subject: Python syntax in Lisp and Scheme In-Reply-To: <6Pfhb.190589$hE5.6425564@news1.tin.it> References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> <92c59a2c.0310031345.57d20631@posting.google.com> <8CVgb.8$KR3.1846@typhoon.nyu.edu> <6Pfhb.190589$hE5.6425564@news1.tin.it> Message-ID: Ok. At this point I feel the need to apoligize to everybody for my rants and I promise I will do my best to end this thread. I therefor utter the H-word and hopefully cause this thread to stop. Cheers -- marco From db3l at fitlinxx.com Fri Oct 24 12:14:42 2003 From: db3l at fitlinxx.com (David Bolen) Date: 24 Oct 2003 12:14:42 -0400 Subject: extending and embedding python with C# References: Message-ID: Bjorn Pettersen writes: > "Luke" wrote in > news:mailman.57.1066944193.702.python-list at python.org: > > > does anybody know anything about pythons ability to act as a wrapper > > for C#? I'm having a hard time finding out about this. Any clues are > > appreciated. > > Depends on what you want to do. There is no out-of-the-box solution... > yet. While still a work in progress: http://www.zope.org/Members/Brian/PythonNet might be worth looking at. It lets you access any managed .NET code from Python (so would include C# code), and even subclass managed objects with Python code. Embedding Python in managed code appears to be in the long term gameplan, but not really supported yet. It does run with it's own copy of the interpreter in the current preview. There was another similar project (KOBRA) but the URL I have for it (http://www.gadgil.net/DotNetWrapperForPython.htm) appears to be no longer valid. -- David From Raaijmakers, Vincent (IndSys, Thu Oct 23 17:57:11 2003 From: Raaijmakers, Vincent (IndSys, (Raaijmakers, Vincent (IndSys,) Date: Thu, 23 Oct 2003 16:57:11 -0500 Subject: Newbie in win32com: getters and setters Message-ID: <971323274247EB44B9A01D0A3B424C850265BD9D@FTWMLVEM02.e2k.ad.ge.com> Newbie question. Until now, I was able to work with all my COM objects until... the class I want to use doesn't contain methods (attributes) but just tables: class HelloWorld(DispatchBaseClass): """HelloWorld Interface""" CLSID = IID('{95A19265-0F7F-11D3-8150-00104B2A983D}') coclass_clsid = IID('{95A19266-0F7F-11D3-8150-00104B2A983D}') _prop_map_get_ = { "Hello": (8, 2, (3, 0), (), "Hello", None) ) _prop_map_put_ = { Hello": ((8, LCID, 4, 0),()) Now I'm lost. makepy didn't create the getters and setters, so how to get and set the values of Hello? So I tried: self.message = Dispatch("Messages.HelloWorld") ## works fine ##but now?? hello = self.message._prop_map_get_('Hello') ##So what is my value now? This looks so ugly and I don't even know what my value is. I expect just one value. Please guide me to some tips/tricks/documentations. Google search provided me only with huge Outlook examples. Thanks, Vincent From Mike at DeleteThis.Geary.com Fri Oct 24 11:44:29 2003 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Fri, 24 Oct 2003 08:44:29 -0700 Subject: 'while' in list comprehension? References: <20031022175924.GA10716@jsaul.de> <20031024125923.GC27460@jsaul.de> Message-ID: > > > wouldn't it be useful to have a 'while' conditional in addition to > > > 'if' in list comprehensions? > > > > > > foo = [] > > > for i in bar: > > > if len(i) == 0: > > > break > > > foo.append(i) > > > > > > would then turn into > > > > > > foo = [ i for i in bar while len(i)>0 ] > > > > while is simply not same as if: break! > > if executes once for each value of i, while indefinitely. > > If you translate back by current rule, which will not change, you get: > > > > foo = [] > > for i in bar: > > while len(i) >0: > > foo.append(i) > > I agree that 'while' cannot not just be considered a replacement > for 'if'. However, adding a 'while' conditional to list > comprehensions would very unlikely be misunderstood as another > (infinite) loop. Instead, I find the above 'while' example about > as intuitive as is the case with 'if'. It simply means that under > a certain condition the loop will be ended, which is just what > most people would probably expect. Here's an idea that might avoid this bit of confusion: foo = [ i for i in bar until len(i) == 0 ] That also makes the conditional test the same as used in the "if/break" form. Hmm... Would this mean that "until" would have to become a reserved word? Maybe not such a good idea if that's the case. -Mike From ianb at colorstudy.com Wed Oct 8 18:55:21 2003 From: ianb at colorstudy.com (Ian Bicking) Date: Wed, 8 Oct 2003 17:55:21 -0500 Subject: Could a single web framework popularize Python? In-Reply-To: Message-ID: <7EFACDB7-F9E2-11D7-B53E-000393C2D67E@colorstudy.com> On Wednesday, October 8, 2003, at 03:47 PM, Dave Benjamin wrote: > I guess it'd help to have a definition for what a web framework really > is. > When I was working with mod_python a lot, I definitely had some > infrastructure to build, but it wasn't massive. It was basically a > combination of the following: > > - database interface > - session handling > - cookie support (mostly already in the standard Python libs) > - templating > - publisher module (url->function mapping) > - assorted libraries (xml, imaging, etc.) A framework is the stuff piece that fits those all together (of course!) -- at least that fits the literal concept of "framework", and also works in practice pretty well. Typically a framework also provides some of those pieces too, but that's often a matter of convenience. E.g., Webware includes a PSP (template) plugin, but it is distinct from the framework and does not exclude other templates. Collecting (and when necessary building) components is a packaging issue -- but packaging is extremely important, especially when you are starting with Python web programming. > So, I'd say about half of the "framework" was available as Python > libraries > (either built-in or third-party), and the main gaping holes were > session > handling and templating. Since then, both of these are also available > as > third-party modules. > > Maybe Python doesn't have ONE_TRUE_FRAMEWORK because you have a choice > in a > lot of these different domains. Maybe that's a blessing in disguise. > It does > require that you think and actively make decisions about your > architecture. This diversity also keeps people from sharing. There is no significant sharing between people using different frameworks. With the number of frameworks out there that means that our efforts are very diluted. Really only one framework (Zope) has critical mass. And Zope 3 is reaching out the rest of the Python world -- it would be nice if we reached back. (Whoever "we" are...) But we don't have to eschew diversity to achieve interoperability. We do have to try, though, because it won't happen on its own, and it hasn't happened so far. -- Ian Bicking | ianb at colorstudy.com | http://blog.ianbicking.org From grelens at NOSPAMyahoo.NOTNEEDEDfr Thu Oct 23 04:58:31 2003 From: grelens at NOSPAMyahoo.NOTNEEDEDfr (GrelEns) Date: Thu, 23 Oct 2003 10:58:31 +0200 Subject: need advices... accessing a huge collection Message-ID: <3f9796c8$0$2774$626a54ce@news.free.fr> hello, having almost 1,000 tar.gz files in different directories (could not change that) and these archives contain over 1,000,000 text files. I would like to build a tool to access as quickly as possible any or sub-collection of these text files to serve them by http upon user request. does anyone have ideas on the good way to do it ? (i was thinking of a mapping in a dictionary whose keys would be filename, value - path to archive containing it, and extract all the files from a same archive at the same time) i also was wondering which is fastest : - upon each user request, re-building a dictionary from reading key/value from a file, - or on the first request building a hard-coded python dictionary and then importing it, - or maybe other suggestions (storing in a database...) ? thanx From eppstein at ics.uci.edu Mon Oct 20 14:15:12 2003 From: eppstein at ics.uci.edu (David Eppstein) Date: Mon, 20 Oct 2003 11:15:12 -0700 Subject: Python from Wise Guy's Viewpoint References: Message-ID: In article , Gerrit Holl wrote: > > I fail to see the lack of uniformity. "print" and "del" are statements, > > I think it is not uniform that print and del are statements rather than > functions, since they don't do control flow (just like exec). In all > three cases, I don't see why it is a statement. It's not obvious how to write e.g. del a[x] as a function, since the argument is an lvalue (position x of list a) rather than an rvalue (the item in position x of list a). Exec needs to be executed in the current scope, not the scope of another function call. Print, I agree, is something of a wart, but a useful one. -- David Eppstein http://www.ics.uci.edu/~eppstein/ Univ. of California, Irvine, School of Information & Computer Science From ville.spammehardvainio at spamtut.fi Thu Oct 30 04:41:28 2003 From: ville.spammehardvainio at spamtut.fi (Ville Vainio) Date: 30 Oct 2003 11:41:28 +0200 Subject: lightweight human-readable config? References: Message-ID: Maxim Khesin writes: > I want to have a config file with my python proggie, satisfying the > following requirements: I usually use plain old python modules for configuration. If you don't want to use 'import' and a name ending with .py, just exec the module in some namaspace. You can do "default value" behaviour by execing some default value module in the same namespace (often you might want to parse /etc/fooconfig before ~/.fooconfig). Then you just harvest the namespace for the config data. -- Ville Vainio http://www.students.tut.fi/~vainio24 From adf at hotmail.com Fri Oct 31 11:03:26 2003 From: adf at hotmail.com (afds) Date: Fri, 31 Oct 2003 16:03:26 GMT Subject: Regular Exp References: <%Ooob.124593$3f.59629@twister01.bloor.is.net.cable.rogers.com> Message-ID: Damn didn't see Harvey's message, ignore. > Ah, so you're saying my Regular Expression is correct? It just matches for > two digits? > > "Ben Finney" wrote in > message news:slrnbq49du.107.bignose-hates-spam at rose.localdomain.fake... > > On 31 Oct 2003 19:29:14 +1050, Ben Finney wrote: > > > You need to define one or more groups within the expression, grouping > > > what you want to access. Then use 'MatchObject.group()' to access one > > > > Or, as Harvey pointed out, use 'MatchObject.group(0)' to access the > > entire matching portion of the string, without needing to explicitly > > define groups. > > > > -- > > \ "Any sufficiently advanced bug is indistinguishable from a | > > `\ feature." -- Rich Kulawiec | > > _o__) | > > Ben Finney > > From wilkSPAM at OUTflibuste.net Mon Oct 6 05:45:46 2003 From: wilkSPAM at OUTflibuste.net (Wilk) Date: Mon, 06 Oct 2003 11:45:46 +0200 Subject: Webware vs. PHP - performance comparision!!! References: Message-ID: <87ekxqzol1.fsf@blakie.riol#flibuste.net> JZ writes: > I created an application based on Webware and Python. I was surprised > why it works so slowly. So I decided to check how fast are different > Python solutions against PHP. You compare litles script where speed doesn't matter finaly. Python web frameworks will win when you'll use them for big application where speed can be important. You'll cache in memory for example and it will become a lot faster than a php solution... I've rewrited a php-cgi application with twisted, the result was a lot faster, with less resources (mono-thread) for a code a lot cleaner... No doubt :-) ! I'll try to post an example... -- William Dode - http://flibuste.net From dcbecker at fuse.net Thu Oct 9 23:22:00 2003 From: dcbecker at fuse.net (beckers) Date: Thu, 9 Oct 2003 22:22:00 -0500 Subject: piglatin program Message-ID: <002001c38edd$aada84b0$0238900a@familyroom> How do you write a function to request a word from the keyboard and translate the word into piglatin? -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at ninereeds.fsnet.co.uk Sun Oct 26 18:09:53 2003 From: steve at ninereeds.fsnet.co.uk (Stephen Horne) Date: Sun, 26 Oct 2003 23:09:53 +0000 Subject: AI and cognitive psychology rant References: Message-ID: On Sun, 26 Oct 2003 20:05:20 -0500, Arthur wrote: >And there is no reason to believe that >the artificial tract will outdo the evolutionary tract, in disentangling >enabling and disabling capacities, which are inherently tangled - because, >in part, of the necessity for acting on the basis of information known to >be imperfect. I tend to agree, with the one proviso that an intelligent designer may be able to exploit options that evolution could not. -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From llafba_NOSPAM_ at gmx.net Thu Oct 16 10:58:33 2003 From: llafba_NOSPAM_ at gmx.net (Tom) Date: Thu, 16 Oct 2003 16:58:33 +0200 Subject: import error? In-Reply-To: References: <3F8E7466.C7BBE935@engcorp.com> Message-ID: Hi Peter, thanks for trying to help me. I can see that it can be confusing to read my posts, but it is so hard to explain a problem if you do not even know the source of the problem?! :-( But I appreciate your patience. I didn't use the interactive interpreter. I don't now why it says and "?". I just use the window (python shell) for output. My code is strctured like this: My main program does not have any classes or functions. It is supposed to run all the way through and calls different modules for the different tasks. I did that because I didn't want to overload the main program. After every step (which usually means after calling a module) I have an output in the shell window. When I said that I include stuff at the beginning I meant at the total beginning of my main programm and at the total beginning of each module that I use (before defining the class and function). Of course I only include what I also need. I use this one module that later causes my problems in the main program for the first time. It works fine there. Than I can start my business which means that I call all the different modules depending on the action that is neccessary. Sometimes it is necessary to use this specific module (that I already used before) in one of the other modules that I just called from my main program. Is that maybe a problem, that I can't include the module in the main program and in a module called by the main program? I import everything that is neccessary it in both! I also tried this: I made an exact copy of my module and just renamed it. Using the original module in the main program and the renamed module in the other module that I call from my main program. That worked fine. Maybe because they were different modules and python doesn't like it if I call the same module? But what still irritates me is the fact that everything also works fine if I write the "from bla import *" line directly before I refere to the function in that module. I don't like this but I meantion it, because I think it is strange that it works then. Well, I could use this copied and renamed module, but because it consists exactly the same code and just changed the filename (all the class and function names are still the same), I don't really see the necessity. Maybe it is one of the Thursday only problems! :-) But I would love to find the find out what's wrong :-) I don't know if this helps or just confuses more. :-) I hope not. :-) Thank you very much for all your help anyway. Regards, Tom From aleax at aleax.it Tue Oct 28 07:51:59 2003 From: aleax at aleax.it (Alex Martelli) Date: Tue, 28 Oct 2003 12:51:59 GMT Subject: PEP 289: Generator Expressions (please comment) References: Message-ID: Skip Montanaro wrote: > > Alex> Let's see: today, I could code: sum([x*x for x in roots]) In > 2.4, Alex> I will be able to code instead: sum(x*x for x in roots) > with some > Alex> performance benefits. Could you please explain how using the > Alex> lighter-weight simple parentheses rather than today's somewhat > Alex> goofy ([ ... ]) bracketing "generally decreases readability"...? > > How is using [...] to construct a list "somewhat goofy"? For list Juxtaposing round parentheses and square brackets because that's the only way to feed a 'comprehension' to a function or type is "somewhat goofy" in my opinion mainly because ([ and ]) look bad to me. I'll be tickled pink when I can omit those brackets (getting a small speed-up by so doing will be just a little extra delight:-). > comprehensions using square brackets to surround the expression make sense > to me. If they hadn't been done that way, you might be looking at using > them to distinguish generator expressions from bracket-less list > comprehensions. ;-) When list comprehensions were the only way you could express such a sequence inline, the brackets were understandably inevitable. Now, or to be more precise when 2.4 comes, I think I'll prefer to lose a modicum of concision and write list(x*x for x in foo if x>bar) rather than [x*x for x in foo if x>bar] for reasons of uniformity that I have already explained in another post. Alex From brian094 at sympatico.ca Fri Oct 10 15:57:13 2003 From: brian094 at sympatico.ca (Brian Alexander) Date: Fri, 10 Oct 2003 15:57:13 -0400 Subject: preserve exception within try .. finally Message-ID: <3F870F19.20502@sympatico.ca> Hello; I'm curious to know how people preserve exceptions that arise in a try .. finally block. Consider this example: try: getResource() doSomething() finally: alwaysFreeResource() If an exception occurs in doSomething(), the resource is freed anyway -- which is good. How can I keep the exception 'raised' for another try-finally/except to deal with? Does this problem reflect an error in the way I am approaching the problem? Many thanks, Brian. From eppstein at ics.uci.edu Thu Oct 16 14:43:06 2003 From: eppstein at ics.uci.edu (David Eppstein) Date: Thu, 16 Oct 2003 11:43:06 -0700 Subject: Python syntax in Lisp and Scheme References: <8CVgb.8$KR3.1846@typhoon.nyu.edu> <20031014050046.GM1454@mapcar.org> <87fzhtlvni.fsf@thalassa.informatimago.com> Message-ID: In article , Joe Marshall wrote: > Alexander Schmolck writes: > > > Did it occur to you that people maybe use python not so much because they > > are > > retards but because it's vastly more effective than CL at the tasks they > > currently need to perform? Should I send you a few hundred lines of my > > python > > code so that you can try translating them into CL? > > Sounds like an interesting challenge... For simple use of built-in libraries, http://online.effbot.org/2003_08_01_archive.htm#troll looks like a good test case. -- David Eppstein http://www.ics.uci.edu/~eppstein/ Univ. of California, Irvine, School of Information & Computer Science From james.anderson at setf.de Sun Oct 19 12:42:04 2003 From: james.anderson at setf.de (james anderson) Date: Sun, 19 Oct 2003 18:42:04 +0200 Subject: Why don't people like lisp? References: <1A8kb.67406$pv6.3464@twister.nyc.rr.com> <874qy5ear5.fsf@bird.agharta.de> Message-ID: <3F92BE48.799F618B@setf.de> Terry Reedy wrote: > > ... > Lisp-aware editors do not solve the problem of reading Lisp code > embedded in text, as with OnLisp formatted .ps or .pdf. well, to the extent that they indent consistently, they do. one trains ones eye to ignore the parentheses. perhaps one may have misinterpretated the resistance to tyrannical indentation. one very effective way to read lisp attends to the indentation and ignores the parentheses. the compiler does not do this, but the eye does. different eyes are trained differently, but the principle remains. for instance, if we take m.kowalczyk's example. a competent lisp programmer could just as readily interpret the text below, as interpret the text with parentheses. the parenthese are redundant information which aids disambiguation - eg where numerous forms are on a single line, and corrects errors, but fairly early on one no longer "reads" them. defun mostn fn lst if null lst values nil nil let result list car lst max funcall fn car lst dolist obj cdr lst let score funcall fn obj cond > score max setq max score result list obj = score max push obj result values nreverse result max practice. one suggestion would be to find an old mac and download a copy of mcl. if you can get along with a mac, it really is the easiest of the lisps to break in with. ... From news at yebu.de Wed Oct 8 05:32:20 2003 From: news at yebu.de (Karl Scalet) Date: Wed, 08 Oct 2003 11:32:20 +0200 Subject: print is not a function Message-ID: Hi, quite often there is a need to just print out the items of a list. [ prt(x) for x in my_list ] that would be nice, except prt() does not exist, and print is a statement not a function, hence cannot replace prt as of above. I don't like to write d def prt(x): print x beforehand and any lambda construct would not be so handy. It should be a short one-liner. Any ideas? Karl From aleax at aleax.it Sun Oct 19 15:09:04 2003 From: aleax at aleax.it (Alex Martelli) Date: Sun, 19 Oct 2003 19:09:04 GMT Subject: Python from Wise Guy's Viewpoint References: <2hvfqlmkcd.fsf@vserver.cs.uit.no> Message-ID: Frode Vatvedt Fjeld wrote: ... > Excuse my ignorance wrt. to Python, but to me this seems to imply that > one of these statements about functions in Python are true: > > 1. Function names (strings) are resolved (looked up in the > namespace) each time a function is called. > > 2. You can't really undefine a function such that existing calls to > the function will be affected. > > Is this (i.e. one of these) correct? Both, depending on how you define "existing call". A "call" that IS in fact existing, that is, pending on the stack, will NOT in any way be "affected"; e.g.: def foo(): print 'foo, before' remove_foo() print 'foo, after' def remove_foo(): print 'rmf, before' del foo print 'rmf, after' the EXISTING call to foo() will NOT be "affected" by the "del foo" that happens right in the middle of it, since there is no further attempt to look up the name "foo" in the rest of that call's progress. But any _further_ lookup is indeed affected, since the name just isn't bound to the function object any more. Note that other references to the function object may have been stashed away in many other places (by other names, in a list, in a dict, ...), so it may still be quite possible to call that function object -- just not to look up its name in the scope where it was earlier defined, once it has been undefined. As for your worries elsewhere expressed that name lookup may impose excessive overhead, in Python we like to MEASURE performance issues rather than just reason about them "abstractly"; which is why Python comes with a handy timeit.py script to time a code snippet accurately. So, on my 30-months-old creaky main box (I keep mentioning its venerable age in the hope Santa will notice...:-)...: [alex at lancelot ext]$ timeit.py -c -s'def foo():pass' 'foo' 10000000 loops, best of 3: 0.143 usec per loop [alex at lancelot ext]$ timeit.py -c -s'def foo():return' 'foo()' 1000000 loops, best of 3: 0.54 usec per loop So: a name lookup takes about 140 nanoseconds; a name lookup plus a call of the simplest possible function -- one that just returns at once -- about 540 nanoseconds. I.e., the call itself plus the return take about 400 nanoseconds _in the simplest possible case_; the lookup adds a further 140 nanoseconds, accounting for about 25% of the overall lookup-call-return pure overhead. Yes, managing less than 2 million function calls a second, albeit on an old machine, is NOT good enough for some applications (although, for many of practical importance, it already is). But the need for speed is exactly the reason optimizing compilers exist -- for those times in which you need MANY more millions of function calls per second. Currently, the best optimizing compiler for Python is Psyco, the "specializing compiler" by Armin Rigo. Unfortunately, it currently only only supports Intel-386-and-compatible CPU's -- so I can use it on my old AMD Athlon, but not, e.g., on my tiny Palmtop, whose little CPU is an "ARM" (Intel-made these days I believe, but not 386-compatible) [ for plans by Armin, and many others of us, on how to fix that in the reasonably near future, see http://codespeak.net/pypy/ ] Anyway, here's psyco in action on the issue in question: import time import psyco def non_compiled(name): def foo(): return start = time.clock() for x in xrange(10*1000*1000): foo() stend = time.clock() print '%s %.2f' % (name, stend-start) compiled = psyco.proxy(non_compiled) non_compiled('noncomp') compiled('psycomp') Running this on the same good old machine produces: [alex at lancelot ext]$ python2.3 calfoo.py noncomp 5.93 psycomp 0.13 The NON-compiled 10 million calls took an average of 593 nanoseconds per call -- roughly the already-measured 540 nanoseconds for the call itself, plus about 50 nanoseconds for each leg of the loop's overhead. But, as you can see, Psyco has no trouble optimizing that by over 45 times -- to about 80 million function calls per second, which _is_ good enough for many more applications than the original less-than-2 million function calls per second was. Psyco entirely respects Python's semantics, but its speed-ups take particular good advantage of the "specialized" cases in which the possibilities for extremely dynamic behavior are not, in fact, being used in a given function that's on the bottleneck of your application (Psyco can also automatically use a profiler to find out about that bottleneck, if you want -- here, I used the finer-grained approach of having it compile ["build a compiled proxy for"] just one function in order to be able to show the speed-ups it was giving). Oh, BTW, you'll notice I explicitly ran that little test with python2.3 -- that was to ensure I was using the OLD release of psyco, 1.0; as my default Python I use the current CVS snapshot, and on that one I have installed psyco 1.1, which does more optimizations and in particular _inlines function calls_ under propitious conditions -- therefore, the fact that running just "python calfoo.py" would have shown a speed-up of _120_ (rather than just 45) would have been "cheating", a bit, as it's not measuring any more anything related to name lookup and function call overhead. That's a common problem with optimizing compilers: once they get smart enough they may "optimize away" the very construct whose optimization you were trying to check with a sufficiently small benchmark. I remember when the whole "SPEC" suite of benchmarks was made obsolete at a stroke by one advance in compiler optimization techniques, for example:-). Anyway, if your main interest is in having your applications run fast, rather than in studying optimization yields on specific constructs in various circumstances, be sure to get the current Psyco, 1.1.1, to go with the current Python, 2.3.2 (the pre-alpha Python 2.4a0 is recommended only to those who want to help with Python's development, including testing -- throughout at least 2004 you can count on 2.3.something, NOT 2.4, being the production, _stable_ version of Python, recommended to all). Alex From fumanchu at amor.org Tue Oct 14 17:08:54 2003 From: fumanchu at amor.org (Robert Brewer) Date: Tue, 14 Oct 2003 14:08:54 -0700 Subject: AI and cognitive psychology rant Message-ID: > Maybe we're having some terminology issue...? For example, I consider > statistical techniques "brute force"; it's not meant as pejorative -- > they're techniques that WORK, as long as you can feed enough good data > to the system for the statistics to bite. A non-brute-force model of > natural language might try to "understand" some part of the real world > that an utterance is about -- build a semantic model, that is -- and > use the model to draw some part of the hypotheses for further pre- > diction or processing; a purely statistical model just sees sequences of > symbols (words) in (e.g.) a Hidden Markov Model from which it takes > all predictions -- no understanding, no semantic modeling. A non-bf > bridge playing program might have concepts (abstractions) such as "a > finesse", "a squeeze", "drawing trumps", "cross-ruffing", etc, and > match those general patterns to the specific distribution of cards to > guide play; GIB just has a deterministic double-dummy engine > and guides play by montecarlo samples of possible distributions > for the two unseen hands -- no concepts, no abstractions. I've always understood the difference from two separate points of view. On one level, you must have a device, a machine, which is built by intelligent humans. There's no getting around this, but it's easy for even the "emergent intelligence" crowd to get side-tracked by people who think that, just because the *substrate* has been designed, that therefore the entire beastie is nothing more than an expert system. However, there are systems built which do possess the concepts/abstractions which you mention. A fantastic example is NOMAD/Darwin, which is a real attempt at hooking learning software to a physical substrate: the feedback is physical, not virtual. cf. http://www.nsi.edu/public/news/pr20000000.php I cornered Jim Snook, gosh, two years ago now, and sat riveted for an hour, listening to him outline everything I've ever wanted to put into such a system (but haven't had the means; it's a purely academic hobby of mine)--their approach seems spot-on to me. Yes, any AI system must be realized in hardware at some point. I think the emergent-properties folks see something fundamentally different than the expert-systems crowd: that at some point, AI builders must take their hands off the reins and let a well-designed system design itself for a while. Not sure what this has to do with Python. :) Robert Brewer MIS Amor Ministries fumanchu at amor.org From bp at computastore.com Fri Oct 17 10:39:01 2003 From: bp at computastore.com (Brian Patterson) Date: Fri, 17 Oct 2003 14:39:01 +0000 (UTC) Subject: Trivial performance questions References: <7h3ad80m2ho.fsf@pc150.maths.bris.ac.uk> Message-ID: >> I appreciate that these are trivial in the extreme, but I seem to be >> writing dozens of them, and I may as well use the right one and >> squeeze what performance I can. > This is an unhelpful attitude. You're writing in Python after all! I have never considered using the fastest available option to be an unhelpful attitude, especially when it does not impact on readability. It occurred to me that someone more knowledgable might know whether there was a 'right' answer to these trivial questions. However, it appears not. Sorry for wasting your time :( Thanks for the tip on the getattr default. This is much cleaner to read, almost certainly quicker, and will serve the purpose well. I had convinced myself that it was not available in 2.1.3. From amoroso at mclink.it Mon Oct 13 13:03:18 2003 From: amoroso at mclink.it (Paolo Amoroso) Date: Mon, 13 Oct 2003 19:03:18 +0200 Subject: Python syntax in Lisp and Scheme References: Message-ID: <873cdxvzmx.fsf@plato.moon.paoloamoroso.it> [following up to comp.lang.python and comp.lang.lisp] Alex Martelli writes: > necessarily yield optimal productivity in programming. What > language design trade-offs WILL yield such optimal productivity, > *DEPENDING* on the populations and tasks involved, is the crux > of this useless and wearisome debate (wearisome and useless, in > good part, because many, all it seems to me on the lisp side, > appear to refuse to admit that there ARE trade-offs and such > dependencies on tasks and populations). I agree (Lisp side). > The only example of 'power' I've seen (besides the infamous > with-condition-maintained example) are such trifles as debugging- > output macros that may get compiled out when a global flag to > disable debugging is set -- exactly the kind of micro-optimization If you are interested in advanced uses of Common Lisp macros, you may have a look at Paul Graham's book "On Lisp", which is available for download at his site. Other examples are probably in the Screamer system by Jeffrey Mark Siskind. Paolo -- Paolo Amoroso From Norman.Shelley at motorola.com Fri Oct 10 19:04:41 2003 From: Norman.Shelley at motorola.com (Norman Shelley) Date: Fri, 10 Oct 2003 16:04:41 -0700 Subject: ?Method to list out map object's keys on KeyError Message-ID: <3F873B09.3774ABCE@motorola.com> Is there a way to get at the object one is trying to access with a key to list out all the possible keys? See the except clause below. #!/usr/bin/env python2.2 from inspect import * import sys program = """ abc = {} print "abc:", abc print abc['def'] """ gdct = globals() ldct = {} try: exec program in gdct, ldct except KeyError: # Some way to get at the abc object to list out all its keys # e.g. abc.keys() Of course program could have any map name # that would fail and I would like that object's keys raise From adalke at mindspring.com Wed Oct 22 03:50:55 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Wed, 22 Oct 2003 07:50:55 GMT Subject: Why don't people like lisp? References: <8Nnlb.619$I04.380@newsread4.news.pas.earthlink.net> Message-ID: Peter Seibel: > Okay, here's a Common Lisp version. Because Lisp functions take either > keyword or positional arguments, I choose to make the generated > functions use keyword arguments. But the variables are gathered in the > right order, so take out the '&key' below to use positional arguments: Cool code. I like that it identifies some of the error locations. > * (funcall (compile-rpn "a b +") :a "foo" :b 2) > Error: `"foo"' is not of the expected type `NUMBER' My Python code reports a line number for this. I figured it would be harder for simple Lisp code to do the same. But that's because I'm cheating; the Python stack trace normally reports the line number so I get most of it for free. I suspect it would be more complicated if the spec said to report the line number *and* character position of the operator which failed. (Not all that hard though; I can use a new object class Add: def __init__(self, lineno, charpos): self.lineno = lineno self.charpos = charpos def __call__(self, left, right): try: return left + right except: ... report the error location ... and make the code look like Mult(4, 2)(3.0, Add(1, 30)(a, 1) + 9.8) but if I'm making a native Python function which doesn't manipulate its own stack then it's probably for the speed, and the above will be slow.) In my reply to Erann Gat I noted that his eval approach might exclude the possibility of using names like 'a)' as identifiers. (I don't know if it does, because I don't know enough Lisp.) My AST solution could easily be changed to support that case, as well as variable like ";;b" and "#c" and ":d:". I'll ask the same of you. Does your code require that the RPN names also be valid Lisp tokens? If so, what happens if it isn't? (Looking at it, the key line is > ((not tok) (return `(lambda (&key ,@(nreverse variables)) (prog1 , at stack)))) but I don't know what @() does nor what happens if a "strange" value is used as the list of keywords) > And for grins here's the x86 machine code generated for the first function: I was never any good at Intel assembly, and I thankfully haven't touched it in about 15 years. I was trying to figure out if it optimized the additions into 15**a, but I could see neither the sequence 1, 2, 3, 4, 5 nor the value 15 (octal 17, hex F) anywhere in the code. Pointers? Andrew dalke at dalkescientific.com From hungjunglu at yahoo.com Thu Oct 23 10:19:16 2003 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 23 Oct 2003 07:19:16 -0700 Subject: Python equivalent for perl's "next"-statement? References: <5A8F954A-0483-11D8-A499-00039315E356@gmx.de> <3F96B3EE.6000200@skynet.be> <87ekx5rvk2.fsf@pobox.com> Message-ID: <8ef9bea6.0310230619.5761634a@posting.google.com> jjl at pobox.com (John J. Lee) wrote in message news:<87ekx5rvk2.fsf at pobox.com>... > def next_foo(foo): > return foo**2 > > while condition(foo): > ... > if hmm(): > foo = next_foo() > continue > ... > if hmph(): break > ... > if hrm(): > foo = next_foo() > continue > .... > foo = next_foo() > > Yuck! Exception handling is often used for this purpose. (Common practice in Python, believe it or not.) class Next(Exception): pass while condition(foo): try: ... if hmm(): raise Next ... if hmph(): break ... if hrm(): raise Next ... except Next: pass foo = foo**2 regards, Hung Jung From jjl at pobox.com Sat Oct 11 07:50:31 2003 From: jjl at pobox.com (John J. Lee) Date: 11 Oct 2003 12:50:31 +0100 Subject: Jython, GILs and object locking. References: Message-ID: <87ad886liw.fsf@pobox.com> Michael Chermside writes: [...] > But if you DO have a task which is compute bound, and it's > the only task running on the machine, and the machine has > multiple processors, and if you particularly care to have > this task run faster, well then Python is not up to the > job because of the GIL. Of course, you should look into [...] That's still too strong, even given your proviso about using C++. First, the code you're already using may already parallelize well enough thanks to C code releasing the GIL. Second, using something like POSH, or splitting up your threads into bunches, in separate processes, also works. Not perfect, of course. John From borcis at users.ch Sun Oct 19 10:33:28 2003 From: borcis at users.ch (Borcis) Date: Sun, 19 Oct 2003 16:33:28 +0200 Subject: Why don't people like lisp? References: Message-ID: <3F92A0B8.8080002@users.ch> Francis Avila wrote: > Procedural, imperative programming is > simply a paradigm that more closely matches the ordinary way of thinking > (ordinary = in non-programming, non-computing spheres of human endevor) than > functional programming. There is no such thing as "the" ordinary way of thinking, except in the mind of people who have not enquired enough about the ways of thinking of other people to discover this "astonishing" fact - but I will concede that failure to enquire is more likely to occur among adepts of procedural and imperative authority (authority - not thinking). This said, I find it a bit ridiculous to oppose lisp and python along that scale; compared to logic programming (eg Prolog), or even to reverse-polish stack-based syntax like in PostScript - and given that both python and lisp are dynamic and don't require types declarations - programming in python and programming in lisp feel very similar (except for a few things you can do in lisp but not in python). ... > The same reason why programmers call lisp "mind-expanding" and "the latin of > programming languages" is the very same reason why they are reluctant to > learn it--its different, and for many also hard to get used to. Everybody finds one's own mother's style of cooking more palatable, but that's no excuse to reflect on things as if everybody had the same mother. > Python doesn't try (too) hard to change the ordinary manner of thinking, > just to be as transparent as possible. I guess in that sense it encourages a > degree of mental sloth, but the objective is executable pseudocode. Python and lisp imho compete for the status of easiest language to program in; python differs from lisp in that in leaves you less freedom to shoot yourself in the foot with meta-programming (having access to code as an easy data structure, something Prolog has too). And python also has for itself a free reference implementation running on all platforms, with an extensive standard lib (that's why I use it rather than lisp). > Lisp > counters that thinking the lisp way may be harder, but the power it grants > is out of all proportion to the relatively meager investment of mental > energy required--naturally, it's hard to convince someone of that if they > don't actually _use_ it first, and in the end some will probably still think > it isn't worth the trouble. It will take very significant and deep cultural > and intellectual changes before lisp is ever an overwhelmingly dominant > language paradigm. The real issue is what language gets taught to beginners and what language is required by employers, and such choices are mostly historical accidents of fad and fashion. > That is, when it becomes more natural to think of > cake-making as > > UD: things > Gxyz: x is baked at y degrees for z minutes. > Hx: x is a cake. > Ix: x is batter. > > For all x, ( (Ix & Gx(350)(45)) > Hx ) > > (i.e. "Everything that's a batter and put into a 350 degree oven for 45 > minutes is a cake") > > ...instead of... > > 1. Heat the oven to 350 degrees. > 2. Place batter in oven. > 3. Bake 45 minutes > 4. Remove cake from oven. > > (i.e. "To make a cake, bake batter in a 350 degree oven for 45 minutes") This is not serious. Write down a piece of idiomatic python, and I'm sure some lisper will show you how well lisp can mimic that. > > ...then lisp will take over the universe. Never mind that the symbolic > logic version has more precision. Lisp isn't symbolic logic. Symbolic logic isn't the example you gave. From usenet at soraia.com Wed Oct 29 16:02:08 2003 From: usenet at soraia.com (Joe Francia) Date: Wed, 29 Oct 2003 21:02:08 GMT Subject: GUI-based build system In-Reply-To: <8ef9bea6.0310291030.1e897e46@posting.google.com> References: <8ef9bea6.0310291030.1e897e46@posting.google.com> Message-ID: Hung Jung Lu wrote: > Hi, > > Does anyone know whether there is any generic GUI-based build system > around? (Python-based would be great. Also, for now I am only looking > for Windows OS.) By "build system" I mean something similar the > "make/makefile" system, but somewhat more > generic/powerful/flexible/higher-level/etc, so that if you have a > sequence (maybe even some simple conditional branches and loops) of > system tasks to perform, you can more easily visualize the steps, and > perhaps resume from some middle point. If it has e-mail capability to > send out final status, even better. :) If it can work both > interactively and a an fire-and-forget stand-alone, even better. :) > > (I don't mind writing simple wrappers to each individual tasks to > produce standardized responses for the build system.) > > My guess is that there are many utilities like that out there already. > Another guess is that some of them use XML for task specification. One > more guess is that some of them are free. But, I could be wrong. :) > You may want to look at Ant. ( http://ant.apache.org ) Ant is a free, Java-based make tool (probably usable from Jython), but "without make's wrinkles". It can do anything Java can do, such as send an email at the end of the process. It uses XML as the project makefiles. It shouldn't be too much work to wrap Ant in a nice wxPython (or whatever) GUI (especially if you can use Jython). You may also want to look at Eclipse ( http://www.eclipse.org ), a Java-based (but highly extensible) IDE which uses Ant for its build process. Peace, Joe From joachim.durchholz at web.de Mon Oct 20 10:20:59 2003 From: joachim.durchholz at web.de (Joachim Durchholz) Date: Mon, 20 Oct 2003 16:20:59 +0200 Subject: Python from Wise Guy's Viewpoint In-Reply-To: <3F93D20A.B9D0C30D@setf.de> References: <3F93D20A.B9D0C30D@setf.de> Message-ID: james anderson wrote: > Joachim Durchholz wrote: > > how about formulating some examples in some language which is adequate to > express them? perhaps somewhat more concretely than the allusions in your > earlier message, in which you suggest some problem domains and some > amorphously difficult decisions, but despite several rereadings, never > concretly indicate what does not "work". > > what does "different directions" mean? "glue code"? "asymmetry"? a "base > class"? a "module"? an "orthogonal extension"? > > what is the distinction between "dynamic dispatch" and "parametric polymorphism". > > if not in the context of clos, then, well, in english. Sorry - this would go beyond the scope of a newsgroup discussion. It would take me several hours to get this all sorted out, written down, and worded so that it's generally understandable. And, frankly, I already have spent too much time on this thread. I do intend to writ it all up and publish it on a WWW site - in my copious spare time... :-( Let me assure you that all these nebulous terms are due to time constraints, not due to fuzzy reasoning. Sorry if this all sounds like a lame excuse (actually it is). And sorry to leave you with lots of fuzzy allusions and no concrete data. Others may be willing to fill in more details. >>I'd really like to see a Lisp dialect that valued reliability over raw >>expressive power. But I fear this isn't very high on the agenda of the >>Lisp community. Besides, it would be difficult to do that - Lisp offers >>no protection against peeking at internals and setting up all that >>unsafe-but-powerful stuff. > > what are "internals", what is "protection"? No way to define an opaque type. AFAIK, modern Lisps allow user-defined types, but they offer no way to protect them against inspecting their internals. I'd prefer to have at least a grain of information hiding... Regards, Jo From gherron at islandtraining.com Fri Oct 31 11:42:01 2003 From: gherron at islandtraining.com (Gary Herron) Date: Fri, 31 Oct 2003 08:42:01 -0800 Subject: Access the methods of a class In-Reply-To: <1225qv0ehamjpk98bk4hush1tbp6eu3kov@4ax.com> References: <1225qv0ehamjpk98bk4hush1tbp6eu3kov@4ax.com> Message-ID: <200310310842.01825.gherron@islandtraining.com> On Friday 31 October 2003 08:10 am, Fernando Rodriguez wrote: > Hi, > > I have a base class with a 'sanity-check' method. This method should > iterate through all the methods and check if they are all 'thunks' (zero > parameter functions, well actually, 1 parameter: self). > > How can I access the list of methods of a given object? BTW, this class > will be inherited from, so it should work with hte derived classes too. > > How can I check the number of parameters of a given function object? > > TIA O:-) > > PS Any pointers to a python reflection tutorial, would also be appreciated. The inspect module should provide everything you need here. >From the manual: inspect -- Inspect live objects New in version 2.1. The inspect module provides several useful functions to help get information about live objects such as modules, classes, methods, functions, tracebacks, frame objects, and code objects. For example, it can help you examine the contents of a class, retrieve the source code of a method, extract and format the argument list for a function, or get all the information you need to display a detailed traceback. Gary Herron From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Thu Oct 2 16:09:53 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Thu, 02 Oct 2003 22:09:53 +0200 Subject: Using TCP/IP In-Reply-To: References: <3F7B100D.5260350C@engcorp.com> <3f7c7f0b$0$58714$e4fe514c@news.xs4all.nl> Message-ID: <3f7c8610$0$58698$e4fe514c@news.xs4all.nl> jblazi wrote: > First the program will work in the class room. And then, some time later, > it should work over the internet. That would impress the pupils. Wouldn't it impress them even more that you can actually achieve this with only about 3 or 4 extra lines of code? ;-) Using Pyro that is. See the 'minimalist' example: http://pyro.sourceforge.net/pyro-manual/8-example.html --Irmen de Jong From BjornPettersen at fairisaac.com Mon Oct 20 07:36:51 2003 From: BjornPettersen at fairisaac.com (Pettersen, Bjorn S) Date: Mon, 20 Oct 2003 06:36:51 -0500 Subject: Python from Wise Guy's Viewpoint Message-ID: <1DAECE9E8F34E04AA0E5699AF7D9FF09085DAA59@stpmsg00.corp.fairisaac.com> > From: Alex Martelli [mailto:aleax at aleax.it] > > Hannu Kankaanp?? wrote: > > > mike420 at ziplip.com wrote in message > > news:... > >> THE BAD: > >> > >> 1. f(x,y,z) sucks. f x y z would be much easier to type (see > >> Haskell) 90% of the code is function applictions. Why not make > >> it convenient? > > > > Python has been designed to attract non-programmers as well. Don't > > you think f(x,y,z) resembles the mathematical notation of passing > > a function some parameters, instead of "f x y z"? > > Yes -- which is exactly why many non-programmers would prefer the > parentheses-less notation -- with more obvious names of course;-). > E.g.: > emitwarning URGENT "meltdown imminent!!!" > DOES look nicer to non-programmers than > emitwarning(URGENT, "meltdown imminent!!!") > > Indeed, such languages as Visual Basic and Ruby do allow calling > without parentheses, no doubt because of this "nice look" thing. > > However, as I explained elsewhere, there are probably-insuperable > language-design problems in merging "implicit call" and > first-classness > of all names unless you basically go all the way following Haskell > with implicit currying and non-strictness (and assignments should > probably go away too, else how to distinguish between assigning to > x a nullary function f itself, and assigning to x the result of > _calling_ f without arguments...?). Not to mention: > > emitwarning URGENT highlight "meltdown imminent!!!" > > where the need to disambiguate between highlight being the second > of three parameters to emitwarning, or a function called with > the string as its sole parameter and its RESULT being the second > of two parameters to emitwarning, [...] You could of course do it the Lisp way and quote the `'#',: out of everything :-) [*sigh*, I promised myself I wouldn't contribute to the Lisp/Python 'debate'...] [..] > My own reasons for the choice of Python over Ruby are quite > nuanced and complicated, actually (those for either of them > over Haskell have much to do with pragmatism over purity:-). [..] Mine are pretty simple, I couldn't stand looking at code calling method 'colour' when I was calling 'color' . (yes, I am kidding -- I own the Pickaxe book and use Ruby for a number of things. I'm also not pragmatic enough to choose not to use a language... ;/) -- bjorn From CousinStanley at hotmail.com Wed Oct 8 18:26:16 2003 From: CousinStanley at hotmail.com (Cousin Stanley) Date: Wed, 8 Oct 2003 15:26:16 -0700 Subject: splitting a list into n groups References: Message-ID: | .... | More test cases | .... Peter .... I use Outlook Express with the Quote-Fix add on for reading news groups and got quite a chuckle when I saw how your test-case code showed up here .... http://fastq.com/~sckitching/Python/python_lol.png [ 2 KB ] -- Cousin Stanley Human Being Phoenix, Arizona From http Tue Oct 14 11:46:53 2003 From: http (Paul Rubin) Date: 14 Oct 2003 08:46:53 -0700 Subject: Read long int from binary file References: Message-ID: <7xvfqrakk2.fsf@ruckus.brouhaha.com> Enrico Morelli writes: > I cannot know the format (little or big endian) and I have to perform the > properly 4 byte reverse order swapping. If you don't know the endianness, you can't tell whether to swap or not. From peter at engcorp.com Wed Oct 29 18:33:38 2003 From: peter at engcorp.com (Peter Hansen) Date: Wed, 29 Oct 2003 18:33:38 -0500 Subject: coverage.py can't find source file References: Message-ID: <3FA04E52.E07A6DB2@engcorp.com> Richard Wesley wrote: > > I am using coverage.py to run my unit test suite to check for missing > tests. It mostly works, but for some mysterious reason, some of the > files can't be found because they are not in the same directory as > configure.py and unit_test.py. But only SOME of them. > > Anyone have any ideas? Yes, but probably not the right one. :-) Anyway, is it possible that actually *none* of those files are being found, but instead a bunch of leftover .pyc files in the current directory (or any other directory that Python can find) are being found? .pyc files are as good as .py files to Python, if it can't find the latter. Also, are you aware of how sys.path is used? If you check each directory, starting with the directory in which the main script is found (and which shows up as '' in sys.path, usually at the start) for the files, you should be able to find them. You can also try importing one of the files that works, then do 'print module.__file__' where module is replaced by the right name, and see where the files that do work are actually coming from. It might not be where you think it is. Finally, try learning how to use "import pdb; pdb.set_trace()" which starts an interactive debugger session in the context where it executes. Putting this just ahead of the failing imports would let you interactively debug the problem. -Peter From emile at fenx.com Tue Oct 14 09:39:05 2003 From: emile at fenx.com (Emile van Sebille) Date: Tue, 14 Oct 2003 06:39:05 -0700 Subject: how to mutate a tuple? References: Message-ID: Carlo v. Dango asks: > But how do I do this if I only at runtime know the size of the tuple? I > wish I could pass around lists instead.. that would be so much easier, but > I'm passing "*args" and "**kwargs" around so I'm not really the one > deciding the use of tuples or lists ;) Convert *args to a list: args = list(args) kwargs should be a dict anyway, not a tuple. Emile van Sebille emile at fenx.com From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Thu Oct 9 15:34:34 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Thu, 09 Oct 2003 21:34:34 +0200 Subject: CGI upload In-Reply-To: References: Message-ID: <3f85b849$0$58705$e4fe514c@news.xs4all.nl> Thomas Williams wrote: > Can anyone tell me where to find info, on writing a > script that handles a file from a CGI form? It's in the manual, about the cgi module: http://www.python.org/doc/current/lib/node403.html at the end of the page. --Irmen From saoirse_79 at yahoo.com Wed Oct 8 04:37:04 2003 From: saoirse_79 at yahoo.com (saoirse_79) Date: Wed, 08 Oct 2003 08:37:04 -0000 Subject: mulit-dimensional lists Message-ID: Thanks for your help...what I exactly want to do is as follows: I have a file (a multiple sequence alignment to be exact) and I want each line in that file to be a separate list, hence creating a list of lists! From mertz at gnosis.cx Tue Oct 21 14:12:54 2003 From: mertz at gnosis.cx (David Mertz) Date: Tue, 21 Oct 2003 14:12:54 -0400 Subject: Why don't people like lisp? References: <3f9302d7.170372828@news.eircom.net> <87ismkcp5d.fsf@bird.agharta.de> Message-ID: Bruce Hoult wrote previously: |~bruce$ ls -l `which emacs` |-rwxr-xr-x 1 root wheel 4596224 Sep 24 04:29 /usr/bin/emacs |~bruce$ ls -l /Applications/Microsoft\ Office\ X/Microsoft\ Word |-rwxr-xr-x 1 bruce admin 10568066 Sep 26 2002 |/Applications/Microsoft Office X/Microsoft Word Not even Windows users use MS-Word to edit program code; this is a completely irrelevant comparison. For more realistic ones (from my OS/2 machine that I'm sitting at, and the editors I actually use): D:\editors % ls boxer\b2.exe jEdit4.2pre1\jedit.jar fte\fte.exe 3-24-95 7:00a 317127 0 b2.exe 5-06-03 1:36a 2797098 219 jedit.jar 1-04-00 9:19p 585235 0 fte.exe On a Linux box where my website is hosted (and emacs isn't installed even if I wanted to use it): ~$ ls -l /usr/bin/joe /usr/bin/vim -r-xr-xr-x 1 root root 166160 Feb 28 2001 /usr/bin/joe* -rwxr-xr-x 1 root root 1172464 Dec 5 2001 /usr/bin/vim* On my Macs I use jEdit too, so the size is basically the same (although I have a bit more up-to-date version there). On my FreeBSD box maybe I'll use kEdit or kDevel, or jed or vim; but I'm not sure of file sizes from here. IOW: Emacs is BLOATED. Yours, David... -- Keeping medicines from the bloodstreams of the sick; food from the bellies of the hungry; books from the hands of the uneducated; technology from the underdeveloped; and putting advocates of freedom in prisons. Intellectual property is to the 21st century what the slave trade was to the 16th. From aleax at aleax.it Wed Oct 29 13:09:49 2003 From: aleax at aleax.it (Alex Martelli) Date: Wed, 29 Oct 2003 18:09:49 GMT Subject: PEP 323: Copyable Iterators Message-ID: Interested parties (essentially, people who write user-coded iterator, or are intense users of iterators as "stream of data", of standard library module itertools, etc) are welcome to read, and possibly comment on, a new PEP on copyable iterators, see: http://www.python.org/peps/pep-0323.html The PEP is currently at revision 1.2, having already been amended and vastly extended as a consequence of discussions on these issues on python-dev. In brief, the PEP proposes that: iterator types supply a __copy__ method, if, and only if, the method can make an independently iterable copy of their instances at reasonably low cost in time and memory; the new function itertools.tee be optimized to exploit this method if its argument iterators support it; existing built-in iterator types be upgraded to supply this __copy__ method where applicable; user-written code normally rely on itertools.tee to get independently iterable iterators on the same underlying sequence (occasionally, for special needs, user-written code may feature-test an iterator for __copy__, as long as said user code wants to deal directly and in special ways with both cases, that of copyable iterators and that of non-copyable iterators). Alex From find at my.address.elsewhere Wed Oct 22 22:16:08 2003 From: find at my.address.elsewhere (Matthias Blume) Date: Thu, 23 Oct 2003 02:16:08 GMT Subject: Python from Wise Guy's Viewpoint References: <_8Ekb.7543$pT1.318@twister.nyc.rr.com> Message-ID: Pascal Costanza writes: > The set of programs that are useful but cannot be checked by a static > type system is by definition bigger than the set of useful programs > that can be statically checked. By whose definition? What *is* your definition of "useful"? It is clear to me that static typing improves maintainability, scalability, and helps with the overall design of software. (At least that's my personal experience, and as others can attest, I do have reasonably extensive experience either way.) A 100,000 line program in an untyped language is useless to me if I am trying to make modifications -- unless it is written in a highly stylized way which is extensively documented (and which usually means that you could have captured this style in static types). So under this definition of "useful" it may very well be that there are fewer programs which are useful under dynamic typing than there are under (modern) static typing. > So dynamically typed languages allow > me to express more useful programs than statically typed languages. There are also programs which I cannot express at all in a purely dynamically typed language. (By "program" I mean not only the executable code itself but also the things that I know about this code.) Those are the programs which are protected against certain bad things from happening without having to do dynamic tests to that effect themselves. (Some of these "bad things" are, in fact, not dynamically testable at all.) > I don't question that. If this works well for you, keep it up. ;) Don't fear. I will. > > (And where are _your_ empirical studies which show that "working around > > language restrictions increases the potential for bugs"?) > > I don't need a study for that statement because it's a simple > argument: if the language doesn't allow me to express something in a > direct way, but requires me to write considerably more code then I > have considerably more opportunities for making mistakes. This assumes that there is a monotone function which maps token count to error-proneness and that the latter depends on nothing else. This is a highly dubious assumption. In many cases the few extra tokens you write are exactly the ones that let the compiler verify that your thinking process was accurate (to the degree that this fact is captured by types). If you get them wrong *or* if you got the original code wrong, then the compiler can tell you. Without the extra tokens, the compiler is helpless in this regard. To make a (not so far-fetched, btw :) analogy: Consider logical statements and formal proofs. Making a logical statement is easy and can be very short. It is also easy to make mistakes without noticing; after all saying something that is false while still believing it to be true is extremely easy. Just by looking at the statement it is also often hard to tell whether the statement is right. In fact, computers have a hard time with this task, too. Theorem-proving is hard. On the other hand, writing down the statement with a formal proof is impossible to get wrong without anyone noticing because checking the proof for validity is trivial compared to coming up with it in the first place. So even though writing the statement with a proof seems harder, once you have done it and it passes the proof checker you can rest assured that you got it right. The longer "program" will have fewer "bugs" on average. Matthias From tweedgeezer at hotmail.com Mon Oct 27 09:25:39 2003 From: tweedgeezer at hotmail.com (Jeremy Fincher) Date: 27 Oct 2003 06:25:39 -0800 Subject: Python is Considered Harmful References: Message-ID: <698f09f8.0310270625.657f7f9a@posting.google.com> mike420 at ziplip.com wrote in message news:... > Ladies and Gentlemen, > > I present to you the final and ultimate proof of Python's > brain-damage: > > As you may remember, > > flist = [] > > for i in range(3) > f = lambda x: x + i > flist.append(f) > > [f(1) for f in flist] > > produces [3, 3, 3] in Python. > > In Haskell, we would express this as follows: > > map (\f -> f 1) [\x -> x + i | i <- [0..2]] First, let's remove the list comprehension syntactical sugar. This is actually: map (\f -> f 1) (map (\i -> (\x -> x + i)) [0..2]) So, as you can see clearly without the sugar, you're basically creating closures, since a new lexical scope is introduced at function creation. > This, of course, evaluates to the expected [1, 2, 3] Expected by functional programmers who expect new lexical scopes to be created at every block, sure. But Python isn't a functional programming language, and doesn't create a new lexical scope in every block. > As you might have heard, the ever so generous GvR allowed us write > the same in Python (literal translation, really): > > map(lambda f: f(1), [lambda x: x + 1 for i in range(3) Others have pointed out your typo here; I'll assume you meant "lambda x: x + i" instead of 1. Again, let's remove the syntactical sugar here: L = [] for i in range(3): L.append(lambda x: x + i) map(lambda f: f(1), L) The observed result, [3, 3, 3] is perfectly in keeping with the fact that Python does not create a new lexical scope in for suites (or if suites, or any other non-class, non-function suite). > Pythonista, you are all very welcome to learn Haskell. > You will find the syntax very familiar. Haskell is short > too (compare one line above that gives the correct > result to several Python lines that surprise you) The Python result is only surprising to those who try to impose other languages' semantics on Python. > All this Python bashing is starting to feel like mocking > a retarded child... You, sir, are a poor representative of the Haskell community. Jeremy From jhbrown at ai.mit.edu Fri Oct 3 13:53:05 2003 From: jhbrown at ai.mit.edu (Jeremy H. Brown) Date: 03 Oct 2003 13:53:05 -0400 Subject: Python syntax in Lisp and Scheme References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> <7wednSJ_q_L85uCiXTWJhQ@comcast.com> <4pthecmq4.fsf@beta.franz.com> Message-ID: Duane Rettig writes: > jhbrown at ai.mit.edu (Jeremy H. Brown) writes: > This is actually a pretty good list. I'm not commenting on > completeness, but I do have a couple of corrections: ... > > Implementations >10 ~4 > ===========================================^ > > See http://alu.cliki.net/Implementation - it lists 9 commercial > implementations, and 7 opensource implementations. There are > probably more. Thanks. I hadn't realized the spread was that large. > > Performance "worse" "better" > > Standards IEEE ANSI > > Reference name R5RS CLTL2 > ============================================^ > > No, CLtL2 is definitely _not_ a reference for ANSI Common Lisp. > It was a snapshot taken in the middle of the ANSI process, and > is out of date in several areas. References which are much closer > to the ANSI spec can be found online at > > http://www.franz.com/support/documentation/6.2/ansicl/ansicl.htm > > or > > http://www.lispworks.com/reference/HyperSpec/Front/index.htm Thanks again. > > > > Try them both, see which one works for you in what you're doing. > > Agreed, but of course, I'd recommend CL :-) I've arrived at the conclusion that it depends both on your task/goal and your personal inclinations. Jeremy From kalath at lycos.com Fri Oct 3 14:50:22 2003 From: kalath at lycos.com (Mark Brady) Date: 3 Oct 2003 11:50:22 -0700 Subject: Python syntax in Lisp and Scheme References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> <7wednSJ_q_L85uCiXTWJhQ@comcast.com> Message-ID: "Terry Reedy" wrote in message news:<7wednSJ_q_L85uCiXTWJhQ at comcast.com>... > "Mark Brady" wrote in message > news:e840346c.0310030302.6be0c378 at posting.google.com... > > This whole thread is a bad idea. > > I could agree that the OP's suggestion is a bad idea but do you > actually think that discussion and more publicity here for Lisp/Scheme > is bad? You make a pretty good pitch below for more Python=>Lisp > converts. > You are right of course, however I dislike cross posting and I also dislike blatantly arguing with people over language choice. I would prefer to lead by example. I think one good program is worth a thousand words. For example people listen to Paul Graham (http://www.paulgraham.com/avg.html) when he advocates Common Lisp because he wrote Viaweb using it and made a fortune thanks to Lisp's features (details in the link). > > If you like python then use python. > > As I plan to do. > Nothing wrong with that. Most people on these groups would agree that Python is a very good choice for a wide range of software projects and it is getting better with every release. I think that if you can get over S-exps then Scheme and Common Lisp feel very like python. I would recommend Pythonistas to at least experiment with Common Lisp or Scheme even if you are perfectly happy with Python. After all you have nothing to lose. If you don't like it then fine you always have Python and you've probably learned something and if you do like it then you have another language or two under your belt. > > Personally I find Scheme and Common Lisp easier to read but that's > > just me, I prefer S-exps and there seems to be a rebirth in the > cheme > > and Common Lisp communities at the moment. Ironically this seems to > > have been helped by python. I learned python then got interested in > > it's functional side and ended up learning Scheme and Common Lisp. A > > lot of new Scheme and Common Lisp developers I talk to followed the > > same route. Python is a great language and I still use it for some > > things. > > Other Lispers posting here have gone to pains to state that Scheme is > not a dialect of Lisp but a separate Lisp-like language. Could you > give a short listing of the current main differences (S vs. CL)? If I > were to decide to expand my knowledge be exploring the current > versions of one(I've read the original SICP and LISP books), on what > basis might I make a choice? > > Terry J. Reedy This is a difficult question to answer. It's a bit like trying to explain the differences between Ruby and Python to a Java developer ;-) *Personally* I find it best to think of Scheme and Common Lisp as two different but very closely related languages. The actual languages and communities are quite different. Common Lisp is a large, very pragmatic, industrial strength language and its community reflects this. Common Lisp has loads of features that you would normally only get in add on libraries built right into the language, it's object system "CLOS" has to be experienced to be believed and its macro system is stunning. Some very smart people have already put years of effort into making it capable of great things such as Nasa's award winning remote agent software (http://ic.arc.nasa.gov/projects/remote-agent/). Scheme is a more functional language and unlike Common Lisp is has a single namespace for functions and variables (Python is like Scheme in this regard). Common Lisp can be just as functional but on the whole the Scheme community seem to embrace functional programming to a greater extend. Scheme is like python in that the actual language is quite small and uses libraries for many of the same tasks Python would use them for, unlike Common Lisp that has many of these features built into the language. It also has a great but slightly different macro system although every implementation I know also has Common Lisp style Macros. Scheme doesn't have a standard object system (it's more functional) but has libraries to provide object systems. This is very hard to explain to python developers, scheme is kind of like a big python metaclass engine where different object systems can be used at will. It's better than I can describe and it is really like a more powerful version of Pythons metaclass system. Pythonistas who love functional programming may prefer Scheme to Common Lisp while Pythonistas who want a standard amazing object system and loads of built in power in their language may prefer Common Lisp. To be honest the these tutorials will do a far better job than I could: For Scheme get DrScheme: http://www.drscheme.org/ and go to 'Teach yourself scheme in fixnum days' : http://www.ccs.neu.edu/home/dorai/t-y-scheme/t-y-scheme.html For Common Lisp get the trial version of Lispworks: http://www.lispworks.com/ and go get Mark Watsons free web book: http://www.markwatson.com/opencontent/lisp_lic.htm Regards, Mark. Ps. If anyone spots a mistake in this mail please correct me, it will have been an honest one and not an attempt to slander your favourite language and I will be glad to be corrected, in other words there is no need to flame me :) From max at alcyone.com Thu Oct 9 05:18:42 2003 From: max at alcyone.com (Erik Max Francis) Date: Thu, 09 Oct 2003 02:18:42 -0700 Subject: Making variable from a variable References: Message-ID: <3F8527F2.21E42656@alcyone.com> "Polerio Babao Jr.II" wrote: > I don't know if this question is easy or not but one thing I can say > is > I haven't encountered this problem yet in my entire python life. I > just opened > this question to the public because I've solved this kind of problem > already > before in my PHP life long time ago. I just want to know if it's also > possible in Python. > Any idea? Thanks. It is, with eval/exec. It's far more likely, though, that in Python a better approach to this sort of problem would be to use a dictionary. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ Custom reconciles us to everything. \__/ Edmund Burke From aleaxit at yahoo.com Sat Oct 11 19:19:54 2003 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 11 Oct 2003 23:19:54 GMT Subject: Python syntax in Lisp and Scheme References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> <92c59a2c.0310031345.57d20631@posting.google.com> Message-ID: Kenny Tilton wrote: ... >> The very 'feature' that was touted by Erann Gat as macros' killer >> advantage in the WITH-CONDITION-MAINTAINED example he posted is the >> crucial difference: functions (HO or not) and classes only group some >> existing code and data; macros can generate new code based on examining, >> and presumably to some level *understanding*, a LOT of very deep things >> about the code arguments they're given. > > Stop, your scaring me. You mean to say there are macros out there whose > output/behavior I cannot predict? And I am using them in a context where > I need to know what the behavior will be? What is wrong with me? And > what sort of non-deterministic macros are these, that go out and make > their own conclusions about what I meant in some way not documeted? Let's start with that WITH-CONDITION-MAINTAINED example of Gat. Remember it? OK, now, since you don't appear to think it was an idiotic example, then SHOW me how it takes the code for the condition it is to maintain and the (obviously very complicated: starting a reactor, operating the reactor, stopping the reactor -- these three primitives in this sequence) program over which it is to maintain it, and how does it modify that code to ensure this purpose. Surely, given its perfectly general name, that macro does not contain, in itself, any model of the reactor; so it must somehow infer it (guess it?) from the innards of the code it's analyzing and modifying. Do you need to know what the behavior will be, when controlling a reactor? Well, I sort of suspect you had better. So, unless you believe that Gat's example was utterly idiotic, I think you can start explaining from right there. > I think the objection to macros has at this point been painted into a > very small corner. I drastically disagree. This is just one example, that was given by one of the most vocal people from your side, and apparently not yet denounced as idiotic, despite my asking so repeatedly about it, so presumably agreed with by your side at large. So, I'm focusing on it until its import is clarified. Once that is done, we can tackle the many other open issues. For example, the fact that Gat himself says that if what I want to write are normal applications, macros are not for me: only for those who want to push the boundaries of the possible are they worthwhile. Do you think THAT is idiotic, or wise? Please explain either the reason of the drastic disagreements in your camp, or why most of you do keep trying pushing macros (and lisp in general) at those of us who are NOT particularly interested in "living on the edge" and running big risks for their own sake, accordingly to your answer to the preceding question, thanks. "Small corner"?! You MUST be kidding. Particularly given that so many on your side don't read what I write, and that you guys answer the same identical questions in completely opposite ways (see below for examples of both), I don't, in fact, see how this stupid debate will ever end, except by exhaustion. Meanwhile, "the objection to macros" has only grown larger and larger with each idiocy I've seen spouted in macros' favour, and with each mutual or self-contradiction among the macros' defenders. >> ...If all you do with your macros is what you could >> do with HOF's, it's silly to have macros in addition to HOF's > > There is one c.l.l. denizen/guru who agrees with you. I believe his ...and there's another who has just answered in the EXACTLY opposite way -- that OF COURSE macros can do more than HOF's. So, collectively speaking, you guys don't even KNOW whether those macros you love so much are really necessary to do other things than non-macro HOFs allow (qualification inserted to try to divert the silly objection, already made by others on your side, that macros _are_ functions), or just pretty things up a little bit. Would y'all mind coming to some consensus among you experienced users of macros BEFORE coming to spout your wisdom over to us poor benigthed non-lovers thereof, THANKYOUVERYMUCH...? >> far from all). This is far from the first time I'm explaining this, btw. > > Oh. OK, now that you mention it I have been skimming lately. In this case, I think it was quite rude of you to claim I was not answering questions, when you knew you were NOT READING what I wrote. As you claim that macros are just for prettying things up, I will restate (as you may not have read it) one of the many things I've said over and over on this thread: I do not believe the minor advantage of prettying things up is worth the complication, the facilitation of language divergence between groups, and the deliberate introduction of multiple equivalent ways to solve the same problem, which I guess you do know I consider a bad thing, one that impacts productivity negatively. Alex From richchas at comcast.net Sun Oct 26 14:35:09 2003 From: richchas at comcast.net (Charles Richmond) Date: Sun, 26 Oct 2003 19:35:09 GMT Subject: OT: The Straight Dope References: Message-ID: <3F9C3D01.9C77374E@comcast.net> Nick Vargish wrote: > > Jeff Bauer writes: > > > if-tim-is-sherlock-then-cecil-must-be-mycroft-ly y'rs, > > Just a correction; the SD article quoted in the previous post was > written by a Staff Reporter ("Una Persson"), not the exalted > Cecil Adams himself. > > I did think it was funny that Python was mentioned, but Perl was > slighted -- backticks are much more common in Perl code than in > Python code, at least in my experience. > Hey, the C-shell in UNIX uses backquote also... I do *not* know about bash, ksh, or sh. -- +----------------------------------------------------------------+ | Charles and Francis Richmond richmond at plano dot net | +----------------------------------------------------------------+ From claird at lairds.com Mon Oct 13 11:42:49 2003 From: claird at lairds.com (Cameron Laird) Date: Mon, 13 Oct 2003 15:42:49 -0000 Subject: Whence the love of Python (was: type checking) References: <3mwib.274990$R32.8966921@news2.tin.it> Message-ID: In article , Alex Martelli wrote: >Stephen Horne wrote: . . . >> Oddly enough, I think my Python code has reflected this for some time >> without me noticing the issue. > >Interesting indeed! This kind of "you're smarter than you know" effect >IS observed time and again, admittedly... > > >Alex > The aptness of jokes about Guido's time-machine hints at real quality in the language. More often than not, or more often than with other languages, Python seems to treat ignorance gently. This is a dimension of craftsman- ship: to do the right thing, degrees of freedom remain. Python Does It Right. No, better than that, Python makes it easy to do it right. -- Cameron Laird Business: http://www.Phaseit.net From lex at cc.gatech.edu Fri Oct 24 11:48:44 2003 From: lex at cc.gatech.edu (Lex Spoon) Date: Fri, 24 Oct 2003 11:48:44 -0400 Subject: Explanation of macros; Haskell macros References: Message-ID: This thread has seemed to miss the biggest advantage of macros. Most examples so far are cases where the macro buys you faster code. This is not extremely exciting, IMHO, because a better compiler can often accomplish the things that are described. If you care that much about performance then surely you want to be using a good optimizing compiler, and a good compiler will surely know about, e.g., for loops that go across constant ranges. I tend to think of macros as bad style for this kind of thing, unless it's very clearly a performance problem you are having. Macros often look like functions, but they don't act like them, and it's very easy to introduce bugs with them. A much bigger advantage of macros is that you can literally extend the language. For example, it is nice to be able to type something like this: (regex (| h H) "ello, " (| w W) orld (? "!")) To allow this in the nicest way requires using a macro for 'regex. Without macros, you can still do it: (regex '(| h H) "ello, " (| w W) orld (? "!")) but now this guy is going to get compiled at runtime, and you get into the issue of trying to save the compiled regex somewhere ahead of time. And while regexes themselves compile pretty quickly, suppose it's something more like: (parser (grammer ;;... a BNF grammer ... I also loved the example of both printing a statement and executing it, which is extremely useful for assertion checking. You can't really do this properly without macros. -Lex From imbosol at aerojockey.invalid Thu Oct 16 15:09:38 2003 From: imbosol at aerojockey.invalid (Carl Banks) Date: Thu, 16 Oct 2003 19:09:38 GMT Subject: assignment expression peeve References: <7x1xtfkuky.fsf@ruckus.brouhaha.com> <6q6jb.10882$fv4.3354@nwrdny02.gnilink.net> <7xk77676bt.fsf@ruckus.brouhaha.com> <7xptgy9qr7.fsf@ruckus.brouhaha.com> <7x8ynm6rtu.fsf@ruckus.brouhaha.com> <%iljb.19300$0I6.15247@nwrdny03.gnilink.net> <7x7k366mwe.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Carl Banks writes: >> Again, apples and oranges. You are comparing meanings, when the >> problem is syntax. "A guy named Bob walks into a bar" and >> "bar.enter(bob := Guy())" might have the same meaning, but they use a >> diffenent syntax to convey it. And the latter uses a syntax with no >> analogue in any natural language I know of. > > Whatever. You're the only programmer I've ever encountered who claims > to have actual trouble understanding assignment expressions. I really don't appreciate you putting words in my mouth, and I'm sorry you feel the need to resort to dishororable tactics. I claim assignment expressions are counterintuitive, and hard to read, because they go against the grain of natural language. They require more effort because we can't use the language parts of our brains to help. I've NEVER said there was any trouble understanding them. The trouble is inputing them into our brains. > With other people, the objection is that they can be confused with > comparison expressions, or that they're simply another > not-so-important feature that Python doesn't need. Bullshit. I'm not the only person to have said these things about assignment expressions. And if you think there are no language experts out there who think assignment expressions are a mistake, you're deluded. -- CARL BANKS http://www.aerojockey.com/software As the newest Lady Turnpot descended into the kitchen wrapped only in her celery-green dressing gown, her creamy bosom rising and falling like a temperamental souffle, her tart mouth pursed in distaste, the sous-chef whispered to the scullery boy, "I don't know what to make of her." --Laurel Fortuner, Montendre, France 1992 Bulwer-Lytton Fiction Contest Winner From bkc at Murkworks.com Fri Oct 17 10:38:08 2003 From: bkc at Murkworks.com (Brad Clements) Date: Fri, 17 Oct 2003 10:38:08 -0400 Subject: Can we use emPy, ReST, and/or YAML for report generation References: Message-ID: I use FOP from Apache.org. Python pulls data from SAPDB and I write it out as XML. FOP makes it into a PDF Nice thing is, the same XML data creates my web pages using client-side XSLT or server-side xlst (with zope). I also use the same xml to make customer invoices (through FOP) . We originally used ReportLab to make PDF reports, but every new report required a lot of tedious programming in Python. ReportLab produces good output, but FOP gave us more flexability. I bet RXML would be good, but that didn't exist when we moved to FOP. -- Novell DeveloperNet Sysop #5 _ "Samir Patel" wrote in message news:ffd90607.0310160431.5fefb027 at posting.google.com... > Currently main choice to create a report in python is reportlab. It > allows a fine control over creation of report at cost of bigger > learning curve. Instead of reportlab, does it make sense to generate > small reports using emPy or ReST with or without use of YAML? Are > there any other choice to create small reports easily in python? > -- > http://mail.python.org/mailman/listinfo/python-list > From keflimarcusx at aol.comNOSPAM Tue Oct 28 14:25:31 2003 From: keflimarcusx at aol.comNOSPAM (KefX) Date: 28 Oct 2003 19:25:31 GMT Subject: Why I love Python (warning: rambling) References: Message-ID: <20031028142531.06025.00000234@mb-m11.aol.com> >Hanging out on python-list will change the way you think about programmers, though. In a good or a bad way? ;) - Kef From achrist at easystreet.com Sun Oct 19 13:26:54 2003 From: achrist at easystreet.com (achrist at easystreet.com) Date: Sun, 19 Oct 2003 10:26:54 -0700 Subject: [Q] ctypes callbacks with Delphi References: <3F90AB7D.711FF820@easystreet.com> <3F922003.4498CFB6@easystreet.com> <87ad7xxrfq.fsf@pobox.com> Message-ID: <3F92C95E.6B1A8242@easystreet.com> "John J. Lee" wrote: > > Googling for " info page" (no quotes) finds mailman > lists. > > http://lists.sourceforge.net/lists/listinfo/ctypes-users > Thanks. The sourceforge page I saw only listed a ctypes developers group. I guess that the ASPN archive might just be a copy of that list. Al From davidcfox at post.harvard.edu Tue Oct 28 13:22:11 2003 From: davidcfox at post.harvard.edu (David C. Fox) Date: Tue, 28 Oct 2003 18:22:11 GMT Subject: manipulate string In-Reply-To: References: Message-ID: > import string > a='0123456789' > l=list(a[::2]) > b=string.join(l,' - ') > print b Chris wrote: > It is me again. > Unfortunately it doesn't work. Python doesn't accept [::2] > TypeError: sequence index must be integer > I use Python Release 2.2.3. > Any ideas? > > -Tom > Yeah, the x[::i] notation for strings and lists only works in 2.3. A couple of alternatives to l = list(a[::2]) which work in 2.2 are: l = [] for i in range( (len(a) + 1) // 2): l.append(a[2*i]) or more compactly l=[a[2*i] for i in range((len(a)+1)//2)] or l = [a[i] for i in range(len(a)) if 2*(i//2) == i] David From peter at engcorp.com Mon Oct 27 08:17:46 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 27 Oct 2003 08:17:46 -0500 Subject: Python is not [yet] Considered Harmful References: <20031027023332.000038fa.ddarius@hotpop.com> Message-ID: <3F9D1AFA.ECC8D739@engcorp.com> Darius wrote: > > On Sun, 26 Oct 2003 22:56:19 -0800 (PST) > mike420 at ziplip.com wrote: > [snip trollisms] > At any rate, either you are a troll and none of the involved want you > here, or you aren't and you should cease posting for a few months > so you stop looking like one. He is a troll, no question. Check his recent postings for confirmation. -Peter From bokr at oz.net Thu Oct 9 20:24:26 2003 From: bokr at oz.net (Bengt Richter) Date: 10 Oct 2003 00:24:26 GMT Subject: What is up with "=="? References: <3F8481A4.36C460FE@alcyone.com> Message-ID: On Wed, 08 Oct 2003 14:29:08 -0700, Erik Max Francis wrote: >Quentin Crain wrote: > >> 1 Whos __eq__ or __cmp__ is being called: String's or >> Int's? >> 2 Why IS comparison supported across types? >> 3 The exception + gives makes it sound like there is >> a built-in function + that does not like taking an >> 'int' and a 'string'. Read this way, the built-in == >> does accept 'int' and 'string'. > >It's really a judgement call. It's certainly possible to set up an >equality operator which respects type, but in a dynamic language like >Python, you'll often find yourself comparing objects of different types >for equality. This can get inconvenient, since this means that this >comparisons would raise TypeErrors when all you really care about is >whether or not they're equal or not. Two objects of different types are >obviously unequal (unless __eq__ is deliberately overridden, etc., >etc.), so it makes sense to simply have == and != not raise TypeErrors. > >In fact, it's so common, that if your standard equality operator _does_ >raise TypeErrors, you're almost guaranteeing you need another builtin >equality operator which does _not_ respect type. So now you have two >equality operators, which can be confusing -- there's >test-equality-and-raise-if-the-types-are-different and >test-equality-and-treat-different-types-as-simply-unequal. This isn't >necessarily the end of the world, but it's inconvenient. (For the >record, I used this approach -- two equality operators, `eq' and `seq' >-- so I'm not opposed to it on general principle.) > >Plus the dynamicism of Python itself enters into it. I can easily come >up with custom classes, whether actually derived from numeric types or >not, which I _do_ want to test equal to existing types. Now it's >looking much more like it would be advantageous for equality to simply >not raise an error on different types and just say, "Nope, they're not >equal." > The OP might want to know about type difference NOT implying unequal when conversion can be done, as between numbers. E.g., >>> 2==2.0, 2==2L, 2L==2.0 (True, True, True) BTW, this looks like a bug in the doc<->reality relationship: 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. >>> help(coerce) Help on built-in function coerce: coerce(...) coerce(x, y) -> None or (x1, y1) When x and y can be coerced to values of the same type, return a tuple containing the coerced values. When they can't be coerced, return None. >>> coerce(2,'2') Traceback (most recent call last): File "", line 1, in ? TypeError: number coercion failed Bad doc string or misimplementation? Or is it fixed in the latest release, (which I haven't gotten around to installing yet)? Regards, Bengt Richter From aleax at aleax.it Tue Oct 21 03:19:34 2003 From: aleax at aleax.it (Alex Martelli) Date: Tue, 21 Oct 2003 07:19:34 GMT Subject: prePEP: Money data type References: Message-ID: Ian Bicking wrote: ... > For instance, Money.parse('$100.00'), Money.parse('$100.00', > decimalSeparator='.'), Money.parse('100Y', currency='Y'), etc. I like the idea of delegating ALL build-by-parsing-string functionality to a Money.parse classmethod -- it nicely matches my suggestion of delegating any fancy emit-string functionality to a .format instance method. This would let Money.__init__ (or Money.__new__, whatever) remain simpler, without need for "decimal separators" etc. > Also, while you can use potentially ambiguous heuristics for this parse > constructor, the main constructor can be more strict -- it's hard to > add strictness, but easier to take it away. I would expect that the Yes, just as for functionality. > main constructor take only a string or a number-like-object (int, Actually, if Money's main ctor did not take ANY string at all, how would that be bad? An explicit Money.parse in the base ctor can take care of that. The reason we don't have this in existing built-ins is that existing built-ins were designed BEFORE we had classmethods, so their ctor was "the" ctor, singular, so it was badly overloaded. But these days we can do better. > float, fixed point, etc), with other information passed through keyword > arguments. I would prefer the string be a Python style of number, > i.e., unambiguously and strictly with '.' for decimals, and no > thousands-separator. But then that matches my locale, so I suppose I'm The Italian locale is different, but I would have no objection to Money.parse in the base class being very spare. It should roughly match the functionality of the .format instance method in the base class: more or less, what .format can emit .parse should be able to use, when each is given appropriate keyword arguments (locale or a localeconv-like dict, indications of whether to use plain or money and base or international settings) -- but it WOULD be fine if that functionality was quite limited, including nothing at all fancy, in the base class (a subclass or perhaps better a mixin SHOULD however also be provided in the module, with at least locale-based parse and format abilities). > biased -- but I see the sole reason for using that string to be that > Python float literals cannot precisely express a fixed-point number. > If a fixed-point literal existed, then I would prefer that no string be > allowed -- the parse constructer better highlights what is being done > in that case. Upon reflection I prefer no string in the main ctor anyway -- float literals CAN express numbers to at least about 16 digits and we don't really need more in most cases (when we do, passing a long and a scale factor such as scale=2 to indicate the long is in /100th's seems quite OK). Of course a float would be rounded-to-nearest to the indicated or defaulted amount of precision, AND it should be a ValueError if the rounding is one ULP or more, because that would surely indicate it wasn't a _literal_ that was passed. > (A fixed-point literal would be quite nice... a fixed-point builtin > would be quite nice...) Yeah, but so would be sets -- first we need to get into the standard library (and the sparest, simplest base class we can make, the more likely I judge we can get into the standard library), THEN once the type is in use we can make a case for literals and builtins. Alex From costanza at web.de Wed Oct 15 16:22:13 2003 From: costanza at web.de (Pascal Costanza) Date: Wed, 15 Oct 2003 22:22:13 +0200 Subject: Car and cdr (Re: Python syntax in Lisp and Scheme) In-Reply-To: <3f8c2182@news.sentex.net> References: <6CZgb.3273$dn6.860@newsread4.news.pas.earthlink.net> <3m3lovgn8obb80b3t2rv96ik5cndfpietj@4ax.com> <3f8c2182@news.sentex.net> Message-ID: Hartmann Schaffer wrote: > In article , > Pascal Costanza writes: > >> ... >> I think that's the essential point here. The advantage of the names car and cdr is that they _don't_ mean anything specific. > > > > gdee, you should read early lisp history ;-). car and cdr ha[d|ve] a > very specific meaning Yes, but noone (noone at all) refers to that meaning anymore. It's a historical accident that doesn't really matter anymore when developing code. Pascal From peter at javamonkey.com Wed Oct 22 01:57:54 2003 From: peter at javamonkey.com (Peter Seibel) Date: Wed, 22 Oct 2003 05:57:54 GMT Subject: Why don't people like lisp? References: <8Nnlb.619$I04.380@newsread4.news.pas.earthlink.net> Message-ID: "Andrew Dalke" writes: > Me: > > Python has the ability to do exactly what you're saying (domain > > language -> AST -> Python code or AST -> compiler). It's rarely > > needed (I've used it twice now in my six years or so of Python), > > so why should a language cater to make that easy at the expense of > > making frequent things harder? > > As an example, here's a quick hack of a way to parse a simple > stack-based language and make a native Python function out of it. I > am the first to admit that it's ugly code, but it does work. > > I am curious to see the equivalent code in Lisp. Here's the spec > > All tokens are separated by whitespace (space, tab, newline, and > include vertical tab and form feed if you want). > > Numbers are the standard IEEE floats (excepting NaN, Inf, etc) > and represented "as usual". > > The operators are addition ("+"), subtraction ("-"), multiplication > ("*"), division ("/"), and exponentiation ("**"). These are binary > operators only, so to get -b use 0 b - . > > The variable names are of the form [A-Za-Z_][A-Za-z0-9_]* > and must be passed to the function when making the function call. > The order of names is the same as the order the names appear > in the RPN expression, so in "b a +" the function created takes > "b" as the first argument and "a" as the second. Okay, here's a Common Lisp version. Because Lisp functions take either keyword or positional arguments, I choose to make the generated functions use keyword arguments. But the variables are gathered in the right order, so take out the '&key' below to use positional arguments: (defun compile-rpn (input) (compile nil (parse input))) (defun parse (input) (let (stack variables (idx 0)) (loop (multiple-value-bind (tok next-idx) (read-from-string input nil nil :start idx) (labels ((line-number () (1+ (count #\Newline input :end idx))) (pop-arg () (or (pop stack) (error "Not enough arguments for ~a at position ~d (line ~d)." tok idx (line-number))))) (cond ((not tok) (return `(lambda (&key ,@(nreverse variables)) (prog1 , at stack)))) ((member tok '(+ * - /)) (push (cons tok (reverse (list (pop-arg) (pop-arg)))) stack)) ((eq tok '**) (push (cons 'expt (reverse (list (pop-arg) (pop-arg)))) stack)) ((numberp tok) (push tok stack)) ((variablep tok) (push tok stack) (pushnew tok variables)) (t (error "Invalid token ~a at position ~d (line ~d)." tok idx (line-number)))) (setq idx next-idx)))))) (defun variablep (sym) (and (symbolp sym) (every #'alpha-char-p (string sym)))) Here's how it works (FUNCALL is the Common Lisp operator to calls a function object such as the one returned by compile-rpn): * (funcall (compile-rpn "1 2 3 4 5 + + + + a **") :a 2) 225 Compile-time error messages: * (compile-rpn "a + 2 * b") Error: Not enough arguments for + at position 2 (line 1). * (compile-rpn "5t") Error: Invalid token 5T at position 0 (line 1). Runtime error handling: * (funcall (compile-rpn "a b +") :a "foo" :b 2) Error: `"foo"' is not of the expected type `NUMBER' And for grins here's the x86 machine code generated for the first function: * (disassemble (compile-rpn "1 2 3 4 5 + + + + a **")) ;; disassembly of # ;; formals: &KEY A ;; constant vector: 0: NIL 1: 1 2: :A 3: EXPT ;; code start: #x7608e4d4: 0: 55 pushl ebp 1: 8b ec movl ebp,esp 3: 56 pushl esi 4: 83 ec 2c subl esp,$44 7: 89 45 08 movl [ebp+8],eax 10: 89 55 0c movl [ebp+12],edx 13: 8d 09 leal ecx,[ecx+0] 15: 8d 45 08 leal eax,[ebp+8] 18: 8d 55 e0 leal edx,[ebp-32] 21: 33 db xorl ebx,ebx 23: b3 48 movb bl,$72 25: ff 57 4f call *[edi+79] ; SYS::KWDSCAN 28: 8d 5d e0 leal ebx,[ebp-32] 31: 8b 13 movl edx,[ebx+0] 33: 3b fa cmpl edi,edx 35: 75 1a jnz 63 37: 8b d7 movl edx,edi 39: 80 7f 97 00 cmpb [edi-105],$0 ; SYS::C_INTERRUPT 43: 74 02 jz 47 45: cd 64 int $100 ; EXCL::TRAP-SIGNAL-HIT 47: 8b 5e 1e movl ebx,[esi+30] ; EXPT 50: 33 c0 xorl eax,eax 52: b0 3c movb al,$60 54: ff 57 27 call *[edi+39] ; SYS::TRAMP-TWO 57: f8 clc 58: c9 leave 59: 8b 75 fc movl esi,[ebp-4] 62: c3 ret 63: 8b 53 04 movl edx,[ebx+4] 66: eb e3 jmp 39 -Peter -- Peter Seibel peter at javamonkey.com Lisp is the red pill. -- John Fraser, comp.lang.lisp From contact at alanlittle.org Wed Oct 8 03:28:09 2003 From: contact at alanlittle.org (Alan Little) Date: 8 Oct 2003 00:28:09 -0700 Subject: merge & de-duplicate lists Message-ID: <4ef0f3a4.0310072328.5ff87e7c@posting.google.com> I need to merge and de-duplicate some lists, and I have some code which works but doesn't seem particularly elegant. I was wondering if somebody could point me at a cleaner way to do it. Here's my function: +++++++++++++++++++ from sets import Set def mergeLists (intialList, sourceOfAdditionalLists, nameOfMethodToCall) : workingSet = Set(initialList) for s in sourceOfAdditionalLists : getList = s.__getAttribute__(nameOfMethodToCall) workingSet = workingSet.union(Set \ (callable(getList) and getList() or getList)) return workingSet ++++++++++++++ Two questions - passing the *name* of the method to call, and then looking it up for each object in the list of extra sources (all of which need to be new-style objects - not a problem in my application) seems inelegant. My "sourcesOfAdditionalLists" are normally all of the same class - is there something I can bind at class level that automagically refers to instance-level attributes when invoked? Second (hopefully clearer & less obscure) question : is sets.Set.union() an efficient way to do list de-duplication? Seems like the obvious tool for the job. From costanza at web.de Thu Oct 23 13:15:48 2003 From: costanza at web.de (Pascal Costanza) Date: Thu, 23 Oct 2003 19:15:48 +0200 Subject: Python from Wise Guy's Viewpoint In-Reply-To: <3F980363.9020407@ps.uni-sb.de> References: <_8Ekb.7543$pT1.318@twister.nyc.rr.com> <3F980363.9020407@ps.uni-sb.de> Message-ID: Andreas Rossberg wrote: >> Can you give me a reference to a paper, or some other literature, that >> defines the terminology that you use? >> >> I have tried to find a consistent set of terms for this topic, and >> have only found the paper "Type Systems" by Luca Cardelli >> (http://www.luca.demon.co.uk/Bibliography.htm#Type systems ) >> >> He uses the terms of static vs. dynamic typing and strong vs. weak >> typing, and these are described as orthogonal classifications. I find >> this terminology very clear, consistent and useful. But I am open to a >> different terminology. > > > My copy, > > http://research.microsoft.com/Users/luca/Papers/TypeSystems.A4.pdf > > on page 3 defines safety as orthogonal to typing in the way Matthias > suggested. Yes, but it says dynamically typed vs statically typed where Matthias says untyped vs typed. Pascal -- Pascal Costanza University of Bonn mailto:costanza at web.de Institute of Computer Science III http://www.pascalcostanza.de R?merstr. 164, D-53117 Bonn (Germany) From peter at javamonkey.com Thu Oct 30 12:09:04 2003 From: peter at javamonkey.com (Peter Seibel) Date: Thu, 30 Oct 2003 17:09:04 GMT Subject: Explanation of macros; Haskell macros References: <87brs2tjut.fsf@memetrics.com> <87he1rdt9d.fsf@memetrics.com> Message-ID: Joachim Durchholz writes: > Efficiency issues aside: how are macros more intuitive than quoting? Because they let you write what you intuitively expect (assuming your intuitions are tuned a particular way, I suppose). In Common Lisp, WHEN is a macro that lets you write this: (when (> x y) (print x)) If you tried to write it as a function using quoting to prevent evaluation you might try this: (when (> x y) '(print x)) which won't work in general because of the iniability for the code inside WHEN to evaluate the data '(print x) in the lexical environment where it appears. Or you could do this: (when (> x y) #'(lambda () (print x))) which could work but seems a bit convoluted (i.e. unintuitive) compared to the macro version. -Peter -- Peter Seibel peter at javamonkey.com Lisp is the red pill. -- John Fraser, comp.lang.lisp From alan.gauld at btinternet.com Tue Oct 28 02:48:58 2003 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 28 Oct 2003 07:48:58 GMT Subject: Is it any good? References: Message-ID: <3f9da7ce.112132257@news.blueyonder.co.uk> On Tue, 28 Oct 2003 00:47:01 +0100, Tim Ronning wrote: > I wonder if I could get some feedback from the list on a Python book I'm > about to order from the net. The book is called "Python How to Program" by > Deithel & Deithel. Issued on Prentice Hall 2002. I'm not an experienced > Python programmer and I'm looking for a comprehensive but also an > "understandable" book. I'm also open for suggestions. I have the Deitel book and find it good as an intro to a huge range of topics - maybe the only book on pyGame? - but in each case it (infuriatingly) stops just at the point where I need more. In other words it gives enough to get you interested in a topic but not quite enough to use as a reference for real work. Given the size of the book and its scope that's not surprising and as a taster its fine. The basic Python coverage is better elsewhere but if you only want one book on Python and are happy digging detail online then its probably OK. An alternative (and no more expensive) is a combination of a basic tutor (Quick Python, Learning Python if you already can program, my book or Ivan van Lanningham's if you can't) to get started plus something like Programming Python or Text Processing in Python or one of the Python Web/XML books - whatever your specialism is likely to be.... Alan G. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld From aleax at aleax.it Wed Oct 15 12:22:12 2003 From: aleax at aleax.it (Alex Martelli) Date: Wed, 15 Oct 2003 16:22:12 GMT Subject: else on the same line - howto References: <3F8D6B1E.C4B8C0C@engcorp.com> Message-ID: Peter Hansen wrote: > Terry Reedy wrote: >> >> "Helmut Jarausch" wrote in >> message news:bmj859$iph$1 at nets3.rz.RWTH-Aachen.DE... >> > Since Python lacks conditional expression >> > like >> > >> > k+= (dy >= 0 ? 1 : -1) >> >> For this specific example: >> >> k+= (dy >= 0 and 1 or -1) >> >> But don't do this unless and until you 1) understand why this works >> and why the and branch must be non-null and what happens if it is null >> (this is discussed both in the FAQ and PEP 308) AND 2) accept >> responsibility for always remembering the caution. > > Is it "non-null" or "non-false"? Non-false. Anyway, if one really wants to obfuscate, why not: k += 1 - 2*(dy<0) ??? Now THAT is clever -- none of those plebeian, obvious if dy>=0: k += 1 else: k -= 1 TWO-liners... first of all, if even your boss can understand what your code is doing, you're not being clever enough and your next raise or even your job could be at risk; second, with the cost of lines these days, obviously saving a WHOLE line _IS_ worth all of the obfuscation in the world. Alex PS: I did think about inserting smilies, but I think colons and closed parentheses are going up in price, too, so, in the same spirit as the saving-one-line above, I decided I'd better not. From P at draigBrady.com Thu Oct 23 08:58:50 2003 From: P at draigBrady.com (P at draigBrady.com) Date: Thu, 23 Oct 2003 13:58:50 +0100 Subject: i18n pot file In-Reply-To: References: Message-ID: <3F97D08A.2070104@draigBrady.com> anabell wrote: >>>>Then your PO file likely isn't in UTF-8. You need to find out what > > encoding your computer uses. As a starting point, you would need to > tell us what operation system you use, and what "locale" you have > activated on that system > > I reloaded my IDE, and everything is working as expected. I use Charset > iso-8859-1 and Transfer Encoding 8bit. > > My "locale" is set to user's working directly which I wrote like this: > > localedir = sys.path[len(sys.path)-1] that's the same as: localedir = sys.path[-1] Hmm, maybe that does what you want (sometimes) on windos only, but I don't see how it could work. As I said privately have a look at how i18n is done in: http://www.iol.ie/~padraiga/fslint/FSlint-2.02.tar.gz In summary it supports local locale info like: if running_locally: locale_base=os.path.dirname(os.path.abspath(sys.argv[0])) locale_base+='/po/locale' else: locale_base=None #sys default P?draig. From tjreedy at udel.edu Mon Oct 6 23:08:23 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 6 Oct 2003 23:08:23 -0400 Subject: Explanation of macros; Haskell macros References: Message-ID: wrote in message news:GGDUFQOGIAD5H2L3GDEKNREOMFKFLREPEFD3MGCP at ziplip.com... > enough memory). In Lisp, you can acomplish this with the > following macro: I presume this is specifically Common Lisp [ for i in seq example ] > Let me know if the above helped you understand the usefulness > of macros or was just as sucky as the earlier stuff. Yes, I understood even though I am not familiar with the ` , & and @ prefixes. Terry J. Reedy From tim.ronning at start.no Tue Oct 28 10:02:59 2003 From: tim.ronning at start.no (Tim Ronning) Date: Tue, 28 Oct 2003 16:02:59 +0100 Subject: Is it any good? Message-ID: Thanks everyone for the book advice. I think I'll take Simon Foster's advice and wait until december for the 2. ed. of O'Reilly's "Learning Python" BTW Alan Gauld. I'm using your tutorial which I found on the net and I want to give you credit for a really good tutorial. FAr from all tutorials have the same standard as yours. Best regards Tim Ronning -- Using M2, Opera's revolutionary e-mail client: http://www.opera.com/m2/ From dan at cgl.ucsf.edu Mon Oct 13 21:40:41 2003 From: dan at cgl.ucsf.edu (Daniel Greenblatt) Date: 13 Oct 2003 18:40:41 -0700 Subject: SocketServer.py on win32 Message-ID: <250e449e.0310131740.5d10749@posting.google.com> Has anyone used the SocketServer.py module successfully on windows? I don't know if I'm doing something terribly wrong, here but I use a SocketServer in my app, running it in a seperate thread, and get very finnicky behavior on my windows XP machine (while the code runs fine on other *nix platforms). Sometimes my app freezes as soon as the socketserver thread is started, other times it is freezes once it receives a connection. Any help would be greatly appreciated. I.e. is it my code, or just one of those windows things? If it is a win. thing, are there any reasonable workarounds? Thanks in advance, Dan Greenblatt From tjreedy at udel.edu Thu Oct 9 18:24:44 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 9 Oct 2003 18:24:44 -0400 Subject: A query about list References: Message-ID: <8mednS0u2MqwfRiiU-KYiQ@comcast.com> "Dave Benjamin" wrote in message news:slrnbobkr7.io6.ramen at lackingtalent.com... > This *seems* to work, but I have a sneaking feeling there's a bug in here as > a result of the slice assignment. I haven't been able to find a boundary > case that breaks this, but it seems like the slice assignment would mess up > the indexes in the loop. Can anyone find a way to either break or improve > this? I believe enumerate is a generator which makes one pair at a time, as needed. If so, then you are iterating over inserted items after the first, which may or may not be what is wanted. I believe an empty sublist would be deleted, shifting remainder to left and skipping next item. Try [1, [], [2,3,5]] and also [[[1,2],3], [4,[5,6]]] > >>> a = [1, [2, 3, 4], 5, 6, 7, [8, 9, 10], 11, 12] > >>> def flatten_sublists(lst): > ... for i, item in enumerate(lst): > ... if type(item) is type([]): > ... lst[i:i+1] = lst[i] > ... > >>> flatten_sublists(a) > >>> a > [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] If my hypothesis is correct, I might rewrite with while i loop to either iterate over either all (for multilevel flatten) or none (for two-level flatten) of inserted items. Terry J. Reedy From dsilva at ccs.neu.edu Sun Oct 12 21:49:46 2003 From: dsilva at ccs.neu.edu (Daniel P. M. Silva) Date: Sun, 12 Oct 2003 21:49:46 -0400 Subject: Python syntax in Lisp and Scheme References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> <6CZgb.3273$dn6.860@newsread4.news.pas.earthlink.net> <%hihb.4368$dn6.2921@newsread4.news.pas.earthlink.net> Message-ID: Alex Martelli wrote: > Andrew Dalke wrote: > >> Alex: >>> Yeah, well, I fear the answer will be yes (it could), but it won't >>> do so since you haven't _asked_ it to wake you up, only if it >>> could. >> >> Pshaw. My hypothetical house of the 2050s or so will know >> that "could" in this context is a command. :) > > Good luck the first time you want to ask it about its capabilities, > and my best wishes that you'll remember to use VERY precise > phrasing then. > Hehe, I hope I never scream "NAMESPACE-MAPPED-SYMBOLS" at my house :P - DS From jkratz1 at hotmail.com Tue Oct 21 15:23:33 2003 From: jkratz1 at hotmail.com (Jason Kratz) Date: Tue, 21 Oct 2003 14:23:33 -0500 Subject: wxPython: wxStaticBox border question References: Message-ID: Boy do I feel stupid. It turns out that the group boxes in Win XP look like crap by default and wxWindows is picking that up of course ;) Jason "Jason Kratz" wrote in message news:bn40ib$2gg$1 at flood.xnet.com... > I was expecting that a wxStaticBox with a sunken border would look (on > Windows) like a line etched into the surface of the dialog/window. However > it only draws a gray line regardless of what I set. Is that how the > wxStaticBox is supposed to work? Is there any way to get the etched look? > > Thanks, > > Jason > > From klapotec at chello.at Thu Oct 2 11:13:33 2003 From: klapotec at chello.at (Christopher Koppler) Date: Thu, 02 Oct 2003 15:13:33 GMT Subject: python can't count! References: <62e9c66e.0310020702.7d0e02b7@posting.google.com> Message-ID: <00gonvs9hno316h12dgg3q8qbn7g6jcbcs@4ax.com> On 2 Oct 2003 08:02:48 -0700, dokaspar at student.ethz.ch (Dominik Kaspar) wrote: >hello > >i'm wondering if i'm just too stupid for python or if i've missed >something fundamentally important of its semantics. >Why does the following program result in the TypeError: print_it() >takes exactly 1 argument (2 given)? >I don't see any function passing or receiving 2 arguments here... am i >blind? > >import threading > >class Server(threading.Thread): > def print_it(n): > print n > > def run(self): > self.print_it(34) > while 1: > pass > >s = Server() >s.start() You're calling print_it as an instance method, and thus should have def'd it as print_it(self, n) --Christopher From ville.spammehardvainio at spamtut.fi Wed Oct 29 14:50:20 2003 From: ville.spammehardvainio at spamtut.fi (Ville Vainio) Date: 29 Oct 2003 21:50:20 +0200 Subject: getopt, i don't get it References: <62e9c66e.0310281136.2248099b@posting.google.com> Message-ID: dokaspar at student.ethz.ch (Dominik Kaspar) writes: > I tried to use getopt and copied the example from: > http://www.python.org/doc/current/lib/module-getopt.html If you haven't used getopt before, don't start now. Check out optparse instead. -- Ville Vainio http://www.students.tut.fi/~vainio24 From mertz at gnosis.cx Thu Oct 9 14:13:51 2003 From: mertz at gnosis.cx (David Mertz) Date: Thu, 09 Oct 2003 14:13:51 -0400 Subject: Books to give to Readers References: Message-ID: I get a lot of books as an author/reviewer. In fact, you can find my reviews of most of these, easily enough. The side effect is that my shelves have a lot of books that I'm not realistically going to look at anymore. I would be very happy to send the below titles to anyone who will pay for shipping (maybe a buck or two extra for my effort). Most of these are listed on TextbookX.com too (for little cost), but for a long time without buyers. Of course, some books I like better than others; I kinda hate to get someone started on a book that isn't as good, even for free... and most of them have at least some merit: Jython Essentials Jython for Java Programmers Python Manual Pages (Dossier Press, no ISBN) Python Library Reference (ditto) Python Miscellanea (ditto) XML Pocket Guide (x2) Python Pocket Reference (1st and 2nd ed) Python Programming on Win32 Perl 5 Howto Python Programming Patterns Core Python Programming Web Programming in PYthon Visual Quickstart Guide Python The Quick Python Book The Zope Book Zope Web Application Development and Content Management Python and Tkinter GUI Programming with Python: Using the QT Toolkit Programming with Python Java Developer's Guid to Servlets and JSP MySQL (A! Press) MySQL: Building User Interfaces Well, those are just the ones I can see from my chair (I throw in a couple that are not Python). I probably have a few more if I were to walk to the next room :-). Email me if interested. Yours, David... -- mertz@ _/_/_/_/ THIS MESSAGE WAS BROUGHT TO YOU BY: \_\_\_\_ n o gnosis _/_/ Postmodern Enterprises \_\_ .cx _/_/ \_\_ d o _/_/_/ IN A WORLD W/O WALLS, THERE WOULD BE NO GATES \_\_\_ z e From liam at tiora.net Mon Oct 6 17:55:02 2003 From: liam at tiora.net (Liam Slusser) Date: Mon, 6 Oct 2003 14:55:02 -0700 Subject: socketserver and postgres Message-ID: <01ff01c38c54$803711a0$6400a8c0@zipper> Im having a really weird problem with socketserver and postgres. Here is my setup... Sun Netra T105 Sun Solaris 8 Generic_108528-23 Postgres 7.3.4 (also tried 7.3.2 same problem) Python 2.3.2 (ive also tried 2.3 same problem) psycopg (python postgres API) 1.1.9 (ive also tried pypgsql 2.4 with the same problem) It seems when i do a select of something that is large in size in the postgres database it crashs when using socketserver. However i remove the socketserver part and it runs great. Here is the code im using... DSN = 'dbname=mydb user=dbuser' import SocketServer import psycopg dbconn = psycopg.connect(DSN) class popSession(SocketServer.StreamRequestHandler): "handles the pop session" def handle(self): db = dbconn.cursor() message_idnr = 1473 msg="" db.execute("select messageblk from messageblks where message_idnr=%d and body_msg=1" % (m essage_idnr)) msg = db.fetchone()[0] #print msg self.wfile.write(msg) SocketServer.ThreadingTCPServer.allow_reuse_address = 1 SocketServer.StreamRequestHandler.rbufsize = 0 server = SocketServer.ThreadingTCPServer(("", 8003), popSession) server.serve_forever() This code works great..but once it gets to a large result set it crashs. I can go into postgres and change messageblk (id 1473) to say "123 im here" and then run the same code over and it works perfect. The error message i get is: ---------------------------------------- Exception happened during processing of request from ('127.0.0.1', 32771) Traceback (most recent call last): File "/usr/local/lib/python2.3/SocketServer.py", line 463, in process_request_thread self.finish_request(request, client_address) File "/usr/local/lib/python2.3/SocketServer.py", line 254, in finish_request self.RequestHandlerClass(request, client_address, self) File "/usr/local/lib/python2.3/SocketServer.py", line 521, in __init__ self.handle() File "tt.py", line 32, in handle db.execute("select messageblk from messageblks where message_idnr=%d and body_msg=1" % (message_idnr)) ProgrammingError: could not receive data from server: No such file or directory select messageblk from messageblks where message_idnr=1473 and body_msg=1 ---------------------------------------- My first thought was something was messed up with psycopg, so i changed the code to use pypgsql. It does the same thing!!!!! Here is that error message... Exception happened during processing of request from ('127.0.0.1', 32772) Traceback (most recent call last): File "/usr/local/lib/python2.3/SocketServer.py", line 463, in process_request_thread self.finish_request(request, client_address) File "/usr/local/lib/python2.3/SocketServer.py", line 254, in finish_request self.RequestHandlerClass(request, client_address, self) File "/usr/local/lib/python2.3/SocketServer.py", line 521, in __init__ self.handle() File "ttt.py", line 34, in handle db.execute("select messageblk from messageblks where message_idnr=%d and body_msg=1" % (message_idnr)) File "/usr/local/lib/python2.3/site-packages/pyPgSQL/PgSQL.py", line 3091, in execute self.res = self.conn.conn.query('FETCH 1 FROM "%s"' % self.name) OperationalError: could not receive data from server: Error 0 ---------------------------------------- So heres the funny part though. I remove socketserver from the code and it works perfect. This code works great... DSN = 'dbname=mydb user=dbuser' import psycopg dbconn = psycopg.connect(DSN) db = dbconn.cursor() message_idnr = 1473 msg="" db.execute("select messageblk from messageblks where message_idnr=%d and body_msg=1" % (message_idnr)) msg = db.fetchone()[0] print msg That code works perfect. Prints out messageblk just like it suppost to. Why does it break once i use socketserver? thanks, liam From nomail at nomail.com Mon Oct 27 10:14:38 2003 From: nomail at nomail.com (Michael Schmitt) Date: Mon, 27 Oct 2003 16:14:38 +0100 Subject: Redirecting stdio for extension function (again) Message-ID: Hello. I wanted to capture the stdout output of a called extension function. Michael Hudson kindly suggested a way to redirect filedescriptors. I still can't get this working: fd_stdout= os.dup(1) def outputOff(): nsofd = os.dup(1) nso = os.fdopen(nsofd, 'w') sys.stdout = nso dnfd = os.open('/dev/null', os.O_WRONLY) os.close(1) os.dup2(dnfd, 1) os.close(dnfd) def outputOn(): os.close(1) os.dup2(fd_stdout, 1) this is used as: outputOff() call_to_extensionfunction() outputOn() Calling outputOn() seems to write the previously redirected output to the screen again. So it seems to be buffered. I played a bit with ftruncate, but have no idea yet, how to discard the buffered output. I think I still didn't really get the details of file descriptors. Thanks for any hints. Michael From jjl at pobox.com Wed Oct 8 18:28:40 2003 From: jjl at pobox.com (John J. Lee) Date: 08 Oct 2003 23:28:40 +0100 Subject: Book Recommendation References: Message-ID: <87k77fmkiv.fsf@pobox.com> Anthony writes: > Hello I'm currently trying to read Core Python Programming, but by the [...] > any of you ever read it? is it a good book? if not what do you suggest i > read. Please help me i'm eager to learn :) No idea about Core PP, but I can certainly say that the Python Cookbook is good. Other people have said good things about the Nutshell (both books are published by O'Reilly). Apparently you can read these free for a month by signing up for O'Reilly's Safari service, then canceling. John From sunking77 at hotmail.com Fri Oct 31 17:08:26 2003 From: sunking77 at hotmail.com (Ray) Date: Fri, 31 Oct 2003 14:08:26 -0800 Subject: Py2exe invalid syntax???/i hate distutils Message-ID: <000001c39ffb$823b2df0$041ad20c@computer> Python setup.py install No still getting "invalid syntax" -------------- next part -------------- An HTML attachment was scrubbed... URL: From joachim.durchholz at web.de Wed Oct 29 09:58:44 2003 From: joachim.durchholz at web.de (Joachim Durchholz) Date: Wed, 29 Oct 2003 15:58:44 +0100 Subject: Python from Wise Guy's Viewpoint In-Reply-To: References: <3F9D5D21.2060408@ps.uni-sb.de> <20031027184024.GO1454@mapcar.org> <20031028093713.GQ1454@mapcar.org> <20031029085604.GU1454@mapcar.org> Message-ID: Espen Vestre wrote: > Now you're conflating two readings of "want declarations" (i.e. "want > them whenever they're convenient for optimizing" vs. "want them > everywhere and always") Type inference is about "as much static checking as possible with as little annotations as absolutely necessary". HM typing is extremely far on the "few declarations" side: a handful even in large systems. It sounds unbelievable, but it really works. Oh, there's one catch: Most functional programs have heaps of type definitions similar to this one: Tree a = Leaf a | Node (Tree a) (Tree a) | Empty However, these definitions don't only declare the type, they also introduce constructors, which also serve as inspectors for pattern matching. In other words, the above code is all that's needed to allow me to construct arbitrary values of the new type (gratuitious angle brackets inserts to make the code easier to recognize with a C++ background), like this: Leaf 5 -- Creates a Leaf object that contains value 5 Node Empty Empty -- Creates a node that doesn't have leaves -- Type is Tree , i.e. we can insert this object into -- a tree of any type, since there's no way that this can ever -- lead to type errors. Node (Leaf 5) (Leaf 6) -- Creates a node with two leaves It also allows me to use the constructor names as tags for pattern matching. Note that every one of the following three definitions consists of the name of the function being defined, a pattern that the arguments must follow to select this particular definition, and the actual function body (which is just an expression here). Calling a function with parameters that match neither pattern is considered an error (which is usually caught at compile time but not in all cases - not everything is static even in functional languages). mapTree f (Leaf foo) = Leaf f foo -- If mapTree if given a "something" called f, -- and some piece of data that was constructed using Leaf foo, -- then the result will be obtained by applying f as a function -- to that foo, and making the result a Leaf. -- The occurence of f in a function position on the right side -- makes type inference recognize it as a function. -- The Leaf pattern (and, incidentally, the use of the Leaf -- constructor on the right side) will make type inference -- recognize that the second parameter of mapTree must be -- of Tree type. Usage details will also make -- type inference conclude that f must be a function from -- one "anything" type to another, potentially different -- "anything" type. -- In other words, the type of mapTree is known to be -- (a -> b) -> Tree a -> Tree b -- without a single type declaration in mapTree's code! mapTree f (Node left right) = Node (maptree f left) (maptree f right) -- This code is structured in exact analogy to the Leaf case. -- The only difference is that it uses recursion to descend -- into the subtrees. -- Incidentally, this definition of mapTree mapTree f Empty = Empty -- The null value doesn't need to be mapped, it will look the -- same on output. -- Note that this definition of mapTree doesn't restrict the -- type of f in the least. -- In HM typing, you usually don't specify the types, every -- usage of some object adds further restrictions what that -- type can be. If the set of types that a name can have becomes -- empty, you have contradictory type usage and hence a type error. Hope this helps Jo From costanza at web.de Fri Oct 24 17:07:58 2003 From: costanza at web.de (Pascal Costanza) Date: Fri, 24 Oct 2003 23:07:58 +0200 Subject: Python from Wise Guy's Viewpoint In-Reply-To: References: <_8Ekb.7543$pT1.318@twister.nyc.rr.com> <3f972315$1@news.unimelb.edu.au> <3638acfd.0310230039.306b14f@posting.google.com> Message-ID: Marshall Spight wrote: > "Pascal Costanza" wrote in message news:bn8nhq$l04$1 at f1node01.rhrz.uni-bonn.de... > >>In a statically typed language, when I write a test case that calls a >>specific method, I need to write at least one class that implements at >>least that method, otherwise the code won't compile. >> >>In a dynamically typed language I can concentrate on writing the test >>cases first and don't need to write dummy code to make some arbitrary >>static checker happy. > > > This is a non-issue. In both cases, you need the implementing code > if you want to be able to run the testcase, and you don't need the > implementing code if you don't. No, in a dynamically typed language, I don't need the implementation to be able to run the testcase. Among other things: - the test cases can serve as a kind of todo-list. I run the testsuite, and it gives me an exception. This shows what portion of code I can work on next. - when a test case gives me an exception, I can inspect the runtime environment and analyze how far the test case got, what it already successfully did, what is missing, and maybe even why it is missing. With a statically typed language, I wouldn't be able to get that far. Furthermore, when I am still in the exceptional situation, I can change variable settings, define a function on the fly, return some value from a yet undefined method by hand to see if it can make the rest of the code work, and so on. Pascal -- Pascal Costanza University of Bonn mailto:costanza at web.de Institute of Computer Science III http://www.pascalcostanza.de R?merstr. 164, D-53117 Bonn (Germany) From bogus at invalid.tld Mon Oct 6 16:01:21 2003 From: bogus at invalid.tld (Jules Dubois) Date: Mon, 6 Oct 2003 14:01:21 -0600 Subject: [Semi-OT] Re: use make and version control system for every project? (was: use make and version control system for every project?) References: Message-ID: On Mon, 06 Oct 2003 02:00:44 GMT, in article , Carl Banks wrote: > Personally, I use make on every single one of my projects. > [...] I'm just the opposite. I don't use make on personal or group Python programming projects. Would you say why you find it useful there? > Version control, it depends. > [...] I always, always, always use version control -- _Essential CVS_ calls what I'm doing "source code control", but I do it anyway. (I'm trying to learn CVS in between other high-priority processes.) > I've used CVS for some personal projects > before, and can't say I've ever found it useful, and it's definitely a > pain to keep things up-to-date. How about the old-timer RCS? > But if you don't use version control, be sure to make frequent backups Excellent advice. From jimmy at retzlaff.com Mon Oct 20 01:46:54 2003 From: jimmy at retzlaff.com (Jimmy Retzlaff) Date: Sun, 19 Oct 2003 22:46:54 -0700 Subject: [Q] ctypes callbacks with Delphi Message-ID: achrist at easystreet.com wrote: > Jimmy Retzlaff wrote: > > > > Another approach might be to spawn two > > executables, one for your wxPython windows, and another for your Delphi > > forms, and use an IPC mechanism to communicate between them. > > > > I suppose I'm now thinking that this would be the best way to go. > It looks to me like using pexpect would be much simpler than > communication through sockets or even ctypes. > > Any likely problems trying to get pexpect to let a GUI wxPython app > control a GUI Delphi app (with console) under all versions of Windows > (say Win NT, Win98 and later)? The last I heard, pexpect didn't work on Windows, but I'm certainly no expert on it. If that still holds then things like XMLRPC and SOAP might be options depending on how well they are supported on the Delphi side. XMLRPC is almost trivial in Python (see xmlrpclib). You can also use the SimpleHTTPServer module in Python and use an http client in Delphi to send strings back and forth pretty easily. All these options would also let the processes run on separate machines if that would be of any benefit in your particular application. Jimmy From anuradha.k.r at sify.com Mon Oct 20 00:56:41 2003 From: anuradha.k.r at sify.com (anuradha.k.r at sify.com) Date: 19 Oct 2003 21:56:41 -0700 Subject: server side socket program hangs References: <57efaf35.0309260215.5ddd5734@posting.google.com> <3f74571f$0$20952$7a628cd7@news.club-internet.fr> <57efaf35.0310092102.1231b120@posting.google.com> <3f8670c7$0$12567$7a628cd7@news.club-internet.fr> <57efaf35.0310132112.6ecd9840@posting.google.com> <57efaf35.0310142225.2b0fc8b4@posting.google.com> <57efaf35.0310160208.6575b8fb@posting.google.com> <9sujb.997$Z54.969@news.get2net.dk> <57efaf35.0310162021.7ac5da39@posting.google.com> Message-ID: <57efaf35.0310192056.783d8723@posting.google.com> hi, do u think there's a version problem?i am using Python 2.2 (windows 2000).is it related in any way? thanx,AKR. J?rgen Cederberg wrote in message news:... > anuradha.k.r at sify.com wrote: > > hi, > > my initial program was to take host value as ''(INADDR ANY) > > only.during my trial and error only i started using > > gethostname.however as of now i am running my client (C program) also > > from the same machine only.so it should not make any difference. > > I've reverted bac to host ''.my program still hangs.i 'v e tried > > changing the port address,but doesn't work.pls help > > thanx, > > AKR. > > Hi > > this is pretty odd. As mentioned in the previous mail, the program works > > with my client program (written in Python by the way). > > You keep saying that the programs 'hang', what do mean by that? I've > tried the program and all I can say is that it works. Are you sure that > your client works correctly? > > Regards > Jorgen > > > > > > > > J rgen Cederberg wrote in message news: > <9sujb.997$Z54.969 at news.get2net.dk>... > >> anuradha.k.r at sify.com wrote: > >> > hi, > >> > i guess no one is ready to help.neways,my problem is getting > >> > solved.I 've slightly modified program (one of the samples found in > >> > the net),now program creates socket,gives bind ,listen success.howev > er > >> > when i debug at accept it goes to the socket.py,at the accept() > >> > function definition.and one more step ahead and it hangs.i dono how > to > >> > debug here(inside socket.py). > >> > > >> > here is how the code looks like > >> > >> Hi ... > >> > >> the program actually works - but there is a quirk, look below for deta > ils. > >> > >> > > >> > //////////////// > >> > from socket import * > >> > import sys > >> > > >> > try: > >> > s= socket(AF INET,SOCK STREAM) > >> > print 'socket created' > >> > except error: > >> > print 'socket not created' > >> > host = '' > >> > port = 9323 > >> > try: > >> > s.bind((gethostname(),port)) > >> > >> You are binding the socket to the hostname of your computer, instead o > f > >> ''. Thus it will only accept connections specific to the hostname and > > >> therefor fail if you try to connect to localhost or 127.0.0.1 > >> > >> > >> > print 'bind success' > >> > except error: > >> > print 'bind' > >> > try: > >> > s.listen(1) > >> > print 'listen success' > >> > except error: > >> > print 'listen' > >> > > >> > conn,addr = s.accept() > >> > print 'client is at ', addr > >> > data = conn.recv(1024) > >> > conn.send(data) > >> > conn.close() > >> > //////////////////////// > >> > but i have a feeling that teher's some problem with the port or > >> > some problem in the program that it hangs.can anyone help?or atleast > > >> > give me few links where i can find a solution,thanx. > >> > AKR. > >> > >> > >> Hope this helps > >> Jorgen From adalke at mindspring.com Fri Oct 3 10:20:59 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Fri, 03 Oct 2003 14:20:59 GMT Subject: GIL in the new glossary References: <9fc58c06.0310020937.457e36d5@posting.google.com> <3F7D5775.3CC05960@hotmail.com> Message-ID: Alan Kennedy: > The amount of loud complaining and misinformation that originates from > people who have just found out about the GIL is inversely proportional > to the amount of factual knowledge that they have about the GIL. Consider the statement The amount of loud complaining and misinformation ... about X is inversely proportional to the amount of factual knowledge ... about X Isn't that generally true, even when X != GIL? I know I've contributed my own share of complaining and misinformation when I'm just starting to learn an API. Andrew dalke at dalkescientific.com From wilkSPAM at OUTflibuste.net Mon Oct 20 05:13:33 2003 From: wilkSPAM at OUTflibuste.net (Wilk) Date: Mon, 20 Oct 2003 11:13:33 +0200 Subject: Alternatives to WebUnit References: Message-ID: <87k7709sqq.fsf@blakie.riol#flibuste.net> Ben Finney writes: > Howdy all, > > In searching for tools to run automated regression tests against a Web > aplication, I found (amid a number of tools requiring non-free Java) the > WebUnit code: > > > > Unfortunately, the code is somewhat beta and doesn't seem to have been > updated since 02-Feb-2002. Does anyone know if this has been updated > since, or merged into some other project? > > Alternatively, does anyone know a (preferably Python) tool for automated > regression testing of Web apps? I use ClientForm and ClientCookies from http://wwwsearch.sourceforge.net/ -- Wilk - http://flibuste.net From jay at jaydorsey.com Thu Oct 2 11:21:30 2003 From: jay at jaydorsey.com (Jay Dorsey) Date: Thu, 02 Oct 2003 10:21:30 -0500 Subject: How To Check For [a-z] In String? In-Reply-To: References: Message-ID: <3F7C427A.2000700@jaydorsey.com> Hank Kingwood wrote: > Also, how would I check if [a-z] is not in a string? following my re examples: >>> import re >>> regex = re.compile('[^a-z]') >>> if regex.search('123123123132'): print "no lower letters!" ... no lower letters! There is a good regular expression tutorial on http://www.amk.ca/python/howto/regex/ jay From tjreedy at udel.edu Sat Oct 18 18:00:43 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 18 Oct 2003 18:00:43 -0400 Subject: [OT] Knuth's rewards [Was: Python syntax in Lisp and Scheme] References: Message-ID: For more about Knuth: his home page is http://www-cs-faculty.stanford.edu/~knuth/index.html From mertz at gnosis.cx Mon Oct 20 14:52:18 2003 From: mertz at gnosis.cx (Lulu of the Lotus-Eaters) Date: Mon, 20 Oct 2003 14:52:18 -0400 Subject: Why don't people like lisp? References: <3f9302d7.170372828@news.eircom.net> Message-ID: Pascal Costanza wrote previously: |Wouldn't it be better if everyone could contribute to the evolution of a |language, and then let the community decide what the best approaches are? I can think of almost nothing worse than this! Well, "design-by-committee" results like XSLT are even worse. But the "benevolent dictator" model is VASTLY better than the "let 1000 flowers bloom" approach. Incidentally, I have never seen--and expect never to see--some new mysterious domain where Python is too limited because the designers did not forsee the problem area. Nor similarly with other very high level languages. It NEVER happens that you just cannot solve a problem because of the lack of some novel syntax to do so... that's what libraries are for. Yours, Lulu... -- Keeping medicines from the bloodstreams of the sick; food from the bellies of the hungry; books from the hands of the uneducated; technology from the underdeveloped; and putting advocates of freedom in prisons. Intellectual property is to the 21st century what the slave trade was to the 16th. From aleax at aleax.it Sat Oct 18 07:08:28 2003 From: aleax at aleax.it (Alex Martelli) Date: Sat, 18 Oct 2003 11:08:28 GMT Subject: printf "fails" in extension References: <73b00f0c.0310171158.4c05317a@posting.google.com> Message-ID: Robert Ferrell wrote: > I'm trying to "extend" Python by writing a bit of C code. I followed > the example in the Python documentation, and almost everything works > fine. I can build a DLL, fire up an interactive Python session and > import my new module. Methods work almost as expected. > > The only problem I'm having is that I can't print to the screen from > the C code. Printing to a file works fine, but neither printf nor > fprintf(stdout,...) puts anything onto the screen. > > I'm working in Windows2K, using Python2.3. Is there some trick to get > this to work? I'm wondering if this is a compiler issue (I'm building > the DLL using an Absoft compiler). I googled around looking for > relevant information, but I didn't find any. Perhaps I didn't have > the right key words? This may well be the case. Python doesn't necessarily have much to do with it: it IS a question of EXE and DLL on Windows needing to share the _same_ stdio infrastructure -- basically, the same instance of the same runtime libraries. Tricky enough when you build EXE and DLL with the same compiler, because even then you need to ensure they're using a version of the C runtime that lives _in yet another DLL_ -- and it must be the same, not e.g. one optimized and the other built for debug instead -- any static linking of the runtime on either or both sides and you're hosed. Even trickier with different compilers, unless one is specifically built to use the C runtime DLL's from the other -- mingw32 being an example (it's built to use MSVCRT.DLL, Microsoft's DLL version of the C runtime libraries). This is a well-known issue among experts of C compilers on Windows -- particularly ones who have ever had the totally harrowing experience of having to mix code built by multiple compilers, but not exclusively, because even using e.g MSVC++ 6 throughout is still tricky due to the possibility of different C runtime library instances being used by different modules (in the Windows sense: each EXE or DLL is a module). How to manage to google for it may be a different issue, particularly as the workaround (if any) will depend on your "Absoft compiler". I can however suggest to skip Python in your searches, because it's not in the picture: what you need to find out is, how (if at all) is it possible to use your compiler to write a DLL which, used from a MSVC++ - made EXE, is able to do normal output to stdout or stderr. Alex From brian094 at sympatico.ca Sun Oct 26 21:48:01 2003 From: brian094 at sympatico.ca (Brian Alexander) Date: Sun, 26 Oct 2003 21:48:01 -0500 Subject: variables with loop-local scope? References: <3F9AF2EE.5090702@sympatico.ca> Message-ID: <3F9C8761.70501@sympatico.ca> Skip Montanaro wrote: >>>>>>"Brian" == Brian Alexander writes: >>>>> > > Brian> Can Python do this? > > Sure: > > for i in listOfNames: > prefixMr = 'Mr' > prefixMs = 'Ms' > if i in mansName: > salutation = prefixMr + i > else: > salutation = prefixMs + i > else: > del prefixMr > del prefixMs > > print 'Hello,' + salutation > > Probably not quite what you wanted. Is there a reason you need/want the > variable to disappear before the function returns? > > Skip > Yes, it seems this is one way of doing it. The reason I was interested is that it can reduce worries in a procedure that may have many local variables. A large number of locals with very limited (sub-procedural) scope is better than a large number of locals with procedural scope. (Of course, having few locals is best of all.) Brian. From adalke at mindspring.com Thu Oct 23 00:02:32 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Thu, 23 Oct 2003 04:02:32 GMT Subject: Python from Wise Guy's Viewpoint References: <_8Ekb.7543$pT1.318@twister.nyc.rr.com> Message-ID: Pascal Costanza: > The set of programs that are useful but cannot be checked by a static > type system is by definition bigger than the set of useful programs that > can be statically checked. So dynamically typed languages allow me to > express more useful programs than statically typed languages. Ummm, both are infinite and both are countably infinite, so those sets are the same size. You're falling for Hilbert's Paradox. Also, while I don't know a proof, I'm pretty sure that type inferencing can do addition (and theorem proving) so is equal in power to programming. > I don't need a study for that statement because it's a simple argument: > if the language doesn't allow me to express something in a direct way, > but requires me to write considerably more code then I have considerably > more opportunities for making mistakes. The size comparisons I've seen (like the great programming language shootout) suggest that Ocaml and Scheme require about the same amount of code to solve small problems. Yet last I saw, Ocaml is strongly typed at compile time. How do you assume then that strongly&statically typed languages require "considerable more code"? Andrew dalke at dalkescientific.com From pythonguy at Hotpop.com Mon Oct 27 01:40:32 2003 From: pythonguy at Hotpop.com (Anand Pillai) Date: 26 Oct 2003 22:40:32 -0800 Subject: Cookie Module References: <5b04353b.0310230357.4d032e95@posting.google.com> <871xt3q116.fsf@pobox.com> Message-ID: <84fc4588.0310262240.1570892c@posting.google.com> It is him alright, and I maintain HarvestMan, (Capital 'H', Capital 'M'). But I dont think Nirmal is masochist, not in any way. I dont understand why you called him "masochist". The reason why we wrote our own cookie handling module using python's Cookie module was that, the ClientCookie module was doing too many things, which we wanted to avoid. ClientCookie is exactly what it says, it is a module that acts as a webclient apart from managing cookies. The ClientCookie module borrows the methods of urllib2 like urlopen() and manages cookies under the covers, so to say. Good design, no doubt but not what we wanted. ClientCookie is something like a wrapper over urllib2 plus cookie handling. We wanted a module, which works *with* urllib2 and does not wrap over it. With all due respect to CC, it cannot be modified in a way to do that, withou writing klunky code, which I did not want. Hence nirmal read the RFCs for cookie handling and implemented a module which works *along with* urllib2 rather than wrapping over it. The module need special calls to set the cookie which is part of the harvestman code(in another module), so in a way it is much inferior to client cookie, which does it transparently. Nirmal is talking about RFCs because we want to have a very correct technical cookie implementation for our module, no matter what web servers does in their wheels and geats. I know that the SetCookie2 method uses latest cookie RFC, which almost no webserver supports, but still the question should be taken in a spirit of technical correctness. Yeah it has an academic quality to it, not of much pratical use maybe right now, but I cannot understand how it makes the guy a masochist. -Anand Pillai jjl at pobox.com (John J. Lee) wrote in message news:<871xt3q116.fsf at pobox.com>... > nirmalkannan at hotmail.com (N.K) writes: > > > Python's existing cookie module doesnt supports new cookie headers > > SetCookie2 , > [...] > > What do you want this for? I'm curious, and I suspect you're unaware > that the RFCs on cookies are *not* the standards followed by most of > the web -- the real 'standards' aren't really written down anywhere. > > Wait a minute (my memory works slowly), didn't I write you an email > about this a while back? Are you the masochist^H^H^H^H^H^H^H^H^Hguy > who wrote some client-side cookie-handling code for a web-crawler > (called harvestman, IIRC?)? > > > John From gregm-news at toadmail.com Sun Oct 19 09:04:32 2003 From: gregm-news at toadmail.com (Greg Menke) Date: 19 Oct 2003 09:04:32 -0400 Subject: Why don't people like lisp? References: Message-ID: mike420 at ziplip.com writes: > > In fact, Lispers take pride in the obscurity of their code. It's part of the > fun of using Lisp. Proof? Recently in CLL-CLP, someone complained that most > (C/C++/Java) programmers do not know what they are doing, writing all their > code as functions that span 300+ lines. On the other hand, Joe Marshall and > someone else touted writing Lisp code that has 25+ nesting levels. Others > approved such practice. I think 25+ depth is much worse than 300+ length. > The _minimal_ example is > > ((((((((((((((((((((((((())))))))))))))))))))))))) > > I don't want to see *real* code that has 25+ depth, I'll have nightmares. > Its not as bad as you think it is. The deeply nested code is likely divided into a sequence of distinct "modules" that accumulate, use and dispense with local state as they execute. There is likely some overall state that is also manipulated, but its likely that only leads to a few of the outermost indents. An editor like Emacs will let you skip from sexp to sexp without having to count parens and indents, so you can navigate at whatever level of detail you want. If you're using an editor that cannot navigate expressions like Emacs can, then any large or deeply nested function in any language is going to be very difficult to manage. Its somewhat analagous to using a computer controlled milling machine to handle repetitive work vs using a manually operated machine to do it. Gregm From m_lehmeier at gmx.de Sat Oct 25 14:16:33 2003 From: m_lehmeier at gmx.de (Michael Lehmeier) Date: Sat, 25 Oct 2003 20:16:33 +0200 Subject: Clueless: piping between 2 non-python processes Message-ID: Hi, I have a problem. I have written a big python script with a simple passage like that: while 1 : if os.system("A | B") == 256 : sys.exit(0) A is a streaming application, B an encoding application. Both are not python. Occasionally A terminates and the command is executed again. If it is stopped by a SIGINT, os.system returns 256 and the script ends. The problem is: B can also terminate by itself. Whenever this happens, A continues to happily pipe data to a non-existant B until eternity or A stops. So I wanted to start A and B as fork, but all solutions to create a pipe between them seem to demand that at least one of the two processes is in python itself. Or maybe I just understood it wrong. So the basic problem is: - create two processes A and B - pipe from A to B - terminate A when B ends Can anybody help? Thanks! From skip at pobox.com Fri Oct 3 15:04:00 2003 From: skip at pobox.com (Skip Montanaro) Date: Fri, 3 Oct 2003 14:04:00 -0500 Subject: GIL in the new glossary In-Reply-To: References: Message-ID: <16253.51232.382678.721554@montanaro.dyndns.org> (Rearranging your note a bit...) Dave> I took a quick look at the "Extending and Embedding the Python Dave> Interpreter" document, and did not see anything about this. I don't think there is a "threading best practices for extension module authors" section. Dave> For example, are any of the following good rules to follow? Dave> - Always release the GIL before I/O operations. Dave> - Always release the GIL at the beginning of and re-acquire it at Dave> the end of any sufficiently long lasting function. I think that's roughly correct. Dave> And, conversely, is there a list of situations when it would be Dave> dangerous or counter-productive to release the GIL in an Dave> extension? That I have no idea about. As is usually the case, the Python source itself can be a good reference. I executed egrep -l 'Py_(BEGIN|END)_ALLOW_THREADS' *.c in the Modules directory and identified 22 files. Many of the modules this revealed are very heavily used (_?bsddb, cPickle, posix, socket, time) and thus most heavily studied. My guess is they probable represent a sort of "best practices" set of examples. Skip From a.schmolck at gmx.net Wed Oct 15 13:22:49 2003 From: a.schmolck at gmx.net (Alexander Schmolck) Date: 15 Oct 2003 18:22:49 +0100 Subject: Python syntax in Lisp and Scheme References: <3cea3gqq.fsf@comcast.net> <87ekxfmhhl.fsf@thalassa.informatimago.com> <1cucnY9twevVdxGiU-KYhA@comcast.com> <1eaf81aa.0310150533.265145b9@posting.google.com> Message-ID: vijayl at lycos.com (Vijay L) writes: > I don't know why you categorize it as idiocy. But I know why you don't know: > I, having no experience whatsoever with Python 'as From vze4rx4y at verizon.net Thu Oct 23 16:28:14 2003 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Thu, 23 Oct 2003 20:28:14 GMT Subject: x[i] as loop variable References: Message-ID: [Gerrit Holl] > PEP 289 says: > (Loop variables may also use constructs like x[i] or x.a; this form may be deprecated.) That was taken out of the pep because it is a distractor issue. > What is the use of this? When should I use it? In general, it should never be used unless you're trying to obfuscate your code. It is a long standing, unintended by-product of the grammar that any lvalue can be used as a loop variable. Most folks aren't aware of it and everyone is better off not knowing about it. In fact, I wish it hadn't come-up at all because someone will read about it and adopt the atrocity as their new favorite style. So, close your eyes, forget this note, and go read about something interesting and useful. Raymond Hettinger From adalke at mindspring.com Mon Oct 13 20:54:56 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Tue, 14 Oct 2003 00:54:56 GMT Subject: Speaking Python References: Message-ID: David Mertz: > So quick test, how do you say: > > def range_sum(N): > if N < 0: > return None > elif N == 1: > return 1 > else: > tot = 0 > for n in range(1,N+1): > tot += n > return tot Here's how I would say it to someone who is typing for me, given that the person knows some Python syntax and given an editor which does auto indentation -- the proverbial man-behind-the-curtains approach to speech recognition: Define a new function named range underscore sum which takes a single parameter, capital N. If n is less than 0, return none. If n is 1, return 1 otherwise start with tot equal to 0 (that's tee-oh-tee; short for the total) for n, which is lowercase n this time, in range starting at 1 and going to capital n plus 1 ... close-parens colon newline tot plus equals lower-case n backspace once return tot This depends on seeing the text as it's typed. I think if I did this over the phone I would say "if n equals equals 1" and be a bit more specific about the colons and pressing enter. Andrew dalke at dalkescientific.com From jacek.generowicz at cern.ch Fri Oct 17 09:37:26 2003 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 17 Oct 2003 15:37:26 +0200 Subject: [OT] Knuth's rewards References: <3f8fb23e$0$225$626a54ce@news.free.fr> Message-ID: Nick Efford writes: > Jacek Generowicz wrote: > > Funny, 32768 and 256 are numbers which ring very loud bells with me > > ... but inserting a "." in the middle completely suppressed this > > otherwise immediate reaction. > > > OK, so they are powers of 2, in cents ... anyone know any further > > motivation ? > > A fascination with numbers / mathematics? I meant "motivation for why those particular powers of two were chosen, whether they evolve with time, and if so, how?" From spam at magnetic-ink.dk Wed Oct 29 18:09:32 2003 From: spam at magnetic-ink.dk (Klaus Alexander Seistrup) Date: Wed, 29 Oct 2003 23:09:32 +0000 (UTC) Subject: Expanding regexps References: <3f9e1b54-8bfeff9c-e85a-4593-914e-0865d5f2afe4@news.szn.dk> Message-ID: <3fa048ac-5fee232e-82ab-488c-857f-abcc74991e04@news.szn.dk> Diez B. Roggisch wrote: >> Is there a way to "expand" simple regexps? Something along >> the lines of: > > What would you expect to be the result of this rex: > > r'a*' > > ? > > The language accepted by this is of unlimited size - where do > you stop? That's why I wrote "simple regexps", I'm fully aware that it would be very difficult to expand all possible patterns - and that's not what I need. But to answer your question, even though it was probably rhetorical, sre_parse looks at it from this angle: #v+ >>> import sre_parse >>> sre_parse.parse(r'a*') [('max_repeat', (0, 65535, [('literal', 97)]))] >>> #v- // Klaus -- ><> unselfish actions pay back better From mspight at dnai.com Thu Oct 23 00:39:31 2003 From: mspight at dnai.com (Marshall Spight) Date: Thu, 23 Oct 2003 04:39:31 GMT Subject: Python from Wise Guy's Viewpoint References: <_8Ekb.7543$pT1.318@twister.nyc.rr.com> Message-ID: <7YIlb.1697$ao4.6695@attbi_s51> "Pascal Costanza" wrote in message news:bn774d$qj3$1 at newsreader2.netcologne.de... > > > > When do programmers know better? An int is an int and a string is a > > string, and nary the twain shall be treated the same. I would rather > > ``1 + "bar"'' signal an error at compile time than at run time. > > Such code would easily be caught very soon in your unit tests. Provided you think to write such a test, and expend the effort to do so. Contrast to what happens in a statically typed language, where this is done for you automatically. Unit tests are great; I heartily endorse them. But they *cannot* do everything that static type checking can do. Likewise, static type checking *cannot* do everything unit testing can do. So again I ask, why is it either/or? Why not both? I've had *great* success building systems with comprehensive unit test suites in statically typed languages. The unit tests catch some bugs, and the static type checking catches other bugs. Marshall From bbiro at netian.com Tue Oct 14 12:23:04 2003 From: bbiro at netian.com (Bart Simpson) Date: 14 Oct 2003 09:23:04 -0700 Subject: Creating ftp account under IIS and controlling Media Service by Python? Message-ID: <10093a06.0310140823.3be18d52@posting.google.com> Hi, I would like to create/delete ftp accounts of windows IIS, and to control MS Media Service under windows 2003 by Python program. A few days ago, I found there is iisftp.vbs vb-script that can creat/delete IIS ftp account. But I've suspected the iisftp cannot configure detailed configueration. (ex. It can't configure anonymous-login and home directory permission.) Is there any python module for controlling IIS ftp account or MS Media Service, or any other way do that? Any comment about that would be helpful to me. :) Thanks! -- Y.H. Rhiu From skip at pobox.com Tue Oct 7 11:10:17 2003 From: skip at pobox.com (Skip Montanaro) Date: Tue, 7 Oct 2003 10:10:17 -0500 Subject: Python on Altix In-Reply-To: <3F82CED3.6020904@stsci.edu> References: <3F82CED3.6020904@stsci.edu> Message-ID: <16258.55129.671685.338799@montanaro.dyndns.org> You wrote: Todd> I configure Python like this: Todd> ./configure --prefix=$HOME --with-pydebug --without-threads then you jump to: Todd> But as soon as I try to run my software self-tests (for the Todd> numarray Numeric-like array package), I get this: ... then later: Todd> I've poked around with this for a few hours, but I'm not getting Todd> much out of GDB. Does anyone have any suggestions on how to get Todd> Python up and running on an Altix or how to solve this problem Todd> more generally? Maybe I'm being too pdeantic, but did Python's own test suite run successfully? You seem to be trying to run before you're walking. 32->64-bit issues do pop up from time-to-time. It's possible that the Python developers have tackled this already but that the numarray folks haven't. If you've run "make test" successfully in your Python build directory, I would imagine you've figured out "how to get Python up and running on an Altix", and that the problem lives in the numarray code. If not, you probably need to ignore numarray for the time being while you debug your basic Python configuration. At first glance, it looks like whoever wrote to the block in question got carried away and scribbled off the end of the block. You might try gdb's "watch" command to keep an eye on that address. You'll probably want to be careful when you set the watchpoint (whittle your failing test case down as small as possible, set the watchpoint as close as possible to the error) to avoid slowing your code down to an unmanageable crawl. Skip From mfranklin1 at gatwick.westerngeco.slb.com Fri Oct 24 05:47:01 2003 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Fri, 24 Oct 2003 10:47:01 +0100 Subject: How to set pythonpath in Mac OS X? In-Reply-To: <4FFFDE3B-0603-11D8-A090-00039315E356@gmx.de> References: <4FFFDE3B-0603-11D8-A090-00039315E356@gmx.de> Message-ID: <1066988821.1130.25.camel@m-franklin> On Fri, 2003-10-24 at 10:20, Eric Wichterich wrote: > Hello Pythonistas, > > I am trying to get certain (self-written) libraries imported into my > scripts using statements like > > "from library import function.py". > Is this a typo you do not need the .py on the end it should (perhaps) read: from library import function > But they are not being found. > > I think that the pythonpath-variable must be expanded to the location > to this libraries. > > But, I can't find any usable information using Google on how to set up > the pythonpath properly. > I don't even know where to look for the pythonpath-variable? > The pythonpath (or PYTHONPATH) variable is an environment variable - I'm no MAC expert but I expect there is a command you could use to show it's value... however from inside a running python program the PYTHONPATH variable is stored in sys.path and is a list of paths that python will look in for your module / package. Python 2.3 (#1, Aug 27 2003, 10:53:10) [GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-5)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> sys.path ['', '/usr/local/lib/python23.zip', '/usr/local/lib/python2.3', '/usr/local/lib/python2.3/plat-linux2', '/usr/local/lib/python2.3/lib-tk', '/usr/local/lib/python2.3/lib-dynload', '/usr/local/lib/python2.3/site-packages', '/usr/local/lib/python2.3/site-packages/PIL'] >>> A quick google on PYTHONPATH should point you towards some useful information... it is also explained in the (free, online) python tutorial http://www.python.org/doc/current/tut/node8.html#SECTION008110000000000000000 > It would be great if anyone could help me out on this? > > Thanks, > Eric Regards Martin -- Martin Franklin From oest at soetu.eu Tue Oct 14 09:22:47 2003 From: oest at soetu.eu (Carlo v. Dango) Date: Tue, 14 Oct 2003 15:22:47 +0200 Subject: how to mutate a tuple? Message-ID: Hello there. I have a function which as an argument takes a tuple and either returns that tuple or a mutated version of it. The problem is that tuples are imutable, hence I have to create a new tuple and copy the content of the old tuple to a new one. But how do I do this if I only at runtime know the size of the tuple? I wish I could pass around lists instead.. that would be so much easier, but I'm passing "*args" and "**kwargs" around so I'm not really the one deciding the use of tuples or lists ;) Am I the first one with a problem like this? I'm not able to find anything using google on this topic. Hope someone can help me ;) -Carlo v. Dango -- Using M2, Opera's revolutionary e-mail client: http://www.opera.com/m2/ From nhodgson at bigpond.net.au Mon Oct 13 05:28:30 2003 From: nhodgson at bigpond.net.au (Neil Hodgson) Date: Mon, 13 Oct 2003 09:28:30 GMT Subject: Debugging woes on python References: Message-ID: <2fuib.148658$bo1.21841@news-server.bigpond.net.au> Glenn Reed: > I could set > breakpoints by using PythonWin but I couldn't step thru the code. File | Debug |Step In (F11) works for me in PythonWin build 157. You can view variables either using the Interactive Window, or int the Watch or Stack Windows. Neil From yahoogroups at starrsrg.mailshell.com Wed Oct 22 18:49:10 2003 From: yahoogroups at starrsrg.mailshell.com (Ashley) Date: Wed, 22 Oct 2003 22:49:10 -0000 Subject: PythonCOM help needed Message-ID: I have quite a few COM servers implemented using Visual C++ 6.0 and I'm having trouble accessing all of them via Python. The problem is with the default being set to pythoncom.Empty while my servers require pythoncom.Missing. According to this article: http://mailman.pythonpros.com/pipermail/pycom-dev/1999q2/000127.html compatibility with Microsoft products requires pythoncom.Empty. I'm wondering if anyone knows how I can change my COM servers so that they no longer require me to change the makepy generated code. Thanks, Charles From ianb at colorstudy.com Mon Oct 6 14:06:00 2003 From: ianb at colorstudy.com (Ian Bicking) Date: Mon, 6 Oct 2003 13:06:00 -0500 Subject: Webware vs. PHP - performance comparision!!! In-Reply-To: <282f826a.0310060222.52f8d144@posting.google.com> Message-ID: On Monday, October 6, 2003, at 05:22 AM, Richard Shea wrote: > Last thing is just an instinctive thing can't really say why but those > first three Python based techniques differ in time by less than 1% ... > just seems a bit strange to me that they would all be quite so similar > in speed. It's actually likely that they would -- in this context both the Cheetah template and the PSP page were being compiled into a Webware servlet. The resulting code should be very similar for the three -- the only difference might be that Cheetah has a bit more overhead for variable access, but there's so little variable access that the difference could be lost in the connection overhead. -- Ian Bicking | ianb at colorstudy.com | http://blog.ianbicking.org From sluis at rci.rutgers.edu Tue Oct 28 11:16:43 2003 From: sluis at rci.rutgers.edu (Arend Sluis) Date: Tue, 28 Oct 2003 11:16:43 -0500 Subject: No model named _socket Message-ID: <3F9E966B.8090401@rci.rutgers.edu> Hi, **obligatory python newbie warning* I have been trying to install python 2.3.2 on Solaris 2.7 (SPARC). Both 'configure' and 'make' do not give problems, but 'make test' does complain: 7 tests failed: test___all__ test_logging test_mimetools test_socket test_sundry test_tempfile test_urllib2 All but test_tempfile can be traced back to the error: ImportError: No module named _socket I have been digging through the FAQ and the bug list, but I cannot find anything helpful. Any help is welcome. (I can provide more details, if necessary.) From arigo at tunes.org Sun Oct 26 14:05:18 2003 From: arigo at tunes.org (Armin Rigo) Date: Sun, 26 Oct 2003 19:05:18 +0000 Subject: Need Psyco profiling help... In-Reply-To: <20031024214940.28132.00000065@mb-m27.aol.com> References: <20031024214940.28132.00000065@mb-m27.aol.com> Message-ID: <3F9C1AEE.3020209@tunes.org> KefX wrote: > Hotshot. Well, Hotshot and Psyco don't work well together, I found out. You seem not to have thought about running Hotshot only (without Psyco) to find out where your code spends most of its time. Psyco not only isn't happy with Hotshot, but whatever results Hotshot could get are wrong because it doesn't know about machine-code-compiled functions. Also note that if the Python code has no long loop, e.g. if it is only functions that are repeatedly called by C/C++ code (with the loop in C/C++), then Psyco won't help at all, it will probably even slow things down. It can only accelerate functions that run for some time (I mean, doing at least 100 or 1000 iterations to fill some array should be ok, but if C/C++ calls your function 100 or 1000 times to fill the same array it is not). A bientot, Armin. From jjl at pobox.com Sat Oct 25 17:39:28 2003 From: jjl at pobox.com (John J. Lee) Date: 25 Oct 2003 22:39:28 +0100 Subject: Strange Hotshot problem... References: <20031024181102.26916.00000093@mb-m05.aol.com> Message-ID: <87d6cl575b.fsf@pobox.com> keflimarcvsx at aol.comNOSPAM (KefX) writes: > Hi guys! I'm still a bit of a Python newbie, but regardless I decided to embed > Python into a plugin for a freeware (closed-source) Windows music program > called Jeskola Buzz. (Man, I can't believe how many people keep telling me > "Extend Python instead!" when clearly I can't do that in this case. If somebody > here tells me this, I will explode in an appropriately gory fashion.) It's a [...] Why don't you extend Python instead? John From anuradha.k.r at sify.com Thu Oct 16 06:08:44 2003 From: anuradha.k.r at sify.com (anuradha.k.r at sify.com) Date: 16 Oct 2003 03:08:44 -0700 Subject: server side socket program hangs References: <57efaf35.0309260215.5ddd5734@posting.google.com> <3f74571f$0$20952$7a628cd7@news.club-internet.fr> <57efaf35.0310092102.1231b120@posting.google.com> <3f8670c7$0$12567$7a628cd7@news.club-internet.fr> <57efaf35.0310132112.6ecd9840@posting.google.com> <57efaf35.0310142225.2b0fc8b4@posting.google.com> Message-ID: <57efaf35.0310160208.6575b8fb@posting.google.com> hi, i guess no one is ready to help.neways,my problem is getting solved.I 've slightly modified program (one of the samples found in the net),now program creates socket,gives bind ,listen success.however when i debug at accept it goes to the socket.py,at the accept() function definition.and one more step ahead and it hangs.i dono how to debug here(inside socket.py). here is how the code looks like //////////////// from socket import * import sys try: s= socket(AF_INET,SOCK_STREAM) print 'socket created' except error: print 'socket not created' host = '' port = 9323 try: s.bind((gethostname(),port)) print 'bind success' except error: print 'bind' try: s.listen(1) print 'listen success' except error: print 'listen' conn,addr = s.accept() print 'client is at ', addr data = conn.recv(1024) conn.send(data) conn.close() //////////////////////// but i have a feeling that teher's some problem with the port or some problem in the program that it hangs.can anyone help?or atleast give me few links where i can find a solution,thanx. AKR. anuradha.k.r at sify.com wrote in message news:<57efaf35.0310142225.2b0fc8b4 at posting.google.com>... > hi, > i've posted my doubt on my server program written in python.i am not > able to communicate with any client.My server program does not even > create a socket.can someone tell me what the problem is? > thanx, > AKR > > > anuradha.k.r at sify.com wrote in message news:<57efaf35.0310132112.6ecd9840 at posting.google.com>... > > hi, > > My one problem is solved,python server no more hangs,but my main > > purpose still remains unsolved,my client is not able to establish > > connection.my client is a C program running on a windows machine.On > > running the python program,in the python shell i get this way > > >>> > > (cursor) > > > > i assumed my server is waiting for a connection,but my client did not > > connect,it failed. > > I tried debugging the python program using the step by step debug > > control.it moves till def __init__(Self,parent): > > and stops(seems to be waiting).It does not move to the next line. > > Can you tell me what is happening? and what is the problem with my > > server program?Sorry for the trouble, > > thanx > > AKR. > > > > > > > > > > > > > > > > > > > > "Anthony McDonald" wrote in message news:<3f8670c7$0$12567$7a628cd7 at news.club-internet.fr>... > > > wrote in message > > > news:57efaf35.0310092102.1231b120 at posting.google.com... > > > > hi, > > > > was stuck with another work.now bac to python program. > > > > i tried out using > > > > PORT = socket.htons(9999) > > > > > > > > it still doesn't work.here is the code.it still hangs.can some one > > > > tell me what could be te problem? > > > > > > > > #from socket import * > > > > import socket > > > > import sys > > > > > > > > HOST = '' #any address > > > > PORT = socket.htons(9222) #same port address as client > > > > > > > > class Sock: > > > > def __init__ (self,parent): > > > > try: > > > > self.s = socket(AF_INET,SOCK_STREAM) > > > > except socket.error: > > > > print 'socket not created' > > > > try: > > > > self.s.bind((HOST,PORT)) > > > > except self.error: > > > > print 'error in bind' > > > > try: > > > > self.s.listen(5) > > > > except self.error: > > > > print 'error in listen' > > > > conn, addr = self.s.accept() > > > > # print 'Connected by',`addr` > > > > while 1: > > > > data = conn.recv(1024) > > > > if not data: break > > > > conn.send(data) > > > > conn.close() > > > > > > > > thanx, > > > > AKR. > > > > > > > Sorry for my brief answer last time, but I had hoped the code fragment I > > > posted would explain what was happening with your code. > > > > > > Your code is almost a verbatum copy of the Python example, except you've > > > chosen to massage the port value using the HTONS function. So for most > > > architectures the port value 9999 or 9222 would be changed to somewhere in > > > the 3xxx port range. Any client trying to connect on those ports will fail. > > > Hence you noted success on a C server which isn't using that function, but > > > failure on your Python server which is. The solution is to just assign the > > > port value you want unchanged. From aleaxit at yahoo.com Sat Oct 11 12:44:07 2003 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 11 Oct 2003 16:44:07 GMT Subject: Python syntax in Lisp and Scheme References: <8CVgb.8$KR3.1846@typhoon.nyu.edu> <87brspzsg3.fsf@thalassa.informatimago.com> <7k3c4r0i.fsf@comcast.net> Message-ID: prunesquallor at comcast.net wrote: ... >>> A single web browser? >> >> I far prefer to have on my cellphone one that's specialized for its small >> screen and puny cpu/memory, and on more powerful computers, more >> powerful browsers. Don't you? > > Cellphone? Why on earth would I want one of those? Why would you want a cellphone, or why would you want a browser on it? As for the former, many people I know first got their cellphones because their parents were old and sick, and they wanted to be sure their parents could immediately get in touch with them in case of need. Of course, not knowing you at all, I can't tell whether you're an orphan, or have parents who are young and healthy, or don't care a whit about their being able to reach you -- whatever. Once you do have a cellphone for whatever reason, why not get more use out of it? Checking whether reports for wherever you're traveling to, etc, etc -- a browser's a decent way to do many such things. >>> A single operating system? >> >> On my cellphone all the way to the datacenter? > > A cellphone with an OS?! The phone I use is implemented > with *wires*. Forget cellphones then, and let's check if we DO want a single operating system over a huge range of computers serving enormously different tasks, as Microsoft is so keen to tell us, or not. What do I want of the OS running my firewall? Security, security, security. It's nice if it can run on very scant resources, offers solid and usable packet filtering, and has good, secure device drivers available for the kind of devices I may want in a computer dedicated to firewalling -- all sorts of ethernet cards, wifi thingies, pppoe and plain old ppp on ISDN for emergency fallback if cable service goes down, UPS boxes, a serial console of course, perhaps various storage devices, and that's about it. I see no reason why I should use anything but OpenBSD for that. Right now I'm running it, for a LAN of half a dozen desktops and 2-5 laptops, on an old scavenged Pentium-75, 32MB RAM, 1GB disk ISA machine, and it's got so many resources to spare that I ended up running services aplently on it too (DHCP, DNS, ntp, Squid for proxying, ...). What do I want of the OS running my desktop? Resources are not a real problem, since throwing CPU cycles, RAM, and disk at it is so dirt-cheap. Some security, just enough to avoid most of the pesky worms and viruses going around. Lots and LOTS of apps, and lots and LOTS of drivers for all sort of cool devices for video, audio, and the like. Linux is pretty good there, though I understand Windows can be useful sometimes (drivers aren't yet available for _every_thing under Linux) even though security is awful there, and MacOS/X would be cool was it not for HW cost. For a small server? Resources should not be eaten up by the OS but available for serving the rest of the LAN -- lots of free server-side apps & proxies -- security important, device drivers so-so -- I can see either Linux, OpenBSD, or FreeBSD being chosen there. A LARGE server, were I to need one? A Linux cluster, or an IBM mainframe able to run Linux at need on virtual machines, sound better then. A laptop? A palmtop? Linux may cover some of those (I do enjoy it on my Zaurus) but is really too demanding for the cheapest palmtops -- and I still can't get good sleep (as opposed to hybernate) from it on laptops with ACPI. What about the several computers in my car? They play very specialized roles and would get NO advantages from general-purpose OS's -- and on the other hand, most of them REALLY need hard real-time OS's to do their jobs. I think not even MS tries to push Windows into most of THOSE computers -- it would be just too crazy even for them. So, in practice, I'd never go with the same OS on ALL computers. What is most needed on computers playing such widely different roles is just too different: an OS trying to cover ALL bases would be so huge, complicated and unwieldy that its security AND general bugginess would suck (please notice that Windows is the only OS really trying, even though not really on anywhere near the WHOLE gamut -- with Linux admittedly close behind;-). Alex From aleax at aleax.it Wed Oct 15 06:13:17 2003 From: aleax at aleax.it (Alex Martelli) Date: Wed, 15 Oct 2003 10:13:17 GMT Subject: XML-RPC, SOAP, and data persistence References: Message-ID: <159jb.286359$R32.9437022@news2.tin.it> Mark Carter wrote: > "A.M. Kuchling" wrote in message >> No, SOAP doesn't address persistence any more than XML-RPC does; both >> implement remote procedure calls with more or fewer bells and whistles. >> SOAP has the additional disadvantage that the spec is very complicated, >> making it hard for Python implementations to be up-to-date. > > Thanks. I once saw a thick book on XML at the office, but soon put it > back as there was an aweful lot to it. But looking at XML-RPC, I saw > how easy it was to implement RPCs. It's so fuss-free and generic that > its difficult to imagine wanting to use any other mechanism. > > Kinda makes you wonder what the whole point of .Net is. It hinges first around MSIL, a bytecode similar to the Java's VM but with some enhancements to make it more suitable for "ahead-of-time" (installation time) compilation to machine code, as well as for some slightly less-traditional languages (e.g., tail-recursion optimization for Scheme and many other such languages); secondly around the CRL, Common Runtime Library, and many other libraries (for windowing, both local and on-net; database access; etc, etc) extending it; thirdly around web services (centered on the more ambitious SOAP protocol as "designed-by-committee" richer successor of XML-RPC); and keeps layering on top of this. FWIW, I do agree that SOAP is much more complicated than XML-RPC, and that this is an important disadvantage, but no doubt the vast committee (of which MS was but a part) could not reach any agreement for simpler things -- it IS harder to make something "so simple it obviously has no deficiencies", so it ends up instead being "so complicated it has no obvious deficiencies", as Hoare put it -- and this goes double with design-by-committee. ".NET" is a huge, vastly layered (and sometimes not WELL layered) blob of things kept together first and foremost by marketing needs (but is J2EE really ALL that different in this respect...?-). Using SOAP instead of XML-RPC is a drop in the .NET ocean, IMHO. Alex From junkie.dolphin at NOSPAMlibero.it Mon Oct 6 15:37:56 2003 From: junkie.dolphin at NOSPAMlibero.it (Junkie Dolphin) Date: Mon, 06 Oct 2003 19:37:56 GMT Subject: [Numpy]Can't make fromfunction() work Message-ID: <20031006213723.74c296cd.junkie.dolphin@NOSPAMlibero.it> Hi, I'm trying this piece of code, but y returns as a float. x and e are created regulary. I'm a beginner with this amazing language, and haven't read (all) the fucking manual yet (shame on me!). If someone used with Numeric could give me an hint I would be very glad.. Thank you! =) from Numeric import *; G = 200. N = 15. def abscissa(i): return i/N def ordinate(i): x = i/N if (0.<=x) & (x<0.3): return 0. elif (0.3<=x) & (x<=0.35): return 20.*x-6. elif (0.35 bash-2.05b$ -- Ciao, Giovanni aka Junkie Dolphin Political language...is designed to make lies sound truthful and murder respectable, and to give an appearance of solidity to pure wind. George Orwell From mk at net.mail.penguinista Thu Oct 2 17:37:16 2003 From: mk at net.mail.penguinista (=?UTF-8?B?0LTQsNC80ZjQsNC9INCzLg==?=) Date: Thu, 02 Oct 2003 23:37:16 +0200 Subject: GIL in the new glossary References: Message-ID: <3f7c9a8c@news.mt.net.mk> > This has come up lots of times, and you can find some old threads (of > the c.l.py kind, not the posix kind :-)). But in general, the strategy > is to use some form of IPC, and launch many Python processes. Each > Python iterpreter can get run in its own processor, and partial > calculations/results exchanged as needed. Various libraries help you > support this. > > Admittedly, this is not the absolutely most memory/CPU friendly > technique possible... but then, Python isn't to start with. If you > really need to scrape out every last CPU cycle, use C, OCaml, Fortran, > or assembly. But who would like to use those?? :) Seriously, the biggest problem with GIL is in applications like mod_python, which is an Python extension to Apache. When Apache works in the multithreaded MPM (I think it was called "Worker") the GIL starts to be a serious bottleneck in your server performance. The GIL will lock your Apache threads if they happen to hit on a mod_python handled location. -- ?????? (jabberID:damjan at bagra.net.mk) Intel: where Quality is job number 0.9998782345! From Scott.Daniels at Acm.Org Fri Oct 10 20:09:15 2003 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Fri, 10 Oct 2003 17:09:15 -0700 Subject: private variables/methods In-Reply-To: References: <3F856275.C884CE5@engcorp.com> Message-ID: <3f874a2f$1@nntp0.pdx.net> Alex Martelli wrote: > ... > I can't think of ANY "feechur" from other popular languages that hasn't > been asked for, thousands of times.... Aha! caught the Martellibot in a rare memory failure (perhaps a rare double-bit parity error)? To my knowledge, nobody has suggested the autodeclaration of variables which begin with the letters 'I' through 'N' as integer variables. So there. :-) Now watch, he'll document 1003 requests on alt.lang.python.it. -Scott David Daniels Scott.Daniels at Acm.Org From jsaul at gmx.de Fri Oct 24 08:59:23 2003 From: jsaul at gmx.de (jsaul) Date: Fri, 24 Oct 2003 14:59:23 +0200 Subject: 'while' in list comprehension? In-Reply-To: References: <20031022175924.GA10716@jsaul.de> Message-ID: <20031024125923.GC27460@jsaul.de> * Terry Reedy [2003-10-23 04:57]: > "jsaul" wrote in message > news:20031022175924.GA10716 at jsaul.de... > > wouldn't it be useful to have a 'while' conditional in addition to > > 'if' in list comprehensions? > > > > foo = [] > > for i in bar: > > if len(i) == 0: > > break > > foo.append(i) > > > > would then turn into > > > > foo = [ i for i in bar while len(i)>0 ] > > while is simply not same as if: break! > if executes once for each value of i, while indefinitely. > If you translate back by current rule, which will not change, you get: > > foo = [] > for i in bar: > while len(i) >0: > foo.append(i) I agree that 'while' cannot not just be considered a replacement for 'if'. However, adding a 'while' conditional to list comprehensions would very unlikely be misunderstood as another (infinite) loop. Instead, I find the above 'while' example about as intuitive as is the case with 'if'. It simply means that under a certain condition the loop will be ended, which is just what most people would probably expect. Anyway, thanks a lot to all who replied! What is your opinion after this discussion, write a PEP or just forget about it? Cheers, jsaul From max at cNvOiSsiPoAnMtech.com Fri Oct 31 10:42:53 2003 From: max at cNvOiSsiPoAnMtech.com (Maxim Khesin) Date: Fri, 31 Oct 2003 15:42:53 GMT Subject: lightweight human-readable config? In-Reply-To: References: Message-ID: <1qvob.46881$ri.7441396@twister.nyc.rr.com> Nick Vargish wrote: > "John Roth" writes: > > >>for line in inFile.readlines(): >> key, value = line.split(":") >> configdict[key] = value > > > for line in inFile.readlines(): > key, value = line.split(':', 1) # only split once, values could Just one comment: using ':' for separator is not a great idea if Windows paths are come of the potential values. m From mertz at gnosis.cx Tue Oct 7 14:13:39 2003 From: mertz at gnosis.cx (David Mertz) Date: Tue, 07 Oct 2003 14:13:39 -0400 Subject: Python syntax in Lisp and Scheme References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> <92c59a2c.0310031345.57d20631@posting.google.com> Message-ID: |> def posneg(filter,iter): |> results = ([],[]) |> for x in iter: |> results[not filter(x)].append(x) |> return results |> collect_pos,collect_neg = posneg(some_property, some_file_name) Pascal Costanza wrote previously: |What about dealing with an arbitrary number of filters? Easy enough: def categorize_exclusive(filters, iter): results = tuple([[] for _ in len(filters)]) for x in iter: for n, filter in enumerate(filters): if filter(x): results[n].append(x) break return results Or if you want to let things fall in multiple categories: def categorize_inclusive(filters, iter): results = tuple([[] for _ in len(filters)]) for x in iter: for n, filter in enumerate(filters): if filter(x): results[n].append(x) return results Or if you want something to satisfy ALL the filters: def categorize_compose(filters, iter): results = tuple([[] for _ in len(filters)]) for x in iter: results[compose(filters)(x)].append(x) return results The implementation of 'compose()' is left as an exercise to readers :-). Or you can buy my book, and read the first chapter. Yours, David... -- Keeping medicines from the bloodstreams of the sick; food from the bellies of the hungry; books from the hands of the uneducated; technology from the underdeveloped; and putting advocates of freedom in prisons. Intellectual property is to the 21st century what the slave trade was to the 16th. -- Buy Text Processing in Python: http://tinyurl.com/jskh From matt at pollenation.net Tue Oct 28 13:25:42 2003 From: matt at pollenation.net (Matt Goodall) Date: Tue, 28 Oct 2003 18:25:42 +0000 Subject: **NEWBIE - QUESTION** In-Reply-To: <3F9EA41C.6060704@jaydorsey.com> References: <0DFFBE2E899E804E9A5710F7071224381E7D3C@sjvapcd-mail.valleyair.org> <3F9EA41C.6060704@jaydorsey.com> Message-ID: <3F9EB4A6.4030003@pollenation.net> Jay Dorsey wrote: > Staven Bruce wrote: > >> I am new to Python and am trying to use the Python-2.3.2-1Interperter on >> Windows. I have a .py file and I am trying to compile it into a .pyc >> file. >> When I began experimenting with Python, I could have sworn that >> opening the >> .py file in IDLE, modifying it, and then saving it would automatically >> create the corresponding .pyc file. But this is not working. > Out of interest, why are you trying to compile the module? This is generally not something you need to worry about. > > I believe you have to *run* the file to get it to compile, not just > save it. Actually, Python only compiles modules that are imported, e.g. python file.py would not compile it, whereas $ python >>> import file.py >>> would compile it. Cheers, Matt -- Matt Goodall, Pollenation Internet Ltd w: http://www.pollenation.net e: matt at pollenation.net From chris.lyon at spritenote.co.uk Mon Oct 20 09:29:15 2003 From: chris.lyon at spritenote.co.uk (Chris Lyon) Date: 20 Oct 2003 06:29:15 -0700 Subject: Best way to use Python to make 2d XY scatter graphs? Will TKinter do it? References: <616fccba.0310200250.22d55351@posting.google.com> Message-ID: rh4170056 at juno.com (rhmd) wrote in message news:<616fccba.0310200250.22d55351 at posting.google.com>... > I need to create image files (eg bmp or jpeg) of xy scatter graphs > (i.e., graphs in which markers denote individual points; the markers > need to be small polygons of various sizes, shapes, colors, shadings, > etc. and there are thousands on them on each graph). Have been using > MS Excel, but its limitations are unbelievable (only whole number > sizes, no way around a 56 color palette, only low quality jpeg files > so that when I publish the graphs I have to print and scan them all to > get a decent image, no more than 32K markers in a single series). > From a programming point of view, Python is perfect to set up > something like this, but MY QUESTION IS: Will TKinter do this? Or > will it be necessary to learn OpenGL? Or is another Python compatible > package best? Thanks for your help. Sounds like a job for PIL. http://www.pythonware.com/products/pil/ From fperez528 at yahoo.com Wed Oct 1 14:17:19 2003 From: fperez528 at yahoo.com (Fernando Perez) Date: Wed, 01 Oct 2003 12:17:19 -0600 Subject: python, vtk, C++ References: <87d6dicwt0.fsf@pobox.com> Message-ID: David Abrahams wrote: > jjl at pobox.com (John J. Lee) writes: > >> "Yi-Yu Chou" writes: >> >>> I want to use python as my GUI to load a 3D volume (vtkImageData), >>> and use a pointer to pass this 3D image to my own C++ class. >>> My question is I don't know how to communicate between python and C++. >>> Any suggestion would be appreciated. >> >> Google. > > I think I can be a little more helpful than that: > > http://www.boost.org/libs/python > http://www.swig.org And even further: google('mayavi python') (this wouldn't be obvious if you didn't know about mayavi). There's a solid chance Mayavi will solve the OP's problem without writing one line of code. The most recent version includes volume rendering right out of the box. If he wants to code, mayavi can also be scripted, and a tool called ivtk is included for interactive manipulation of vtk objects. Cheers, f. From tstegen at cis.strath.ac.uk Thu Oct 23 15:13:56 2003 From: tstegen at cis.strath.ac.uk (Thomas Stegen) Date: Thu, 23 Oct 2003 20:13:56 +0100 Subject: approx 100 assorted computer/ math/other books In-Reply-To: References: <3F9531FE.F1381691@nomail.com> <3F969C4E.3CF6CA2F@yahoo.com> <55rdpvcniuskhqu9qah0j7q2u18knt04pe@4ax.com> Message-ID: <3f98289d@nntphost.cis.strath.ac.uk> Roedy Green wrote: > > The blast is against those who complain about top posting. Top posting > is GOOD on one respect. It is at least is a step in the right > direction away from forcing people to read stuff they have seen many > times before -- especially those folk who quote with nests 10 posts > deep. Top posting is never good. Just delete all the text in the previous post if you do not have the need to include some more specific context. It is not that hard. -- Thomas. From p at trick.lu Sun Oct 5 13:48:24 2003 From: p at trick.lu (Patrick Useldinger) Date: Sun, 05 Oct 2003 19:48:24 +0200 Subject: newbie needs help with GUI References: <3F7F1F51.D7976752@easystreet.com> <1065296088.11913.16.camel@devilbox.homelinux.net> Message-ID: <09m0ovkrtprk40k4ndutdfeuv7nhds6jb7@4ax.com> On Sun, 05 Oct 2003 14:08:48 +0200, Frantisek Fuka wrote: >I just wanted to say that "Strc prst skrz krk" is perfectly valid Czech >sentence (meaning "Put your finger in your throat"). Thank you. Nice. Otherwise, I might trade some letters (not only vowels), if you are interested. Although we are a very small country, we do have some natural resources (I am married to one). -pu From stevewilliams at wwc.com Sat Oct 11 23:37:09 2003 From: stevewilliams at wwc.com (Steve Williams) Date: Sun, 12 Oct 2003 03:37:09 GMT Subject: Python syntax in Lisp and Scheme In-Reply-To: References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> <92c59a2c.0310031345.57d20631@posting.google.com> <3F85A6E4.3050402@nospam.com> Message-ID: Alex Martelli wrote: [snip] > but we DO want to provide very clear and precise error diagnostics, of course, > and the language/metalanguage issue is currently open). You will note > that this use of macros involves none of the issues I have expressed about > them (except for the difficulty of providing good error-diagnostics, but > that's of course solvable). finally, a breath of fresh air. From inyeol.lee at siimage.com Tue Oct 28 13:31:52 2003 From: inyeol.lee at siimage.com (Inyeol Lee) Date: Tue, 28 Oct 2003 10:31:52 -0800 Subject: manipulate string In-Reply-To: References: Message-ID: <20031028183152.GB2741@siliconimage.com> On Tue, Oct 28, 2003 at 07:06:36PM +0100, Chris wrote: > It is me again. > Unfortunately it doesn't work. Python doesn't accept [::2] > TypeError: sequence index must be integer > I use Python Release 2.2.3. > Any ideas? Then, >>> s = "0123456789" >>> " - ".join([s[i] for i in range(0, 10, 2)]) '0 - 2 - 4 - 6 - 8' -Inyeol From ktilton at nyc.rr.com Sun Oct 19 00:32:15 2003 From: ktilton at nyc.rr.com (Kenny Tilton) Date: Sun, 19 Oct 2003 04:32:15 GMT Subject: Why don't people like lisp? In-Reply-To: References: <1A8kb.67406$pv6.3464@twister.nyc.rr.com> Message-ID: Rune Steffensen wrote: > ...it could have something to do with its users. > more personal attacks? what part of the thread subject do you not understand? You are reading this thread voluntarily, and your only contribution is bile. Super. The fact is, Pythonistas are using python because Java (and C++) did not meet their needs. ie, thy are not sheep. They think for themselves. Lispniks consider such folk Deeply Worthy. This thread arose (in a prior incarnation) only because Python merely /considered/ macros. Some mis-characterizations of macros arose and a few of us swung by to say those characterizations did not match our experience. We (I) do not give a rat's ass if Python adopts macros, but we have a ball with them and we thought Pythonistas should have the Best Information before rejecting them. kenny -- http://tilton-technology.com What?! You are a newbie and you haven't answered my: http://alu.cliki.net/The%20Road%20to%20Lisp%20Survey From claird at lairds.com Fri Oct 10 15:12:53 2003 From: claird at lairds.com (Cameron Laird) Date: Fri, 10 Oct 2003 19:12:53 -0000 Subject: How do I pass a variable to an external program References: Message-ID: In article , Rigga wrote: >> . >> . >> . >> In the short term, >> os.system('cd %s' % variable) >> is probably what you think you want. >Wow thanks for the fast response that works a treat, now i just gotta find >out how you run more than one command on a line i.e. >os.system('cd %s' 'ls -lt') > > os.system('cd %s; ls -lt' % variable) To save even more time, visit . -- Cameron Laird Business: http://www.Phaseit.net From joachim.durchholz at web.de Mon Oct 20 14:41:57 2003 From: joachim.durchholz at web.de (Joachim Durchholz) Date: Mon, 20 Oct 2003 20:41:57 +0200 Subject: Python from Wise Guy's Viewpoint In-Reply-To: References: Message-ID: Espen Vestre wrote: > Joachim Durchholz writes: > >> Actually, my experiences with Lisp come from several pre-Scheme >> encounters. They include a rather poor (by today's standards) >> dialect called Interlisp, which worked OK but was a little >> restricted, and a Lisp machine that offered no protection >> whatsoever for the system internals and, consequently, crashed in >> ways that make even Windows ME look like the incarnation of >> stability. > > Probably, you have tried, as I did, to use Xerox Lisp Machines in > standalone mode. They were not Xerox, but something similar. That was about the late 1980ies, I think - Lisp machines being on or slightly after the peak of their hype. It might indeed have been a server thing though - there was some backup server in the background. I still found it unacceptable if I could bring the machine down on its knees by inadvertently changing some system function... Well, that's long past. The real issues are different. > (Anyway, even using them standalone was better than Windows ME wrt. > stability) Maybe. I'm pretty sure it wasn't Xerox, but something else. I tried to forget the whole unwholesome episode as quickly as possible :-) >> before/after/around don't offer anything that a simple call to an >> ancestor method wouldn't offer, and with less linguistic >> requirements. > > Yes they do. E.g. :around-methods wrap _around_ the primary method. > If you want the most specific method to be called first, you can > always use ordinary ancestor methods (call-next-method). No, I just want to use the implementation that happens to be useful for my subclass. > I agree that multimethods must be used with care. But so must many > constructs, even in languages that try hard to put a straight jacket > on their users. Hey, straightjackets aren't enough, you need ball and chains! ;-) Seriously, I see that multimethods can solve problems. It's just that I have seen so many constructs that were later replaced by slightly less powerful and much safer constructs. >> stupid coding error, and you simply fix the problem? (C programmers >> don't see C as a dangerous language, they just consider race >> conditions and buffer overruns as stupid programming mistakes as >> well... deficits of a language are easier to see if you take an >> outside perspective.) > > Sorry, but I don't think the multimethod/buffer overrun analogy is a > fair one (except if you can come up with at least one real life > example of multi-method-hell at work). Too detailed for now. >> In practice, most programmers aren't great, they are average. >> Assuming a halfways sane distribution, 50% of all programmers are >> even /below/ average - and their services are still very much in >> need. How should they get their work done? Educating them isn't an >> option - if that were a possibility, it would have long been done. > > The problem with this attitude, is that below-average programmers > usually advance, through the Dilbert Principle, to pointy-haired > positions, and if there is this idea that "everybody must use the > same programming language, and it must be a simple one" floating > around as a principle, you can be sure that they grab it. Hey, but that's sensible. The less languages you have in shop, the less problems you have reassigning people between tasks. And every constraint removed if making life easier - there are already enough constraints to keep satisfied. I don't pretend I'm happy with that. I just mean that I can understand the PHB reasoning at work, and I don't know any good alternatives. Welcome to real life - TANSTAAFL. > Another point: Do you have any _substantial_ reasons for claiming > that mediocre (or worse) programmers _really_ work better with any of > the more mainstream languages than they would do with Common Lisp (if > we for a moment disregard the most simple 'library-assembling- > programming' in VB or java where CL obviously currently has a > drawback by supporting fewer libraries)? They certainly would work better with a language with a "more standard" syntax ("Lots of Irritating Superfluous Parentheses" and all). I know it's something that people learn to "see through", but it's certainly massively irritating getting used to it. I did some programming in Lisp, but I never fully got rid of that parenthesis paranoia... maybe a full year of part-time Lisp programming isn't enough. Though that's already too long for a commercial project. Job satisfaction is an important factor, and forcing developers to adopt to many parentheses is just a needless irritation (from a boss's perspective, Lispers will do fine with them of course). > Yet another point: Inside every substantially advanced program, > there's a lisp trying to get out. I agree with that, though one could replace "Lisp" with other language names. > _My_ idea (this is just guessing, I admit), is that large CL systems > are _easier_ to maintain, even for Joe Notsobright, than large > complicated systems written in other languages, where all the fancy > mechanisms have been reinvented (had to be reinvented!) in much more > obscures way to make the program work. I have seen similar claims for almost any language "with a mission", such as Smalltalk and Eiffel. Which happens to be the languages that I dug into well enough to see such statements - I'm pretty sure that many other languages claim this as well. I'd be interested in any hard facts about such issues. (I know that they are difficult if not impossible to come by. I'm just thinking wishfully, and aloud...) Regards, Jo From skip at pobox.com Fri Oct 3 15:56:02 2003 From: skip at pobox.com (Skip Montanaro) Date: Fri, 3 Oct 2003 14:56:02 -0500 Subject: negative numbers and integer division In-Reply-To: References: Message-ID: <16253.54354.336490.541529@montanaro.dyndns.org> Mark> I was given the impression that (int // int) was going to be the Mark> replacement for (int / int) when (int / int) is changed to return Mark> a float, but -1/12 now gives 0, not -1, so (int // int) is not a Mark> replacement for (int / int). >>> from __future__ import division >>> -1/12 -0.083333333333333329 >>> -1//12 -1 Skip From abriggs at westnet.com.au Tue Oct 28 07:00:38 2003 From: abriggs at westnet.com.au (Anthony Briggs) Date: Tue, 28 Oct 2003 20:00:38 +0800 Subject: Concurrency models (was: Timer) In-Reply-To: References: <3f9c9cdb$0$23610$5a62ac22@freenews.iinet.net.au> <3f9d1775$0$23584$5a62ac22@freenews.iinet.net.au> Message-ID: At 11:14 AM +0000 28/10/03, Alex Martelli wrote: >Anthony Briggs wrote: > ... >> No, I wrote something that I consider true. I'd consider that after >> command to be on a par with Fortran's(?) COME FROM statement in terms > >Intercal. Lawrence Clark's 1973 article about "comefrom" in Fortran >was satire (just as all of Intercal is). Ah. I just read the article at . Most enlightening ;) >Note that, in Python, you have that 'after' available any time >you're running a Tkinter GUI: any Tkinter widget has an 'after' >method that takes a delay (in milliseconds), a callable object, >and optionally some arguments, and schedules the callable to >be called with those arguments after that delay. > >It works a charm, btw. I'll take your word for it. It sounds like a recipe for a lot of hair pulling to me. What happens if there's some part of your code that you don't want interrupted? eg. database commits, file access, any sort of time critical stuff, that sort of thing. Is there a way to switch it off? > >>my money, the event-oriented model behind the [after] >>>above is at least as robust as any other. >> >> Yes, that's what I said - only with fewer words :) > >I thought you were arguing AGAINST the 'after' functionality, >and therefore against event-driven programming...?! Perhaps I was taking his words a little too literally. As far as I can tell with threads, etc, they're little better than voodoo. So the after statement is at least as robust, even if it's a complete horror... Anthony -- ---------------------------------------------------- HyPEraCtiVE? HeY, WhO aRE YoU cALliNg HypERaCtIve?! aBRiGgS at wEStNeT.cOm.aU ---------------------------------------------------- From a.held at computer.org Mon Oct 13 08:30:34 2003 From: a.held at computer.org (Andreas Held) Date: 13 Oct 2003 05:30:34 -0700 Subject: Tkinter, wxPython, PyGtk, or PyQt... References: Message-ID: <564eac6f.0310130430.1b6d6ee7@posting.google.com> For a light-weight and cross-platform alternative to Tkinter and all the others you might want to look at pyFLTK at http://pyfltk.sourceforge.net. Of course I am a little bit biased as I am the maintainer of pyFLTK. Andreas Held Alex Martelli wrote in message news:... > carljohan.rehn at chello.se wrote: > > > I would like like to start doing some GUI-programming in Python, but don't > > know which library to choose. > > > > Tkinter seems a bit old. Correct me if I am wrong! The layout doesn't look > > as nice as for the others. > > Yes, it's old (and others have expressed doubts about its looks). F. Lundh > is preparing a revamped version but I don't much about it. > > > > wxPython seems to be the first-hand choice for people doing > > W32-programming (with MFC-experience). > > If win32 is your target and mfc your experience, pythonwin may be > what you want. wxPython is, however, cross-platform. > > > PyGtk seems to be a modern, very clean and nice approach, but with poor > > W32-support. Is PyGtk a mature library with respect to version stability > > and documentation. > > Not sure, sorry. > > > PyQt is a huge library (thanks to Qt), but not free on W32, or? > > Right, either not free or limited on win32. I got a license for it as a > part of Blackadder, now out of beta and costing $50 I believe. It's > indeed a marvel of power and ease of use on all scores, IMHO. But > if you must have the full power on win32 and can't spend that much, > it's not an option. > > > Is there any possibility that any of the above-mentioned libraries will be > > included as a standard library in any of the near-future Python > > distributions? > > If you mean those made by the PSF, I don't see anything taking the > place of Tkinter in the near future. Tkinter is what wonderful free > PSF tools like IDLE are based on, so it will stay. Other distributions > are perfectly free to bundle all they want. > > > > I myself program on W32 at work, but use Linux at home. So, which one > > should I start with in order to reduce the effort of learning something > > new and to be productive in the shortest time possible? > > If you're sure you can't afford any form of PyQt, Tkinter is probably > simplest to use, but limited and maybe not as good-looking as you > might like, wxWindows is probably richer and better looking. > > > > By the way, how do I most easily include plotting capabilities to my > > Python-apps? > > A couple dozen tools are linked to from: > http://www.python.org/topics/scicomp/plotting.html > and there are few others too. I do not know which one will be > easiest for you to use. > > > Alex > > > > > > Carl From ddarius at hotpop.com Fri Oct 24 03:57:56 2003 From: ddarius at hotpop.com (Darius) Date: 24 Oct 2003 00:57:56 -0700 Subject: Why don't people like lisp? References: <8Nnlb.619$I04.380@newsread4.news.pas.earthlink.net> Message-ID: <9d140b81.0310232357.76cf8fea@posting.google.com> Joe Marshall wrote in message news:... > "Andrew Dalke" writes: > > > As an example, here's a quick hack of a way to parse a simple > > stack-based language and make a native Python function out > > of it.... > > [code elided] > > Let's take on something more complicated. A lot more complicated. > > Suppose I am solving problems that are best expressed > non-deterministically, and I need a domain language that has the > following non-deterministic constructs: > > EITHER -- > Used as a mechanism to combine expressions > non-deterministically as in > > Whatever the syntax, EITHER introduces a choice-point. It > begins by attempting evaluation of the first subexpression. > If that subexpression returns a value, EITHER returns that > value. If the subexpression `fails', EITHER attempts to > evaluate the next subexpression. The first subexpression > to produce a value is the value of the whole expression. > If all subexpressions `fail', then the EITHER form itself > `fails'. > > FAIL -- > Causes an expression to `fail'. This means that control is > immediately returned to the nearest enclosing EITHER form > (backtracking) which will then proceed to attempt to evaluate > the next subexpression. If the current subexpression is the > last form in the enclosing EITHER, the EITHER form propagates > the failure up to the next enclosing EITHER. > > ALL-VALUES -- > Used to collect all possible values returned by a > non-deterministic expression. If all possible choice-points > in the expression yield failure, then ALL-VALUES > deterministically returns an empty collection. Thus failures > cannot propagate past an ALL-VALUES form. > > ONE-VALUE -- > Returns the first possible value returned by a non-deterministic > expression, or some sort of distinguished token if no value > can be found. Also blocks propagation of `failure'. > > > Since I am unsure of the entire details of the problem I am solving, I > also wish to have these forms integrated into a reasonably complete > computer language. Obviously this new language will have syntactic > differences from anything other language (via the introduction of > these forms), but by and large, the subexpressions of this new > language ought to be something familiar. > > So if we extended Lisp, for example, I could write: > > (defun an-integer-between (low high) > (if (> low high) > (fail) > (either low (an-integer-between (+ low 1) high)))) > > (defun pythagorean-triples (n) > (all-values > (let ((opposite (an-integer-between 1 n)) > (adjacent (an-integer-between 1 n)) > (hypotenuse (an-integer-between 1 n))) > (if (= (+ (* opposite opposite) > (* adjacent adjacent)) > (* hypotenuse hypotenuse)) > (list opposite adjacent hypotenuse) > (fail))))) pythagoreanTriples n = [ (opposite,adjacent,hypotenuse) | opposite <- [1..n], adjacent <- [1..n], hypotenuse <- [1..n], opposite^2 + adjacent^2 == hypotenuse^2] {- or with alternative syntax pythagoreanTriples n = do opposite <- [1..n] adjacent <- [1..n] hypotenuse <- [1..n] guard (opposite^2 + adjacent^2 == hypotenuse^2) return (opposite,adjacent,hypotenuse) -} > and (pythagorean-triples 10) > would return ((3 4 5) (4 3 5) (6 8 10) (8 6 10)) *Main> pythagoreanTriples 10 [(3,4,5),(4,3,5),(6,8,10),(8,6,10)] pythagoreanTriples n = [ (opposite,adjacent,hypotenuse) | let ns = [1..n], opposite <- ns, adjacent <- ns, hypotenuse <- ns, opposite^2 + adjacent^2 == hypotenuse^2 ] behaves better... Don't try this with the Lisp. I wonder if something along the lines of, [ (x,y) | range <- rangeOfRanges, x <- range, y <- range ] works with the Lisp version and does the Right Thing, namely give: [(1,1),(1,2),(2,1),(2,2),(3,3),(3,4),(4,3),(4,4)] when rangeOfRanges is (either (either 1 2) (either 3 4)) or something to that affect ([[1,2],[3,4]] was used to get the above numbers). > on the other hand, if we extended Python, I could write: Oops! Wrong language. Also forgot to extend the language. *sigh* I can't do anything right. > This is a tricky problem, but one approach in Lisp is to make > ALL-VALUES and EITHER be rather complicated macros. > > The advantage of doing this is that the rest of the language, LET, > DEFUN, *, +, conditionals, strings, CLOS, i.e. everything, is pretty > much intact. Since I know that Lisp is a `reasonably complete' > substrate, I don't have to worry about designing and parsing an entire > non-deterministic language. I can just graft my extension on to > something people will be familiar with. > > Yes, I know that adding non-determinism to the language is going to > mean a change in how people would program (how could it not?!) but > I'm attempting to *minimize* the intellectual burden by making the > non-deterministic language very similar to one that already exists. > > How would one approach this in Python? If Python had macros, then > one could take exactly the same approach as Lisp. What does a Pythonista > do when encountering a problem like this? (I'm actually curious, > not raising rhetorical questions. I assume that there is *something* > one would do, but not being a python hacker, I don't know what it is.) (posted mostly for my own amusement though I am interested in how the rangeOfRanges example is handled) From sorr at rightnow.com Thu Oct 2 19:45:37 2003 From: sorr at rightnow.com (dbdweeb) Date: 2 Oct 2003 16:45:37 -0700 Subject: Implementing RRDtool with Python on Windoze Message-ID: I've been using RRDtool/Python/Apache with great success on Linux but now I need to implement on Windoze2K and I don't have a Windoze C compiler. Is there a RRDtool binary and Python module for it which I can just plug in? TIA From news at yebu.de Mon Oct 6 09:24:10 2003 From: news at yebu.de (Karl Scalet) Date: Mon, 06 Oct 2003 15:24:10 +0200 Subject: HTML -> text/plain "clever" formatting In-Reply-To: References: Message-ID: Gilles Lenfant wrote: > > Thanks Karl, I found what you're talking about > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52297 > > Need to rework that TtyFormatter in depth to mimic lynx :o) > > Cheers > Hi Gilles actually I was talking about a different even similar example. But could not find it either in the online version. So maybe this is available only in the printed version, sorry. But if your recipe is good enough , why bother :-) Karl From tfb at famine.OCF.Berkeley.EDU Fri Oct 31 00:20:16 2003 From: tfb at famine.OCF.Berkeley.EDU (Thomas F. Burdick) Date: 30 Oct 2003 21:20:16 -0800 Subject: LAID (was: python libs v lisp coolness? References: Message-ID: mike420 at ziplip.com writes: For those of you who haven't noticed yet, this is a troll whose "name" is a wack allusion to smoking marijuana. Ignore it. -- /|_ .-----------------------. ,' .\ / | No to Imperialist war | ,--' _,' | Wage class war! | / / `-----------------------' ( -. | | ) | (`-. '--.) `. )----' From gherron at islandtraining.com Thu Oct 30 11:16:45 2003 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 30 Oct 2003 08:16:45 -0800 Subject: How can I move or copy files using python? In-Reply-To: References: Message-ID: <200310300816.45372.gherron@islandtraining.com> On Wednesday 29 October 2003 02:37 pm, Kay Lee wrote: > Hi, > > I looked up os module to find out some method to move and copy files in > python, > but os doesn't support such methods. > Is there any way to move & copy files in python? > Thanks in adv. See the shutil module. Gary Herron From aleax at aleax.it Sun Oct 19 18:27:43 2003 From: aleax at aleax.it (Alex Martelli) Date: Sun, 19 Oct 2003 22:27:43 GMT Subject: Why don't people like lisp? References: <1A8kb.67406$pv6.3464@twister.nyc.rr.com> <874qy5ear5.fsf@bird.agharta.de> <6Szkb.6421$i92.5421@clgrps13> <7xvfqlp1qp.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: ... > This is untested but looks simpler than the lisp example: > > def mostn (fn, lst): > max = None > for a in lst: > score = fn(lst) Perhaps "score = fn(a)" ? > if max is None or score > max: > max = score > ret = [a] > elif score == max: > ret.append(a) > return ret it it all right to raise an exception if lst is empty? I'm not sure of the lisp example's behavior in that case, but I suspect it returns an empty list and None. In that case, we may need to initialize ret to [] too. Stylistically (but it's just me) I don't much like that "first-time switch" use -- null in lisp, None in Python. An alternative might be to treat the empty lst as an exceptional case: def mostfn(fn, lst): try: a = lst[0] except IndexError: return [], None ret, max = [], fn(a) for a in lst: score = fn(a) if score > max: max = score ret = [a] elif score == max: ret.append(a) return ret, max a _bit_ more complicated than Paul's code, and calls fn twice on lst[0], but it caters to my dislike for "first-time switches"...;-). One could remove the double-call problem by changing the start to: def mostfn(fn, lst): it = iter(lst) try: a = it,next() except StopIteration: return [], None ret, max = [a], fn(a) for a in it: ... If taking O(N) auxiliary memory was acceptable, of course, there would be an alternate possibility: def mostfn(fn, lst): if not lst: return [], None aux = [ (fn(a), a) for a in lst ] Max = max([ f for f, a in aux ]) return [ a for f, a in aux if f==Max ], Max Typical problem with all high-level languages -- they often make most attractive an approach that may not be quite as spare of bytes and cycles as some lower-level one!-) [A simple test with fn=lambda x:x%333 and lst=range(9999) shows the lower-level approach is over 3 times faster, both with and without psyco.proxy on both]. Alex From imbosol at aerojockey.invalid Sun Oct 5 23:08:57 2003 From: imbosol at aerojockey.invalid (Carl Banks) Date: Mon, 06 Oct 2003 03:08:57 GMT Subject: use make and version control system for every project? References: Message-ID: Roy Smith wrote: > Carl Banks wrote: >> Version control, it depends. I've used CVS for some personal projects >> before, and can't say I've ever found it useful, and it's definitely a >> pain to keep things up-to-date. I recommend, for personal projects, >> not bothering with version control at least until the project is >> fairly stable. > > I suppose this is a personal preference kind of thing, but I use > revision control (CVS or RCS mostly, Clearcase when they hold a gun to > my head) for everything, from the very beginning. Source code, > documents, test notes, project plans, it all goes under revision > control. Best yet, the OP should probably try it and see if it works for him. I recommended not bothering early on because I tend to move files around quite a bit early on (a major pain in CVS), and I suspect I'm not the only person to do that. But if he's the type of person whose projects are "fairly stable" in the very beginning, by all means, he should CVS away. [snip] > There's the running commentary of the checkin messages (I'm pretty > anal about trying to keep a good checkin log). Incidentally, this is probably greatest strength of version control relative to frequent backups (for personal projects, of course). It's also a feature I've found extremely little use for. I mean, it sounds cool to be able to go back and see exactly when you made a certain change, but is that really useful in practice? I'm sorry, but my pragmatic mind tells me it's all wasted effort, a lot of work for little benefit. Frequent backups do well enough for me, with far less effort, so it's what I've been moving towards. But whatever works for you. And, of course, the OP should try it and decide if it works for him. -- CARL BANKS http://www.aerojockey.com/software As the newest Lady Turnpot descended into the kitchen wrapped only in her celery-green dressing gown, her creamy bosom rising and falling like a temperamental souffle, her tart mouth pursed in distaste, the sous-chef whispered to the scullery boy, "I don't know what to make of her." --Laurel Fortuner, Montendre, France 1992 Bulwer-Lytton Fiction Contest Winner From mertz at gnosis.cx Wed Oct 1 13:32:45 2003 From: mertz at gnosis.cx (Lulu of the Lotus-Eaters) Date: Wed, 01 Oct 2003 13:32:45 -0400 Subject: Prime number module References: <7b4hnvgplqk6g1d5vig0dsdvic1ru62r4e@4ax.com> <+Nfe/kKkXkJT092yn@gnosis.cx> <15we/kKkXIaL092yn@gnosis.cx> Message-ID: <9+we/kKkXMhG092yn@gnosis.cx> "Andrew Dalke" wrote previously: |In essense, if you know the full corpus beforehand, it's really |easy to compress - just store the identifier for each text. I've invented an excellent compression algorithm. It represents the 12.5 meg bit sequence for prime/no-prime (<10^8) as the bit "1". To encode other sequences, you use the escape bit "0" as the first bit... Pick the best algorithm for the job at hand... Yours, Lulu... |Iran nuclear neocon expose POTUS patriot Pakistan armed weaponized |enriched uranium UN smallpox Gitmo invasion Castro Tikrit revolution sarin Yeah... I like those. I'll add a new .signature to my rotation list. I can troll both the spooks of the mid-1990s and those of the mid-2000s. -- mertz@ | The specter of free information is haunting the `Net! All the gnosis | powers of IP- and crypto-tyranny have entered into an unholy .cx | alliance...ideas have nothing to lose but their chains. Unite | against "intellectual property" and anti-privacy regimes! ------------------------------------------------------------------------- From tim.ronning at start.no Mon Oct 27 18:47:01 2003 From: tim.ronning at start.no (Tim Ronning) Date: Tue, 28 Oct 2003 00:47:01 +0100 Subject: Is it any good? Message-ID: Hello list, I wonder if I could get some feedback from the list on a Python book I'm about to order from the net. The book is called "Python How to Program" by Deithel & Deithel. Issued on Prentice Hall 2002. I'm not an experienced Python programmer and I'm looking for a comprehensive but also an "understandable" book. I'm also open for suggestions. Best regards Tim Ronning -- Using M2, Opera's revolutionary e-mail client: http://www.opera.com/m2/ From antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru Wed Oct 22 11:36:25 2003 From: antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru (anton muhin) Date: Wed, 22 Oct 2003 19:36:25 +0400 Subject: extending the break statement In-Reply-To: <2259b0e2.0310220706.142bf8cb@posting.google.com> References: <2259b0e2.0310220706.142bf8cb@posting.google.com> Message-ID: Michele Simionato wrote: > Is there a way of "ending" a module? I would like something like this: > > # mod.py > print 'something here' > end() # some mysterious function > print 'you should not get here' > > # main.py > import mod > print 'it works' > > I cannot use 'sys.exit' in place of ``end()``, since it would exit from > the whole program and the line 'it works' would not be printed. > I know that I can modify the main program to catch the SystemExit > exception: > > > # main.py > try: > import mod > except SystemExit: > pass > print 'it works' > > but I find it really ugly, since I am forced to change by hand > all the scripts importing 'mod'. Moreover, I am abusing ``SystemExit``; > I should add instead a new built-in exception ``EndModule``, but this > requires even more lines of code for something that should be trivial. > > On the other hand, I don't like the ``if 0:`` option, i.e. writing ``mod.py`` > in the form > > # mod.py > print 'something here' > end() # some mysterious function > if 0: > print 'you should not get here' > > since it requires re-indenting by hand the (potentially long) block > of code to be commented out. Yes, I know about C-c->, but honestly > it is a PITA. Typically, I would like to comment out portions of > experimental code during debugging; that code will enter in the final > program at the end, so I must indent and re-indent it until it works > (which means lots of times). > > More in general, one could think of an ``end()`` function with the ability of > stopping the execution of the current frame and going back to the previous > frame. One could even terminate classes in this way, i.e. skipping all the > methods defined after the ``end()`` > > .... (some time passes) ... > > BTW, I have just realized that we don't need a new ``end()`` function: it would be > enough to extend the ``break`` statement. Currently, it works only inside > loops, why not to extend it to terminate classes and modules? IMHO, it would be > very useful during debugging and refactoring. What do you people think? > Or is there already same magic which can do what I ask for? > If not, take it as a feature request ;-) > > > Michele Simionato, Ph. D. > MicheleSimionato at libero.it > http://www.phyast.pitt.edu/~micheles/ > ---- Currently looking for a job ---- As a hack: for _ in "_": print "here" break print "there" Ugly, but it works. hth, anton. From ykingma at accessforall.nl Tue Oct 7 23:46:49 2003 From: ykingma at accessforall.nl (Ype Kingma) Date: Tue, 07 Oct 2003 20:46:49 -0700 Subject: Queues - Is Infinity all right? References: <84fc4588.0310050520.42e5f9d4@posting.google.com> <3F802006.93571400@engcorp.com> <3f818f20$0$14130$e4fe514c@dreader4.news.xs4all.nl> <84fc4588.0310061548.110533ff@posting.google.com> Message-ID: <3f830a38$0$420$e4fe514c@dreader7.news.xs4all.nl> Anand Pillai wrote: > This was exactly what my problem was. The producer thread was > creating a lot of data to the queue which the consumer cannot > keep up with. > > Since I am using python threads, it so happens most of the time > that the queue is filled to huge sizes, and the consumer thread > context switch is not done, causing memory problems. > > I have not gone through the code of Queue.py, but I think that > the queue.get() method is an O(n) operation, considering the > ration of 'put's to the 'get's. As Peter already remarked, the source of the your problem is not the get() operation. > A related question here is... How do you avoid producer thread > deadlocking when the consumer queue is full? By using a separate thread for the consumer(s), as you indicate below. > If the question is not clear, my queue is of size 'n'. It is already > full with 'n' pieces of data inside it. All of my 'n' producer threads > are trying to push data into it at the *same* time and there is no > consumer thread popping the data off (In my program, the consumers > are the producers themselves, a bad design I agree...). That's probably the source of your problem. > This is clearly a deadlock situtation, since no thread will enter the > queue forever. I solved it by creating a new consumer thread to pop > off some data, when deadlock occurs. But sometimes the deadlock > occurs very often resulting in many extra threads being created like this. > > The other approach is to write separate out consumer and producer thread > roles so that there is always one consumer thread somewhere which is > popping data off the queue, which is what I have done now. > > Anyway how do you make sure that dead lock situations not occur? When there is a cycle between the producers and the consumers, ie. back from the consumers to the producers, you may need one queue (eg. the backwards queue) of infinite size to prevent deadlock. However, you should make sure that no thread accesses a queue in the wrong direction, because that might still cause deadlock. In case you have a fixed ratio between the amounts of things on the various queues, you might consider not using queues at all for these fixed ratios. > Can you write some Event() based mechanisms to make sure that the > threads always access the queue at different times? Since python offers A queue provides synchronized access already, you don't need anything else. > no control over thread priority or mechanisms to suspend a thread, how > else could this be done? You can make reasonably sure that work is going on everywhere by keeping the queues small enough. This forces more thread switching, though. > That brings me to a favorite topic, to implement a thread wrapper > over the existing python threading API to allow suspending of threads > and modifying thread priority. Has this been considered as a PEP anytime > before? Thread suspension is (very) difficult to implement correctly. Thread priorities are good eg. when you have background work going on and you want some short interactive pieces of work done at normal speed. Also, if you have a series of threads and queues it can be helpful to give the first thread a higher priority when it also has to wait for external events. I don't know whether there was a PEP for any of this. Kind regards, Ype > Thank you all > > -Anand > > > ykingma at accessforall.nl wrote in message > news:<3f818f20$0$14130$e4fe514c at dreader4.news.xs4all.nl>... >> Peter Hansen wrote: >> >> >> ... >> > >> > That said, I'd consider using a fixed queue only when I was greatly >> > concerned about whether my consumer thread was going to be able to >> > keep up with my producer thread(s), and was therefore concerned about >> > overflowing memory with unconsumed input. >> > >> > In other words, I'd worry more about the robustness of the app >> > than about optimizing it before it worked... >> > >> >> I've been bitten a few times by unbounded queues when the consumer >> thread could not keep up: the queue grows to memory limits and >> no robustness is left. >> >> So I changed my default choice for queue implementations to bounded >> queues. They are much more predictable under unexpected loads >> as they evt. force the producer to wait for the consumer. >> >> The next question is off course what maximum queue size to use. >> You can get good answers from queuing theory, but 10 to 20 >> works well in many cases. >> >> Kind regards, >> Ype -- email at xs4all.nl From vanessabj at free.linux.net.mk Wed Oct 8 12:05:05 2003 From: vanessabj at free.linux.net.mk (Vanessa BJ) Date: 8 Oct 2003 09:05:05 -0700 Subject: SUCK my HUSBAND'S CUM from my CUNT Message-ID: Yeah baby! From jjl at pobox.com Tue Oct 21 07:56:05 2003 From: jjl at pobox.com (John J. Lee) Date: 21 Oct 2003 12:56:05 +0100 Subject: SSL security authorization? References: <874qy5xpvy.fsf@pobox.com> <84fc4588.0310200835.412bb5a0@posting.google.com> Message-ID: <87he22st2i.fsf@pobox.com> pythonguy at Hotpop.com (Anand Pillai) writes: > I tried your patch on a website with SSL auth and it did not work. > Can you give me an example of how to do this using urllib? [...] Again untested (and note the comment from Martin von Loewis in one of the SF bugs I mentioned in my earlier post in this thread -- sounds like he's not entirely confident the existing code is actually working): import urllib opener = urllib.URLOpener(key_file="/path/to/my_key_file", cert_file="/path/to/my_cert_file") response = opener.open(url) # GET response = opener.open(url, data) # POST John From find at my.address.elsewhere Thu Oct 23 11:26:14 2003 From: find at my.address.elsewhere (Matthias Blume) Date: 23 Oct 2003 10:26:14 -0500 Subject: Python from Wise Guy's Viewpoint References: <_8Ekb.7543$pT1.318@twister.nyc.rr.com> Message-ID: Matthias Blume writes: > Yes, the usefulness of static types seems to be inversely proportional > to the imperativeness of one's programming style (Haskell, Miranda). > Static types *really* shine in purely functional settings (****). [...] Obviously, the parenthetical remark "(Haskell, Miranda)" should be where the (****) is. Matthias From bokr at oz.net Sun Oct 5 15:50:13 2003 From: bokr at oz.net (Bengt Richter) Date: 5 Oct 2003 19:50:13 GMT Subject: os.listdir() bug in WinXp. Calling with empty string References: <840592e1.0310040736.83c9bc3@posting.google.com> Message-ID: On Sun, 5 Oct 2003 07:29:34 -0400, "John Roth" wrote: > >"Terry Reedy" wrote in message >news:NK-dnYuNtPlipuKiU-KYuA at comcast.com... >> >> "Hannu Kankaanp??" wrote in message >> news:840592e1.0310040736.83c9bc3 at posting.google.com... >> > This may be a bug or simply a strange result of undefined >> > behaviour, but this is what I get with Python 2.3.2 on >> > Windows XP: >> > >> > >>> import os >> > >>> os.listdir('') >> > [ filenames in the current directory, e.g. c:\python\ ] >> > >>> os.listdir(u'') >> > [ filenames in the drive's root directory, e.g. c:\ ] >> >> On Win98, *both* calls list root directory. listdir(path) must pass >> path to os system call and print response or raise exception as >> determined by os response. >> >> >Maybe os.listdir() behaviour is undefined for empty strings, >> >> It seems to be defined as whatever the os does with empty strings, >> which is not much more useful. You could open SF bug report listing >> various XP, W98, Linux behaviors and suggest that listdir def be >> changed to 'if path: current behaviour; else: raise exception'. > >I'd like to argue *against* raising an exception. We had a long >discussion on this exact point on the XP list a while ago, with >Ron Jeffries holding out for the position that if you can define >a useful behavior for a corner case, then you should do so >rather than raising an exception. The least surprising behavior >here is to simply list the current directory. In other words, >a null string would be equivalent to a string containing a single >dot. > +1 That intuitively matches well with arg-less invocation of ls or dir. Regards, Bengt Richter From nospam at nospam.net Tue Oct 7 20:40:19 2003 From: nospam at nospam.net (Riad Djemili) Date: Wed, 08 Oct 2003 02:40:19 +0200 Subject: timer freezes system Message-ID: Hi there, when executing the standard python example for Timer my python shell freezes after giving out 'hello' and has to be killed. What am I doing wrong!? --code-- import threading def hello(): print "hello, world" t = threading.Timer(30.0, hello) t.start() # after 30 seconds, "hello, world" will be printed --code-- I'm on a WinXP System Regards, Riad From mrroach at okmaybe.com Thu Oct 30 14:27:06 2003 From: mrroach at okmaybe.com (Mark Roach) Date: Thu, 30 Oct 2003 19:27:06 GMT Subject: Microsoft Access read from linux python References: Message-ID: On Wed, 29 Oct 2003 11:10:43 +0100, David ROBERT wrote: > I need to read data from a MS Access database. > The program (reader) is installed on a linux box and > is written in python langage. > The database is MS Access 2002 installed on a Win XP box > networked with the linux box. > Is it possible for python/linux to read data from MS Access > Database ? mdbtools: http://mdbtools.sourceforge.net/ provides a unixODBC driver for MS access databases. Install it and mxODBC, then you should be able to create a DSN for the access db, and connect to it using mxODBC > I've read a lot of things about mxODBC, iODBC and so on, > but I'm still very confused, It looks like it is _not_ What exactly are you confused about? Perhaps someone can help answer some specific questions... -Mark From usenet_spam at janc.invalid Tue Oct 28 01:32:20 2003 From: usenet_spam at janc.invalid (JanC) Date: Tue, 28 Oct 2003 06:32:20 GMT Subject: Cookie Module References: <5b04353b.0310230357.4d032e95@posting.google.com> <871xt3q116.fsf@pobox.com> <84fc4588.0310262240.1570892c@posting.google.com> Message-ID: pythonguy at Hotpop.com (Anand Pillai) schreef: > Yeah it has an academic quality to it, not of much pratical use maybe > right now, but I cannot understand how it makes the guy a masochist. JJL did implement it in ClientCookie, so I'm sure he knows by experience what a masochist is... ;-) -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From j-anthony at rcn.com Fri Oct 24 12:10:55 2003 From: j-anthony at rcn.com (Jon S. Anthony) Date: 24 Oct 2003 12:10:55 -0400 Subject: Why don't people like lisp? References: <8Nnlb.619$I04.380@newsread4.news.pas.earthlink.net> Message-ID: Marcin 'Qrczak' Kowalczyk writes: > On Thu, 23 Oct 2003 19:35:05 -0400, Jon S. Anthony wrote: > > > The above example (with some differing details I think) is given by > > Paul Graham in 2-3 pages of code in On Lisp in the Nondeterminism > > chapter. > > In Scheme it doesn't use macros but continuations. I pointed that out. But it's irrelevant to the general capability and point. > impressed. If not, this is only a partially correct solution; a full > solution requires continuations and it doesn't need macros. The real point here is that even in Scheme where you have continuations, the implementation here would make use of macros to provide the natural expression of the intent. It's just that the macros would expand into stuff using continuations. /Jon From dthierbach at gmx.de Sun Oct 26 12:03:18 2003 From: dthierbach at gmx.de (Dirk Thierbach) Date: Sun, 26 Oct 2003 18:03:18 +0100 Subject: Python from Wise Guy's Viewpoint References: Message-ID: Brian McNamara! wrote: > Pascal Costanza once said: >>Brian McNamara! wrote: > But I suppose you really want this example >>>(defun f (x) >>> (unless (< x 200) >>> (cerror "Type another number" >>> "You have typed a wrong number") >>> (f (read))) >>> (* x 2)) > statically typed, huh? After quite some time, I think I have finally figured out what Pascal meant with >> The type system might test too many cases. I have the impression that he is confusing dynamic type errors and runtime errors. In Lisp and Smalltalk they are more or less the same, and since dynamic type errors map to static type errors, he may think by analogy that other runtime errors must necessarily also map to compile errors somehow involved with static typing. Of course this is nonsense; those two are completely different things. The "too many cases" referred to some cases of runtime errors he didn't want to be checked at compile time. As you cannot get "too many test cases" by type annotations static typing (which was the context where he made this comment), like you cannot get "too many test cases" by writing too many of them by hand, I really had a hard time figuring this out. To sum it up: Unit tests (some, not all!) correspond to type annotations, static type checking is the same as running the test suite, dynamic types correspond to data types, runtime errors correspond to runtime errors (surprise :-). > Ok, I'll try. If I come up short, I expect it's because I'm fluent > in neither Haskell nor Lisp, not because it can't be done. You don't really need runtime errors for the above example, but here's a similar version to yours that throws an error in 'cerror' to return to the toplevel. No Maybe types. cerror :: String -> String -> IO a -> IO a cerror optmsg errmsg cont = do print errmsg print ("1: " ++ optmsg) print ("2: Fail") s <- getLine x <- readIO s let choice 1 = cont choice 2 = ioError (userError errmsg) choice x f :: Integer -> IO (Integer) f x = if (x < 200) then return (x * 2) else cerror "Type another number" "You have typed a wrong number" (getLine >>= readIO >>= f) >> I don't want an "approximation of cerror". I want cerror! And you got it, exactly as you wanted. Perfectly typeable. (Please don't say now "but I want to use the Lisp code, and it should run exactly as it is, without any changes in syntax"). You could even assign the very same types in Lisp if any of the extensions of Lisp support that. (I didn't try.) - Dirk From ransom at physics.mcgill.ca Thu Oct 16 12:58:53 2003 From: ransom at physics.mcgill.ca (Scott Ransom) Date: 16 Oct 2003 09:58:53 -0700 Subject: General Numerical Python question References: <500a4565.0310112113.a0840e8@posting.google.com> <500a4565.0310131915.148ce3f5@posting.google.com> <500a4565.0310140541.4f4fd35f@posting.google.com> <%xVib.26249$gi2.16759@fed1read01> <6869c57c.0310151854.1450d5b1@posting.google.com> Message-ID: larix_occidentalis at yahoo.com (Western Larch) wrote in message news:<6869c57c.0310151854.1450d5b1 at posting.google.com>... > Michael Ressler wrote: > > [...] > > from Numeric import * > > a=array([1.,2.,-3.,4.,-5.,6.,-7.,-8.,9.]) # make up an array > > idx=nonzero(a<0) # indexes of the negative values > > sqrs=sqrt(abs(take(a,idx))) # get the sqrts of neg elements > > put(a,idx,sqrs) # put them back into a > > print a # works! > > > > You can make the whole thing a one-liner if you want to get carried > > away with it. It's too bad "nonzero" isn't called "whereis" or > > something like that - it would make the idx= line more obvious. It's actually quite easy (and much more readable IMHO) as a one liner: > from Numeric import * > from umath import fabs, sqrt > a = array([1.,2.,-3.,4.,-5.,6.,-7.,-8.,9.]) > a = where(a<0, sqrt(fabs(a)), a) That's it! > In the Octave programming language (Matlab-like), the operation > is called "find" -- find(a<0) returns the indices of the negative > elements; a(find(a<0)) returns the negative elements themselves. A similar operation is possible in Numeric: compress(a<0, a) returns the elements of a that have a<0. > With all due respect, Octave rocks pretty hard, and although I > love Python I've only fiddled around with Numeric Python a little > bit -- I haven't found any reason to prefer it to Octave. Numeric is wonderful as well. And one of the biggest benefits is that you get all of the power of Python (and its _huge_ standard and contributed libraries) as a bonus. Scott From nomail at hursley.ibm.com Mon Oct 27 23:59:50 2003 From: nomail at hursley.ibm.com (Derek Fountain) Date: Tue, 28 Oct 2003 12:59:50 +0800 Subject: PIL: Do I need to close? Message-ID: <3f9df74f$0$23606$5a62ac22@freenews.iinet.net.au> I've just started looking at the PIL module. There doesn't seem to be a close method. Is that right? I just open the image file, and never need to close it? From peter at engcorp.com Mon Oct 20 09:28:41 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 20 Oct 2003 09:28:41 -0400 Subject: Python from Wise Guy's Viewpoint References: Message-ID: <3F93E309.BFA2A735@engcorp.com> mike420 at ziplip.com wrote in separate messages: > > Anyway, this discussion is boring me. I'll leave you to > argue amongst yourselves. My job here is done. ..that job now proven as having been to start a language flame-fest. "420", please stay out of comp.lang.python in the future. I also suspect the comp.lang.functional and comp.lang.lisp people, being reasonable beings, would wish the same for their respective groups. -Peter From __peter__ at web.de Fri Oct 31 14:30:52 2003 From: __peter__ at web.de (Peter Otten) Date: Fri, 31 Oct 2003 20:30:52 +0100 Subject: HTMLParser problems. References: Message-ID: Sean Cody wrote: > I'm trying to take a webpage that has a nxn table of entries (bus times) > and > convert it to a 2D array (list of lists). Initially this was simple but I > need to be able to access whole 'columns' of data so the 2D array cannot > be sparse but in the HTML file I'm parsing there can be sparse entries > which > are repsented in the table as   entities. The sparse output breaks my > ability to use entire columns and have entries correspond properly. > > Is there a simple way to tell the parser whenever you see a   in table > data return say... "-1" or "NaN"? > The HTMLParser documentation is a bit.... terse. I was considering using > the handle_entityref() method but I would assume the data has already been > parsed at that point. > > I could try: > def handle_entityref(self,entity): > if self.in_td == 1: > if entity == "nbsp": > self.row.append(-1) > > But that seems ulgy... (comments?). > > As an example here is some code I'm using and partial output: [...] > parser.feed(socket.read()) The simplest solution is to replace the above line with parser.feed(socket.read().replace(" ", "NaN") Below is an only slightly more robust solution. It implements a rudimentary "what table are we in?" check and can handle table cells with multiple data chunks. import htmllib,os,string,urllib from HTMLParser import HTMLParser class foo(HTMLParser): def __init__(self): self.matrix = [] self.row = None self.cell = None self.in_table = 0 self.empty = "NaN" self.reset() def handle_starttag(self,tag,attrs): if tag == "table": self.in_table += 1 elif self.in_table == 2: if tag == "td": assert self.cell is None self.cell = [] elif tag == "tr": self.row = [] self.matrix.append(self.row) def handle_data(self,data): if self.in_table == 2: if self.cell is not None: data = string.strip(data) if data or True: self.cell.append(data) def handle_endtag(self,tag): if tag == "table": self.in_table -= 1 elif self.in_table == 2: if tag == "td": s = " ".join(self.cell).replace("\n", " ") if s == "": s = self.empty self.row.append(s) self.cell = None elif tag == "tr": self.row = None parser = foo() if 0: instream = urllib.urlopen( "http://winnipegtransit.com/TIMETABLE/TODAY/STOPS/105413bottom.html") else: instream = file("105413bottom.html") data = instream.read() parser.feed(data) instream.close() parser.close() for row in parser.matrix: assert len(row) == 4 print row I've replaced the urlopen() call with access to a local file as you might want to run your tests with a local copy of the time table, too. Peter From james.anderson at setf.de Mon Oct 20 08:19:24 2003 From: james.anderson at setf.de (james anderson) Date: Mon, 20 Oct 2003 14:19:24 +0200 Subject: Python from Wise Guy's Viewpoint References: Message-ID: <3F93D20A.B9D0C30D@setf.de> Joachim Durchholz wrote: > > mike420 at ziplip.com wrote: > > > [...] If you [...] think that multimethods are a BIGGER problem than > > uni-methods, please provide a specific example (in CLOS) > > I can't write in CLOS, I'd make all sorts of stupid mistakes since I > never read more than the language specs (and that's several years in the > past). > Anyway, I lost interest in CLOS when I saw those clumsy BEFORE and AFTER > keywords, and that priorization machinery for multimethods. Too > complicated, too liberal (allowing lots of powerful things and lots of > subtle bugs). > I might be conflating this with Scheme, though. I looked at both at > about the same time :-) how about formulating some examples in some language which is adequate to express them? perhaps somewhat more concretely than the allusions in your earlier message, in which you suggest some problem domains and some amorphously difficult decisions, but despite several rereadings, never concretly indicate what does not "work". what does "different directions" mean? "glue code"? "asymmetry"? a "base class"? a "module"? an "orthogonal extension"? what is the distinction between "dynamic dispatch" and "parametric polymorphism". if not in the context of clos, then, well, in english. > > I'd really like to see a Lisp dialect that valued reliability over raw > expressive power. But I fear this isn't very high on the agenda of the > Lisp community. Besides, it would be difficult to do that - Lisp offers > no protection against peeking at internals and setting up all that > unsafe-but-powerful stuff. what are "internals", what is "protection"? please at least propose some concrete examples or use cases before making assertions to which your opening sentence does not lend much authority. it would be nice to understand better the problem which you appear to want to discuss, but you will need to be more thorough in your exposition. ... > In my eyes, Lisp is a valuable > experimentation lab for new language mechanisms, but not fit for > production use. > Let me add a troll-bait disclaimer: no troll disclaimers necessary, just substance. ... From scott.b.drummonds.nospam at intel.com Wed Oct 1 17:16:59 2003 From: scott.b.drummonds.nospam at intel.com (Scott Brady Drummonds) Date: Wed, 1 Oct 2003 14:16:59 -0700 Subject: Capturing/Recognizing Text In Another Window Message-ID: Hello, everyone, I'd like to write a Python program that could capture the contents of another Windows program and analyze the resultant bitmap. First, I have no idea how to capture another window. Second, I'm not even certain if this graphical problem is a Python issue or a Windows issue. Can anyone offer me some guidance on this? Thanks, Scott -- Remove ".nospam" from the user ID in my e-mail to reply via e-mail. From mis6 at pitt.edu Mon Oct 27 01:57:24 2003 From: mis6 at pitt.edu (Michele Simionato) Date: 26 Oct 2003 22:57:24 -0800 Subject: wxPython and macros (was: Why don't people like lisp? References: <_yYmb.9355$Gq.3838698@twister.nyc.rr.com> Message-ID: <2259b0e2.0310262257.2ca2a920@posting.google.com> Kenny Tilton wrote in message news:<_yYmb.9355$Gq.3838698 at twister.nyc.rr.com>... > Now the million dollar question is: how could the longer version above > be cleaned up without macros, with HOFs or a metaclass hack or something? > > kenny Probably yes. For what concerns automatically calling the base class __init__ method with a metaclass, see this thread (sorry for the long URL): http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&threadm=3nfevuomi6bo0f57n9l354ftusjrvis9v6%404ax.com&rnum=1&prev=/groups%3Fhl%3Den%26lr%3D%26ie%3DISO-8859-1%26q%3Dsimionato%2Bautoinit%26btnG%3DGoogle%2BSearch%26meta%3Dgroup%253Dcomp.lang.python.* It is interesting to notice that I never use this trick since "explicit is better than implicit" and I do prefer to call explicitly the __init__ method. I think it is better for the readers of my classes (including myself six months from now). Michele From raffael at mediaone.net Wed Oct 29 23:40:57 2003 From: raffael at mediaone.net (Raffael Cavallaro) Date: 29 Oct 2003 20:40:57 -0800 Subject: Test cases and static typing References: <87ekx4xaym.dlv@wanadoo.fr> <87znfsvuqh.dlv@wanadoo.fr> <6ogn61-f61.ln1@ID-7776.user.dfncis.de> Message-ID: "Marshall Spight" wrote in message news:... > "Pascal Costanza" wrote in message news:bnc8dj$pvi$1 at f1node01.rhrz.uni-bonn.de... > > > > And that's all I wanted from the very beginning - static typing as an > > additional tool, not as one that I don't have any other choice than use > > by default. > > I can get behind that idea! It strikes me as being better > than what one has now with either statically typed > languages or dynamically typed languages. Then the addition of parameterized types to goo, might interest you. Also see the main goo page: From Erendil at aol.com Sat Oct 18 13:03:43 2003 From: Erendil at aol.com (Erendil at aol.com) Date: Sat, 18 Oct 2003 13:03:43 EDT Subject: Why don't people like lisp? Message-ID: <18a.20df5aa8.2cc2cc6f@aol.com> "All code is non-intuitive and hard to read." Wow...where have you been? I find that well written Python code and extremely well written C++ code is very intuitive and easy to read. As with Python, a friend of mine who knows nothing about it could read several samples of fairly detailed code without trouble. C++ required some explanation from me. He is currently taking a course in Lisp and finds it far less intuitive or easy to read than Python. From hank at bogusaddress.xyz Thu Oct 2 10:56:10 2003 From: hank at bogusaddress.xyz (Hank Kingwood) Date: Thu, 02 Oct 2003 14:56:10 GMT Subject: How To Check For [a-z] In String? In-Reply-To: References: Message-ID: Also, how would I check if [a-z] is not in a string? Thanks again, Hank Hank Kingwood wrote: > This is probably an easy question, but I can't find a function (maybe my > syntax is off...) to search for [a-z] in a string. If someone would > help out, I'd appreciate it! > > Also, how would you recommend searching for the following in the same > string: > [a-z] > [A-Z] > [0-9] > - > > My approach would be to perform four separte checks, but I'm thinking > there might be some cool approach that would use a dictionary or array. > Ideas? > > Thanks, > Hank > From tweedgeezer at hotmail.com Fri Oct 10 13:15:34 2003 From: tweedgeezer at hotmail.com (Jeremy Fincher) Date: 10 Oct 2003 10:15:34 -0700 Subject: Python 2.3.2 Compile problems on Solaris 7. Message-ID: <698f09f8.0310100915.359b2e09@posting.google.com> I'm having problems compiling Python with socket support (and support for several other libraries) on Solaris 7. When I do the standard ./configure, make, make install dance, I got a fully compiled Python without an _socket module. So I uncommented the appropriate socketmodule.c line in Modules/Setup, and recompiled. I get this: gcc -fno-strict-aliasing -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DPy_BUILD_CORE -c ./Modules/socketmodule.c -o Modules/socketmodule.oIn file included from Modules/socketmodule.c:293: Modules/getnameinfo.c: In function `fake_getnameinfo': Modules/getnameinfo.c:173: warning: implicit declaration of function `inet_ntop'Modules/getnameinfo.c:174: warning: comparison between pointer and integer Modules/getnameinfo.c:206: warning: comparison between pointer and integer Modules/socketmodule.c: In function `socket_inet_pton': Modules/socketmodule.c:2972: error: `AF_INET6' undeclared (first use in this function)Modules/socketmodule.c:2972: error: (Each undeclared identifier is reported only onceModules/socketmodule.c:2972: error: for each function it appears in.) Modules/socketmodule.c: In function `socket_inet_ntop': Modules/socketmodule.c:3016: error: `INET_ADDRSTRLEN' undeclared (first use in this function)Modules/socketmodule.c:3046: warning: assignment makes pointer from integer without a castModules/socketmodule.c:3016: warning: unused variable `ip' *** Error code 1 make: Fatal error: Command failed for target `Modules/socketmodule.o' I even tried copying the socketmodule.c from the 2.3b1 source code (which we had been using until now, which supported sockets on our machine) and recompiling to no avail. That's the major problem I'm having and need to solve. Aside from that, I'm also getting hundreds of errors like this: 0x1c60 /usr/common/lib/libncurses.a(lib_tparm.o) with several libraries, including curses and ssl. This is the first real compilation error I've ever had with Python, and I don't know what to do from here. Any help is appreciated :) Thanks, Jeremy From skip at pobox.com Tue Oct 7 07:51:49 2003 From: skip at pobox.com (Skip Montanaro) Date: Tue, 7 Oct 2003 06:51:49 -0500 Subject: interpreter In-Reply-To: <68.35a38b6f.2cb35ce3@aol.com> References: <68.35a38b6f.2cb35ce3@aol.com> Message-ID: <16258.43221.873943.375103@montanaro.dyndns.org> (redirecting away from webmaster and to python-list at python.org) > I'm using python to create a program for my science fair project, and > I'm going to present it on a rather ancient laptop that has windows > 95. Unfortunately it only has a floppy port so I can't install > anything bigger than that, and I was wondering how I could just > download the python interpreter, without idle and all the other stuff, > so I can run the program for my presentation. Is there a way to > separate it once you have downloaded the rest of it onto a different > computer? Assuming you run the installer on another machine with more space, you should be able to delete the parts you don't want and zip up the remainder into a small enough package which will fit on a floppy. Does it have to run from the floppy as well? If not, you can be less ruthless in what you delete and zip up pieces of the Python tree onto multiple floppies. (In fact, WinZip or other zip utilities may know about saving across multiple floppies.) Also, double-check that the version of Python you want to use will run on Win95. I suspect it will, but I doubt Python gets a lot of testing there these days. Good luck with the science fair project... -- Skip Montanaro Got gigs? http://www.musi-cal.com/ http://www.mojam.com/ Got spam? http://spambayes.sf.net/ From fuerte at sci.fi Sun Oct 19 12:20:19 2003 From: fuerte at sci.fi (Harri Pesonen) Date: Sun, 19 Oct 2003 19:20:19 +0300 Subject: Jython, GILs and object locking. In-Reply-To: References: Message-ID: Aahz wrote: > In article , > Harri Pesonen wrote: > >>Aahz wrote: >> >>>In article , >>>Harri Pesonen wrote: >>> >>>>Aahz wrote: >>>> >>>>>In article , >>>>>Harri Pesonen wrote: >>>>> >>>>>>Why? Each thread has its own variables, they are not shared, there is no >>>>>>need for synchronizing. >>>>> >>>>>Either you don't understand how Python currently works or you're talking >>>>>about implementing a completely different language that happens to share >>>>>syntax and some semantics with Python. Which is it? >>>> >>>>Mostly the latter. It would be 99% compatible with the Python syntax, >>>>the only difference would be in threading. But it would be >>>>free-threading, not pseudo-threading as the current Python. >>> >>>The point is that it would be at best 80% compatible with current >>>Python's semantics. CPython doesn't have "variables", it has names and >>>objects; all objects are global within a single process. Changing that >>>semantic has implications far beyond threading. There's also the issue >>>that you keep refusing to address: making Python work with random >>>third-party libraries that aren't thread-safe or thread-hot. >> >>Sure Python has variables. You can call them objects if you like. >> >>Objects are global only within one interpreter state. You can have >>several interpreter and thread states already in CPython. >> >>Only a few static objects are global within a single process. > > Ah. Looks like I guessed right the first time: you *DON'T* understand > how Python works. Never mind. Let me know if/when you want to get > educated by starting a new thread; I'm done wasting my time here. Hehe, what a lozer. Harri From brent.turner at clarisay.com Thu Oct 23 15:44:40 2003 From: brent.turner at clarisay.com (Brent Turner) Date: 23 Oct 2003 12:44:40 -0700 Subject: includes on an exec? References: Message-ID: <2f6cf792.0310231144.29159030@posting.google.com> "berklee just berklee" wrote in message news:... > I want to run a code module by loading the code as any other text file, and > then calling exec() on its contents. > > For some reason, Python doesn't seem to find the includes that are > referenced in the script being called. > > I tried dropping it into the Python 'lib' folder, and in the same folder as > my script, neither seems to work? > > Any suggestions? Here is some code that I use: # class for compiling and using python code (Text) class PyCode: def __init__(self): self.code = None self.module = None # compile module from file def fromFile(self, filename): f = open(filename, 'r') text = f.read() f.close() return self.CompileModule(GetFilenameBase(filename), text) # compile to a module (with name moduleName) from text (code) def CompileModule(self,moduleName, text): # remove all cariage returns (compile does not like it) text = string.replace(text, '\r', '') # make sure there is a line feed at the end # compile does not like it if there is not if text and text[-1] != '\n': text += '\n' co = compile(text, '', 'exec') # create a new module and exec the code object into the dict import imp codeModule = imp.new_module(moduleName) exec co in codeModule.__dict__ return codeModule # clear the compiled code def SetCode(self, code, bCheckDiff = 1): code = string.strip(code) if (bCheckDiff and code != self.code) or not bCheckDiff: self.code = code if self.code: self.module = self.CompileModule('CodeEdit', self.code) else: self.module = None # exec code in the module def execCode(self, code_str): exec code_str in self.module.__dict__ ******************************************************** to Use: pc = PyCode() module = pc.fromFile('Test.py') # now module should act as any other module object Hope this Helps, Brent From tchur at optushome.com.au Sun Oct 12 22:04:44 2003 From: tchur at optushome.com.au (Tim Churches) Date: Mon, 13 Oct 2003 12:04:44 +1000 Subject: Rankordering for nonparametric statistics (Newbie) Message-ID: <200310130204.h9D24i215107@mail017.syd.optusnet.com.au> An embedded and charset-unspecified text was scrubbed... Name: not available URL: From $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk Fri Oct 10 07:47:45 2003 From: $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk (Stephen Horne) Date: Fri, 10 Oct 2003 12:47:45 +0100 Subject: Precision issue References: <8lvhb.258000$R32.8375967@news2.tin.it> Message-ID: <393dovognaci9de797qdtf7i4055ca4f0f@4ax.com> On Fri, 10 Oct 2003 09:54:12 GMT, Alex Martelli wrote: >Ladv?nszky K?roly wrote: > >> Entering 3.4 in Python yields 3.3999999999999999. >> I know it is due to the fact that 3.4 can not be precisely expressed by >> the powers of 2. Can the float handling rules of the underlying layers be >> set from Python so that 3.4 yield 3.4? > >It seems, from the question, that you might not have entirely understood >and grasped the explanations you can find at: >http://www.python.org/doc/current/tut/node14.html >and I quote, in particular: >""" >no matter how many base 2 digits you're willing to use, the decimal value >0.1 cannot be represented exactly as a base 2 fraction. >""" There are simple workarounds for this, though. For instance, if someone needs one or two decimal digits of precision, they can simply hold all values scaled by 10 or 100 - while neither 0.01 nor 0.1 can be precisely represented as a binary value, 1 can be. Actually, scaling by 100 is overkill - the nearest power of two is 128, and 100/128 is equivalent to 25/32, so a scale factor of 25 should be sufficient to allow two decimal digits of precision. However, there is probably no advantage to scaling by 25 instead of 100 - just the disadvantage that the purpose of the scaling is less obvious. Anyway, this could be what Ladv?nszky K?roly meant, I suppose, by 'float handling rules of the underlying layers'. Of course this can't be done using the existing float class as Python doesn't define the float handling rules - they are presumably defined in most cases by the floating point logic built into the CPU. Perhaps Ladv?nszky K?roly has used Ada, where you can request a fixed point or floating point type with particular properties and it is up to the compiler to find or create one to suit. Though IIRC its floats are still always binary floats - only its fixed point values can handle decimals as Ladv?nszky K?roly has requested. There are also, of course, languages which support different numeric types such as a decimal type - Java has BigDecimal and C# has Decimal (the C# one works using a fixed point scaling where the scaling must be a power of 10, Java BigDecimal is IIRC more powerful - arbitrary scale and precision, I think). The issue of alternate numeric representations does get raised from time to time, as I'm sure Alex knows better than me. There are packages around. One key problem is that different people want different things. A person who wants a fixed-point number class, for instance, is not going to want the additional overhead from a rational number class. Even a symbolic expression class has been suggested in the past. One common need for decimals is for currency values. This need can be avoided by simply storing currency values in pence/cents rather than pounds/dollars. Similarly, percentages can be handled using integer calculations. For example, adding 17.5% (for UK VAT, perhaps) can be handled using floats as follows... result = value * 1.175 or using integers as follows... result = (value * 1175) / 1000 In the example above, the parentheses are unnecessary but included to emphasise the order of the calculations, which is important. In my experience, this method handles most cases where results need to be consistent with decimal arithmetic - store values using appropriate units and the problem usually goes away. -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From bokr at oz.net Thu Oct 30 03:04:45 2003 From: bokr at oz.net (Bengt Richter) Date: 30 Oct 2003 08:04:45 GMT Subject: How do you make Python reliable??? References: Message-ID: On Wed, 29 Oct 2003 23:52:29 -0500, "Aubrey Hutchison" wrote: >Using Python 2,3,2 with idle for developing programs >about 200 lines long. - Problem is not common to any specific program. >Program are rather simple with no trick programming. Usually no classes but >a few functions using math module with long integers. > >Usually for the first few tryout everything works fine and >then idle locks "out" windows xp pro.. I can run other programs, but >clicking on idle icon gets me an hour glass for a few moments and then goes >away. > >Acts like I filled up memory but with 1 gig that should not >be a problem. > >Word, Acad, quickbasic, and anyother program will work when python starts >doing this lock out. But python will not work. Killing the computer is the >usual way out of the problem. > >Shuting down just get me a dialog window telling me to click to shut down >windowmenu. Which only gets me the >same dialog a few moment later. > >Full power off is usually the only way, and at time upon reboot -the same >will continue. > >When this happens I can load a game, Acad or word which work as they should. > >When this starts I get an indication the idle is not responding and I kill >it with the status panel.Some times this happens only once but usually it >ends up as a lock out. > >Computer is clean- no virus. > >Thanks for any help > The best way would be to provide a minimal recipe for duplicating your problem. Otherwise we'll be playing 20 questions until someone gets an inspiration. Meanwhile, when stuck, will Ctrl-C have any effect? If not, how about Ctrl-D or Ctrl-Break? I hardly ever run idle, but I just did, and I seem to have experienced a bit of the same problem ;-( I dimissed it with Ctrl-D after a Ctrl-C, and then when I tried to start it again from the start menu ( I am on NT4 with python 2.3 something: >>> sys.version '2.3 (#46, Jul 29 2003, 18:54:32) [MSC v.1200 32 bit (Intel)]' >>> sys.version_info (2, 3, 0, 'final', 0) ) and it did not come up. Ctrl-Alt-Del gave me the security dialog that lets me run the task manager, which I tried, and _it_ did not pop up. Normally it displaces almost anything. This makes me wonder if idle is using something that runs at super high priority and forgets to let go or lower its priority if it gets blocked. Eventually applications started to respond to Alt-F4 (I had quite a few instances of vim and netstcape and a few console windows going plus agent and eudora, so it's hard to say what was happening, but I didn't like the feel. I have 320 MB ram, so normally I can keep a lot of stuff open simultaneously. I don't think it was a memory problem. IIRC I read/heard that idle runs as separate communicating processes now. I could see someone being tempted to boost priority somewhere to keep the user experience tolerably snappy on an older machine. Output like "for i in range(400): print i," is really slow on mine, compared to the console version. Not being an idle user (;-) I can't say much more at this point. But given that all I did was start it up, print a series of numbers and kill it with Ctrl-C and Ctrl-D, perhaps you don't need to work up much of a recipe for duplicating the problem. After the aforementioned, just trying to start it again brought it on. As for your subject question, I find the console version quite reliable, and would recommend using that, along with vim or another editor that suits you. Sorry if this idle UI bog-down was your first exposure to Python (though it is not Python per se, only a UI). Regards, Bengt Richter From tjreedy at udel.edu Sun Oct 5 16:57:22 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 5 Oct 2003 16:57:22 -0400 Subject: Newcomer struggling with tutorial References: Message-ID: <8sydnfO-5KoqGB2iXTWJkA@comcast.com> "CPK Smithies" wrote in message news:blpf2k$fef$1 at titan.btinternet.com... > What I found so disturbing is that > a < b == c > is not equivalent either to > (a < b) == c > nor to > a < (b == c) > since (given that for example (a, b, c) == (-1, 77, 1)) the first is false > while the latter are both true. Correct. Chained comparisons, like logical 'and' and 'or' are convenient 'special forms' (to use the Scheme/Lisp terminology) that one has to learn if you are to read or write them. I believe all other operators act as you expect. Terry J. Reedy From oest at soetu.eu Wed Oct 15 17:47:27 2003 From: oest at soetu.eu (Carlo v. Dango) Date: Wed, 15 Oct 2003 23:47:27 +0200 Subject: inner classes in python as inner classes in Java References: Message-ID: Comming to think of it, it can't be done in python! Since there is no way to denote you want to access a field rather than creating a new one, __setattr__ will have no changes of knowing when to create the field or look it up in the outer scope... this suxx man... I never understood the smart thing about that feature in python.. anyone care to enlighten me? <- carlo -> -- Using M2, Opera's revolutionary e-mail client: http://www.opera.com/m2/ From eppstein at ics.uci.edu Mon Oct 6 13:46:13 2003 From: eppstein at ics.uci.edu (David Eppstein) Date: Mon, 06 Oct 2003 10:46:13 -0700 Subject: Python syntax in Lisp and Scheme References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> <92c59a2c.0310031345.57d20631@posting.google.com> Message-ID: In article , my-first-name.my-last-name at jpl.nasa.gov (Erann Gat) wrote: > > : Here's another example of what you can do with macros in Lisp: > > > > : (with-collector collect > > : (do-file-lines (l some-file-name) > > : (if (some-property l) (collect l)))) > > > > : This returns a list of all the lines in a file that have some property. > > > > OK, that's _definitely_ just a filter: filter someproperty somefilename > > Perhaps throw in a fold if you are trying to abstract "collect". > > The net effect is a filter, but again, you need to stop thinking about the > "what" and start thinking about the "how", otherwise, as I said, there's > no reason to use anything other than machine language. Answer 1: literal translation into Python. The closest analogue of with-collector etc would be Python's simple generators (yield keyword) and do-with-file-lines is expressed in python with a for loop. So: def lines_with_some_property(some_file_name): for l in some_file_name: if some_property(l): yield l Your only use of macros in this example is to handle the with-collector syntax, which is handled in a clean macro-free way by Python's "yield". So this is unconvincing as a demonstration of why macros are a necessary part of a good programming language. Of course, with-collector could be embedded in a larger piece of code, while using yield forces lines_with_some_property to be a separate function, but modularity is good... Answer 2: poetic translation into Python. If I think about "how" I want to express this sort of filtering, I end up with something much less like the imperative-style code above and much more like: [l for l in some_file_name if some_property(l)] I have no problem with the assertion that macros are an important part of Lisp, but you seem to be arguing more generally that the lack of macros makes other languages like Python inferior because the literal translations of certain macro-based code are impossible or more cumbersome. For the present example, even that argument fails, but more generally you'll have to also convince me that even a freer poetic translation doesn't work. -- David Eppstein http://www.ics.uci.edu/~eppstein/ Univ. of California, Irvine, School of Information & Computer Science From asd at asd.it Thu Oct 23 12:07:56 2003 From: asd at asd.it (danissim) Date: Thu, 23 Oct 2003 18:07:56 +0200 Subject: please help me!! References: <3F97E7D2.B591C96F@engcorp.com> Message-ID: thanks a lot ! i have win xp and i've installed python 2.3 this is my first work with python i must to do somthing that rename the files into a folder for example in to a folder "work" i have the files "asd.jpg" "dsa.jpg" and "esd.jpg" now i must to rename the pictures to "workF.jpg""workR.jpg""workD.jpg" sorry but i'm a virgin with python... "Peter Hansen" ha scritto nel messaggio news:3F97E7D2.B591C96F at engcorp.com... > danissim wrote: > > > > help!! > > hi people > > could you to tell me how can i execute a program after i wrote the code??? > > If you program is saved in a file named "mycode.py", you would execute the > following command at a command prompt: "python mycode.py" > > This will work only if your computer is properly configured. You need > the folder containing the Python executable (e.g. python.exe on Windows) > to be in your PATH environment variable, for example. > > You haven't included enough information for anyone to help more. What > platform/operating system are you using. How do you write your code? > Using an IDE, such as IDLE or PythonWin, or using another text editor? > Have you installed Python yet? > > Also, have you done the online tutorial yet? It gives useful background > that might help you out. > > See http://www.python.org/doc/current/tut/tut.html > > -Peter From tjreedy at udel.edu Sun Oct 19 19:27:52 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 19 Oct 2003 19:27:52 -0400 Subject: Python from Wise Guy's Viewpoint References: <_8Ekb.7543$pT1.318@twister.nyc.rr.com> Message-ID: "Scott McIntire" wrote in message news:MoEkb.821534$YN5.832338 at sccrnsc01... > There was a nice example from one of the ILC 2003 talks about a Europian > Space Agency rocket exploding with a valueable payload. My understanding was > that there was testing, but maybe too much emphasis was placed the static > type checking of the language used to control the rocket. The end result was > a run time arithmetic overflow which the code intepreted as "rocket off > course". The rocket code instructions in this event were to self destruct. > It seems to me that the Agency would have fared better if they just used > Lisp - which has bignums - and relied more on regression suites and less on > the belief that static type checking systems would save the day. > > I'd be interested in hearing more about this from someone who knows the > details. I believe you are referring to the first flight of the Ariane 5 (sp?). The report of the investigating commission is on the web somewhere and an interesting read. They identified about five distinct errors. Try google. Terry From jjl at pobox.com Mon Oct 27 15:57:02 2003 From: jjl at pobox.com (John J. Lee) Date: 27 Oct 2003 20:57:02 +0000 Subject: AI and cognitive psychology rant (getting more and more OT - tell me if I should shut up) References: <2askpv0sqrv7k9hbpis3ig4iqclpl24ojc@4ax.com> <3f8lpvsddmeltg69vkl2uu8u8cei7bb2cg@4ax.com> <8nlnpvcsgodtmlpfng7rtf27r1s7hi56ph@4ax.com> <87d6cjope5.fsf@pobox.com> <87he1vsopi.fsf@pobox.com> Message-ID: <87d6cio0v5.fsf@pobox.com> Stephen Horne writes: > On 26 Oct 2003 20:56:09 +0000, jjl at pobox.com (John J. Lee) wrote: > > >> Yes, but why can we see the affects of superposition at the > >> microscopic scale but not at the macroscopic. That is what strikes me > >> as odd - if parallel universes work as an explanation, then why do > >> they work differently at the two scales. In particular, why can we not > > > >They don't. > > Are you claiming that in schroedingers experiment that the dead and > live cats interact in some way that can be measured outside the box > without collapsing the waveform? Well, in the many-worlds interpretation (MWI) there *is* no wavefunction collapse: everything just evolves deterministically according to the Schrodinger equation. But of course, since cats are big lumps of matter, one wouldn't expect to be able to measure interference effects using cats. > I was also under the impression that the largest 'particle' to be > successfully superposed in an experiment was a buckyball (or something > like that - at least a 'large' molecule of some kind or another) and > the timescale for that superposition was tiny. The largest *measured* superposition, yes. The Copenhagen interpretation says that the world evolves according to the Schrodinger equation until, um, it stops doing that, and collapses to an eigenstate. When does the Copenhagen interpretation say the wfn collapses? It doesn't! It denies any meaning to that question. That's claiming that we just "shouldn't" ask about this part of reality, and stop our enquiry there. Why should I follow that instruction when the MWI explains exactly what happens? If a theory explains more than its rival, one rejects the rival theory. And it doesn't make any sense to say "there are many universes, except for large objects, for which there is only one universe". This brings us into epistemological issues which Deutsch deals with in his book much better than I can. Of course, there's more to this debate than Copenhagen vs. MWI, but the other rival theories all (to my very limited knowledge) seem to be either re-hashings of MWI in disguise, or complicated theories that introduce ad-hoc irrelevancies without any compensating benefit. And, to dispense with the absurd objection that MWI is 'expensive in universes', since when has complexity of *entities* been a criterion on which to judge a theory?? Complexity of *theories* of the world is a problem, complexity of the world itself is not. Indeed, one thing we know independent of any theory of quantum mechanics (QM) is that the world is damned complicated! > Yet the whole point of the thought experiment is that according to the > theory, as conventionally described (I know next to nothing of the > detail), it should be possible for a cat to be superposed almost as > easily as it is possible for a subatomic particle - a simple > cause-and-effect chain is all that is needed. If that is the case, > superpositions of macroscopic objects should be happening all the > time. They do, yes! > Now either the superpositions are in parallel universes with each > state undetectable from an observer in another one of those universes, *The fact that those superpositions exist* is justified by the fact that MWI is the best theory of QM that we have. The particular nature of a particular large object's superposition is not measurable. Contrary to popular belief, this raises no major epistemological problems for MWI, and does not turn it into metaphysics. > or they are in the same universe and detectable in some way, or there > is a differentiation between the microscopic and macroscopic scales, > or - and this is very likely, I admit - I am seriously confused about > what the hell is going on (the natural state for a human confronted > with quantum theory). Saying that superpositions are "in one universe" or another seems to be playing mix-n-match with the various theories. [...] > >We see exactly the effects that the theory predicts. They're just > >very small. > > OK - so why is it not possible to detect the superposition of that > cat? Why is the experiment still considered a thought experiment only? Simply because that's what QM predicts for large objects. The 'accident' of the size of Planck's constant means that interference effects are small for large objects. The universes involved are none the less real for that: denying that requires doublethink. Interference effects aside, why *should* we experience anything unusual when "we" (scare quotes because issues of personal identiy come up here, of course) exist as a superposition, ie. when we exist in multiple universes? There is a very close parallel here with people's disbelief in the round-earth theory because they couldn't see why they wouldn't fall off the earth if they moved too far from "the top of the earth". Why don't we fall off the earth? Because the (scientifically justified) theory says we won't. Why doesn't the me in this universe experience multiple universes simultaneously? Because the (scientifically justified) theory says I won't. Why *should* we experience multiple universes? -- universes are entirely independent of each other apart from interference effects that are only large for very small objects, or slightly larger and very carefully constructed ones. But again, for those arguments in more detail you're vastly better advised to go to David Deutsch's (extremely readable and enlightening) book than to me :-) [...] > >Yeah -- hence the solipsism joke. > > Ah - sorry - I'm not actually familiar with that term. Well, explaining a joke always spoils it, but: a solipsist is a person who believes that he is the only real thing in existence. The rest of the universe, to a solipsist (to *the* solipsist, in fact ;-) is simply the result of his own imaginings. Deutsch very clearly presents an argument that this position is indefensible and meaningless, starting from that joke I quoted. John From hans at zephyrfalcon.org Sat Oct 4 21:20:40 2003 From: hans at zephyrfalcon.org (Hans Nowak) Date: Sat, 04 Oct 2003 21:20:40 -0400 Subject: Python syntax in Lisp and Scheme In-Reply-To: References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> <92c59a2c.0310031345.57d20631@posting.google.com> <8b9e2260.0310032317.72abd86a@posting.google.com> <5vvf/kKkXU0D092yn@gnosis.cx> Message-ID: <3F7F71E8.1050809@zephyrfalcon.org> Lulu of the Lotus-Eaters wrote: > grzegorz at pithekos.net (Grzegorz Chrupala) wrote previously: > |shocked at how awkward Paul Graham's "accumulator generator" snippet is > |in Python: > |class foo: > | def __init__(self, n): > | self.n = n > | def __call__(self, i): > | self.n += i > | return self.n > > Me too. The way I'd do it is probably a lot closer to the way Schemers > would do it: > > >>> def foo(i, accum=[0]): > ... accum[0]+=i > ... return accum[0] > ... > >>> foo(1) > 1 > >>> foo(3) > 4 > > Shorter, and without an awkward class. Yah, but instead it abuses a relatively obscure Python feature... the fact that default arguments are created when the function is created (rather than when it is called). I'd rather have the class, which is, IMHO, a better way to preserve state than closures. (Explicit being better than implicit and all that... :-) -- Hans (hans at zephyrfalcon.org) http://zephyrfalcon.org/ From g_will at cyberus.ca Tue Oct 28 10:17:27 2003 From: g_will at cyberus.ca (Gordon Williams) Date: Tue, 28 Oct 2003 10:17:27 -0500 Subject: Installation of Python 2.3 on Windows 95 Message-ID: <001101c39d66$9910b5a0$a056e640@amd950> Don wrote: We have attempted several times to install Python 2.3 on a Windows 95 system. Each time, at the end of the install the following error is displayed: A while back I had some problems with python win on Windows 95. This is the thread. http://groups.google.com/groups?q=serial+error+gordon+group:comp.lang.python .*&hl=en&lr=&ie=UTF-8&group=comp.lang.python.*&selm=DOr4a.70%24hv3.13231%40n ews20.bellglobal.com&rnum=3 Seems like people are not interested in supporting W95 any more. Too bad because there are a lot of old machines and laptops that are just fine for doing low level stuff. Good luck. Gordon Williams From jfranzXREMOVEX at neurokode.com Thu Oct 16 17:10:18 2003 From: jfranzXREMOVEX at neurokode.com (Jon Franz_antispam) Date: Thu, 16 Oct 2003 17:10:18 -0400 Subject: Jython, GILs and object locking. References: Message-ID: <01d401c39429$e94c0830$7401a8c0@voidmk9> Daniel wrote: > A test would still be needed in the ref counting macros to check for > global/thread local. I don't know the overhead for this, but as there <> > But removing the object from the list wouldn't make it local again as > there could be other global objects pointing to it. > > I think "painful to implement" doesn't even begin to describe it. All the reasons given above are why I said it would be painful - it just appears we have different definitions of painful. I don't use it lightly. Jumping over to another part of this conversation.... Harri Pesonen wrote: > You are probably asking next "how threads can communicate". They can > communicate with messages, and via special shared interpreter state, > which needs a new "shared" keyword in python. Access to these shared > variables is synchronized, all other variables are local to thread, and > they need not be synchronized Unless these shared variables had different semantics than all other python variables, that is, assignment by value, not reference, then shared variables can have the same issues as described above by Daniel - assignment to/from local variables will complicate matters greatly. .................. But the message passing scheme brings to mind a new idea for a different take on reference counting, once again, painful, this time especially so. Remember that I'm throwing ideas out as I have them, and I'm not edorsing the ideas, just bringing them up. Move reference counting to its own thread. Py_INCREF and Py_DECREF would send messages to this thread, thus avoiding locking. The reference counting thread would then be responsible for all GC, and timing of GC for an object would never be guaranteed - it could be collected almost immediately, or in 2 seconds when the ref-count thread has worked its way through its message queue and 'gets to' the final DECREF message. Internally, the GC thread (that fits more than calling it a ref-count thread) would need to keep track of which thread the references were held for - thus thread-exit would trigger a DECREF for all outstanding refs held by a thread. Storing the ownership of a reference internally to the GC would seem preferable to storing it thread-local, since an abnormal thread-exit could prevent DECREF messages from being delivered by a thread on exit. Pros: - the GC thread can continue in the background while the rest of the process exits. This doesn't apply to most users, but for programs will large amounts of objects (>1000000), the time it takes to tear-down a python process can be excessive, and leave you waiting for a command prompt (if you happen to have launched the process from one.). (I can provide an example script for anyone running on a large memory (>4GB) system for those curious about this phenomenon.) - no locking for ref-counting Cons: - Ugly, very painful to implement. - It is unclear what thread-context del methods on an object should be considered for and DECREFs they trigger. Possibly the thread that created the object? - True benefit (speed wise) unknown since impact of extra thread and message passing is unknown. ~Jon Franz From snarflemike at yahoo.com Fri Oct 24 17:06:39 2003 From: snarflemike at yahoo.com (Mike Silva) Date: 24 Oct 2003 14:06:39 -0700 Subject: Python from Wise Guy's Viewpoint References: <_8Ekb.7543$pT1.318@twister.nyc.rr.com> Message-ID: <20619edc.0310241306.631ff013@posting.google.com> "Marshall Spight" wrote in message news:... > "Scott McIntire" wrote in message news:MoEkb.821534$YN5.832338 at sccrnsc01... > > It seems to me that the Agency would have fared better if they just used > > Lisp - which has bignums - and relied more on regression suites and less on > > the belief that static type checking systems would save the day. > > I find that an odd conclusion. Given that the cost of bugs is so high > (especially in the cited case) I don't see a good reason for discarding > *anything* that leads to better correctness. Yes, bignums is a good > idea: overflow bugs in this day and age are as bad as C-style buffer > overruns. Why work with a language that allows them when there > are languages that don't? As I understand it, the Operand Error that caused the grief was a hardware trap in the 68k FPU. Seems that this trap would have been programmed to do the same thing regardless of the language used. Also, I wouldn't call this an overflow "bug." The code was written to assume (based on proofs) that any overflow indicated a hardware failure, and to take the designed action for hardware failure. It would have been trivial for the programmers to prevent the overflow or handle it in another way. Instead, they made a deliberate decision that the default exception handling was exactly the right response for overflow on this variable. Mike From aleax at aleax.it Wed Oct 29 05:01:01 2003 From: aleax at aleax.it (Alex Martelli) Date: Wed, 29 Oct 2003 10:01:01 GMT Subject: Python slow for filter scripts References: <9769adc8.0310281233.5fc5d252@posting.google.com> Message-ID: William Park wrote: > Alex Martelli wrote: >> and I'm specifically reading the King James' Bible (an easily >> available text so you can reproduct my results!) and writing > > Can you post URL for the Bible? I originally got it from some MySQL stuff by Paul DuBois and decided it would make a good general dataset for reproducible tests and benchmarks. A little googling suggests that it comes from: http://unbound.biola.edu/zips/index.cfm?lang=English and specifically from the kjv.zip referenced there under the "King James Version" anchor (unzipped, of course). Alex From mertz at gnosis.cx Sat Oct 18 15:11:17 2003 From: mertz at gnosis.cx (Lulu of the Lotus-Eaters) Date: Sat, 18 Oct 2003 15:11:17 -0400 Subject: Why don't people like lisp? References: <1A8kb.67406$pv6.3464@twister.nyc.rr.com> Message-ID: |> In my own mind, the biggest impediment to really liking Lisp is not the |> annoying parentheses and awful syntax... it's many Lispers (especially |> those like Tilton). Pascal Costanza wrote previously: |You don't like Lisp because you don't like some other guy who is using |it?!? Absolutely! One of the things that is greatest about Python is its programming community, and its newsgroup. Quite apart from any matters of syntax or semantics, or OOP vs. FP, or any of that stuff, it's a heck of a lot nicer working in a language where you can get friendly, helpful, informative answers to questions... and ones that lack scorn and contempt. >From what I can tell, Lisp would be a terrible choice from that POV. Python is good, but so are, e.g., Ruby or Haskell in slightly different ways. Perl, PHP, C++, and Java would probably be ranked in descending order here, but still mostly positive. The only languages I've seen with truly vindictive and nasty user communities are Lisp... and VB. It's a strange closeness of the two. All the more so because VB has a lot of poorly educated, not particularly bright, user who are merely boastfully defensive about the only thing they know. To the contrary, I clearly recognize that Lispers--even most of the most over-the-top rude ones--are startlingly intelligent. I'm not sure which is worse though... someone like Tilton is easily smart enough to avoid sophistry, and yet he engages in it. All that said, I also know that you cannot choose a language ONLY on its user community. Obviously issues like static/dynamic typing, available libraries, platform ports, and lots of issues cannot be brushed off. Even speed of execution occassionally matters. Yours, Lulu... -- mertz@ _/_/_/_/_/_/_/ THIS MESSAGE WAS BROUGHT TO YOU BY:_/_/_/_/ v i gnosis _/_/ Postmodern Enterprises _/_/ s r .cx _/_/ MAKERS OF CHAOS.... _/_/ i u _/_/_/_/_/ LOOK FOR IT IN A NEIGHBORHOOD NEAR YOU_/_/_/_/_/ g s From perry62fr at yahoo.fr Wed Oct 8 04:39:59 2003 From: perry62fr at yahoo.fr (=?iso-8859-1?q?jonathan=20hunt?=) Date: Wed, 8 Oct 2003 10:39:59 +0200 (CEST) Subject: Communications with DDE Message-ID: <20031008083959.81246.qmail@web21507.mail.yahoo.com> Does someone know the set of class and functions from the DDE module? This module in the distribution of Python2.3 under the form of dde.pyd and with two examples: Ddeserver.py and Ddeclient.py. The whole set runs correctly but i search more information because i want to do communicate a ddeserver written in C++ and a ddeclient written in Python. Is there another method for this purpose? With all my thanks. --------------------------------- Do You Yahoo!? -- Une adresse @yahoo.fr gratuite et en fran?ais ! Testez le nouveau Yahoo! Mail -------------- next part -------------- An HTML attachment was scrubbed... URL: From hs at heaven.nirvananet Tue Oct 14 12:38:35 2003 From: hs at heaven.nirvananet (Hartmann Schaffer) Date: 14 Oct 2003 12:38:35 -0400 Subject: Python syntax in Lisp and Scheme References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> <92c59a2c.0310031345.57d20631@posting.google.com> <8yno1dvi.fsf@comcast.net> Message-ID: <3f8c268b@news.sentex.net> In article , Raffael Cavallaro writes: > In article <8yno1dvi.fsf at comcast.net>, prunesquallor at comcast.net wrote: > >> (flet ((add-offset (x) (+ x offset))) >> (map 'list #'add-offset some-list)) > > But flet is just lambda in drag. I mean real, named functions, with > defun. Then the code becomes: > > (add-offset the-list) > > instead of either of theversions you gave. the version he gave has the advantage that it doesn't clutter up the namespace of the environment. with (map (lambda (x) (+ x offset)) the-list) you have everything that is relevant in the immediate neighborhood of the statement. with a separate defun you have to search the program to see what the function does. i agree that for lengthy functions defining it separately and just writing the name is preferrable. > ... > I guess I'm arguing that the low level implementation details should not > be inlined by the programmer, but by the compiler. To my eye, anonymous > functions look like programmer inlining. i would call this a misconception hs -- ceterum censeo SCO esse delendam From adalke at mindspring.com Fri Oct 3 19:23:37 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Fri, 03 Oct 2003 23:23:37 GMT Subject: GIL in the new glossary References: <87oewzyv81.fsf@pobox.com> Message-ID: John J. Lee: > Did you get the earlier references to POSH? > > http://poshmodule.sourceforge.net/posh/html/ To point out, the C extension uses a spin lock written in Intel assembly, so doesn't work on my PowerBook. And I don't want to learn enough assembly to supply my own version. Andrew dalke at dalkescientific.com From enrique.palomo at xgs-spain.com Thu Oct 16 06:21:35 2003 From: enrique.palomo at xgs-spain.com (Enrique) Date: Thu, 16 Oct 2003 12:21:35 +0200 Subject: xls to txt Message-ID: Hello all, I`m searching in www, win32com docs, o'really examples, ... and i can?t find anything that i can use. i wan`t to make a simple script to pass an excel file to txt file. where can i find the methods to work, or sample code?? Thanks **AVISO DE CONFIDENCIALIDAD** La informaci?n contenida en este mensaje y archivos es privada y confidencial estando dirigida solamente al destinatario. Si Ud. ha recibido esta informaci?n por error, por favor, proceda a su inmediata destrucci?n. Cualquier opini?n o punto de vista contenido en este mensaje corresponde al remitente y necesariamente no representa la opini?n del GRUPO XEROX. -------------- next part -------------- An HTML attachment was scrubbed... URL: From peter at engcorp.com Mon Oct 20 09:25:17 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 20 Oct 2003 09:25:17 -0400 Subject: Python from Wise Guy's Viewpoint References: <840592e1.0310192322.6a765e87@posting.google.com> Message-ID: <3F93E23D.2E8F48C4@engcorp.com> Gerrit Holl wrote: > > But I have heard that there are a > lot of former Python programmers in the Ruby community. I think > it is safe to say that of all languages Python programmers migrate > to, Ruby is the strongest magnet. OTOH, the migration of this part > of the Python community to Ruby may have been completed already, > of course. And also on the other hand, perhaps not enough time has yet passed for us to see the migration of these fickle people *back* to Python. :-) -Peter From aleaxit at yahoo.com Sun Oct 12 11:30:48 2003 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 12 Oct 2003 15:30:48 GMT Subject: private variables/methods References: <3F856275.C884CE5@engcorp.com> Message-ID: Terry Reedy wrote: ... >>>> globals()[__name__] = __import__(__name__) >>>> __main__ > > > I believe globals line above will work in imported modules, in which > __name__ is import name (file name if from file), but have not tested > it in such. Yes, this will work at the global level in any module. But it's not a normal import instruction, while the modified builtin __import__ I showed does allow normal importing; and your _use_ of __import__ and globals() cannot bind a _local_ variable of a function to the current module object. >> I think that __current_module__ is perhaps a bit too lengthy > > and redundant ;-) I disagree. Lengthy it may be, but we do want a 'reserved module name' to use for this purpose. For a normal import instruction to work, and to work just as well if you cut and paste the same function elsewhere, I think we want to define that "import somespecificname" is importing THIS module, the CURRENT module, under that name (or another specified with 'as'). This can be experimented with easily, by changing the builtin __import__ (or setting an import hook, maybe) in site-specific file; and if it catches on the builtin __import__ could easily be customized to perform the same task quite speedily. Alex From torfer at pvv.org Thu Oct 2 09:03:30 2003 From: torfer at pvv.org (Tore Ferner) Date: Thu, 02 Oct 2003 15:03:30 +0200 Subject: rpath in setup.py? Message-ID: <3F7C2222.5080102@pvv.org> Hi, On linux: I'm a newbie and want to make build-versions of python 2.1.3 and it's modules which link against different versions of a library located in directories not mentioned in /etc/ld.so.conf, e.g. versions of expat could be: /opt/expatx /opt/expaty /opt/expatz How do I make python use -rpath against such directories, for example by changing setup.py? So far I've made setup.py detect my expat.h in /opt/expat/include, but when I use ldd on pyexpat.so, the libexpat located in /usr/lib is used instead of /opt/expatx/lib. I have tried to use flags like LDFLAGS="-Wl,--rpath -Wl,/opt/expatx/lib" and similar things during ./configure and make, but without luck. I am confused... I use Debian "stable" with gcc/g++ 3.3 and GNU ld 2.11.90.0.8 from "testing". Any help/links will be greatly appreciated!! Regards, Tore From martin at v.loewis.de Fri Oct 10 18:51:15 2003 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 11 Oct 2003 00:51:15 +0200 Subject: Unicode troubles In-Reply-To: <3f85733a_2@nova.entelchile.net> References: <3f85733a_2@nova.entelchile.net> Message-ID: <3F8737E3.2080103@v.loewis.de> Rodrigo Benenson wrote: > Sometimes I get len(u"el?") = 3 (the good result) and other times > len(u"el?") = 4 (wrong result). These seems indiferent of the OS. You should not use non-ASCII characters in source code, unless you also use a PEP 263 source encoding. Most likely, the string your editor displays is not the string you are constructing. Use hexadecimal or symbolic notation for non-ASCII characters in Python source code. Available notations are \x, \u, and \N. Regards, Martin From gerrit at nl.linux.org Thu Oct 9 04:26:17 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Thu, 9 Oct 2003 10:26:17 +0200 Subject: OT: Larry Wall In-Reply-To: References: Message-ID: <20031009082617.GA3191@nl.linux.org> I saw this message on python-checkins: > Modified Files: > ACKS NEWS (...) > diff -C2 -d -r1.247 -r1.248 > *** ACKS 2 Sep 2003 02:13:42 -0000 1.247 > --- ACKS 8 Oct 2003 21:08:29 -0000 1.248 > *************** > *** 573,576 **** > --- 573,577 ---- > Richard Walker > Larry Wall > + Wojtek Walczak > Greg Ward > Barry Warsaw Huh? Has Larry Wall actually contributed to Python? Kewl :) Gerrit. -- 263. If he kill the cattle or sheep that were given to him, he shall compensate the owner with cattle for cattle and sheep for sheep. -- 1780 BC, Hammurabi, Code of Law -- Asperger Syndroom - een persoonlijke benadering: http://people.nl.linux.org/~gerrit/ Kom in verzet tegen dit kabinet: http://www.sp.nl/ From amk at amk.ca Sat Oct 11 07:17:26 2003 From: amk at amk.ca (A.M. Kuchling) Date: Sat, 11 Oct 2003 06:17:26 -0500 Subject: Jython, GILs and object locking. References: <1065822463.3f8728ff68fd9@mcherm.com> Message-ID: On Fri, 10 Oct 2003 21:28:06 -0400, Jon Franz_antispam wrote: > Where XXX is a reference describing the GIL and the limitations it > imposes. I've always thought a threading FAQ would be useful. --amk From a.schmolck at gmx.net Mon Oct 13 16:22:39 2003 From: a.schmolck at gmx.net (Alexander Schmolck) Date: 13 Oct 2003 21:22:39 +0100 Subject: question: usage of __slots__ References: <3F89620C.4080605@snafu.de> Message-ID: "T. Kaufmann" writes: > Hi there, > > Can somebody give me some good examples of the usage of __slots__? __slots__ are a premature optimization and best avoided. 'as From andy47 at halfcooked.com Tue Oct 28 12:45:16 2003 From: andy47 at halfcooked.com (Andy Todd) Date: Tue, 28 Oct 2003 17:45:16 +0000 Subject: SQL recordset -> XML In-Reply-To: <282f826a.0310271500.62fe7a5a@posting.google.com> References: <282f826a.0310271500.62fe7a5a@posting.google.com> Message-ID: Richard Shea wrote: > Hi - Not sure if this is a really stupid question or not ... so I > thought I'd ask it anyway ;-) > > I want to take data from a SQL generated recordset and represent it as > XML. > > I can think of *very* straightforward ways (as I'm sure all you can) > to do that (please excuse rough/weird pseudo code) ... > [snip] You may also want to check out the Effbot's ElementTree as well (http://effbot.org/zone/element-index.htm). It has a component called the 'Simple XML Writer' which may fit your needs. Regards, Andy -- -------------------------------------------------------------------------------- From the desk of Andrew J Todd esq - http://www.halfcooked.com/ From jjl at pobox.com Sun Oct 26 10:10:36 2003 From: jjl at pobox.com (John J. Lee) Date: 26 Oct 2003 15:10:36 +0000 Subject: AI and cognitive psychology rant (getting more and more OT - tell me if I should shut up) References: <0KRib.213549$hE5.7197672@news1.tin.it> <7id6cz7rl4.fsf@enark.csis.hku.hk> <9XVib.214859$hE5.7243121@news1.tin.it> <3ovpovc9hmahv5g373jm2oo7mk3i83ldtb@4ax.com> <29cjb.218983$hE5.7379913@news1.tin.it> <5tksov8r4c3caoatfoslfi87q61dupaq81@4ax.com> <2askpv0sqrv7k9hbpis3ig4iqclpl24ojc@4ax.com> Message-ID: <874qxwxcer.fsf@pobox.com> What an outrageously off-topic thread, I can't resist it :-) Robin Becker writes: > In article <2askpv0sqrv7k9hbpis3ig4iqclpl24ojc at 4ax.com>, Stephen Horne > writes > >Even if this was not the case, you have not proved that reality is not > >real. What would it mean to 'prove that reality is not real', in fact?? > >Of course perception still varies slightly from person to > >person, and more extensively from species to species, It can vary in arbitrarily large ways. Our perception of the world is based on our understanding of it (our models of it), including that 'understanding' embodied in our biology, put there by our evolutionary past. > >but it is not > >independent of reality - it still has to be tied to reality as closely > >as possible or else it is useless. Absolutely! And there's no contradiction between that and the fact that perception depends on both reality and our models of reality. > Actually it was not my intention to attempt any such proof, merely to > indicate that what we call real is at the mercy of perception. The notion of reality is simply the working hypothesis that there's a world out there to be understood, and that we have some hope of understanding it, isn't it? Why give up on that until we get really stuck? Science as a whole shows no sign of being stuck at present. > If I > choose to call a particular consensus version of reality the 'one true > reality' I'm almost certainly wrong. What justification do you have for that statement? > As with most of current physics we > understand that 'reality' is a model. Can you explain how that statement means anything at all? > An evolution based on low speed > physics hardly prepares us for quantum mechanics and spooky action at a > distance interactions. For that reality, which we cannot perceive, we > employ mathematicians as interpreters (priests?) to argue about the > number of hidden dimensions etc etc. Even causality is frowned upon in > some circles. Well, they frown on it for no good reason. They're arbitrarily setting aside a bunch of stuff and trying to legislate that "everything works just *as if* it were real, except parts of it aren't real". They can make that decision if they want to, but don't expect others to likewise give up on science. > What we humans call 'reality' is completely determined by our senses and > the instruments we can build. Well, your use of the word 'reality' is at odds with the way it's usually understood (see above). You can use it in that way (where most people would use the word 'model' in its place), but that only serves to making communication more difficult. > How we interpret the data is powerfully > influenced by our social environment and history. As an example the Oh, sure -- except that you're kind of implying that data even *exists* in isolation from models of the world. > persistence of material objects is alleged by some to be true only for > small time scales <10^31 years; humans don't have long enough to learn > that. It must be a mystery to you, then, how we know it. ;-) John From robin at jessikat.fsnet.co.uk Sat Oct 11 19:16:17 2003 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Sun, 12 Oct 2003 00:16:17 +0100 Subject: Python syntax in Lisp and Scheme References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> <92c59a2c.0310031345.57d20631@posting.google.com> <6CZgb.3273$dn6.860@newsread4.news.pas.earthlink.net> <%hihb.4368$dn6.2921@newsread4.news.pas.earthlink.net> Message-ID: In article , Alex Martelli writes >Jon S. Anthony wrote: > ... >> bombs waiting to go off since they have long standing prior meanins >> not in any way associated with this type of operation. OTOH, if you >> really wanted them, you could define them. > >Is it a good thing that you can define "bombs waiting to go off"? > > >>> Python's reply "There should be one-- and preferably only one -- >>> obvious way to do it." >> >> This then is probably the best reason to _not_ use Python for anything >> other than the trivial. It has long been known in problem solving >> (not just computation) that multiple ways of attacking a problem, and >> shifting among those ways, tends to yield the the better solutions. > >One, and preferably only one, of those ways should be the obvious one, >i.e., the best solution. There will always be others -- hopefully they'll >be clearly enough inferior to the best one, that you won't have to waste >too much time considering and rejecting them. But the obvious one >"may not be obvious at first unless you're Dutch". > >The worst case for productivity is probably when two _perfectly >equivalent_ ways exist. Buridan's ass notoriously starved to death in >just such a worst-case situation; groups of programmers may not go >quite as far, but are sure to waste lots of time & energy deciding. > > >Alex > I'm not sure when this concern for the one true solution arose, but even GvR provides an explicit example of multiple ways to do it in his essay http://www.python.org/doc/essays/list2str.html Even in Python there will always be tradeoffs between clarity and efficiency. -- Robin Becker From nospam at nospam.com Wed Oct 22 07:25:58 2003 From: nospam at nospam.com (MrBill) Date: Wed, 22 Oct 2003 11:25:58 GMT Subject: Parsing MS Word Document? Message-ID: I would like to be able to open, read, and extract data from a report that is produced in MS Word. The doc seems to contain embedded spreadsheets. I would like to extract some of the data from the spreadsheets and feed it into another application. I've been reading a little bit about OLE and MS Word and sure would like to find a module that hides some of this so-called innovation from me. Thanks, Bill From prunesquallor at comcast.net Sat Oct 18 19:08:39 2003 From: prunesquallor at comcast.net (prunesquallor at comcast.net) Date: Sat, 18 Oct 2003 23:08:39 GMT Subject: Why don't people like lisp? References: <1A8kb.67406$pv6.3464@twister.nyc.rr.com> Message-ID: Lulu of the Lotus-Eaters writes: > I'm not sure which is worse though... someone like Tilton is easily > smart enough to avoid sophistry, and yet he engages in it. What can I say? Lisp attracts a more sophistricated kind of programmer. From duncan at NOSPAMrcp.co.uk Tue Oct 21 04:24:09 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Tue, 21 Oct 2003 08:24:09 +0000 (UTC) Subject: Python from Wise Guy's Viewpoint References: <840592e1.0310192322.6a765e87@posting.google.com> Message-ID: Alex Martelli wrote in news:OwOkb.19485$e5.710958 at news1.tin.it: > Yes -- which is exactly why many non-programmers would prefer the > parentheses-less notation -- with more obvious names of course;-). > E.g.: > emitwarning URGENT "meltdown imminent!!!" > DOES look nicer to non-programmers than > emitwarning(URGENT, "meltdown imminent!!!") > > Indeed, such languages as Visual Basic and Ruby do allow calling > without parentheses, no doubt because of this "nice look" thing. I know we are agreed that Visual Basic is fundamentally broken, but it might be worth pointing out the massive trap that it provides for programmers in the subtle difference between: someProcedure x and someProcedure(x) and call someProcedure(x) If 'someProcedure' is a procedure taking a single reference parameter, and modifying that parameter, then the first and third forms will call the procedure and modify 'x'. The second form on the other hand will call the procedure and without any warning or error will simply discard the modifications leaving 'x' unchanged. -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From stevev at hexadecimal.uoregon.edu Sun Oct 5 02:58:32 2003 From: stevev at hexadecimal.uoregon.edu (Steve VanDevender) Date: 04 Oct 2003 23:58:32 -0700 Subject: Python syntax in Lisp and Scheme References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> <92c59a2c.0310031345.57d20631@posting.google.com> <8b9e2260.0310032317.72abd86a@posting.google.com> <8b9e2260.0310040524.229dfd9f@posting.google.com> Message-ID: <874qyodvc7.fsf@localhost.efn.org> "Terry Reedy" writes: > Lisp (and possibly other languages I am not familiar with) adds the > alternative of *not* evaluating arguments but instead passing them as > unevaluated expressions. In other words, arguments may be > *implicitly* quoted. Since, unlike as in Python, there is no > alternate syntax to flag the alternate argument protocol, one must, as > far as I know, memorize/learn the behavior for each function. The > syntactic unification masks but does not lessen the semantic > divergence. For me, it made learning Lisp (as far as I have gotten) > more complicated, not less, especially before I 'got' what going on. What you're talking about are called "special forms" and are definitely not functions, and are used when it is semantically necessary to leave something in an argument position unevaluated (such as in 'cond' or 'if', Lisp 'defun' or 'setq', or Scheme 'define' or 'set!'). Programmers create them using the macro facilities of Lisp or Scheme rather than as function definitions. There are only a handful of special forms one needs to know in routine programming, and each one has a clear justification for being a special form rather than a function. Lisp-family languages have traditionally held to the notion that Lisp programs should be easily representable using the list data structure, making it easy to manipulate programs as data. This is probably the main reason Lisp-family languages have retrained the very simple syntax they have, as well as why there is not different syntax for functions and special forms. > Question: Python has the simplicity of one unified assignment > statement for the binding of names, attributes, slot and slices, and > multiples thereof. Some Lisps have the complexity of different > functions for different types of targets: set, setq, putprop, etc. > What about Scheme ;-? Scheme has 'define', 'set!', and 'lambda' for identifier bindings (from which 'let'/'let*'/'letrec' can be derived), and a number of mutation operations for composite data types: 'set-car!'/'set-cdr!' for pairs, 'vector-set!' for mutating elements of vectors, 'string-set!' for mutating strings, and probably a few others I'm forgetting. -- Steve VanDevender "I ride the big iron" http://jcomm.uoregon.edu/~stevev stevev at hexadecimal.uoregon.edu PGP keyprint 4AD7AF61F0B9DE87 522902969C0A7EE8 Little things break, circuitry burns / Time flies while my little world turns Every day comes, every day goes / 100 years and nobody shows -- Happy Rhodes From find at my.address.elsewhere Tue Oct 28 23:55:08 2003 From: find at my.address.elsewhere (Matthias Blume) Date: Wed, 29 Oct 2003 04:55:08 GMT Subject: Python from Wise Guy's Viewpoint References: <3F994597.7090807@ps.uni-sb.de> <6dnq61-kl.ln1@ID-7776.user.dfncis.de> <87oew33h8t.fsf@sidious.geddis.org> <3F9D5D21.2060408@ps.uni-sb.de> Message-ID: Pascal Costanza writes: [ on my claim that every dynamically typed program has a statically typed translation: ] > No, that's not all you need to do. Essentially you would need to write > a complete interpreter/compiler for the dynamically typed language on > top of the statically typed one, _if_ you want runtime > metaprogramming. That's not what I would call a straightforward > translation. Actually, I didn't say what I need, so how can you contradict me on this point? Anyway, having to have a compiler/interpreter around is only true if the original program contained a complete compiler/interpreter, in which case I'd say this is just par for the course. > > [This whole discussion is entirely due to a mismatch of our notions of > > what constitutes expressive power.] > > No, it's not. There's a class of programs that exhibit a certain > behavior at runtime that you cannot write in a statically typed > language _directly in the language itself_. This is simply not true. See above. > There's no program that > exhibits a certain behavior at runtime that you can only write in a > statically typed language. [1] I do not dispute this fact. > [11 Except perhaps for a class of programs that would change their > runtime and/or space complexity, provided they would need lots of > dynamic type checks. This comment makes me /very/ uneasy. Namely, the funny thing here is that you seem to question a statement that you make /yourself/ even though it is undoubtedly true. *Of course* you can write everything that can be written in a statically typed language in a dynamically typed language in such a way that runtime behavior is the same (including complexity). Translating a well-typed ML program into, say, Lisp is completely straightforward. (Early ML implementations were done that way.) The proof of type-safety for the original ML program also shows that no additional runtime checks are needed for the result of the translation. You don't even need the runtime checks that Lisp does on its own because it doesn't know any better. (This is unless you turn these checks off explicitly -- which in general would make the code unsafe but in this specific case does not.) So rest assured that the answer to your question: > But I haven't sorted out yet whether this class > really exists. is "no". But that was not my point anyway. Matthias PS: You don't need to try and convince me of the virtues of dynamic typing. I *come* from this world -- having implemented at least three (if not four -- depending on how you count) interpreters/compilers for dynamically typed languages. Because of this I also already know all the arguments that you are undoubtedly thinking of bringing forward, having either used them myself or once marveled at them when I heard them from other, then like-minded folks. But the long-term effect of working with and on such systems was that I now prefer to avoid them. "Run-time metaprogrammming" you say? The emperor has no clothes. From aleaxit at yahoo.com Wed Oct 15 18:20:44 2003 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 15 Oct 2003 22:20:44 GMT Subject: inner classes in python as inner classes in Java References: Message-ID: <0Ljjb.221887$hE5.7473075@news1.tin.it> Carlo v. Dango wrote: > Comming to think of it, it can't be done in python! Since there is no way > to denote you want to access a field rather than creating a new one, When you access a field you access it, e.g: print blah.bluh this accesses it -- it will never create anything. When you ASSIGN to a field you create it if it wasn't there (if it was there, the previous value is removed, and the field is created afresh again). You can use descriptors (in new-style classes) to handle assignments (and accesses too, if you want) in special ways for some attributes. > __setattr__ will have no changes of knowing when to create the field or > look it up in the outer scope... this suxx man... I never understood the > smart thing about that feature in python.. anyone care to enlighten me? If you can't see that it's simpler to let target = value have the same semantics whether target was already bound to something or not, it's hard to see what will convince you. For the case of someobject.attr = value, you do get to add complications if you want -- e.g., when wrapping someobject in your proxy, you can introspect to find what attributes it had at that time, and prepare a custom class with the set of descriptors you want. Or, if you are in no hurry, you can to such checks at the time of eahc assignment. Such tender loving care will typically break the semantics of your proxying in general cases, but if you have total control on the class whose instances you're wrapping that need not be the case. It's still hard to say what benefits you'll be getting, of course, but there may be some cunning plan behind it all. Alex From roy at panix.com Sun Oct 26 08:11:50 2003 From: roy at panix.com (Roy Smith) Date: Sun, 26 Oct 2003 08:11:50 -0500 Subject: Newbie Questions: Swithing from Perl to Python References: <%5Gmb.37416$RP2.4260@twister.tampabay.rr.com> Message-ID: In article <%5Gmb.37416$RP2.4260 at twister.tampabay.rr.com>, "Luther Barnum" wrote: > I see your from the Tampa area also, cool. That part seems pretty easy but > what I'm looking for is incrementing a counter. I use this all the time for > summarizing log files. I would probably prefer to keep using Perl but I work > in a place where Python is used much more than Perl so I want to learn it > the Python way. > > Here is another example: > > ex: > > While() { > chomp; > if(/(\w+ # Date > \s+ # Space > \d+ # Day > \s+ # Space > (\w+) # Server > \s+ # Space > (\w+)/x) { # Error > > $server = $1; > $error = $2; > > $server_totals{$server}++; > $error_totals{$error}++; > } > } Basicly, I'll repeat my advice from yesterday -- check out the re module in the on-line library reference. It implements full Perl-style regular expressions, including the ability to grab the value of sub-expressions (the $1, $2 stuff). The Python code will be a little less compact (but, IMHO, easier to read) than the Perl code, but every bit of Perl functionality above translates directly on a 1-to-1 basis into Python using the re module. Your xxx_totals hashes just become dictionaires in Python. From ianb at colorstudy.com Fri Oct 10 19:44:05 2003 From: ianb at colorstudy.com (Ian Bicking) Date: Fri, 10 Oct 2003 18:44:05 -0500 Subject: Could a single web framework popularize Python? In-Reply-To: Message-ID: On Friday, October 10, 2003, at 04:00 PM, Nick Vargish wrote: > Alex Martelli writes: > >> they're referring to the .net rather than the .org site. >> "Annotatable" >> docs (perhaps with some overview) sure sounds like a way-cool idea, >> but >> I have no first-hand experience of how well it works in practice. > > My guess is that the annotatable docs at php.net are exactly what > PHPsters mean when they talk about community. I haven't been there > for a couple of years (not doing any PHP these days), but I had > mixed feelings about the docs. On one hand, there were often > helpful tips about how to use a function. On the other hand, the > comments sometimes contradicted each other, which was kind of > daunting. And on the third hand, the PHP docs were often vague or incomplete, so the comments were required to understand how things worked or where related functions might be. Python stdlib docs aren't perfect, but on the whole they are considerably better than PHP. Without comments, of course -- with comments the PHP docs are pretty good. -- Ian Bicking | ianb at colorstudy.com | http://blog.ianbicking.org From jhefferon at smcvt.edu Thu Oct 16 09:30:59 2003 From: jhefferon at smcvt.edu (Jim Hefferon) Date: 16 Oct 2003 06:30:59 -0700 Subject: teaching programming to children References: Message-ID: <545cb8c2.0310160530.3ee31948@posting.google.com> andy at post.tau.ac.il wrote > I would be gratefull if people who had a similar experience would told me about > it. I brought home Alice http://www.alice.org for my kids the other day and they now beg me to give them extra computer time so they can play with it more. It is worth a look, at least. Jim From sross at connectmail.carleton.ca Mon Oct 27 09:41:27 2003 From: sross at connectmail.carleton.ca (Sean Ross) Date: Mon, 27 Oct 2003 09:41:27 -0500 Subject: Newbie: Classes References: <3F9DDCA3.60709@sympatico.ca> Message-ID: "Andrew Bennetts" wrote in message news:mailman.125.1067232717.702.python-list at python.org... > On Mon, Oct 27, 2003 at 12:08:39AM -0500, Sean Ross wrote: > > > > "Michael Loomington" wrote in message > > news:bni80i$11dkvg$1 at ID-198839.news.uni-berlin.de... > > > I tried doing the following but it doesn't work: > > > > > > def __mul__(self, m) > > > self.r= self.r * m > > > self.i= self.i * m > > > return Complex(self.r, self.i) > > > > > > > Hi. Python allows you to define behaviour for both left and right > > multiplication (instance*2 or 2*instance). See if this helps: > > > > def __mul__(self, m): > > self.r *= m > > self.i *= m > > return Complex(self.r, self.i) > > Uh, I don't think you want to mutate this instance... > > -Andrew. > > I suppose not. I just went from what the OP already had. From ianb at colorstudy.com Thu Oct 9 11:25:03 2003 From: ianb at colorstudy.com (Ian Bicking) Date: Thu, 9 Oct 2003 10:25:03 -0500 Subject: run time code generation in python In-Reply-To: Message-ID: On Thursday, October 9, 2003, at 07:21 AM, Carlo v. Dango wrote: > Hello there. I have found a need to runtime generate a method and > instert > it into an object instance. The code is a simple forwarding mechanism > like > > def foo(self, *args, **kwargs): > self.i.foo(*args, **kwargs) > method.. however, it is only at runtime that I know the name "foo" so I > cannot gerenate such a method any sooner. I have tried the compile(str) > method but I haven't succeeded. I've tried using the __getattribute__ > but > there is a problem in that I do not know if __getattribute__ was > called due > to a method call taking place, or due to someone who just wants a > reference > to a method.. (and for other reasons as well :) I need to runtime > generate > the above method. __getattr__ will allow you to forward all the methods you don't want to override. So you can do: class OverridingProxy: def __init__(self, obj): self.obj = obj def overridedMethod(self, foo, bar): # ... custom implementation def __getattr__(self, attr): return getattr(self.obj, attr) You don't need to distinguish between methods and normal attributes, generally. If you do (e.g., you want to filter the output of all the methods) you'll have to check the type of the getattr() result, and create a second proxy if it's a method. (That proxy would take the method reference as the object to wrap, and would implement __call__) -- Ian Bicking | ianb at colorstudy.com | http://blog.ianbicking.org From stevewilliams at wwc.com Mon Oct 20 22:43:03 2003 From: stevewilliams at wwc.com (Steve Williams) Date: Tue, 21 Oct 2003 02:43:03 GMT Subject: Is there any good wxPython documentation? In-Reply-To: <711c7390.0310201642.3db29ba1@posting.google.com> References: <711c7390.0310201642.3db29ba1@posting.google.com> Message-ID: Daniel Ehrenberg wrote: > I'm trying to learn wxPython, but I can't seem to find much > documentation. The wxPython website says that all advanced (and even > some basic) documentation for wxPython is only available in C++ syntax > in the main wxWindows documentation. It also says that the samples > will help, but I can't seem to make sense of them. Should I just use a > not-as-good GUI like Tkinter or a not-as-common one like Anygui or > PyUI if I want to have documentation? > LittleDan wxPython is definitely worth the effort. I spent time getting over the wxPython learning curve and I'm happy I did it. You really don't need the advanced documentation (unless you're pushing the envelope). The wxWindows documentation and the demos are enough. Try to duplicate the demos in your own code. Learn the difference between wxWindow, wxScrolledWindow, wxFrame and wxPanel. Play with wxTextCtrl, wxStaticText and wxListBox. Forget the menu stuff in the beginning. You can add it later. Work with the dialogs--wxMessageDialog, wxTextEntryDialog, wxSingleChoiceDialog and wxMultipleChoiceDialog. Avoid the sizers. Use the RolColSizer instead (a wonderful tool). The wxPython objects have a lot of methods and attributes. Wrap them in your own Python functions to create interfaces you're comfortable with. Time spent with wxGrid is golden. Study the documentation and create your own interfaces, as there are way too many features to absorb at once. Subscribe to wxPython-users at lists.wxwindows.org to get truly helpful answers to your questions. From max at alcyone.com Thu Oct 16 16:42:40 2003 From: max at alcyone.com (Erik Max Francis) Date: Thu, 16 Oct 2003 13:42:40 -0700 Subject: In need of c.l.p.discussion References: Message-ID: <3F8F02C0.69BB4C0D@alcyone.com> Rune Steffensen wrote: > Any comments on this? First, due to the anarchic nature of Usenet, there is on possible way this could work. There's be no incentive to get people to do this, and there'd be no way to enforce it when they didn't. I've never heard of an existing newsgroup that reliably operates the way you describe, so you're talking about something without precedent. Besides, that's what comp.lang.python is _for_ -- discussion. Second, remember that comp.lang.python is also gated to a mailing list. Unless you gate both to separate lists, then the people on the mailing list suddenly see discussions disappear. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ Most men do not mature, they simply grow taller. \__/ Leo Rosten From ktilton at nyc.rr.com Sat Oct 4 14:55:57 2003 From: ktilton at nyc.rr.com (Kenny Tilton) Date: Sat, 04 Oct 2003 18:55:57 GMT Subject: Flat-schmat! [was Re: Python syntax in Lisp and Scheme] In-Reply-To: References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> <92c59a2c.0310031345.57d20631@posting.google.com> <8b9e2260.0310032317.72abd86a@posting.google.com> <8b9e2260.0310040524.229dfd9f@posting.google.com> Message-ID: <1JEfb.10609$pv6.8453@twister.nyc.rr.com> Alex Martelli wrote: > record as promising that the major focus in the next release > of Python where he can introduce backwards incompatibilities > (i.e. the next major-number-incrementing release, 3.0, perhaps, > say, 3 years from now) will be the _elimination_ of many of > the "more than one way to do it"s that have accumulated along > the years mostly for reasons of keeping backwards compatibility > (e.g., lambda, map, reduce, and filter, Oh, goodie, that should win Lisp some Pythonistas. :) I wonder if Norvig will still say Python is the same as Lisp after that. > Python draws a firm distinction between expressions and > statements. Again, the deep motivation behind this key > distinction can be found in several points in the Zen of > Python, such as "flat is better than nested" (doing away > with the expression/statement separation allows and indeed > encourages deep nesting) and "sparse is better than dense" > (that 'doing away' would encourage expression/statements > with a very high density of operations being performed). In Lisp, all forms return a value. How simple is that? Powerful, too, because a rule like "flat is better than nested" is flat out dumb, and I mean that literally. It is a dumb criterion in that it does not consider the application. Take a look at the quadratic formula. Is that flat? Not. Of course Python allows nested math (hey, how come!), but non-mathematical computations are usually trees, too. I was doing an intro to Lisp when someone brought up the question of reading deeply nested stuff. It occurred to me that, if the computation is indeed the moral equivalent of the quadratic formula, calling various lower-level functions instead of arithmetic operators, then it is /worse/ to be reading a flattened version in which subexpression results are pulled into local variable, because then one has to mentally decipher the actual hierarchical computation from the bogus flat sequence. So if we have: (defun some-vital-result (x y z) (finally-decide (if (serious-concern x) (just-worry-about x z) (whole-nine-yards x (composite-concern y z))))) ...well, /that/ visually conveys the structure of the algorithm, almost as well as a flowchart (as well if one is accustomed to reading Lisp). Unwinding that into an artificial flattening /hides/ the structure. Since when is that "more explicit"? The structure then becomes implicit in the temp variable bindings and where they get used and in what order in various steps of a linear sequence forced on the algotrithm. I do not know what Zen is, but I do now that is not Zen. Yes, the initial reaction of a COBOL programmer to a deeply nested form is "whoa! break it down for me!". But that is just lack of familiarity. Anyone in a reasonable amount of time can get used to and then benefit from reading nested code. Similarly with every form returning a value...the return statement looks silly in pretty short order if one spends any time at all with a functional language. kenny From peter at engcorp.com Mon Oct 6 21:07:28 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 06 Oct 2003 21:07:28 -0400 Subject: Queues - Is Infinity all right? References: <84fc4588.0310050520.42e5f9d4@posting.google.com> <3F802006.93571400@engcorp.com> <3f818f20$0$14130$e4fe514c@dreader4.news.xs4all.nl> <84fc4588.0310061548.110533ff@posting.google.com> Message-ID: <3F8211D0.23F9D652@engcorp.com> Anand Pillai wrote: > > This was exactly what my problem was. The producer thread was > creating a lot of data to the queue which the consumer cannot > keep up with. > > Since I am using python threads, it so happens most of the time > that the queue is filled to huge sizes, and the consumer thread > context switch is not done, causing memory problems. > > I have not gone through the code of Queue.py, but I think that > the queue.get() method is an O(n) operation, considering the > ration of 'put's to the 'get's. I think you might be misinterpreting things. Remember that put() and get() on a list are actually implemented in C code, so relative to anything you would actually do with the data that you get(), and to anything you actually do in order to produce the data that you put(), the actual put() and get() operations are effectively both instantaneous (and thus in effect O(1)) unless you are talking literally thousands of items in the Queue. And you seem to be suggesting it is because get() is O(n) that you are even getting to this overload point, but the time for the get() won't become noticeable until you've already had a problem for quite some time. -Peter From fuerte at sci.fi Tue Oct 14 14:14:03 2003 From: fuerte at sci.fi (Harri Pesonen) Date: Tue, 14 Oct 2003 21:14:03 +0300 Subject: Python free IDE on windows In-Reply-To: <3f8c2bfb$0$27591$626a54ce@news.free.fr> References: <3f8c2bfb$0$27591$626a54ce@news.free.fr> Message-ID: odel wrote: > Hello there, could anyone give me some idea about python IDE's on > windows? > > thanks ! > > b PythonWin From jegenye2001 at fw.hu Tue Oct 14 14:14:27 2003 From: jegenye2001 at fw.hu (Jegenye 2001 Bt) Date: Tue, 14 Oct 2003 20:14:27 +0200 Subject: Z in ZOPE References: <87fzhvg2c2.fsf@pobox.com> Message-ID: That's an equally good resolution, I think. ;) Or even better. lol Zope is "Zope Object Publishing Environment" All in all, Z stands for no particular thing. And that's fine. :) Best, Mikl?s John J. Lee wrote in message news:87fzhvg2c2.fsf at pobox.com... > > I'd always assumed it stood for 'ZOPE', in the GNU tradition. > > > John From http Fri Oct 17 11:22:30 2003 From: http (Paul Rubin) Date: 17 Oct 2003 08:22:30 -0700 Subject: [OT] Knuth's rewards [Was: Python syntax in Lisp and Scheme] References: Message-ID: <7x4qy728jt.fsf@ruckus.brouhaha.com> Jacek Generowicz writes: > > Could you afford to pay $327.68 for every bug found in your glorious > > software? > > Anyone know how Knuth arrives at the amounts he offers ? > > (He also offers $2.56 for errors in his books.) For errors in the books, traditionally the reward was $2.00 per error. Maybe in the more recent ones he increased it to $2.56. For TeX, I believe he offered $2.56 per bug for the first year, $5.12 the second year, etc. until it reached $327.68 and he prudently stopped increasing it further. He actually did pay out $327.68 to someone for some bug a couple of years ago. But prior to that, no bugs had been found in many years. A lot of people who find errors in the books and get $2.00 checks from Knuth save the checks as souvenirs instead of cashing them. A friend of mine had one hanging on his wall for quite a long time. But Knuth says there's a guy in San Jose, CA who has received and cashed something like hundreds of them. From alanmk at hotmail.com Wed Oct 8 10:09:20 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Wed, 08 Oct 2003 15:09:20 +0100 Subject: Pure Python XML parser References: <3F81F883.7CFE9C95@engcorp.com> <873ce5q707.fsf@pobox.com> Message-ID: <3F841A90.5209BB1C@hotmail.com> Uche Ogbuji wrote: > After all, DOM pretty much sucks. Uche, You're the second person in a week to express that sentiment, after the EffBot last week. I was going to make some points in reply to last week, but held back. But now that it's come up again, I thought I'd chip in my ?0,02. I mostly agree: the DOM sucks. But only when it is used for purposes for which it was never designed. DOM was designed to be a simple object model for documents, which was easily manipulable with script languages. But, most importantly, it was designed for use on the client side only, i.e. in the browser. So although the DOM is a *huge* memory hog, this is not a problem in its natural environment, the browser, where only 1 DOM is created per document being viewed. The problems come with DOM when people start doing stupid things with it, like trying to use it in server applications, and creating multiple DOMs to service every single client. IMHO, people are asking for trouble when they do that, and I have little sympathy for them. I feel that DOM has gotten bad press because of these kinds of misuses: I still believe that DOM is great for what it was designed for: non-server, script-based simple document manipulation. regards, -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan Uche Ogbuji wrote: > > jjl at pobox.com (John J. Lee) wrote in message news:<873ce5q707.fsf at pobox.com>... > > Peter Hansen writes: > > > > > "Ellinghaus, Lance" wrote: > > > > > > > > Does anyone have a pure python XML parser? > > > > > > http://www.fourthought.com (I *think* it's pure XML...) > > > > I guess you're referring to 4DOM. Fourthought no longer maintain > > that. It's part of PyXML now. > > > > I was about to say that 4DOM isn't up-to-date with the DOM spec, but > > now I come to think of it, I'm not certain whether the XML part is or > > is not up-to-date. What I am sure about is that the HTML DOM part > > isn't (it's level 2, but based on the prosposed spec. of September > > 2000). > > > > Whatever, 4DOM certainly isn't as standards-compliant as pxdom. > > I haven't used 4DOM for years. There are certainly better > alternatives. > > But I think this discussion is off topic. The OP was asking about > *parsers*, not DOM implementations. For all we know, he's not even > interested in DOM at all. After all, DOM pretty much sucks. > > The only pure Python parser I know of is xmlproc, which is part of > PyXML. > > http://pyxml.sourceforge.net/ > > --Uche > http://uche.ogbuji.net -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From ressler at cheetah.jpl.nasa.gov Mon Oct 13 12:27:46 2003 From: ressler at cheetah.jpl.nasa.gov (Michael Ressler) Date: 13 Oct 2003 16:27:46 GMT Subject: General Numerical Python question References: <500a4565.0310112113.a0840e8@posting.google.com> Message-ID: In article , Alex Martelli wrote: > 2mc wrote: > >> Generally speaking, if one had a list (from regular Python) and an >> array (from Numerical Python) that contained the same number of >> elements, would a While loop or a For loop process them at the same >> speed? Or, would the array process faster? >> >> I'm new to Python, so my question may expose my ignorance. I >> appreciate anyone's effort to help me understand. > > I don't know, I've never measured. Let's find out together. The real question is - why do you want to run a loop over an array? The whole point of Numeric is that you want to eliminate loops entirely. Keeping things in the array domain is infinitely faster than running explicit loops. You may need to come up with some clever expressions to do it, but most loops can be gotten rid of with clever uses of put(), take(), and the like. Loops are evil. 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 p at trick.lu Mon Oct 13 13:54:58 2003 From: p at trick.lu (Patrick Useldinger) Date: Mon, 13 Oct 2003 19:54:58 +0200 Subject: How to read this news group in OutLook? References: Message-ID: <4mplovcg716s0algnln179lv3fs29cvcd2@4ax.com> On 13 Oct 2003 01:58:25 -0700, searchsa at sohu.com (Searchsa) wrote: >I want to use Outlook to read the message of this news group, >but every time the Outlook say it cann't find the host, >what happened? And how to sovle it? You need to ask your provider for the correct settings, your question has nothing to do with this newsgroup. You'd have the same problem with any newsgroup. -pu From ingvar at cathouse.bofh.se Mon Oct 6 05:29:45 2003 From: ingvar at cathouse.bofh.se (Ingvar Mattsson) Date: 06 Oct 2003 10:29:45 +0100 Subject: Python syntax in Lisp and Scheme References: <3cea3gqq.fsf@comcast.net> Message-ID: <87r81qogs6.fsf@gruk.tech.ensign.ftech.net> Joe Marshall writes: > Alexander Schmolck writes: > > > prunesquallor at comcast.net writes: > > > >> mike420 at ziplip.com writes: > >> > >> > I think everyone who used Python will agree that its syntax is > >> > the best thing going for it. > >> > >> I've used Python. I don't agree. > > > > I'd be interested to hear your reasons. *If* you take the sharp distinction > > that python draws between statements and expressions as a given, then python's > > syntax, in particular the choice to use indentation for block structure, seems > > to me to be the best choice among what's currently on offer (i.e. I'd claim > > that python's syntax is objectively much better than that of the C and Pascal > > descendants -- comparisons with smalltalk, prolog or lisp OTOH are an entirely > > different matter). > > (I'm ignoring the followup-to because I don't read comp.lang.python) > > Indentation-based grouping introduces a context-sensitive element into > the grammar at a very fundamental level. Although conceptually a > block is indented relative to the containing block, the reality of the > situation is that the lines in the file are indented relative to the > left margin. So every line in a block doesn't encode just its depth > relative to the immediately surrounding context, but its absolute > depth relative to the global context. Additionally, each line encodes > this information independently of the other lines that logically > belong with it, and we all know that when some data is encoded in one > place may be wrong, but it is never inconsistent. > > There is yet one more problem. The various levels of indentation > encode different things: the first level might indicate that it is > part of a function definition, the second that it is part of a FOR > loop, etc. So on any line, the leading whitespace may indicate all > sorts of context-relevant information. Yet the visual representation > is not only identical between all of these, it cannot even be > displayed. It's actually even worse than you think. Imagine you want "blank lines" in your code, so act as paragraph separators. Do these require indentation, even though there is no code on them? If so, how does that interact with a listener? From what I can tell, the option chosen in the Python (the language) community, the listener and the file reader have different view on blank lines. This makes it harder than necessary to edit stuff in one window and "just paste" code from another. Bit of a shame, really. //ingvar -- When it doesn't work, it's because you did something wrong. Try to do it the right way, instead. From google at dalvander.com Thu Oct 30 04:40:48 2003 From: google at dalvander.com (Anders Dalvander) Date: 30 Oct 2003 01:40:48 -0800 Subject: popen: how to make sure child process is terminated and get return code? References: Message-ID: Tung Wai Yip wrote in message news:... > Secondly, the is some documention on popen() about how to get the > return code. But there is almost none for popen2-4(). What I discover > is it has to close all streams and the last one will give some the > return code. Disclaimer: I'm new to Python I'm in the same situation as you are, I'm trying to popen4 a program and getting the stdout and stderr from it. The documentation states that popen[2-4] does not support a way of getting the return code. But I've found it to be the return value for the last close-call you make on what popen4 returned. I'm also on Win2K. I don't know if it is the same for other platforms, but I think it should be some sort of standard way of doing this rather common and simple thing. From dthierbach at gmx.de Mon Oct 27 11:16:34 2003 From: dthierbach at gmx.de (Dirk Thierbach) Date: Mon, 27 Oct 2003 17:16:34 +0100 Subject: Python from Wise Guy's Viewpoint References: <30dv61-ni5.ln1@ID-7776.user.dfncis.de> Message-ID: <20tv61-ike.ln1@ID-7776.user.dfncis.de> Pascal Costanza wrote: > Dirk Thierbach wrote: >>>According to your criteria, (real * 200) is >>>- a certain class of values >>>- given in a limited language describing that class >> Yes, but you will have a hard time developing a static type checker >> that will work with such a language. > I am not asking for a definition of the term "static type", but for a > definition of the term "type". I am happy with a definition of "type" that allows arbitrary sets of values, but how does this apply to static typing? Or dynamic type checking? I was talking all the time about a definition of a "static type", because that it what is relevant here. Philosophically, there are a lot more sensible definitions for type, but how does one such definition relate to our discussion? > Haskell: "An expression evaluates to a value and has a static type." > (http://www.haskell.org/onlinereport/intro.html#sect1.3 ) > > Where is the definiton for "type"? (without "static"?) There is none, because that is not relevant. > Let's first get our terminology right. Maybe we should also agree on what we want to use the terminology for. > I don't mind if you want to change that terminology. Let's just > rephrase it: Static type systems need to reject programs that > wouldn't necessarily fail in serious ways at runtime. I think I already agreed with that several times, didn't I? But then you have also to add "even if they won't necessarily fail, nearly all of them won't be well-behaved". >>>But I am interested in the question why you (or others) think that >>>almost all software should be developed like that. >> I didn't say that. Please do not put up a strawman. In fact, I >> explicitely said "you use whatever tool you like best". > But that was the original question that initiated this thread. If we > have an agreement here, that's perfect! Finally. *Sigh*. Why do I have to repeat that multiple times? > What about the example in > http://groups.google.com/groups?selm=bnf688%24esd%241%40newsreader2.netcologne.de > ? > I don't think this can be done without a serious rewrite. The problem here is that the object system of CLOS and OCaml is quite different, and Haskell has no objects at all. So you cannot directly transfer that example to those languages. Not because they are statically typed, but because they are different. It probably wouldn't be possible to do exactly the same in another arbitrary dynamically typed language, either. But you can trivially simulate the *effects* of your program once you accept that such a simulation need not use classes. Please don't mix the differences because of statically/dynamically typing and because of other language features. > Right, it comes from a more principled consideration: You can't have > metacircularity in a statically type language. You might be able to have > metacircularity if you strictly separate the stages, but as soon as you > want to be able to at least occasionally call base code from meta code > and vice versa, then you lose. But you don't need metacircularity, because then you simply solve your problem in a different way. > Metacircularity gives me the guaranntee that I can always code around > any unforeseeable limitations that might come up, without having to > start from scratch. You can also create very subtle bugs that are difficult to find. > I haven't said that I can do more things in a dynamically typed > language. I have said that statically typed languages need to reject > well-behaved programs. That's a different claim. We are not talking > about Turing equivalence. Neither am I talking about Turing equivalence. But if you can agree that it is not harder to express something in a (properly) statically typed languages then to express it in a dynamically typed language, then we can stop the discussion here. What I want you is to give up the point of view that dynamically languages have an *advantage* because they are dynamically typed. - Dirk From ktilton at nyc.rr.com Wed Oct 22 23:00:56 2003 From: ktilton at nyc.rr.com (Kenny Tilton) Date: Thu, 23 Oct 2003 03:00:56 GMT Subject: Why don't people like lisp? In-Reply-To: <3F9707D1.6090107@rdrop.com> References: <8Nnlb.619$I04.380@newsread4.news.pas.earthlink.net> <3F9707D1.6090107@rdrop.com> Message-ID: Jim Newton wrote: > Perhaps lisp is not so well-liked is because there are not enough > standard libraries available. Perl has the CPAN libraries that > you can simply download and use. I've heard the Python also > has a huge number of such libraries. But if i want a lisp-tk > CLOS library, i'd have to write it myself, or lisp-DOM, or > lisp-cvs, or lisp-mySQL. > > On this note, has anyone ever heard of openAccess or openEDA? > http://www.openeda.org/ Wow. That's the first open source project that demanded a license agreement or something before letting me download. They use that word Open so much, but I do not think it means what they think it means. :) Anyway, I just wanted to see what everyone is interfacing to. Oops. You already said C++. Might take a C wrapper so Lisp FFIs can cope. > > it's an open source database for dealing with EDA design > data. Currently there is a C++ interface and Python. > At Tcl interface is either here on on its way. > > In my opinion a CLOS library would be much easier to use > than any of the other, if it existed. But what i've decided > to do in the mean time is to start from scratch learing > Python. If you are not part of the solution, you are part of the problem. Tilton's Law: Solve the right problem. Your problem is not that you do not know Python. A giveaway is that learning Python will not help you use OpenEDA from Lisp. That is your problem. What is the solution? UFFI bindings for OpenEDA. Regrettably, possibly also some gluing of C++ classes to C structs so Lisp FFIs can cope. The good news is that the problem is linear and finite, albeit tedious. But crafty Lisp macros can help. Might take a week or two. I and others here can help with that. Tilton's Law: Move towards the light. If you have to do some hard work over the next few weeks, would you rather (a) know and be using Python or (b) know Lisp FFIs (it's not /that/ bad) and be using Lisp? > > The C++ standard API is open, and well documented. Does > anyone volunteer to start such a openAcces --> CLOS > project? > Yep, some guy named: > > -jim > And I can help you with the FFI. Do they /really/ use C++ classes, or is it just C in C++ clothing? Is it a persistent C++ DB format? Probably not. I am thinking, just read the DB in Lisp, eliminate the bothersome middleman. They didn't use XML? Or is it more than a DB, really? kenny -- http://tilton-technology.com What?! You are a newbie and you haven't answered my: http://alu.cliki.net/The%20Road%20to%20Lisp%20Survey From christophe.dutrieux.nospam at free.fr Mon Oct 13 16:05:35 2003 From: christophe.dutrieux.nospam at free.fr (Dutrieux Christophe) Date: Mon, 13 Oct 2003 22:05:35 +0200 Subject: Boa crashes on Windoze 98 References: <84fc4588.0310130853.2f064be5@posting.google.com> Message-ID: On Mon, 13 Oct 2003 09:53:21 +0000, Anand Pillai wrote: > I am trying to run the latest Boa on Windows 98 2nd edition, using > python 2.2. The program starts up and immediately windows gives it's > stupid error box. > > ... > > -Anand I tried with success Boa Version 0.2.0 on Windows 98 (win32 exe package available at http://prdownloads.sourceforge.net/boa-constructor/boa-constructor-0.2.0.win32.exe?download) Christophe From n.favrefelix at NOSPAM__free.fr Mon Oct 27 19:25:41 2003 From: n.favrefelix at NOSPAM__free.fr (Nicolas Favre-Félix) Date: Tue, 28 Oct 2003 01:25:41 +0100 Subject: [Tkinter] Listbox only takes one column References: <3f9d6b30$0$2777$626a54ce@news.free.fr> Message-ID: <3f9db70d$0$2770$626a54ce@news.free.fr> Thank you Peter. From mwh at python.net Thu Oct 2 06:32:44 2003 From: mwh at python.net (Michael Hudson) Date: Thu, 2 Oct 2003 10:32:44 GMT Subject: Missing messagen (Was: Re: Fun with fancy slicing) References: <7h3isnaz6qw.fsf@pc150.maths.bris.ac.uk> Message-ID: <7h3brt0x7d1.fsf@pc150.maths.bris.ac.uk> Gerrit Holl writes: > Dave Benjamin wrote: > > In article <7h3isnaz6qw.fsf at pc150.maths.bris.ac.uk>, Michael Hudson wrote: > > > Dave Benjamin writes: > > > > > >> Anyone have any other interesting applications of the extended slice syntax? > > > > > > You can use it in a sieve prime finder (ooh, thread crossing :-): > > > ... > > > but it's not especially efficient (in speed or memory). Quite cute, > > > though. > > I do not seem to have received this message from Michael Hudson through > python-list. I am able to locate it on the newsgroup. Does anyone else > have this problem? Hmm, I saw it :-) Google also has it: http://groups.google.com/groups?selm=7h3isnaz6qw.fsf%40pc150.maths.bris.ac.uk I don't really read the newsgroup closely enough any more to know if any messages are going missing, I'm afraid. Cheers, mwh -- Screaming 14-year-old boys attempting to prove to each other that they are more 3133t than j00. -- Reason #8 for quitting slashdot today, from http://www.cs.washington.edu/homes/klee/misc/slashdot.html From max at alcyone.com Thu Oct 23 21:15:57 2003 From: max at alcyone.com (Erik Max Francis) Date: Thu, 23 Oct 2003 18:15:57 -0700 Subject: x[i] as loop variable References: Message-ID: <3F987D4D.9C139E4E@alcyone.com> Raymond Hettinger wrote: > In general, it should never be used unless you're trying to obfuscate > your code. It is a long standing, unintended by-product of the > grammar that any lvalue can be used as a loop variable. Most folks > aren't aware of it and everyone is better off not knowing about it. > In fact, I wish it hadn't come-up at all because someone will read > about it and adopt the atrocity as their new favorite style. Yes, I encountered this when implementing iterative control markups for EmPy. I was quite surprised that such syntaxes were allowed in Python; I'd never seen them or heard of them being used, and only through an experiment did I realize much to my surprise that, as you say, any lvalue can be used as the iteration variable. Even though the EmPy control markups are intended to mimic the native Python control structures as closely as possible (the pinciple of least surprise), needless to say, I got no complaints about deliberately deviating from Python in this respect; in EmPy, iteration variables must be simple variable names and nothing more. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ Pick the roses from the thorns / Wash with waters of the storms \__/ Chante Moore From santanu at softhome.net Thu Oct 9 17:28:25 2003 From: santanu at softhome.net (Santanu Chatterjee) Date: Fri, 10 Oct 2003 02:28:25 +0500 Subject: A query about list References: Message-ID: On Thu, 09 Oct 2003 21:19:18 +0000, Dave Benjamin wrote: > In article , Santanu > Chatterjee wrote: >> I was trying something like a.insert(1,a.pop(1)) but I need to modify >> a.pop(1) somehow so that the brackets vanish ...you know what I mean. Is >> that possible ? > > Ahh, I see what you mean, now. You probably want slice assignment. > > Try, for starters: > a[1:2] = a[1] > > You'll probably still need to use type(). Yes, this is what I wanted. Thanks for this simple solution. Regards, Santanu From amk at amk.ca Fri Oct 10 07:39:30 2003 From: amk at amk.ca (A.M. Kuchling) Date: Fri, 10 Oct 2003 06:39:30 -0500 Subject: Could a single web framework popularize Python? References: <1Ivhb.193919$hE5.6560510@news1.tin.it> Message-ID: On Fri, 10 Oct 2003 10:18:37 GMT, Alex Martelli wrote: > I think you're wrong, but I admit I'm guessing. To me, particularly > networking at OSCON, it seemed as if Parrot was generating lots of buzz. Buzz, sure -- people are willing to *talk* about it, but people are willing to talk and opine about anything. When it comes to actually devoting coding time to the project, however, people are much more conservative. > to get inspiration from. I've often seen PHP'ers moving to Python > bemoan the fact that www.python.org isn't community-run and intense- > community-involvement the way www.php.org is -- that seems as inevitable > a complaint as Perlites-moving-to-Python's hankering for CPAN. Did you mean PHP.net, not PHP.org? PHP.org seems to be just a bunch of forums; PHP.net has more content, but it's not clear how the site is more community-oriented than python.org; are you referring to the annotatable documentation, or to something else? --amk From eddie at holyrood.ed.ac.uk Wed Oct 8 14:38:45 2003 From: eddie at holyrood.ed.ac.uk (Eddie Corns) Date: Wed, 8 Oct 2003 18:38:45 +0000 (UTC) Subject: splitting a list into n groups References: Message-ID: Rajarshi Guha writes: >Hi, > is there an efficient (pythonic) way in which I could split a list into >say 5 groups? By split I mean the the first x members would be one group, >the next x members another group and so on 5 times. (Obviously x = >lengthof list/5) How about: ------------------------------------------------------------ def span (x, n): return range(0, x, n) def group (l, num): n = (len(l)/num) + 1 return [l[s:s+n] for s in span (len(l), n)] # test cases l1 = range(100) print group (l1, 5) print group (l1, 6) print group (l1, 4) ------------------------------------------------------------ Even though span could be folded in to make it shorter, abstracting it out allows you to name and document what it does (return the start index of each SPAN of n items). Also it doesn't worry too much about the last list being the same size as the rest. I'm too lazy to check the boundary conditions properly (an exercise for the reader). A completely non lazy person would possibly define the more primitive group_by_n: def group_by_n (l, n): return [l[s:s+n] for s in span (len(l), n)] and define group_into_num_pieces in terms of that: def group_into_num_pieces (l, num): return group_by_n (l,(len(l)/num) + 1) giving you 3 useful functions for the price of 1, but I'm too lazy for that. Eddie From kaz at ashi.footprints.net Wed Oct 15 14:32:31 2003 From: kaz at ashi.footprints.net (Kaz Kylheku) Date: 15 Oct 2003 11:32:31 -0700 Subject: Python syntax in Lisp and Scheme References: Message-ID: kaz at ashi.footprints.net (Kaz Kylheku) wrote in message news:... > Matthias Blume wrote in message news:... > > kaz at ashi.footprints.net (Kaz Kylheku) writes: > > > > > Marcin 'Qrczak' Kowalczyk wrote in message news:... > > > > On Mon, 13 Oct 2003 13:51:22 -0700, Kaz Kylheku wrote: > > > > > > > > > Secondly, it would be unoptimizeable. The result of evaluating a > > > > > lambda expression is an opaque function object. It can only be called. > > > > > > > > This is not true. When the compiler sees the application of a lambda, > > > > it can inline it and perform further optimizations, fusing together > > > > its arguments, its body and its context. > > > > > > Kindly keep in mind the overall context of the discussion, which is > > > HOF's versus macros. The closures being discussed are ones passed down > > > into functions. Those closures typically cannot be inlined, except > > > under very special circumstances taken advantage of by a compiler with > > > very smart global optimizations. > > > > If a macro works in a particular situation, then any equivalent HOF > > can be inlined there as well. Granted, not all compilers will > > actually do so, but the possibility trivially exists. This does not > > depend on "very smart" global optimizations. > > That is a case of bringing all of the function into the present > context so it can be mixed with the closures manually created there. > > A macro controls how much material is inlined and how much isn't. What I said here is silly because a HOF can also be structured to have inlined and noninlined parts: an inlined skeleton function that calls non-inlined functions. > A macro can have its own binary interface between the expanded > material and some material in a library that is associated with the > macro. > > The macro decides what forms need to be made into a closure that is > passed to the library and which are not. This is the real point; in a Lisp macro, material from parameters is usually spun into closures precisely because inlining is not wanted; it's a compromise which allows some remote function to call back into the present lexical environment, allowing the macro to generate less inlined bloat. In functional languages with lazy evaluation, evey expression is effectively a closure. When you call some function f with argument x, that x is effectively a lambda function which returns the value of x in its original environment. When the argument to a function is an expression, it need not be evaluated prior to the call; it may be delayed until the last possible moment when its value is actually needed, and it may never be evaluated at all. So it seems as if higher order functions have the evaluation control of macros. But delaying evaluation is not the same as control over evaluation. Moreover, a macro is not just some mechanism for delaying the evaluation of expressions; it's a mechanism for assigning an arbitrary meaning to expressions. A HOF can generate code only by interpolating parameters into a fixed body. The meaning of everything stays the same. A HOF can trivially replace a macro under two conditions: 1. The macro is used as an interface to hide lambdas from the user. This is not necessary if the language has lazy evaluation. Every expression is already a lambda, capable of being passed to a foreign environment and evaluated there, with all the hooks to the original environment. 2. The macro is used as a trivial inlining mechanism, which substitutes expressions into a template. HOF inlining effectively does the same thing. Since evaluation is lazy, there is little or no semantic difference between evaluating parameters and calling a function, or inserting the unevaluated expressions into the body and inlining it. In Common Lisp, we don't have the lazy evaluation semantics, so certain macro uses that fall under 1. are essential. People who argue against these always use HOF examples from another programming language. But CL programmers don't want to switch to another programming language. You can't switch programming languages while holding everything else constant. Certain macro uses in Lisp that seem to fall under 2. are also essential; some macros that do nothing more than substitute their arguments into some functional template nevertheless have imperative semantics, such as conditional or repeated evaluation of some forms. When Lisp programmers demonstrate these uses, again, they are countered by examples from a different programming language. ``Gee, if you only had virtual sequences (or whatever gadget), you wouldn't need that imperative DO- stuff.'' But now you are no longer talking about just HOF's, but HOF's plus virtual sequences. In general, for every macro use, you could design a programming language feature, such as higher order functions, lazy sequences and whatnot, and then claim that the macro use is unnecessary when you have that feature. The problem is that there is no end to this progression. Macros can implement anything you want (arbitrary syntax to semantics mapping), and that anything can always be given a name and codified in some offshoot academic language under a coat of hard-coded syntax, and you can then claim that you eliminated macros once and for all for all situations that you (and by implication everyone else) cares about. From newsgroups at jhrothjr.com Tue Oct 21 07:32:33 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Tue, 21 Oct 2003 07:32:33 -0400 Subject: Deprecated: list comp leak use References: Message-ID: "Terry Reedy" wrote in message news:c8ydnYL_P9UILgmiRVn-jw at comcast.com... > Announcement/Warning > > In the current implementation of list comprehensions, for-part control > variables leak to the surrounding context. Example: > >>> [i for i in [1,2]] > [1, 2] > >>> print i > 2 > The name i was bound within the list comprehension. The Reference > Manual currently says nothing about this behavior. However, the tutorial for 2.2.3 not only describes it, but it gives an example of how it can be used. John Roth > > Terry J. Reedy > > From mpeuser at web.de Wed Oct 15 02:24:56 2003 From: mpeuser at web.de (Michael Peuser) Date: Wed, 15 Oct 2003 08:24:56 +0200 Subject: assigning values to array element References: Message-ID: "Ben" > > This may sound easy but I'm having trouble assigning values to array > element. My problem is as follows: > > m = ['Peter', 'Sam', 'Dave', 'Carl'] > for o in m: > # Here first o is 'Peter'.. I want to do something like this: > Peter = 10 > > # if i do %s %o = 10, it gives me error... > > How can I do it? I think 'old stuff' is really appropriate here: for index in xrange(len(m)): m[index]=10 Kindly MichaelP From tim.one at comcast.net Wed Oct 29 22:48:53 2003 From: tim.one at comcast.net (Tim Peters) Date: Wed, 29 Oct 2003 22:48:53 -0500 Subject: gc assertion failure In-Reply-To: <3FA03EE6.7020805@stsci.edu> Message-ID: [Todd Miller] >>>> python: Modules/gcmodule.c:231: visit_decref: Assertion >>>> `gc->gc.gc_refs != 0' failed. Abort (core dumped) >>>> ... >>>> #5 0x080e9222 in visit_decref (op=0x405adc74, data=0x0) at >>>> Modules/gcmodule.c:231 >>>> #6 0x0808cebf in tupletraverse(o=0x40a62f74, visit=0x80e9194 >>>> , arg=0x0) at Objects/tupleobject.c:398 > FWIW, here's what my bug looked like: > > < key = Py_BuildValue("(NNsNN)", _digest(in1), _digest(out), > cumop, thread_id, type > --- > > key = Py_BuildValue("(NNsNO)", _digest(in1), _digest(out), > cumop, thread_id, type > > Since I used "N" for type in the Py_BuildValue, it stole a reference > to type which it shouldn't have. Switching to "O" made the > Py_BuildValue reference count neutral for type and the problem was > solved. That sure fits the pattern, but I'm baffled as to whether to call this one a missing incref or an excess decref <0.8 wink>. > Thanks for the help, Oh, I've seen this assert fail many times in development code. It's worth running a debug-build Python just to get it, since it's the only check in the code that *can* catch a too-small refcount before the refcount falls to 0 and the object vanishes (after which point it can be very hard even to figure out what type the object had). Unfortunately, it can still be excruciating to track down the cause, because the complaint from gc comes at seemingly random times, and the code that failed to incref (or erroneously decrefed) has nothing to do with what's on the call stack at the time the assert triggers. Next time, set the gc threshold to 1. This is much slower, because gc triggers on every container allocation then. The good part is that it generally finds the too-small refcount much closer to the time an object grows an unaccounted-for reference. Then, with some luck, you only have to reconstruct what happened in the preceding 5 million measly little machine cycles . brains-don't-scale-ly y'rs - tim From andy47 at halfcooked.com Fri Oct 24 05:22:57 2003 From: andy47 at halfcooked.com (Andy Todd) Date: Fri, 24 Oct 2003 10:22:57 +0100 Subject: How to write good Python objects? In-Reply-To: References: Message-ID: John Ladasky wrote: > Hi, folks, > [snip] > > One other thing -- I would like to be able to include a statement in > my program to the effect of: "from my_package import > my_function_or_class". Python seems to look for .pyc files in the > /Lib folder. By placing a .py file in /Lib, I got it to compile, and > to be recognized by an import statement. Is this the right way for > users to package their own code? It seems kludgy to me. > > If it matters (it shouldn't), I'm running Python 2.2.2 on Win2000 Pro. > > Thanks for your advice! > > -- > John J. Ladasky Jr., Ph.D. > Department of Biology > Johns Hopkins University > Baltimore MD 21218 > USA > Earth You can put your modules anywhere you like. You just need to tell the Python interpreter where to look for them. You can do this one of two ways, either by setting a PYTHONPATH environment variable; http://www.python.org/doc/current/tut/node8.html#SECTION008110000000000000000 Do this on Windows 2000 with Start->Settings->Control Panel->System Then select the 'Advanced' tab and click on the button labelled "Environment variables..." Or, you can use path configuration (.pth) files; http://www.python.org/doc/current/lib/module-site.html On Windows 2000, and with Python installed to C:\Python2.2 you would place your file (called, say John.pth) in C:\Python2.2\Lib\site-packages Regards, Andy -- -------------------------------------------------------------------------------- From the desk of Andrew J Todd esq - http://www.halfcooked.com/ From gh at ghaering.de Tue Oct 7 12:59:02 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Tue, 07 Oct 2003 18:59:02 +0200 Subject: multidimensional lists In-Reply-To: <20031007154855.4866.qmail@web13807.mail.yahoo.com> References: <20031007154855.4866.qmail@web13807.mail.yahoo.com> Message-ID: <3F82F0D6.1090505@ghaering.de> Orla O'Sullivan wrote: > I have a list of characters and I want to convert it > into a list of lists..how can I do this?? Unless you want to change the caracters, I can't think of a good reason why you would need this. Anyway, here we go for the simplest way: >>> l = ["abc", "xyz"] >>> [list(x) for x in l] [['a', 'b', 'c'], ['x', 'y', 'z']] It's called a "list comprehension". As you're probably a Python newbie you might want to see a less concise version that's easier to understand: >>> l2 = [] >>> for s in l: ... l2.append(list(s)) ... >>> print l2 [['a', 'b', 'c'], ['x', 'y', 'z']] -- Gerhard From imbosol at aerojockey.invalid Wed Oct 15 16:58:39 2003 From: imbosol at aerojockey.invalid (Carl Banks) Date: Wed, 15 Oct 2003 20:58:39 GMT Subject: Jython, GILs and object locking. References: Message-ID: <3yijb.19187$0I6.8697@nwrdny03.gnilink.net> Daniel Dittmar wrote: > Harri Pesonen wrote: >> It will be faster because there is no need to Py_INCREF(Py_None) or >> Py_DECREF(Py_None) or other static variables, and because there is no >> GIL or thread state swapping, but it will be slower because there will >> be an extra state argument in function calls. I guess the speed will be >> about the same for single-threaded programs. The real advantage comes of >> course from free-threading. > > Py_INCREF and Py_DECREF will have to use some kind of interlock to > synchronize reference counting, this will probably slow down things a lot. See, it seems to me that reference counting is the biggest technical obstacle to getting rid of the GIL. If I were getting rid of GIL without a ground-up rewrite, I'd definitely try to take out reference counting with it, perhaps using the slot formerly reserved for reference count to keep track of locking (hopefully one integer value is enough). Of course, that would require a whole new garbage collection scheme. But honestly, that's probably simple compared to getting rid of reference counting and the GIL. -- CARL BANKS http://www.aerojockey.com/software As the newest Lady Turnpot descended into the kitchen wrapped only in her celery-green dressing gown, her creamy bosom rising and falling like a temperamental souffle, her tart mouth pursed in distaste, the sous-chef whispered to the scullery boy, "I don't know what to make of her." --Laurel Fortuner, Montendre, France 1992 Bulwer-Lytton Fiction Contest Winner From godoy at metalab.unc.edu Sun Oct 12 11:26:42 2003 From: godoy at metalab.unc.edu (Jorge Godoy) Date: Sun, 12 Oct 2003 12:26:42 -0300 Subject: Tkinter, wxPython, PyGtk, or PyQt... References: Message-ID: "carljohan.rehn at chello.se" writes: > wxPython seems to be the first-hand choice for people doing W32-programming > (with MFC-experience). We use wxPython for our projects and benefit from its multiplatform support. I can write code on Linux and have it running on any *nix, Windows and other. It uses the GTK library in operating systems other than Windows. I recommend going with wxPython/wxWindows. See you, -- Godoy. From gt5163b at prism.gatech.edu Tue Oct 14 22:52:41 2003 From: gt5163b at prism.gatech.edu (Brian McNamara!) Date: Wed, 15 Oct 2003 02:52:41 +0000 (UTC) Subject: Express What, not How. References: Message-ID: Raffael Cavallaro once said: > Marcin 'Qrczak' Kowalczyk wrote: >> Sometimes a function is so simple that its body is more clear than any >> name. A name is an extra level of indirection. You must follow it to be >> 100% sure what the function means, or to understand what does it really >> mean that it does what it's named after. > >Your argument is based on the assumption that whenever people express >_what_ a function does, they do so badly, with an inappropriate name. ... >Anonymous functions add no clarity except to our understaning of >_implementation_, i.e., _how_ not _what_. Higher level abstractions >should express _what_. Implementation details should remain separate, >both for clarity of exposition, and for maintanence and change of >implementation. I am in total agreement with Marcin. What you (Raffael) say here sounds simply like dogma, rather than practical advice for constructing software. As a short practical example of what I'm saying, consider code like -- I am translating this from another language; apologies if I have -- screwed up any of the Haskell details nat :: Parser Int nat = do {c <- digit; return charToInt c} `chainl1` (return \x y -> 10*x+y) The code here parses natural numbers; it does do by parsing individual digit characters, translating the digit characters into the corresponding integers, and then combining the digit-integers into the overall number. If I understand you correctly, you would insist I write something like nat :: Parser Int nat = do {c <- digit; return charToInt c} `chainl1` combineDigits where combineDigits = return \x y -> 10*x+y In my opinion, the code here is worse than the original. "combineDigits" (or whatever we might choose to name it) is a one-time function. It is not going to be reused (it's local to "nat"; moving it to a more-top-level scope would just cause more problems finding a good name for it). Introducing a name for this function does nothing more than clutter the code. The name provides no extra understanding. Of course the function is "combining digits"! If the programmer is using chainl1, he already knows that chainl1 :: Parser a -> Parser (a->a->a) -> Parser a -- parses a series of items separated by left-associative operators -- which are used to combine those items and he can infer "combining digits" just by seeing the call to chainl1 and inspecting its left argument. >Anonymous functions are a form of unnecessary information overload. If I >don't need to see how something works right here, in this particular >context, then don't put its implementation here. Just refer to it by >name. There are more functional abstractions than there are reasonable names. Forcing programmers to name every abstraction they'll ever encounter is tantamount to forcing them to memorizing a huge vocabulary of names for these abstractions. Perhaps you can remember the precise meanings of ten-thousand function names off the top of your head. I, on the other hand, can probably recall only a hundred or so. Thus, I must write, e.g. zipWith (\x y -> (x+y,x-y)) list1 list2 rather than zipWith makePairOfSumAndDifference list1 list2 By only naming the most reusable abstractions (and, ideally, selecting a set which are mostly orthogonal to one another), we provide a "core vocabulary" which captures the essential basis of the domain. Lambda then takes us the rest of the way. In my opinion, a core vocabulary of named functions plus lambda is better than a separate name for every abstraction. In natural language, such a scheme would be considered double-plus-un-good, but in programming, I think it lends itself to the simplest and most precise specifications. I agree with your one of your overall theses, which is that we should focus on the "what" rather than the "how". Where our opinions diverge, however, is that I think sometimes the best way to communicate an abstraction is to show the "how" inline, rather than creating a new name in an attempt to capture the "what". -- Brian M. McNamara lorgon at acm.org : I am a parsing fool! ** Reduce - Reuse - Recycle ** : (Where's my medication? ;) ) From usenet at jasoegaard.dk Sun Oct 26 05:19:26 2003 From: usenet at jasoegaard.dk (=?ISO-8859-2?Q?Jens_Axel_S=3Fgaard?=) Date: Sun, 26 Oct 2003 11:19:26 +0100 Subject: Whoa! Do Python and Lisp really have LAMBDA ? References: Message-ID: <3f9b9fec$0$69997$edfadb0f@dread12.news.tele.dk> Marcin 'Qrczak' Kowalczyk wrote: > Scheme doesn't have a for loop either, I think it's like in SML - or would > it be more idiomatic to use "set!"? in which case it would not work. You forget do. (And for-each and map) -- Jens Axel S?gaard From alan.gauld at btinternet.com Tue Oct 21 17:58:39 2003 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 21 Oct 2003 21:58:39 GMT Subject: Lisp in Python as a library (not crossposted) References: Message-ID: <3f95abc6.859682748@news.blueyonder.co.uk> On 21 Oct 2003 09:39:04 +0300, Ville Vainio wrote: > Apparently there is some kind of toy Lisp interpreter written in Python: > > http://www.biostat.wisc.edu/~annis/creations/PyLisp/pylisp.html Danny Yoo did a basic Scheme or Lisp intrpreter in Python a few years ago - it may be on the Useless Python website...??? Are you listening Danny? Alan G. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld From achrist at easystreet.com Fri Oct 17 22:35:07 2003 From: achrist at easystreet.com (achrist at easystreet.com) Date: Fri, 17 Oct 2003 19:35:07 -0700 Subject: Python for Asset Management! References: <68fec103.0310171001.36ff0258@posting.google.com> <3F905ACB.3E16F843@easystreet.com> Message-ID: <3F90A6DB.1FC34A7@easystreet.com> Emile van Sebille wrote: > > > I don't agree with your "... and thus..." conclusion. Python with Numeric > and the gui kit that matches your taste is easily up to this task. > > For comparison, I've written a python+zope based application that juggles > sales data and provides sub-15 second response time recapping 1M+ records of > ~180cols. Sub-selections from any combination of 20 parameters speed things > up further. > I didn't say it couldn't be done, but I sure didn't want to lose any sleep figuring out how to do it. This project was done 3 years ago, we were selling into a market with many slow and old computers about, and we were dealing with people who like paper, so we wanted to create pretty reports way up around 1000 pages without any major delay. Maybe next time we'll do something like this in Python. Al From peter at engcorp.com Sun Oct 5 22:14:53 2003 From: peter at engcorp.com (Peter Hansen) Date: Sun, 05 Oct 2003 22:14:53 -0400 Subject: use make and version control system for every project? References: Message-ID: <3F80D01D.9CC28AA1@engcorp.com> AK wrote: > > Hi, I recently read an advice here that one should try to use make and > version control system even if you're the only one working on the > program. Is that a good advice? How many of you do that? I don't use make with Python, but I use it with anything compiled, as with embedded development. I *always* use CVS at this point, and I deeply regret the years that I spent not using it and the many varied ways in which I made negative progress because of that (lost files, incompatibilities that could not be resolved between various versions of things, inability to identify exactly when and why a given thing was done, etc). I _strongly_ recommend learning to use CVS, or *any equally simple version control system*, even for personal projects, so that it becomes second nature early on and you never find yourself without it. -Peter From SEE_AT_THE_END at hotmail.com Sat Oct 18 02:03:59 2003 From: SEE_AT_THE_END at hotmail.com (Georgy Pruss) Date: Sat, 18 Oct 2003 06:03:59 GMT Subject: Confusing performance results for prime References: Message-ID: I did the tests for the original Primes1 & 2 (only changed range --> xrange and sqrt --> int(sqrt)) and your Primes3 Primes1: 9592 primes up to 100000 in 0.547 secs Primes2: 9592 primes up to 100000 in 0.813 secs (+48.6%) Primes3: 9592 primes up to 100000 in 0.578 secs (+5.7%) Primes1: 49098 primes up to 600000 in 5.047 secs Primes2: 49098 primes up to 600000 in 8.844 secs (+75.2%) Primes3: 49098 primes up to 600000 in 5.922 secs (+17.3%) Primes1: 107126 primes up to 1400000 in 14.469 secs Primes2: 107126 primes up to 1400000 in 27.453 secs (+89.7%) Primes3: 107126 primes up to 1400000 in 17.203 secs (+18.9%) Georgy E^mail: 'ZDAwMTEyMHQwMzMwQGhvdG1haWwuY29t\n'.decode('base64') "Bengt Richter" wrote in message news:bmqfp9$1fu$0 at 216.39.172.122... > <...> > Sorry, I can't resist suggesting a slight speed improvement ;-) > > def Primes3(prime_range_top): > primes = [2] > for prime_candidate in xrange(3,prime_range_top,2): > for p in primes: > if prime_candidate%p==0: break > if p*p>prime_candidate: > primes.append(prime_candidate) > break > else: > primes.append(prime_candidate) > return primes > > And maybe running the bunch with > > if __name__ == "__main__": > n=100000 > times = [] > for pfun in (Primes1, Primes2, Primes3): > tb = time.time() > l1 = pfun(n) > dt = time.time() - tb > times.append(dt) > print '%s: %s primes up to %s in %5.3f secs' % ( > pfun.__name__, len(l1), n, dt) > fastest = min(times) > print '\nTimes relative to the fastest:' > for i, pfun in enumerate((Primes1, Primes2, Primes3)): > print '%s: %5.3f'%(pfun.__name__, times[i]/fastest) > > Which gave me (on older machine ;-) > > Primes1: 9592 primes up to 100000 in 2.984 secs > Primes2: 9592 primes up to 100000 in 5.608 secs > Primes3: 9592 primes up to 100000 in 2.444 secs > > Times relative to the fastest: > Primes1: 1.221 > Primes2: 2.295 > Primes3: 1.000 > > Regards, > Bengt Richter From newsgroups at jhrothjr.com Mon Oct 13 06:46:54 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 13 Oct 2003 06:46:54 -0400 Subject: Debugging woes on python References: Message-ID: "Glenn Reed" wrote in message news:bmdq3l$d8d$1 at lust.ihug.co.nz... > This is just a general comment after trying my hand at some serious python > programming for the first time. Have played with it for some time but this > is the first serious thing I've done with it. (By serious I mean 650 lines > of python code written for a client). > > The version of Python is the ActiveState version for Windows which included > PythonWin IDE. > > Prior to that I learn't Perl and used it for sometime. What I miss with > python is the lack of a straightforward command line debugger. That is > setting breakpoints and going step, step, step thru my code and examining > variables as appropriate. While I enjoyed Python's better syntax I found > Python's debugger frustrating and basically found it unusable. I could set > breakpoints by using PythonWin but I couldn't step thru the code. The worst > thing was that I couldn't list the source code or see any visual recognition > of stepping thru source code. The debugger was Python's pdb module. Is > there anything better for python? It didn't take me this long to get > started with Perl's command line (non-GUI) debugger. I suspect that part of the reason is simply that a lot of us have gotten bitten by the Test Driven Development bug, and found that debuggers are simply unnecessary if we have pervasive executable programmer tests. The other part of the reason is that Python is largely a volunteer effort. There's no intrinsic reason why it couldn't grow a command line debugger, but it's something that someone is going to have to want enough to write, debug and convince the core developers group to include in the distribution. If you want to start on this effort, I'd suggest looking at the debugging interface in IDLE, since it has to deal with cross-process issues. John Roth > > Thanks in advance > Glenn. > > From pclinch at internet-glue.co.uk Thu Oct 30 15:21:23 2003 From: pclinch at internet-glue.co.uk (Paul Clinch) Date: 30 Oct 2003 12:21:23 -0800 Subject: Installing a second version of an existing package References: <3f9de456$0$23612$5a62ac22@freenews.iinet.net.au> Message-ID: <8cf2994e.0310301221.748d6f0c@posting.google.com> Derek Fountain wrote in message news:<3f9de456$0$23612$5a62ac22 at freenews.iinet.net.au>... > Is it possible to install a second version of an existing package? My SUSE > Linux box has PIL-1.1.3 installed, and this is used by the OS for various > tasks. It's bundled as part of a "python-imaging" package, which includes > tkinter and other stuff. Removing it causes widespread damage! My suse is version 8.2, I used yast to check dependencies prior to removing it, which reported only sketch requires python-imaging. You may have other packages installed, but they're hardly the OS. > > I want to install PIL-1.1.4, since I need the EXIF stuff. Is it possible to > install PIL-1.1.4 alongside PIL-1.1.3? If so, how do I go about it, and how > do I ensure my script runs the version of the library I want? I'm not familiar with PIL, but usually packages numbered using this form are upwardly compatible when the last digit, ie. minor version number changes. So you may be able to able to ignore a warnings from the installer. Its easy to back up the site-packages/PIL directory prior to doing this, just in case. If it turns out that the different versions aren't compatible, you'll have to:- a) rename the new directory site-packages/PIL4 and change your import statement or, b) install a different version of python, eg. 2.3 then install the .4 PIL into that site-packages directory. Hope this makes sense, Paul Clinch From Dick.Zantow at lexisnexis.com Tue Oct 21 15:59:39 2003 From: Dick.Zantow at lexisnexis.com (rzed) Date: Tue, 21 Oct 2003 15:59:39 -0400 Subject: a little bit of recursion References: <62e9c66e.0310211147.64f2200c@posting.google.com> Message-ID: Dominik Kaspar wrote: > I'm trying to write a quite big recursive function, but the baseline > is the following: > > def rek(N, L): > N = N + 1 > if N >= 9: return L > else: return rek(N, L = L.append(N)) > > print rek(0, []) > > Why isn't this working? > In my opinion it should return [1, 2, ..., 9] > > Thanks for any answers. One problem is that L = L.append(N) does not have the effect you want. Try it on its own. Another is that it won't return [1,2,...,9] even when that is corrected. From mertz at gnosis.cx Thu Oct 23 01:01:44 2003 From: mertz at gnosis.cx (Lulu of the Lotus-Eaters) Date: Thu, 23 Oct 2003 01:01:44 -0400 Subject: Python from Wise Guy's Viewpoint References: <_8Ekb.7543$pT1.318@twister.nyc.rr.com> <3f972e54$1@news.unimelb.edu.au> Message-ID: <4C2l/kKkXQcQ092yn@gnosis.cx> Joachim Durchholz writes: >My 100% subjective private study reveals not a single complaint about >over-restrictive type systems in comp.lang.functional in the last 12 >months. I also read c.l.functional (albeit only lightly). In the last 12 months, I have encountered dozens of complaints about over-restrictive type sytems in Haskell, OCaml, SML, etc. The trick is that these complaints are not phrased in precisely that way. Rather, someone is trying to do some specific task, and has difficulty arriving at a usable type needed in the task. Often posters provide good answers--Durchholz included. But the underlying complaint -really was- about the restrictiveness of the type system. That's not even to say that the overall advantages of a strong type system are not worthwhile--even perhaps better than more dynamic languages. But it's quite disingenuous to claim that no one ever complains about it. Obviously, no one who finds a strong static type system unacceptable is going to be committed to using, e.g. Haskell--the complaint doesn't take the form of "I'm taking my marbles and going home". Yours, Lulu... -- Keeping medicines from the bloodstreams of the sick; food from the bellies of the hungry; books from the hands of the uneducated; technology from the underdeveloped; and putting advocates of freedom in prisons. Intellectual property is to the 21st century what the slave trade was to the 16th. From a.schmolck at gmx.net Wed Oct 8 13:22:31 2003 From: a.schmolck at gmx.net (Alexander Schmolck) Date: 08 Oct 2003 18:22:31 +0100 Subject: Python syntax in Lisp and Scheme References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> <92c59a2c.0310031345.57d20631@posting.google.com> <3F82EF06.F3D7A10@setf.de> <8765j0akfk.fsf@thalassa.informatimago.com> <87y8vw7imp.fsf@thalassa.informatimago.com> Message-ID: Pascal Bourguignon writes: > Well, I would say that kanji is badly designed, compared to latin > alphabet. The voyels are composed with consones (with diacritical > marks) and consones are written following four or five groups with > additional diacritical marks to distinguish within the groups. It's > more a phonetic code than a true alphabet. Huh? You seem to be confused (BTW French is misleading here: it's vowels and consonants in English). *Kanji* are not phonetic, you seem to be talking about *kana*. And the blanket claim that Japanese spelling in kana is badly designed compared to say, English orthography seems really rather dubious to me. 'as From mwilson at the-wire.com Thu Oct 9 17:34:56 2003 From: mwilson at the-wire.com (Mel Wilson) Date: Thu, 09 Oct 2003 17:34:56 -0400 Subject: Is this a safe thing to do? References: <221e7b06.0310090440.727cf10f@posting.google.com> <5rycnTJjK94NEBiiXTWJhg@comcast.com> Message-ID: In article <5rycnTJjK94NEBiiXTWJhg at comcast.com>, "Terry Reedy" wrote: > >"Duncan Booth" wrote in message >news:Xns940F8C176F22Bduncanrcpcouk at 127.0.0.1... >> The answer is to iterate over a COPY of the list if you want to >modify it >> during the iteration: > >or, when deleting items, carefully iterate backwards > >x=[{'f':9},{'f':1},{1:3,'f':9},{'f':9},{'f':3}] >for i in range(len(x)-1,-1,-1): > if x[i]['f'] == 9: > del x[i] > >>>> x >[{'f': 1}, {'f': 3}] Apropos of something else, I'm getting really sympathetic with the plight of the reverse-iterator proponents. Until they get their way, def xreverse (start, stop, split): return xrange (stop-split, start-split, -split) Regards. Mel. From vanicat+invalid at labri.fr Thu Oct 23 08:28:16 2003 From: vanicat+invalid at labri.fr (Remi Vanicat) Date: Thu, 23 Oct 2003 14:28:16 +0200 Subject: Python from Wise Guy's Viewpoint References: <_8Ekb.7543$pT1.318@twister.nyc.rr.com> <3f972e54$1@news.unimelb.edu.au> <3f9795dd$1@news.unimelb.edu.au> Message-ID: <87ismgxhnj.dlv@wanadoo.fr> Fergus Henderson writes: > Lulu of the Lotus-Eaters writes: > >>Joachim Durchholz writes: >>>My 100% subjective private study reveals not a single complaint about >>>over-restrictive type systems in comp.lang.functional in the last 12 >>>months. >> >>I also read c.l.functional (albeit only lightly). In the last 12 >>months, I have encountered dozens of complaints about over-restrictive >>type sytems in Haskell, OCaml, SML, etc. >> >>The trick is that these complaints are not phrased in precisely that >>way. Rather, someone is trying to do some specific task, and has >>difficulty arriving at a usable type needed in the task. Often posters >>provide good answers--Durchholz included. But the underlying complaint >>-really was- about the restrictiveness of the type system. > > Could you provide a link to an example of such a post? I've no link but I'm sure to have seen (here or on one of the caml list) people trying to do polymorphic recursion, something that is not easy to do in ocaml... -- R?mi Vanicat From prunesquallor at comcast.net Sat Oct 25 15:28:05 2003 From: prunesquallor at comcast.net (prunesquallor at comcast.net) Date: Sat, 25 Oct 2003 19:28:05 GMT Subject: Python from Wise Guy's Viewpoint References: Message-ID: <8yn9ce2k.fsf@comcast.net> gt5163b at prism.gatech.edu (Brian McNamara!) writes: > If I have read that correctly, it looks like it admits these Haskell > types: > > lookup :: > (Eq k)=> k -> Map k v -> (v -> a) -> a -> a > lookupDefault :: > (Eq k)=> k -> Map k v -> Map k v -> (v -> a) -> a -> a > transformList :: > (Eq k)=> k -> Map k v -> Map k v -> ([a] -> b) -> (k -> a) -> [b] > > Actually, rewriting all of these functions using the Error monad would > make it all more elegant. True. Monads are relative newcomers to the Lisp world. You won't see them very often. The other problem is that monads don't compose. From aleax at aleax.it Mon Oct 27 09:11:10 2003 From: aleax at aleax.it (Alex Martelli) Date: Mon, 27 Oct 2003 14:11:10 GMT Subject: PEP 289: Generator Expressions (please comment) References: <5d83790c.0310231158.65595858@posting.google.com> Message-ID: <2I9nb.360782$R32.11877162@news2.tin.it> Daniel Dittmar wrote: > Raymond Hettinger wrote: >> bestplayer, bestscore = max( (p.score, p.name) for p in players ) >> >> Each of the above runs without creating a full list in memory, >> which saves allocation time, conserves resources, and exploits >> cache locality. > > Why should generator comprehension be useful only for arguments? Nobody ever said it would be. RH's examples were all function calls because that's an "obvious" use case. > counter proposal: > g[(p.score, p.name) for p in players ] Looks like it's indexing g. > This works similar to r'\' for raw strings and u'x' for unicode strings. Nope, it's ambiguous, while adjacent to '...' isn't. > This has the advantage that it can be more easily extended: > d[(p.name, p.score) for p in players] creates a dictionary dict((p.name, p.score) for p in players) will do it in a much more obvious way. > s[(p.score, p.name) for p in players] creates a sorted list list.sorted((p.score, p.name) for p in players) will do it in a much more obvious way, and also allow you to specify such optional niceties as (e.g.) "key=" (in 2.4 -- and, btw, thanks to all of RH's work on the issue!). > and > p[$*-=%/sd/!] allows to embed perl code If you want perl, you know where to find it. Alex From amk at amk.ca Sun Oct 12 11:46:17 2003 From: amk at amk.ca (A.M. Kuchling) Date: Sun, 12 Oct 2003 10:46:17 -0500 Subject: What you can do with macros in Lisp References: <87n0c6im3b.fsf@thalassa.informatimago.com> Message-ID: On Sun, 12 Oct 2003 14:49:24 GMT, Kenny Tilton wrote: > Right. I want to start this almost 500 message thread over again and say > to the Pythonistas, "I thought you valued visually cleaner code?". Yes, but we also value people who know when the horse is dead. --amk From n17999950.temp.werner at neverbox.com Mon Oct 27 07:47:54 2003 From: n17999950.temp.werner at neverbox.com (Werner Schiendl) Date: Mon, 27 Oct 2003 13:47:54 +0100 Subject: E_ACCESSDENIED problem with win32 disk quota In-Reply-To: <10093a06.0310240024.27719278@posting.google.com> References: <10093a06.0310240024.27719278@posting.google.com> Message-ID: <3f9d13c9$1@brateggebdc5.br-automation.co.at> Bart Simpson wrote: > > I have known error code -2147024891 (0x80070005) means E_ACCESSDENIED > by someone's kind help. (Thanks Roger :) > > But I run PythonWin on Administrator privilege and I couldn't find any > related method for setting permission in 'Microsoft.DiskQuota.1' > object. > > Does anyone have any ideas? > I think this will probably similar to rebooting the PC: You will need to acquire some kind of "Security Token". Unfortunately I don't have the actual name for it handy :-( So even when you have the right to do it, you need to tell windows that you are about to do something "potentially dangerous". hth Werner From peter at engcorp.com Thu Oct 16 17:56:38 2003 From: peter at engcorp.com (Peter Hansen) Date: Thu, 16 Oct 2003 17:56:38 -0400 Subject: In need of c.l.p.discussion References: <3F8F02C0.69BB4C0D@alcyone.com> <3F8F0FD5.8386B56C@alcyone.com> <3f8f13c4-b57ff7ba-a857-423f-b79d-d32256c4d1c6@news.szn.dk> Message-ID: <3F8F1416.5840CC5B@engcorp.com> Klaus Alexander Seistrup wrote: > > Erik Max Francis wrote: > > > Announcements are for comp.lang.python.announce (moderated), and > > discussion is for comp.lang.python (unmoderated). > > (Except many tend to announce in both groups. :-() I believe the mailing list gates only comp.lang.python, so announcements in c.l.p.a alone would be missed by many who read only via email. Conversely, posts to c.l.p alone will of course often get lost in the noise, so consequently one feels somewhat obliged to post to both. -Peter From gerrit at nl.linux.org Wed Oct 8 13:58:56 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Wed, 8 Oct 2003 19:58:56 +0200 Subject: print is not a function In-Reply-To: References: Message-ID: <20031008175856.GA7320@nl.linux.org> Karl Scalet wrote: > So my own (best??) solution is: > > >>> from pprint import pprint as prt # cannot overcome this line :-( > >>> from qt import * # now the secret unveils > >>> [ prt(x) for x in locals() if x[:2]=='QA' ] > # sorry Signore Alex, but it's shorter than startswith :-) > # gives me > >>> 'QAssistantClient' > >>> 'QAccel' > >>> 'QActionGroup > >>> 'QApplication' > >>> 'QAction' > >>> [None, None, None, None, None] # well, I can live with > > In the case of doing such interactive inspections, i don't > mind about potential side-effects, i actually don't see them here. How about: import qt pprint.pprint(qt) ? Gerrit. -- 138. If a man wishes to separate from his wife who has borne him no children, he shall give her the amount of her purchase money and the dowry which she brought from her father's house, and let her go. -- 1780 BC, Hammurabi, Code of Law -- Asperger Syndroom - een persoonlijke benadering: http://people.nl.linux.org/~gerrit/ Kom in verzet tegen dit kabinet: http://www.sp.nl/ From tjreedy at udel.edu Fri Oct 17 12:18:40 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 17 Oct 2003 12:18:40 -0400 Subject: Why don't people like lisp? References: Message-ID: Someone wrote: > >>It is still a question of heated debate what actually killed the lisp > >>machine industry. The premise of this question is that there actually was a lisp-machine industry (LMI) to be killed. My memory is that is was stillborn and that the promoters never presented a *convincing* value proposition to enough potentional customers to really get it off the ground. and continued: > >>I have so far not seen anybody dipsuting that they were a marvel of > >>technical excellence, Never having seen one, or read an independent description, I cannot confirm or 'dipsute' this. But taking this as given, there is the overlooked matter of price. How many people, Lispers included, are going to buy, for instance, an advanced, technically excellent, hydrogen fuel cell car, complete with in-garage hydrogen generator unit, for, say $200,000. > >>sporting stuff like colour displays, graphical > >>user interfaces and laser printers way ahead of anybody else. I believe these are disputable. The American broadcast industry switched to color displays in the 50s-60s. Around 1980 there were game consoles (specialized computers) and small 'general purpose' computers that piggybacked on color televisions. TV game consoles thrive today while general PC color computing switched (mid80s) to computer monitors with the higher resolution needed for text. It was their use with PCs that brought the price down to where anyone could buy one. Did lisp machines really have guis before Xerox and Apple? Did lisp machine companies make laser printers before other companies like HP made them for anyone to use? If so, what did they price them at? > Francis Avila wrote: > > > I think what helped kill the lisp machine was probably lisp: many people > > just don't like lisp, because it is a very different way of thinking that > > most are rather unaccustomed to. "Pascal Costanza" responded > Wrong in two ways: In relation to the question about the would-be Lisp machine industry, this answer, even if correct, is besides the point. People buy on the basis of what they think. One answer may to be that the LMI failed to enlighten enough people as to the error or their thoughts. I wonder about another technical issue: intercompatibility. I strongly believe that media incompatibility helped kill the once thriving 8080/Z80/CPM industry. (In spite of binary compatibility, there were perhaps 30 different formats for 5 1/2 floppies.) I believe the same about the nascent Motorola 68000 desktop Unix industry of the early 80s. (My work unit has some, and I loved them.) So I can't help wondering if the LMI made the same blunder. Did all the LMI companies adopt the same version of Lisp so an outside Lisper could write one program and sell it to run on all? Or did they each adopt proprietary versions so they could monopolize what turned out to be dried-up ponds? Again, did they all adopt uniform formats for distribution media, such as floppy disks, so that developers could easily distribute to all? Or did they differentiate to monopolize? Terry J. Reedy From duncan at NOSPAMrcp.co.uk Thu Oct 9 09:32:27 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Thu, 9 Oct 2003 13:32:27 +0000 (UTC) Subject: sys.exit() References: Message-ID: "Ivan Voras" wrote in news:bm3msp$fjo$1 at bagan.srce.hr: > In a code such as: > > if len(sys.argv) < 2: > print "I need arguments!" > sys.exit(1) > > Is sys.exit() really a good choice? Is there something more elegant? (I > tried return but it is valid only in a function) More elegant might be to put your code in a function which would let you use return, although even then you need to call sys.exit somewhere if you want to set a return code. Remember that sys.exit just throws an exception, so you can always catch it further out if you need to. Also you can combine the print into the call to sys.exit and save a line: import sys def main(args): if len(args) < 2: sys.exit("I need arguments!") print "rest of program..." if __name__=='__main__': main(sys.argv) -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From radam2 at tampabay.rr.com Wed Oct 29 00:47:49 2003 From: radam2 at tampabay.rr.com (Ron Adam) Date: Wed, 29 Oct 2003 05:47:49 GMT Subject: regular expression reverse match? References: Message-ID: On Tue, 28 Oct 2003 21:19:56 -0600, Jay Dorsey wrote: > >How about: > > >>> matcher = "abcd and a bunch of other stuff" > >>> phrases = ["a", "ab", "abc", "abd", "aaaa", "abcd and a bunch of >other stuff and then some"] > >>> for phrase in phrases: >... if phrase == matcher[:len(phrase)]: print "pass" >... else: print "fail" >... >pass >pass >pass >fail >fail >fail > > >Jay > Hi Jay, That was an overly simple example I gave I think. The 'pattern' will in most case not be just a simple string. And I'll only be testing on one string at a time as it forms. It's an interactive input routine. So as the person types, I want to test the buffer and accept or reject each key according to the pattern. Pass or fail. This method would work though if it's possible to expand a regular expression out to a string of single matching re characters I think. Then it would be a matter of doing re.match('ibuffer', pattern[:len(ibuffer)]. I just don't know enough yet, but am learning quickly though, thanks. _Ron From http Wed Oct 8 20:24:52 2003 From: http (Paul Rubin) Date: 08 Oct 2003 17:24:52 -0700 Subject: Python syntax in Lisp and Scheme References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> <92c59a2c.0310031345.57d20631@posting.google.com> <87llrvs4yw.fsf@bird.agharta.de> Message-ID: <7xu16jmf57.fsf@ruckus.brouhaha.com> Kenny Tilton writes: > I think Python's problem is its success. Whenever something is > succesful, the first thing people want is more features. Hell, that is > how you know it is a success. The BDFL still talks about simplicity, > but that is history. GvR, IMHO, should chased wish-listers away with > "use Lisp" and kept his gem small and simple. That's silly. Something being successful means people want to use it to get things done in the real world. At that point they start needing the tools that other languages provide for dealing with the real world. The real world is not a small and simple place, and small simple systems are not always enough to cope with it. If GVR had kept his gem small and simple, it would have remained an academic toy, and I think he had wide-reaching ambitions than that. From martin at v.loewis.de Wed Oct 1 17:55:43 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 01 Oct 2003 23:55:43 +0200 Subject: Special Characters in Console References: Message-ID: "Neil Hodgson" writes: > The windows console is generally using the "Terminal" font with the "DOS: > Western Europe" character set which displays \xE4 as capital sigma. I don't > know of an encoding that matches this. In Python 2.3, using a Unicode string should make it work "out of the box". The code page is cp850, but printing on sys.stdout will automatically convert to the terminal encoding, so application knowledge about the terminal encoding is not needed. Regards, Martin From aleax at aleax.it Fri Oct 10 13:36:37 2003 From: aleax at aleax.it (Alex Martelli) Date: Fri, 10 Oct 2003 17:36:37 GMT Subject: Precision issue References: <8lvhb.258000$R32.8375967@news2.tin.it> Message-ID: Duncan Booth wrote: > Alex Martelli wrote in > news:8lvhb.258000$R32.8375967 at news2.tin.it: > >> Ladv?nszky K?roly wrote: >> >>> Entering 3.4 in Python yields 3.3999999999999999. >>> I know it is due to the fact that 3.4 can not be precisely expressed >>> by the powers of 2. Can the float handling rules of the underlying >>> layers be set from Python so that 3.4 yield 3.4? >> >> It seems, from the question, that you might not have entirely >> understood and grasped the explanations you can find at: >> http://www.python.org/doc/current/tut/node14.html >> and I quote, in particular: > > I know this is an FAQ, but the one thing I've never seen explained > satisfactorily is why repr(3.4) has to be '3.3999999999999999' rather than > '3.4'? > > Surely the important thing is that the equality eval(repr(x))==x has to > hold for floating point numbers, and that holds just as true for the short > 3.4 as it does for the 17 digit version? > > Microsoft .Net has a numeric format "R" which does a similar job. The R > specifier guarantees that a floating point numeric value converted to a > string will be parsed back into the same numeric value. It does this by > first trying a general format with 15 digits of precision then parsing > that back to a number. If the result is not the same as the original it > then falls back to the 17 digit value. There's no reason why Python > couldn't do the same: > > def float_repr(x): > s = "%.15g" % x > if float(s)==x: return s > return "%.17g" % x > > This would be MUCH friendlier for newcomers to the language. I like this idea, actually. Care to try your hand at a patch for 2.4 ...? Alex From __peter__ at web.de Fri Oct 10 16:25:34 2003 From: __peter__ at web.de (Peter Otten) Date: Fri, 10 Oct 2003 22:25:34 +0200 Subject: Preferred Python idiom for handling non-existing dictionary keys and why? References: Message-ID: Terry Reedy wrote: > Neither. For me, both are superceded by > > d={} > for (k,v) in somedata(): > d[k] = d.get(k, []).append(v) This would have to look up the key twice, so it has no advantage over if k in d: d[k].append(v) else: d[k] = [v] Anyway, list.append() returns always None, so it does not work. I think you mean d = {} for (k, v) in somedata: d.setdefault(k, []).append(v) There is a small overhead for throwing away a new list object if the key is already in the dictionary, but I don't really care. (Or is the compiler smart enough to reuse the empty list?) Peter From gerrit at nl.linux.org Thu Oct 9 14:44:55 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Thu, 9 Oct 2003 20:44:55 +0200 Subject: sys.exit() In-Reply-To: References: Message-ID: <20031009184455.GA7721@nl.linux.org> Ivan Voras wrote: > Gerrit Holl wrote: > > An alternative that I often choose is: > > > > raise SystemExit("I need arguments!") > > > > This is the same in one line, and I think it is more elegant, because > > it > > is higher-level: you are not using the low-level interface of error > > Yes, I agree. This is what I was looking for (as always, it was obvious > :) ), thanks. Only, what error code is returned for this termination method? For a string, I believe it is 1, although I don't know when this holds and when it doesn't - I don't care for myself, so I never tried to find out, really ;) Gerrit. -- 258. If any one hire an ox-driver, he shall pay him six gur of corn per year. -- 1780 BC, Hammurabi, Code of Law -- Asperger Syndroom - een persoonlijke benadering: http://people.nl.linux.org/~gerrit/ Kom in verzet tegen dit kabinet: http://www.sp.nl/ From tweedgeezer at hotmail.com Tue Oct 14 00:12:39 2003 From: tweedgeezer at hotmail.com (Jeremy Fincher) Date: 13 Oct 2003 21:12:39 -0700 Subject: question: usage of __slots__ References: <3F89620C.4080605@snafu.de> Message-ID: <698f09f8.0310132012.738e22fc@posting.google.com> Alexander Schmolck wrote in message news:... > __slots__ are a premature optimization and best avoided. It's nice to see that there's *someone* out there with a handle on every single possible use for Python. Jeremy From qrczak at knm.org.pl Tue Oct 28 04:55:58 2003 From: qrczak at knm.org.pl (Marcin 'Qrczak' Kowalczyk) Date: Tue, 28 Oct 2003 10:55:58 +0100 Subject: Python from Wise Guy's Viewpoint References: <6dnq61-kl.ln1@ID-7776.user.dfncis.de> <87oew33h8t.fsf@sidious.geddis.org> <3F9D5D21.2060408@ps.uni-sb.de> <20031027184024.GO1454@mapcar.org> Message-ID: On Tue, 28 Oct 2003 02:46:54 +0100, Pascal Costanza wrote: > Sorry, I don't get this. Why should it be more dangerous with dynamic > typing? Common Lisp definitely gets this right, and most probably some > other dynamically typed languages. Common Lisp, Scheme and Perl get it right: the result of / on integers is a rational or floating point number, and integer division is spelled differently. Python and Ruby get it wrong: the result is an integer (truncated division), very different from the result of / on the same numbers represented in a different type. If a statically typed language get's this "wrong", it doesn't hurt, except newbies which write 1/n. For example consider this: double foo(double *a, int len) { ... Some computation involving a[i]/a[j] which is supposed ... to produce a true real quotient. } You make some array of doubles, set a[i] = exp(i) (a double) and it works. Then you set a[i] = 2*i (an integer) and it still works, because the integer has been converted to double during assignment. An integer can be used in place of a double with the same value. Now in a dynamically typed language the analogous code would set some array elements to integers without conversion. If division on them means a different thing, an integer can no longer be used in place of a floating point number with the same value. And division is the only operation whith breaks this. Dynamically typed languages shouldn't use / for both real and truncating division. For statically typed languages it's only a matter of taste (I prefer to use different symbols), but for dynamically typed languages it's important to prevent bugs. -- __("< Marcin Kowalczyk \__/ qrczak at knm.org.pl ^^ http://qrnik.knm.org.pl/~qrczak/ From a.schmolck at gmx.net Wed Oct 15 13:33:43 2003 From: a.schmolck at gmx.net (Alexander Schmolck) Date: 15 Oct 2003 18:33:43 +0100 Subject: Python syntax in Lisp and Scheme References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> <92c59a2c.0310031345.57d20631@posting.google.com> Message-ID: Peter Seibel writes: > Alexander Schmolck writes: > > > Peter Seibel writes: > > > > > If for some reason you believe that macros will have a different > > > effect--perhaps decreasing simplicity, clarity, and directness then > > > I'm not surprised you disapprove of them. But I'm not sure why you'd > > > think they have that effect. > > > > Well, maybe he's seen things like IF*, MVB, RECEIVE, AIF, (or as far as > > simplicity is concerned LOOP)...? > > > > I'm not saying that macros always have ill-effects, but the actual > > examples above demonstrate that they *are* clearly used to by people > > to create idiosyncratic versions of standard functionality. Do you > > really think clarity, interoperability or expressiveness is served > > if person A writes MULTIPLE-VALUE-BIND, person B MVB and person C > > RECEIVE? > > Yes. But that's no different with macros than if someone decided that > they like BEGIN and END better than FIRST and REST (or CAR/CDR) and so wrote: > > (defun begin (list) (first list)) > (defun end (list) (rest list)) The reason it's different is that people apparently engage in the former (we seem to agree undesirable) behavior, but not in the latter. I suppose this is because programmers generally feel that wasting CPU cycles is a bad thing (I know you could DECLAIM INLINE the above in CL). Also, you can't do things like AIF as a function. > > As almost everyone who has stuck up for Lisp-style macros has > said--they are just another way of creating abstractions and thus, by > necessity, allow for the possibility of people creating bad > abstractions. I guess so much everyone agrees on:) The point that the lisp side seems to under-appreciate is that (even powerful) abstractions have their limitations and also come at a cost. This cost should be carefully analyzed because it is not always worth paying (and even if it is, as is surely the case for macros in CL, awareness of the downside might help minimize it). Unfortunately, I'm pretty worn out by this thread now and have to catch up with my work, so I won't go into detail. > But if I come up with examples of bad functional abstractions or poorly > designed classes, are you going to abandon functions and classes? Probably > not. Depends on the *implementation* of those constructs themselves and *which* features (e.g. multiple inheritance). I'd forgo C++ for some saner language without built-in OO anytime. > It really is the same thing. Would you like to see continuations in CL? If not, note that your argument would be equally applicable. > > > > > (deftest foo-tests () > > > (check > > > (= (foo 1 2 3) 42) > > > (= (foo 4 5 6) 99))) > > > > > > Note that this is all about the problem domain, namely testing. > > > > I think the example isn't a bad one, in principle, in practice > > however I guess you could handle this superiorly in python. > > Well, I admire your faith in Python. ;-) It would be less a question of faith, but more an incorrect conclusion. > > > I develop my testing code like this: > > > > # like python's unittest.TestCase, only that it doesn't "disarm" > > # exceptions > > TestCase = awmstest.PermeableTestCase > > #TestCase = unittest.TestCase > > > > class BarTest(TestCase): > > ... > > def test_foos(self): > > assert foo(1,2,3) = 42 > > assert foo(4,5,6) = 99 > > > > Now if you run this in emacs/ipython with '@pdb on' a failure will > > raise an Exception, the debugger is entered and emacs automatically > > will jump to the right source file and line of code (I am not > > mistaken in thinking that you can't achieve this using emacs/CL, > > right?) > > No, you're mistaken. In my test framework, test results are signaled > with "conditions" which are the Common Lisp version of exceptions. Run > in interactive mode, I will be dropped into the debugger at the point > the test case fails where I can use all the facilities of the debugger Yep, I'm aware. > to figure out what went wrong including jumping to the code in > question OK, I was under the maybe mistaken impression that this wasn't generally possible (if by "jumping to the code" you mean actually jumping to *the line* where the error occured, in your editor window). > examining stack framse, and then if I think I've figured out > the problem, I can redefine a function or two and retry the test case > and proceed with the rest of my test run with the fixed code. Yes, restarts sure are handy for interactive development (and absent in python). > (Obviously, after such a run you'd want to re-run the earlier tests to > make sure you hadn't regressed. If I really wanted, I could keep track > of the tests that had been run prior to such a change and offer to > rerun them automatically.) > > > and I can interactively inspect the stackframes and objects that > > were involved in the failure. > > Yup. Me too. Can you retry the test case and proceed with the rest of > your tests? Nope, not to my knowledge (if anyone knows how to do this with pdb, I'd love to hear about it). > Yup. That's really handy. I agree. > > So, in all sincere curiosity, why did you assume that this couldn't be > done in Lisp. Well, basically because I tried to get some reasonable debugging environment working (with ilisp/cmucl or clisp) and failed miserably (and googling didn't help much further either). That macros (esp. reader macros) wouldn't interact all that well with source level debugging also didn't seem like the most unreasonable assumption. Any suggestions how to get something like the following to source debug with emacs/ilisp/cmucl? ;;test-debug.lisp (declaim (optimize (debug 3))) (defun buggy-defun () (loop with bar = 10 for i below 30 collect (/ i (- i bar)))) ;<= I'd like to start stepping here in emacs (buggy-defun) > I really am interested as I'm writing a book about Common Lisp and part of > the challenge is dealing with people's existing ideas about the language. Good idea. I think it would also be worthwhile to have a good luck at close competitors like python in order to do so effectively. > Feel free to email me directly if you consider that too far offtopic for > c.l.python. > > -Peter 'as From cartermark46 at ukmail.com Mon Oct 13 06:34:47 2003 From: cartermark46 at ukmail.com (Mark Carter) Date: 13 Oct 2003 03:34:47 -0700 Subject: XML-RPC, SOAP, and data persistence Message-ID: I had a play with XML-RPC the other day, and it seemed really simple to use; which really made an impression on me. But you can't make data persist on the server (not without rolling your own mechanism, at any rate). I'm thinking here about thin clients, where the main process runs on a server. Is there any free solution to this problem? Is SOAP the answer? From CousinStanley at hotmail.com Wed Oct 22 11:42:32 2003 From: CousinStanley at hotmail.com (Cousin Stanley) Date: Wed, 22 Oct 2003 08:42:32 -0700 Subject: Trailing comma (was: Re: structure in Python) References: Message-ID: Skip ... Thanks for the info .... In the case where an addition is made to the end of a L O N G sequence and then followed by a resort, I can see that depending on how the sequence is used that problems arising from inadvertent omission of the comma delimeter by whomever extended the sequence might not manifest themselves immediately and could perhaps be difficult to spot .... In spite of my Python teacher's praise for using this style, I would probably still wonder how he/she managed to make it through school without getting whacked for using it themselves .... -- Cousin Stanley Human Being Phoenix, Arizona From tim.hochberg at ieee.org Wed Oct 15 16:15:36 2003 From: tim.hochberg at ieee.org (Tim Hochberg) Date: Wed, 15 Oct 2003 13:15:36 -0700 Subject: Python syntax in Lisp and Scheme In-Reply-To: <87oewi9spr.fsf@bird.agharta.de> References: <8CVgb.8$KR3.1846@typhoon.nyu.edu> <20031014050046.GM1454@mapcar.org> <6mWdnVM6bOIOiRGiU-KYhA@comcast.com> <3f8c24c6@news.sentex.net> <87oewi9spr.fsf@bird.agharta.de> Message-ID: Edi Weitz wrote: > On Wed, 15 Oct 2003 12:41:07 -0700, David Eppstein wrote: > > >>Apparently I was mistaken, at least for modern lisps. I haven't >>programmed in lisp for a long time; the most recent lisp manual I >>can find at hand is a 1981 Chinual, which still seems to be using >>dynamic scoping and requires an explicit function call to create a >>closure. > > > Fair enough. But then we should compare this Lisp to the state of > Python around 1981... :) Nope, with python in 2010 -- at that point, Python will be about as old as Lisp was in '81. -tim > Edi. From santanu at softhome.net Thu Oct 9 15:55:37 2003 From: santanu at softhome.net (Santanu Chatterjee) Date: Fri, 10 Oct 2003 00:55:37 +0500 Subject: A query about list Message-ID: Hello everybody, I am very new to python. I have a query about list in python. Suppose I have a list a = [1,[2,3,4],5,6,7,[8,9,10],11,12] I want to know if there is any simple python facility available that would expand the above list to give a = [1,2,3,4,5,6,7,8,9,10,11,12] I know I can do that with a type() and a for/while loop, but is there any simpler way? Regards, Santanu From martin at v.loewis.de Wed Oct 1 01:29:39 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 01 Oct 2003 07:29:39 +0200 Subject: PEP-0263 and default encoding References: <3f782aef-bdbbd6f1-a72a-4a6c-8b23-c4915b89a61f@news.szn.dk> Message-ID: "John Roth" writes: > > 2. You are writing new code, and you are annoyed by the encoding > > declaration. Just save your code as UTF-8, using the UTF-8 BOM. > > The problem with the UTF-8 BOM is that it precludes using the #! header > line under Linux/Unix. Otherwise, it's a great solution. Indeed, in an executable script, you would use the encoding declaration - or you would restrict yourself to ASCII only in the script file (which might, as its only action, invoke a function from a library, in which case there really isn't much need for non-ASCII characters). OTOH, I do hope that Unix, some day, recognizes UTF-8-BOM-#-! as executable file. Regards, Martin From aleax at aleax.it Tue Oct 28 09:40:46 2003 From: aleax at aleax.it (Alex Martelli) Date: Tue, 28 Oct 2003 14:40:46 GMT Subject: itertools.flatten()? and copying generators/iterators. References: Message-ID: Francis Avila wrote: ... > try: seq+'' seems more expensive. Is it just to handle the case where > someone makes a string-alike that doesn't derive from str? (Actually, I As per my other post, it sure SEEMS more expensive - whether it IS or not depends on details:-). Yes, it's basically to try and treat as a string any class that looks like one. > guess that's about all pre-2.2 code.) Nope, UserString is still alive and well in 2.2 and 2.3 -- and doesn't subclass basestring (I don't know why). Yes, if you write stringlike classes in 2.2 and later, subclassing basestring, just as a "flag" since quite a few spots may specialcase instances of basestring, IS becoming advisable, I suspect. > Is it expensive enough to even matter? Nope (in the sample case I measured), again see my other post for details. But perhaps my old-style insistence against isinstance abuse is becoming misplaced in this one case -- basestring exists ONLY for the purpose of allowing easy isinstance checks, after all, it offers no useful functionality per se. So, I should maybe resign myself to the inevitable... ...and hope a similar type 'basenumber' to become the "just flagging" baseclass of int, long, float and complext doesn't emerge...:-) Alex From seberino at spawar.navy.mil Tue Oct 21 18:37:05 2003 From: seberino at spawar.navy.mil (Christian Seberino) Date: 21 Oct 2003 15:37:05 -0700 Subject: distutils:How suppress warning message? (about nonstandard install path) Message-ID: distutils question: I reset prefix to something else and happily installed everything a package I made fine. There is a warning message at end of installation about prefix not being in sys.path. Can I remove this warning somehow?? Chris From soso_pub at yahoo.com Fri Oct 3 16:02:04 2003 From: soso_pub at yahoo.com (soso) Date: Fri, 3 Oct 2003 13:02:04 -0700 (PDT) Subject: Find subclasses of a class Message-ID: <20031003200204.36661.qmail@web14810.mail.yahoo.com> Hi everybody, Is there a way to find out the subclasses of a class? Thanks in advance, soso __________________________________ Do you Yahoo!? The New Yahoo! Shopping - with improved product search http://shopping.yahoo.com From p.magwene at snet.net Tue Oct 14 18:43:39 2003 From: p.magwene at snet.net (netnews.upenn.edu) Date: Tue, 14 Oct 2003 18:43:39 -0400 Subject: Python LaTeX codec? In-Reply-To: References: Message-ID: David Eppstein wrote: >> >> >>Microsoft Windows 2000 [Version 5.00.2195] >>(C) Copyright 1985-2000 Microsoft Corp. > > > I am using a Mac, so Windows not having these isn't a problem. > > But, Park's response doesn't really address my question at all. > For one thing, there was a reason I asked for this as Python code, which > is that I want to use this as a subroutine of a larger application, and That was essentially the point of the rest of my post -- the quoted unix tools weren't universal and that you had asked for Python code. I used Windows as an example because that was the box I was sitting at when I read the post. Actually, I think many (all?) of those tools may be available by default if you're using OS X, but I'm too lazy to fire up my powerbook at the moment... --Paul From bokr at oz.net Thu Oct 2 14:29:47 2003 From: bokr at oz.net (Bengt Richter) Date: 2 Oct 2003 18:29:47 GMT Subject: Prime number module References: <7b4hnvgplqk6g1d5vig0dsdvic1ru62r4e@4ax.com> <+Nfe/kKkXkJT092yn@gnosis.cx> Message-ID: On Wed, 01 Oct 2003 02:35:31 -0400, Lulu of the Lotus-Eaters wrote: >|> I was disappointed that gzip only reduces the size by 41%. I would have >|> guessed better, given the predominance of 0 bits. > >Juha Autero wrote previously: >|patterns and it's hardly a suprise that bitmap of prime numbers >|doesn't have lots of repeating bit patterns. > >Sure it does. The bit pattern "0 0 0 0 0 0 0" occurs a WHOLE LOT of >times :-). Certainly much more than any other pattern. After all, my >10^8/2 bits only contain 5,761,453 ones among them[*]--there's got to be >a lot of runs of zeros in there :-). > >The problem, I think, is that these bit patterns don't fall on byte >borders as neatly as I would like. I am pretty sure that I could write >a custom LZ-style compressor that did better by being bit-oriented >rather than byte-oriented. But I'm not going to do that work, 3.8 megs >is small enough for me. Hm, a bit sequence 001010010010000100100001001000010000001001 ... could be encoded in a series of symbols '001', '01', '001', '001', '00001', '001', ... which are essentially just different string representations for prime first differences, e.g., (faking in the starting 0) >>> prime = [0,2,3,5,7,11,13,17,19,23,29,31] >>> ['0'*(prime[i+1]-prime[i])+'1' for i in range(len(prime)-1)] ['001', '01', '001', '001', '00001', '001', '00001', '001', '00001', '0000001', '001'] Or, using different concrete symbols, >>> [chr(prime[i+1]-prime[i]+ord('a')) for i in range(len(prime)-1)] ['c', 'b', 'c', 'c', 'e', 'c', 'e', 'c', 'e', 'g', 'c'] Maybe it would be best to analyze the frequency and assign huffman codes and pack those, for maximal compression? I guess that is about what zip would do to the latter (byte-oriented, as you mentioned) symbols. But actually, I was looking at a modulo 2*3*5*7... mask as a pre-compression step, which might pack things even tighter, because it eliminates whole structured patterns from the whole. One could do a bigger modulo too. If I get ambitious, I might try it. I have an inkling of a multi-step modulo, multi-bitmap check that could go fast in smaller space, but I have to meet someone now... [Back next day, didn't post that] The idea alluded to above is to make a mask using a selected part of the front of the big bitmap, and noting that its zeroes are guaranteed to repeat in forward repeats of that mask, so those zeroes don't need actual representation going forward. I.e., if pfact(p) is the "factorial" product of all primes from p on down, then if mlen=pfact(p), [bitmap[i:i+mlen] for i in range(1,len(bitmap):mlen)] will be (untested) a list of bitmap chunks with guaranteed zeroes everywhere bitmap[1:mlen+1] had them. I downloaded your bitmap, so it should be easy to confirm... (Ok, but I reconstituted the theoretical bitmap by including factors of 2 and the primes 1 & 2 in the following) ===< primask.py >==================================================== def getbitmasks(fpath, nb): chunksize = (nb/2+7)//8 # nb/2 since even bits are not in bitfile f = file(fpath,'rb') bits = [] def bufbits(): if len(bits)>=nb: return bitchunk = f.read(chunksize) # bigendian bytes w/ bits for odd no's 1,3,5... for byte in bitchunk: ibyte = ord(byte) for b in xrange(8): bits.append('.1'[(0x80>>b)&ibyte>0]) bits.append('.') # add in evens bufbits() bits[0:2] = ['1','1'] # account for primes 1 & 2 not in bit file at front while 1: bufbits() # make sure if not bits: break yield ''.join(bits[:nb]) bits = bits[nb:] def primask(p, nlines=5): pf = {2:2, 3:6, 5:30, 7:210, 11:2310, 13:30030, 17:510510}[p] # should suffice bgen = getbitmasks('primes.bitarray', pf) print 'Prime for mask = %s, mask length = %s' % (p, pf) for n in xrange(nlines): s = bgen.next() nz = s.count('.') if not n: print 'Precompression possible: (%s-%s zeroes)/%s => %.1f %% of orig' %( pf,nz,pf,100.*(pf-nz)/pf) print '%4s: %s' %(nz, len(s)<80 and s or s[:80]+' etc.') if __name__ == '__main__': import sys try: args = map(int, sys.argv[1:]) p = args.pop(0) nl = args and args.pop(0) or 5 primask(p, nl) except: raise; SystemExit(""" Usage: primask prime [number_of_lines] where prime determines size of mask as product of primes at and below this and number of lines is number to print.""") ===================================================================== This will print segments of the bit map (reconstituted to include all numbers starting with 1,2,3,...). The segments are the length of a possible mask taken from the front whose non-prime slots are bound to repeat through the rest, since corresponding slots will be multiples of the primes in the first set. Since those zeroes repeat, one could remove them from the rest of the bit file, as you did with even numbers. I print the possible compression based on the number of zeroes in the first segment. So unless I goofed, ... (To read primes from masks start with 1,2,3,(.),5,(.) etc) [11:00] C:\pywk\clp\prime>primask.py 3 Prime for mask = 3, mask length = 6 Precompression possible: (6-2 zeroes)/6 => 66.7 % of orig 2: 111.1. 123 5 <<-- (primes represented, etc) 4: 1...1. 7 +--11 4: 1...1. | +--17 +------13 4: 1...1. 5: ....1. [11:00] C:\pywk\clp\prime>primask.py 5 Prime for mask = 5, mask length = 30 Precompression possible: (30-19 zeroes)/30 => 36.7 % of orig 19: 111.1.1...1.1...1.1...1.....1. 23: 1.....1...1.1...1.....1.....1. 23: 1.....1...1.1.....1...1.....1. 24: ......1...1.1...1.1...1....... 25: ......1...1.....1.1.........1. [11:00] C:\pywk\clp\prime>primask.py 7 Prime for mask = 7, mask length = 210 Precompression possible: (210-163 zeroes)/210 => 22.4 % of orig 163: 111.1.1...1.1...1.1...1.....1.1.....1...1.1...1.....1.....1.1.....1...1.1.....1. etc. 175: 1...........1...1.1...1.....1.1.........1.....1.....1.....1.1.....1...1.1....... etc. 177: 1.........1.1.....1...1.....1.......1...1.1...1...........1.......1...1.......1. etc. 178: 1.........1.1...1.....1.....1.1...........1...1.....1.......1.........1.......1. etc. 180: ............1...1.1...1.............1...1.1...1...................1...1.......1. etc. [11:00] C:\pywk\clp\prime>primask.py 11 Prime for mask = 11, mask length = 2310 Precompression possible: (2310-1966 zeroes)/2310 => 14.9 % of orig 1966: 111.1.1...1.1...1.1...1.....1.1.....1...1.1...1.....1.....1.1.....1...1.1.....1. etc. 2030: 1.....................1.....1.1.....1...1.....1.............1.....1...1.1.....1. etc. 2043: 1...............1.1...1.....1.1.....1.....1.........1.....1...........1......... etc. 2055: ................1.1.........1.1.....1...1.....1.....1.......1.....1...1......... etc. 2064: 1...............1...................1...1.1.........1.................1.......1. etc. [11:00] C:\pywk\clp\prime>primask.py 13 Prime for mask = 13, mask length = 30030 Precompression possible: (30030-26781 zeroes)/30030 => 10.8 % of orig 26781: 111.1.1...1.1...1.1...1.....1.1.....1...1.1...1.....1.....1.1.....1...1.1.....1. etc. 27216: ................1...........1...........1.................1.1.....1.....1.....1. etc. 27366: ................1.....1.....1.1.........1.1...1...................1.....1.....1. etc. 27444: ................1.............1.....1.....................1.............1....... etc. 27481: 1...................................1.....1...1.............1...........1.....1. etc. [11:00] C:\pywk\clp\prime>primask.py 17 Prime for mask = 17, mask length = 510510 Precompression possible: (510510-468178 zeroes)/510510 => 8.3 % of orig 468178: 111.1.1...1.1...1.1...1.....1.1.....1...1.1...1.....1.....1.1.....1...1.1.....1. etc. 472790: ..................1.....................1.1...............1...........1.1.....1. etc. 474186: ......................1.......................1.....1.......1.....1...1.1....... etc. 475041: ..................1...........1.....1.......................1................... etc. 475727: ..................1.................1.....1.......................1...1......... etc. So it appears we could compress that file (imagining it as containing evens also) quite a bit, by using a (510510+7)//8 => 63814 byte mask as the pattern for squishing zeroes out of the rest. BTW, I thought primes ran about 10% of all numbers, so 8.3 % seems a little suspicious. Did I goof, or what is the right percentage? I guess I'll make a dict of all the gap sizes with their respective counts in the bit map and see, but have to leave this for now ... > >FWIW, bzip2 doesn't do much better either. I'd be kinda surprised at >this point if another representation of the primes under 10^8 actually >did better[**]. I proposed listing the gaps as a strategy; but given >that there are 5.7 million gaps to list, it's hard to beat 3.8 megs. >Maybe encoding gaps in nibbles-with-escaping would work. But now I'm >fond of the speed of the bit array. > >Yours, Lulu... > >[*] I'm missing two primes versus some other claims. My odd numbers >don't include 2; and I called 1 a non-prime. I don't feel strongly >about the second matter though. > >[**] Well, a MUCH shorter representation is a Python-coded algorithm for >generating the primes in the first place. But somehow that seems like >cheating :-). Oops, better post this and go... Regards, Bengt Richter From bignose-hates-spam at and-benfinney-does-too.id.au Sun Oct 5 23:20:27 2003 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 6 Oct 2003 13:10:27 +0950 Subject: use make and version control system for every project? References: Message-ID: On Mon, 06 Oct 2003 03:08:57 GMT, Carl Banks wrote: > I recommended not bothering early on because I tend to move files > around quite a bit early on (a major pain in CVS), and I suspect I'm > not the only person to do that. That's a flaw of CVS, not of revision control. Other revision control systems (Arch, Subversion, even RCS) don't suffer from this flaw; use any of those to have *no* excuse not to use revision control from the project's inception. > Incidentally, this is probably greatest strength of version control > relative to frequent backups (for personal projects, of course). It's > also a feature I've found extremely little use for. I mean, it sounds > cool to be able to go back and see exactly when you made a certain > change, but is that really useful in practice? It's more than cool. A change history is vital on a fast-changing project; you can see when a particular feature went in, when a bug was fixed, when a structural change was made, etc. A change history is vital in multi-developer projects (though that's not what the OP asked about) to supplement fallible human memory. A change history is required by many free software licenses (the GPL being one) when you change another's work. Sound useful enough? -- \ "Last year I went fishing with Salvador Dali. He was using a | `\ dotted line. He caught every other fish." -- Steven Wright | _o__) | Ben Finney From aleax at aleax.it Tue Oct 28 06:35:25 2003 From: aleax at aleax.it (Alex Martelli) Date: Tue, 28 Oct 2003 11:35:25 GMT Subject: Python is Considered Harmful References: <7ioew3xjh1.fsf@enark.csis.hku.hk> Message-ID: <1wsnb.366321$R32.12079281@news2.tin.it> Jegenye 2001 Bt wrote: > Thank you, Alex, for clarifing this issue for me.. > > So this was actually like the famous equation > "9*6=42" > :-) > It is correct (or incorrect) if you look at it in the right (or wrong) > way. Do you mean, implicitly using base 13? I know of no programming language that lets you set the number base to be used for literals (except presumably ones with particularly 'powerful' macros...?-) and I hope I never have to contend with one. Alex From joswig at lispmachine.de Tue Oct 14 17:09:10 2003 From: joswig at lispmachine.de (Rainer Joswig) Date: Tue, 14 Oct 2003 17:09:10 -0400 Subject: Why don't people like lisp? References: <86ecnT2RX9nDxhGiXTWJlg@comcast.com> <9aZib.4$pt4.1610@news1.telusplanet.net> Message-ID: In article <9aZib.4$pt4.1610 at news1.telusplanet.net>, Wade Humeniuk wrote: > Terry Reedy wrote: > > > My contemporaneous impression, correct or not, as formed from > > miscellaneous mentions in the computer press and computer shows, was > > that they were expensive, slow, and limited -- limited in the sense of > > being specialized to running Lisp, rather than any language I might > > want to use. I can understand that a dedicated Lisper would not > > consider Lisp-only to be a real limitation, but for the rest of us... > > > > Well its not true. Symbolics for one supported additional languages, > and I am sure others have pointed out that are C compilers for > the Lisp Machines. > > See > > http://kogs-www.informatik.uni-hamburg.de/~moeller/symbolics-info/symbolics-tech-summary.html > > Section: Other Languages > > It says that Prolog, Fortran and Pascal were available. > > Wade > ADA also. Actually using an incremental C compiler and running C on type- and bounds-checking hardware - like on the Lisp Machine - is not that a bad idea. A whole set of problems disappears. From imbosol at aerojockey.invalid Sun Oct 5 22:00:44 2003 From: imbosol at aerojockey.invalid (Carl Banks) Date: Mon, 06 Oct 2003 02:00:44 GMT Subject: use make and version control system for every project? References: Message-ID: AK wrote: > Hi, I recently read an advice here that one should try to use make and > version control system even if you're the only one working on the > program. Is that a good advice? How many of you do that? Personally, I use make on every single one of my projects. I even use make to run setup.py in my pure Python packages. (Cause it's just easier to 'type make install' than 'python setup.py install--home=~'.) It's not necessary, but it can save a lot of work and keep everything up-to-date. Version control, it depends. I've used CVS for some personal projects before, and can't say I've ever found it useful, and it's definitely a pain to keep things up-to-date. I recommend, for personal projects, not bothering with version control at least until the project is fairly stable. But if you don't use version control, be sure to make frequent backups (and store the backups on another medium; hard disks crash; it happened to me). my-2-cents-ly yr's, -- CARL BANKS http://www.aerojockey.com/software As the newest Lady Turnpot descended into the kitchen wrapped only in her celery-green dressing gown, her creamy bosom rising and falling like a temperamental souffle, her tart mouth pursed in distaste, the sous-chef whispered to the scullery boy, "I don't know what to make of her." --Laurel Fortuner, Montendre, France 1992 Bulwer-Lytton Fiction Contest Winner From gerrit at nl.linux.org Fri Oct 3 07:05:52 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Fri, 3 Oct 2003 13:05:52 +0200 Subject: Learning Python By Mark Lutz, David Ascher In-Reply-To: <5e8bd451.0310022359.47862a89@posting.google.com> References: <5e8bd451.0310022359.47862a89@posting.google.com> Message-ID: <20031003110552.GA3542@nl.linux.org> kevin parks wrote: > Is as excellent as it is out of date. Which is to say it is > exceedingly, ridiculously, hideously, insanely, absurdly out of date. > *^-^* (look again there is a compliment in there ^^) > > And i hear again and again and again and again, over and over and over > how a 2nd edition is due any time now... Amazon claimed 1 october until 1 october arrives, now it says that it may is due any time :) regards, Gerrit. -- 49. If any one take money from a merchant, and give the merchant a field tillable for corn or sesame and order him to plant corn or sesame in the field, and to harvest the crop; if the cultivator plant corn or sesame in the field, at the harvest the corn or sesame that is in the field shall belong to the owner of the field and he shall pay corn as rent, for the money he received from the merchant, and the livelihood of the cultivator shall he give to the merchant. -- 1780 BC, Hammurabi, Code of Law -- Asperger Syndroom - een persoonlijke benadering: http://people.nl.linux.org/~gerrit/ Het zijn tijden om je zelf met politiek te bemoeien: http://www.sp.nl/ From peter at javamonkey.com Tue Oct 7 18:37:20 2003 From: peter at javamonkey.com (Peter Seibel) Date: Tue, 07 Oct 2003 22:37:20 GMT Subject: Python syntax in Lisp and Scheme References: Message-ID: corey.coughlin at attbi.com (Corey Coughlin) writes: > Using parentheses and rpn everywhere makes lisp very easy to parse, > but I'd rather have something easy for me to understand and hard for > the computer to parse. That would be a strong argument--seriously--if the only folks who benefited from the trivial mapping between Lisp's surface syntax and underlying were the compiler writers. I certainly agree that if by expending some extra effort once compiler writers can save their users effort every time they write a program that is a good trade off. If the only thing a "regular" programmer ever does with a language's syntax is read and write it, then the only balance to be struck is between the perhaps conflicting goals of readability and writability. (For instance more concise code may be more "writable" but taken to an extreme it may be "write only".) But "machine parsability" beyond, perhaps, being amennable to normal machine parsing techniques (LL, LALR, etc.) should not be a consideration. So I agree with you. But Lisp's syntax is not the way it is to make the compiler writer's job easier. In Lisp "regular" programmers also interact with the code as data. We can easily write code generators (i.e. macros) that are handed a data representation of some code, or parts of code, and have only to return a new data structure representing the generated code. This is such a useful technique that it's built into the compiler--it will run our code generators when it compiles our code so we don't have to screw around figuring out how to generate code at runtime and get it loaded into our program. *That's* why we don't mind, and, in fact, actively like, Lisp's syntax. The point is not that the syntax, taking in total isolation from the rest of the language, is necessarily the best of all possible syntaxi. The point is that the syntax makes other things possible that *way* outweigh whatever negatives the syntax may have. I'd humbly suggest that if you can't see *any* reason why someone would prefer Lisp's syntax, then you're not missing some fact about the syntax itself but about how other language features are supported by the syntax. -Peter -- Peter Seibel peter at javamonkey.com Lisp is the red pill. -- John Fraser, comp.lang.lisp From fgeiger at datec.at Sun Oct 12 03:49:55 2003 From: fgeiger at datec.at (F. GEIGER) Date: Sun, 12 Oct 2003 09:49:55 +0200 Subject: type checking References: Message-ID: <3f89075d@news.swissonline.ch> "sashan" schrieb im Newsbeitrag news:bmafsm$3i9$1 at lust.ihug.co.nz... > I'm a Python newbie. I have been using c++ for 5 years and before that I > was programming in Pascal. The one thing that annoys me about python > is dynamic typing because I find myself making typographical errors of > the sort that would under C++ be picked up by the compiler at compiler > time. With Python I have to wait for the error to appear at runtime in > order for me to correct it. I find this inefficient. Any advice about > how to get around this would be appreciated. > Use pychecker for that. It really helps to find typos. Cheers Franz GEIGER From jockc at mail.com Wed Oct 15 13:09:04 2003 From: jockc at mail.com (Jock Cooper) Date: 15 Oct 2003 10:09:04 -0700 Subject: Python syntax in Lisp and Scheme References: <8CVgb.8$KR3.1846@typhoon.nyu.edu> <20031014050046.GM1454@mapcar.org> <6mWdnVM6bOIOiRGiU-KYhA@comcast.com> <3f8c24c6@news.sentex.net> Message-ID: David Eppstein writes: > In article , > David Eppstein wrote: > > > > Isn't it true though that the lambda can only contain a single expression > > > and no statements? That seems to limit closures somewhat. > > > > It limits lambdas. It doesn't limit named functions. Unlike lisp, a > > Python function definition can be nested within a function call, and the > > inner function can access variables in the outer function's closure. > > To clarify, by "unlike lisp" I meant only that defun doesn't nest (at > least in the lisps I've programmed) -- of course you could use flet, or > bind a variable to a lambda, or whatever. > Ok so in Python a function can DEF another function in its body. I assume this can be returned to the caller. When you have a nested DEF like that, is the nested function's name globally visible? From klapotec at chello.at Wed Oct 1 07:54:04 2003 From: klapotec at chello.at (Christopher Koppler) Date: 1 Oct 2003 04:54:04 -0700 Subject: terminal character control clean up References: Message-ID: Eric Texier wrote in message news:... > On linux, I am parsing the output of an executable > that's returning color and font information, thing like > \x1b[1m\x1b[31m. > > It's there a module that will help me clean up those control, > or do I have to do it with regular expression. > Thanks for your help take a look at Twisted's AnsiParser: http://twisted.sourceforge.net/TwistedDocs-1.0.3/api/public/twisted.conch.ui.ansi.AnsiParser.html -- Christopher From fjh at cs.mu.oz.au Mon Oct 27 12:27:11 2003 From: fjh at cs.mu.oz.au (Fergus Henderson) Date: Mon, 27 Oct 2003 17:27:11 GMT Subject: Python from Wise Guy's Viewpoint References: <_8Ekb.7543$pT1.318@twister.nyc.rr.com> <3f972315$1@news.unimelb.edu.au> <3638acfd.0310230039.306b14f@posting.google.com> Message-ID: <3f9d556c$1@news.unimelb.edu.au> Pascal Costanza writes: >In a statically typed language, when I write a test case that calls a >specific method, I need to write at least one class that implements at >least that method, otherwise the code won't compile. No -- you don't need to implement the method. You only need to declare it. Even the need to declare it is really just a property of implementations, not languages. >Well, the research that ultimately lead to the HotSpot Virtual Machine >originated in virtual machines for Smalltalk and for Self. Especially >Self is an "extremely" dynamic language, but they still managed to make >it execute reasonably fast. Please correct me if I'm wrong, but as I understand it, iterating over a collection of values is still going to require keeping some representation of the type of each element around at runtime, and testing the type for each element accessed, in case it is not the expected type. AFAIK neither HotSpot nor the Self compiler do the kind of optimizations which would be needed to avoid that. -- Fergus Henderson | "I have always known that the pursuit The University of Melbourne | of excellence is a lethal habit" WWW: | -- the last words of T. S. Garp. From mwilson at the-wire.com Sat Oct 4 21:58:54 2003 From: mwilson at the-wire.com (Mel Wilson) Date: Sat, 04 Oct 2003 21:58:54 -0400 Subject: newbie needs help with GUI References: <3F7F1F51.D7976752@easystreet.com> <1065296088.11913.16.camel@devilbox.homelinux.net> Message-ID: In article , Patrick Useldinger

wrote: >Is there any statistical analysis available if the probability of >running out of characters is more or less likely with a given (natural) >language? Or a given set of applications? You don't see a lot of Usenet postings from Poland or Hawai'i, do you? That is why. Had the last WTO round not failed, trade in vowels and consonants between Poland and Hawai'i would have solved the problem, to the immense profit of both. Regards. Mel. From tjreedy at udel.edu Sun Oct 5 12:18:43 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 5 Oct 2003 12:18:43 -0400 Subject: Callable assertion? References: Message-ID: "Roy Smith" wrote in message news:roy-F9A420.08554505102003 at reader2.panix.com... > I've got a function which gets passed a call-back function as a > parameter. I want to check to make sure the thing passed in is indeed > callable. The acid test is to try calling it: try: param() except TypeError, msg: You can check that msg.endswith('not callable') if you want but I don't know the stability of the error message. Terry J. Reedy From http Tue Oct 21 16:24:05 2003 From: http (Paul Rubin) Date: 21 Oct 2003 13:24:05 -0700 Subject: Why don't people like lisp? References: <3f9302d7.170372828@news.eircom.net> <87ismkcp5d.fsf@bird.agharta.de> Message-ID: <7x65iiqqze.fsf@ruckus.brouhaha.com> mertz at gnosis.cx (David Mertz) writes: > |-rwxr-xr-x 1 root wheel 4596224 Sep 24 04:29 /usr/bin/emacs > |~bruce$ ls -l /Applications/Microsoft\ Office\ X/Microsoft\ Word > |-rwxr-xr-x 1 bruce admin 10568066 Sep 26 2002 > |/Applications/Microsoft Office X/Microsoft Word > > Not even Windows users use MS-Word to edit program code; this is a > completely irrelevant comparison. OK, compare it to Visual Studio (not counting the compilers) instead. > IOW: Emacs is BLOATED. Or whatever else you're using is underpowered... From max at alcyone.com Sun Oct 5 22:01:29 2003 From: max at alcyone.com (Erik Max Francis) Date: Sun, 05 Oct 2003 19:01:29 -0700 Subject: use make and version control system for every project? References: Message-ID: <3F80CCF9.41329B17@alcyone.com> AK wrote: > Hi, I recently read an advice here that one should try to use make and > version control system even if you're the only one working on the > program. Is that a good advice? How many of you do that? Yes, and yes. All my Web sites and programs are built with make, even my resume (of which a few variations are built from templates and then each is automatically converted to a bunch of formats). Using source control, even for your solitary projects, is always advisable: you get a little touch of automatic backups (particularly if your source control server is on a different machine), as well as the ability to work on different branches simultaneously and have authoritative information on precisely what you did to your software and when. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ Every path has its puddle. \__/ (an English proverb) From bill at kill.com Sat Oct 25 19:37:01 2003 From: bill at kill.com (Kill Bill) Date: Sat, 25 Oct 2003 19:37:01 -0400 Subject: Regular expressions References: Message-ID: Also, if yipee is a variable, what happens when I do? re.search("[yipee]*", line): This will treat yipee as a string correct? I want it to treat yipee as a variable and perform the different combinations on whatever is inside the variable. "Kill Bill" wrote in message news:bneu7i$10u2ht$1 at ID-198839.news.uni-berlin.de... > I'm trying to find all combinations of the a string. > I found that [blah]* gives it to me but it uses the same letter multiple > times which I dont' want. > > From dfarning at localhost.localdomain Thu Oct 23 12:10:48 2003 From: dfarning at localhost.localdomain (dave) Date: Thu, 23 Oct 2003 16:10:48 GMT Subject: config file saver Message-ID: I am current using ConfigParse to read my config file. Is anyone aware of a good example of a class that I can use to modify and then rewrite the config data back to file. Dave From newsgroups at jhrothjr.com Tue Oct 28 18:38:39 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Tue, 28 Oct 2003 18:38:39 -0500 Subject: PEP 322: Reverse Iteration (REVISED, please comment) References: <5d83790c.0310281022.6264aa16@posting.google.com> Message-ID: +1 "Raymond Hettinger" wrote in message news:5d83790c.0310281022.6264aa16 at posting.google.com... > Based on your extensive feedback, PEP 322 has been completely revised. > The response was strongly positive, but almost everyone preferred > having a function instead of multiple object methods. The updated > proposal is at: > > www.python.org/peps/pep-0322.html > > In a nutshell, it proposes a builtin function that greatly simplifies reverse > iteration. The core concept is that clarity comes from specifying a > sequence in a forward direction and then saying, "inreverse()": > > for elem in inreverse(seqn): > . . . > > Unlike seqn[::-1], this produces a fast iterator instead of a full reversed > copy. > > Discussions with Guido made it clear that inreverse() will not be extended > to cover all iterables. The proposal is about simplicity, expression, and > performance. As such, it would be counter-productive to take in a general > iterable, run it to completion, save the data in memory, and then iterate > over the data in reverse. It's certainly clear enough, and I like it in general. I'd appreciate a bit of discussion about why reverse() was rejected as the name, though. John Roth > > > Raymond Hettinger From stevena at neosynapse.net Fri Oct 3 13:02:20 2003 From: stevena at neosynapse.net (Steven D. Arnold) Date: Fri, 03 Oct 2003 13:02:20 -0400 Subject: can't import dl module Message-ID: Hi, I'm on Mac OS X 10.2.6, using Python 2.3final. I would like to use the dl module to get access to some system calls, in particular kvm_getprocs. However, when I try to import dl at the Python command-line, it tells me it couldn't find the module. It would seem I have to do something special to get dl to build on my machine. Does anyone know what that would be? Or is there some other problem that prevents this from working? Alternatively, does anyone know what else I could do to get at those calls? Perhaps I could try SWIG, but that seems like a hassle compared to dl. Thanks, steve From aleaxit at yahoo.com Sun Oct 12 16:43:46 2003 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 12 Oct 2003 20:43:46 GMT Subject: Identifying Caller References: Message-ID: <62jib.272389$R32.8873728@news2.tin.it> Tongu? Yumruk wrote: > Is there a way to identify the caller of a function? For example: > > def foo(): > print > > def bar(): > foo() > > I want foo to print "bar"... And it will be great if I can also detect > call is came from which module. See function _getframe in module sys. The frame object that it returns has many attributes useful for your tasks. In particular, sys._getframe(1).f_code.co_name should be 'bar' as you require, and sys._getframe(1).f_globals['__name__'] should be the module name which you desire. Alex From eppstein at ics.uci.edu Sun Oct 5 12:28:13 2003 From: eppstein at ics.uci.edu (David Eppstein) Date: Sun, 05 Oct 2003 09:28:13 -0700 Subject: About that 'yield' word References: <954cdb5b6f1176116641306583c684c3@news.teranews.com> Message-ID: In article , Andrew Koenig wrote: > David> def maker(): > David> return range(100) > > David> seems a little less contorted... > > Maybe so, but it behaves differently so direct comparisons aren't > particularly helpful: I considered mentioning iter(range(100)) instead but I couldn't think of an actual reason one would care about the difference. -- David Eppstein http://www.ics.uci.edu/~eppstein/ Univ. of California, Irvine, School of Information & Computer Science From ktilton at nyc.rr.com Sun Oct 19 18:30:48 2003 From: ktilton at nyc.rr.com (Kenny Tilton) Date: Sun, 19 Oct 2003 22:30:48 GMT Subject: Python from Wise Guy's Viewpoint In-Reply-To: <_8Ekb.7543$pT1.318@twister.nyc.rr.com> References: <_8Ekb.7543$pT1.318@twister.nyc.rr.com> Message-ID: Kenny Tilton wrote: > > > Joachim Durchholz wrote: > >> Oh, you're trolling for an inter-language flame fest... >> well, anyway: >> >>> 3. no multimethods (why? Guido did not know Lisp, so he did not know >>> about them) You now have to suffer from visitor patterns, etc. like >>> lowly Java monkeys. >> >> >> >> Multimethods suck. >> >> The longer answer: Multimethods have modularity issues > > > Lisp consistently errs on the side of more expressive power. The idea of > putting on a strait jacket while coding to protect us from ourselves > just seems batty. Similarly, a recent ex-C++ journal editor recently > wrote that test-driven development now gives him the code QA peace of > mind he once sought from strong static typing. An admitted former static > typing bigot, he finished by wondering aloud, "Will we all be coding in > Python ten years from now?" http://www.artima.com/weblogs/viewpost.jsp?thread=4639 -- http://tilton-technology.com What?! You are a newbie and you haven't answered my: http://alu.cliki.net/The%20Road%20to%20Lisp%20Survey From claird at lairds.com Fri Oct 17 08:33:40 2003 From: claird at lairds.com (Cameron Laird) Date: Fri, 17 Oct 2003 12:33:40 -0000 Subject: In need of c.l.p.discussion References: <3F8F0FD5.8386B56C@alcyone.com> Message-ID: In article , Bengt Richter wrote: . . . >It strikes me that something could be done to make filtering more effective. >Maybe adding a marker and/or a keyword line to particularly good posts. I.e., >those that explain something unusually well, or present something easy to miss >in the docs, or report bug status and demonstrate the bug. Etc. > >[OT] in the subject line helps a little. Likewise [ANN] etc. (Is there >an official >collection of these?) > >Maybe someone with too much time can come up with a clpy-code rating for >clpy posts, >analogous to geek-code. Just kidding. > >But when a thread winds up with a "keeper" maybe we could mark it >[keeper] some place? >Keeping in mind googlability. > >What's a good keyword list to choose from to classify posts? . . . Rather than answer any of your questions, I want to make it explicit and as clear as possible that, when you (or anyone else) spot(s) a particularly valuable post or thread, it is a VERY good thing to send a note to that effect to python-url at phaseit.net I assure you that that will help focus the attention of thousands of fellow Pythoneers on that specific item. also is pertinent in these discussions. -- Cameron Laird Business: http://www.Phaseit.net From mcfletch at rogers.com Tue Oct 28 19:18:37 2003 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Tue, 28 Oct 2003 19:18:37 -0500 Subject: Python debug libraries In-Reply-To: <73b00f0c.0310281458.324085e2@posting.google.com> References: <73b00f0c.0310281458.324085e2@posting.google.com> Message-ID: <3F9F075D.7010509@rogers.com> See my recent post... http://groups.google.ca/groups?q=debug+extension+win32+group:comp.lang.python&hl=en&lr=&ie=UTF-8&oe=UTF-8&selm=mailman.26.1065949224.2192.python-list%40python.org&rnum=2 (all one line). You probably don't want to debug *everything*, just your particular extension, and this recipe allows that fairly readily w/out requiring getting every single dependency built against debug Python (which can be a royal PITA). HTH, Mike Robert Ferrell wrote: >I'm trying to do some debugging of python extensions on Windows2K. MS >Visual Studio (.NET) says it can't find the debug version of the >python libraries. (The message is "python.exe does not contain any >debugging information".) I installed the binaries from the Windows >installer. How should I get the debug libraries? Or is that even >what I need? I'm kind of new to Windows, and Visual Studio in >particular, so maybe I'm way off base. > >thanks, >-robert > > _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From peter at engcorp.com Fri Oct 31 13:58:15 2003 From: peter at engcorp.com (Peter Hansen) Date: Fri, 31 Oct 2003 13:58:15 -0500 Subject: Boolean confusion References: Message-ID: <3FA2B0C7.CA6D4703@engcorp.com> Frantisek Fuka wrote: > > Can anyone please explain why these two give different results in Python > 2.3? > > >>> 'a' in 'abc' == 1 > False > >>> ('a' in 'abc') == 1 > True > > I know it's not a good idea to compare boolean with Integer but that's > not the answer to my question. Hmm.... >>> dis.dis(lambda : 'a' in 'abc' == 1) 1 0 LOAD_CONST 1 ('a') 3 LOAD_CONST 2 ('abc') 6 DUP_TOP 7 ROT_THREE 8 COMPARE_OP 6 (in) 11 JUMP_IF_FALSE 10 (to 24) 14 POP_TOP 15 LOAD_CONST 3 (1) 18 COMPARE_OP 2 (==) 21 JUMP_FORWARD 2 (to 26) >> 24 ROT_TWO 25 POP_TOP >> 26 RETURN_VALUE >>> dis.dis(lambda : ('a' in 'abc') == 1) 1 0 LOAD_CONST 1 ('a') 3 LOAD_CONST 2 ('abc') 6 COMPARE_OP 6 (in) 9 LOAD_CONST 3 (1) 12 COMPARE_OP 2 (==) 15 RETURN_VALUE Judging by the "odd" (unexpected) code in the first example, "A in B == C" is actually doing operator chaining, in a manner similar to "A < B < C". Since 'a' is in 'abc' but 'abc' is not equal to 1, the chained test fails. I can't comment further on the validity of such a thing, but there you have it. -Peter From joachim.durchholz at web.de Mon Oct 20 14:28:04 2003 From: joachim.durchholz at web.de (Joachim Durchholz) Date: Mon, 20 Oct 2003 20:28:04 +0200 Subject: Python from Wise Guy's Viewpoint In-Reply-To: <87ismjg7u9.fsf@thalassa.informatimago.com> References: <_8Ekb.7543$pT1.318@twister.nyc.rr.com> <3f9390d5$1@news.unimelb.edu.au> <87ismjg7u9.fsf@thalassa.informatimago.com> Message-ID: Pascal Bourguignon wrote: > The post at that url writes about the culture of the Ariane team, but > I would say that it's even a more fundamental problem of our culture > in general: we build brittle stuff with very little margin for error. > Granted, it would be costly to increase physical margin, Which is exactly why the margin is kept as small as possible. Occasionally, it will be /too/ small. Anybody seen a car model series, every one working perfectly from the first one? From what I read, every new model has its small quirks and "near-perfect" gotchas. The difference is just that you're not allowed to do that in expensive things like rockets (which is, among many other things, one of the reasons why space vehicles and aircraft are so d*mn expensive: if something goes wrong, you can't just drive them on the nearest parking lot and wait for maintenance and repair...) > but in this > case, adopting a point of view more like _robotics_ could help. Even > in case of hardware failure, there's no reason to shut down the mind; > just go on with what you have. As Steve wrote, letting a rocket carry on regardless isn't a good idea in the general case: it would be a major disaster if it made it to the next coast and crashed into the next town. Heck, it would be enough if the fuel tanks leaked, and the whole fuel rained down on a ship somewhere in the Atlantic - most rocket fuels are toxic. Regards, Jo From bokr at oz.net Mon Oct 13 22:46:48 2003 From: bokr at oz.net (Bengt Richter) Date: 14 Oct 2003 02:46:48 GMT Subject: User comments on python.org References: Message-ID: On Mon, 13 Oct 2003 13:07:25 -0500, "A.M. Kuchling" wrote: >[CC'ing to pydotorg-redesign, and setting followups there, too.] (somehow the email address got into the newsgroup slot for me, so I had to fix it) > >On Sat, 11 Oct 2003 19:19:41 -0500, > Ian Bicking wrote: >> I don't really know how the Python site is set up now, but could >> comments be included inline as an SSI? Like > >I don't think SSIs are currently enabled, but it wouldn't be hard to turn >them on. However, I have two worries about this: > >1) Fitting the comments into the page design -- a page with a lot of > comments would be really, really lengthy. > >2) What if people post obscenities or harmful material? > Showing comments by default would be embarrassing; if you have to > explicitly choose to view them, this is less worrying. > Python.org has a really good Google PageRank, I expect, making it > a good target for link spam, so this is something to worry about. > >The Wiki has mostly escaped such vandalism; presumably it's unobtrusive >enough that spammers haven't noticed it. > >> the page content and the barest of controls). I think it would be best >> done as a separate wiki, maybe with a namespace that fits the library >> documentation structure better. Or maybe both are possible. It would > >Perhaps. Wiki names can contain '/', so we can have annotations for every >single page on the site by just using the full path name. The question is >whether we need that level of support; perhaps the docs are the only place >where comments are valuable. I do think that comments on the reference >manual or the Distutils manuals would be useful. (Possibly PEPs, too?) > >I did a bit of experimenting with the separate page, adding JavaScript to >ht2html's output and adding an ugly 'view comment' link. If we're >interested in pursuing this, I'm willing to do the following: > >1) Make a set of experimental pages with comment links, so we can see > what they look like and how they work in practice. >2) If 1) looks worthwhile, then I'll make a new Wiki for user notes that has > minimal styling. > >What I'd really need is presentation suggestions: *how* to show the comment >link? Have a look at http://www.xml.com/axml/testaxml.htm for a way of associating commentary with (it says, at least) unchanged original matter (in this case the XML spec). It's pretty easy on the eyes. I don't know the implementation, but I think that separation of pristine original from comment material would be good. The above site probably has the advantage of heavy xml tagging in the original that the commentary database can used for retrieving associated commentary, I would guess. Since full comment generation for dynamic javascript-controlled interaction is somewhat computer-costly, caching results of generating responses to comments would make sense, I think, and I don't think generating it should be the default. If the python.org server is able to insert an optional footer chunk just before the when so configured to do it for a directory or a file (I don't know if Apache can do that, since I just made it up, but ISTM it would be a useful option ;-), then that footer could contain a link for viewing commentary. The link would go to a comment-server URL, e.g., commentary.python.org/coments.cgi, The cgi program will see HTTP_REFERER from the page the user clicked the comments link on, and it can either get a copy via HTTP, or look it up on the local hard disk if it's local. The URL can also be used as a key into a database of commentary, where also commenter-accounts could be maintained to keep out spammers. With the original page plus a database of commentary, the problem becomes building a new image of the original with unobtrusive commentary navigation. With javascript you could do floating hint text from commentary title lines associated with paragraphs or other elements you were mousing over. Clicking might put the commentary in a separate popup window. Right clicking on a previous comment might mean pop a form to add your 2 cents. Right clicking on the main page where no comment hint is being displayed would pop up the same but with an option to give it a title, since it's new commentary. All of this is pretty much paragraph oriented. Indexing locations, which have to be w.r.t. unmarked text in the original can do some kind of soft hash of

sections in the original as indices instead of using line numbers, so the data base can have the hashes as keys, and not get thrown too much by updates in the original. Actual anchor targets and tag ids can be used too I suppose (I'm just thinking out loud ;-) Anyway, you get the idea. If it makes you rich, I want a piece ;-) my 2 cents ;-) Regards, Bengt Richter From nav+posts at bandersnatch.org Tue Oct 28 13:28:17 2003 From: nav+posts at bandersnatch.org (Nick Vargish) Date: 28 Oct 2003 13:28:17 -0500 Subject: OT: The Straight Dope References: <3F9C3D01.9C77374E@comcast.net> <45f171-k13.ln1@beastie.ix.netcom.com> Message-ID: Dennis Lee Bieber writes: > Though, if I may drag in some decade old history, tcsh was quite > comfortable to someone used to the Amiga's CLI -- no experience with > actual scripting, but at the interactive level when I had a shell > account with Netcom, using tcsh minimized confusion between the two > systems. Right, tcsh wasn't bad as an interactive shell; until zsh showed up, it was probably the best choice since it had a number of features that sh lacked (filename completion being the big one, but the history facilities were handy too). The papers cited by other posters, which I was too lazy to google for, are mostly arguments against programming in (t)csh. It's nice to be able to write off-the-cuff scripts on the command line in the same language you write your system admin scripts in. That's why zsh and bash are so great -- all the interactive features of tcsh (and more!) in a regular and sane Bourne syntax. Nick -- # sigmask || 0.2 || 20030107 || public domain || feed this to a python print reduce(lambda x,y:x+chr(ord(y)-1),' Ojdl!Wbshjti!=obwAcboefstobudi/psh?') From DennisR at dair.com Sat Oct 25 20:07:29 2003 From: DennisR at dair.com (Dennis Reinhardt) Date: Sun, 26 Oct 2003 00:07:29 GMT Subject: Regular expressions References: Message-ID: <5fEmb.3338$AF2.152@newssvr14.news.prodigy.com> > re.search("[yipee]*", line): > > This will treat yipee as a string correct? I want it to treat yipee as a > variable and perform the different combinations on whatever is inside the > variable. You don't want square bracket. You want parenthesis. But this is not the only problem. Simply replacing the square brackets with parenthesis does not treat yipee as a variable. The "%s" % variable idiom will do this Also, it is not clear why the sample line ends with a colon. I took it off The "*" will match on no occurrences and I suspect you want to match on one or more. I replaced "*" with "+". I think you want: re.search("(%s)+" % yipee, line) -- Dennis Reinhardt DennisR at dair.com http://www.spamai.com?ng_python From tim.golden at viacom-outdoor.co.uk Mon Oct 20 06:45:32 2003 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Mon, 20 Oct 2003 11:45:32 +0100 Subject: Installation of Python 2.3 on Windows 95 Message-ID: > -----Original Message----- > From: dewatf at nothotmail.com [mailto:dewatf at nothotmail.com] > Sent: 20 October 2003 11:22 > To: python-list at python.org > Subject: Re: Installation of Python 2.3 on Windows 95 > > > On 19 Oct 2003 17:54:10 -0700, donorr at fcc-online.org (Don) wrote: > > >We have attempted several times to install Python 2.3 on a Windows 95 > >system. Each time, at the end of the install the following error is > >displayed: > > > >Error in installer script. > >Traceback (most recent call last): > > File "C:\WINDOWS\TEMP\FinishInstall.py", line 101, ApplyEntryPoint > > apply(ep,args) > > File "C:\WINDOWS\TEMP\FinishInstall.py", line 82, in > >DoCompileAllAndRegisterCOM FindDuplicates(mod,dir) > > File "C:\WINDOWS\TEMP\FinishInstall.py", line 143, in > FindDuplicates > > import win32api > >ImportError:DLL load failed: A device attached to the system is not > >functioning. > > > >On attempting to run PythonWin, we get the following error: > > > >The application cannot locate win32ui.pyd (or Python)(1157) > >One of the library files needed to run this application cannot be > >located. > > > >I have uninstalled Python, rebooted, reinstalled and the same thing > >keeps happening. > > > >I have searched and searched for these errors and cannot find the > >problem. > > > >Thank you in advance. > > I can't help you but had the same problem. It is with the PythonWin > install not the python 2.3 install. > > dewatf. Usually seems to happen if the user logged on when the install is done is not an Administrator. Don't know why, doesn't give an error or anything, just does a half-hearted install. If you haven't already, log on as an Administrator and rerun the install. 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 exarkun at intarweb.us Mon Oct 6 10:15:22 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Mon, 6 Oct 2003 10:15:22 -0400 Subject: another fp problem In-Reply-To: <1065443222.3f815f966419d@anchor.net.au> References: <1065443222.3f815f966419d@anchor.net.au> Message-ID: <20031006141522.GB12361@intarweb.us> On Mon, Oct 06, 2003 at 10:27:02PM +1000, Michael Hall wrote: > Hi All: > > I'm a relative newbie to Python, apart from some CGI and shell scripting type > stuff. Anyway, I'm having some problems doing maths in Python 2.2.2 on RH9. > > I'm wondering what is the best way or numerical data type to do simple monetary > calculations in Python? I only need to work with decimal numbers to two decimal > points. Are floating point numbers the only option? They're giving me hell! > > If floating point numbers are the only option, how can I round off a number to > two decimal points? Converting to an integer is not working ... the cents disappear. > > Leaving valuse as floating point is also not working ... I end up with figures > like $35.33000000018. > > BTW, I'm putting values in and out of a MySQL database (DECIMAL data type) using > MySQLdb. The values giving me the most grief have been pulled out of the > database, where they look just fine. > > Any advice graetly appreciated. Multiply everything by a hundred, use integers which correspond to numbers of cents. If this simplistic approach doesn't cover all your needs, look into using a fixed point type (there are none in the stdlib, but modules which implement them are available -- check google). Jp From mwh at python.net Mon Oct 6 07:55:20 2003 From: mwh at python.net (Michael Hudson) Date: Mon, 6 Oct 2003 11:55:20 GMT Subject: python 2.3.1 issues DeprecationWarning for FCNTL when importing tempfile References: <7h3u16qsf70.fsf@pc150.maths.bris.ac.uk> <7jhfb.6764$op2.758773@news20.bellglobal.com> <7h3d6des2js.fsf@pc150.maths.bris.ac.uk> Message-ID: <7h3pthar38l.fsf@pc150.maths.bris.ac.uk> Pierre Rouleau writes: > BTW, I solved the problem by deleting the fcntl.pyc. See my other > post below. Actaully, I read this thread completely out of order, but glad to see you got it sorted. Definitely a good mystery! Cheers, mwh -- I have a feeling that any simple problem can be made arbitrarily difficult by imposing a suitably heavy administrative process around the development. -- Joe Armstrong, comp.lang.functional From mal at lemburg.com Thu Oct 9 12:59:50 2003 From: mal at lemburg.com (M.-A. Lemburg) Date: Thu, 09 Oct 2003 18:59:50 +0200 Subject: py2exe & pyxml In-Reply-To: References: <3f7c18cd$0$13656$afc38c87@news.optusnet.com.au> Message-ID: <3F859406.6070701@lemburg.com> Steven Bell wrote: >>I've no idea what Martin was referring to when he said RTFM, because I could >>find nothing about this. (Then again, perhaps I'm misunderstanding what he >>means by RTFM?) > > RTFM is tech jargon for "read the f**king manual". In the Python world this usually reads as "Read The Felicitous Manual" :-) -- Marc-Andre Lemburg eGenix.com Professional Python Software directly from the Source (#1, Oct 09 2003) >>> Python/Zope Products & Consulting ... http://www.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ ::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,FreeBSD for free ! :::: From jjl at pobox.com Wed Oct 8 18:25:56 2003 From: jjl at pobox.com (John J. Lee) Date: 08 Oct 2003 23:25:56 +0100 Subject: Book Recommendation References: Message-ID: <87oewrmknf.fsf@pobox.com> Anthony writes: > Hello I'm currently trying to read Core Python Programming, but by the > looks of it im never going to get done the book is about 860 pages long > real intimidating, but im guess im going to have to stick in there. have > any of you ever read it? is it a good book? if not what do you suggest i > read. Please help me i'm eager to learn :) I'd say read the stuff on language issues, skim the stuff on libraries &c. (assuming that's what fills all those pages?), then ditch the book and just write some code. You just need to have read enough to have a good mental map and some basic knowledge -- at that point, reading without doing becomes an inefficient way of learning. Then come back to this newsgroup and c.l.py.announce, read other people's code, read the rest of the book and articles on the web, experiment with libraries, etc. That's what I did when learning Python (in sharp contrast to C++, which scares me enough that I read several books before writing a line of code...). John From my-first-name.my-last-name at jpl.nasa.gov Mon Oct 6 14:53:55 2003 From: my-first-name.my-last-name at jpl.nasa.gov (Erann Gat) Date: Mon, 06 Oct 2003 11:53:55 -0700 Subject: Python syntax in Lisp and Scheme References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> <92c59a2c.0310031345.57d20631@posting.google.com> Message-ID: In article , aleax at aleax.it wrote: > Erann Gat wrote: > > > In article , aleax at aleax.it wrote: > > > >> Erann Gat wrote: > >> ... > >> > (That's why the xrange hack was invented.) > >> > >> Almost right, except that xrange is a hack. > > > > I presume you meant to say that xrange is *not* a hack. Well, hackiness > > Please don't put words in my mouth, thanks. xrange _IS_ a hack, Perhaps English is not your first langauge? When one says "Almost right, except..." the implication is that you are disagreeing with something. But you didn't disagree, you parroted back exactly what I said, making it not unreasonable to assume that you inadvertantly left out the word "not". > it was introduced in Python back in the dark ages before Python had the > iterator protocol. But it's always the dark ages. Any non-extensible langauge is going to be missing some features, but that is usually not apparent until later. The difference between Python and Lisp is that when a user identifies a missing feature in Lisp all they have to do is write a macro to implement it, whereas in Python they have no choice but to wait for the next version to come along. > Now, clearly, _uniformity_ in the code will be to the advantage > of the team and of the project it develops. Yes. But non-extensible languages like Python only enforce the appearance of uniformity, they do not and cannot enforce true stylistic uniformity. As a result there are two kinds of code, the kind that fits naturally into the style of the language, and the kind that doesn't and has to be shoehorned in. Of course, superficially both kinds of code sort of look the same. But underneath code of the second sort becomes a horrible mess. > Here is the crux of our disagreement. If you believe everybody can > become a good language designer, I think the onus is on you to explain > why most languages are not designed well. Because most langauges are designed by people who have had very little practice designing langauges. And they've had very little practice designing langauges because designing languages is perceived as a hard thing to do. And if you try to do it without the right tools it is in fact a hard thing to do. If you try to do it with the right tool (Lisp) then it's very easy, you can do lots of iterations in a short period of time, and gain a lot more experience about what works and what doesn't. That's why people who use Lisp tend to be good language designers, and people who don't tend not to be. It's also why every language feature ever invented what invented in Lisp first. > If I thought Python's design was badly done, and a bad fit for my > problem domain, then, obviously, I would not have chosen Python (I > hardly lack vast experience in many other programming languages, > after all). Isn't this totally obvious? No, it's not. You have taken a strong position against macros, which means that if you ever encounter a problem domain that is not a good fit for any language that you know then you have a problem. I don't know how you'd go about solving that problem, but I think that a likely outcome is that you'd try to shoehorn it in to some language that you know (and maybe not even realize that that is what you are doing). > Therefore, clearly, your assertion that > (to adopt Python) one has "to give up all hope" of such goals is not > at all well-founded. There is nothing intrinsic to Python that can > justify it. Actually, there is. Python's dynamicism is so extreme that efficient native code compilation is impossible unless you change the semantics of the language. > nuclear warheads An inappropriate metaphor. > >> while in Python, where iterators are "the other way around" (they > >> get relevant items out rather than taking a code block in), it would be: > >> > >> for leaf in doleaves(tree): > >> ... > > > > Forcing you to either waste a lot of memory or write some very awkward > > code. > > I _BEG_ your pardon...? Oh, right, I forgot they added the "yield" thingy. But Python didn't always have yield, and before it had yield you were stuck. I could come up with another example that can't be done with yield, but your response will undoubtedly be, "Oh, that can be handled by feature FOO which is going to be in Python 3.0" or some such thing. The point is, a Python programmer is dependent on Guido for these features. Lisp programmer's aren't dependent on anyone. >>> class criticalsection(object): All this does is demonstrate how destructors can be used to emulate unwind-protect. If you use this to implement crtical-section in the obvious way you will find that your critical sections do not nest properly. > I have no idea of how with-maintained-condition would find and > examine each of the steps in the body in this example; isn't > the general issue quite equivalent to the halting problem, and > thus presumably insoluble? Only if the conditions you write are unconstrained. But there is no reason for them to be unconstrained. The WITH-MAINTAINED-CONDITION macro would presumably generate a compile-time error if you asked it to maintain a condition that it didn't know how to handle. > If your claim is that macros are only worthwhile for "artificial > intelligence" code that is able, by perusing other code, to infer > (and perhaps critique?) the physical world model it is trying to > control, and modify the other code accordingly, I will not dispute > that claim. s/only/also/ > Ah, must be a mutation of the whitespace-eating nanovirus No, auto-indent in emacs Python mode will generate indentation bugs. > Whoa there. I detect in this tirade a crucial unspoken assumption: that > One Language is necessarily going to be all I ever learn, all I ever use, > for "any programming domain I might ever choose to explore". No, the issue is general. If you concede that for any non-extensible langauge there are things for which that language is not well suited, then for any finite number of such languages there will be things for which none of those languages are well suited. At that point you only have two choices: use an inappropriate language, or roll your own. And if you choose to roll your own the easiest way to do that is to start with Lisp. Of course, the same reasoning that leads you to conclude that Lisp is good for *something* also leads you inexorably to the conclusion that Lisp is good for *anything*, since its extensibility extends (pardon the pun) to everything, not just features that happen not to exist in other languages at the time. > There being no open-source, generally useful operating system kernels in > any language but C That is indeed unfortunate. Perhaps some day the Lisp world will produce its own Linus Torvalds. > I think I have a reasonably deep understanding of "what programming is" My last remarks weren't addressed to you in particular, but to anyone who might be reading this dialog. If you want (meaning if one wants) to gain a deep understanding of how computers work, Lisp provides a better path IMO. (And Eric Raymond thinks so too.) > I think macros (Lisp ones in particular) are a huge win in situations > in which the ability to enrich / improve / change the language has more > advantages than disadvantages. So, I think they would be a great fit > for languages which target just such situations, such as, definitely, > Perl, and perhaps also Ruby; and a net loss for languages which rely on > simplicity and uniformity, such as, definitely, Python. That's not an unreasonable position. E. From $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk Thu Oct 2 09:59:55 2003 From: $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk (Stephen Horne) Date: Thu, 02 Oct 2003 14:59:55 +0100 Subject: "for" with "else"? References: <2c9knv86m1il4ajng85655dm7u5j5b992i@4ax.com> <2Ureb.10786$NX3.1457@newsread3.news.pas.earthlink.net> Message-ID: On Thu, 02 Oct 2003 09:26:43 GMT, Alex Martelli wrote: >They might, *EXCEPT* that "passing a callable" is out of fashion, and >out of favour, in the BDFL's current opinion -- and for good reasons, >too, although they MIGHT change in the future. I agree mostly. At present, first-class functions are very powerful tools, but they certainly have some drawbacks. The trouble, as you said, is the syntax. At present, the most natural syntax happens in list comprehensions - where the language grammar isolates the 'code block'. It's hard to think of a good syntax which (1) doesn't recreate lambda to explicitly mark out the 'code block', and (2) can exist within Pythons existing dynamic model. :-( -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From j-anthony at rcn.com Thu Oct 23 18:03:37 2003 From: j-anthony at rcn.com (Jon S. Anthony) Date: 23 Oct 2003 18:03:37 -0400 Subject: Why don't people like lisp? References: <8Nnlb.619$I04.380@newsread4.news.pas.earthlink.net> Message-ID: Joe Marshall writes: > Let's take on something more complicated. A lot more complicated. > > Suppose I am solving problems that are best expressed > non-deterministically, and I need a domain language that has the > following non-deterministic constructs: >... > This is a tricky problem, but one approach in Lisp is to make > ALL-VALUES and EITHER be rather complicated macros. This is the well known standard approach. >... > How would one approach this in Python? Give up and call out to a Prolog interpreter. /Jon From peter at engcorp.com Thu Oct 9 07:17:06 2003 From: peter at engcorp.com (Peter Hansen) Date: Thu, 09 Oct 2003 07:17:06 -0400 Subject: Writing Hardware Simulators? References: <33803989.0310090135.20cfe08@posting.google.com> Message-ID: <3F8543B2.673F1257@engcorp.com> Miki Tebeka wrote: > > I'll be writing a hardware simulator for one of our CPU's shortly. > Any advices/links/... on the subject? No links I'm aware of, although you can easily find an HC11 simulator out there somewhere. Kaval has written but not yet released (okay, not even completed) an HC12 simulator (independent of the above effort). Performance is roughly 1/60 of the actual CPU speed running at the nominal clock speed (16MHz), when the code is run on the simulator on a PC of about 600MHz. If performance is not your greatest concern (which presumably it isn't or you wouldn't consider Python in the first place :-), you shouldn't have much difficulty... Advice? Write *lots* of tests. In fact, write dozens (literally!) of test cases for each opcode. Make sure you have a clear idea of your priorities and don't try to implement more than you really need, to begin with. I didn't need anything involving simulating the actual instruction cycle times (i.e. simulating time was not important yet), and I haven't gotten to the point where I care much about simulating hardware peripherals such as the serial port. I'm just doing the basic CPU and opcodes, and obviously memory. As a result of this narrow focus, it took only a few weeks to produce an effective, usable simulator, although I still have a few opcodes to complete. (Even the opcodes I'm implementing only as I have code that requires them. I suggest implementing an UnimplementedOpcode exception for *all* opcodes, then running your code. Only implement the actual opcodes as you need them...) -Peter From missive at frontiernet.net Wed Oct 1 16:23:01 2003 From: missive at frontiernet.net (Lee Harr) Date: Wed, 01 Oct 2003 20:23:01 GMT Subject: Extracting text from .png images References: Message-ID: In article , Henrik Berg Nielsen wrote: > Hi group! > > I need to extract some text (well numbers actually) from a bunch of > similarly looking .png images. After extraction the numbers will be fed to a > Python script for further processing. Any good ideas on how to go about with > this? I have no idea whatsoever about how to extract the numbers out of the > images... > http://www.claraocr.org/ From daniel at dittmar.net Tue Oct 28 15:04:24 2003 From: daniel at dittmar.net (Daniel Dittmar) Date: Tue, 28 Oct 2003 21:04:24 +0100 Subject: PEP 289: Generator Expressions (please comment) In-Reply-To: <7Rtnb.366605$R32.12088099@news2.tin.it> References: <5d83790c.0310231158.65595858@posting.google.com> <2I9nb.360782$R32.11877162@news2.tin.it> <7Rtnb.366605$R32.12088099@news2.tin.it> Message-ID: Alex Martelli wrote: > reasonable to form the working hypothesis that you LIKE perl syntax, > rather than being engaged in sarcasm against your own proposals (which > is a form of split personality one rarely comes upon). I don't like list comprehension when compared to Smalltalk code blocks, so I was really looking for a way to keep any additional 'comprehension' variants limited to one syntax rule. But it seems as if the current trend in Python is toward succinctness. To paraphrase one poster: 'It is documented, therefor it is explicit'. I try to keep quiet, enjoy the parts of Python I like and wait for the tide to turn. Daniel From Dick.Zantow at lexisnexis.com Tue Oct 14 10:27:55 2003 From: Dick.Zantow at lexisnexis.com (rzed) Date: Tue, 14 Oct 2003 10:27:55 -0400 Subject: Speaking Python References: Message-ID: Sean Ross wrote: > "David Mertz" wrote in message > news:mailman.72.1066076254.2192.python-list at python.org... >> So quick test, how do you say: >> >> def range_sum(N): >> if N < 0: >> return None >> elif N == 1: >> return 1 >> else: >> tot = 0 >> for n in range(1,N+1): >> tot += n >> return tot > > def range underscore sum open bracket n close bracket colon new > line indent if n less than zero colon newline indent > return none newline dedent > elif n equals equals 1 colon newline indent > return 1 newline dedent > else colon newline indent > tot equal zero newline > for n in range open bracket 1 comma n plus 1 close bracket colon > newline indent > tot plus equal n newline dedent > return tot newline dedent > dedent > > (this assumes that the user is aware that if no indent or dedent > message is given, the current level of indentation should be > maintained). This seems pretty good to me, although I'd let 'colon' imply a subsequent indent. Line breaks would be indicated by pauses and pitch changes, which I think would be true in the above as well. def range underscore sum open paren n close paren colon if n less than zero colon return none dedent elif n equal-equal 1 colon return 1 dedent else colon tot equal zero for n in range open paren 1 comma n plus 1 close paren colon tot plus equals n dedent return tot dedent dedent I would probably use "paren" to mean "open paren" as well, although explicit might be better there. I once worked as a proofreader, where one task was to record written material in a fairly stylized manner similar to this. Punctuation was explicitly pronounced, as was space where it was unusual. The listeners could generally make the best sense of the minimum information; too much would slow reading down to the point that comprehension suffered. Conventions (in reading) that were usually honored tended to work better than explicit statement of what was expected. In code like: if n < 3: break # don't worry about this stuff The colon convention above would have to be overridden explicitly, so it would come out more like Sean's reading. if n less than three colon no-newline break [ and perhaps, "comment don't worry about this stuff" ] -- rzed From pclinch at internet-glue.co.uk Thu Oct 23 15:00:11 2003 From: pclinch at internet-glue.co.uk (Paul Clinch) Date: 23 Oct 2003 12:00:11 -0700 Subject: Documentation using PyDoc References: <3F96DA19.7070104@sympatico.ca> Message-ID: <8cf2994e.0310231100.1c070982@posting.google.com> I am not familiar with the numarray package, but you could tweak the pydoc code. in fact the pydoc file contains; class HTMLDoc(Doc): which contains a function; def classlink(self, object, modname): some code ... return '%s' % ( module.__name__, name, classname(object, modname)) so "numarray.html#classname" is really what is wanted. I guess insertion of code something like; if module.__name__ == 'numarray': return '%s' % name, classname(object, modname) else ... or something else suitable. Good luck, Paul Clinch From aleax at aleax.it Sat Oct 4 15:49:50 2003 From: aleax at aleax.it (Alex Martelli) Date: Sat, 04 Oct 2003 19:49:50 GMT Subject: About that 'yield' word References: <954cdb5b6f1176116641306583c684c3@news.teranews.com> Message-ID: Tobiah wrote: > > def maker(): > for i in range(100): > yield i > > > foo:4: Warning: 'yield' will become a reserved keyword in the future > File "foo", line 4 > yield i > ^ > SyntaxError: invalid syntax > > Python 2.2.2 > > > ??? You seem to have omitted the necessary statement at the start of your module (in Python 2.2): from __future__ import generators Alternatively, upgrade to 2.3, and you won't need that statement any more. Alex From jmdeschamps at cvm.qc.ca Fri Oct 31 12:42:38 2003 From: jmdeschamps at cvm.qc.ca (jmdeschamps) Date: 31 Oct 2003 09:42:38 -0800 Subject: programming languages (etc) "web popularity" fun References: Message-ID: <3d06fae9.0310310942.65b709b@posting.google.com> Alex Martelli wrote in message news:... > (You need Mark Pilgrim's pygoogle, see > http://diveintomark.org/projects/pygoogle/ , and a personal license to the ... > Alex My previous post refers to Fredrik (Lundh), not Fredrick - apologies! Jean-Marc From ktilton at nyc.rr.com Sat Oct 18 12:25:42 2003 From: ktilton at nyc.rr.com (Kenny Tilton) Date: Sat, 18 Oct 2003 16:25:42 GMT Subject: Why don't people like lisp? In-Reply-To: References: Message-ID: dan wrote: > Google ate my long post, so I'll make it simple. > > Lisp failed (yes, it did) because of the parentheses. Normal people > can't parse 13 close-parens easily. Aaaaannnnnndddd they're off! (for another four hundred messages) Nobody looks at or counts parentheses, except in languages other than Lisp. We have editors that not only help keep them straight, but also let us move chunks of code in the meaningful semantic chunks defined by parentheses. So editing with parentheses is actually the best possible way to edit code. > Functional notation I do not think you know much about Lisp. Lisp does imperative as well as functional. It is a multi-paradigm language. I prefer functional, because it exposes the structure of my algorithm. YMMD. > is non-intuitive and hard to read. All code is non-intuitive and hard to read. > The world is moving in the direction of languages like Python, And Python is moving in the direction of Lisp, tho I do not know if Python has abandoned its original modest intentions and now wants to go all the way and be a full-blown HLL. Already seems perty close, just not sure if the Mission Statement has been changed. > fit naturally with how we speak and write. You only /think/ you speak and write that way because you have written step-wise code for so long. If you are a real old fart this started with Fortran and Basic, maybe Assembler. From the above it is clear you know nothing about Lisp, so of course it seems strange to you. But don't you think a language an order of magnitude better than anything else will have to be different enough to seem strange? The good news is how fast you will adjust and your old language seems strange. kenny -- http://tilton-technology.com What?! You are a newbie and you haven't answered my: http://alu.cliki.net/The%20Road%20to%20Lisp%20Survey From matt at pollenation.net Sat Oct 25 15:37:19 2003 From: matt at pollenation.net (Matt Goodall) Date: Sat, 25 Oct 2003 20:37:19 +0100 Subject: 2.3 on Debian Woody: doable? In-Reply-To: <0r4lpvos52hovek30hola8i184vmnagvqh@4ax.com> References: <0r4lpvos52hovek30hola8i184vmnagvqh@4ax.com> Message-ID: <3F9AD0EF.4010809@pollenation.net> Rene Pijlman wrote: >There doesn't seem to be an apt package for Python 2.3 on Debian Woody. > >Should I expect unusual difficulties or unsolvable problems when building >and installing 2.3 on Woody from the source distribution of Python? > >E.g. things like dependencies on other libraries that are not available on >Woody? > > > I know it's not really Woody but if you feel brave then Debian testing is fantastic for Python. To tempt you, here's the list of readily available Python packages: http://packages.debian.org/testing/python/ Just in case you don't already know ... it's relatively easy to have a basic Debian stable system with some packages (i.e. Python) upgraded to testing or even unstable. Read about Debian apt pinning for more information. Cheers, Matt -- Matt Goodall, Pollenation Internet Ltd w: http://www.pollenation.net e: matt at pollenation.net From bjorn.pettersen at comcast.net Fri Oct 24 06:40:51 2003 From: bjorn.pettersen at comcast.net (Bjorn Pettersen) Date: Fri, 24 Oct 2003 05:40:51 -0500 Subject: Why don't people like lisp? References: <3f9302d7.170372828@news.eircom.net> <3f96b046$0$556$b45e6eb0@senator-bedfellow.mit.edu> <20031022234546.GS1454@mapcar.org> <3f97eb1f$0$573$b45e6eb0@senator-bedfellow.mit.edu> <5627c6fa.0310230919.d2eb49a@posting.google.com> <3f9823b7$0$565$b45e6eb0@senator-bedfellow.mit.edu> <864qxz2if5.fsf@raw.grenland.fast.no> <86znfr0yhl.fsf@raw.grenland.fast.no> Message-ID: Raymond Wiker wrote in news:86znfr0yhl.fsf at raw.grenland.fast.no: > Bjorn Pettersen writes: > >> (c) why are open file objects special (are you saying objects with no >> internal references are less likely to be reachable from a cycle, >> or that there is something intrinsically special about (open?) >> files)? > > I cannot think of any scenarios where open files would be > involved in a cycle, that's all. That doesn't mean that it's > impossible. Ok. Btw., creating such a cycle is easy, a = [open('foo')] b = [a] a.append(b) (i.e. any file that's reachable from a cycle). IIRC, A commonly used 'markup' library up until recently kept open file handles for all inline images as part of the internal object state -- although I'd perhaps call that more of a bug than a scenario? -- bjorn From raffaelcavallaro at junk.mail.me.not.mac.com Sun Oct 12 21:26:51 2003 From: raffaelcavallaro at junk.mail.me.not.mac.com (Raffael Cavallaro) Date: Mon, 13 Oct 2003 01:26:51 GMT Subject: Python syntax in Lisp and Scheme References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> <%hihb.4368$dn6.2921@newsread4.news.pas.earthlink.net> Message-ID: In article , Pascal Costanza wrote: > Many programming languages require you to build a model upfront, on > paper or at least in your head, and then write it down as source code. > This is especially one of the downsides of OOP - you need to build a > class hierarchy very early on without actually knowing if it is going to > work in the long run. This parallels Paul Graham's critique of the whole idea of program "specifications." To paraphrase Graham,for any non-trivial software, there is no such thing as a specification. For a specification to be precise enough that programmers can convert it directly into code, it must already be a working program! What specifications are in reality is a direction in which programmers must explore, finding in the process what doesn't work and what does, and how, precisely, to implement that. Once you've realized that there is really no such thing as the waterfall method, it follows inevitably that you'll prefer bottom up program development by exploratory methods. Once you realize that programs are discovered, not constructed from a blueprint, you'll inevitably prefer a language that gives you freedom of movement in all directions, a language that makes it difficult to paint yourself into a corner. From gat at jpl.nasa.gov Mon Oct 13 17:26:53 2003 From: gat at jpl.nasa.gov (Erann Gat) Date: Mon, 13 Oct 2003 14:26:53 -0700 Subject: Python syntax in Lisp and Scheme References: Message-ID: In article , aleax at aleax.it wrote: > > Not only did Erann refuse to reciprocate Alex Martelli's ad hominem > > He earlier posted my assertions were "mind-boggling" No, I didn't, as a quick Google search will verify. (Notwithstanding, I don't consider "mind-boggling" to be a particularly pejorative term.) > , then, without any apology whatsoever, that he found them reasonable. I'm pretty sure I didn't do that either, because I don't. > So it's not > a matter of E.G. "reciprocating attacks", but, rather, INITIATING > them (and weaving and ducking to admit any responsibility whatsoever). Actually it appears to be a matter of you making things up out of whole cloth (not uncommon on Usenet I'm afraid). E. From frithiof.jensen at removethis.ted.ericsson.dk Fri Oct 24 07:52:35 2003 From: frithiof.jensen at removethis.ted.ericsson.dk (Frithiof Andreas Jensen) Date: Fri, 24 Oct 2003 13:52:35 +0200 Subject: Design Question: GUI+Threads. References: <3f97ee4a$0$573$b45e6eb0@senator-bedfellow.mit.edu> Message-ID: Thaks for the reply, "Brian Kelley" wrote in message news:3f97ee4a$0$573$b45e6eb0 at senator-bedfellow.mit.edu... > Syver Enstad wrote: > > You might make your life easier by having the controller and the view be > on the main thread and dispatch a new model to the work thread. Hmm. I think that makes sense, since it is the GUI that "demands" attention - I was doing sort-of the other way round by having a thread dispatching messages to models AND the GUI thread.... > Usually you can wrap model events into gui events and let the gui's > mainloop sort them out and dispatch them to the controllers callbacks. So, To make sure that I understand correctly: I will have one Controller per Worker; the Controller interacts with the GUI and it is the Controller that "understands" that the Worker is running in a separate thread and maps GUI/Worker events across the thread boundary by some means - I was planning to use of a Dispatcher/Mailbox System: The worker thread(S) blocks on an input queue until a message is in that queue - then the worker thread process the message and places a result in an output queue. The results in the output queue(s) of each worker are read by the main thread and placed in the input queues of other workers or in the GUI.....most of the time a worker will sleep, waiting for work. The input and output queues would be owned by the workers, the "distribution lists" i.e. which event goes where would be owned by a "Dispatcher" running in the main thread . While this is fine for Data, setting parameters etc. is clumsy: One needs to setup a filter to sort parameter messages from the data and do special processing - i would rather keep only data in the message loop. > In python it is thread safe to set variables across the thread boundary, > the model will have to check for these variables changing though. ...I will need locking in the models setXyz() methods so that I do not stomp on some data that the worker thread is using? > What gui framework are you using? wxPython - in the hope that SciPy eventually will do a Python 2.2.3 release, so that by the time I need it, I can get my hands on all those neat Plotting, Numeric and Stats tools waiting to be liberated ;-) From peter at engcorp.com Wed Oct 1 13:22:33 2003 From: peter at engcorp.com (Peter Hansen) Date: Wed, 01 Oct 2003 13:22:33 -0400 Subject: [ANN] pylint-0.2 References: <3F782D20.5BB43A1F@engcorp.com> <1i0eb.275$t44.11623@nnrp1.ozemail.com.au> Message-ID: <3F7B0D59.3C1A9864@engcorp.com> Peter Milliken wrote: > > No, I caught all of the dependencies that are required (common libraries and > optik - I think that is all that is required). I installed both of them > before attempting to run pylint and still received that error. Perhaps the > install is order dependent i.e. I installed pylint, then the "common > libraries" then the optik package. > > Does Pylint work for you? Sorry, I was jumping to conclusions. I got the same message you did, after a pylint-only install, so then I visited the web site and saw the notes about common and posted my response. Didn't actually try it out yet. Thanks to Sylvain for posting the fix that resolves this. (Assuming it does... anyone try it yet? ;-) -Peter From SBrunning at trisystems.co.uk Wed Oct 8 11:13:24 2003 From: SBrunning at trisystems.co.uk (SBrunning at trisystems.co.uk) Date: Wed, 8 Oct 2003 16:13:24 +0100 Subject: looping through a list of lists. Message-ID: <31575A892FF6D1118F5800600846864D014B2A5C@intrepid> > From: saoirse_79 [SMTP:saoirse_79 at yahoo.com] > I have a list of lists as follows: > [['-', '-', '-', '-', '-', '-', '-', 'K', 'S', 'A', 'K'], > ['-', '-', '-', '-', 'L', 'Q', 'Q', 'T', 'N', 'S', 'E'], > ['T', 'L', 'E', 'E', 'L', 'M', 'K', 'L', 'S', 'P', 'E']] > I want to be able to read each character and compare it with all > characters at the same positon in all sublists. Is this possible. > I have tried a few different methods but nothing seems to allow me to > compare the sublists character by character. 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. >>> spam = [['-', '-', '-', '-', '-', '-', '-', 'K', 'S', 'A', 'K'],['-', '-', '-', '-', 'L', 'Q', 'Q', 'T', 'N', 'S', 'E'], ['T', 'L', 'E', 'E', 'L', 'M', 'K', 'L', 'S', 'P', 'E']] >>> for eggs, chips, beans in zip(*spam): ... print eggs, chips, beans ... - - T - - L - - E - - E - L L - Q M - Q K K T L S N S A S P K E E HTH... Cheers, Simon Brunning, 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 costanza at web.de Mon Oct 27 20:46:54 2003 From: costanza at web.de (Pascal Costanza) Date: Tue, 28 Oct 2003 02:46:54 +0100 Subject: Python from Wise Guy's Viewpoint In-Reply-To: References: <6dnq61-kl.ln1@ID-7776.user.dfncis.de> <87oew33h8t.fsf@sidious.geddis.org> <3F9D5D21.2060408@ps.uni-sb.de> <20031027184024.GO1454@mapcar.org> Message-ID: Marcin 'Qrczak' Kowalczyk wrote: > On Mon, 27 Oct 2003 13:40:24 -0500, Matthew Danish wrote: > > >>Something that annoys me about many statically-typed languages is the >>insistence that arithmetic operations should return the same type as the >>operands. 2 / 4 is 1/2, not 0. Arithmetically, 1 * 1.0 is >>well-defined, so why can I not write this in an SML program? > > > Confusing integer division with rational division is not a consequence > of static typing, except that with static typing it's not as dangerous as > with dynamic typing (because a function declared as taking floating point > arguments and performing / on them will do the same even if you pass > integers to it, which in most languages will be automatically converted). Sorry, I don't get this. Why should it be more dangerous with dynamic typing? Common Lisp definitely gets this right, and most probably some other dynamically typed languages. > Mixed-type arithmetic is a different story. I'm talking only about 1/2 > being equal to 0 in some languages - this doesn't coincide with static > typing. Yes, dynamic vs static typing seems to be irrelevant here. (Although I wonder why you should need to distinguish between / and div...) Pascal From claird at lairds.com Fri Oct 31 12:06:27 2003 From: claird at lairds.com (Cameron Laird) Date: Fri, 31 Oct 2003 17:06:27 -0000 Subject: Get more from Google (was: programming languages (etc) "web popularity" fun) References: <9Vvob.74272$e5.2721707@news1.tin.it> Message-ID: In article <9Vvob.74272$e5.2721707 at news1.tin.it>, Alex Martelli wrote: . . . >thanks to the "allintext:" qualifier. (BTW, should anybody with >any interest in web searching not have O'Reilly's book "Google >Hacks" yet, GET IT!-). . . . Also . -- Cameron Laird Business: http://www.Phaseit.net From mwh at python.net Thu Oct 2 11:07:02 2003 From: mwh at python.net (Michael Hudson) Date: Thu, 2 Oct 2003 15:07:02 GMT Subject: Where are "What's new" for 2.0, 2.1? References: Message-ID: <7h33cebu1b6.fsf@pc150.maths.bris.ac.uk> "Edward K. Ream" writes: > The docs for 2.2 and 2.3 contain a "What's new" section. > > Are there any such sections for 2.0 and 2.1? If so, where are they? http://www.amk.ca/python/2.0/ http://www.amk.ca/python/2.1/ How hard did you look? Cheers, mwh -- Distribution of this memo is unnecessary. -- RFC 1926 From costanza at web.de Sat Oct 18 14:00:23 2003 From: costanza at web.de (Pascal Costanza) Date: Sat, 18 Oct 2003 20:00:23 +0200 Subject: Why don't people like lisp? In-Reply-To: References: Message-ID: dan wrote: > The world is moving in the direction of languages like Python Yes, and that's a good thing. It's a good thing because it means that static approaches are replaced by dynamic approaches. Pascal From mertz at gnosis.cx Tue Oct 7 19:36:18 2003 From: mertz at gnosis.cx (Lulu of the Lotus-Eaters) Date: Tue, 07 Oct 2003 19:36:18 -0400 Subject: Python syntax in Lisp and Scheme In-Reply-To: <87y8vw7imp.fsf@thalassa.informatimago.com> References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> <92c59a2c.0310031345.57d20631@posting.google.com> <3F82EF06.F3D7A10@setf.de> <8765j0akfk.fsf@thalassa.informatimago.com> <87y8vw7imp.fsf@thalassa.informatimago.com> Message-ID: | 3- what do you mean "printed"? A double-click on any parenthesis | selects the enclosed list so it's quite easy to see what it encloses. I kept clicking on the parenthesis in all your samples. All my newsreader did was go to text-select mode! Btw. I believe the word "printed" means "printed"... you've seen that stuff where ink is applied to paper, yes? Yours, Lulu... -- ---[ to our friends at TLAs (spread the word) ]-------------------------- Echelon North Korea Nazi cracking spy smuggle Columbia fissionable Stego White Water strategic Clinton Delta Force militia TEMPEST Libya Mossad ---[ Postmodern Enterprises ]-------------------------- From costanza at web.de Wed Oct 8 07:04:56 2003 From: costanza at web.de (Pascal Costanza) Date: Wed, 08 Oct 2003 13:04:56 +0200 Subject: Python syntax in Lisp and Scheme In-Reply-To: References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> <92c59a2c.0310031345.57d20631@posting.google.com> Message-ID: Terry Reedy wrote: > "Pascal Costanza" wrote in message > news:blu4q0$1568$1 at f1node01.rhrz.uni-bonn.de... > >>What about dealing with an arbitrary number of filters? > > > [macro snipped] > > What about it? Using macros for somewhat simple functions stikes me > as overkill. You're right. The use of with-collectors makes it more appropriate to express it as a macro, but of course, one can use a simple function when you don't stick to with-collectors. > >>An example: >> >> > (predicate-collect '(-5 -4 -3 -2 -1 0 1 2 3 4 5) >> (function evenp) >> (lambda (n) (< n 0)) >> (lambda (n) (> n 3))) >>(-4 -2 0 2 4) >>(-5 -3 -1) >>(5) >>(1 3) > > > In Python: > > def multisplit(seq, *preds): > predn = len(preds) > bins = [[] for i in range(predn+1)] > predpends = [(p,b.append) for (p,b) in zip(preds,bins)] > rpend = bins[predn].append > for item in seq: > for pred,pend in predpends: > if pred(item): > pend(item) > break > else: rpend(item) > return bins > > multisplit(range(-5,6), lambda i: not i%2, lambda i: i<0, lambda i: > i>3) > > [[-4, -2, 0, 2, 4], [-5, -3, -1], [5], [1, 3]] For the sake of completeness, here is the Lisp version: (defun predicate-collect (list &rest predicates) (let ((table (make-hash-table)) (preds (append predicates (list (constantly t))))) (dolist (elem list) (loop for pred in preds until (funcall pred elem) finally (push elem (gethash pred table)))) (mapcar (lambda (pred) (nreverse (gethash pred table))) preds))) ? (predicate-collect '(-5 -4 -3 -2 -1 0 1 2 3 4 5) (function evenp) (lambda (n) (< n 0)) (lambda (n) (> n 3))) ((-4 -2 0 2 4) (-5 -3 -1) (5) (1 3)) Pascal From sross at connectmail.carleton.ca Mon Oct 13 17:01:05 2003 From: sross at connectmail.carleton.ca (Sean Ross) Date: Mon, 13 Oct 2003 17:01:05 -0400 Subject: private variables/methods References: <3F856275.C884CE5@engcorp.com> <3ogib.657$cT6.27058@news20.bellglobal.com> <8Nkib.272892$R32.8895469@news2.tin.it> <17bkov48ob18hbg959r8o8vr8q17md8373@4ax.com> Message-ID: "Harri Pesonen" wrote in message news:SMDib.231$8j.6 at reader1.news.jippii.net... > Christopher Koppler wrote: > > Hmmm, asking naively: why not make global (or some better name, I > > don't have any good ideas however) the self of the current module - > > i.e. instead of > > > > def fun(): > > global x > > x = somevalue > > > > or your import, you'd use > > > > def fun(): > > global.x = somevalue Christopher: Hi. You couldn't use "global" that way for backwards compatability reasons. Still, I like the overall idea. [snip] > Sounds good to me. So if you have now > > a = 1 > def b(): > a = 2 > > This would cause a compiler warning that a global "a" already exists. Harri: Hi. Actually, I don't think that is what's intended. Rather, if you want to use the global variable a, you will need to access it through the current module object, which can be referenced using global, i.e., a = 1 def b(): global.a = 2 # rebinds the global variable a a = 3 # binds a new local variable a, the global variable a is unaffected. print "a values: global = %s; local = %s"%(global.a, a) #output a values: global = 2; local = 3 the local and global variables a will not be confused, because the global variable a can only ever be referenced in the local scope via the current module reference ("global"). Meaning, if you want to use a global variable in a scope other than at the module level , you'll have to preface it with "global.". > So > the programmer should write either > > def b(): > global.a = 2 > > or > > def b(): > local.a = 2 > > The latter of course creates a new local variable with the same name. > After this it is OK to use just "a" without "local" prefix? > > def b(): > local.a = 2 > a = 3 > So, continuing from the explanation above, you will not have to say "local.a = 2" to bind a local variable. All variables will be local by default. Variables from other namespaces (such as globals) will have to be explicitly resolved (e.g. "global.a = 2") > How about the following: > > def b(): > global.a = 2 > a = 3 > > Is the second "a" still global? > No. > The idea with "Option Explicit" gets around this differently. The > following creates a new local variable: > > def b(): > var a = 2 > > While the following refers to the global variable, if there is no local > variable with the same name: > > def b(): > a = 2 > > This would be more beautiful. > Making a variable local by default, and requiring that globals be accessed explicitly seems like a better path to me. As far as I know, the use of globals is generally discouraged. So a lot of people try to avoid using them in code, when they can. But local variables occur all the time. Using "Option Explicit" would seem to be making you write more code for something that happens more often (local variable binding), and less code for something that is discouraged and should be happening less often (global variable rebinding). But maybe thats just me... Sean From peter at engcorp.com Fri Oct 17 15:26:06 2003 From: peter at engcorp.com (Peter Hansen) Date: Fri, 17 Oct 2003 15:26:06 -0400 Subject: wait until change References: <3F90399E.AA2AF998@engcorp.com> Message-ID: <3F90424E.A5301708@engcorp.com> Tom wrote: > > Peter Hansen wrote: > > >Use time.sleep(). > > > >-Peter > > > If I use sleep, I have to know how long the process should sleep, but > sometimes it should sleep for seconds and sometimes for minutes. So it > would be good if I can put it to sleep and somehow wake it up if the > file changed. See Tim's excellent reply. Also, note that there are non-cross-platform solutions that basically notify your program "as soon as" (possibly without any latency guarantees) a change has happened. They are harder to use and quite likely unnecessary in your case, and the time.sleep() approach Tim points out is simpler and therefore the best thing to start with. You do have to confirm of course that this other application won't be writing to the file so often that you might run into trouble. Does this other program write updates infrequently, and does your Python analysis script run quickly enough, that if your code wakes up within a few seconds of each update it will complete its work soon enough to avoid problems? -Peter From martin at v.loewis.de Thu Oct 9 00:30:36 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 09 Oct 2003 06:30:36 +0200 Subject: Changing default encoding References: Message-ID: "jean.moser" writes: > Word is my word-processing tool.I can save the files in txt format > but special characters like ? are transformed in \xe9 when I read > the files in Python. That is not the case. They are not transformed to \xe9. Why do you believe such a transformation happens? > How do I proceed to get the original files in latin-1 ? They still have the original latin-1. Regards, Martin From aahz at pythoncraft.com Thu Oct 23 19:31:48 2003 From: aahz at pythoncraft.com (Aahz) Date: 23 Oct 2003 19:31:48 -0400 Subject: Why Python style guide (PEP-8) says 4 space indents instead of 8 space??? 8 space indents ever ok?? References: <3d6c6fc3.0310221836.fc8c89@posting.google.com> Message-ID: In article , Martin v. =?iso-8859-15?q?L=F6wis?= wrote: > >In non-Python-aware editors (like Usenet messages), I prefer 2-space >indentation as well. While programming larger projects, I use a >Python-aware editor, and that editor makes indentation automatically >(to four spaces), so it is just as easy to type. Get a better newsreader. ;-) (My newsreader lets me pick any editor I want.) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From costanza at web.de Thu Oct 23 04:44:06 2003 From: costanza at web.de (Pascal Costanza) Date: Thu, 23 Oct 2003 10:44:06 +0200 Subject: Python from Wise Guy's Viewpoint In-Reply-To: References: <_8Ekb.7543$pT1.318@twister.nyc.rr.com> Message-ID: Matthias Blume wrote: > Pascal Costanza writes: > > >>The set of programs that are useful but cannot be checked by a static >>type system is by definition bigger than the set of useful programs >>that can be statically checked. > > > By whose definition? What *is* your definition of "useful"? It is > clear to me that static typing improves maintainability, scalability, > and helps with the overall design of software. (At least that's my > personal experience, and as others can attest, I do have reasonably > extensive experience either way.) > > A 100,000 line program in an untyped language is useless to me if I am > trying to make modifications -- unless it is written in a highly > stylized way which is extensively documented (and which usually means > that you could have captured this style in static types). So under > this definition of "useful" it may very well be that there are fewer > programs which are useful under dynamic typing than there are under > (modern) static typing. A statically typed program is useless if one tries to make modifications _at runtime_. There are software systems out there that make use of dynamic modifications, and they have a strong advantage in specific areas because of this. If you can come up with a static type system for an unrestricted runtime metaobject protocol, then I am fine with static typing. >>So dynamically typed languages allow >>me to express more useful programs than statically typed languages. > > > There are also programs which I cannot express at all in a purely > dynamically typed language. (By "program" I mean not only the executable > code itself but also the things that I know about this code.) > Those are the programs which are protected against certain bad things > from happening without having to do dynamic tests to that effect > themselves. This is a circular argument. You are already suggesting the solution in your problem description. > (Some of these "bad things" are, in fact, not dynamically > testable at all.) For example? >>I don't question that. If this works well for you, keep it up. ;) > > > Don't fear. I will. > > ...and BTW, please let me keep up using dynamically typed languages, because this works well for me! (That's the whole of my answer to the original question, why one would want to give up static typing.) >>>(And where are _your_ empirical studies which show that "working around >>>language restrictions increases the potential for bugs"?) >> >>I don't need a study for that statement because it's a simple >>argument: if the language doesn't allow me to express something in a >>direct way, but requires me to write considerably more code then I >>have considerably more opportunities for making mistakes. > > > This assumes that there is a monotone function which maps token count > to error-proneness and that the latter depends on nothing else. This > is a highly dubious assumption. In many cases the few extra tokens > you write are exactly the ones that let the compiler verify that your > thinking process was accurate (to the degree that this fact is > captured by types). If you get them wrong *or* if you got the > original code wrong, then the compiler can tell you. Without the > extra tokens, the compiler is helpless in this regard. See the example of downcasts in Java. > To make a (not so far-fetched, btw :) analogy: Consider logical > statements and formal proofs. Making a logical statement is easy and > can be very short. It is also easy to make mistakes without noticing; > after all saying something that is false while still believing it to > be true is extremely easy. Just by looking at the statement it is > also often hard to tell whether the statement is right. In fact, > computers have a hard time with this task, too. Theorem-proving is > hard. > On the other hand, writing down the statement with a formal proof is > impossible to get wrong without anyone noticing because checking the > proof for validity is trivial compared to coming up with it in the > first place. So even though writing the statement with a proof seems > harder, once you have done it and it passes the proof checker you can > rest assured that you got it right. The longer "program" will have fewer > "bugs" on average. Yes, but then you have a proof that is tailored to the statement you have made. The claim of people who favor static type systems is that static type systems are _generally_ helpful. Pascal From mspight at dnai.com Fri Oct 24 17:15:09 2003 From: mspight at dnai.com (Marshall Spight) Date: Fri, 24 Oct 2003 21:15:09 GMT Subject: Python from Wise Guy's Viewpoint References: <_8Ekb.7543$pT1.318@twister.nyc.rr.com> <3f972315$1@news.unimelb.edu.au> <3638acfd.0310230039.306b14f@posting.google.com> <3638acfd.0310232246.64fa09ed@posting.google.com> <65fn61-b61.ln1@ID-7776.user.dfncis.de> Message-ID: "Pascal Costanza" wrote in message news:bnbafk$uu6$1 at f1node01.rhrz.uni-bonn.de... > ... there exist programs that work but > that cannot be statically typechecked. These programs objectively exist. > By definition, I cannot express them in a statically typed language. I agree these programs exist. It would be really interesting to see a small but useful example of a program that will not pass a statically typed language. It seems to me that how easy it is to generate such programs will be an interesting metric. Anyone? (Sorry, I'm a static typing guy, so my brain is warped away from such programs. :-) Marshall From aleax at aleax.it Tue Oct 28 18:44:57 2003 From: aleax at aleax.it (Alex Martelli) Date: Tue, 28 Oct 2003 23:44:57 GMT Subject: Python is Considered Harmful References: <7ioew3xjh1.fsf@enark.csis.hku.hk> <1wsnb.366321$R32.12079281@news2.tin.it> <3F9E878F.1090703@info.unicaen.fr> Message-ID: Jerzy Karczmarczuk wrote: > Alex Martelli wrote: >> Jegenye 2001 Bt wrote: > >>>So this was actually like the famous equation >>>"9*6=42" ... >> Do you mean, implicitly using base 13? I know of no programming ... > In Icon you can write 13r9 * 13r6. Icon is a decent, although weakly known > language, without any "particularly 'powerful' macros", which permits to > choose the base of literals. Nothing horrible. Yes, I used to love Icon (the coroutines and backtracking and all, cool!) but notice it uses EXPLICIT indications of non-10 base. There is, indeed, nothing at all horrible with that. Besides, the problem is not with 9 or 6, which happen to have the same value in either base 10 or 13:-). The problem is with that result...:) Alex From tjreedy at udel.edu Sun Oct 5 17:20:01 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 5 Oct 2003 17:20:01 -0400 Subject: Callable assertion? References: Message-ID: "Lulu of the Lotus-Eaters" wrote in message news:mailman.1065381789.5393.python-list at python.org... > "Terry Reedy" wrote previously: > |The acid test is to try calling it: > |try: param() > |except TypeError, msg: > > This is usually a bad idea though. I disagree. The OP previously got the iscallable() answer, with the caveat that True may be a lie, and I posted in that context. One might still want to wrap the actual call in a try block. It is the same for reading files or making socket connections. No matter what pre-info one gathers, the acid test is to try to do it, and a careful coder will prepare for possible failure. > Many, if not most, things you call can either have side effects and/or > consume non-trivial resources (time, memory, especially). > For example, you don't want to change state by making a call if you know > you are not ready for that state change until something else happens. Of course. I assumed the OP already knows this. > But you may want to know whether 'param' is callable before you bother > with the setup code. Of course, but regardless of 'want', you cannot know for sure, as 1 or 2 others have said and shown (see Rodriguez' post). Terry J. Reedy From tjreedy at udel.edu Sun Oct 19 17:41:18 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 19 Oct 2003 17:41:18 -0400 Subject: Python from Wise Guy's Viewpoint References: <2hvfqlmkcd.fsf@vserver.cs.uit.no> <2hn0bxm8kf.fsf@vserver.cs.uit.no> Message-ID: "Frode Vatvedt Fjeld" wrote in message news:2hn0bxm8kf.fsf at vserver.cs.uit.no... cc'ed in case you are not reading c.l.python, which I am limiting this to. > So to get from the ID to the bytecode, you go through a dictionary? > And the mapping from name to ID happens perhaps when the caller is > bytecode-compiled? No. In Python, all names are associated with objects in namespaces. Lookup is done as needed at the appropriate runtime. Function objects are 1st class and are no different from any others in this respect. The same goes for slots in collection objects being associated with member objects. The free online tutorial as www.python.org explains Python basics like this. Terry J. Reedy From max at alcyone.com Wed Oct 15 17:32:34 2003 From: max at alcyone.com (Erik Max Francis) Date: Wed, 15 Oct 2003 14:32:34 -0700 Subject: use make and version control system for every project? References: <3F81BE4A.8B084E4B@alcyone.com> <3F89B6B0.8E2ABFDD@alcyone.com> Message-ID: <3F8DBCF2.496862B2@alcyone.com> Aahz wrote: > Does Perforce work without a server? No, but as I said, you can run it without a license with two users and two client workspaces for free for as long as you want; the client and server are free to download. See the Licensing section of this page: http://www.perforce.com/perforce/loadprog.html You can run the server yourself, you just can't add more than two users or workspaces -- and for single use, that's often a perfectly acceptable limitation. And as I mentioned, you can supposedly qualify for a free license with open source projects that meet some criteria, but I haven't looked into it closely myself so I don't know the precise details. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ In our family we don't divorce our men -- we bury them. \__/ Ruth Gordon From xavim at fqingenieria.es Wed Oct 1 04:01:12 2003 From: xavim at fqingenieria.es (Xavier Martinez) Date: Wed, 1 Oct 2003 10:01:12 +0200 Subject: Tkinter not installed References: <57efaf35.0309300435.8864896@posting.google.com> <57efaf35.0309302152.2e539524@posting.google.com> Message-ID: <002d01c387f2$2f4b3840$0102a8c0@xavim> > hi, > i am very sorry.i am using Redhat Linux 8.0. > I 've downloaded few rpm files "tkinter-2.2.1-17.i386.rpm" > will this be of any use?if so how do i extract the files from rpm(i > know that it is used to compress some software files). I have not used Red Hat for a long time. However, a bit of googling gives: Using RPM (from the Red Hat manuals) (command-line tool): http://www.redhat.com/docs/manuals/linux/RHL-8.0-Manual/custom-guide/s1-rpm-using.html In short, write (as root): $ rpm -Uvh tkinter-2.2.1-17.i386.rpm If it complains about 'Failed dependencies', you will need to install some other packages first. You can also use a graphical tool. See: http://www.redhat.com/docs/manuals/linux/RHL-8.0-Manual/custom-guide/ch-graphical-rpm.html Another alternative is to use 'apt-rpm'. See: http://apt-rpm.tuxfamily.org/ From http Wed Oct 8 18:03:18 2003 From: http (Paul Rubin) Date: 08 Oct 2003 15:03:18 -0700 Subject: Book Recommendation References: <7xd6d7e6c8.fsf@ruckus.brouhaha.com> Message-ID: <7x8ynve6ah.fsf@ruckus.brouhaha.com> Paul Rubin writes: > First, read the tutorial. Then, if you're still confused, go look at > the book in the store and see if it answers your questions. If it > does, buy it and read it. If it doesn't, look for another group, ask > questions on the newsgroup, etc. Bah, I'm not typing well today. I meant to say "If it doesn't, look for another BOOK, ask questions on the newsgroup, etc.". From inyeol.lee at siimage.com Wed Oct 29 14:26:42 2003 From: inyeol.lee at siimage.com (Inyeol Lee) Date: Wed, 29 Oct 2003 11:26:42 -0800 Subject: PEP 289: Generator Expressions (please comment) In-Reply-To: <45228044.0310240442.4903f866@posting.google.com> References: <5d83790c.0310231158.65595858@posting.google.com> <45228044.0310240442.4903f866@posting.google.com> Message-ID: <20031029192642.GE2741@siliconimage.com> On Fri, Oct 24, 2003 at 05:42:44AM -0700, Chris Perkins wrote: > In fact, list comprehensions themselves become redundant syntactic > sugar under the new proposal: > > [foo(x) for x in bar] ==> list(foo(x) for x in bar) Is there any plan to deprecate list comprehension when we move to Python3.0? I think the advantages are; 1. It's just a syntactic sugar, only saves 4 chars. 2. It solves loop variable leaking problem of list comprehension. I think it causes less confusion to remove list comprehension than to change the semantics of it not to leak loop variables when 3.0 comes. 3. We can From no.mail at ever.no Thu Oct 30 04:46:22 2003 From: no.mail at ever.no (Javier) Date: Thu, 30 Oct 2003 10:46:22 +0100 Subject: Python + ioctl + Windows HOWTO?? Message-ID: Hi all!! I'm trying to use Python to help in testing software for the Windows Platform. The sw we develop at the company I work for sets up quite a number of "new" device drives in Windows, and as part of the testing process I'd need to be able to "query" them about their state and suchlike. The "interface" for doing so involves opening "device files" (of the form \\.\Device\CDCrypto) and sending them ioctls to query their state. I've been searching / googling for ioctl, and the only mentions I've seen are to UNIX-specific modules such as fcntl. My question is, is it possible to use similar functions / modules in windows? If so, how? Thanks a lot Javier PS: Also, is there any "pre-built" "sw-testing" framework developed in Python. I'm not refering to "unit testing" for Python code, but a way of "plugging-on" tests and specifying dependencies so that I'd only have to worry about what tests to write / how to test things. Thank,s JJJ From Kyle_E2006 at hotmail.com Sun Oct 26 14:04:04 2003 From: Kyle_E2006 at hotmail.com (Kyle E) Date: Sun, 26 Oct 2003 13:04:04 -0600 Subject: Help: low level user input Message-ID: <1067195038.643136@news001.transaeris.com> Ok, I have a little tiny problem, a beginner problem, that I am overlooking. I am writing a Information Gathering Program, that takes user input from scripted questions and prints them in a handy list in the end. As of now, when one of my questions is asked, the only possible way to enter text is to type ( "John" ) minus the parenthesis. You do need the qoutation marks though. I just want to be able to type ( John ) without the unneeded quotation marks. I know someone has the answer, sorry for the inexperienced question, but it's ticking me off. This is my program: from time import sleep ##INTRODUCTION print "Personal Information Program" print "----------------------------" print sleep(3) print "Please input the requested information... " sleep(1) ##INPUT NAME print "ID: " sleep(2) print "What is your first name?" fname = input ("> ") sleep(1) print "What is your middle initial?" mname = input ("> ") sleep(1) print "What is your last name?" lname = input ("> ") sleep(1) ##INPUT ADDRESS print "Location: " sleep(2) print "What is your street address?" saddy = input ("> ") sleep(1) print "What city do you live in?" city = input ("> ") sleep(1) print "What state do you live in?" state = input ("> ") sleep(1) print "What is your zipcode?" zip = input ("> ") sleep(1) print "Do you have a P.O. Box?" poan = input ("> ") if poan == yes: print "What is your P.O. Box number?" pobox = input ("> ") From ingvar at cathouse.bofh.se Mon Oct 20 11:19:14 2003 From: ingvar at cathouse.bofh.se (Ingvar Mattsson) Date: 20 Oct 2003 16:19:14 +0100 Subject: Python from Wise Guy's Viewpoint References: <3F93D20A.B9D0C30D@setf.de> Message-ID: <87he249bt9.fsf@gruk.tech.ensign.ftech.net> [ Follow-up redirected to comp.lang.lisp ] Joachim Durchholz writes: > james anderson wrote: > > > Joachim Durchholz wrote: [SNIP] > >>I'd really like to see a Lisp dialect that valued reliability over raw > >>expressive power. But I fear this isn't very high on the agenda of the > >>Lisp community. Besides, it would be difficult to do that - Lisp offers > >>no protection against peeking at internals and setting up all that > >>unsafe-but-powerful stuff. > > what are "internals", what is "protection"? > > No way to define an opaque type. AFAIK, modern Lisps allow > user-defined types, but they offer no way to protect them against > inspecting their internals. I'd prefer to have at least a grain of > information hiding... Well... Using INSPECT one can "look inside" a type, but one has almost the same (possibly the same) amount of introspection in (say) Python, using dir() (and very handy it is, not as good as reading documentation, but for those "I need to check this now" moments, it can often be sufficient). One should, as usual, follow one's introspective moments by checking The Reference(s), to see if what one saw, introspecting, is "supported" or "unsupported" (if the latter, one can bet things will break in interesting ways, either "soon" or "on next upgarde"). But, at times, that can be the only way to use a third-party module taht *almost* fits one's needs. I saw a horror-story of someone having to retro-fit third-part C++ modules by clever run-time mangling of things, to get it to work Right, instead of "it does almost what the documentation says, but not quite and fixing it is faster than getting a patch or rolling it ourselves". I think it was in a thread in comp.lang.lisp, a few years back, regarding why it was a *bad* thing forbidding access to non-exported sympols from a package. Not exporting something is a good sign taht one shouldn't touch it and well-behaved programmers won't. They *may* file a bug saying "this would be handy if it was supported", but they should, in general, not go ahead and use it. //Ingvar -- Coffee: Nectar of gods / Aesir-mead of sysadmins / Elixir of life From imbosol at aerojockey.invalid Wed Oct 15 16:26:02 2003 From: imbosol at aerojockey.invalid (Carl Banks) Date: Wed, 15 Oct 2003 20:26:02 GMT Subject: assignment expression peeve References: <7x1xtfkuky.fsf@ruckus.brouhaha.com> <6q6jb.10882$fv4.3354@nwrdny02.gnilink.net> <7xk77676bt.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Carl Banks writes: >> The designers of Python believe that assignment expressions are bad >> news > > I'm not sure you're correct about that. The impression I've gotten > when this subject has come up before is designers are terrified of > someone saying > > if x = y: > > when they meant ==, and causing a nuclear meltdown or something. > Using a different operator like "x := y", avoids that problem which is > why I did it that way in the example I gave. However, with that > problem removed, it's still not considered a done deal. With my apologies for sounding a little edgy in the first post, I think this is only only a minor reason why Python has no assignment expressions. The real reason is that assignment expressions lead to all kinds of ugly and unreadable code. This is because there is no linguistic analogue for assignment as an expression. Things that work as expressions in computer code are uttered as nouns, or noun phrases, in natural languages. Assignments, however, are not uttered as nouns, but as imperatives, and therefore are inappropraite as expressions. Assignment expressions are bad news, I think, and I think the designers think, because it goes against the grain of natural language, and is thus counterintuitive, and leads to code that takes a lot of effort to read and understand. >> (which I agree with), > > Well, that's your opinion. I've given some linguistic evidence why it's ugly and counterintuitive. Take it as you will. >> and they will NEVER make assigments into expressions just to avoid >> this little problem. > > There's no way to know that, without first waiting til the end of "never". Well, an evil alien can possess Guido's body, and declare that Python will add assignment expressions--and then do it tactfully enough that the masses won't rise against the BDFL. You're right, I'd have to wait until never ends to know that won't happen. Barring that though, I can pretty much assure you that this will NEVER change. -- CARL BANKS http://www.aerojockey.com/software As the newest Lady Turnpot descended into the kitchen wrapped only in her celery-green dressing gown, her creamy bosom rising and falling like a temperamental souffle, her tart mouth pursed in distaste, the sous-chef whispered to the scullery boy, "I don't know what to make of her." --Laurel Fortuner, Montendre, France 1992 Bulwer-Lytton Fiction Contest Winner From vze4rx4y at verizon.net Wed Oct 29 11:52:57 2003 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Wed, 29 Oct 2003 16:52:57 GMT Subject: On PEP 322 (ireverse) References: <4xQnb.373812$R32.12367046@news2.tin.it> Message-ID: > Gon?alo Rodrigues wrote: > > First, i like the name ireverse, much better then inreverse (eek!). Thanks. [Alex] > I still prefer Werner Schiendl's idea of iter.reversed, IF we find a > way to have builtin function iter grow a 'staticmethod' of sorts...! No thanks. Yuck. Please do not twist this simple idea into knots. This is supposed to be something you can teach in the first half-hour and then use forever. I would sooner teach negative xrange() indices than immediately launch into dotted references to a static method attached to something that doesn't look like it should have a method. This is a simplification, not an exercise in being cute or clever just to avoid a builtin. Raymond Hettinger From peter at engcorp.com Sun Oct 19 09:21:18 2003 From: peter at engcorp.com (Peter Hansen) Date: Sun, 19 Oct 2003 09:21:18 -0400 Subject: Python from Wise Guy's Viewpoint References: Message-ID: <3F928FCE.5C57BB6A@engcorp.com> Warning! Troll alert! I missed the three newsgroup cross-post the first time, so I thought this might be a semi-serious question. -Peter mike420 at ziplip.com wrote: > > THE GOOD: > > 1. pickle > > 2. simplicity and uniformity > > 3. big library (bigger would be even better) > > THE BAD: > > 1. f(x,y,z) sucks. f x y z would be much easier to type (see Haskell) > 90% of the code is function applictions. Why not make it convenient? > > 2. Statements vs Expressions business is very dumb. Try writing > a = if x : > y > else: z > > 3. no multimethods (why? Guido did not know Lisp, so he did not know > about them) You now have to suffer from visitor patterns, etc. like > lowly Java monkeys. > > 4. splintering of the language: you have the inefficient main language, > and you have a different dialect being developed that needs type > declarations. Why not allow type declarations in the main language > instead as an option (Lisp does it) > > 5. Why do you need "def" ? In Haskell, you'd write > square x = x * x > > 6. Requiring "return" is also dumb (see #5) > > 7. Syntax and semantics of "lambda" should be identical to > function definitions (for simplicity and uniformity) > > 8. Can you undefine a function, value, class or unimport a module? > (If the answer is no to any of these questions, Python is simply > not interactive enough) > > 9. Syntax for arrays is also bad [a (b c d) e f] would be better > than [a, b(c,d), e, f] > > 420 > > P.S. If someone can forward this to python-dev, you can probably save some > people a lot of soul-searching From hanzspam at yahoo.com.au Thu Oct 2 02:54:45 2003 From: hanzspam at yahoo.com.au (Hannu Kankaanp??) Date: 1 Oct 2003 23:54:45 -0700 Subject: IDE Python References: <3f79f9b0$0$58706$e4fe514c@news.xs4all.nl> Message-ID: <840592e1.0310012254.48b9347c@posting.google.com> Irmen de Jong wrote in message news:<3f79f9b0$0$58706$e4fe514c at news.xs4all.nl>... > But keep in mind that powerful 'intellisense' > is impossible in such a dynamic language as Python... I wouldn't say so. Autocomplete just needs to be a bit more intelligent than in statically typed languages. At first, it could search all class definitions for method names. Then at first it could only help you when typing long variable names since they can be pretty unique across different types - And completing long names is where autocomplete is most useful anyway. After you called one or two methods for a certain type, it could narrow down the possibilities of what type the variable is, or possibly nail it down to some specific type right away. The auto-complete could memoize the types you use often and have preference for those types. It could also memoize patterns in variable names and then figure that if the variable name has "text" or "name" etc. in it, it's more probably a string object, since that's how the programmer indicated string-like objects earlier too. And similarly if you have two variables named 'internal_buffer' at different parts of your program, they're likely the same type. Then it could also search code and look where some functions are actually called. The call site often has more info of the types being used. Functions in a single module often work with similar types too, so the auto-complete tool could have preference to the types used (already deduced) in the current module. All in all, I believe a very powerful autocomplete tool is possible in a dynamically typed language. After all, we as humans know what the types often are and what methods we will want to call for the parameter objects. An auto-complete-tool can try to archieve the same (without having to plug into our brains and read our thoughts, mind you). What dynamic typing lacks though, is 100% reliability of the type. Auto-complete-tool could be correct 95% of time and it wouldn't really matter if it sometimes did a mistake. But automatic refactoring tools are something that can't make mistakes, since they often have to deal with so many renamings. Bicycle Repair Man (Python refactoring tool) also often says "50% chance" and the like for variable names that it can't deduce with certanity. Perhaps there's no cure for that, unless the refactoring tool is some super-smart AI. From imbosol at aerojockey.invalid Tue Oct 7 15:16:58 2003 From: imbosol at aerojockey.invalid (Carl Banks) Date: Tue, 07 Oct 2003 19:16:58 GMT Subject: Class instantiation question References: Message-ID: Todd Johnson wrote: > Ok, say I have a class MyClass and an __init__(self, > a, b) Say that a and b are required to be integers > for example. So my init looks like: > > __init__(self, a, b): > try: > self.one = int(a) > self.two = int(b) > except ValueError: > #nice error message here > return None > > I have even tried a similar example with if-else > instead of try-except, but no matter what if I call > > thisInstance = MyClass(3, "somestring") > > it will set self.one to 3 and self.two will be > uninitialised. The behavior I am hoping for, is that > thisInstance is not created instead(or is None). How > do I get the behavior I am looking for? 1. I highly recommend you rethink your programming. Are you planning to handle the error in the function that called the MyClass contructor? In other words, are you doing something like this: def some_function(a,b): thisInstance = MyClass(a,b) if thisInstance is None: handle_error() else: do_something_useful(thisInstance) If so, you are not taking full advantage of the exception handling mechanism. The best way to do it is like this: def some_function(a,b): try: thisInstance = MyClass(a,b) except ValueError: handler_error() else: do_something_useful(thisInstance) As always, a larger code snippet can help us help you with that, if you wish. 2. If you're sure the behavior you want is to return None if a or b is not an integer, then I recommned you use a factory function: def my_class_maker(a,b): try: return MyClass(a,b) except ValueError: return None -- CARL BANKS http://www.aerojockey.com/software As the newest Lady Turnpot descended into the kitchen wrapped only in her celery-green dressing gown, her creamy bosom rising and falling like a temperamental souffle, her tart mouth pursed in distaste, the sous-chef whispered to the scullery boy, "I don't know what to make of her." --Laurel Fortuner, Montendre, France 1992 Bulwer-Lytton Fiction Contest Winner From skip at pobox.com Fri Oct 24 09:45:50 2003 From: skip at pobox.com (Skip Montanaro) Date: Fri, 24 Oct 2003 08:45:50 -0500 Subject: PEP 289: Generator Expressions (please comment) In-Reply-To: References: <5d83790c.0310231158.65595858@posting.google.com> Message-ID: <16281.11534.296535.370301@montanaro.dyndns.org> Ville> However, I'm not completely sure about allowing them to be Ville> creatad w/o parens in function calls, seems a bit too magical for Ville> my taste. Think of parens and genex's the same way you'd think of parens and tuples. Creating tuples often doesn't require parens either, but sometimes does in cases where the syntax would be ambiguous). As arguments to function calls, parens would be required to separate generator expressions from other arguments. In the one arg case they aren't required (though you're free to add them if it warms the cockles of your heart ;-). Skip From costanza at web.de Fri Oct 24 13:56:22 2003 From: costanza at web.de (Pascal Costanza) Date: Fri, 24 Oct 2003 19:56:22 +0200 Subject: Test cases and static typing In-Reply-To: References: <3638acfd.0310230039.306b14f@posting.google.com> <87ekx4xaym.dlv@wanadoo.fr> <87znfsvuqh.dlv@wanadoo.fr> <6ogn61-f61.ln1@ID-7776.user.dfncis.de> Message-ID: Dirk Thierbach wrote: > Pascal Costanza wrote: > >>Dirk Thierbach wrote: > >>OK, I have got it. No, that's not what I want. What I want is: >> >>testxyz obj = (concretemethod obj == 42) >> >>Does the code compile as long as concretemethod doesn't exist? > > No. Does your test pass as long as conretemthod doesn't exist? It doesn't, > for the same reason. As long as I am writing only tests, I don't care. When I am in the mood of writing tests, I want to write as many tests as possible, without having to think about whether my code is acceptable for the static type checker or not. >>>It's the same with compile-time type errors. The only difference is >>>that they happen at compile-time, not at test-suite run-time, but the >>>necessary reaction is the same: Fix your code so that all tests (or >>>the compiler-generated type "tests") pass. Then continue with the next >>>step. > >>The type system might test too many cases. > > I have never experienced that, because every expression that is valid > code will have a proper type. > > Can you think of an example (not in C++ or Java etc.) where the type > system may check too many cases? Here is one: (defun f (x) (unless (< x 200) (cerror "Type another number" "You have typed a wrong number") (f (read))) (* x 2)) Look up http://www.lispworks.com/reference/HyperSpec/Body/f_cerror.htm#cerror before complaining. Pascal -- Pascal Costanza University of Bonn mailto:costanza at web.de Institute of Computer Science III http://www.pascalcostanza.de R?merstr. 164, D-53117 Bonn (Germany) From d95-bli at nada.kth.se Thu Oct 9 06:14:05 2003 From: d95-bli at nada.kth.se (=?iso-8859-1?q?Bj=F6rn_Lindberg?=) Date: 09 Oct 2003 12:14:05 +0200 Subject: Python syntax in Lisp and Scheme References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> <92c59a2c.0310031345.57d20631@posting.google.com> <8CVgb.8$KR3.1846@typhoon.nyu.edu> Message-ID: "Andrew Dalke" writes: > prunesquallor at comcast.net: > > So either the syntax doesn't make a whole hell of a lot of difference > > in readability, or readability doesn't make a whole hell of a lot of > > difference in utility. > > Or the people who prefer the awesome power that is Lisp and > Scheme don't find the limited syntax to be a problem. All evidence points to the fact that Lisp syntax is no worse than Algol-style syntax. As Joe explained, other syntaxes have been used for Lisp many times over the years, but lispers seem to prefer the s-exp one. If anything, one could draw the conclusion that s-exp syntax must be /better/ than Algol-style syntax since the programmers who have a choice which of them to use -- for the same language -- apparently choose s-exp syntax. You really have no grounds to call Lisp syntax limited. Bj?rn From mertz at gnosis.cx Fri Oct 3 12:58:56 2003 From: mertz at gnosis.cx (David Mertz) Date: Fri, 03 Oct 2003 12:58:56 -0400 Subject: GIL in the new glossary References: <87oewzyv81.fsf@pobox.com> <9fc58c06.0310030613.67c32a7a@posting.google.com> Message-ID: lcaamano at mindspring.com (Luis P Caamano) wrote previously: |> > a) play with IPC again |> Sounds like a great idea to me. :-) |Not if you need several hundred threads in your app. You don't NEED hundreds of threads in your app. You have decided to implement your app using hundreds of threads; which might be fine, but it certainly not the ONLY possibility (even without knowing what your app is). Threads are NEVER "the only way." For example, using "weightless threads" has much less overhead than does PThreads, if you really need hundreds (or at least if you need thousands), see . In any case, there is no reason why threading and IPC cannot combine. One process (for one processor) can itself run as many threads as it wants, and IPC can communicate data between each hundred-thread process. Problem solved... at the cost of requiring a bit of lumpiness in the division of computation. Given that massively parallel machines are EXPENSIVE, and that applications that need them are RARE, it hardly seems like an unbearable burden for programmers of such apps to put in a SMALL amount of extra work using an IPC framework. I doubt that Python developers will ever invest the much larger amount of work that would be needed for a free threading interpreter... but you are welcome to, of course. As someone else commented, Caamano seems to want PThreads more as a matter of religious dogma than out of any concrete benefits. That's the wrong approach, to my mind, for implementing any application... but even more so for computationally expensive ones. |see how it would compare to the same app written in |C running on an OS with an MxN pthread library. :-) Yep. C is faster than Python. Given the rest of Caamano's doctrine that his apps must be written in Python, that seems irrelevant though. Yours, David... -- _/_/_/ THIS MESSAGE WAS BROUGHT TO YOU BY: Postmodern Enterprises _/_/_/ _/_/ ~~~~~~~~~~~~~~~~~~~~[mertz at gnosis.cx]~~~~~~~~~~~~~~~~~~~~~ _/_/ _/_/ The opinions expressed here must be those of my employer... _/_/ _/_/_/_/_/_/_/_/_/_/ Surely you don't think that *I* believe them! _/_/ From dkuhlman at rexx.com Sat Oct 11 20:02:43 2003 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Sat, 11 Oct 2003 17:02:43 -0700 Subject: stop program and start interactive interpreter References: Message-ID: Dave Reed wrote: > > I seem to remeber reading somewhere there was a statement you > could put in your python program to stop its execution and start > the interactive interpreter at that point (and then you could > change the value of some variables and continue executing). Am I > having delusions or is there a way to do this? > > Thanks, > Dave Take a look at IPython. It provides both an enhanced Python command line and an interactive shell that you can call from within your Python source code. However, I believe that if you change the value of variables, those new values are lost when you exit the IPython shell and continue execution. http://ipython.scipy.org/ The manual is at: http://ipython.scipy.org/doc/manual/index.html And the part of the manual about the interactive shell is at: http://ipython.scipy.org/doc/manual/node9.html Hope this helps. (another) Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman dkuhlman at rexx.com From hanzspam at yahoo.com.au Mon Oct 27 05:16:06 2003 From: hanzspam at yahoo.com.au (Hannu Kankaanp??) Date: 27 Oct 2003 02:16:06 -0800 Subject: 'while' in list comprehension? References: <20031022175924.GA10716@jsaul.de> <20031024125923.GC27460@jsaul.de> Message-ID: <840592e1.0310270216.47ff13cf@posting.google.com> "Michael Geary" wrote in message news:... > Here's an idea that might avoid this bit of confusion: > > foo = [ i for i in bar until len(i) == 0 ] Another variation: foo = [i for i in bar, break if len(i) == 0] This wouldn't need a new keyword. From skip at pobox.com Tue Oct 21 11:02:05 2003 From: skip at pobox.com (Skip Montanaro) Date: Tue, 21 Oct 2003 10:02:05 -0500 Subject: <> and DeprecationWarning In-Reply-To: References: <20031020163642.GA5539@nl.linux.org> Message-ID: <16277.19053.91483.60153@montanaro.dyndns.org> Dennis> Though I feel comfortable with Dennis> x <> y I suspect anyone who's written significant amounts of Pascal will find it comfortable (though I imagine that population is dwindling as CS departments struggle to make their programs more "relevant" and bow to the gods from Redmond). '!=' makes more mnemonic sense if you're a C programmer, despite being slightly harder to type. '<>' sort of suggests 'less than or greater than'. Maybe it should be written as '<|>'. I-think-we-need-a--operator-ly, y'rs, Skip From avera at coes.org.pe Tue Oct 21 10:34:13 2003 From: avera at coes.org.pe (Alberto Vera) Date: Tue, 21 Oct 2003 09:34:13 -0500 Subject: searching structures References: Message-ID: <002301c397e0$66320b10$1603a8c0@pc22> RE: searching structuresYes, I do ----- Original Message ----- From: Batista, Facundo To: Python-List (E-mail) Sent: Tuesday, October 21, 2003 9:06 AM Subject: RE: searching structures #- I'd like to know how many 'arrays' start with ABCD like ABCD* #- (ABCD,ABCDE,ABCDEF) You mean filtering by the NAME of the object? . 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. ------------------------------------------------------------------------------ -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From Scott.Daniels at Acm.Org Thu Oct 2 10:18:46 2003 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Thu, 02 Oct 2003 07:18:46 -0700 Subject: Python and Memory In-Reply-To: <3f7bad69.18663686@news.houston.sbcglobal.net> References: <3f7bad69.18663686@news.houston.sbcglobal.net> Message-ID: <3f7c33c7$1@nntp0.pdx.net> Ben Fairbank wrote: > I have to pick a language to commit to for general purpose > scientific/statistical/utility/database programming at my office and > have pretty much narrowed it down to R or Python. In a previous life, I went for R and Python and eventually stayed in python (with numeric, of course) because, in my case, moving data over to R and then operating there was always more expensive than simply doing the calculations in python. These days I'd check if numarray did the trick. If you want to play in this world, check out the enthought packaging of python: http://www.enthought.com/python/ They've got most of the goodies in there that you'd be likely to want to run out and add to your python in the first months. -Scott David Daniels Scott.Daniels at Acm.Org From costanza at web.de Sun Oct 12 11:43:47 2003 From: costanza at web.de (Pascal Costanza) Date: Sun, 12 Oct 2003 17:43:47 +0200 Subject: Python syntax in Lisp and Scheme In-Reply-To: References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> <6CZgb.3273$dn6.860@newsread4.news.pas.earthlink.net> <%hihb.4368$dn6.2921@newsread4.news.pas.earthlink.net> Message-ID: Andrew Dalke wrote: > In retrospect I should have given a more obvious possibility. > As some point I hope to have computer systems I can program > by voice in English, as in "House? Could you wake me up > at 7?" That is definitely a type of programming, but Lisp is > a language designed for text, not speed. I don't understand that last sentence. Could you clarify this a bit? You don't want to say that there is an inherent dichotomy between text and speed, do you?!? > Pascal Costanza: > >>I believe it is an accepted fact that uniformity in GUI design is a good >>thing because users don't need to learn arbitrarily different ways of >>using different programs. You only need different ways of interaction >>when a program actually requires it for its specific domain. > > > My spreadsheet program looks different from my word processor > looks different from my chemical structure editor looks different from > my biosequence display program looks different from my image > editor looks different from my MP3 player looks different from my > email reader looks different from Return to Castle Wolfinstein .... > > There are a few bits of commonality; they can all open files. But > not much more. ...but you probably know from the start where to find the menus, what the shortcuts are for opening and saving files, how to find the online help, and so forth. Lisp also has this to a certain degree: It's always clear what constitutes the meaning of an s-expression, namely its car, no matter what language "paradigm" you are currently using. > Toss out the MP3 player and RtCW and there > is more in common. Still, the phrase "practicality beats purity" is > seems appropriate here. > > >>>I firmly believe people can in general easily handle much more >>>complicated syntax than Lisp has. There's plenty of room to >>>spare in people's heads for this subject. >> >>Sure, but is it worth it? > > > Do you have any doubt to my answer? :) No, not really. :) >>Convenience is what matters. If you are able to conveniently express >>solutions for hard problems, then you win. In the long run, it doesn't >>matter much how things behave in the background, only at first. > > > Personally, I would love to write equations on a screen like I > would on paper, with integral signs, radicals, powers, etc. and > not have to change my notation to meet the limitations of computer > input systems. I know people who have even started to use s-expression for mathematical notation (on paper), because they find it more convenient. > For Lisp is a language tuned to keyboard input and not the full > range of human expression. (As with speech.) There is some research going on to extend Lisp even in this regard (incorporating more ways of expression). > (I know, there are people who can write equations in TeX as > fast as they can on paper. But I'm talking about lazy ol' me > who wants the covenience.) > > Or, will there ever be a computer/robot combination I can > teach to dance? Will I do so in Lisp? ?!? >>It seems to me that in Python, just as in most other languages, you >>always have to be aware that you are dealing with classes and objects. >>Why should one care? Why does the language force me to see that when it >>really doesn't contribute to the solution? > > > Hmmm.. Is the number '1' an object? Is a function an object? > What about a module? A list? A class? > > >>>>print sum(range(100)) > > 4950 > > > Where in that example are you aware that you are dealing with classes > and objects? Well, maybe I am wrong. However, in a recent example, a unit test expressed in Python apparently needed to say something like "self.assertEqual ...". Who is this "self", and what does it have to do with testing? ;) >>>>If it's only a syntactical issue, then it's a safe bet that you can add >>>>that to the language. Syntax is boring. >>> >>>Umm... Sure. C++ can be expressed as a parse tree, and that >>>parse tree converted to an s-exp, which can be claimed to be >>>a Lisp; perhaps with the right set of macros. >> >>That's computational equivalence, and that's not interesting. > > > Which is why I didn't see the point of original statement. My > conjecture is that additional syntax can make some things easier. > That a problem can be solved without new syntax does not > contradict my conjecture. If additional syntax makes specific things easier, then in god's name just add it! The loop macro in Common Lisp is an example of how you can add syntax to make certain things easier. This is not rocket science. The point here is that for most languages, if you want to add some syntax, you have to change the definition of the language, extend the grammar, write a parser, extended a compiler and/or interpreter, maybe even the internal bytecode representation, have wars with other users of the language whether it's a good idea to change the language that way, and so forth. In Lisp, you just write a bunch of macros and you're done. No problems with syntax except if you want them, most of the time no problems with changes to the language (far less than in other languages), no messing around with grammars and related tools, no need to know about compiler/interpreter internals and internal representation, no wars with other language users, and so forth. Syntax is boring. ;) >>If it's a good Lisp library I would expect it to work like this: >> >>(with-allocation-from :shared-memory >> ...) >> >>;) >> >>Any more questions? > > > Yes. Got a URL for documentation on a Lisp providing access > to shared memory? OK, I am sorry that I have lost focus here. You have given this example as one that shows what probably cannot not be done in Lisp out of the box. However, most Lisp implementations provide a way to access native code and in that way deal with specific features of the operating system. And there is a de-facto standard for so-called foreign function calls called UFFI that you can use if you are interested in a considerable degree of portability. I don't know a lot about the specifics of shared memory, so I can't comment on your specific questions. > This service is straight-forward to support in C/C++. It > sounds like for Lisp you are dependent on the implementation, > in that if the implementation doesn't support access to its > memory allocator/gc subsystem then it's very hard to > write code for this hardware on your own. It may be > possible to use an extension (written in C? ;) to read/write > to that persistent memory using some sort of serialization, > but that's the best you can do -- you don't have live objects > running from nonvolatile store -- which is worse than C++. This should be possible as a combination of a FFI/UFFI and the CLOS MOP. AFAIK, you can define the memory layout and the allocation of memory for specific metaclasses. However, I really don't know the details. The paper at http://www-db.stanford.edu/~paepcke/shared-documents/mopintro.ps might be interesting. For UFFI, see http://uffi.b9.com/ As Paul Graham put it, yes, there is some advantage when you use the language the operating system is developed in, or it ++. Pascal From tjreedy at udel.edu Wed Oct 29 12:56:43 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 29 Oct 2003 12:56:43 -0500 Subject: On PEP 322 (ireverse) References: <4xQnb.373812$R32.12367046@news2.tin.it> Message-ID: "Raymond Hettinger" wrote in message news:YSSnb.29683$4O1.16000 at nwrdny01.gnilink.net... > [Terry Reedy] > > Any good reason not to make iter so? int, str, and float were once > > bifs also. > > The C code for it has a split path, calling __iter__ for objects that > have it, building iterator wrappers for sequences that don't have > __iter__, or building another wrapper when the inputs are a > function and sentinel. IOW, it is a factory function capable > of constructor any of several different types. Good reason acknowledged. > > I'm +1 on iter.reversed, rescinded. tjr From larry_Goodman at yahoo.com Thu Oct 9 11:19:37 2003 From: larry_Goodman at yahoo.com (Larry goodman) Date: Thu, 09 Oct 2003 11:19:37 -0400 Subject: Python factoids... after 3 three years. References: <8338c7cc.0310070618.41d2544e@posting.google.com> <9qg8ovsl75bsk9nth2k9nrsbbkqfill50h@4ax.com> Message-ID: >I think BlackAdder is a (commercial) good IDE that includes >a usable screen-painter. 1.0 just got out of beta and is right >now suffering a few adjustments/instabilities, admittedly... > yeh i bought the personal version. Bug ridden and it doesnt even have code completion. Its still a good deal though because it does give you a QT/PyQt license. From edi at agharta.de Thu Oct 9 16:54:43 2003 From: edi at agharta.de (Edi Weitz) Date: 09 Oct 2003 22:54:43 +0200 Subject: Python syntax in Lisp and Scheme References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> <92c59a2c.0310031345.57d20631@posting.google.com> <6CZgb.3273$dn6.860@newsread4.news.pas.earthlink.net> Message-ID: <87oewqw2r0.fsf@bird.agharta.de> On 09 Oct 2003 16:25:22 -0400, j-anthony at rcn.com (Jon S. Anthony) wrote: > "Andrew Dalke" writes: > > > Is there a free Lisp/Scheme implementation I can experiment with > > which include in the distribution (without downloading extra > > packages; a "moby" distribution in xemacs speak): > > - unicode > > - xml processing (to some structure which I can use XPath on) > > - HTTP-1.1 (client and server) > > - URI processing, including support for opening and reading from > > http:, file:, and https: > > - regular expressions on both 8-bit bytes and unicode > > - XML-RPC > > - calling "external" applications (like system and popen do for C) > > - POP3 and mailbox processing > > Yes. Allegro CL (ACL) for one. > > > As far as I can tell, there isn't. I'll need to mix and match > > packages > > You obviously can't "tell" too well. It is true that AllegroCL has all these features and it probably is the only CL implementation that includes all of them out of the box but it is not true that it is free (which was one of the things Mr. Dalke asked for). At least it wasn't true the last time I talked to the Franz guys some days ago. If that has changed in the last week please let me know... :) You might be able to get most of these features with "free" CL implementations but not all at once I think. (AFAIK CLISP is currently the only "free" CL which supports Unicode but it is lacking in some other areas.) As far as "mix and match" of packages is concerned: Use Debian (testing) or Gentoo. I've been told it's just a matter of some invocations of 'apt-get install' or 'emerge' to get the CL packages you want. At least it shouldn't be harder than, say, getting stuff from CPAN. What? You don't use Debian or Gentoo? Hey, you said you wanted "free" stuff - you get what you pay for. No, seriously. It'd definitely be better (for us Lispers) if we had more freely available libraries plus a standardized installation procedure ? la CPAN. Currently we don't have that - there are obviously far more people working on Perl or Python libraries. So, here are your choices: 1. Buy a commercial Lisp. I've done that and I think it was a good decision. 2. Try to improve the situation of the free CL implementations by writing libraries or helping with the infrastructure. That's how this "Open Source" thingy is supposed to work. I'm also doing this. 3. Run around complaining that you can't use Lisp because a certain combination of features is not available for free. We have far too many of these guys on c.l.l. 4. Just don't use it. That's fine with me. It currently looks like the number of people choosing #2 is increasing. Looks promising. You are invited to take part - it's a great language and a nice little community... :) Edi. PS: You might also want to look at . From paul at boddie.net Thu Oct 23 05:18:34 2003 From: paul at boddie.net (Paul Boddie) Date: 23 Oct 2003 02:18:34 -0700 Subject: Why Python style guide (PEP-8) says 4 space indents instead of 8 space??? 8 space indents ever ok?? References: <3F970FBF.85974E79@alcyone.com> Message-ID: <23891c90.0310230118.2d3cd8ba@posting.google.com> Erik Max Francis wrote in message news:<3F970FBF.85974E79 at alcyone.com>... > Christian Seberino wrote: > > > I REALLY WANT TO DO MY OPEN SOURCE PYTHON PROJECT > > WITH 8 SPACE IDENTS!!!! > > You don't really think a style guide is going to stop you from doing > that, do you? Keep looking over your shoulder! Only if you expect the (style guide) Spanish Inquisition, will they never show up. That's your only protection if you're an eight spaces heretic. ;-) Paul P.S. Seriously, most people respect the indentation of the project "lead" on open source projects - for example, Webware employs hard tabs throughout its source code, and yet very few people go in and mangle the code with two space indents and other such misdemeanours. Some people claim some kind of inherent superiority with "whitespace insensitive" languages, but I imagine that they are members of that irritating club who go into C++ files and trash the indentation, claiming that "it looks OK in Visual Studio". I suppose that this is another area where Python almost inadvertently encourages more considerate programming practices. From mike420 at ziplip.com Mon Oct 27 11:27:27 2003 From: mike420 at ziplip.com (mike420 at ziplip.com) Date: Mon, 27 Oct 2003 08:27:27 -0800 (PST) Subject: Python is not [yet] Considered Harmful Message-ID: Hannu Kankaanp?? wrote: > mike420 at ziplip.com wrote in message > news:... >> It was an honest mistake, not a troll! Still, I think it should >> be [1, 2, 3] instead of [3, 3, 3] > > I don't think you understand what a troll is. Troll is someone > who posts any of the following: > > 1. "Python is Considered Harmful" (given it's highly readable syntax, > great libraries and high dynamicity, I can't see how a single > feature could make Python 'harmful'. The title could've just been > "Unexpected behaviour of closures inside list comprehensions") > > 2. "I present to you the final and ultimate proof of Python's > brain-damage" (again, a needless attack.. which turned against > yourself though) > > 3. "All this Python bashing is starting to feel like mocking > a retarded child..." (this doesn't need explanation, I hope) This is circular logic. Since no one else yet wrote any of the above, what you are saying is "you are a troll, because troll is you". I don't think you know what troll means, so you use it like an insult ("Boo, you criticized my pet computer language, you are a troll") Nevertheless, let's ask the experts. If only 3 (three!) people from alt.troll say that writing while believing that Python does something very nasty, or, say, (which turned into an interesting discussion, by the way!) makes one a troll, then I'll stop :-( {F-up2 alt.troll only is OK. I never read that newsgroup, but I'll check the responses (and who they are from, if negative) in a few days} From lbates at swamisoft.com Fri Oct 31 15:19:10 2003 From: lbates at swamisoft.com (Larry Bates) Date: Fri, 31 Oct 2003 14:19:10 -0600 Subject: Image recognition + python + pil References: Message-ID: "Noen" wrote in message news:yphob.23929$BD3.4492365 at juliett.dax.net... > Hi. > > I wondered if anyone had any experience with text recognition using > python. Any sites I could be pointed to... ideas... etc? > From jkrepsBEAR at FISHneb.rr.com Fri Oct 31 23:11:46 2003 From: jkrepsBEAR at FISHneb.rr.com (GrayGeek) Date: Fri, 31 Oct 2003 22:11:46 -0600 Subject: import cx_Oracle References: <3fa32966$0$1118$6c56d894@feed0.news.be.easynet.net> Message-ID: Bernard Delm?e wrote: >> It gives me an error about being unable to find the OCISetDefault entry >> point in 'oci.dll'. > > cx_Oracle works on top of the regular oracle client, which you'll > need to install before it works. The OCI libraries are part of that. I have it installed, and have used it to create webpages using Oracle's HTP.P function, and I also accessed tables on the Oracle9 server from JDev9 and from PLSQLDeveloper. The oci.dll is in the Oracle Home/dll directory. As my first post indicated, cx_Oracle is able to see oci.dll, it just can't communicate with it properly. ??? -- - GrayGeek From http Fri Oct 3 12:21:07 2003 From: http (Paul Rubin) Date: 03 Oct 2003 09:21:07 -0700 Subject: Python syntax in Lisp and Scheme References: Message-ID: <7xzngipa18.fsf@ruckus.brouhaha.com> Oren Tirosh writes: > Implementing Python-like syntax in LISP or even a full Python > implementation in LISP would be a worthwhile goal (LPython?). BTW, this > kind of implementation is one of the relatively few programming tasks > that can benefit greatly from macros. The Python semantics can be mostly > done using macros and a preprocessor would translated Python syntax to > s-expression code that uses those macros. If done straightforwardly, the language semantics would end up different from Python's in a few ways. For example, strings in most Lisp systems are mutable. Also, Python's class system doesn't map onto Lisp all that well; Python's variable-scoping rules are bizarre, and so forth. I think the result would still be worth doing but it would be a further departure from CPython than, say, Jython is. From ulysses_dm at yahoo.com.cn Sun Oct 12 12:02:42 2003 From: ulysses_dm at yahoo.com.cn (ulysses) Date: 12 Oct 2003 09:02:42 -0700 Subject: [pyqt] Can't show QString textLabel in windows 98 GUI program References: <43e3984e.0310022037.69f90013@posting.google.com> Message-ID: <43e3984e.0310120802.d1eb287@posting.google.com> ulysses_dm at yahoo.com.cn (ulysses) wrote in message news:<43e3984e.0310022037.69f90013 at posting.google.com>... I mean this program can show textlabel,capion in Win2000,winxp. Because I use __tr() to translate multilanguage. qApp.translate("Form",s,c) return a QString Object. it's a unicode codec. I can't show it in Windows 98. Anyone can help me. I crazy for it. thanks million. My freeware bittorrent download tools build by PYQT 3.8. www.turbobt.com Ulysses From bradd+news at szonye.com.invalid Sun Oct 26 04:51:56 2003 From: bradd+news at szonye.com.invalid (Bradd W. Szonye) Date: Sun, 26 Oct 2003 09:51:56 GMT Subject: Whoa! Do Python and Lisp really have LAMBDA ? References: Message-ID: > (setf flist (loop for i from 0 to 2 > collect (lambda (x) (+ x i)))) > (loop for f in flist > collect (funcall f 1)) > > I got (4 4 4). Yes, that is suprising, although it makes more sense once you realize that they all bind to the same i, which is mutated during the loop. > I'm sure Haskell does this right. What about Scheme and ML? The equivalent in Scheme (named let) introduces a new binding with each iteration, so it does what you expect. (define flist (let loop ((i 0) (r '())) (cond ((> i 2) (reverse r)) (else (loop (+ 1 i) (cons (lambda (x) (+ x i)) r)))))) (let loop ((l flist) (r '())) (cond ((null? l) (reverse r)) (else (loop (cdr l) (cons ((car l) 1) r))))) Unlike the Lisp version of flist, the Scheme loop binds a new i for each iteration. Therefore, each closure has its own i. My Scheme version is much wordier than the Lisp version above. Perhaps the more experienced schemers can show you a less verbose version that still does what you want. I've always been fond of functional languages, but I've only recently had the chance to work with them extensively, so I'm still learning. -- Bradd W. Szonye http://www.szonye.com/bradd My Usenet e-mail address is temporarily disabled. Please visit my website to obtain an alternate address. From dokaspar at student.ethz.ch Thu Oct 16 09:29:19 2003 From: dokaspar at student.ethz.ch (Dominik Kaspar) Date: 16 Oct 2003 06:29:19 -0700 Subject: console output delay Message-ID: <62e9c66e.0310160529.7774f6bd@posting.google.com> hello, my question concerns the following code fragment: print "searching for bla bla...", [long calculation] print "found", numberofblablas when this program is running, the "please be patient message" is not displayed until the long calculation has actually completed. is there any way to force the first print statement to be shown on the console? dominik From jim.potts at sbcglobal.net Thu Oct 2 15:48:42 2003 From: jim.potts at sbcglobal.net (Jim Potts) Date: Thu, 02 Oct 2003 19:48:42 GMT Subject: Reading Windows (NT/2000/XP) system and user environment variables Message-ID: What is the best way in Python version 2.x to read/get Windows (nt/2000/xp) system and user environment variables? Thanks for the help! jep From oest at soetu.eu Thu Oct 16 09:12:13 2003 From: oest at soetu.eu (Carlo v. Dango) Date: Thu, 16 Oct 2003 15:12:13 +0200 Subject: run time code generation in python References: Message-ID: On Thu, 9 Oct 2003 11:08:36 -0700, Robert Brewer wrote: > "Carlo v. Dango" wrote in > news:Xns940F929A63B436020206 at 172.16.0.1: > >> >> Hello there. I have found a need to runtime generate a method and >> instert it into an object instance. The code is a simple forwarding >> mechanism like > You can obtain the magic binding to self with the "new" module's > instancemethod() function. > > cf. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/198078 sounds great! many thanks, will have a look at it. I assume that such a representation uses less memory than adding a function (an object, right?) to an instance... -carlo -- Using M2, Opera's revolutionary e-mail client: http://www.opera.com/m2/ From a.schmolck at gmx.net Tue Oct 28 10:58:39 2003 From: a.schmolck at gmx.net (Alexander Schmolck) Date: 28 Oct 2003 15:58:39 +0000 Subject: Python from Wise Guy's Viewpoint References: <6dnq61-kl.ln1@ID-7776.user.dfncis.de> <87oew33h8t.fsf@sidious.geddis.org> <3F9D5D21.2060408@ps.uni-sb.de> <20031027184024.GO1454@mapcar.org> Message-ID: Marcin 'Qrczak' Kowalczyk writes: > Python and Ruby get it wrong: the result is an integer (truncated > division), very different from the result of / on the same numbers > represented in a different type. It's being fixed since python >= 2.2 (sort of): >>> from __future__ import division >>> 1/3 0.33333333333333331 >>> 5//2 2 'as From hans at zephyrfalcon.org Mon Oct 6 21:20:24 2003 From: hans at zephyrfalcon.org (Hans Nowak) Date: Mon, 06 Oct 2003 21:20:24 -0400 Subject: Python syntax in Lisp and Scheme In-Reply-To: References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> <92c59a2c.0310031345.57d20631@posting.google.com> Message-ID: <3F8214D8.1010400@zephyrfalcon.org> Alex Martelli wrote: > [...] Fortunately, in either case, the rich > and stong suite of unit tests that surely accompanies such a > "mission-critical application" will easily detect the nefarious > deed and thus easily defang the nanoviruses' (nanovirii's? nanovirorum...?) > menace, [...] Hmm, if I recall correctly, in Latin the plural of 'virus' is 'virus'. (I like to write 'virii' myself, knowing that it's wrong, but it looks cute. :-) -- Hans (hans at zephyrfalcon.org) http://zephyrfalcon.org/ From RobMEmmons at cs.com Mon Oct 6 20:31:53 2003 From: RobMEmmons at cs.com (RobE) Date: Mon, 06 Oct 2003 19:31:53 -0500 Subject: Newbie needs to see a large project References: <9Clgb.12141$sw6.8259@newssvr25.news.prodigy.com> Message-ID: > Hi everyone, > I have been checking Python recently and have presented what little I > know to mangement. They have asked if there is any large business apps > (like an accounting system) using python and what the performance is > like. We would be running on Linux with a large database (maybe > postgres or mysql) of 3-5 Gbytes. We would be moving from a windows > platform(foxpro apps) to Linux (python). About 50 users total. Thanks > in advance.... I'll say I'm no expert with databases, but I have played with a 5 GB stock database on Postgres with python for my personal use. The comments I would make are: * Yes you can do it. * Good thing (and bad thing) is that most of the speed issues will probably be on the database side. You need to think carefully about how you setup the tables and indexes in your database and you need enough computing horsepower to handle the queries your users are going to do throw at it. Complicated queries on large databases can be very time consuming, but it all depends on number of records and indexing you use. * On the python side--be aware that python data storage is not particularly efficient in terms of memory. As an example, in my stock database an easy way to loadup the daily data would have been to load all 30000 symbols for the day at a time and then send it to the database--if you define this using classes--it's huge, if you do it as a sequence of tuples then it's much smaller--just keep this in mind if your doing a lot of data--who you store it in python can matter. You only need to consider this if you find your using a lot of memory and need to track down why. * Other thing I would suggest -- figure out where the real processing needs to be done--if your just handling small amounts of data with the python clients--then it should not be a problem. If it's large than you'll have to experiment--python is still interpretivie on one hand--on the other for large amounts of data your queries (on the database side) may still be the limiting factor. Also keep in mind if you need to you can extend python with C code if you have to get speed. There is also "good" and "bad" python code--so be creative. * Python can be used for large programs -- I've written a 10000 line python program without difficulty. The other two common scripting langauges out there are PHP and Perl. I don't know much about these, but I heard people say you'd never write large Perl code like this. PHP I don't know...people do use this for web/db work a lot. Incidently, the python active content web solution is Zope... but I'm not a web guy so I don't know anything about it. * I don't know how much you've done with databases--but a reminder. Have a backup plan. You can't just run tar over a running database and get a restorable backup--you'll need to dump the database using whatever procedure postgres has for this and then backup the static dump. * Incidently: The reason I use python myself is that it has a large application range--it can do everything from quick tools to full up applications, to active web content. Pretty flexible. Just some food for thought. Rob From CousinStanley at hotmail.com Fri Oct 24 15:38:13 2003 From: CousinStanley at hotmail.com (Cousin Stanley) Date: Fri, 24 Oct 2003 12:38:13 -0700 Subject: Trailing comma (was: Re: structure in Python) References: <3F95585C.3EDF3364@engcorp.com> <653b7547.0310231853.215189da@posting.google.com> Message-ID: | ... | the best reason to consistently use trailing commas | is how a CVS (or other) diff will look later. | You can either see one deleted line plus two added lines, | or a single added line, your choice. Patrick .... Thanks for the info .... I'm not currently using versioning tools as I'm only a single developer and most of my code at this point is very simple and a backup copy or two usally work OK for me .... However, I will keep this in mind for the future .... -- Cousin Stanley Human Being Phoenix, Arizona From aleax at aleax.it Fri Oct 17 05:01:11 2003 From: aleax at aleax.it (Alex Martelli) Date: Fri, 17 Oct 2003 09:01:11 GMT Subject: Language selection for new projects References: Message-ID: Limey Drink wrote: > Alex, I don't know how you find the time to write such detailed replies > :-) but they're very welcome. Glad to be of help. > I have the book Learning Python, I think its an excellent book for > learning the core language but I have noticed on the O'reilly website a > 2nd Edition being released in December. > > Has the core of the language changed very significantly from the version > covered in the first edition of Learning Python ? Yes, the current Python (2.3) is substantially larger, even at its "core", than the 1.5.2 version described in the current (old) edition of "Learning Python". The effect of some additions has been to marginalize idioms and techniques previously prominent. In particular, list comprehensions have further marginalized lambda, map, reduce, filter; the apply built-in is basically obsolete thanks to the *args and **kwds forms of argument passing in function calls; nested lexical scopes make the good old idea of "foo=foo" ``default arguments'' used for name injection into inner scopes somewhat quaint and of little practical interest; ... Not to mention the reorganization of OO into "new-style classes", a much clearer and simpler systematization than the "classic classes" that also remain in the language (and indeed are the default, for backwards compatibility). To teach the language today, one does not want to dwell on the way the language was five years ago, and on features that remain in the language just because of backwards compatibility constraints. The parts of the language that you should normally use in writing new code are in fact no larger than the ones you should have used in Python 1.5.2 -- but they ARE different to some measurable extent, say (hard to gauge) with some 75% overlap and 25% difference. One day, when we can break _some_ backwards compatibility -- presumably at the release of 3.0, maybe 3 years from now -- many of the "just backwards compatiiblity" ideas will be deprecated or removed; Guido van Rossum is on record as saying that 3.0 will be about simplification and getting back to "one obvious way to do it", removing "legacy", backwards-compatibility-only stuff. > Would you mind if I email you in the future if I am really stuck witha > problem ? looool :-) Actually, I would: I prefer to discuss things on the newsgroup, since this way one gets the benefit of multiple voices. No single "expert" has ALL the answers (not even me, nach!), and the give-and-take of debate here often proves more productive than just getting some single oracular response would. Further, discussion here can benefit others beyond the single person who's posing a question, so there are larger returns for the same amount of effort. Alex From adalke at mindspring.com Wed Oct 1 16:30:01 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Wed, 01 Oct 2003 20:30:01 GMT Subject: can i implement virtual functions in python ? References: <3c91a864.0309301332.3483a61@posting.google.com> <3c91a864.0310011206.381249a0@posting.google.com> Message-ID: Me: > > However, I do use NotImplementedError so the exception > > which percolates up is more obvious than AttributeError. It also > > allows me to put in a docstring describing the interface requirements > > of derived classes. logistix at cathoderaymission.net: > Either using hasattr or or a try...except clause gets a little clunky. > I'd just rather do something like: > > class abstract: > def a(self): raise NotImplementedError("Virtual Method") > def b(self): raise NotImplementedError("Virtual Method") > def c(self): raise NotImplementedError("Virtual Method") Well, I agreed with you ;) I think this is the right way, and it lets you include a docstring to describe the interface better. Andrew dalke at dalkescientific.com From amk at amk.ca Thu Oct 9 21:27:49 2003 From: amk at amk.ca (A.M. Kuchling) Date: Thu, 09 Oct 2003 20:27:49 -0500 Subject: Python syntax in Lisp and Scheme References: <92c59a2c.0310031345.57d20631@posting.google.com> <8CVgb.8$KR3.1846@typhoon.nyu.edu> Message-ID: <9J-dneXG4vKIlhuiRTvU2Q@speakeasy.net> On Thu, 09 Oct 2003 20:56:01 GMT, Andrew Dalke wrote: > or not. The similar statement which bristles me the most is at the > top of biolisp.org, ... Yee-*ouch*. For those not reading the site: it modifies an aphorism from Henry Spencer to "Those who do not know Lisp are condemned to reinvent it.... poorly," and hyperlinks it to biopython.org. Tacky. Sheesh, the Perl/Python squabbling has pretty much died down these days; maybe they missed the memo. --amk From a at a.invalid Wed Oct 22 02:59:23 2003 From: a at a.invalid (Timo Virkkala) Date: Wed, 22 Oct 2003 09:59:23 +0300 Subject: Trailing comma In-Reply-To: References: Message-ID: Georgy Pruss wrote: > "Timo Virkkala" wrote in message news:bn415p$u9s$1 at nyytiset.pp.htv.fi... > Another "solution" is just to look at the previous line and check if it has the comma > or not. You'd better get a habit to THINK and not do things mechanically, as others > suggest. Yeah, that's what I have done thus far. =) I don't know.. I can't recall ever being burned by forgetting a comma.. Whereas I do remember a couple of occasions where I've included a trailing comma where I shouldn't have (SQL). -- Timo Virkkala From dave at 3dex.com Wed Oct 8 20:54:14 2003 From: dave at 3dex.com (Dave Benjamin) Date: Thu, 09 Oct 2003 00:54:14 GMT Subject: Code block literals In-Reply-To: References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> <92c59a2c.0310031345.57d20631@posting.google.com> Message-ID: Sean Ross wrote: >>Yeah, wasn't something like that up on ASPN? That's an interesting >>trick... are you sure it's not supposed to be "property(*aprop())" >>though? (who's being pedantic now? =) > > Hi. > > The idiom/recipe is at > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/205183 Thanks, Sean. From tfb at firestorm.OCF.Berkeley.EDU Mon Oct 6 18:13:36 2003 From: tfb at firestorm.OCF.Berkeley.EDU (Thomas F. Burdick) Date: 06 Oct 2003 15:13:36 -0700 Subject: Python syntax in Lisp and Scheme References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> <92c59a2c.0310031345.57d20631@posting.google.com> <36wr81qfxg9.fsf@chagall.ti.uni-mannheim.de> <8665j2k4hf.fsf@raw.grenland.fast.no> Message-ID: David Rush writes: > On Mon, 06 Oct 2003, Raymond Wiker wrote: > > Matthias writes: > >> (In certain cases macros) can easily be misused. > ... > >> You have to know if you want a sharp knife (which may hurt you when > >> misused) or a less sharper one (where it takes more effort to cut > >> with). > > > > It is easier to hurt yourself with a blunt knife than a sharp > > one. > > Actually I've noticed that I usually cut myself when I *switch* from > a dull knife to a sharp one. I don't think the truism about cutting yourself with dull vs sharp knives means to say anything about superficial cuts. You don't lop your finger off with a sharp knife, because you're handling it carefully. With a dull knife, your best bet is to put your weight behind it; that's also a good way to lose a finger / dump core. -- /|_ .-----------------------. ,' .\ / | No to Imperialist war | ,--' _,' | Wage class war! | / / `-----------------------' ( -. | | ) | (`-. '--.) `. )----' From n17999950.temp.werner at neverbox.com Thu Oct 23 07:44:06 2003 From: n17999950.temp.werner at neverbox.com (Werner Schiendl) Date: Thu, 23 Oct 2003 13:44:06 +0200 Subject: closed source In-Reply-To: References: <3F968833.C1F4A1FF@engcorp.com> Message-ID: <3f97bedb$1@brateggebdc5.br-automation.co.at> Hi, Milos Prudek wrote: > > Is this protection implementable? > Some points that come to mind. Personally I think C is still harder to decompile than Python (or for that matter any VM based language like Java or .NET IL). The reason is, that these VMs usually have much higher level constructs than plain x86 assembly language (create object, access member, etc. have their own opcode) So you could write an extension module containing some part of the logic and also the protection algorithm. Having only the protection in the C extension is counter-productive, as it makes it even simpler to crack. So be sure to add some logic vital to your application here. Another point would be that I'd use some sort of strong encryption for the key, similar to PGP signed mail messages. This does not prevent actually cracking the software, but it's close to impossible to write a key generator for it. In addition, be sure to add the licensee's name in plain text in the licence - nobody will give away such a license file, right? Anyway you should be aware of what the other's in this thread said: there is no real way of protection *except* not giving the software out of your hands (i. e. make it a web service and only hand out a client). hth Werner From peter at engcorp.com Tue Oct 14 12:54:21 2003 From: peter at engcorp.com (Peter Hansen) Date: Tue, 14 Oct 2003 12:54:21 -0400 Subject: threading.Timer newbie question References: Message-ID: <3F8C2A3D.570643BB@engcorp.com> berklee just berklee wrote: > > When you call a timer, like in the documentation: > def hello(): > print "hello, world" > > t = Timer(30.0, hello) > t.start() # after 30 seconds, "hello, world" will be printed > Does the thread get destroyed after the task is done? I mean, if I set up an > ongoing monitor and use timers to watch over jobs, do I have to worry about > thread management? The best way to answer such questions is to check the source (in threading.py). In this case, in threading._Timer(), you can see that the run() method simply waits for the required amount of time, calls the function, calls .set() on the Event object it holds, then finishes. Since _Timer is simply a subclass of _Thread, you can count on it behaving the way a regular thread would (which is, it will be destroyed, assuming regular threads get destroyed on your platform...). -Peter From adalke at mindspring.com Wed Oct 22 15:34:40 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Wed, 22 Oct 2003 19:34:40 GMT Subject: Python from Wise Guy's Viewpoint References: <_8Ekb.7543$pT1.318@twister.nyc.rr.com> Message-ID: Pascal Costanza: > ...because static type systems work by reducing the expressive power of > a language. It can't be any different for a strict static type system. > You can't solve the halting problem in a general-purpose language. > > This means that eventually you might need to work around language > restrictions, and this introduces new potential sources for bugs. Given what I know of embedded systems, I can effectively guarantee you that all the code on the rocket was proven to halt in not only a finite amount of time but a fixed amount of time. So while what you say may be true for a general purpose language, that appeal to the halting problem doesn't apply given a hard real time constraint. Andrew dalke at dalkescientific.com From eppstein at ics.uci.edu Thu Oct 9 22:10:18 2003 From: eppstein at ics.uci.edu (David Eppstein) Date: Thu, 09 Oct 2003 19:10:18 -0700 Subject: Python syntax in Lisp and Scheme References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> <6CZgb.3273$dn6.860@newsread4.news.pas.earthlink.net> <3F853D60.9E133724@setf.de> <3F85CEC3.D17BE65E@setf.de> Message-ID: In article , Pascal Costanza wrote: > It's probably just because the Common Lisp community is still relatively > small at the moment. But this situation has already started to improve a > lot. It's only been out, what, twenty years? And another twenty before that for other lisps... How much time do you think you need? -- David Eppstein http://www.ics.uci.edu/~eppstein/ Univ. of California, Irvine, School of Information & Computer Science From james.anderson at setf.de Tue Oct 7 12:54:41 2003 From: james.anderson at setf.de (james anderson) Date: Tue, 07 Oct 2003 18:54:41 +0200 Subject: Python syntax in Lisp and Scheme References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> <92c59a2c.0310031345.57d20631@posting.google.com> Message-ID: <3F82EF06.F3D7A10@setf.de> Matthias Blume wrote: > > raffael at mediaone.net (Raffael Cavallaro) writes: > > ... > > Two words: code duplication. > ... > > Three words and a hyphen: Higher-Order Functions. > > Most of the things that macros can do can be done with HOFs with just > as little source code duplication as with macros. (And with macros > only the source code does not get duplicated, the same not being true > for compiled code. With HOFs even executable code duplication is > often avoided -- depending on compiler technology.) is the no advantage to being able to do either - or both - as the occasion dictates? i'd be interested to read examples of things which are better done with HOF features which are not available in CL. sort of the flip-side to the example of compile-time calculation and code generation. taking into account that generic functions are, at least to some extent, the equivalent of value-domain macro-expansion. ? From indigomoon at bonbon.net Wed Oct 1 01:31:07 2003 From: indigomoon at bonbon.net (Indigo Moon Man) Date: Tue, 30 Sep 2003 23:31:07 -0600 Subject: py2exe dll file Message-ID: The .dll file that py2exe creates to go with the program is huge even for a small program. Is there any way to possibly optomize the .dll file to make it smaller? -- Audio Bible Online: http://www.audio-bible.com/ From hs at heaven.nirvananet Wed Oct 15 23:19:39 2003 From: hs at heaven.nirvananet (Hartmann Schaffer) Date: 15 Oct 2003 23:19:39 -0400 Subject: Express What, not How. References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> <92c59a2c.0310031345.57d20631@posting.google.com> Message-ID: <3f8e0e4b@news.sentex.net> In article , Raffael Cavallaro writes: >> A programmer accustomed to the >> functional style finds the need in non-FP languages to name every >> function analogously awkward. > > No one is talking about need, but about clarity of exposition. which is essentially a style question, which usually don't have absolute answers > It is perfectly possible to program functionally in lisp, as I'm sure > you know. It just makes code less readable to use _anonymous_ functions. > Code is no less functional when the functions are named. this would largely depend on the function. e.g. i don't see any benefit in adding function definitions to add 2 or multiply by 3 instead of using anonymous functions (defun add2 (x) (+ x 2)) ... many lines / pages/ screenloads of code (map 'list #'add2 list) doesn't look any more expositive to me than (map 'list (lambda (x) (+ x 2)) list), quite to the contrary. there are enough cases where you need something like this. obviously, you can abuse this > ... > Anonymous functions force the _how_ to be interleaved with the _what_, > breaking up the clarity of the _what_. Named functions (and macros) > allow the high level abstractions to be expressed in terms of _what_ is > happening, without unnecessary reference to _how_. > > Anonymous functions force the reader to deal with _how_ precisely > because there is no descriptive name that expresses _what_ the funtion > does. This is an inappropriate conflation of two distinct purposes, that > can and should be separated in source code. the problem with your position is that you make a dogma out of a generally useful observation hs -- ceterum censeo SCO esse delendam From carel.fellinger at chello.nl Mon Oct 13 17:45:52 2003 From: carel.fellinger at chello.nl (Carel Fellinger) Date: Mon, 13 Oct 2003 23:45:52 +0200 Subject: Speaking Python In-Reply-To: References: Message-ID: <20031013214552.GA11802@mail.felnet> On Mon, Oct 13, 2003 at 04:02:37PM -0400, David Mertz wrote: ... > So quick test, how do you say: without being able to test it and lacking thourough thinking I would use at least a two pitched voice and use the lower pitched voice to pronounce keywords, punctuation and numbers, whereas the slightly higher pitched voice would be used for all other items. Ofcourse indentation shouldn't be pronounced as a series of spaces, but as an indentation level. Likely uninformative things like token separating spaces and newlines prior to indents and dedents can be omitted most of the time:) Triple quotes (''') and triple double quotes (""") should be pronounced as: low: triple quote low: triple double quote And some might prefer tricks like: >>> SomeUglyIdentifier low: camelcased high: some ugly identifier # distinctive short pauses between words >>> some_other_identifier low: underscore separated high: some other identifier # distinctive short pauses between words >>> __identifier low: privat high: identifier Maybe using pitches is no good, as pitch in western languages is used to help manage larger sentences. I choose it as it seemed (on first thought) less distracting then the obvious alternative of using two distinct voices. A simple user test would clear this up, though. > def range_sum(N): low: indent level zero def high: range low: underscore high: sum low: paren open uppercase high: n low: paren close colon # newline prior to indent omitted > if N < 0: low: indent if uppercase high: n low: less then zero colon # newline prior to indent omitted > return None low: indent return camelcase high: none # newline prior to dedent omitted > elif N == 1: low: dedent elif uppercase high: n low: equals one colon # newline prior to indent omitted > return 1 low: indent return 1 # newline prior to dedent omitted > else: low: dedent else colon # newline prior to indent omitted > tot = 0 low: indent high: tot low: becomes zero newline > for n in range(1,N+1): low: for high: n low: in high: range low: paren open 1 comma uppercase high: N low: plus 1 paren close colon # newline prior to indent omitted > tot += n low: indent high: tot low: augmenting plus # or simply: plus becomes? high: n # newline prior to dedent omitted > return tot low: dedent return high: tot low: newline -- groetjes, carel From adalke at mindspring.com Thu Oct 9 16:19:09 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Thu, 09 Oct 2003 20:19:09 GMT Subject: Python syntax in Lisp and Scheme References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> <92c59a2c.0310031345.57d20631@posting.google.com> <3F85A6E4.3050402@nospam.com> Message-ID: <1pjhb.4408$dn6.1383@newsread4.news.pas.earthlink.net> Doug Tolton: > I have this personal theory (used in the non-strict sense here) that > given enough time any homogenous group will split into at least two > competing factions. Reminds me of Olaf Stapledon's "First and Last Men"? His civilizations often had two roughtly equal but opposing components. Also reminds me of learning about the blue eyed/brown eyed experiment in my sociology class in high school. As it turns out, I was the only blue-eyed person in the class of 25 or so. :) > Over time it seems to me that human > beings are incapable of remaining as one single cohesive group, rather > that they will always separate into several competing factions. Or at > the very least groups will splinter off the main group and form their > own group. Not necessarily "competing", except in a very general sense. Is Australian English in competition with Canadian English? > However in the opensource world I expect splinters to happen frequently, > simply because there is little to no organizational control. Even > Python hasn't been immune to this phenomenon with both Jython and > Stackless emerging. As well as PyPy and (more esoterically) Vyper. Excepting the last, all have had the goal of supporting the C Python standard library where reasonably possible. When not possible (as the case with Jython and various C extensions), then supporting the native Java libraries. > "bristly" ;) Ohh! Good word! I had forgotten about it. Andrew dalke at dalkescientific.com From peter at engcorp.com Fri Oct 17 18:00:32 2003 From: peter at engcorp.com (Peter Hansen) Date: Fri, 17 Oct 2003 18:00:32 -0400 Subject: Trivial performance questions References: <3F902E8E.3D201BC3@engcorp.com> Message-ID: <3F906680.BB90A8AD@engcorp.com> Geoff Gerrietts wrote: > > Quoting Peter Hansen (peter at engcorp.com): > > > > Not unless you add Alex' constraint that the two alternatives under > > consideration are equally readable. Otherwise the less readable one > > is always going to cost you more at maintenance time. > > Yes to your first sentence, not so sure to the second. The implication > is the code will always be touched, and my contention is that if you > don't pay at least trivial attention to writing something optimal -- > includes avoiding geometric algorithms -- then you're significantly > increasing the amount of maintenance work necessary. I won't disagree with most of that (we're rapidly reaching near total agreement here! :-) but I do think that assuming "the code will always be touched" is a very healthy attitude, in the same way you think that at least trivial attention to performance is a healthy attitude. We certainly have code that hasn't been touched during maintenance, but nobody could have predicted which areas of the code that would be. > Capitalism has bred a real reliance on "good enough": when you hit > your payoff point, you don't go any farther. It's a useful metric to > apply, but a dangerous premise to base all your decisions on. "Good > enough" needs to be critically evaluated for both the short term and > the long term. As an XP team, we tend to consider that critical evaluation to be the domain of the customer, so we basically don't worry about it until there is feedback that we're doing the wrong thing. This, in cooperation with the customer, makes the best use of the our resources (for which the customer is paying, in effect). But, yeah, that's just the XP view of things. > A half-million micro-optimizations may not pay for themselves Phew! I seriously hope your group hasn't examined that many pieces of code with performance concerns in mind! We don't have even that many lines of code, let alone areas that could be micro-optimized. > individually. But in the long term, when confronted with a total > system rewrite because the collected work can no longer perform > adequately, and standard optimization techniques have met with > diminishing returns, you're going to regret not having paid attention > the first time through, There's some truth in that, but I can't shake the nagging feeling that simply by using Python, we've moved into a realm where the best way to optimize a serious problem area is to rewrite in C or Pyrex, or get a faster processor. (Like you, I can be persuaded, but this is what _my_ experience has taught me.) > > http://c2.com/cgi/wiki?MakeItWorkMakeItRightMakeItFast > > It's an interesting formulation but it stinks of propaganda to me. > When generic catchphrases are re-interpreted by almost every viewer > its a pretty fair bet they're not precise enough to be really useful. > The discussion on this page makes me think of Biblical scholars > debating the meaning of ambiguous passages. Actually, it's probably just that re-interpretation and discussion which proves so very useful, not the phrase itself. Like a Zen koan or something, it's too short (or ambiguous) to have direct, hard meaning, but the meme it carries is a valuable one with which to be infected. ;-) The same probably holds true about ambiguous biblical passages, I hate to admit. > My group has invested probably something like 15 person-years writing > Python code in the last few years. We have probably put about one of > those person years into trying to account for performance bottlenecks. > Management is presently of the opinion that a drastic rewrite is the > only way to resolve the remaining issues. Perhaps the most distinct > difference between your group and mine is that many of our developers > are fairly novice, and prone to select solutions that are not > well-informed about performance issues and algorithm complexity. On > the other hand, maybe our code is just more heavily used? I'd vote for the latter. My group has been heavily junior in flavour. Perhaps another cause of the difference is our greater (?) emphasis on XP and test-driven development? I doubt anyone could say, but for sure your code is more heavily used. I don't even need to know what it does to say that. :-) Maybe one example: we used += with strings a lot in the early days. Partly junior developers, a greater part due to inexperience with Python. I think only one or two bits of our code has been re-written to use [].append() and ''.join() instead, because only those bits came to the fore when performance was an issue. The rest is still merrily chewing up CPU time doing wasteful += on strings, but nobody cares. We refactor that (for consistency, mainly, I think) when we get to them for other reasons, and new code probably doesn't use += so much, but that's about the extent of it. > At first blush, I thought "maybe there's an equilibrium that needs to > be found". But I don't think so now. I think it's important for > younger (intermediate?) developers to be obsessed with performance, so > they can learn the dangers of bad algorithms, how to recognize them, > how to avoid them. And it's worth building good habits where you > choose an optimal idiom rather than a slower one. I would agree that new developers would benefit from that kind of experience. One of the few reasons why a (good) university or college education can be of value to a programmer. So can critical reading of some decent books or web pages on the topic. > You can disagree, but I've done a lot of reading and thinking on the > matter, in part because my experience and my beliefs have been at odds > in the past. Consequently, you're going to hafta try harder than > invoking the divine authority of Kent Beck (or even Knuth!) to > persuade me. Still, I can yet be persuaded; my mind is quite > tractable. I think Kent is merely on a par with the Pope, but is not Himself divine. ;-) Knuth is another story, perhaps. :-) -Peter From pf_moore at yahoo.co.uk Tue Oct 21 16:16:06 2003 From: pf_moore at yahoo.co.uk (Paul Moore) Date: Tue, 21 Oct 2003 21:16:06 +0100 Subject: Unittest - How do I code lots of simple tests Message-ID: One of the things I really dislike about Unittest (compared, say, to a number of adhoc testing tricks I've used in the past, and to Perl's "standard" testing framework) is that the testcase-as-a-class model tends to imply a relatively high granularity in testing. A good example of this comes from "Dive Into Python" (http://diveintopython.org) section 7.3. Here, the author has written a module which converts numbers to Roman numerals. The test case is then class KnownValues(unittest.TestCase): knownValues = ( (1, 'I'), ... # 50-plus specific cases def testToRomanKnownValues(self): """toRoman should give known result with known input""" for integer, numeral in self.knownValues: result = roman.toRoman(integer) self.assertEqual(numeral, result) Now, to my mind, the big problem here is that this *isn't* one test, but rather 50 (or more). OK, the same checks are done if everything succeeds, but 1. If a test fails, the rest are skipped! If there's a pattern to the failures (the code handles numbers ending in 4 and 9 wrongly, for example) it's much easier to find if all of the checks are reported. 2. Psychologically, "52 tests succeeded" is a much bigger boost than "1 test succeeded" (albeit this test covered 52 cases). And it's not just psychology - we really *did* test 52 distinct conditions. The only way I can see of producing the "true" number of tests is via some form of ugly hack like test_values = ((1, 'I'), ...) class KnownValues(unittest.TestCase): pass for arabic, roman in test_values: def test(self): result = roman.toRoman(arabic) self.assertEqual(roman, result) setattr(KnownValues, 'test_%s_%s' % (arabic, roman), test) But I can't really see that as the "right approach". Can anyone suggest a more reasonable way of running this sort of table-driven test via unittest? Maybe I should use doctest instead, but to be honest, I prefer the overall infrastructure of unittest (for real tests). It's just this particular issue that really bugs me... Paul. -- This signature intentionally left blank From jjl at pobox.com Sat Oct 4 12:26:31 2003 From: jjl at pobox.com (John J. Lee) Date: 04 Oct 2003 17:26:31 +0100 Subject: Web-crawling References: Message-ID: <87k77l2clk.fsf@pobox.com> "John Bradbury" writes: > "Rene Pijlman" wrote in > message news:bretnvcng69nqpoeug71jon4obs0moe63f at 4ax.com... > > John Bradbury: > > >I am trying to develop a special putpose crawler using htmllib & urllib. > > >How do you tell the server application that you are a modern browser > > >and can handle frames? [...] > > server would care, but you could mimic the User-agent header sent by a [...] > I don't know what is causing the problem, but the site I am accessing is > sending out forms for a browser that has a low resolution and does not > support frames. Excuse my ignorance, but where do you set up the > User-agent header you suggested. For urllib2 (well, almost): http://wwwsearch.sourceforge.net/ClientCookie/doc.html#headers John From pruebauno at latinmail.com Wed Oct 8 00:00:10 2003 From: pruebauno at latinmail.com (nnes) Date: 7 Oct 2003 21:00:10 -0700 Subject: Newbie needs to see a large project References: <9Clgb.12141$sw6.8259@newssvr25.news.prodigy.com> Message-ID: John Fabiani wrote in message news:<9Clgb.12141$sw6.8259 at newssvr25.news.prodigy.com>... > Hi everyone, > I have been checking Python recently and have presented what little I know > to mangement. They have asked if there is any large business apps (like an > accounting system) using python and what the performance is like. We would > be running on Linux with a large database (maybe postgres or mysql) of 3-5 > Gbytes. We would be moving from a windows platform(foxpro apps) to Linux > (python). About 50 users total. Thanks in advance.... http://www.gnuenterprise.org Maybe? From alan.gauld at btinternet.com Thu Oct 9 14:13:54 2003 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 09 Oct 2003 18:13:54 GMT Subject: Book Recommendation References: Message-ID: <3f85a45e.682008736@news.blueyonder.co.uk> On Thu, 09 Oct 2003 12:32:01 GMT, Anthony wrote: > replies, and honesty. I can't believe my core python programming book is > outdated my mom just purchased it. please tell me it's still readable Its a very good introductory text. It is outdated in that the version it uses is now out of date but 95% (at least) is still perfectly valid and 99% will work as is, there just might be better more recent ways. Python develops at a fairly rapid rate so that any book will go out of date quickly. My own book started using 1.5.1, finished using 1.5.2 but the current version by the time of release was 2.0 (which I put on the CD). You just can't keep up with the changes and write a good book too (IMHO). If you like the style of Core Python stick with it, its as good as any other. Then read the online tutor which gets updated with each language version so you can pick up whats changed. If you don;t like the style then the other suggestions are all valid too. Alan G. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld From vanicat+invalid at labri.fr Sat Oct 25 17:03:58 2003 From: vanicat+invalid at labri.fr (Remi Vanicat) Date: Sat, 25 Oct 2003 23:03:58 +0200 Subject: What static typing makes difficult References: Message-ID: <87ekx1av29.dlv@wanadoo.fr> gt5163b at prism.gatech.edu (Brian McNamara!) writes: > mertz at gnosis.cx once said: >>The package gnosis.xml.objectify takes an XML source, and turns it into >>a "native" Python object. The function make_instance() can accept a >>wide range of different things that might sensibly relate to XML: a DOM >>object, a filename, an XML string, any object with a .read() method. >>Just one function deals happily with whatever you throw at it--without >>any deep commitments about what type of thing it is (i.e. some novel >>file-like object, or some new DOM implementation work without any >>problem). > > I have no chance at a full implementation, but here is a sketch in > Haskell. I know that a mere sketch is never as good as a working > implementation, so I hope someone else will take up the challenge. > > Anyway: > > type XMLRep = ... -- "internal" representation of XML objects > > class ConvertibleToXML a where > convertToXML :: a -> Maybe XMLRep > > instance ConvertibleToXML DomObject where > convertToXML :: DomObject -> Maybe XMLRep > convertToXML aDomObj = ... > > instance ConvertibleToXML String where > convertToXML :: String -> Maybe XMLRep > convertToXML s = if (head s) = '<' > then XMLStringToXML s -- assume an XML string > else readXMLFromFileNamed s > -- yes, we'd need to be in the IO monad here > > -- Later in the program > someFunc x y = > ... > let xml = convertToXML x in ... > -- which will infer the constraint "ConvertibleToXML x" > > As far as I can tell, the only "extra scaffolding" is the type class > ConvertibleToXML. Each time some new data type comes along which can be > converted to XML, we add a new instance declaration which shows how. By the way, this system have one big advantage with regard to the David Mertz example : Every one can had a new type to the ConvertibleToXML class, when with David example, one have to change the class XML_Objectify to have the same effect. -- R?mi Vanicat From dsilva at ccs.neu.edu Wed Oct 8 03:11:58 2003 From: dsilva at ccs.neu.edu (Daniel P. M. Silva) Date: Wed, 08 Oct 2003 03:11:58 -0400 Subject: Python syntax in Lisp and Scheme References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> <92c59a2c.0310031345.57d20631@posting.google.com> Message-ID: Greg Ewing (using news.cis.dfn.de) wrote: > Daniel P. M. Silva wrote: > >> Haven't some people implemented an entire class system as one huge macro? > > YES! Been there, done that -- about 3 or 4 times, actually. > I went through a bit of a phase where writing OO implementations > for Scheme was one of my principal hobbies. :-) > Nice! I was alluding to MzScheme's class.ss but I guess that's a fun hobby to have. :) Do you have your class systems available anywhere to download? I would be especially interested in them if they allow multiple inheritance, run-time pillaging of class contracts, and explicit "this" arguments to methods... > By the way, Scheme was my Favourite Cool Language for quite > a while. Then I discovered Python, and while I still appreciate > all the things about Scheme that I appreciated then, I wouldn't > want to go back to using it on a regular basis now. So it's not > a given that any person who likes Scheme must inevitably dislike > Python! > > I do "get" macros, and I appreciate having them available in > languages like Scheme, where they seem to fit naturally. But > I can't say I've missed them in Python, probably because Python > provides enough facilities of its own for constructing kinds of > mini-languages (keyword arguments, operator overloading, > iterators, etc.) to satisfy my needs without having to resort > to macros. You still can't add new binding constructs or safe parameterizations like a with_directory form: with_directory("/tmp", do_something()) Where do_something() would be evaluated with the current directory set to " tmp" and the old pwd would be restored afterward (even in the event of an exception). Last year -- I think at LL2 -- someone showed how they added some sort of 'using "filename":' form to Python... by hacking the interpreter. > And I do regard macros as something that one "resorts" to, for > all the reasons discussed here, plus another fairly major one > that nobody has mentioned: Unless both the macro system and > the macros written in it are *extremely* well designed, error > reporting in the presence of macros of any complexity tends to > be abysmal, because errors get reported in terms of the expansion > of the macro rather than what the programmer originally wrote. I've yet to encounter this problem in the standard library included with my Scheme implementation of choice, but ok. > ALL macro systems of any kind that I have ever used have suffered > from this - cpp, C++ templates, Lisp/Scheme macros, TeX, > you name it. I'd hate to see Python grow the same problems. > Some people use Python's hooks to create little languages inside Python (eg. to change the meaning of instantiation), which are not free of problems: class Object(object): def __init__(this, *args, **kwargs): this.rest = args this.keys = kwargs def new_obj_id(count=[0]): count[0] = count[0] + 1 return count[0] def tag_obj(obj, id): obj.object_id = id return obj def obj_id(obj): return obj.object_id type.__setattr__(Object, "__new__", staticmethod(lambda type, *args: tag_obj(object.__new__(type), new_obj_id()))) Great, now all object instantiations (of our own Object class) will also tag new objects with an ID: obj = Object() print "id: ", obj_id(obj) print "another id: ", obj_id(Object()) Which gives you 1 and then 2. Hurrah. Have you caught the bug yet? # forgot to check for this case... print Object(foo="bar") This is of course illegal and I get the following error message: Traceback (most recent call last): File "n.py", line 27, in ? print Object(foo="bar").rest TypeError: () got an unexpected keyword argument 'foo' Hmm... From m_mommer at yahoo.com Wed Oct 8 04:50:11 2003 From: m_mommer at yahoo.com (Mario S. Mommer) Date: 08 Oct 2003 10:50:11 +0200 Subject: Python syntax in Lisp and Scheme References: Message-ID: Peter Seibel writes: > corey.coughlin at attbi.com (Corey Coughlin) writes: > > > Using parentheses and rpn everywhere makes lisp very easy to parse, > > but I'd rather have something easy for me to understand and hard for > > the computer to parse. Intrestingly enough, I think this is a question of getting used to it. The notation is so relentlessly regular that once you got it, there are no more syntactical ambiguities. None. Ever. It is the difference (for me) between reading roman numerals (that would be the baroque-ish syntax of other languages, full of irregularities, special cases, and interference patterns), and arabic numerals (that would be lisp). I never have a doubt about what the S-expr. representation encodes. From llafba_NOSPAM_ at gmx.net Tue Oct 28 13:06:36 2003 From: llafba_NOSPAM_ at gmx.net (Chris) Date: Tue, 28 Oct 2003 19:06:36 +0100 Subject: manipulate string In-Reply-To: References: Message-ID: It is me again. Unfortunately it doesn't work. Python doesn't accept [::2] TypeError: sequence index must be integer I use Python Release 2.2.3. Any ideas? -Tom From pecora at anvil.nrl.navy.mil Fri Oct 24 13:37:25 2003 From: pecora at anvil.nrl.navy.mil (Louis Pecora) Date: Fri, 24 Oct 2003 13:37:25 -0400 Subject: Where's EditPythonPrefs (in Mac OS X) ?? Message-ID: I finally made the change to OS X and downloaded and installed MacPython-2.3. But... I cannot find EditPythonPrefs. The documentation and help tell me to use it to add the path to my modules, but the only copies I have are old system 9 ones. Nothing like EditPythonPrefs seems to be in the new MacPython 2.3. Am I missing something. I've spent some time going through the help files, but I can't find a clue. Can anyone point me to how to add paths to modules with 2.3? Thanks for any help. (also posted to Python Mac Sig - email list) -- -- Lou Pecora From ykingma at accessforall.nl Mon Oct 6 20:49:59 2003 From: ykingma at accessforall.nl (ykingma at accessforall.nl) Date: Mon, 06 Oct 2003 17:49:59 -0700 Subject: Queues - Is Infinity all right? References: <84fc4588.0310050520.42e5f9d4@posting.google.com> <3F802006.93571400@engcorp.com> Message-ID: <3f818f20$0$14130$e4fe514c@dreader4.news.xs4all.nl> Peter Hansen wrote: ... > > That said, I'd consider using a fixed queue only when I was greatly > concerned about whether my consumer thread was going to be able to > keep up with my producer thread(s), and was therefore concerned about > overflowing memory with unconsumed input. > > In other words, I'd worry more about the robustness of the app > than about optimizing it before it worked... > I've been bitten a few times by unbounded queues when the consumer thread could not keep up: the queue grows to memory limits and no robustness is left. So I changed my default choice for queue implementations to bounded queues. They are much more predictable under unexpected loads as they evt. force the producer to wait for the consumer. The next question is off course what maximum queue size to use. You can get good answers from queuing theory, but 10 to 20 works well in many cases. Kind regards, Ype -- email at xs4all.nl From daniel.dittmar at sap.com Fri Oct 10 04:45:59 2003 From: daniel.dittmar at sap.com (Daniel Dittmar) Date: Fri, 10 Oct 2003 10:45:59 +0200 Subject: Redirection of stdout fails on Windows References: <87a6f033.0310091222.182da0ee@posting.google.com> Message-ID: Joel Wagner wrote: > python tst.py > out > > I get the expected string 'a b c' in the file 'out'. > > When run like this: > > tst > out > > I get an error message 'The handle is invalid' and nothing in the > file 'out'. This is a bug in cmd.exe. If script is started by looking at the extension and then finding the real executable through the registry, redirection does not work. I think the easiest work around is to create batch files for every python script you want to execute. Daniel From abhjrpe at comcast.net Wed Oct 29 23:52:29 2003 From: abhjrpe at comcast.net (Aubrey Hutchison) Date: Wed, 29 Oct 2003 23:52:29 -0500 Subject: How do you make Python reliable??? Message-ID: Using Python 2,3,2 with idle for developing programs about 200 lines long. - Problem is not common to any specific program. Program are rather simple with no trick programming. Usually no classes but a few functions using math module with long integers. Usually for the first few tryout everything works fine and then idle locks "out" windows xp pro.. I can run other programs, but clicking on idle icon gets me an hour glass for a few moments and then goes away. Acts like I filled up memory but with 1 gig that should not be a problem. Word, Acad, quickbasic, and anyother program will work when python starts doing this lock out. But python will not work. Killing the computer is the usual way out of the problem. Shuting down just get me a dialog window telling me to click to shut down windowmenu. Which only gets me the same dialog a few moment later. Full power off is usually the only way, and at time upon reboot -the same will continue. When this happens I can load a game, Acad or word which work as they should. When this starts I get an indication the idle is not responding and I kill it with the status panel.Some times this happens only once but usually it ends up as a lock out. Computer is clean- no virus. Thanks for any help Aubrey From claird at lairds.com Fri Oct 31 19:53:17 2003 From: claird at lairds.com (Cameron Laird) Date: Sat, 01 Nov 2003 00:53:17 -0000 Subject: programming languages (etc) "web popularity" fun References: <3d06fae9.0310310915.4447d4ca@posting.google.com> <9Zzob.75517$e5.2773519@news1.tin.it> Message-ID: In article <9Zzob.75517$e5.2773519 at news1.tin.it>, Alex Martelli wrote: . . . >> BTW Thanks for a great nutshell book! > >You're welcome! googling for 'XXX in a Nutshell' does show >my work doing roughly as well as could be expected given the >languages' popularity (and the lack of Nutshell books for >some, which helps:-): > > java 10700 > perl 5540 > python 1140 > c# 393 > delphi 354 > c++ 352 . . . Note, too, that the Python one hasn't been on the street as long as some of the others. It's reasonable to specu- late that the ratios haven't equilibrated yet. -- Cameron Laird Business: http://www.Phaseit.net From find at my.address.elsewhere Wed Oct 29 09:12:05 2003 From: find at my.address.elsewhere (Matthias Blume) Date: Wed, 29 Oct 2003 14:12:05 GMT Subject: Python from Wise Guy's Viewpoint References: <3F9D5D21.2060408@ps.uni-sb.de> <20031027184024.GO1454@mapcar.org> <20031028093713.GQ1454@mapcar.org> <20031029085604.GU1454@mapcar.org> Message-ID: Matthew Danish writes: > Declarations can take this further, such that a compiler as smart as > CMUCL can manipulate raw (unsigned-byte 32) values, for example. Oh, so you're saying you want static declarations, checked and enforced by the compiler? Hmm, I've read this point of view in this thread somewhere. > Are the vast majority of your programs the type which behave properly > within machine-word integers? > > idea that the only correct result of 20 * 30 has to be 600.) > > (20 * 30) mod 256 is, of course, a completely different expression. Undoubtedly, it is a different expression. But it might mean the same, given a correspondingly chosen domain for 20 and 30, together with an certain * operation. Matthias From gh at ghaering.de Sun Oct 5 16:14:04 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Sun, 05 Oct 2003 22:14:04 +0200 Subject: SpamAssassin in Python? In-Reply-To: <87ad8fv5sp.fsf@blakie.riol#flibuste.net> References: <87ad8fv5sp.fsf@blakie.riol#flibuste.net> Message-ID: <3F807B8C.2010801@ghaering.de> Wilk wrote: > Roman Suzi writes: > >>Is there SpamAssassin-like app (well, maybe just rule-based >>part of it) written in Python? I do not need any fancities >>just liked to know if it will be faster than Perl version. > > http://spambayes.sourceforge.net/ SpamBayes is not rule-based. -- Gerhard From ktilton at nyc.rr.com Thu Oct 9 19:47:53 2003 From: ktilton at nyc.rr.com (Kenny Tilton) Date: Thu, 09 Oct 2003 23:47:53 GMT Subject: Python syntax in Lisp and Scheme In-Reply-To: References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> <92c59a2c.0310031345.57d20631@posting.google.com> <87llrvs4yw.fsf@bird.agharta.de> <7xu16jmf57.fsf@ruckus.brouhaha.com> Message-ID: Lulu of the Lotus-Eaters wrote: > Kenny Tilton wrote previously: > |Do they ever plan to do a compiler for it [Python]? > > You mean like Psyco? > > Been there, done that. (and it's great, and getting better). Oh, excellent name. OK, the context was "what are Python's aspirations?" . Is Python now no longer content to be a (very powerful) scripting language? Or is it just tired of being ragged on for being slow? -- http://tilton-technology.com What?! You are a newbie and you haven't answered my: http://alu.cliki.net/The%20Road%20to%20Lisp%20Survey From nospam-deets at web.de Wed Oct 22 12:00:07 2003 From: nospam-deets at web.de (Diez B. Roggisch) Date: Wed, 22 Oct 2003 18:00:07 +0200 Subject: Pan/Zoom Image class? References: Message-ID: Hi, > I'm just getting started rewriting a small CAD/GIS like application > for designating outlines of objects in photographs/images in Python. > Is there a class out there that already handles panning and zooming > along with lines that have been drawn on top of the object???If?got?a > simple scrolling canvas working and user designation of objects with > the mouse.??But?I'm?wondering?if?there?is?an?elegant?solution?that > handles zooming too.??I'm?using?Tkinter?with?a?canvas,?but?at?this > point I could switch to any GUI package.??Any?recommendations? You could go for pygame and/or pyopengl. I'm not sure if there is a way to embed a pygame-window or opengl window into a canvas, but maybe you can roll out your own toolkit-implementation on top of pygame. (There is even one, based on pygame and opengl, but it seems to work only under windows, which I don't have) Diez From user at domain.invalid Thu Oct 30 15:52:28 2003 From: user at domain.invalid (user at domain.invalid) Date: Thu, 30 Oct 2003 20:52:28 GMT Subject: Propert handler question Message-ID: Is there a way, from within a getter/setter method linked to a propert, that I can tell which property triggered the method? This would be great, because I need a great number of these properties, each having only slightly different actions, which could be triggered correctly if I knew the name of the property that was being accessed. Thanks, Toby From usenet-reply at henrik-motakef.de Fri Oct 24 19:07:15 2003 From: usenet-reply at henrik-motakef.de (Henrik Motakef) Date: 25 Oct 2003 01:07:15 +0200 Subject: Test cases and static typing References: <87ekx4xaym.dlv@wanadoo.fr> <87znfsvuqh.dlv@wanadoo.fr> <6ogn61-f61.ln1@ID-7776.user.dfncis.de> Message-ID: <861xt2utek.fsf@pokey.internal.henrik-motakef.de> Dirk Thierbach writes: > OTOH, Lisp certainly doesn't check types, Ho hum. I realize that this is probably not what you meant, but given the existence of usenet archives, I have to oppose this statement anyway ;-) Lisp implementations are not /required/ to check types at compile time (they are at run time, when they encounter a CHECK-TYPE form), but that doesn't neccessarily mean they don't. Even if the CL type system isn't as friendly for such things as the ones of Ocaml or Haskell may be (try proving whether a value is of type (satisfies (lambda (x) (= x (get-universal-time))))[1] for a start), some implementations really do honor you optional type declarations, and even do some significant type inferencing. They won't just abort compilation if they think you program could be improved type-wise, but they will issue a warning, which is just as good IMHO. > OTOH, this example is tied to a specific Lisp debugger feature. The Lisp debugger is a standardized part of the language, just like the type system is. [1] Yes, yes, you'll have to create a named function for that lambda expression in reality scince SATISFIES doesn't actually accept lambdas for some reason, but you get the point. From nhodgson at bigpond.net.au Fri Oct 24 20:26:57 2003 From: nhodgson at bigpond.net.au (Neil Hodgson) Date: Sat, 25 Oct 2003 00:26:57 GMT Subject: Strange Hotshot problem... References: <20031024181102.26916.00000093@mb-m05.aol.com> Message-ID: KefX: > Well, it finds the file just > fine, but it can't read it. It raises an IndexError from trying to pop an empty > list or some such. I've tested Hotshot with simple test scripts in pure Python > and it works just fine. I saw a similar issue that could be 'fixed' by running Python in optimized '-O' mode rather than normal mode as -O turns off assertions. Neil From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Fri Oct 10 13:08:44 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Fri, 10 Oct 2003 19:08:44 +0200 Subject: Where can I find some examples of program in Python? In-Reply-To: References: Message-ID: <3f86e79c$0$58714$e4fe514c@news.xs4all.nl> littleneo wrote: > If there is somebody knows where to get examples of programs in Python > concerned about any specific problems? Thanks! I'm not sure what you need exactly so here are a bunch of general links: http://www.python.org/cgi-bin/moinmoin/PythonSoftware http://www.python.org/pypi http://www.vex.net/parnassus/ (seems down at the moment?) http://aspn.activestate.com/ASPN/Python/Cookbook/ The last link is more of a library of handy code snippets. The others have many links to Python programs... --Irmen From adalke at mindspring.com Wed Oct 1 06:07:41 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Wed, 01 Oct 2003 10:07:41 GMT Subject: Prime number module References: <7b4hnvgplqk6g1d5vig0dsdvic1ru62r4e@4ax.com> <+Nfe/kKkXkJT092yn@gnosis.cx> Message-ID: Lulu of the Lotus-Eaters: > FWIW, bzip2 doesn't do much better either. I'd be kinda surprised at > this point if another representation of the primes under 10^8 actually > did better[**]. As I recall, the Burrows-Wheeler transform used in bzip2 uses a clever way to rearrange the data in a block into a form which is more compressible, yes? Well, what about rearranging the bits so that every multiple of 3 is before every non-multiple of 3, then every multiple of 5, etc. There's a simple algorithm to unravel the ordering, and you'll end up with lot of 0s at the start of the block. It's very much like the ordering+compression you did when you moved all the terms divisible by 2 to the front of the group then realized they could all be represented as part of the decompression algorithm. Extend my idea far enough and you'll have a prime sieve. > [**] Well, a MUCH shorter representation is a Python-coded algorithm for > generating the primes in the first place. But somehow that seems like > cheating :-). Why doesn't bzip2 feel like cheating? It's good at compressing text because it's designed for the sort of patterns found in text. Why doesn't mp3 feel like cheating? It's designed to handle the sounds we normally hear, as compared to the output of a random noise generator. In essense, if you know the full corpus beforehand, it's really easy to compress - just store the identifier for each text. There's only one text here so the result is trivial compressed to nothing. The problem is, your algorithm tries to compress an ordered list of odd numbers, and so fails to compress as well as a compression algorithm tuned for just compressing the first N primes. > ---[ to our friends at TLAs (spread the word) ]-------------------------- > Echelon North Korea Nazi cracking spy smuggle Columbia fissionable Stego > White Water strategic Clinton Delta Force militia TEMPEST Libya Mossad Hmm... Seems dated. Terms like whitewater and Clinton (Bill, not Hillary) don't hit many hot buttons these days, the number of people in various milita has gone way down [*] and Libya is working towards renormalization. What about these words? Iran nuclear neocon expose POTUS patriot Pakistan armed weaponized enriched uranium UN smallpox Gitmo invasion Castro Tikrit revolution sarin Andrew dalke at dalkescientific.com [*] Actually, US law states http://www4.law.cornell.edu/uscode/10/311.html (a) The militia of the United States consists of all able-bodied males at least 17 years of age and, except as provided in section 313 of title 32, under 45 years of age who are, or who have made a declaration of intention to become, citizens of the United States and of female citizens of the United States who are members of the National Guard. (b) The classes of the militia are - (1) the organized militia, which consists of the National Guard and the Naval Militia; and (2) the unorganized militia, which consists of the members of the militia who are not members of the National Guard or the Naval Militia Therefore, the numbers of people in the militia hasn't changed that drastically -- and I'm a member of the unorganized militia of the US. Maybe I should get a patch saying that, and wear it next time I visit Europe? :) From aleax at aleax.it Mon Oct 20 06:10:54 2003 From: aleax at aleax.it (Alex Martelli) Date: Mon, 20 Oct 2003 10:10:54 GMT Subject: Python from Wise Guy's Viewpoint References: <840592e1.0310192322.6a765e87@posting.google.com> Message-ID: Hannu Kankaanp?? wrote: > mike420 at ziplip.com wrote in message > news:... >> THE BAD: >> >> 1. f(x,y,z) sucks. f x y z would be much easier to type (see Haskell) >> 90% of the code is function applictions. Why not make it convenient? > > Python has been designed to attract non-programmers as well. Don't > you think f(x,y,z) resembles the mathematical notation of passing > a function some parameters, instead of "f x y z"? Yes -- which is exactly why many non-programmers would prefer the parentheses-less notation -- with more obvious names of course;-). E.g.: emitwarning URGENT "meltdown imminent!!!" DOES look nicer to non-programmers than emitwarning(URGENT, "meltdown imminent!!!") Indeed, such languages as Visual Basic and Ruby do allow calling without parentheses, no doubt because of this "nice look" thing. However, as I explained elsewhere, there are probably-insuperable language-design problems in merging "implicit call" and first-classness of all names unless you basically go all the way following Haskell with implicit currying and non-strictness (and assignments should probably go away too, else how to distinguish between assigning to x a nullary function f itself, and assigning to x the result of _calling_ f without arguments...?). Not to mention: emitwarning URGENT highlight "meltdown imminent!!!" where the need to disambiguate between highlight being the second of three parameters to emitwarning, or a function called with the string as its sole parameter and its RESULT being the second of two parameters to emitwarning, is important for human readers (indeed some languages that DO allow parentheses-less calls, such as Ruby, warn against actually USING this possibility in all cases where ambiguity-to-human-readers may result, such as the above -- the need to be very careful and selective in actually using the capability makes me less and less willing to pay any large price for it). In other words, it's a language design tradeoff, like so many others -- one which I believe both Python and Haskell got just right for their different audiences and semantics (I know VB _didn't_, and I suspend judgment on Ruby -- maybe firstclassness of all names isn't as important as it FEELS to me, but...). >> 6. Requiring "return" is also dumb (see #5) > > You really don't get any of this "explicit is better than implicit" > thing, do you? Requiring people to write "return" instead of > leaving it as optional like in Ruby, is again one reason why > Pythonistas *like* Python instead of Ruby. You come to I think that making return optional is slightly error-prone, but it DOES make the language easier to learn for newbies -- newbies often err, in Python, by writing such code as def double(x): x+x which indicates the lack of 'return' IS more natural than its mandatory presence. So, it's a tradeoff one could sensibly chose either way. Of course, such cases as: def buhandclose(boh): try: boh.buh() finally: boh.close() would give you a bad headache in trying to explain them to newbies ("hmyes the result of buhandclose IS that of the last expression it evaluates, BUT the one in the finally clause, although evaluated AFTER boh.buh(), doesn't really count because..." [keeps handwaving copiously & strenously]). So, mandatory 'return' does make the language more uniform, consistent, and easy to master, though not quite as easy to "pick up casually in a semi-cooked manner". Still, I for one don't condemn Ruby for making the opposite choice -- it IS a nicely balanced issue, IMHO. > Anyway, as a conclusion, I believe you'd be much happier with > Ruby than with Python. It doesn't do this weird "statement vs > expression" business, it has optional return, it has optional > parens with function calls, and probably more of these things > "fixed" that you consider Python's downsides. You're trying to But doesn't make higher-order-functions as much of a no-brainer as they're in Python, sigh. > make Python into a language that already exists, it seems, but > for some reason Pythonistas are happy with Python and not rapidly > converting to Ruby or Haskell. Instead of trying to tell us My own reasons for the choice of Python over Ruby are quite nuanced and complicated, actually (those for either of them over Haskell have much to do with pragmatism over purity:-). It boils down to my desire to write application programs, often requiring cooperation of middling-sized groups of people, rather than experimental frameworks, or programs written by a lone coder or a small group of highly-attuned experts. I have the highest respect for Ruby -- it just doesn't match my needs QUITE as well as Python does. But, yes, if somebody doesn't really think about what kind of programs they want to write, but rather focuses on syntax sugar issues such as return being optional or mandatory "per se", then it's definitely worthwhile for that somebody to try Ruby and leave c.l.py in peace:-). Alex From claird at lairds.com Mon Oct 27 20:04:58 2003 From: claird at lairds.com (Cameron Laird) Date: Tue, 28 Oct 2003 01:04:58 -0000 Subject: Concurrency models (was: Timer) References: <3f9c9cdb$0$23610$5a62ac22@freenews.iinet.net.au> <3F9D77BE.B66D1F08@hotmail.com> Message-ID: In article <3F9D77BE.B66D1F08 at hotmail.com>, Alan Kennedy wrote: >[Cameron Laird] >> This thread is really about asynchronous or concurrent >> processing, > >I really don't have time to post to the level of detail I would like, >but I had to put forward a couple of thoughts. This is mostly a "me, too" follow-up. I decided to post it, though, if only to ensure > >> I claim, and I further claim we really don't >> have *any* satisfying model for coding those. > >I think you might get some disagreement from the Twisted, Medusa and >ZServer people. And possibly see a slanging match erupt on whose >design is best.... that Twisted et al. don't feel abused. I am VERY fond of Twisted, Medusa, and Zope, and have even written an (unpublished, still) article on their concurrency management. I, also, won't go into detail now; I just want to make clear that I think they're great, and was excluding them only for categorical reasons. . [much truth] . . >My ?0,02: Generators (and, by extension, coroutines) will be python's >greatest advance in simplifying writing event-based server >architectures: resumable functions are a honking great idea. Worth repeating. . . . -- Cameron Laird Business: http://www.Phaseit.net From pih00 at doc.ic.ac.uk Fri Oct 10 14:09:17 2003 From: pih00 at doc.ic.ac.uk (Perflubron) Date: 10 Oct 2003 11:09:17 -0700 Subject: Installing MySQLdb under Cygwin Message-ID: <9de526d5.0310101009.648c6d13@posting.google.com> Hi, I'm having trouble installing MySQLdb 0.9.2 on the following Cygwin system: - Python 2.2.2 - MySQL 3.23.57 - gcc 2.95.3-10 The steps I take are: 1. Modify setup.py - Set thread_safe_library = NO - Change the Cygwin paths to use /cygdrive/c/... - Change the library path to .../lib/opt 2. Run setup.py build --> Errors on lines 2005-7 and 2094-6 of _mysql.c: "Initializer element is not constant" 3. Replace the above lines with "0," 4. Run setup.py build --> Many undefined references to mysql functions 5. Change setup.py to use mysql library instead of mysqlclient 6. Run setup.py build --> It compiles, so I run the setup.py install 7. When I try to import the library, I get the following error: Traceback (most recent call last): File "./test.py", line 4, in ? import MySQLdb File "MySQLdb/__init__.py", line 27, in ? import _mysql ImportError: dlopen: Win32 error 127 I'm stuck. I've tried using g++ instead of gcc, which gets rid of the Initializer element is not constant" error. But I end up at the same error when I try to import the module. I have seen some posts from people who have managed to install MySQLdb on Cygwin - could someone please let me know how to do it? Kind regards, Per From brlspam at yahoo.com Fri Oct 10 09:28:51 2003 From: brlspam at yahoo.com (Bruce Lewis) Date: 10 Oct 2003 09:28:51 -0400 Subject: startup time (was: Python syntax in Lisp and Scheme) References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> <92c59a2c.0310031345.57d20631@posting.google.com> <6CZgb.3273$dn6.860@newsread4.news.pas.earthlink.net> <%hihb.4368$dn6.2921@newsread4.news.pas.earthlink.net> Message-ID: j-anthony at rcn.com (Jon S. Anthony) writes: > If your problems are trivial, I suppose the presumed lower startup > costs of Python may mark it as a good solution medium. I find no significant difference in startup time between python and mzscheme. From http Sat Oct 18 12:04:54 2003 From: http (Paul Rubin) Date: 18 Oct 2003 09:04:54 -0700 Subject: prePEP: Money data type References: <7xbrse3bup.fsf@ruckus.brouhaha.com> Message-ID: <7xr81a7crd.fsf@ruckus.brouhaha.com> "John Roth" writes: > COBOL's default rounding policy is to truncate. It has a second > rounding policy that is invoked by the keyword ROUND (surprise, > eh?) However, one of the things that COBOL arithmetic has is > precise control of the number of decimal places at all points in > a computation[1], so if you don't like either truncation or the effects > of ROUND, then you simply maintain an additional decimal place > or two and do it your way.[2] Yeah, but what about the exact method of rounding, like the pre-PEP specifies 1.125 rounds down but 1.135 rounds up (or maybe it was the other way), while some other standard specifies always rounding down (or up) when the extra digit is a 5. > [2] Unless that would run you over 18 digits. Why 18, I > have no idea, and I'm afraid that most of the people on the > original COBOL committee are no longer with us. That's obvious, it's how many BCD digits would fit in a doubleword of the 36-bit machines in use at that time. From paul.kemp at standardbank.com Sat Oct 18 03:31:42 2003 From: paul.kemp at standardbank.com (Paul) Date: 18 Oct 2003 00:31:42 -0700 Subject: pythoncom - 'module' object has no attribute 'frozen' References: Message-ID: Thanks Thomas - adding the sys.frozen = 1 line seemed to do the trick. I'm a beginner here - would you mind explaining to me what the 'frozen' attribute means? Thanks Paul Thomas Heller wrote in message news:... > paul.kemp at standardbank.com (Paul) writes: > > > Hi > > > > I'm trying to build a standalone COM exe server using Python 2.2 + > > Mark Hammond's windows extensions + Py2Exe. I've built the example > > linked on the Py2Exe homepage and get this error when running the exe: > > > > I:\Program Files\Python22\dist\comtest>comtest --register > > Traceback (most recent call last): > > File "", line 37, in ? > > File "win32com\server\register.pyc", line 468, in UseCommandLine > > File "win32com\server\register.pyc", line 405, in RegisterClasses > > File "win32com\server\register.pyc", line 188, in RegisterServer > > AttributeError: 'module' object has no attribute 'frozen' > > > > Does anyone know what I'm doing wrong? thanks. btw, I have to use > > Python 2.2. > > Mark Hammond changed his code to support McMillan installer. > Looking at line 188 in win32com\server\register.py explains what happens: > > 187 if pythoncom.frozen: > 188 assert sys.frozen, "pythoncom is frozen, but sys.frozen is not set - don't know the context!" > 189 if sys.frozen == "dll": > > You need to make sure that sys.frozen is also set, but better not to > 'dll'. I didn't try it, but the next step for you would be to change > your code in the way mentioned below: > > > 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 > [...] > > The good news is that Mark and I are currently working on a brand new > version of py2exe which will support 2.3 only, but which is much better > integrated with the win32all stuff. In this version, you don't have to > do anything special in your com server code, although you have to change > your setup script a little bit. > > Thomas From raffaelcavallaro at junk.mail.me.not.mac.com Mon Oct 20 19:20:12 2003 From: raffaelcavallaro at junk.mail.me.not.mac.com (Raffael Cavallaro) Date: Mon, 20 Oct 2003 23:20:12 GMT Subject: Express What, not How. References: <3f8f0bca.425450585@news.blueyonder.co.uk> <87ekxciphd.wl@strelka.synthcode.com> Message-ID: In article , David Rush wrote: > I have in a mail-processing application 2 functions IF-FROM-LINE (used in > mbox file processing) and RFC822-COLLAPSE-HEADER (used in RFC822 header > processing) which both implement algorithms which are parameterized > by functions. This is vaguely similiar in spirit to the visitor pattern > from OO land, but much more flexible. Both of these functions are used > in multiple contexts where the anonymous functions contextualize the > operations performed under specific conditions in their implemented > algorithms. These operations have (so far) been strictly one-off animals. I think you are in violent agreement with me. I wrote: > > The problem I see with the use of > > the typical anonymous functional ^^^^^^^^^ > > style is twofold: 1. If-from-line is a _named_ function, not an anonymous function. My only objection was to _anonymous_ functions replacing named abstractions, not to functional programming itself. > In the event that I ever feel a need to re-use one of them I will simply > lift the anonymous function from its original source location, give it > a top-level name et voila - instant reuse. 2. Which is precisely what I suggested in all of my previous posts. I.e., if the anonymous function is used more than once, name it, and use the name. From pajer at iname.com Wed Oct 1 13:09:06 2003 From: pajer at iname.com (Gary) Date: 1 Oct 2003 10:09:06 -0700 Subject: fink dependency problem: python23-shlib Message-ID: <4e47e24d.0310010909.45e7bd11@posting.google.com> I'm trying to install various things via fink, in particular numeric-py23. The process stops with a dependency error: dpkg: dependency problems prevent configuration of python23: python23 depends on python23-shlibs (= 2.3-1); however: Version of python23-shlibs on system is 1:2.3-1. fink list -i python shows that python23-shlibs is installed, but python23 is not. But python2.3 itself seems to run just fine. Attempts to install python23 end in the same error. I've tried to remove and reinstall python23-shlibs, I've tried to purge python23-shlibs, I've tried to purge and reinstall everything related to python23, with the same results each time. I have the unstable packages opened up by mods to fink.conf. What's the difference between version 1:2.3-1 and 2.3-1 ??? Oddly, I've installed everything on another Mac (all macs are OSX 10.2.6) and I don't remember having any problems like this. Any idea what's up?? -gary From mwh at python.net Fri Oct 24 07:15:25 2003 From: mwh at python.net (Michael Hudson) Date: Fri, 24 Oct 2003 11:15:25 GMT Subject: Why Python style guide (PEP-8) says 4 space indents instead of 8 space??? 8 space indents ever ok?? References: Message-ID: <7h3n0bqj3h1.fsf@pc150.maths.bris.ac.uk> Ian Bicking writes: > > Okay, okay, let's just compromise somewhere in between: 5 character > indents. 7.5! Cheers, mwh -- 34. The string is a stark data structure and everywhere it is passed there is much duplication of process. It is a perfect vehicle for hiding information. -- Alan Perlis, http://www.cs.yale.edu/homes/perlis-alan/quotes.html From mwilson at sarcastic-horse.com Fri Oct 3 14:42:48 2003 From: mwilson at sarcastic-horse.com (Matthew Wilson) Date: Fri, 3 Oct 2003 14:42:48 -0400 (EDT) Subject: negative numbers and integer division Message-ID: <36085.199.169.240.132.1065206568.squirrel@svr1.turboweb.net> Hi- I just discovered this: >>> -1 // 12 -1 >>> 1 // 12 0 >>> I thought that -1 // 12 would be 0 also. I'm writing a simple monthly date class and i need (-1,2001) to be translated to (11,2000). Any ideas? From tjreedy at udel.edu Thu Oct 9 17:46:02 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 9 Oct 2003 17:46:02 -0400 Subject: generator testing and attrs References: Message-ID: "Mike" wrote in message news:gGfhb.528065$Oz4.405020 at rwcrnsc54... > I need to be able to store a list of schedulable items, either regular > callables or generator-producing functions -- is there a way to test if a fn > is generator-producing? Yes, but I forget how. The ref-man section on type hierarchy lists and explains 'special attributes' for each type. Functions or code objects have an indication of normal vs. generator. TJR From anton at vredegoor.doge.nl Thu Oct 30 10:12:44 2003 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Thu, 30 Oct 2003 16:12:44 +0100 Subject: alwayssortedlist (was Re: On PEP 322 (ireverse)) References: <4xQnb.373812$R32.12367046@news2.tin.it> Message-ID: Alex Martelli wrote: >class alwayssortedlist(list): > > def __init__(self, *args): > list.__init__(self, *args) > self.sort() > >We need to ensure sorting at creation. We _might_ make the sort >method in this class a noop and call list.sort(self) instead, >but, naah -- list.sort is SO fast when called on an already >sorted list that it ain't even funny, so, choose simplicity. >Onwards to simple mods: > > def append(self, *args): > list.append(self, *args) > self.sort() > > def __setitem__(self, *args): > list.__setitem__(self, *args) > self.sort() How about this code: a = alwaysssortedlist(range(10)) a[5] = 20 What's the use of assigning to a specific list position if the object could end up being in some other place? Anton From antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru Tue Oct 14 12:30:39 2003 From: antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru (anton muhin) Date: Tue, 14 Oct 2003 20:30:39 +0400 Subject: Python vs. Lisp: scope issues Message-ID: In addition to s[0] hack, I'd like to suggest the following code. Any comments are highly appreciated: class Scope(object): pass def accumulator(): scope = Scope() scope.n = 0 def f(n): scope.n += n return scope.n return f a1 = accumulator() print a1(1) print a1(2) a2 = accumulator() print a2(10) print a2(20) regards, anton. From wester at ilt.fraunhofer.de Tue Oct 7 03:33:37 2003 From: wester at ilt.fraunhofer.de (Rolf Wester) Date: Tue, 07 Oct 2003 09:33:37 +0200 Subject: Explanation of macros; Haskell macros In-Reply-To: References: Message-ID: mike420 at ziplip.com wrote: > Let's say you do not have the "for" keyword, but you have > "dolist" for iterating a list and "dotimes" - a simple > index loop. You want to create "for" just like in Python, and > you also want "for i in range(10000): print i" to be efficient > and avoid constructing the big list (maybe you do not have > enough memory). In Lisp, you can acomplish this with the > following macro: > > (defmacro for(i in list &rest rest) > (if (eql 'in in) > (if (and (listp list) > (eql (length list) 2) > (eql 'range (first list)) > (integerp (second list))) > `(dotimes (,i ,(second list)) , at rest) > `(dolist (,i ,list) , at rest)) > (error "syntax error"))) > > What will a Pythonista think about Lisp macros when he/she tries: (defun f (n) (for i in (range n) (print i))) (f 10000) Maybe the macro should better be written: (defmacro for (i in list &rest rest) (if (eql 'in in) (if (and (listp list) (eql (length list) 2) (eql 'range (first list)) (or (integerp (second list)) (symbolp (second list)))) `(if (integerp ,(second list)) (dotimes (,i ,(second list)) , at rest) (error "not an integer")) `(dolist (,i ,list) , at rest)) (error "syntax error"))) Rolf Wester From costanza at web.de Thu Oct 23 12:04:06 2003 From: costanza at web.de (Pascal Costanza) Date: Thu, 23 Oct 2003 18:04:06 +0200 Subject: Python from Wise Guy's Viewpoint In-Reply-To: References: <_8Ekb.7543$pT1.318@twister.nyc.rr.com> <3f972e54$1@news.unimelb.edu.au> <3f9795dd$1@news.unimelb.edu.au> Message-ID: Matthias Blume wrote: > Pascal Costanza writes: > > >>Well, to say this once more, there are programs out there that have a >>consistent design, that don't have "problems", and that cannot be >>statically checked. > > > Care to give an example? How you you know that the design is > consistent? Squeak, probably. Lisp development environments. Probably almost any development environment with a good debugger that allows for changing code on the fly. > Do you have a proof for that claim? Can you write that > proof down for me, please? No. Design consistency is an aesthetical category. > :-) > > Matthias Pascal -- Pascal Costanza University of Bonn mailto:costanza at web.de Institute of Computer Science III http://www.pascalcostanza.de R?merstr. 164, D-53117 Bonn (Germany) From joostkremers at yahoo.com Tue Oct 21 11:18:03 2003 From: joostkremers at yahoo.com (Joost Kremers) Date: 21 Oct 2003 15:18:03 GMT Subject: [OT] Inuit? Eskimo? References: <20031020163642.GA5539@nl.linux.org> <4vre61-ku2.ln1@beastie.ix.netcom.com> Message-ID: Skip Montanaro wrote: > "Native American" is to "American Indian" as ______ is to "Eskimo". > > Anyone in the .ca domain care to educate the .us folks? to the best of my knowledge, Inuit is the term that the original inhabitants of (northern) Canada and of Greenland use for themselves. in their language, Inuktitut, it is the plural of inut, which means 'man' or 'person'. the word 'eskimo' was a pejorative term used by (non-inuit) peoples living further to the south on the american continent, and has the meaning 'eater of raw meat'. because of this origin, it is disfavoured. -- Joost Kremers since when is vi an editor? a discussion on vi belongs in comp.tools.unusable or something... ;-) From mwilson at the-wire.com Tue Oct 14 10:57:31 2003 From: mwilson at the-wire.com (Mel Wilson) Date: Tue, 14 Oct 2003 10:57:31 -0400 Subject: private variables/methods References: <3F856275.C884CE5@engcorp.com> Message-ID: In article , Alex Martelli wrote: >Terry Reedy wrote: >>> I think that __current_module__ is perhaps a bit too lengthy >> >> and redundant ;-) > >I disagree. Lengthy it may be, but we do want a 'reserved module >name' to use for this purpose. To me, the existence of a qualified __current_module__.xyz = 3 implies that another local variable can also be called xyz. So we're forced to code things like __current_module__.xyz = 1 - __current_module__.xyz even with all the beautification brackets '__', this starts to look cumbersome to me. I would also prefer (while we're talking about me) that '__' be a hint that we're dealing with wizard code -- overloading standard operators inside class definitions, etc. I don't think I should have to put on my masked avenger tights just to get at my own module-level variables. Maybe Python 3 could re-cast the 'global' keyword to take the place of '__current_module__'. 'module' might be more meaningful, if it doesn't ultimately take one too many useful names away from the programmers. Regards. Mel. From bokr at oz.net Wed Oct 15 22:57:14 2003 From: bokr at oz.net (Bengt Richter) Date: 16 Oct 2003 02:57:14 GMT Subject: Python syntax in Lisp and Scheme References: <8CVgb.8$KR3.1846@typhoon.nyu.edu> <20031014050046.GM1454@mapcar.org> Message-ID: On Wed, 15 Oct 2003 00:04:21 +1300, Paul Foley wrote: >On Tue, 14 Oct 2003 01:26:54 -0400, David Mertz wrote: > >> Matthew Danish wrote previously: >> |On Wed, Oct 08, 2003 at 03:59:19PM -0400, David Mertz wrote: >> |> |Come on. Haskell has a nice type system. Python is an application of >> |> |Greespun's Tenth Rule of programming. >> |> Btw. This is more nonsense. HOFs are not a special Lisp thing. Haskell >> |> does them much better, for example... and so does Python. > >> |Wow. The language with the limited lambda form, whose Creator regrets >> |including in the language, is ... better ... at HOFs? >> |You must be smoking something really good. > >> I guess a much better saying than Greenspun's would be something like: >> "Those who know only Lisp are doomed to repeat it (whenver they look at >> another language)." It does a better job of getting at the actual >> dynamic. > >Is there anyone who knows only Lisp? > >Those who know Lisp repeat it for a reason -- and it isn't because >it's all they know! [Besides, Greenspun's 10th isn't about _Lispers_ >reinventing Lisp; it's about _everybody else_ reinventing Lisp] > >> In point of fact, Python could completely eliminate the operator >> 'lambda', and remain exactly as useful for HOFs. Some Pythonistas seem >> to want this, and it might well happen in Python3000. It makes no >> difference... the alpha and omega of HOFs is that functions are first >> class objects that can be passed and returned. Whether they happen to >> have names is utterly irrelevant, anonymity is nothing special. > True, but if you are forced to bind to a name in order to get hold of some first class functions but not others, then some are IMO "more equal than others." And unless you allow assignments in expressions, def foo():... will be excluded, because it assigns/binds foo in the def evaluation context, whereas lambda doesn't. For simple functions, things look a lot the same, e.g., >>> def show(): ... def foo(x): return x+1 ... bar = lambda x: x+1 ... return foo,bar ... >>> import dis >>> dis.dis(show) 2 0 LOAD_CONST 1 (", line 2>) 3 MAKE_FUNCTION 0 6 STORE_FAST 0 (foo) 3 9 LOAD_CONST 2 ( at 009034A0, file "", line 3>) 12 MAKE_FUNCTION 0 15 STORE_FAST 1 (bar) 4 18 LOAD_FAST 0 (foo) 21 LOAD_FAST 1 (bar) 24 BUILD_TUPLE 2 27 RETURN_VALUE 28 LOAD_CONST 0 (None) 31 RETURN_VALUE >>> foo,bar = show() >>> dis.dis(foo) 2 0 LOAD_FAST 0 (x) 3 LOAD_CONST 1 (1) 6 BINARY_ADD 7 RETURN_VALUE 8 LOAD_CONST 0 (None) 11 RETURN_VALUE >>> dis.dis(bar) 3 0 LOAD_FAST 0 (x) 3 LOAD_CONST 1 (1) 6 BINARY_ADD 7 RETURN_VALUE The difference in the code generated seems to be mainly that lambda is guaranteed to have a return value expression at the end, so there is no return case to solve by default boilerplate, and it is left out. Lambda is an expression, so this is possible with Python's syntax: >>> (lambda ... x ... : ... x ... + ... 1 ... ) at 0x008FDE70> (because indentation is ignored inside brackets). This obviously now precludes lambda bodies that are dependent on indented code suites, and makes it (so far) impossible to put def foo():pass inside expression brackets. But this is surface stuff w.r.t. the definition of the code body IMO. The name part does make a difference, however, because it amounts to a forced assignment (note that that you get MAKE_FUNCTION followed by STORE_FAST whether you assign a lambda expression "manually" or do it by def. You get identical code (see above), but with lambda you don't have to have a STORE_FAST LOAD_FAST to get the use of your function as "first class"). >True enough. Naming things is a pain though. Imagine if you couldn't >use numbers without naming them: e.g., if instead of 2 + 3 you had to >do something like > > two = 2 > three = 3 > two + three > >Bleargh! It "makes no difference" in much the same way that using >assembler instead of Python "makes no difference" -- you can do the >same thing either one, but one way is enormously more painful. > I think it makes a semantic difference, not just convenience. >[Mind you, Python's lambda is next to useless anyway] Well, even so, I would miss it, unless it's given a full life as a nameless def(): I don't think we can know if YAGNI will apply, since there is no current opportunity for beautiful use cases to evolve or even viably to be conceived. Regards, Bengt Richter From mrs_mazuri at qhalcyoqneqt.irg.za Tue Oct 28 09:03:48 2003 From: mrs_mazuri at qhalcyoqneqt.irg.za (MandlaX) Date: Tue, 28 Oct 2003 16:03:48 +0200 Subject: Python mascot? How about a Pythoneer? References: Message-ID: We're fresh out of those, but I've got a lovely terrier .... From aleaxit at yahoo.com Sun Oct 12 17:59:26 2003 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 12 Oct 2003 21:59:26 GMT Subject: Python syntax in Lisp and Scheme References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> <92c59a2c.0310031345.57d20631@posting.google.com> <6WKdnf4hoZxoRRWiXTWJig@comcast.com> <39hib.205605$hE5.6914649@news1.tin.it> Message-ID: <29kib.206536$hE5.6945256@news1.tin.it> Pascal Costanza wrote: ... >>>Well, this proves that Python has a language feature that is as >>>dangerous as many people seem to think macros are. ... >> Indeed, a chorus of "don't do that" is the typical comment each >> and every time a newbie falls into that particular mis-use. Currently, ... >> large existing codebase) is under active consideration for the next >> version of Python, expected (roughly -- no firm plans yet) in early 2005. > > OK, I understand that the Python mindset is really _a lot_ different > than the Lisp mindset in this regard. As in, no lisper will ever admit that a currently existing feature is considered a misfeature?-) > Ah, you want something like final methods in Java, or better probably > final implicitly as the default and means to make select methods > non-final, right? Not really, the issue I was discussing was specifically with importing. Normally, an import statement "looks" for a module [a] among those already loaded, [b] among the ones built-in to the runtime, [c] on the filesystem (files in directories listed in sys.path). "import hooks" can be used to let you get modules from other places yet (a database, a server over the network, an encrypted version, ...). The new architecture I mentioned lets many import hooks coexist and cooperate, while the old single-hook architecture made that MUCH more difficult, that's all. "final implicitly as the default and means to make select methods non-final" is roughly what C++ has -- the "means" being the "virtual" attribute of methods. Experience proves that's not what we want. Rather, builtin (free, aka toplevel) _names_ should be locked down just as today names of _attributes_ of builtin types are mostly locked down (with specific, deliberate exceptions, yes). But I think I'm in a minority in wanting similar mechanisms for non-built-ins, akin to the 'freeze' mechanism of Ruby (and I'm dismayed by reading that experienced Rubystas say that freeze LOOKS like a cool idea but in practice it's almost never useful -- they have the relevant experience, I don't, so I have to respect their evaluation). > What makes you think that macros have farther reaching effects in this > regard than functions? If I call a method and pass it a function object, > I also don't know what the method will do with it. Of course not -- but it *cannot possibly* do what Gat's example of macros, WITH-MAINTAINED-CONDITION, is _claimed_ to do... "reason" about the condition it's meant to maintain (in his example a constraint on a variable named temperature), about the code over which it is to be maintained (three functions, or macros, that start, run, and stop the reactor), presumably infer from that code a model of how a reactor _works_, and rewrite the control code accordingly to ensure the condition _is_ in fact being maintained. A callable passed as a parameter is _atomic_ -- you call it zero or more times with arguments, and/or you store it somewhere for later calling, *THAT'S IT*. This is _trivially simple_ to document and reason about, compared to something that has the potential to dissect and alter the code it's passed to generate completely new one, most particularly when there are also implicit models of the physical world being inferred and reasoned about. Given that I've seen nobody say, for days!, that Gat's example was idiotic, as I had first I thought it might be, and on the contrary I've seen many endorse it, I use it now as the simplest way to show why macros are obviously claimed by their proponents to be _scarily_ more powerful than functions. (and if a few voices out of the many from the macro-lovers camp should suddely appear to claim that the example was in fact idiotic, while most others keep concurring with it, that will scale down "their proponents" to "most of their proponents", not a major difference after all). > Overriding methods can also be problematic when they break contracts. That typically only means an exception ends up being raised when the method is used "inappropriately" - i.e. in ways depending on the contract the override violates. The only issue is ensuring that the diagnostics of the error are clear and complete (and giving clear and complete error diagnostics is often not trivial, but that is common to just about _any_ classes of errors that programmers do make). > (Are you also considering to add DBC to Python? I would expect that by > now given your reply above.) Several different implementations of DBC for Python are around, just like several different architectures for interfaces (or, as I hope, Haskell-like typeclasses, a more powerful concept). [Note that the lack of macros stops nobody from playing around with concepts they would like to see in Python: they just don't get to make new syntax to go with them, and, thus, to fragment the language thereby:-)]. Guido has already declared that ONE concept of interfaces (or typeclasses, or protocols, etc) _will_ eventually get into Python -- but _which one_, it's far too early to tell. I would be surprised if whichever version does make it into Python doesn't let you express contracts. A contract violation will doubtlessly only mean a clear and early error diagnostic, surely a good thing but not any real change in the power of the language. > Can you give an example for the presumably dangerous things macros > supposedly can do that you have in mind? I have given this repeatedly: they can (and in fact have) tempt programmers using a language which offers macros (various versions of lisp) to, e.g., "embed a domain specific language" right into the general purpose language. I.e., exactly the use which is claimed to be the ADVANTAGE of macros. I have seen computer scientists with modest grasp of integrated circuit design embed half-baked hardware-description languages (_at least_ one different incompatible such sublanguage per lab) right into the general-purpose language, and tout it at conferences as the holy grail -- while competitors were designing declarative languages intended specifically for the purpose of describing hardware, with syntax and specifically limited semantics that seemed to be designed in concert with the hardware guys who'd later be USING the gd thing (and were NOT particularly interested in programming except in as much it made designing hardware faster and cheaper). The effort of parsing those special-purpose language was of course trivial (even at the time -- a quarter of a century ago -- yacc and flex WERE already around...!), there was no language/metalanguage confusion, specialists in the domain actually did a large part of the domain-specific language design (without needing macro smarts for the purpose) and ended up eating our lunch (well, except that I jumped ship before then...;-). Without macros, when you see you want to design a special-purpose language you are motivated to put it OUTSIDE your primary language, and design it WITH its intended users, FOR its intended purposes, which may well have nothing at all to do with programming. You parse it with a parser (trivial these days, trivial a quarter of a century ago), and off you go. With macros, you're encouraged to do all the wrong things -- or, to be more precise, encouraged to do just the things I saw causing the many costly failures (one or more per lab, thanks to the divergence:-) back in that my early formative experience. I have no problem with macros _in a special-purpose language_ where they won't tempt you to embed what you _should_ be "out-bedding", so to speak -- if the problem of giving clear diagnostics of errors can be mastered, denoting that some functions are to be called at compile time to produce code in the SPL has no conceptual, nor, I think, particular "sociological" problem. It's only an issue of weighing their costs and usefulness -- does the SPL embody other ways to remove duplication and encourage refactoring thereby, are there overlap among various such ways, etc, etc. E.g., a purely declarative SPL, with the purpose of describing some intricate structure, may have no 'functions' and thus no other real way to remove duplication than macros (well, it depends on whether there may be other domain specific abstractions that would be more useful than mere textual expansions, of course -- e.g. inheritance/specialization, composition of parts, and the like -- but they need not be optimal to capture some inevitable "quasi-accidental duplications of SPL code" where a macro might well be). Alex From srinathava_news at yahoo.com Fri Oct 24 18:03:30 2003 From: srinathava_news at yahoo.com (Srinath Avadhanula) Date: Fri, 24 Oct 2003 15:03:30 -0700 Subject: Counting unicode graphemes in python In-Reply-To: References: Message-ID: On Fri, 24 Oct 2003, vincent wehren wrote: > | > | the first two "code points" represent a single character on the screen. > > My GUESS is that you can do that unless you *know* exactly which codepoints > form ligatures. In DEVANAGARI this are e.g. the so-called dependent vowels > in range 093e - 094c, wherin 093f stands "left of the consonant" when > rendered. (My knowledge of Indic languages is limited, at best, so there may > be mor to it..) > After a sleepless night, I finally found out that calculating grapheme boundaries for devanagari is not so hard after all. It seems to work reasonably well if I use just three simple rules: To detect whether in the code point sequence 'ab', the junction between 'a' and 'b' is a glyph boundary. 1. If 'b' is some kind of a mark (i.e unicodedata.category(b) starts with 'M'), then the 'ab' junction is not a glyph boundary. 2. If 'b' is not a Mark, but is a devanagari letter (i.e category 'Lo') AND 'a' is a VIRAMA character i.e, 'VIRAMA' in unicodedata.name(a), then the 'ab' junction is not a glyph boundary. 3. In every other situation, the 'ab' junction is a glyph boundary. Dont really know if this is completely correct, but it performs pretty well on quite a big sanskrit text I have... Handles things like NA + HALANT + DHA + HALANT + YA + AA and reports it (correctly) as a single glyph. > | In my application, the GUI seems to handle that part (i.e combining > | characters). However, I need to handle cursor movement myself. The GUI > | can only be told to move forward by a specified number of bytes. > > What GUI are you working with? > I am using wxPython on windows XP. There are two text display widgets, wxTextCtrl and wxStyledTextCtrl. The former is pretty basic but the caret positioning is pretty robust. The latter is very fancy, hanles syntax highlighting etc, but has some serious problems with combining characters. > Some systems such as the X Server on IndiX seem to dig into the GPOS and > GSUB tables in the OpenType font. See: > > http://rohini.ncst.ernet.in/indix/doc/HOWTO/Devanagari-HOWTO-5.html > Thanks for the link! > Would "Look at > http://www.unicode.org/Public/UNIDATA/UCD.html#General_Category_Values " do? It does indeed. Notice my new-found fluency with unicodedata.category? :) Thanks, Srinath From pf_moore at yahoo.co.uk Tue Oct 28 17:50:09 2003 From: pf_moore at yahoo.co.uk (Paul Moore) Date: Tue, 28 Oct 2003 22:50:09 +0000 Subject: Python for .NET 1.0 beta 1 released References: Message-ID: "Brian Lloyd" writes: > Python for .NET 1.0 beta 1 has been released - you can download > it from: > > http://www.zope.org/Members/Brian/PythonNet/ A quote from the README: **Can I use it with my existing Python installation?** Yes, at least on win32 systems. Just copy the files Python.Runtime.dll and CLR.dll from the PythonNet directory to the root directory of your python installation. Actually, this isn't entirely true: I copied the 2 files as described, and then tried the following: >python Python 2.3.2 (#49, Oct 2 2003, 20:02:00) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import CLR.System.Windows.Forms Traceback (most recent call last): File "", line 1, in ? ImportError: No module named System.Windows.Forms >>> import CLR >>> import CLR.System.Windows.Forms It looks like CLR needs to be imported explicitly, before anything else. This is *not* the case with the python.exe which is supplied - actually, it is, it's just that CLR gets implicitly imported somewhere in the startup: C:\Data\PythonNet-1.0-beta1 >python Python 2.3.2 (#49, Oct 2 2003, 20:02:00) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> sys.modules.keys() ['copy_reg', 'locale', '__main__', 'site', '__builtin__', 'encodings', 'os.path' , 'encodings.encodings', 'encodings.codecs', 'ntpath', 'UserDict', 'encodings.ex ceptions', 'nt', 'stat', 'zipimport', 'warnings', 'encodings.types', '_codecs', 'encodings.cp1252', 'sys', 'codecs', 'types', '_locale', 'CLR', 'signal', 'linec ache', 'exceptions', 'os'] Note here ---------------------^^^ Paul. -- This signature intentionally left blank From jwsacksteder at ramprecision.com Wed Oct 1 08:45:23 2003 From: jwsacksteder at ramprecision.com (jwsacksteder at ramprecision.com) Date: Wed, 1 Oct 2003 08:45:23 -0400 Subject: how to create type libraries for py2exe? Message-ID: <71650A6F73F1D411BE8000805F65E3CB3B3646@SRV-03> I have a working COM object that registers and I can 'dispatch' correctly. I need register a type library for this project to integrate with my application- Crystal Reports. I understand I need to compose an IDL file, then process that with MIDL.exe to produce a .tlb file. That can then be add as a resource to the .dll that py2exe creates. HOWEVER- IDL is pretty intimidating if you don't know C++. Is there a way to automatically generate the IDL I need? I am under urgent time pressure, so I would prefer expediency over correctness. From peter at engcorp.com Tue Oct 14 22:36:34 2003 From: peter at engcorp.com (Peter Hansen) Date: Tue, 14 Oct 2003 22:36:34 -0400 Subject: assigning values to array element References: Message-ID: <3F8CB2B2.DEF2CB65@engcorp.com> Ben wrote: > > This may sound easy but I'm having trouble assigning values to array > element. My problem is as follows: > > m = ['Peter', 'Sam', 'Dave', 'Carl'] > for o in m: > # Here first o is 'Peter'.. I want to do something like this: > Peter = 10 > > # if i do %s %o = 10, it gives me error... > > How can I do it? You seem to want to create variables with names Peter, Sam, etc. If that's so, you should explain your problem in more detail, because doing this dynamically is useless: after all, how do you plan to *retrieve* those variables if you don't know in advance what they are called? What you are trying to do is probably better accomplished using Python dictionary type: # using your "m" list of names, above: d = {} for name in m: d[name] = 10 # then to access things, do this: print d['Peter'] If you need more, please explain the rationale behind the program, rather than just examples of code that didn't work, so we'll understand *why* you are trying to do what you are trying to do. -Peter From tim.one at comcast.net Fri Oct 10 14:37:51 2003 From: tim.one at comcast.net (Tim Peters) Date: Fri, 10 Oct 2003 14:37:51 -0400 Subject: Precision issue In-Reply-To: Message-ID: [Duncan Booth] > I know this is an FAQ, but the one thing I've never seen explained > satisfactorily is why repr(3.4) has to be '3.3999999999999999' rather > than '3.4'? Python doesn't do float<->string conversion itself. That's done by the platform C library. The IEEE-754 standard requires that if a 754 double is converted to a string with 17 significant decimal digits, then converted back to a 754 double again, you'll get back exactly the double you started with. Python does not guarantee that, and it can't, because the C library does the heavy lifting in both directions. But because Python use a C %.17g format, Python eval(repr(x)) == x holds on any platform whose C library meets the minimal relevant requirements of the 754 standard. I believe all major C libraries do meet this now. The 754 standard does not require that string->double or double->string round correctly in all cases. That's a (much) stronger requirement than that eval(repr(x)) == x. > ... > There's no reason why Python couldn't do the same: > > def float_repr(x): > s = "%.15g" % x > if float(s)==x: return s > return "%.17g" % x Sorry, but there is a reason: if done on a platform whose C library implements perfect-rounding double->string (e.g., I think gcc does now), this can hit cases where the string may not reproduce x when eval'ed back on a different platform whose C library isn't so conscientious but which nevertheless meets the 754 standard's more forgiving (than perfect rounding) requirements. This is acutely important because Python's marshal format (used for .pyc files) represents floats as repr'ed strings. By making repr() pump out 17 digits, we maximize the odds that .pyc files ported across platforms load back exactly the same 754 doubles across (754) platforms. > This would be MUCH friendlier for newcomers to the language. A decimal floating type would be truly friendlier for them. In extensive experience with Python using %.12g for repr(float) in the old days, the primary effect of that was to delay the point at which newcomers bumped into their first fatal fp "surprise", and *recognized* it as being fatal to them. I've come to love seeing newcomers whine about the output for, e.g., 0.1: they hit it early, and are immediately directed to the Appendix explaining what's going on. This spurs a healthy and necessary mental reset about how binary floating-point arithemtic really works. In return, what we see much less often now are complaints about binary fp surprises in much subtler contexts. If 3.4 got displayed as exactly "3.4", newcomers would face the much harder task of recognizing the subtle consequences of that, no, in reality it's not exactly 3.4 at all, and assuming that is can have catastrophic consequences. All that said, there's an implementation of IBM's (Mike Cowlishaw's) proposed standard decimal arithmetic in the Python CVS sandbox, begging for use, docs and improvement. That would match newcomer expectations much better, without contorted hacks trying to make it appear that it's something it isn't. Effort put there would address a cause instead of a symptom. From ngps at netmemetic.com Thu Oct 2 11:55:40 2003 From: ngps at netmemetic.com (Ng Pheng Siong) Date: 2 Oct 2003 15:55:40 GMT Subject: Best Bug Tracker on Zope platform ? References: <62f2814b.0309300355.6091dd84@posting.google.com> <874qyseuo7.fsf@tanya.home.spb> Message-ID: According to Eugene Morozov : > - JTracker (very robust and really simple -- my > personal choice) I just tried this one today. In the "create an issue" form, I left out email, it demanded that I supply one. I didn't notice it bounced me to a (semi?) blank form, so after I supplied an email address, it demanded something else. I zapped it. Downloaded Roundup after that and got it going. ZRoundup came up broken in my Zope 2.6.1 though. -- Ng Pheng Siong http://firewall.rulemaker.net -+- Manage Your Firewall Rulebase Changes http://sandbox.rulemaker.net/ngps -+- Open Source Python Crypto & SSL From jatwood at cvpjaws03.dhcp.cv.hp.com Fri Oct 24 13:04:20 2003 From: jatwood at cvpjaws03.dhcp.cv.hp.com (John Atwood) Date: Fri, 24 Oct 2003 17:04:20 +0000 (UTC) Subject: Static typing References: Message-ID: Pascal Costanza wrote: >Mastering a programming language is a very long process. > >> So you see that with different tools, you cannot do >> it in exactly the same way as with the old tools, and immediately you >> start complaining that the new tools have "less expressive power", >> just because you don't see that you have to use them in a different >> way. The "I can do lot of things with macros in Lisp that are >> impossible to do in other languages" claim seems to have a similar >> background. > >No, you definitely can do a lot of things with macros in Lisp that are >impossible to do in other languages. There are papers that show this >convincingly. Try >ftp://publications.ai.mit.edu/ai-publications/pdf/AIM-453.pdf for a >start. Then continue, for example, with some articles on Paul Graham's >website, or download and read his book "On Lisp". That's a great paper; however, see Steele's later work: http://citeseer.nj.nec.com/steele94building.html John From hungjunglu at yahoo.com Wed Oct 22 21:18:46 2003 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 22 Oct 2003 18:18:46 -0700 Subject: 'while' in list comprehension? References: <20031022175924.GA10716@jsaul.de> Message-ID: <8ef9bea6.0310221718.c13cec4@posting.google.com> jsaul wrote in message news:<20031022175924.GA10716 at jsaul.de>... > > foo = [ i for i in bar while len(i)>0 ] > > Is there any reason for not having this kind of thing? I actually > miss it pretty often. Could you provide an example where you need it? >From your message, it seems "bar" might be a list of strings. If so, you could use: foo = bar[:bar.index('')] regards, Hung Jung From mwh at python.net Fri Oct 17 07:29:38 2003 From: mwh at python.net (Michael Hudson) Date: Fri, 17 Oct 2003 11:29:38 GMT Subject: In need of c.l.p.discussion References: <3F8F02C0.69BB4C0D@alcyone.com> <3F8F0FD5.8386B56C@alcyone.com> Message-ID: <7h3n0c0m7h8.fsf@pc150.maths.bris.ac.uk> Rune Steffensen writes: > > A far better solution to your problem -- namely avoiding threads you do > > not want to see -- is to just use a killfile. > > I know. But, as I said in another posting in this thread, I'm not using > python in an active way these days, even if I probably will in the > future. So the maintainance would need more work, than the delete- > strategy. > > > Even really lousy newsreaders, like the one I still use > [snip] > > If you think Mozilla sucks, give Opera a try. I've been using it for news > for some weeks now, and I'm very satisfied. Doesn't Opera have a way of saying "I never want to see this thread again"? If it doesn't, I suggest finding a newsreader that does. If *that's* too much maintenence for you, not reading the list at all sounds the most sensible option. Cheers, mwh -- About the use of language: it is impossible to sharpen a pencil with a blunt axe. It is equally vain to try to do it with ten blunt axes instead. -- E.W.Dijkstra, 18th June 1975. Perl did not exist at the time. From jjl at pobox.com Fri Oct 10 14:56:50 2003 From: jjl at pobox.com (John J. Lee) Date: 10 Oct 2003 19:56:50 +0100 Subject: Preferred Python idiom for handling non-existing dictionary keys and why? References: Message-ID: <87ad88c45p.fsf@pobox.com> Quentin Crain writes: > (First, I would like to mention I did try to google > for the answer here!) > > Say I am populating a dictionary with a list and > appending. I have written it thusly: [...] You want the dict.setdefault method. John From bdesth.nospam at removeme.free.fr Wed Oct 8 15:48:39 2003 From: bdesth.nospam at removeme.free.fr (Bruno Desthuilliers) Date: Wed, 08 Oct 2003 21:48:39 +0200 Subject: print is not a function In-Reply-To: References: Message-ID: <3f8466fe$0$27050$626a54ce@news.free.fr> Karl Scalet wrote: > Hi, > > quite often there is a need to just print out the items of a list. > > [ prt(x) for x in my_list ] > > that would be nice, except prt() does not exist, and print is a > statement not a function, hence cannot replace prt as of above. > > I don't like to write d > def prt(x): > print x > beforehand and any lambda construct would not be so handy. > It should be a short one-liner. > Any ideas? import sys sys.stdout.write("hello world\n") HTH From nid_oizo at yahoo.com_remove_the_ Wed Oct 15 12:24:52 2003 From: nid_oizo at yahoo.com_remove_the_ (Nicolas Fleury) Date: Wed, 15 Oct 2003 12:24:52 -0400 Subject: Expat current line/column number Message-ID: Hi, Is it possible with xml.parsers.expat to get the current line and column number if an exception is raised by one of the callbacks (not necessary an xml.parsers.expat.ExpatError)? Thx and Regards, Nicolas Fleury From tjreedy at udel.edu Fri Oct 10 20:13:50 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 10 Oct 2003 20:13:50 -0400 Subject: Precision issue References: Message-ID: "Cameron Laird" wrote in message news:vodvspiogmil0f at corp.supernews.com... > In article , > Terry Reedy wrote: > >It is for decimally representing, as precisely as possible *with 17 > >digits*, the actual value. I presume that 17 in the minimum necessary > >to guarantee a unique, back-convertible prepresentation for every > >float. > Stuff in this area is difficult to express precisely. I'm > not sure what your, "I presume that ..." means. Here's one > way to think about that magic number: there are "floats" > which are distinct, but agree to sixteen (decimal-)digits > of accuracy. That is what I meant. 16 digits is not enough for binary float=> decimal rep to be one-to-one > Some (seventeen-digit) decimals canNOT be achieved through > a round trip. If you mean s != (sometimes) repr(eval(s)), of course; there are (I believe) fewer than 10**17 floats (ignoring exponents), so mapping in that direction cannot be onto. This is the fundamental problem; for any positive number of bits and decimals, the two sets have different sizes. Terry J. Reedy From ramen at lackingtalent.com Tue Oct 14 12:59:29 2003 From: ramen at lackingtalent.com (Dave Benjamin) Date: Tue, 14 Oct 2003 16:59:29 -0000 Subject: Preferred idion for adding instance methods Message-ID: I just noticed that the "new" module is deprecated in Python 2.3. Since the old way of adding a method to a particular instance (not its class) was to use new.instancemethod, I am guessing that we are now supposed to use types.MethodType. Is this the preferred idiom for adding an instance method? import new import types class Test(object): def __init__(self, x): self.x = x t = Test(42) def print_x(self): print self.x # The old way. #t.print_x = new.instancemethod(print_x, t, Test) # The new way? t.print_x = types.MethodType(print_x, t, Test) t.print_x() Thanks, Dave -- .:[ dave benjamin (ramenboy) -:- www.ramenfest.com -:- www.3dex.com ]:. : d r i n k i n g l i f e o u t o f t h e c o n t a i n e r : From pfleonard at hotmail.com Sun Oct 19 23:33:49 2003 From: pfleonard at hotmail.com (peter leonard) Date: Sun, 19 Oct 2003 20:33:49 -0700 Subject: Beginner question : skips every second line in file when using readline() Message-ID: Hi, I having a problem with reading each line from a text file. For example, the file is a text file named 'test.txt' with the following content : line 1 line 2 line 3 line 4 line 5 The following script attempts to print out each line : datafile ="C:\\Classifier\Data\\test.txt" dataobject = open(datafile,"r") while dataobject.readline() !="": line = dataobject.readline() print line However, the output from this script is : line 2 line 4 I'm sure this is a simple problem but I can't figure it after loking up several reference books and web pages. Any help would be greatly appreciated. Regards Peter _________________________________________________________________ Want to check if your PC is virus-infected? Get a FREE computer virus scan online from McAfee. http://clinic.mcafee.com/clinic/ibuy/campaign.asp?cid=3963 From benkial at hotmail.com Sat Oct 11 19:42:02 2003 From: benkial at hotmail.com (Ben Kial) Date: Sat, 11 Oct 2003 23:42:02 GMT Subject: Event driven programing using Python Message-ID: In Tkinter can I define events of my own other than the system defined events like "ButtonPress", "FocusIn"...? I'd like to practice some event driven programming in Python. Any help will be very much appreciated. Thanks in advance, Ben From ktilton at nyc.rr.com Fri Oct 3 09:33:25 2003 From: ktilton at nyc.rr.com (Kenny Tilton) Date: Fri, 03 Oct 2003 13:33:25 GMT Subject: Python syntax in Lisp and Scheme In-Reply-To: References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> Message-ID: Toni Nikkanen wrote: > kalath at lycos.com (Mark Brady) writes: > > >>just me, I prefer S-exps and there seems to be a rebirth in the Scheme >>and Common Lisp communities at the moment. Ironically this seems to >>have been helped by python. I learned python then got interested in >>it's functional side and ended up learning Scheme and Common Lisp. > > > It's be interesting to know where people got the idea of learning > Scheme/LISP from (apart from compulsory university courses)? We wonder alike. That's why I started: http://alu.cliki.net/The%20Road%20to%20Lisp%20Survey That recently got repotted from another cliki and it's a little mangled, but until after ILC2003 I am a little too swamped to clean it up. But there is still a lot of good stuff in there. On this page I grouped folks according to different routes to Lisp (in the broadest sense of that term): http://alu.cliki.net/The%20RtLS%20by%20Road You will find some old-timers because I made the survey super-inclusive, but my real interest was the same as yours: where are the New Lispniks coming from? Speaking of which, Mark Brady cited Python as a stepping-stone, and I have been thinking that might happen, but the survey has yet to confirm. Here's one: http://alu.cliki.net/Robbie%20Sedgewick's%20Road%20to%20Lisp So Ping! Mark Brady, please hie ye (and all the others who followed the same road to Lisp) to the survey and correct the record. I think > that for me, it was the LPC language used in LPmuds. It had a > frightening feature called lambda closures, and useful functions such > as map and filter. Then one day I just decided to bite the bullet and > find out where the heck all that stuff came from (my background was > strongly in C-like languages at that point. LPC is like C with some > object-oriented and some FP features.) > > Yes, I know, there's nothing frightening in lambda closures. But the > way they were implemented in LPC (actually just the syntax) was > terrible :) You could cut and paste that into the survey as well. :) kenny From stuart at bmsi.com Tue Oct 28 13:52:26 2003 From: stuart at bmsi.com (Stuart D. Gathman) Date: Tue, 28 Oct 2003 13:52:26 -0500 Subject: Getting real argv[0] in python Message-ID: I need to be able to obtain the real argv[0] (not the script name). The application is writing a CUPS backend in python. For some reason, CUPS decided to pass the URI as argv[0] (perhaps to ensure that CUPS will only ever run on Unix, since CUPS stands for Common *Unix* Printing System). The only solution I can think of is to write a C wrapper that inserts the original argv[0] before execing python with the script. Is there already a way to do this that I have missed? -- Stuart D. Gathman Business Management Systems Inc. Phone: 703 591-0911 Fax: 703 591-6154 "Confutatis maledictis, flamis acribus addictis" - background song for a Microsoft sponsored "Where do you want to go from here?" commercial. From $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk Wed Oct 1 22:32:04 2003 From: $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk (Stephen Horne) Date: Thu, 02 Oct 2003 03:32:04 +0100 Subject: "for" with "else"? References: <2c9knv86m1il4ajng85655dm7u5j5b992i@4ax.com> <2Ureb.10786$NX3.1457@newsread3.news.pas.earthlink.net> Message-ID: On Wed, 01 Oct 2003 03:31:10 GMT, "Andrew Dalke" wrote: >In my search, I didn't see any examples which were >better done with exceptions -- and since (string) exceptions >existed in the language for a long time (from the start >I would imagine and definitely pre-1.3, which is >about when I started), I find it hard to believe that >your statement reflects what really happened. You are quite right - I think I mentioned already in another post that I'd completely forgotten the break-on-found idiom until I read Michael Gearys post (I don't always read a thread fully before I reply to stuff). I still think that exception-based approaches are far from painful for this kind of stuff. However, with your example from binhex.py... for c in data: if not c.isspace() and (c<' ' or ord(c) > 0x7f): break else: finfo.Type = 'TEXT' The cleanest way to eliminate the 'break' and 'else' is probably as follows... try: c = data.next () while c.isspace() or (c<' ' or ord(c) > 0x7f) : c = data.next () except StopIteration : finfo.Type = 'TEXT' Or possibly... try : ifilter (lambda c : c in string.printable, data).next () except StopIteration : finfo.Type = 'TEXT' But these approaches both have a major failing - they don't express the intention well. Actually, there is a very clean and expressive approach that I'd use if I had access to my own library stuff... if mylib.exists (lambda c : c in string.printable, data) : finfo.Type = 'TEXT' with, in 'mylib'... def exists (pred, seq) : for i in seq : if pred(i) : return True return False ...which is, of course, cheating as that return is just as unstructured as a break - but I don't mind cheating too much when it is localised in a trivial library function. -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From op73418 at mail.telepac.pt Thu Oct 16 10:26:43 2003 From: op73418 at mail.telepac.pt (Gonçalo Rodrigues) Date: Thu, 16 Oct 2003 15:26:43 +0100 Subject: inner classes in python as inner classes in Java References: <0Ljjb.221887$hE5.7473075@news1.tin.it> Message-ID: <19atovkdjbep7002u21e6nmrenb6blj6o5@4ax.com> On Thu, 16 Oct 2003 09:48:52 +0200, "Carlo v. Dango" wrote: [text snipped] > >aaaah come on :) you really cannot see the nice things of having a scope >for inner class instances?? It's like inner method.. atleast they share >scope with their outer method... if it didn't it would render inner >methods almost useless.. > >class A(object): > def foo(self): > i = 3 > def bar(): > print i > > bar() What do you *really* want? As far as I remember (it's been a long time since I've dealt with Java), the biggest use for inner classes in Java is in faking closures. That's a non-issue in Python, in part because *every* object is a first class citizen, functions, methods and classes included. There is no such thing as a class-scope, only function definitions open a new (local) scope. As others have posted you *can* fake that with __setattr__ and/or a metaclass solution, but *why* would you want to go down that path that is what I cannot fathom. With my best regards, G. Rodrigues From fjh at cs.mu.oz.au Wed Oct 29 04:26:01 2003 From: fjh at cs.mu.oz.au (Fergus Henderson) Date: Wed, 29 Oct 2003 09:26:01 GMT Subject: Python from Wise Guy's Viewpoint References: <30dv61-ni5.ln1@ID-7776.user.dfncis.de> Message-ID: <3f9f87a6$1@news.unimelb.edu.au> Pascal Costanza writes: >You can't have metacircularity in a statically type language. Could you explain exactly what you mean by "metacircularity"? Anyway, I'm skeptical of this claim. At very least, it should be possible to have a language which is mostly statically typed (i.e. statically typed by default), even if on some occaisions you have to fall back to dynamic typing. Whether or not any existing statically typed language implementations support this sort of thing is another question... -- Fergus Henderson | "I have always known that the pursuit The University of Melbourne | of excellence is a lethal habit" WWW: | -- the last words of T. S. Garp. From peter at engcorp.com Fri Oct 3 15:49:59 2003 From: peter at engcorp.com (Peter Hansen) Date: Fri, 03 Oct 2003 15:49:59 -0400 Subject: Python 2.3.2 RPM's for Redhat 8.0 or Python source RPM and upgradeprocedure? References: <200310031043.31734.scott_list@mischko.com> Message-ID: <3F7DD2E7.82C19EF1@engcorp.com> Skip Montanaro wrote: > > Scott> Does anynone have these available? I'd like to upgrade (hoping > Scott> it doesn't break my Redhat install). > > Sean Reifschneider builts them as a service to the community. I suspect it > will be a few days to a week before he releases 2.3.2 RPMs. > > Scott> If I upgrade, all my site-packages have to be reinstalled to the > Scott> new site-packages directory right? > > No, the installation will go to (I think) /usr/local/lib/python2.3 or > /usr/lib/python2.3. The site-packages directory will thus remain the same. Unless the OP is upgrading from a pre-2.3 version of Python. I don't think he says enough to know for sure, but I think we can infer from his comment about breaking the Redhat install that he is talking about upgrading from Python 2.2, not 2.3.x. Sean, I believe you *would* have to copy over the site-packages contents from the 2.2 installation to the 2.3 folder, but don't count on everything working... only pure Python code will generally continue to work without a new download and install of a 2.3-compatible version of your extension. -Peter From adalke at mindspring.com Wed Oct 22 02:27:15 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Wed, 22 Oct 2003 06:27:15 GMT Subject: Why don't people like lisp? References: <8Nnlb.619$I04.380@newsread4.news.pas.earthlink.net> <7xoew9lvy6.fsf@ruckus.brouhaha.com> Message-ID: <7rplb.712$I04.647@newsread4.news.pas.earthlink.net> Paul Rubin: > You could of course do something similar in Lisp, but normally you'd > just use S-expressions instead of concocting your own weird syntax > every time you want to build a small language into something. Then > you just use the regular Lisp "read" function and the S-expressions > get parsed automatically for you. Your whole parser becomes just one > line of code. Ahh, but that's writing the domain language to fit the implementation language. The moral equivalent for Python would be to use Python's syntax to define a function, which is simple. Eg, Suppose the domain language required that identifiers be labeled with parens, as in a chemistry specific language where you might want 1-1'-(ethylenediimino)di-2-proponal as a native identifier. Andrew dalke at dalkescientific.com From skip at pobox.com Fri Oct 31 16:55:36 2003 From: skip at pobox.com (Skip Montanaro) Date: Fri, 31 Oct 2003 15:55:36 -0600 Subject: Py2exe invalid syntax???/i hate distutils In-Reply-To: References: Message-ID: <16290.55896.983657.905118@montanaro.dyndns.org> ray>

ray>

This is the syntax i'm using: python setup.py p2exe

Try python setup.py install (and also try turning off the HTML email). Skip From duncan at NOSPAMrcp.co.uk Fri Oct 10 08:09:15 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Fri, 10 Oct 2003 12:09:15 +0000 (UTC) Subject: Precision issue References: <8lvhb.258000$R32.8375967@news2.tin.it> <7h3r81lb9u6.fsf@pc150.maths.bris.ac.uk> Message-ID: Michael Hudson wrote in news:7h3r81lb9u6.fsf at pc150.maths.bris.ac.uk: >> I know this is an FAQ, but the one thing I've never seen explained >> satisfactorily is why repr(3.4) has to be '3.3999999999999999' rather >> than '3.4'? > > I believe "computational and code complexity" is the main answer to > that one. > > Start here > > http://citeseer.nj.nec.com/gay90correctly.html The code I gave isn't exactly complex, even when you rewrite it in C. >> def float_repr(x): >> s = "%.15g" % x >> if float(s)==x: return s >> return "%.17g" % x >> >> This would be MUCH friendlier for newcomers to the language. > > It would be nice, but I think it's pretty hard to do efficiently. Tim > Peters would be more certain than me :-) > > "Patches welcome" might apply, too. I don't think your suggested > float repr will fly, I'm afraid... > I'm happy to do a patch if there is any chance of it being accepted. Obviously doing the conversion twice makes the code slower, but I'm not sure how critical it would be given that its a pretty fast operation to begin with: C:\Pythonsrc\python\dist\src\PCbuild>python ..\lib\timeit.py "repr(3.4)" 100000 loops, best of 3: 10.5 usec per loop C:\Pythonsrc\python\dist\src\PCbuild>\python23\python ..\lib\timeit.py "repr(3.4)" 100000 loops, best of 3: 7.58 usec per loop So its about a third slower, but you have to do 300,000 reprs before you lose 1 second of cpu time. -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From tjreedy at udel.edu Wed Oct 15 10:42:50 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 15 Oct 2003 10:42:50 -0400 Subject: BIG successes of Lisp (was ...) References: <63bjb.774440$YN5.758743@sccrnsc01> Message-ID: "Scott McKay" wrote in message news:63bjb.774440$YN5.758743 at sccrnsc01... > > wrote in message > news:BYIFD1LVHXB1ALLZLRH3P2BZOIIFHWLSJ4B4BRP3 at ziplip.com... > > In the context of LATEX, some Pythonista asked what the big > > successes of Lisp were. I think there were at least three *big* > > successes. > > > a. AFAIK Orbitz frequently has to be shut down for maintenance > > (read "full garbage collection" - I'm just guessing: with > > generational garbage collection, you still have to do full > > garbage collection once in a while, and on a system like that > > it can take a while) > > > > Not true. The servers do get restarted a couple of times > a day to get new data loads, which are huge. Does Orbitz have anything to do with Python? If not, please leave c.l.py off further discussion thereof. From edi at agharta.de Tue Oct 14 07:38:16 2003 From: edi at agharta.de (Edi Weitz) Date: 14 Oct 2003 13:38:16 +0200 Subject: BIG successes of Lisp (was ...) References: Message-ID: <87y8voaw2f.fsf@bird.agharta.de> On Mon, 13 Oct 2003 16:23:46 -0700 (PDT), mike420 at ziplip.com wrote: > a. AFAIK Orbitz frequently has to be shut down for maintenance Where do you "know" that from? Have you any quotes or numbers to back up your claims or are you just trying to spread FUD? > (read "full garbage collection" - Others have debunked this already. > I'm just guessing: Please leave the guessing to people who are better at it. Edi. From $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk Mon Oct 13 12:28:58 2003 From: $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk (Stephen Horne) Date: Mon, 13 Oct 2003 17:28:58 +0100 Subject: Car and cdr (Re: Python syntax in Lisp and Scheme) References: <6CZgb.3273$dn6.860@newsread4.news.pas.earthlink.net> <3m3lovgn8obb80b3t2rv96ik5cndfpietj@4ax.com> Message-ID: On Mon, 13 Oct 2003 14:08:17 +0200, Pascal Costanza wrote: >Stephen Horne wrote: >> On Mon, 13 Oct 2003 15:28:57 +1300, "Greg Ewing (using >> news.cis.dfn.de)" wrote: >>>From that point of view, "car" and "cdr" are as good >>>as anything! >> >> >> "left" and "right" - referring to 'subtrees'? >Note: Why break anyone else's code just because you prefer a different >vocabulary? I wasn't really suggesting a change to lisp - just asking if they might be more appropriate names. Actually, I have been having a nagging doubt about this. I had a couple of phases when I learned some basic lisp, years ago. A bit at college in the early nineties, and IIRC a bit when I was still at school in the mid eighties. This was well before common lisp, I believe. Anyway, I'd swear 'car' and 'cdr' were considered backward compatibility words, with the up-to-date words (of the time) being 'head' and 'tail'. Maybe these are/were common site library conventions that never made it into any standard? This would make some sense. After all, 'head' and 'tail' actually imply some things that are not always true. Those 'cons' thingies may be trees rather than lists, and even if they are lists they could be backwards (most of the items under the 'car' side with only one item on the 'cdr' side) which is certainly not what I'd expect from 'head' and 'tail'. -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From tjreedy at udel.edu Thu Oct 16 10:47:32 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 16 Oct 2003 10:47:32 -0400 Subject: Python syntax in Lisp and Scheme References: <8CVgb.8$KR3.1846@typhoon.nyu.edu> <20031014050046.GM1454@mapcar.org> <87fzhtlvni.fsf@thalassa.informatimago.com> Message-ID: <7q2dneIXY78AMhOiRVn-gA@comcast.com> > Ultimately, all these Python v Lisp arguments boil down to the > differing philosophies: Agreed so far... > Python: > - Keep it simple Simple can be powerful ;-) > - Guido knows what's best for me Hogwash. I don't believe that, and neither does Guido. > Lisp: > - Provide as much power to the programmer as possible, out of the box Vroom, vroom, maybe I should take it out for a spin .... at the local racetrack. > - I know what's best for me, and I want a language that allows me to > invest effort in making difficult things easy for me This I agree with, and it is why I currently choose Python. Presenting the choice as 'toady language' versus 'real man language' is rather biased. Terry J. Reedy From spam at magnetic-ink.dk Thu Oct 16 17:55:16 2003 From: spam at magnetic-ink.dk (Klaus Alexander Seistrup) Date: Thu, 16 Oct 2003 21:55:16 +0000 (UTC) Subject: In need of c.l.p.discussion References: <3F8F02C0.69BB4C0D@alcyone.com> <3F8F0FD5.8386B56C@alcyone.com> Message-ID: <3f8f13c4-b57ff7ba-a857-423f-b79d-d32256c4d1c6@news.szn.dk> Erik Max Francis wrote: > Announcements are for comp.lang.python.announce (moderated), and > discussion is for comp.lang.python (unmoderated). (Except many tend to announce in both groups. :-() // Klaus -- ><> unselfish actions pay back better From luca.masini at t-online.de Sat Oct 4 17:22:53 2003 From: luca.masini at t-online.de (Luca Masini) Date: Sat, 04 Oct 2003 23:22:53 +0200 Subject: freezy.py and pygtk Message-ID: Hi, I tryed to freeze a pygtk script but I get the following error message when I run the freezed binary: MSG: Traceback (most recent call last): MSG: File "freezme.py", line 24, in ? MSG: import gtk MSG: File "/usr/local/lib/python2.3/site-packages/gtk- 2.0/gtk/__init__.py", line 43, in ? MSG: from _gtk import * MSG: SystemError: dynamic module not initialized properly This is the script: #! /usr/bin/env python import sys sys.path = [ '.', '/usr/local/lib', '/usr/local/lib/python2.3', '/usr/local/lib/python2.3/plat-linux-i386', '/usr/local/lib/python2.3/lib-dynload', '/usr/local/lib/python2.3/site-packages', '/usr/local/lib/python2.3/site-packages/gtk-2.0', '/usr/local/lib/python2.3/site-packages/gtk-2.0/gtk' ] from pprint import pprint import gtk pprint( dir( gtk ) ) and this is the freezing command script used: frizza="/usr/src/Python-2.3.2c1/Tools/freeze/freeze.py" $frizza -a gtk=/usr/local/lib/python2.3/site-packages/gtk-2.0/gtk -o frizzing freezme.py cd frizzing make The _gtk is a shared library (/usr/local/lib/python2.3/site-packages/gtk- 2.0/gtk/_gtk.so). When loaded from inside the freezed version I get that error. Any suggestion ? tanks in advance. Luca Masini. From aleax at aleax.it Fri Oct 10 12:54:46 2003 From: aleax at aleax.it (Alex Martelli) Date: Fri, 10 Oct 2003 16:54:46 GMT Subject: The compiler canard References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> <92c59a2c.0310031345.57d20631@posting.google.com> <87llrvs4yw.fsf@bird.agharta.de> <7xu16jmf57.fsf@ruckus.brouhaha.com> Message-ID: Lulu of the Lotus-Eaters wrote: ... > Python never had an "aspiration" of being "just a scripting language", Hmmm, at the start it sure seemed like that. Check out http://www.python.org/search/hypermail/python-1992/0001.html actually from late '91. By 1991 Guido was already calling Pyhton "a prototyping language" and "a programming language" (so, the "just a scripting language" was perhaps only accurate in 1990), but in late '91 he still wrote: """ The one thing that Python definitely does not want to be is a GENERAL purpose programming language. Its lack of declarations and general laziness about compile-time checking is definitely aimed at small-to-medium-sized programs. """ Apparently, it took us (collectively speaking) quite a while to realize that the lack of declarations and compile-time checks aren't really a handicap for writing larger programs (admittedly, Lispers already knew it then -- so did I personally, thanks also to experiences with e.g. Rexx -- but I didn't know of Python then). So, it _is_ historically interesting to ascertain when the issue of large programs first arose. > nor WAS it ever such a thing. From its release, Python was obviously a > language very well suited to large scale application development (as Well, clearly that was anything but obvious to Guido, from the above quote. Or maybe you mean by "release" the 1.0.0 one, in 1994? At that time, your contention becomes quite defensible (though I can't find a Guido quote to support it, maybe I'm just not looking hard enough), e.g. http://www.python.org/search/hypermail/python-1994q1/0050.html where Bennett Todd muses """ I think Python will outstrip every other language out there, and Python (extended where necessary in C) will be the next revolutionary programming tool ... Perl seems (in my experience) to be weak for implementing large systems, and having them run efficiently and be clear and easy to maintain. I hope Python will do better. """ So, here, the idea or hope that Python "will do better" (at least wrt Perl) "for implementing large systems" seems already in evidence, though far from a community consensus yet. I do find it fascinating that such primary sources are freely available on the net -- a ball for us amateur historians...!-) Alex From robin at jessikat.fsnet.co.uk Wed Oct 15 18:55:58 2003 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Wed, 15 Oct 2003 23:55:58 +0100 Subject: reasonably priced reporting solution References: <7x7k36td9p.fsf@ruckus.brouhaha.com> <2ferov40tvrbejgg20ic27l5pm9mteh1q8@4ax.com> <7x7k36f8zu.fsf@ruckus.brouhaha.com> Message-ID: In article <7x7k36f8zu.fsf at ruckus.brouhaha.com>, Paul Rubin writes >Larry goodman writes: >> >See http://www.reportlab.org for example. >> >> But this is free for only GPL apps right? My app will be closed >> source. The only price i see there is 25,000 for their enterprise SDK >> and that is way out of my range. > >According to their developers faq: > > The ReportLab toolkit and most of our other Open Source tools are > available under the BSD license. This means that you can basically do > anything you want with it, including using it in a commercial package. > >So you should be ok. That is indeed true! At Andy Robinson's command I copied the template BSD license and tried to insert the relevant data in the right places. Personally I prefer the ASL (Anarchist Software License) http://groups.google.com/groups?q=anarchist+software+license&hl=en&lr=&i e=UTF-8&selm=igRpPUAi30U2Ewmt%40jessikat.demon.co.uk&rnum=1 but Andy differs as he's a bit more serious. -- Robin Becker From uche at ogbuji.net Wed Oct 8 10:04:11 2003 From: uche at ogbuji.net (Uche Ogbuji) Date: 8 Oct 2003 07:04:11 -0700 Subject: xml.dom.minidom question References: <3f79ad4b$0$10696$ba620e4c@reader2.news.skynet.be> <2mjeb.10237$NX3.9179@newsread3.news.pas.earthlink.net> Message-ID: "Greg Krohn" wrote in message news:<2mjeb.10237$NX3.9179 at newsread3.news.pas.earthlink.net>... > "Geiregat Jonas" wrote in message > news:3f79ad4b$0$10696$ba620e4c at reader2.news.skynet.be... > > I'm using xml.dom.minidom, I get some data by using > > obj.getElementsByTagName("name")[0] then I have an object, but how can I > > get the data between the tags ? I could do .toxml() and then strip it > > away. But is there a better way maybe a function made for it ? > > Also is it possible using the xml.dom.minidom module to create modify an > > xml file ? > > Given Greg, 'Greg' is considered an element inside the 'name' > element. So, all you have to do is go one level of elements deeper. You mean it's considered a text node inside of the 'name' element node. I'll point out that it might actually be more than one text node. Only safe way is to use the normalize() method. Better yet, why torture yourself with DOM API, especially when all you need is to extract data from XML files? My recommendations would be to use Anobind, Elementtree, gnosis.xml.objectify or 4XPath (an advanage of XPath is that at least the extraction expression is ross-language): Anobind: http://uche.ogbuji.net/tech/4Suite/anobind/ http://www.xml.com/pub/a/2003/08/13/py-xml.html Elementtree: http://effbot.org/zone/element-index.htm http://www.xml.com/pub/a/2003/02/12/py-xml.html gnosis.xml.objectify: http://www.xml.com/pub/a/2003/07/02/py-xml.html http://www-106.ibm.com/developerworks/xml/library/x-matters11.html 4XPath: http://uche.ogbuji.net/tech/akara/nodes/2003-01-01/basic-xpath http://www.xml.com/pub/a/2002/10/16/py-xml.html Good luck. --Uche http://uche.ogbuji.net From dthierbach at gmx.de Fri Oct 24 07:58:30 2003 From: dthierbach at gmx.de (Dirk Thierbach) Date: Fri, 24 Oct 2003 13:58:30 +0200 Subject: Test cases and static typing (was: Python from Wise Guy's Viewpoint) References: <3f972315$1@news.unimelb.edu.au> <3638acfd.0310230039.306b14f@posting.google.com> <87ekx4xaym.dlv@wanadoo.fr> <87znfsvuqh.dlv@wanadoo.fr> Message-ID: <6ogn61-f61.ln1@ID-7776.user.dfncis.de> Pascal Costanza wrote: > Remi Vanicat wrote: >>>>> In a statically typed language, when I write a test case that >>>>> calls a specific method, I need to write at least one class that >>>>> implements at least that method, otherwise the code won't >>>>> compile. >>>>Not in ocaml. >>>>ocaml is statically typed. >> It make the verification when you call the test. I explain : >> let f x = x #foo >> >> which is a function taking an object x and calling its method >> foo, even if there is no class having such a method. >> >> When sometime latter you do a : >> >> f bar >> >> then, and only then the compiler verify that the bar object have a foo >> method. BTW, the same thing is true for any language with type inference. In Haskell, there are to methods and objects. But to test a function, you can write test_func f = if (f 1 == 1) && (f 2 == 42) then "ok" else "fail" The compiler will infer that test_func has type test_func :: (Integer -> Integer) -> String (I am cheating a bit, because actually it will infer a more general type), so you can use it to test any function of type Integer->Integer, regardless if you have written it already or not. > Doesn't this mean that the occurence of such compile-time errors is only > delayed, in the sense that when the test suite grows the compiler starts > to issue type errors? As long as you parameterize over the functions (or objects) you want to test, there'll be no compile-time errors. That's what functioncal programming and type inference are good for: You can abstract everything away just by making it an argument. And you should know that, since you say that you know what modern type-systems can do. But the whole case is moot anyway, IMHO: You write the tests because you want them to fail until you have written the correct code that makes them pass, and it is not acceptable (especially if you're doing XP) to continue as long as you have failing tests. You have to do the minimal edit to make all the tests pass *right now*, not later on. It's the same with compile-time type errors. The only difference is that they happen at compile-time, not at test-suite run-time, but the necessary reaction is the same: Fix your code so that all tests (or the compiler-generated type "tests") pass. Then continue with the next step. I really don't see why one should be annoying to you, and you strongly prefer the other. They're really just the same thing. Just imagine that you run your test suite automatically when you compile your program. - Dirk From donn at u.washington.edu Fri Oct 17 16:32:56 2003 From: donn at u.washington.edu (Donn Cave) Date: Fri, 17 Oct 2003 13:32:56 -0700 Subject: assignment expression peeve References: <7x1xtfkuky.fsf@ruckus.brouhaha.com> <6q6jb.10882$fv4.3354@nwrdny02.gnilink.net> <7xk77676bt.fsf@ruckus.brouhaha.com> <6ZWjb.49$Vf7.34@nwrdny02.gnilink.net> Message-ID: In article <6ZWjb.49$Vf7.34 at nwrdny02.gnilink.net>, Carl Banks wrote: ... > My contention is that a large part of what makes something "readable" > in code is that is it resembles, to some degree, natural language. > This is because we can use the parts of our brain that parse natural > language to help us parse code. Makes sense, pretty obvious. > > The thing is, these analogues have to match syntactically as well as > semantically. In other words, if the language construct in question > does not have an analogue that matches syntactically, then we have to > acquire the ability to parse it. Furthermore, if it turns out that > our "language circuits" are not able to internalize an unusual syntax, > then parsing it will always require intellectual effort. (Whether > this is true of assignment expression I won't speculate at this > moment.) In the end, we have something that is at least harder to > learn, and possibly takes more effort to read. This part is less obvious. Syntactical relationships are learned, and arguably learned in a very context sensitive way. Computer programming languages are relatively simple and regular, and it is not clear that they depend a lot on congruence with some natural language. > Now, your example does manage to communicate the semantics of > assignment expression (unlike Rubin's example, which didn't > communicate that anything was being assigned). However, I would say > your example still is not a proper analogy, for a very simple reason: > most people read computer programs as imperative, while your example > is declarative. > > I hope I don't have to argue the point that most people think of > programming as imperative. I believe programmers think of "a=b" as > "Set a to b," not "a's value becomes b's value". Therefore, I don't > consider a declarative clause to be an analogue of an assignment; it > is both syntactically and semantically different. If we stipulate that we are talking about Python programmers, maybe. In more general terms, though, I think it could be argued that assignment actually doesn't play much of a role in natural speech anyway, whether in the declarative or imperative sense. Unless you count lexical function, but you're talking about syntax. This should be bad news for Python, but by the time people get here it doesn't matter much. Moreover, I think you should probably quit while you're ahead, because I have a hunch that the point you're pushing there would actually work against you if it were more patently true. Suppose the syntax actually were "set a to b", or of course more like "set `a b" because this isn't Applescript or Cobol. Borrow the time machine and make it so. Now, will this turn out to be an expression? Very good odds, because now it's just a function. Functions can be imperative, and they're certainly expressions. Basically, I don't think you want to tie the quality of a computer programming language to its congruence with English syntactical forms. If there were a clear case for that, I think the FPL crowd would come out way ahead. > When I look at a statement or an expression, I prefer that I can look > at it and know that exactly ONE thing happens. Either it has a side > effect, or it returns a value: not both. (Although I'm not opposed to > stuff like readline(), which affect its file object and returns a > value, as long as the side effects are contained.) Assignment > expressions are, of course, the epitome of both at the same time, > which is the real reason I have such a distaste for them. > > It would be really nice (generally, not Python in particular) if we > could have all things that return values be expressions, and all > things that have side effects be statements, AND be able to implement > it in a practical way. > > I'm not sure if it's practical, thought; Ada does (or tries to do) > something like it, and it went a little too far. Probably didn't go near far enough. You have to get a look at Haskell. Whether it's practical is endlessly debatable, and I'm not sure it exactly does what you say there ... or maybe you'd have to program in Haskell to see what you're saying. But it is rather rigorous in this respect. Donn Cave, donn at u.washington.edu From peter at javamonkey.com Thu Oct 30 18:29:00 2003 From: peter at javamonkey.com (Peter Seibel) Date: Thu, 30 Oct 2003 23:29:00 GMT Subject: Explanation of macros; Haskell macros References: <87brs2tjut.fsf@memetrics.com> <87he1rdt9d.fsf@memetrics.com> Message-ID: "Anton van Straaten" writes: > Peter Seibel wrote: > > Joachim Durchholz writes: > > > > > Peter Seibel wrote: > > > > Joachim Durchholz writes: > > > > > > > >>Efficiency issues aside: how are macros more intuitive than quoting? > > > > Or you could do this: > > > > (when (> x y) #'(lambda () (print x))) > > > > which could work but seems a bit convoluted (i.e. unintuitive) > > > > compared to the macro version. > > > > > > Um, right, but that's just a question of having the right syntactic > sugar. > > > > Uh right, that's what macros are for, providing the syntactic sugar. > > Yes, but the point is that with a concise syntax for lambda, entire > classes of macros can become unnecessary. That's how Smalltalk > handles 'if', for example - no macros or special forms needed. Okay, so I picked an unfortunate example in that it also falls in the class of macros that become unecessary when other bits of syntactic sugar are provided. How about this one. Which is more intuitive? This: (defun foo () (print "hello, world"))) Or this: (progn (eval-when (:compile-toplevel) (excl::check-lock-definitions-compile-time 'foo 'function 'defun (fboundp 'foo)) (push 'foo excl::.functions-defined.)) (progn (eval-when (:compile-toplevel) (excl::check-de-argdecl-change 'foo 'nil)) (declaim (excl::dynamic-extent-arguments nil foo))) (setf (fdefinition 'foo) (let ((excl::f (named-function foo (lambda nil (block foo (print "hello, world")))))) (excl::set-func_name excl::f 'foo) excl::f)) (remprop 'foo 'excl::%fun-documentation) (record-source-file 'foo) 'foo) -Peter -- Peter Seibel peter at javamonkey.com Lisp is the red pill. -- John Fraser, comp.lang.lisp From aleax at aleax.it Wed Oct 29 15:41:08 2003 From: aleax at aleax.it (Alex Martelli) Date: Wed, 29 Oct 2003 20:41:08 GMT Subject: PEP 322: Reverse Iteration (REVISED, please comment) References: <5d83790c.0310281022.6264aa16@posting.google.com> <3f9ec63f$1@brateggebdc5.br-automation.co.at> Message-ID: Raymond Hettinger wrote: >> The static method approach would clearly document that the >> result is an iterator (which none of the other names proposed >> really does IMHO) > > Better name are welcome! > > Moving it somewhere else is not open. It is proposed as a builtin for a > reason -- it is a core looping tool like zip() or enumerate() and it is I don't think it has anywhere like the frequency of use of either. > Static methods, class methods, and weird descriptors be darned, this is > not an exercise in how weirdly it can be implemented just to avoid > having a builtin. I just don't think it's worth making a built-in. > Would everything be somehow better if Alex's wonderful sum() had > been implemented as a int.sum() classmethod or was tucked way in > another module? int.sum would be a disaster either way: if it was forced to return an int it would reduce use cases substantially; if it wasn't it would be just weird. math.sum would be arguably equivalent to sum as a built-in -- a tad less immediately accessible, but perhaps superior in that it immediately suggests it's about numbers only, so we'd avoid the icky performance trap you now get with sum(manylists, []) {which makes sum only 2/3 wonderful at best -- fine with numbers ONLY}. > Of course not! Likewise, would zip() or enumerate() > be successful solutions to lock-step iteration and the loop-counter > problems if they were iter.zip() and iter.enumerate()? No, of course not. zip is currently an INFERIOR solution for lock-step iteration: your itertools.izip is much better for that. Unfortunately zip IS constrained to return a list BUT that fact is not reflected in it being a classmethod list.zipped (we didn't have classmethods when zip was introduced, so that wasn't an option). If it had been made one, then by now we might have a built-in version of izip, sigh. Your enumerate is excellent, and just as frequently used as izip. I prefer it as a builtin -- though I wouldn't be heartbroken if it had been in itertools, but it's better in the builtins _because_ it's so frequently used. Unfortunately we have too many and inappropriate builtins and they're not going to go away until 3.0 (years away). This raises the bar for other not-obviously-indispensable built-ins more than it would be sensible to do in a hypothetical "greenfield design". > Let's put an end to this silliness right now. The idea is offered as a > builtin or not at all; otherwise, the existing [::-1] starts to look > better. You're clearly overwrought, so I won't "see" that "silliness" and get offended by it. If the choice was only to have the reverser (by whatever name) as a built-in or not at all, I'd be -0 on the reverser -- slightly against, though not enough to bother opposing it. If it could be sited somewhere appropriate (ok, not as iter.reversed if that's technically unfeasible -- i did say "appropriate":-) I'd be +1. > The challenge with a PEP this simple is that experts feel this > overpowering urge to apply all their know-how and transform > in to something other than a clean, fast, simple solution. The crux of our disagreement, namecalling apart, might be highlighted by your assertion in another short and emotional post: > This is supposed to be something you can teach in the first half-hour I can't imagine "teaching this in the first half-hour" of any Python course I teach. There are FAR too many other functions, including non-builtin ones such as sys.exit, and some in itertools too, that are more important than this, in my own assessment. So we disagree about frequence of usage, and consequently "warrantedness" as a built-in -- big deal. I honestly don't understand how this purely technical disagreement can explain these intense emotions. _I_ am supposed to be the Latin, Mediterranean, hot-blooded enthusiast, after all, and on average I think I cover the role adequately. Oh well, with the incredible amount of good things you've done for Python development, I guess you're surely entitled to blow your top occasionally, if that's your preference. Also, presumably, to get your pet built-in into the language, as you've slipped it past Guido. As for name, I therefore second the neatest suggestion I've seen: since it IS a reversed iter, and we can't directly call it that, then: reti Hey, it IS short, so if it's gonna be so heavily used, good thing, no?-) Alex From bvdpoel at kootenay.com Sun Oct 12 19:45:44 2003 From: bvdpoel at kootenay.com (Bob van der Poel) Date: Sun, 12 Oct 2003 16:45:44 -0700 Subject: unintuitive dict timings In-Reply-To: References: <3f89a527_1@dns.sd54.bc.ca> Message-ID: <3f89e8bf$1_1@dns.sd54.bc.ca> Alex Martelli wrote: > > def sede(key, val): > d.setdefault(key, []).append(val) > > appears to be very marginally fastest, but again it's a close call: Ahhh, an example of setdefault(). I looked at this in the docs but it really didn't make much sense.... I'll give this a try just to see what difference it makes. Thanks. -- Bob van der Poel ** Wynndel, British Columbia, CANADA ** EMAIL: bvdpoel at kootenay.com WWW: http://www.kootenay.com/~bvdpoel From contact at alanlittle.org Thu Oct 9 07:56:23 2003 From: contact at alanlittle.org (Alan Little) Date: 9 Oct 2003 04:56:23 -0700 Subject: Could a single web framework popularize Python? References: Message-ID: <4ef0f3a4.0310090356.4908b1b3@posting.google.com> I'm a beginner at python in my spare time. In my day job I'm an experienced (16 years) corporate developer who has worked on a lot of big database systems and a couple of java/XML web services projects. I'm finding python much more pleasant and productive to work with than java, but it's frustrating that there is no clear (de facto) standard for developing web systems. I've been following this discussion with interest. Here are my thoughts on the subject - which are a series of semi-disconnected bullet points, not a coherent essay. I see no real likelihood of python ever eating a significant chunk of the corporate big systems market - there's too much already invested in J2EE (not to mention older architectures that are still heavily used like CORBA and CICS). Java is more than good enough for the job and the skills are readily available. Why would anybody risk their company and their job on a completely unproven environment just because it happens to use a nicer programming language? Coding productivity as such is less important in this environment than proven reliability and compatibility with existing environments. Yes I know there are exceptions. "Google uses python" etc. etc. Google started four years ago and did not have millions already invested in Java, Cobol, SAP, Oracle business-critical systems. And Google uses python for what? If they use it to drive their extremely high traffic and usually admirably fast web front end, they're unlikely to tell anyone how. And even if they did, their problem is very large numbers of simple, read-only transactions none of which matter individually. This is entirely different from, say, a typical financial system where you have fairly large numbers of update transactions, some of them complex, where the integrity of individual transactions matters a great deal. What do you mean by a "web framework"? In the Java world, JSP and servlets are a subset of J2EE, the rest of which is aimed at scaleability and transaction integrity for big corporate applications that might just happen to have a web interface as one of their front ends. (A large proportion of corporate back office systems that are *really* serious about scaleability and transaction integrity are probably still running CICS on mainframes, but that's a whole 'nother story). Full-blown J2EE is overkill for [practically anything?] applications that just want read & update one database via a web front end. So are you talking about a python equivalent of Tomcat, a python equivalent of jBoss, or a python equivalent of the J2EE standard (with something like Tomcat as a reference implementation of part of it), where different products could implement different subsets but there would be at least some hope of interoperability and portability? I'm not necessarily saying that an overblown formal standard like J2EE is the best way to go. "Rough consensus and running code" is a better way to arrive at de facto standards that actually work in the long run. But in the python web world at the moment there seems to be a surfeit of "running code" in varying states of maturity, and no discernible "rough consensus" about how to hang it all together. Learning J2EE for a Java programmer is easy. If you're being paid by your employer to learn it, you use what they use. If you're doing it with your own time & money, the only decision you have to make is which servlet engine to use in front of jBoss. Either way, you spend maybe half a day installing and messing about with deployment files, and you're off. You may not be taking much advantage of all the facilities the environment has to offer, but you're up and running and can learn gradually from there - the mountain is high, but the learning curve isn't steep. (Horrible mixed metaphor, sorry). With python, you face a non-trivial research project even deciding which environment you're going to use. The thing you're going to hear most about is Zope, but you're also going to hear that Zope has a high & steep learning curve before you can get anything working at all, and that even although Zope itself is built using python, any existing python skills you may have aren't going to be particularly relevant for building applications that use it, for which you're going to have to learn some wierd template language instead. I don't know if these things are necessarily completely true or up to date, but they *are* what newcomers hear, and in the case of this newcomer they were enough to put me off even considering learning Zope. If you decide not to use Zope, you have a choice of a wide variety of wierd & wonderful offerings that address different but overlapping subsets of the problem at varying levels of prototypishness. There is no consensus as to what the emerging or de facto standards are, no particular reason to believe that whatever you choose will be supported or widely used in three years time - and if it isn't, the skills you're invested your valuable time acquiring won't be directly usable with whatever else is around. See the J2EE example above - if BEA were to go out of business, the Weblogic folks wouldn't have much difficulty switching their hard-earned skills over to jBoss. My personal decision was that the advantages of python as a language are so great that it's worth spending a bit of time finding something that will run it nicely behind a web server for small personal projects. I chose webware and I'm having fun playing with it. In its current state I wouldn't feel at all confident about using or recommending it for any kind of serious production system, even if it was in a greenfield situation where the comments above about legacy & compatibility didn't apply. I don't understand all this talk about twisted as a transport mechanism. The web runs on Apache (~70%) and IIS (~25%). Anything that aspires to be at all widely adopted has to have speed and stability running behind one or both of those as one of its primary goals. I don't know much about twisted - perhaps somebody could explain where it fits into that picture? Alan Little http://www.alanlittle.org/weblog From steve at ninereeds.fsnet.co.uk Fri Oct 24 11:06:36 2003 From: steve at ninereeds.fsnet.co.uk (Stephen Horne) Date: Fri, 24 Oct 2003 16:06:36 +0100 Subject: AI and cognitive psychology rant (getting more and more OT - tell me if I should shut up) References: <0KRib.213549$hE5.7197672@news1.tin.it> <7id6cz7rl4.fsf@enark.csis.hku.hk> <9XVib.214859$hE5.7243121@news1.tin.it> <3ovpovc9hmahv5g373jm2oo7mk3i83ldtb@4ax.com> <29cjb.218983$hE5.7379913@news1.tin.it> <5tksov8r4c3caoatfoslfi87q61dupaq81@4ax.com> Message-ID: On Fri, 24 Oct 2003 16:00:12 +0200, anton at vredegoor.doge.nl (Anton Vredegoor) wrote: >There *is* no fixed past. So you are saying that if a psychiatrist convinces his patient that she was abused by her parents as a child, even though it never occurred, to the point that she can remember it - then it must be true! I'm not confused on this - you are. Sorry, but you are not keeping a clear distinction between "the past" and "knowledge of the past". If memory is altered then it doesn't change the past, only the (now incorrect) memory. This sounds a lot like extreme cultural relativism. But I'm afraid that if you drive your car past a village of people with no knowledge of cars, while they may believe that your car is propelled by a demon under the hood, in reality the engine will still be there. Perception is not reality. It is only a (potentially flawed) representation of reality. But reality is still real. And perception *is* tied to reality as well as it can be by the simple pragmatic principle of evolution - if our ancestors had arbitrary perceptions which were detached from reality, they could not have survived and had children. You'll find many people who claim otherwise, of course. But the limits of perception are actually already better understood than most people realise. On the whole, they are pretty much the limits of information processing. -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From http Wed Oct 15 18:09:57 2003 From: http (Paul Rubin) Date: 15 Oct 2003 15:09:57 -0700 Subject: reasonably priced reporting solution References: <7x7k36td9p.fsf@ruckus.brouhaha.com> <2ferov40tvrbejgg20ic27l5pm9mteh1q8@4ax.com> Message-ID: <7x7k36f8zu.fsf@ruckus.brouhaha.com> Larry goodman writes: > >See http://www.reportlab.org for example. > > But this is free for only GPL apps right? My app will be closed > source. The only price i see there is 25,000 for their enterprise SDK > and that is way out of my range. According to their developers faq: The ReportLab toolkit and most of our other Open Source tools are available under the BSD license. This means that you can basically do anything you want with it, including using it in a commercial package. So you should be ok. From m_mommer at yahoo.com Sat Oct 4 15:13:43 2003 From: m_mommer at yahoo.com (Mario S. Mommer) Date: 04 Oct 2003 21:13:43 +0200 Subject: Python syntax in Lisp and Scheme References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> <92c59a2c.0310031345.57d20631@posting.google.com> Message-ID: jcb at iteris.com (MetalOne) writes: > I have tried on 3 occassions to become a LISP programmer, based upon > the constant touting of LISP as a more powerful language and that > ultimately S-exprs are a better syntax. Each time, I have been > stopped because the S-expr syntax makes we want to vomit. :-) Although people are right when they say that S-exprs are simpler, and once you get used to them they are actually easier to read, I think the visual impact they have on those not used to it is often underestimated. And to be honest, trying to deal with all these parenthesis in an editor which doesn't help you is not an encouraging experience, to say the least. You need at least a paren-matching editor, and it is a real big plus if it also can reindent your code properly. Then, very much like in python, the indent level tells you exactly what is happening, and you pretty much don't see the parens anymore. Try it! In emacs, or Xemacs, open a file ending in .lisp and copy/paste this into it: ;; Split a string at whitespace. (defun splitatspc (str) (labels ((whitespace-p (c) (find c '(#\Space #\Tab #\Newline)))) (let* ((posnew -1) (posold 0) (buf (cons nil nil)) (ptr buf)) (loop while (and posnew (< posnew (length str))) do (setf posold (+ 1 posnew)) (setf posnew (position-if #'whitespace-p str :start posold)) (let ((item (subseq str posold posnew))) (when (< 0 (length item)) (setf (cdr ptr) (list item)) (setf ptr (cdr ptr))))) (cdr buf)))) Now place the cursor on the paren just in front of the defun in the first line, and hit ESC followed by . > If a set of macros could be written to improve LISP syntax, then I > think that might be an amazing thing. An interesting question to me > is why hasn't this already been done. Because they are so damned regular. After some time you do not even think about the syntax anymore. From jay at jaydorsey.com Wed Oct 22 14:49:44 2003 From: jay at jaydorsey.com (Jay Dorsey) Date: Wed, 22 Oct 2003 13:49:44 -0500 Subject: using PIL for anti-automation in ASP In-Reply-To: <525cbda1.0310221014.4e5ed50c@posting.google.com> References: <525cbda1.0310221014.4e5ed50c@posting.google.com> Message-ID: <3F96D148.2060804@jaydorsey.com> Doug R wrote: > I'm trying to create an anti-automation feature to prevent scripts > from running reports on our website by requiring users to enter a code > from an image (like Yahoo e-mail sign-up, or Network Solutions WHOIS > search). > > I'm using Python as the scripting language in the ASP page, and using > PIL to generate the image. The code is stored into a session variable, > which is used to check the user's entry. It works fine the first time > around, but the problem I'm running into is that the page doesn't > refresh properly if the user returns to it. It just returns a blank > page. > Maybe the users browser is caching the image/page? Try a unique image name each time, or appending a date/time stamp to the image name (image.gif?blah=12345). First, if you're using IE, you could also disable page/image caching in the browser (you can do this in Mozilla too I think, and other browsers). Jay From joachim.durchholz at web.de Sat Oct 25 15:40:29 2003 From: joachim.durchholz at web.de (Joachim Durchholz) Date: Sat, 25 Oct 2003 21:40:29 +0200 Subject: Python from Wise Guy's Viewpoint In-Reply-To: References: <_8Ekb.7543$pT1.318@twister.nyc.rr.com> Message-ID: Marshall Spight wrote: > > Does the existence of downcasts point out a place where > Java is lame? Absolutely. Does extra effort result from > this lameness? Certainly. Does this extra effort cause > bugs? Nope. Bugs are not the only thing that I would term a "serious problem". Actually, I'd call everything a "serious problem" that eats up productivity. Of course, some problems are more serious than others; the absence of a good way to catch exceptions in C++ constructors (and, hence, that an exception thrown somewhere within a C++ constructor will almost inevitably leak memory) is worse than Java's ubiquitous need for downcasts. But I also consider the unavailability of type inference in Java a "serious problem". Actually I fear that my preferences have changed from "static typing > run-time typing" to "type inference > run-time typing > explicit static typing". > (Anyway, the situation is much better with Java generics, > available now in prerelease form; mainsteam in the next > major version.) Good thing, that. Let's just hope that having to wait a decade for Java generics was worth it... Java is probably the inevitable next step in my career. Well, there are worse languages, that's what I always tell myself (and it almost suffices to calm me down...) Regards, Jo From skip at pobox.com Thu Oct 23 15:24:05 2003 From: skip at pobox.com (Skip Montanaro) Date: Thu, 23 Oct 2003 14:24:05 -0500 Subject: iterating bit-by-bit across int? In-Reply-To: References: Message-ID: <16280.10965.73558.883581@montanaro.dyndns.org> Matthew> I'm playing around with genetic algorithms and I want to write Matthew> a function that mutates an integer by iterating across the Matthew> bits, and about 1 in 10 times, it should switch a zero to a Matthew> one, or a one to a zero. Just use Python's bitwise ops, for example: >>> x = 0x0FFFCCCC >>> hex(x) '0xfffcccc' >>> hex(x | (1 << 13)) '0xfffeccc' Skip From nomail at hursley.ibm.com Wed Oct 29 03:03:41 2003 From: nomail at hursley.ibm.com (Derek Fountain) Date: Wed, 29 Oct 2003 16:03:41 +0800 Subject: Do I need to close? References: <3f9df74f$0$23606$5a62ac22@freenews.iinet.net.au> Message-ID: <3f9f73da$0$1741$5a62ac22@freenews.iinet.net.au> > PIL works with image objects, not files. It automagically closes the > file when it doesn't need it any more. Ah, OK. As a Python newbie, it's these details I still need to think through properly. > If you don't trust PIL, do this: Oh, I trust it. Really! Thanks! From just at xs4all.nl Mon Oct 20 12:51:49 2003 From: just at xs4all.nl (Just) Date: Mon, 20 Oct 2003 18:51:49 +0200 Subject: <> and DeprecationWarning References: Message-ID: In article , Barry Warsaw wrote: > On Mon, 2003-10-20 at 11:21, Wojtek Walczak wrote: > > Dnia Mon, 20 Oct 2003 12:18:31 +0200, Gerrit Holl napisa?(a): > > > the <> inequality test operator has been deprecated for a loooooong time. > > Who said that? > > Well, Guido doesn't like it, but Just does, so that cancels out the Van > Rossum vote . I'm on Just's side though, but this is about as > religious an argument as Pythoneers get. I've long since given in, though... I don't like having two ways to spell one thing any more than the next guy. In the end it's just a matter of what you're used to, and I'm totally used to != now. (Heck, you can even find me occasionally indenting with _spaces_, that's how low I've sunk ;-) > I'm confident there's no way > <> can be officially deprecated as long as Python 2.x is alive. That's for sure. Just From oren-py-l at hishome.net Thu Oct 23 14:32:24 2003 From: oren-py-l at hishome.net (Oren Tirosh) Date: Thu, 23 Oct 2003 14:32:24 -0400 Subject: Tabs In-Reply-To: References: Message-ID: <20031023183224.GA46671@hishome.net> Some tabs are 8 space wide But spaces don't cost any money Other tabs leap 4 in one stride They make my source code look funny From mwh at python.net Thu Oct 30 08:47:01 2003 From: mwh at python.net (Michael Hudson) Date: Thu, 30 Oct 2003 13:47:01 GMT Subject: hashing mutable instances References: <840592e1.0310300020.144da59c@posting.google.com> <7h3ekwvngme.fsf@pc150.maths.bris.ac.uk> <6qfzhaj1mu.fsf@salmakis.intevation.de> Message-ID: <7h3llr2n8q4.fsf@pc150.maths.bris.ac.uk> Bernhard Herzog writes: > Thomas Heller writes: > > > Michael Hudson writes: > > > >> Try inserting a bunch of instances of > >> > >> class C: > >> def __hash__(self): return 0 > >> > >> into a dictionary. > > > > I've though about using something like this in production code > > to be able to store mutable instances in a dict. > > Performance problems aside (since there are only a couple of key/value > > pairs in the dict), is it such a bad idea? > > IMO it depends on what equality means for instances. E.g. if two > instances are only equal if they're identical, i.e. a == b is equivalent > to a is b, then defining __hash__ can be very useful, because then you > can use them in dictionaries and mutability doesn't really matter > because no change to one instance can make it equal to a nother > instance. Um. In that case why define __hash__ or __eq__ at all? Cheers, mwh -- Just put the user directories on a 486 with deadrat7.1 and turn the Octane into the afforementioned beer fridge and keep it in your office. The lusers won't notice the difference, except that you're more cheery during office hours. -- Pim van Riezen, asr From pmaupin at speakeasy.net Thu Oct 23 22:53:28 2003 From: pmaupin at speakeasy.net (Patrick Maupin) Date: 23 Oct 2003 19:53:28 -0700 Subject: Trailing comma (was: Re: structure in Python) References: <3F95585C.3EDF3364@engcorp.com> Message-ID: <653b7547.0310231853.215189da@posting.google.com> Cousin Stanley wrote: > The style that looks the most natural and seems the easiest > to extend and edit to me is .... > > x = [ 'fe' , > 'fi' , > 'fo' , > 'fum' ] Other people have raised some good points as to why using trailing commas can be better, but for my money the best reason to consistently use trailing commas is how a CVS (or other) diff will look later. You can either see one deleted line plus two added lines, or a single added line, your choice. Pat From http Mon Oct 20 18:31:47 2003 From: http (Paul Rubin) Date: 20 Oct 2003 15:31:47 -0700 Subject: Why don't people like lisp? References: <3f9302d7.170372828@news.eircom.net> Message-ID: <7xhe23k0bw.fsf@ruckus.brouhaha.com> David Steuber writes: > If even XEmacs is ported over to Common Lisp in my lifetime I will be > surprised. If it happens to GNU Emacs, surprise will not be enough > and I will have to resort to astonishment. > > I'm not thinking of the core code. I'm thinking of all those *.el > files floating around the universe. Plans have been to convert Emacs to use a Scheme dialect with hacks to support old .el files. From davidcfox at post.harvard.edu Fri Oct 10 16:55:45 2003 From: davidcfox at post.harvard.edu (David C. Fox) Date: Fri, 10 Oct 2003 20:55:45 GMT Subject: round/float question In-Reply-To: References: Message-ID: Please use a word wrap of 75 characters or less. Jason Tesser wrote: > I am using Rekall which uses Python as it's scripting language and I > have a question about Python. I am developing a POS system and am > working on the checkout form. I pass a parameter named SaleID and > another one named Total. I am trying to take total and convert it to > a float with 2 decimals top be used as money obviously. What would > be the proper syntax for this? I tried Total = round(Total [, 2]) i > also tried that with float. > > Jason Tesser Web/Multimedia Programmer Northland Ministries Inc. > (715)324-6900 x3050 > > For monetary values, you are much better off avoiding floating point altogether. For example, you could express total in cents. Then, to convert to dollars and cents, you can use divmod(total, 100), which divides total by 100, returning the integer portion (the dollar amount) followed by the remainder (cents amount). For example: total = 599 # ($5.99) print "item $%d.%d" % divmod(total, 100) total = total + 275 dollars, cents = divmod(total, 100) print "subtotal $%d.%d" % divmod(total, 100) taxrate = .05 tax = int(round(total*taxrate)) print "tax $%d.%d" % divmod(tax, 100) total = total + tax print "total $%d.%d" % divmod(total, 100) David From usenet-reply at henrik-motakef.de Sun Oct 12 19:20:41 2003 From: usenet-reply at henrik-motakef.de (Henrik Motakef) Date: 13 Oct 2003 01:20:41 +0200 Subject: Python syntax in Lisp and Scheme References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> <92c59a2c.0310031345.57d20631@posting.google.com> <6WKdnf4hoZxoRRWiXTWJig@comcast.com> <39hib.205605$hE5.6914649@news1.tin.it> <29kib.206536$hE5.6945256@news1.tin.it> Message-ID: <868ynqvy9i.fsf@pokey.internal.henrik-motakef.de> Alex Martelli writes: > > OK, I understand that the Python mindset is really _a lot_ different > > than the Lisp mindset in this regard. > > As in, no lisper will ever admit that a currently existing feature is > considered a misfeature?-) You might want to search google groups for threads about "logical pathnames" in cll :-) > Guido has already declared that ONE concept of interfaces (or > typeclasses, or protocols, etc) _will_ eventually get into Python -- but > _which one_, it's far too early to tell. A propos interfaces in Python: The way they were done in earlier Zope (with "magic" docstrings IIRC) was one of the things that led me to believe language extensibilit was a must, together with the phletora of SPLs the Java community came up with, either in comments (like JavaDoc and XDoclet) or ad-hoc XML "configuration" files that grow and grow until they are at least turing-complete at some point. (blech) People /will/ extend the base language if it's not powerfull enough for everything they want to do, macros or not. You can either give them a powerfull, documented and portable standart way to do so, or ignore it, hoping that the benevolent dictator will someday change the core language in a way that blesses one of the extensions (most likely a polished variant of an existing one) the "obvious", official one. It is the difference between implementing a proper type system and extending lint to check for consistent use of the hungarian notation at the end of the day. From bill at kill.com Sun Oct 26 00:44:20 2003 From: bill at kill.com (Kill Bill) Date: Sun, 26 Oct 2003 00:44:20 -0400 Subject: Comparing variable types References: <20031025224446.20009.00000076@mb-m07.aol.com> Message-ID: Where can I find all the methods for Dictionaries? They list some here, but is that all of them? http://www.python.org/doc/2.3.2/tut/node7.html#SECTION007140000000000000000 I think it is, but I don't like how its written. I want it to be written you know by method, constuctors, like in the Java API. Anyone know what I'm talking about? Its so quick to skim through the API to see which method you are looking for. Not the case here. "Andrew Bennetts" wrote in message news:mailman.103.1067137271.702.python-list at python.org... > On Sat, Oct 25, 2003 at 10:50:21PM -0400, Kill Bill wrote: > > Can you tell me where you found that method in the docs? I'm having trouble > > navigating them, the java docs are so much easier to look at. > > Library Reference, section 2.1: Built-in Functions > http://python.org/doc/current/lib/built-in-funcs.html > > -Andrew. > > From martin at v.loewis.de Mon Oct 27 19:15:14 2003 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 28 Oct 2003 01:15:14 +0100 Subject: Python on win64 In-Reply-To: References: Message-ID: <3F9DB512.7020909@v.loewis.de> Mauro Cicognini wrote: > The question is: Does anyone have any advice on how to build Python on > win64 boxes? > > We know it _is_ possible after we found Martin von Loewis's cool > installer. The only catch is, we don't know how he got there :-( Like Trent says: Export the makefiles in VC6. Then, you have to massage them manually, i.e. replacing all /machine:x86 by /machine:ia64 or some such. You also have to remove libraries that aren't there in the Win64 SDK. > I'm asking 'cause we recently got an Itanium machine with Windows Server > 2003 on it and started looking on how to port some of our stuff to it. > However, since there's no MS IDE for win64, the only way to build Python > would be to use the SDK, but that needs makefiles and those would need > to be exported from the MSVC project files, with no guarantee of success. Strictly speaking, this is not true: you don't actually *need* the makefiles. You could instead perform all necessary compiler invocations manually. Also, I advise against building on Win64: The SDK compiler is an x86 application, and those are awfully slow when executed on Itanium. So it is faster to build on x86, and carry over the binaries. An alternative might be to use the Intel compiler, which is a native Itanium binary. > Besides, we'd need to have some other windows things there, and we have > few clues on how to proceed, so if anyone has any pointers we'd be very > thankful. You might want to take a look at Peter Tr?ger's "Visual Studio External Compiler" project, at sf.net/projects/vsextcomp. It allows to derive Win64 targets from VC7.1 Win32 projects, using the SDK compiler. Using that technology, the procedure is: 1. convert the VC6 project files to VC7 2. for each project, for both the debug and the release target, create a parallel debug64 and release64 target, using the new item in the Tools menu. With that approach, you can run the entire build process inside VC7.1. The intention is to extend this beyond Win64-Itanium-SDK-compiler; feedback and patches are welcome (e.g. it should be possible to put triple-projects, including AMD64, into place, once the SDK supports AMD64). I'm using this to eliminate all the size_t warnings in Python, which I hope to contribute for 2.4 once completed. As for generating an MSI file at the end: please don't ask me - atleast not unless you know what orca.exe is :-) Regards, Martin From skip at pobox.com Mon Oct 13 12:35:09 2003 From: skip at pobox.com (Skip Montanaro) Date: Mon, 13 Oct 2003 11:35:09 -0500 Subject: targeting the PVM In-Reply-To: <1066060361.3f8aca49a79e5@webmail2.tau.ac.il> References: <1066060361.3f8aca49a79e5@webmail2.tau.ac.il> Message-ID: <16266.54333.336610.759385@montanaro.dyndns.org> andy> I have found that the format of the "JVM machine language" andy> (i.e. class files) is well documented. However I was not able to andy> find some good documentation on "Python's machine language". andy> Can someone provide with pointers? Nope. The Python virtual machine is an "implementation detail" of the CPython implementation. As such, about the only documentation is the code in ceval.c itself. I started on something a long time ago: http://manatee.mojam.com/pyvmwiki but never really got anywhere with it. Skip From tjreedy at udel.edu Thu Oct 9 22:15:21 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 9 Oct 2003 22:15:21 -0400 Subject: Python syntax in Lisp and Scheme References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> <92c59a2c.0310031345.57d20631@posting.google.com> <87llrvs4yw.fsf@bird.agharta.de> <7xu16jmf57.fsf@ruckus.brouhaha.com> Message-ID: "Kenny Tilton" wrote in message news:Jsmhb.27968$pv6.19754 at twister.nyc.rr.com... > > > You mean like Psyco? > > > > Been there, done that. (and it's great, and getting better). > > Oh, excellent name. PYthon Specializing COmpiler, slightly permuted. Also somehow apt for something that dynamically compiles bytecode to type-specific machine code. Many of us did not quite believe it until the pudding was cooked. > OK, the context was "what are Python's aspirations?" > . Is Python now no longer content to be a (very powerful) scripting > language? Prime focus is still correct and readable code with execution speed somewhat secondary but not ignored. The interpreter slowly speeds up; more compiled C extension modules appear; other compilation options appear; and 3 gig processors run Python about as fast as P125s did with compiled C. > Or is it just tired of being ragged on for being slow? I suspect that that pushes a bit too, but I can't speak for anyone in particular. Terry J. Reedy From aleaxit at yahoo.com Sun Oct 12 16:27:50 2003 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 12 Oct 2003 20:27:50 GMT Subject: type checking References: <1065938227.288329@yasure> <8eaib.269339$R32.8774481@news2.tin.it> Message-ID: Stephen Horne wrote: ... >>> | language. Either Java, C# or Delphi may be a good option for you. ... >>I'd like to second Donn's recommendation and express reservations >>on Stephen's. Java &c just don't have a high enough semantic level >>to give you the same productivity as Python. > > I suggested C# - _not_ C. That is a very different thing. C# is Sure. "&c" stands for "etc", in this context "and all the others [which you had mentioned]". > A good language can mean big gains, but not necessarily as big as > someone else having written key parts of your application for you in > the form of libraries - and testing them too. Definitely. But SWIG often helps a lot -- if the library's around for C, it's not far from your favourite SWIG-supported language. > An additional issue is familiarity - if sashan is having a hard time > adapting to Python, I suspect he'll find functional languages require > an even bigger paradigm shift. Java and C# require relatively few > mindset adjustments relative to C++. True, they're closer to C++ in many respects than Python is (except that Python, like C++, is multi-paradigm, has multiple inheritance, allows operator overloading, lets you pick and choose among GUI toolkits rather than coming with one, etc -- but probably not the kinds of things one will have most "mindset adjustments" about). By the same token, Java and C# will give few benefits if you already master C++ -- perhaps a little help with memory management to be offset against losing templates, a HUGE loss to adjust to, and such niceties as the "resource allocation is construction" idiom. If one masters C++ and is looking for productivity higher enough to matter, Python (or other similar VHLLs) and FP languages are much more likely to produce it than Java or C# are. Alex From robin at jessikat.fsnet.co.uk Thu Oct 9 03:53:00 2003 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Thu, 9 Oct 2003 08:53:00 +0100 Subject: [ANN] python-dateutil 0.1 References: Message-ID: In article , Gustavo Niemeyer writes >What is it? >----------- >The dateutil module provides powerful extensions to the standard >datetime module, available in Python 2.3+. > .... is there support for business dates ie number of business days between two dates etc? -- Robin Becker From aleax at aleax.it Mon Oct 20 19:17:26 2003 From: aleax at aleax.it (Alex Martelli) Date: Mon, 20 Oct 2003 23:17:26 GMT Subject: assignment expression peeve References: <7x1xtfkuky.fsf@ruckus.brouhaha.com> <6q6jb.10882$fv4.3354@nwrdny02.gnilink.net> <7xk77676bt.fsf@ruckus.brouhaha.com> <6ZWjb.49$Vf7.34@nwrdny02.gnilink.net> Message-ID: Carl Banks wrote: ... >> "if distance divided by time, call it speed, is above 50 MPH, decelerate" >> >> and, since you HAVE claimed you're not stuck on word-order >> >> "if (speed := distance/time) > 50: decelerate()" >> >> how CAN you claim these are ANYTHING *BUT* ANALOGOUS?! > > I don't!!! But if the programmer doesn't see "speed := ..." as "call > it speed", then it's not a verbal equivalent, and not being one, it > will be more difficult to read, or at least harder to learn. Even IF a programmer is so utterly obtuse and obdurate as to be unable to "read" := as 'call it', 'is', 'becomes', 'which is', and so on ad nauseam (any of the bazillion natural-language analogues I've shown), and so narrow-minded, as you claim, that he or she will keep stubbornly reading it as a "set to" which is NEVER appropriate, then MAYBE that subnormal programmer will have a slightly harder time learning ':=' than he or she has learning other constructs. Miraculously, of course, said programmer HAS learned to "read" e.g. % as meaning 'modulo' in some expressions and 'formatting' in others; 2:7 as "2 maps to 7" within braces, but as "from 2 to 7" within brackets; parentheses meaning tuple here, function call there, class inheritance yonder; and so on, and so forth -- yet that paragon of mental flexibility, so GOOD at reading the SAME construct in different appropriate ways depending on context, has an inexplicably localized blind spot in reading two DIFFERENT constructs, = vs := , in two different and appropriate ways -- truly wondrous to behold. Yeah, well, given his/her incredibly-conveniently-located immutable blind spot, said inDUHvidual WILL have some learning problems connected to that one immutable blind spot. Surprise, surprise. I don't agree with the likelihood of any of these hypotheses for one second (and I suspect I've taught programming to more newbies than you have), but, no matter. What DOES matter, is that no shred is left of the "no analog in natural language" assertion -- indeed, you now say: > though it's completely analogous. Oh *GOOD*. COMPLETELY. Wow, we do agree. All that's left is your unsupported hypothesis that programmers are likelier to have a blind spot here than anywhere else. I disagree. I do not intend to fund a study to find out, either:-). Please find other NON-natural-language related ways to attack your pet-hate assignment-expression and its ilk. Wrapping up -- I disagree that saying "a is b" is inappropriate. You keep talking about RE-binding of name a, but that's not necessarily what's happening. It's also quite possible that a had previously no binding. In any case, the implied "from now on, until further notice" can cancel the difference (in fact, single-assignment languages HAVE some empirical support as being easier to learn, if I recall correctly -- subjectively, I recall from my very first attempt at Fortran, well over a quarter century ago, that the ONE construct that stumped me a bit was exactly "X = X + 1", the kind of construct that single assignment languages deliberately do NOT have -- oh well, anyway, just a digression). You claim I earlier agreed that saying "a is b" does not clearly communicate assignment. I don't think I did, and I suspect that if you read that into my words I may have expressed myself in unclear ways (unless it was a blind spot on your part:-). Sure, longer words and phrases "stand out" more, but that's a matter of emphasis and connotation, not one of denotation. Alex From aleaxit at yahoo.com Mon Oct 20 04:47:19 2003 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 20 Oct 2003 10:47:19 +0200 Subject: prePEP: Money data type In-Reply-To: <9A316652-02B6-11D8-BCD7-000393C2D67E@colorstudy.com> References: <9A316652-02B6-11D8-BCD7-000393C2D67E@colorstudy.com> Message-ID: <200310201047.19752.aleaxit@yahoo.com> On Monday 20 October 2003 06:33 am, Ian Bicking wrote: ... > > BECAUSE for reasons totally unclear to me x isn't allowed to carry > > the rounding spec, even though all computations on x must use that > > spec, would drive me away in no time. > > Money could carry the rounding policy -- I don't really know if that's > right or not, I'm not convinced either way. But I'm not sure it's > really "money" if it carries a rounding policy. A rounding policy > isn't intrinsic to the notion of money. EU has a rounding policy, but Thanks, you clarified your reasons now, even though I disagree. Money is a legal and social construct and the laws and customs that dictate its use will impose a rounding policy (which might well be "no rounding allowed" in some cases). > require "v1, v2, v3 = x.divide(3)", so that pennies aren't lost. I > don't see how a rounding policy can handle that, unless you intend a By having among others a "Money.no_rounding_allowed" policy that can raise an exception on operations that are to be disallowed. Easy! > If you include a rounding policy you are really specifying an > accounting entry. That "money" cannot be put into other accounts > without checking and converting the rounding policy. But the rounding > policy may not be the only policy -- I don't have experience to know of > other circumstances, but it's easy enough to imagine other kinds of > policies that belong to entries. But class Money in itself should specify *arithmetic*, that's all. Accounting may require a bazillion other kinds of policies, but I see as the role of class Money in that larger picture that of handing arithmetic -- and that requires a rounding policy (only). Policies such as "withdrawals of over 10,000 in cash must send an email to account XXX" belong elsewhere, at higher application levels; arithmetic belongs in class Money. > If that's common, then you probably will want a formal "entry" object, > which would contain a money object. At that point the rounding > information held by the money object will be redundant and perhaps a > hinderance. Not at all: being able to delegate arithmetic issues to the "quantity" object (Money in this case) is, on the contrary, crucial to simplify higher application levels. There IS a case for "money with currency unit" to be separate from pure Money, basically to catch errors due to trying to sum Euros and Dollars and the like; but that can be built by subclassing a Money that's blissfully oblivious to currencies. As long as that Money CAN handle arithmetic, though; otherwise, what ARE its responsibilities?! > I prefer the idea of wrapping money in domain-specific ways, and > leaving the money object relatively pure. A relatively-pure object should generally have an area of responsibility nevertheless. I see Money's area of responsibility as arithmetic, and rounding policy as being intrinsic to that. > > that we can predict in advance, then the requirement to subclass is not > > too onerous. But normal cases should be in the Money class! > > Agreed. The one kind of customization I might consider is if you > wanted to, application-wide, enforce coding standards, like no implicit > rounding. You could subclass and replace the money class for the > entire application. It's kind of hackish, but it should actually work > okay for this particular case. Most other kinds of customization don't > work well, because library code will usually use uncustomized classes. GOOD Library code should accept indications of what class to use (with a sensible default). That's a key reason that makes classes as first-class citizens SUCH a great idea - it's trivially easy to pass them around for such purposes. For example, mailbox.UnixMailbox _defaults_ to using class rfc822.Message, but you can perfectly well (and should, these days) pass it email.message_from_file (or a factory wrapping the latter if you need to deal very robustly with potentially malformed mailboxes). > Especially with immutable instances, where library code will return new > objects instead of modifying your customized object in place. Using the passed-in object's __class__ may be sufficient in that case, and that should often be transparently achievable, as calling methods on a money instance that return another new money instance should automatically use the same class. That's very easy too, e.g. consider a very toy example, a meant-as-immutable Money that only holds an amount and lets you sum a number to that returning a new instance: class Money(object): def __init__(self, amount): self.amount = amount def __add__(self, other): return self.__class__(self.amount + other) the point is to use self.__class__ as the factory for new objects to be returned, rather than using Money for the purpose. > >>>> No, the only places where repr() round trips is for Python literals. ... > > Guaranteed readability is the business of str(). repr() must be > > complete > > and accurate even if that sacrifices readability. Round-tripping > > cannot > > generally be guaranteed for many types, but when it can it's a sensible > > way to double check on completeness and accuracy; readability must > > not be allowed to interfere with completeness and accuracy. Sure, > > pickle > > is there for those times where round-tripping is too onerous on other > > grounds, but readability is not one of those grounds -- otherwise what > > do you think str() is there FOR? > > That's not a realistic idea of repr() -- repr() doesn't need to be > accurate, because it usually isn't! Anyone who expects repr() to be a > accurate way to reconstruct objects isn't just wrong, they aren't even > paying attention. Or has read the Python library docs about repr: """ For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval(). """ MANY types; not ALL (obviously), but MANY. No "only Python literals" constraint, no readability intent. As the docs say about str: """ The difference with repr(object) is that str(object) does not always attempt to return a string that is acceptable to eval(); its goal is to return a printable string. """ The docs put it a bit too strongly IMHO, because repr also does not ALWAYS attempt &c. I think it would be better to weaken str's docs to "does not EVEN attempt to" -- str just cares about "nicely printable" strings, not about acceptability to eval. But even if we weaken this to str "not even attempting", there IS still an implication that repr DOES "attempt", which goes well with the "many types ... makes an attempt" in repr's own documentation. I also (of course;-) like the way I've put this in the Nutshell's docs on __repr__ and __str__ (p. 94): essentially, repr MUST be accurate and unambiguous, and WHEN FEASIBLE a good way to achieve that is to produce a string acceptable to eval (the "round-tripping" you're deprecating). > repr() is generally for debugging purposes. It's a summary of an > object where completeness is valued over aesthetics (contrary to > str()). It's not necessarily a complete picture of an object. Nobody ever said repr is NECESSARILY a complete picture -- it most obviously can't ALWAYS be that, as there are many cases where that would be patently unfeasible (e.g., a file object...!). But it's still worth having repr be "complete" when feasible, and having it "round-trip" with eval can often be done just fine; when it can, I think it definitely should. Alex From costanza at web.de Thu Oct 30 20:04:42 2003 From: costanza at web.de (Pascal Costanza) Date: Fri, 31 Oct 2003 02:04:42 +0100 Subject: Explanation of macros; Haskell macros In-Reply-To: References: <87brs2tjut.fsf@memetrics.com> <87he1rdt9d.fsf@memetrics.com> Message-ID: Peter Seibel wrote: > "Anton van Straaten" writes: >>Yes, but the point is that with a concise syntax for lambda, entire >>classes of macros can become unnecessary. That's how Smalltalk >>handles 'if', for example - no macros or special forms needed. > > > Okay, so I picked an unfortunate example in that it also falls in the > class of macros that become unecessary when other bits of syntactic > sugar are provided. No, I don't think so. Here is what I needed in a real program. I had several cond statements at various places of my code. They all didn't have a default case. At a certain stage, I needed to be sure to get an exceptional return value for the default case instead of NIL. So I added a macro: (defconst *error-form* '(mv (trans-pstate pstate :exception 'program-error) *void*)) (defmacro ev-cond* (pstate &body body) `(cond ,@(append body `((t (let ((pstate ,pstate)) ,*error-form*)))))) *ERROR-FORM* here is the standard code that changes a program state to a state with an exception and a *void* return type. EV-COND* is my modified COND that simply adds a default case in which PSTATE is correctly bound so that *ERROR-FORM* can do the right thing. (This isn't "pure" Common Lisp, but ACL2, and the code is somewhat more complicated than necessary because ACL2 places some severe restrictions on the code that one can write.) The essence of this is as follows: (defmacro my-cond (&body body) `(cond ,@(append body '(t (handle-the-default-case)))) With simple shadowing imports one can make this completely transparent to client code. How would you do this with a Smalltalk-like if expression? (This is not a rhetoric question - I would be really interested to hear how one could make this work.) Pascal From aleax at aleax.it Wed Oct 29 15:58:01 2003 From: aleax at aleax.it (Alex Martelli) Date: Wed, 29 Oct 2003 20:58:01 GMT Subject: itertools.flatten()? and copying generators/iterators. References: <0Wunb.58272$e5.2143391@news1.tin.it> Message-ID: Peter Otten wrote: ... > def flatten_dict(s, isScalar): > try: > scalar = isScalar[s.__class__] > except KeyError: > t = s.__class__ > try: > s = iter(s) > except TypeError: > scalar = isScalar[t] = True > else: > scalar = isScalar[t] = False > > if scalar: > yield s > else: > for elem in s: > for subelem in flatten_dict(elem, isScalar): > yield subelem Neat: "caching" (aka memoizing) IS a good general technique for optimization, and this is a cool and un-obvious application. Alex From zorro at chez.com Tue Oct 28 17:30:40 2003 From: zorro at chez.com (jb) Date: Tue, 28 Oct 2003 23:30:40 +0100 Subject: Pdf -> Doc References: <84fc4588.0310272223.177e33c4@posting.google.com> Message-ID: <3f9eee15$0$252$636a55ce@news.free.fr> you can convert the pdf in any format like html or rtf with a 3rd party tool and then, if you have word on on machine, you can with python use win23com to do a macro which will open word, open your exported file and save it as a doc file. then you can batch your filez you can even write the macro string in python, and execute it on the fly through word good luck jb "Anand Pillai" a ?crit dans le message de news:84fc4588.0310272223.177e33c4 at posting.google.com... > Is there any python module which will convert Acrobat > PDF files to MS Word documents? > > I googled for it, but could not find much results apart > from a pdf2doc plugin which needs the compelte acrobat > installation to work. > > Thanks for any hints. > > -Anand Pillai From __peter__ at web.de Tue Oct 14 07:01:09 2003 From: __peter__ at web.de (Peter Otten) Date: Tue, 14 Oct 2003 13:01:09 +0200 Subject: Problem with variables and Tkinter... References: <3405914.1065377943@dbforums.com> Message-ID: Baltor wrote: > OK, so I'v got 11 radio buttons hooked up to one variable: > self.weaponbonus. However, no matter what radio button I have checked, > self.weaponbonus is treated as 0. This is my code: [...] > Does anyone know what's wrong? The random button must trigger a function that sets the IntVar. One way to achieve this is presented below. I would prefer a normal Button over a Radiobutton to set the random value. import Tkinter as tk import random class BonusFrame(tk.Frame): def __init__(self, *args, **kwd): tk.Frame.__init__(self, *args, **kwd) self.grid() self.weaponbonus = tk.IntVar() for i in range(10): val = i + 1 btn = self.radio1 = tk.Radiobutton(self, text="+%d" % val, variable=self.weaponbonus, value=val) btn.grid(row=i//5, column=i%5) def setRandom(): self.weaponbonus.set(random.randint(1, 10)) if 0: #not recommended self.radioran = tk.Radiobutton(self, text="Random", variable=self.weaponbonus, value=99, command=setRandom) self.radioran.grid(row=3, column=0, columnspan=5) else: self.radioran = tk.Button(self, text="Random", command=setRandom) self.radioran.grid(row=3, column=0, columnspan=5) # for your information only lbl = tk.Label(self, text="Bonus is") lbl.grid(row=4, column=0, columnspan=2) lbl = tk.Label(self, textvariable=self.weaponbonus) lbl.grid(row=4, column=1) root = tk.Tk() frame = BonusFrame(root) root.mainloop() Peter From daniel at dittmar.net Sat Oct 25 15:47:19 2003 From: daniel at dittmar.net (Daniel Dittmar) Date: Sat, 25 Oct 2003 21:47:19 +0200 Subject: database widgets In-Reply-To: References: <8765idqwlu.fsf@pobox.com> Message-ID: Ken Godee wrote: > With PyQt you do not use any "Python database drivers", the PyQt > database widgets are "data aware widgets", you simply load the correct > Qt/PyQt database driver for your database, write your python code > calling any of the PyQt data aware widgets. Really pretty cool, simple > and works good. What I meant: when this guy asks in a Python newsgroup about data aware widgets, chances are that he wants his program to do more with the database than just use the widgets. And the database interface of Qt was rather limited last time I looked and it may not support a certain database. Daniel From rainerd at eldwood.com Thu Oct 23 18:15:57 2003 From: rainerd at eldwood.com (Rainer Deyke) Date: Thu, 23 Oct 2003 22:15:57 GMT Subject: PEP 289: Generator Expressions (please comment) References: <5d83790c.0310231158.65595858@posting.google.com> Message-ID: Raymond Hettinger wrote: > "Daniel Dittmar" wrote in message > news:bn9evl$5ug$1 at news.eusc.inter.net... >> Why should generator comprehension be useful only for arguments? > > It is not limited to just function arguments. > It is a first class citizen. You can use it for anything you want. At the very least, it would require parentheses if you want to create a list containing exactly one such generator. [(x for x in y)] # List containing generator [x for x in y] # List comprehension -- Rainer Deyke - rainerd at eldwood.com - http://eldwood.com From gh at ghaering.de Sat Oct 4 19:16:29 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Sun, 05 Oct 2003 01:16:29 +0200 Subject: php squirrelmail out of memory at ISP's webmail :-( In-Reply-To: References: Message-ID: <3F7F54CD.5000705@ghaering.de> Bengt Richter wrote: > [PHP *yuck*] > Fatal error: Allowed memory size of 8388608 bytes exhausted (tried to allocate 42 bytes) in > /vhome/common/webmail/squirrelmail-1.4.1/functions/imap_general.php on line 735 Entering the error message verbatim into Google would have helped ;-) The solution is to change the memory_limit parameter in the php.ini file. Of course you'll need admin privileges for this ;-) -- Gerhard From jrm at ccs.neu.edu Tue Oct 14 14:02:08 2003 From: jrm at ccs.neu.edu (Joe Marshall) Date: Tue, 14 Oct 2003 14:02:08 -0400 Subject: BIG successes of Lisp References: Message-ID: mike420 at ziplip.com writes: > Joe Marshall wrote: > >> mike420 at ziplip.com writes: >> >>> Ivan Toshkov wrote: >>> >>>> >>>> Besides, when I read the description of orbiz, I was with the >>>> impression, that they prealocated the memory for just that reason: to >>>> remove the need for garbage collection. >>> >>> An why would anyone do something this gross to optimize something >>> that is not a real bottleneck? Think when you read. The fact is, >>> they still had close their whole web site for maintenance every >>> once in a while (I never said if it was a supercomputer cluser or >>> a DOS machine) I added "AFAIK" qualifier because it may >>> be an old and already resolved issue. >>> >>> Edi Weitz and Joe Marshall, you may stop kissing ass now. You >>> need brains to work for ITA, not lips. >> >> I'm well aware of the necessary qualifications for working at ITA. > > Do the necessary qualifications have anything to do with > why you do not work there any more, while ITA is still > recruiting? You're obviously more informed than I am, so you tell me. > I did not inhale. >> I worked there. > > Half-truth Which half? >> Any shutdown at Orbitz was (and is) unrelated to >> garbage collection. > > Another The expert speaks. > Anyway, I'm getting tired of your mindless content-free > pukes of posts. I don't recall asking you. > Someone said prunesquallor at comcast.net was > also you. Is that right? > > If you strive for expressing balanced opinions, I might > let you stick around and have my left-overs. Why would I want those? From adalke at mindspring.com Thu Oct 9 15:35:10 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Thu, 09 Oct 2003 19:35:10 GMT Subject: Python syntax in Lisp and Scheme References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> <92c59a2c.0310031345.57d20631@posting.google.com> <6CZgb.3273$dn6.860@newsread4.news.pas.earthlink.net> <0_ghb.251516$mp.168001@rwcrnsc51.ops.asp.att.net> <3F85A0D7.EAE94C0A@setf.de> Message-ID: Rainer Deyke wrote: > Is portability of code across different language implementations not a priority > for LISP programmers? james anderson: > there are some things which the standard does not cover. "The standard" as I understand it, is some document written a decade ago. Can't a few of you all get together and say "hey, the world's advanced. Let's agree upon a few new libraries and APIs."? Andrew dalke at dalkescientific.com From saoirse_79 at yahoo.com Tue Oct 7 11:48:55 2003 From: saoirse_79 at yahoo.com (=?iso-8859-1?q?Orla=20O'Sullivan?=) Date: Tue, 7 Oct 2003 16:48:55 +0100 (BST) Subject: multidimensional lists Message-ID: <20031007154855.4866.qmail@web13807.mail.yahoo.com> I have a list of characters and I want to convert it into a list of lists..how can I do this?? ________________________________________________________________________ Want to chat instantly with your online friends? Get the FREE Yahoo! Messenger http://mail.messenger.yahoo.co.uk From fjh at cs.mu.oz.au Wed Oct 29 11:24:22 2003 From: fjh at cs.mu.oz.au (Fergus Henderson) Date: Wed, 29 Oct 2003 16:24:22 GMT Subject: Python from Wise Guy's Viewpoint References: <_8Ekb.7543$pT1.318@twister.nyc.rr.com> <3f972315$1@news.unimelb.edu.au> <3638acfd.0310230039.306b14f@posting.google.com> <3f9d556c$1@news.unimelb.edu.au> <3f9f8f49$1@news.unimelb.edu.au> Message-ID: <3f9fe9b1$1@news.unimelb.edu.au> Pascal Costanza writes: >Fergus Henderson wrote: >>Pascal Costanza writes: >>>Fergus Henderson wrote: >>>>Pascal Costanza writes: >>>Furthermore, if I remember correctly, dynamically compiled systems use >>>type inferencing at runtime to reduce the number of type checks. >> >> In cases such as the one described above, they may reduce the number of >> times that the type of the _collection_ is checked, but they won't be >> able to avoid checking the element type at every element access. > >Why? If the collection happens to contain only elements of a single type >(or this type at most), you only need to check write accesses if they >violate this condition. As long as they don't, you don't need to check >read accesses. So which, if any, implementations of dynamic languages actually perform such optimizations? -- Fergus Henderson | "I have always known that the pursuit The University of Melbourne | of excellence is a lethal habit" WWW: | -- the last words of T. S. Garp. From sax at dhcp226-160.cs.chalmers.se Wed Oct 29 06:21:59 2003 From: sax at dhcp226-160.cs.chalmers.se (Stefan Axelsson) Date: 29 Oct 2003 11:21:59 GMT Subject: Python is Considered Harmful References: <7ioew3xjh1.fsf@enark.csis.hku.hk> <1wsnb.366321$R32.12079281@news2.tin.it> Message-ID: In article , Alex Martelli wrote: > > Actually, I did work in Forth (it was the in-ROM language of a > neat computer I once bought, called "Jupiter ACE"; and also of a > special-purpose image processing PC card I once used at work), > but never came across that "feature" (assuming those dialects of > Forth in those ROMs supported it, that is). Guess I was lucky > that in those special cases I wasn't sharing code w/others:-). Well the Jupiter ACE (of which I'm still a proud owner) suppored it, it's in the '79 standard after all. E.g. just do '16 base !', for hexadecimal input for example. Makes writing an assembler in Forth, or the usual combination of Forth and assembly simpler if nothing else. As everything Forth, judicious use is key. Stefan, -- Stefan Axelsson (email at http://www.cs.chalmers.se/~sax) From j-anthony at rcn.com Thu Oct 9 17:30:58 2003 From: j-anthony at rcn.com (Jon S. Anthony) Date: 09 Oct 2003 17:30:58 -0400 Subject: Python syntax in Lisp and Scheme References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> <92c59a2c.0310031345.57d20631@posting.google.com> <6CZgb.3273$dn6.860@newsread4.news.pas.earthlink.net> Message-ID: "Andrew Dalke" writes: > Jon S. Anthony: > > This thing has been debunked for years. No one with a clue takes it > > seriously. Even the author(s) indicate that much of it is based on > > subjective guesses. > > Do you have a reference? And a pointer to something better? Even nothing is better than misinformation. > 2 of 6 is better than random, so Jones' work can't be > complete bunkum. 2 of 6 is worse than flipping a coin. /Jon From prunesquallor at comcast.net Tue Oct 7 19:26:35 2003 From: prunesquallor at comcast.net (prunesquallor at comcast.net) Date: Tue, 07 Oct 2003 23:26:35 GMT Subject: Python syntax in Lisp and Scheme References: <3cea3gqq.fsf@comcast.net> Message-ID: Alexander Schmolck writes: > Joe Marshall writes: > > >> Alexander Schmolck writes: >> >> > prunesquallor at comcast.net writes: >> (I'm ignoring the followup-to because I don't read comp.lang.python) > > Well, I supposed this thread has spiralled out of control already anyway:) > >> Indentation-based grouping introduces a context-sensitive element into >> the grammar at a very fundamental level. Although conceptually a >> block is indented relative to the containing block, the reality of the >> situation is that the lines in the file are indented relative to the >> left margin. So every line in a block doesn't encode just its depth >> relative to the immediately surrounding context, but its absolute >> depth relative to the global context. > > I really don't understand why this is a problem, since its trivial to > transform python's 'globally context' dependent indentation block structure > markup into into C/Pascal-style delimiter pair block structure markup. Of course it can. Any unambiguous grammar has a parse tree. > Significantly, AFAICT you can easily do this unambiguously and *locally*, for > example your editor can trivially perform this operation on cutting a piece of > python code and its inverse on pasting (so that you only cut-and-paste the > 'local' indentation). Prima facie I don't see how you loose any fine control. Only if your cut boundaries are at the same lexical level. If you cut across boundaries, it is no longer clear what should happen at the paste. Also, it is frequently the case that you need to `tweak' the code after you paste it. >> Additionally, each line encodes this information independently of the other >> lines that logically belong with it, and we all know that when some data is >> encoded in one place may be wrong, but it is never inconsistent. > > Sorry, I don't understand this sentence, but maybe you mean that the potential > inconsitency between human and machine interpretation is a *feature* for Lisp, > C, Pascal etc!? If so I'm really puzzled. You misunderstand me. In a python block, two expressions are associated with each other if they are the same distance from the left edge. This is isomorphic to having a nametag identifying the scope of the line. Lines are associated with each other iff they have the same nametag. Change one, and all must change. If, instead, you use balanced delimiters, then a subexpression no longer has to encode its position within the containing expression. Let me demonstrate the isomorphism. A simple python expression: (grrr.. I cut and paste it, but it lost its indentation between the PDF file and Emacs. I hope I redo it right...) def index(directory): # like os.listdir, but traverses directory trees stack = [directory] files = [] while stack: directory = stack.pop() for file in os.listdir(directory): fullname = os.path.join(directory, file) files.append(fullname) if os.path.isdir(fullname) and not os.path.islink(fullname): stack.append(fullname) return files Now the reason we know that ` files.append(fullname)' and ` fullname = os.path.join(directory, file)' are part of the same block is because they both begin with 12 spaces. The first four spaces encode the fact that they belong to the same function, the next four indicate that they belong in the while loop, and the final four indicate that they belong in the for loop. The ` return files', on the other hand, only has four spaces, so it cannot be part of the while or for loop, but it is still part of the function. I can represent this same information as a code: t -def index(directory): d - # like os.listdir, but traverses directory trees d - stack = [directory] d - files = [] d - while stack: dw - directory = stack.pop() dw - for file in os.listdir(directory): dwf - fullname = os.path.join(directory, file) dwf - files.append(fullname) dwf - if os.path.isdir(fullname) and not os.path.islink(fullname): dwfi- stack.append(fullname) d - return files The letter in front indicates what lexical group the line belongs to. This is simply a different visual format for the leading spaces. Now, suppose that I wish to protect the body of the while statement within a conditional. Simply adding the conditional won't work: d - while stack: dw - if copacetic(): dw - directory = stack.pop() dw - for file in os.listdir(directory): dwf - fullname = os.path.join(directory, file) dwf - files.append(fullname) dwf - if os.path.isdir(fullname) and not os.path.islink(fullname): dwfi- stack.append(fullname) because the grouping information is replicated on each line, I have to fix this information in the six different places it is encoded: d - while stack: dw - if copacetic(): dwi - directory = stack.pop() dwi - for file in os.listdir(directory): dwif - fullname = os.path.join(directory, file) dwif - files.append(fullname) dwif - if os.path.isdir(fullname) and not os.path.islink(fullname): dwifi- stack.append(fullname) The fact that the information is replicated, and that there is nothing but programmer discipline keeping it consistent is a source of errors. >> There is yet one more problem. The various levels of indentation encode >> different things: the first level might indicate that it is part of a >> function definition, the second that it is part of a FOR loop, etc. So on >> any line, the leading whitespace may indicate all sorts of context-relevant >> information. > > I don't understand why this is any different to e.g. ')))))' in Lisp. The > closing ')' for DEFUN just looks the same as that for IF. That is because the parenthesis *only* encode the grouping information, they do not do double duty and encode what they are grouping. The key here is to realize that the words `DEFUN' and the `IF' themselves look very different. >> Yet the visual representation is not only identical between all of these, it >> cannot even be displayed. > > I don't understand what you mean. Could you maybe give a concrete example of > the information that can't be displayed? Sure. Here are five parens ))))) How much whitespace is there here: > > Still, I'm sure you're familiar with the following quote (with which I most > heartily agree): > > "[P]rograms must be written for people to read, and only incidentally for > machines to execute." > > People can't "read" '))))))))'. Funny, the people you just quoted would disagree with you about parenthesis. I expect that they would disagree with you about whitespace as well. From cookedm+news at physics.mcmaster.ca Fri Oct 10 17:11:12 2003 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Fri, 10 Oct 2003 17:11:12 -0400 Subject: distutils question->when do install, says header (.h) file is an unknown file type!?!?! References: <87u16hcm6u.fsf@psi.lupan.zamek.gda.pl> Message-ID: At some point, Lukasz Pankowski wrote: > seberino at spawar.navy.mil (Christian Seberino) writes: > >> I have a program that has Python and C code. >> >> I added Extension stuff to setup.py and all .c and .h >> files get into tarball fine. >> >> (I have something like Extension("foo", glob.glob("bar/*.[ch]") ) >> >> When I try to INSTALL the package it says header (.h) >> file is an unknown type. How fix this??? >> >> Chris > > Do not include your header files in Extension (their not supported > there), if you want to distribute them with your extension, add them > to setup call, as in > > setup(..., headers=['bcsim/bcsim.h']) > > if you only need them to build your extension (for source > distributions and rpms) include them in MANIFEST.in instead. distutils now supports (as of 2.3) the depends= keyword in Extension, which adds more make-like functionality: Extension("foo", ['bar/bar.c'], depends=['bar/bar.h']) will cause the foo module to be rebuilt if bar/bar.h changes. I think what the OP wants is for his .h files to be included in the source distribution. setup(..., headers=[...]) won't do that; you'll still have to add them to the MANIFEST.in. When in doubt whether it will be packaged, add it to MANIFEST.in. -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From claird at lairds.com Thu Oct 9 05:49:54 2003 From: claird at lairds.com (Cameron Laird) Date: Thu, 09 Oct 2003 09:49:54 -0000 Subject: Making variable from a variable References: Message-ID: In article , Dave Benjamin wrote: >In article , Polerio >Babao Jr.II wrote: >> in php >> >>> >> $a = 'b'; >> ${$a} = 'c'; >> print "$a $b"; >> >> ?> >> >> output is >> >> b c > >Your PHP example can be accomplished with a dictionary, which is a better >way to go altogether in my opinion: . . . > >And don't program that way, anyway. It's just SILLY. (Believe me. I used to >write plenty of PHP.) > . . . It's suboptimal *even in PHP*. It's a great puzzle to my why leading PHPers continue to propagate this unhelpful idiom. I'll be more precise: there are few calls for appli- cation programmers to give variables variable names. "Systems programmers" writing frameworks, debugging jigs, and such, certainly need the capability. -- Cameron Laird Business: http://www.Phaseit.net From rossberg at ps.uni-sb.de Thu Oct 23 12:25:46 2003 From: rossberg at ps.uni-sb.de (Andreas Rossberg) Date: Thu, 23 Oct 2003 18:25:46 +0200 Subject: Python from Wise Guy's Viewpoint References: <_8Ekb.7543$pT1.318@twister.nyc.rr.com> <3f972315$1@news.unimelb.edu.au> <3638acfd.0310230039.306b14f@posting.google.com> Message-ID: <3F98010A.5000804@ps.uni-sb.de> Pascal Costanza wrote: >> >> But only at runtime, where a logic flaw may or may not trigger the >> assertion. > > I don't care about that difference. My development environment is > flexible enough to make execution of test suites a breeze. I don't need > a separate compilation and linking stage to make this work. > >> (Assertions are still useful: if they are active, they prove that the >> errors checked by them didn't occur in a given program run. This can >> still be useful. But then, production code usually runs with assertion >> checking off - which is exactly the point where knowing that some bug >> occurred would be more important...) > > Don't let your production code run with assertion checking off then. You don't seem to see the fundamental difference, which has been stated as "Static typing shows the absence of [certain classes of] errors, while testing [with assertions] can only show the presence of errors." When you actively use a type system as a tool and turn it to your advantage that "certain class" can be pretty large, btw. > I hear that in the worst case scenarios, static type checking in modern > type systems needs exponential time, but for most practical cases this > doesn't matter. Maybe it also doesn't matter for most practical cases > that you can't check all permutations of data in a test suite. Come on, you're comparing apples and wieners. The implications are completely different. -- Andreas Rossberg, rossberg at ps.uni-sb.de "Computer games don't affect kids; I mean if Pac Man affected us as kids, we would all be running around in darkened rooms, munching magic pills, and listening to repetitive electronic music." - Kristian Wilson, Nintendo Inc. From frodef at cs.uit.no Fri Oct 3 18:22:47 2003 From: frodef at cs.uit.no (Frode Vatvedt Fjeld) Date: Sat, 04 Oct 2003 00:22:47 +0200 Subject: Python syntax in Lisp and Scheme References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> <92c59a2c.0310031345.57d20631@posting.google.com> Message-ID: <2h65j69d1k.fsf@vserver.cs.uit.no> jcb at iteris.com (MetalOne) writes: > [..] However, from an earlier post on comp.lang.python comparing a > simple loop. > > Scheme > (define vector-fill! > (lambda (v x) > (let ((n (vector-length v))) > (do ((i 0 (+ i 1))) > ((= i n)) > (vector-set! v i x))))) > > Python > def vector_fill(v, x): > for i in range(len(v)): > v[i] = x > > To me the Python code is easier to read, and I can't possibly fathom > how somebody could think the Scheme code is easier to read. It truly > boggles my mind. [..] The scheme example can only have been written by someone who is on the outset determined to demonstrate that sexp-syntax is complicated. This is how I'd write it in Common Lisp: (defun vector-fill (v x) (dotimes (i (length v)) (setf (aref v i) x))) As you can see, it matches the python example quite closely. > [..] If a set of macros could be written to improve LISP syntax, > then I think that might be an amazing thing. An interesting > question to me is why hasn't this already been done. Lisp macros and syntactic abstractions are one of those things whose power and elegance it is somewhat hard to explain to those who have not experienced it themselves first hand. Paul Graham's book "On Lisp" is considered by many to be a good introduction to the subject. I am quite comforatble with Common Lisp's syntax, and I see no particular need for some set of macros to improve its syntax. In fact I have no idea what so ever as to what such a set of macros would look like. -- Frode Vatvedt Fjeld From bignose-hates-spam at and-benfinney-does-too.id.au Wed Oct 15 00:54:27 2003 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 15 Oct 2003 14:44:27 +0950 Subject: assignment expression peeve References: <7x1xtfkuky.fsf@ruckus.brouhaha.com> Message-ID: On 14 Oct 2003 21:12:29 -0700, Paul Rubin wrote: > It gets annoying when there are 4 different regexps that the line > might match, and I want to do something different depending on which > one matches. If you want to do lots of different things, you really should be placing them in different functions: def deal_with_line_type_A(): # do stuff for lines of type A def deal_with_line_type_B(): # do stuff for lines of type B This allows the tasks to be completely different for each type of line, without cramming it into one structure. Then, having defined what to do with each line type, map the regex to the function for each type: line_action = { 'AAA': deal_with_line_type_A, 'BBB': deal_with_line_type_B, } The dictionary then acts as the switchboard: for regex in line_action: match = re.match( regex, line ) if( match ): line_action[regex](match) Extending the range of lines is a matter of adding items to line_actions, and writing the resulting function. The decision code remains the same. -- \ "Self-respect: The secure feeling that no one, as yet, is | `\ suspicious." -- Henry L. Mencken | _o__) | Ben Finney From rudy.schockaert at pandoraSTOPSPAM.be Mon Oct 13 16:20:28 2003 From: rudy.schockaert at pandoraSTOPSPAM.be (Rudy Schockaert) Date: Mon, 13 Oct 2003 20:20:28 GMT Subject: Python vs Visual Basic In-Reply-To: <3F8AFDD0.DE2F91DD@easystreet.com> References: <3F8ABD2D.324E7381@easystreet.com> <18flovotqn296g70t0s358pglrs5pu91es@4ax.com> <3F8AFDD0.DE2F91DD@easystreet.com> Message-ID: > Can't RTF's contain arbitrary binary data embedded within (eg images)? > From the RTF specification: Pictures An RTF file can include pictures created with other applications. These pictures can be in hexadecimal (the default) or binary format. From avera at coes.org.pe Mon Oct 20 19:13:48 2003 From: avera at coes.org.pe (Alberto Vera) Date: Mon, 20 Oct 2003 18:13:48 -0500 Subject: structure in Python Message-ID: <000b01c3975f$d15a7700$1603a8c0@pc22> Hello: I have the next structure: [key1,value1,value2] ['A',1,5] ['B',6,7] How Can I make it using Python? How Can I update the value of 6? How Can I insert a key called "C" and its values? How Can I delete a key called "B"? How Can I search a key called "A"(parameter) and get its values? Regards -------------- next part -------------- An HTML attachment was scrubbed... URL: From jjl at pobox.com Sun Oct 26 12:34:32 2003 From: jjl at pobox.com (John J. Lee) Date: 26 Oct 2003 17:34:32 +0000 Subject: AI and cognitive psychology rant (getting more and more OT - tell me if I should shut up) References: <9XVib.214859$hE5.7243121@news1.tin.it> <3ovpovc9hmahv5g373jm2oo7mk3i83ldtb@4ax.com> <29cjb.218983$hE5.7379913@news1.tin.it> <5tksov8r4c3caoatfoslfi87q61dupaq81@4ax.com> <2askpv0sqrv7k9hbpis3ig4iqclpl24ojc@4ax.com> <3f8lpvsddmeltg69vkl2uu8u8cei7bb2cg@4ax.com> <52Tmb.34761$Fm2.13285@attbi_s04> Message-ID: <87he1voqc7.fsf@pobox.com> "Rainer Deyke" writes: > Robin Becker wrote: > > Your assertion that there is an objective reality requires proof as > > well. Probably it cannot be proved, but must be made an axiom. The > > scientific method requires falsifiability. > > If the statement that there is an objective reality (or any other statement) > can be objectively proven either way, then objective truth (and hence > objective reality) exists. If it cannot, then the statement that there is > an objective reality is as true as any other statement, and requires no > proof. The justification of scientific knowledge doesn't require proof in the usual sense of the word, so your statement seems ill-founded. My guess is that the concept of reality is a metaphysical one, though (inevitably quoting from Deutsch again): "The reliability of scientific reasoning is ... a new fact about physical reality itself..." John From hungjunglu at yahoo.com Mon Oct 20 03:12:20 2003 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 20 Oct 2003 00:12:20 -0700 Subject: closing excel application References: <8ef9bea6.0310180909.57b47ff6@posting.google.com> Message-ID: <8ef9bea6.0310192312.a711255@posting.google.com> hungjunglu at yahoo.com (Hung Jung Lu) wrote in message > > import win32com.client > import pythoncom > app = win32com.client.Dispatch('Excel.Application') > app.Visible = 1 > ... > print pythoncom._GetInterfaceCount() > app = None > print pythoncom._GetInterfaceCount() > pythoncom.CoUninitialize() Sorry, missed the line app.Quit() before the first print statement. import win32com.client import pythoncom app = win32com.client.Dispatch('Excel.Application') app.Visible = 1 ... app.Quit() print pythoncom._GetInterfaceCount() app = None print pythoncom._GetInterfaceCount() pythoncom.CoUninitialize() Hung Jung From reply.in.the.newsgroup at my.address.is.invalid Sat Oct 4 08:22:53 2003 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Sat, 04 Oct 2003 14:22:53 +0200 Subject: Web-crawling References: Message-ID: John Bradbury: >I am trying to develop a special putpose crawler using htmllib & urllib. >How do you tell the server application that you are a modern browser and can >handle frames? I don't know of any "I can handle frames" header and I don't see why the server would care, but you could mimic the User-agent header sent by a modern browser. -- Ren? Pijlman From mwilson13 at cox.net Mon Oct 13 00:13:18 2003 From: mwilson13 at cox.net (Mark Wilson) Date: Mon, 13 Oct 2003 00:13:18 -0400 Subject: Python syntax in Lisp and Scheme In-Reply-To: Message-ID: <92FB5132-FD33-11D7-B569-000393876156@cox.net> On Sunday, October 12, 2003, at 06:56 PM, Alex Martelli wrote: > Mark Wilson wrote: > ... >> 3. Python's syntax is one of the worst features of the language and > > Ha. How cogent. > >> should not be adopted by Lisp and Scheme. > > Obviously not, as it would not fit in with all the rest of their > features. That idea was the point of the post that started this thread/ > >> Joe Marshall's analysis is establishes this. There have been no > > "is establishes"? Is that a new variant on "all your bases are belong > to us"? Typographical error. > >> responses to Joe Marshall's analysis that successfully refute his >> analysis. > > I guess I haven't been posting ENOUGH on this thread -- I don't > recall the "is establishes" analysis in question, just the usual FUD > about "copy and paste errors" and other variants on whitespace- > eating nanoviruses -- I tore a few to shreds, but it was almost > incidental to all the rest of the volume. Check on the responses from Joe Marshall (who also has an email account called prunesquallor, or something like that. The only person to engage his arguments in this thread was the original poster. I would find it enlightening to read a cogent response to his analysis, although I doubt that one can in fact be maintained. > >> 4. The productivity of the prolific posters must have precipitously >> phaded. > > True in my case -- the amount of FUD and insults posted and > demanding response being so high -- as seen above, even so I > may not have noticed all of the "is establishes" alleged ``analyses'' > which sufficiently clueless readers (and you seem to be successfully > posing as one) may think "irrefutable" unless one tediously, over > and over, cuts them to confetti-size shreds and throws back > into their proponents' faces. The above is really uncalled for and beneath a person of your purported stature. It makes me wonder if I was wrong to think highly of you. Confronting Lisp may have had a deleterious effect on your thinking. As to me being clueless, that may be true, although I have my doubts. Clear cogent arguments advancing your views might provide me with a clue. > I guess I'm just about ready to drop > off this interminable thread, except presumably for whatever > further dismantling of insults, FUD and disinformation I just > can't resist. Please resist. > > >> 5. Use Ruby, be happy. > > I earnestly hope you'll start a new cross-thread between c.l.lisp and > c.l.ruby about first-class functions, macros, case sensitivity, regular > expressions as inherently embedded in the language, and whatever > else can most enflame them -- please leave c.l.ruby out of it, tx. I have nothing against Lisp or Scheme (I'm learning both). I have nothing against Ruby either (Ruby is my favorite language and the first one I started learning). It has the advantage of not considering other programming languages a waste of time. I have never heard a Ruby programmer complain about others "wasting" their efforts on other programming languages. I have heard such talk from Python people. So what is it with the Python people? > Alex Regards, Mark Wilson From ingvar at cathouse.bofh.se Thu Oct 9 05:31:51 2003 From: ingvar at cathouse.bofh.se (Ingvar Mattsson) Date: 09 Oct 2003 10:31:51 +0100 Subject: Python syntax in Lisp and Scheme References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> Message-ID: <87k77ekb94.fsf@gruk.tech.ensign.ftech.net> "Karl A. Krueger" writes: [SNIP] > Incidentally, I regard objections to "the whitespace thing" in Python > and objections to "the parenthesis thing" in Lisp as more or less the > same. People who raise these objections are usually just saying "Ick! > This looks so unfamiliar to me!" in the language of rationalizations. > I guess a philosopher would say that I am an emotivist about notation > criticisms. My main problem with "indentation controls scoping" is taht I've actually had production python code die because of whitespace being mangled in cutting&pasting between various things. It looks a bit odd, but after having written BASIC, Pascal, APL, Forth, PostScript, Lisp, C and Intercal looking "odd" only requires looking harder. Killing a production system due to whitespace-mangling isn't. And, yes, I probably write more Python code than lisp code in an average week. //Ingvar -- Ingvar Mattsson; ingvar at hexapodia.net; You can get further with a kind word and a 2x4 than you can with just a kind word. Among others, Marcus Cole From spock at telerama.com Wed Oct 29 06:49:08 2003 From: spock at telerama.com (Matt Newcomb) Date: 29 Oct 2003 03:49:08 -0800 Subject: jython/java inheritance question? Message-ID: <40cdba6.0310290349.64842cb@posting.google.com> G'day, Hi, I've got a java class called ChannelIteratorAlgorithm which extends SampledChannelGroupIteratorAlgorithm. SampledChannelGroupIteratorAlgorithm has a stub method processSampledChannelGroup(Object[] in, Object[] out) that is overridden by a method in the ChannelIteratorAlgorithm class. Now, I've got a jython script that contains a class that extends the ChannelIteratorAlgorithm class ( are you having fun yet? ) and it's got a processSampledChannelGroup method that looks like this: class testalg(ChannelIteratorAlgorithm): def processSampledChannelGroup(self, inGroups, outGroups): if (self.samplesToPass!=0): print "samples left: %d" % self.samplesToPass ChannelIteratorAlgorithm.processSampledChannelGroup(self, inGroups, outGroups) However, each time I try to run this script I get this exception: 2003-10-29 05:26:29 ERROR:: spigot_1.handleData() encountered a fatal Exception:Traceback (innermost last): File "", line 187, in processSampledChannelGroup AttributeError: class 'gov.nasa.gsfc.irc.algorithms.ChannelIteratorAlgorithm' has no attribute 'processSampledChannelGroup' What?!?!?! Why an attribute and not a method? And why, given that yes there is an implementation of processSampledChannelGroup in the ChannelIteratorAlgorithm class and yes it really looks like: protected void processSampledChannelGroup (Object[] inputChannelDataBuffersForGroup, Object[] outputChannelDataBuffersForGroup) would there be an issue? Is this a feature that I'm unaware of? Thanks for any suggestions, Matt Newcomb Yerkes Observatory Williams Bay, WI 53191 From adalke at mindspring.com Mon Oct 6 04:09:24 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Mon, 06 Oct 2003 08:09:24 GMT Subject: Python syntax in Lisp and Scheme References: <3cea3gqq.fsf@comcast.net> <3f805e89.11295087@news.eircom.net> <3f80ed0a.47781316@news.eircom.net> Message-ID: [cc'ed since I wasn't sure if you would be tracking the c.l.py thread] Russell Wallace: > A program is a stream of tokens, which may be separated by whitespace. > The sequence { (zero or more statements) } is a statement. Some C tokens may be separated by whitespace and some *must* be separated by whitespace. static const int i static const inti i + + + 1 i ++ + 1 The last case is ambiguous, so the tokenizer has some logic to handle that -- specifically, a greedy match with no backtracking. It throws away the ignorable whitespace and gives a stream of tokens to the parser. > What's the equivalent for Python? One definition is that "a program is a stream of tokens, some of which may be separated by whitespace and some which must be separated by whitespace." Ie, the same as my reinterpretation of your C definition. For a real answer, start with http://python.org/doc/current/ref/line-structure.html "A Python program is divided into a number of logical lines." http://python.org/doc/current/ref/logical.html "The end of a logical line is represented by the token NEWLINE. Statements cannot cross logical line boundaries except where NEWLINE is allowed by the syntax (e.g., between statements in compound statements). A logical line is constructed from one or more physical lines by following the explicit or implicit line joining rules." http://python.org/doc/current/ref/physical.html "A physical line ends in whatever the current platform's convention is for terminating lines. On Unix, this is the ASCII LF (linefeed) character. On Windows, it is the ASCII sequence CR LF (return followed by linefeed). On Macintosh, it is the ASCII CR (return) character." and so on. > Except that 'if', 'while' etc lines are terminated with delimiters > rather than newline. Oh, and doesn't Python have the option to use \ > or somesuch to continue a regular line? The C tokenizer turns the delimiter character into a token. The Python tokenizer turns indentation level changes into INDENT and DEDENT tokens. Thus, the Python parser just gets a stream of tokens. I don't see a deep difference here. Both tokenizers need to know enough about the respective language to generate the appropriate tokens. > But in ways that are objectively less severe because: > > - If the indentation is buggered up, the brackets provide the > information you need to figure out what the indentation should have > been. As I pointed out, one of the pitfalls which does occur in C is the dangling else if (a) if (b) c++; else /* indented incorrectly but valid */ c-- That mistake does not occur in Python. I personally had C++ code with a mistake based on indentation. I and three other people spent perhaps 10-15 hours spread over a year to track it down. We all knew where the bug was supposed to be in the code, but the indentation threw us off. > - The whole tabs vs spaces issue doesn't arise. That's an issue these days? It's well resolved -- don't use tabs. And you know, I can't recall a case where it's every been a serious problem for me. I have a couple of times had a problem, but never such that the code actually worked, unlike the if/else code I listed above for C. Andrew dalke at dalkescientific.com From huzzah at tampabay.rr.com Sun Oct 26 00:28:24 2003 From: huzzah at tampabay.rr.com (Todd Stephens) Date: Sun, 26 Oct 2003 04:28:24 GMT Subject: Newbie Questions: Swithing from Perl to Python References: Message-ID: On Sat, 25 Oct 2003 23:16:35 -0400, Roy Smith wrote: > Exactly. > > keys = myDict.keys() > keys.sort() > for key in keys: > print key Thanks for the info. Knowing that the Python community prefers one correct way to do something, can you explain to me how this is different/incorrect? : myD = {'x':4, 'k':2, 'r':3, 'e':1} myL = list(myD) myL.sort() for x in myL: print "%s = %s" %(x, myD[x]) When run, it yields this: e = 1 k = 2 r = 3 x = 4 I have tried this both ways, and I appear to get the same results. Are there situations where the method I have listed here would yield unpredictable or unwanted results? Or is this an area where Python doesn't care? -- Todd Stephens From follower at iname.com Sun Oct 26 23:08:42 2003 From: follower at iname.com (Follower) Date: 26 Oct 2003 20:08:42 -0800 Subject: "Error in sys.excepthook" message from Python 2.3 multi-threaded script Message-ID: Hi, I've run into an issue which seems to have been discussed previously on `python-dev` but only in context of Zope3: "Fun with 2.3 shutdown" -- Tim Peters The following message is displayed (one or more times) when exiting (in this case via a `KeyboardInterrupt` exception) a multi-threaded Python 2.3 script (on Mac OS X 10.2.1): """ Unhandled exception in thread started by Error in sys.excepthook: Original exception was: """ It doesn't always happen consistently. As a comparison, I have run the same script under Python 2.2.2 and the problem does not seem to occur there. (Although, of course, with threads that's no guarantee...) I had a look at the bug list on Sourceforge and this issue doesn't seem to have made it there yet, so I thought I'd raise it here, partly as Google-bait and partly to see if I should re-raise the issue on `python-dev`. The script in question is a multi-threaded curses framework I'm developing, and I can post code if that's useful. --Phil. From mspight at dnai.com Fri Oct 24 18:21:44 2003 From: mspight at dnai.com (Marshall Spight) Date: Fri, 24 Oct 2003 22:21:44 GMT Subject: Test cases and static typing References: <87ekx4xaym.dlv@wanadoo.fr> <87znfsvuqh.dlv@wanadoo.fr> <6ogn61-f61.ln1@ID-7776.user.dfncis.de> Message-ID: "Pascal Costanza" wrote in message news:bnc8dj$pvi$1 at f1node01.rhrz.uni-bonn.de... > > And that's all I wanted from the very beginning - static typing as an > additional tool, not as one that I don't have any other choice than use > by default. I can get behind that idea! It strikes me as being better than what one has now with either statically typed languages or dynamically typed languages. Marshall From mark_space44 at hotmail.com Thu Oct 9 22:56:25 2003 From: mark_space44 at hotmail.com (Mark Space) Date: Thu, 09 Oct 2003 19:56:25 -0700 Subject: %1 is not a valid Win32 application? In-Reply-To: References: Message-ID: Update #2: Renamed the extension yet again, this time to .py. Mozilla seems to recognize this as a text file and displays it, but IIS still doesn't seem to catch the .py rule I added to the IIS Admin properties. The script is still not being executed. Win2K Pro, IIS 5.0. SP4 and current on all updates. Man I hope someone can help, I'm really lost here. I think I'll try to add perl as a script just to see if I can get it to work. From jroznfgre at jngpugbjreQBGbet.cy Tue Oct 7 10:17:58 2003 From: jroznfgre at jngpugbjreQBGbet.cy (JZ) Date: Tue, 07 Oct 2003 16:17:58 +0200 Subject: SQLError: (2014, "Commands out of sync; You can't run this command now") Message-ID: I have problems with many concurrent request for Webware. I get the error: SQLError: (2014, "Commands out of sync; You can't run this command now") MyDB.py ======= from MyDBPool import datapool class MyDB(Config): def __init__(self): self.conn = None self.cursor = None self.rowcount = 0 def dbConnect(self): self.conn = datapool.getConnection() self.cursor = self.conn.cursor() def dbDisconnect(self): if self.cursor: self.cursor.close() if self.conn: self.conn.close() def execute(self, sql): self.dbConnect() self.rowcount = self.cursor.execute(sql) self.dbDisconnect() return self.rowcount #... MyDBPool.py: ========== # inspired from #http://sourceforge.net/mailarchive/forum.php?thread_id=2693193&forum_id=3505 from Config import Config import MySQLdb, MySQLdb.cursors from MiscUtils.DBPool import DBPool datapool = DBPool(MySQLdb, 20, host=Config.dbHost, user=Config.dbUser, passwd=Config.dbPasswd, db=Config.dbName , compress=0, cursorclass=MySQLdb.cursors.DictCursor) I do not know how to fix it. I tried change above method to: def execute(self, sql): _cache_lock = thread.allocate_lock() _cache_lock.acquire() self.dbConnect() self.rowcount = self.cursor.execute(sql) self.dbDisconnect() _cache_lock.release() return self.rowcount But it could not help. :( -- JZ ICQ:6712522 From prunesquallor at comcast.net Tue Oct 14 03:19:39 2003 From: prunesquallor at comcast.net (prunesquallor at comcast.net) Date: Tue, 14 Oct 2003 07:19:39 GMT Subject: Python syntax in Lisp and Scheme References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> <92c59a2c.0310031345.57d20631@posting.google.com> Message-ID: Marcin 'Qrczak' Kowalczyk writes: > Note that Lisp and Scheme have a quite unpleasant anonymous function > syntax, which induces a stronger tension to macros than in e.g. Ruby or > Haskell. Good grief! Unpleasant is the inner classes needed to emulate anonymous functions in Java. From robin at jessikat.fsnet.co.uk Sun Oct 12 06:53:13 2003 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Sun, 12 Oct 2003 11:53:13 +0100 Subject: Identifying Caller References: Message-ID: In article , Tongu? Yumruk writes >Is there a way to identify the caller of a function? For example: > >def foo(): > print > >def bar(): > foo() > >I want foo to print "bar"... And it will be great if I can also detect >call is came from which module. > >Thanks. > try something like this ############################# def who_called_me(n=0): import sys f = sys._getframe(n) c = f.f_code return c.co_filename, c.co_name, f.f_lineno if __name__=='__main__': def test2(): print 'test2',who_called_me(1) def test1(): print 'test1',who_called_me(1) test2() def test(): print 'test',who_called_me(1) test1() test2() class dingo: def __init__(self): self.a = 1 print '__init__',who_called_me(1) def doit(self): print 'dingo.doit',who_called_me(1), self.a def calldoit(self): print 'dingo.calldoit',who_called_me(1), self.a self.doit() test() def mongo(): print 'mongo', who_called_me(1) d=dingo() d.doit() d.calldoit() test() test1() test2() mongo() -- Robin Becker From aleax at aleax.it Fri Oct 10 09:24:06 2003 From: aleax at aleax.it (Alex Martelli) Date: Fri, 10 Oct 2003 13:24:06 GMT Subject: Python syntax in Lisp and Scheme References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> <92c59a2c.0310031345.57d20631@posting.google.com> <6CZgb.3273$dn6.860@newsread4.news.pas.earthlink.net> Message-ID: Bj?rn Lindberg wrote: ... >> Agreed. I pointed out elsewhere that there has been no systematic >> study to show that Lisp code is indeed "so much shorter than the >> equivalent code in other languages" where "other languages" include >> Python, Perl, or Ruby. > > It would be interesting to see such studies made. Absolutely! But funding such studies would seem hard. Unless some company or group of volunteers had their own reasons to take some existing large app coded in Lisp/Python/Perl/Ruby, and recode it in one of the other languages with essentially unchanged functionality, which doesn't seem all that likely. And if it happened, whatever group felt disappointed in the results would easily find a zillion methodological flaws to prove that the results they dislike should be ignored, nay, reversed. In practice, such a re-coding would likely involve significant changes in functionality, making direct comparisons iffy, I fear. I know (mostly by hearsay) of some C++/Java conversions done within companies (C++ -> Java for portability, Java -> C++ for performance) with strong constraints on functionality being "just the same" between the two versions (and while that's far from a "scientific result", a curious pattern seems to emerge: going from C++ to Java seems to produce the same LOC's, apparently a disappointment for some; going from Java to C++ seems to expand LOC's by 10%/20%, ditto -- but how's one to say if the C++ code had properly exploited the full macro-like power of templates, for example...?). But I don't even have hearsay about any such efforts between different higher-level languages (nothing beyond e.g. a paltry few thousand lines of Perl being recoded to Python and resulting in basically the same LOC's; or PHP->Python similarly, if PHP can count as such a language, perhaps in a restricted context). >> In any case, it implies you need to get to some serious sized >> programs (1000 LOC? 10000LOC? A million?) before >> the advantages of Lisp appear to be significant. > > I think that goes for any advantages due to abstraction capabilities > of macros, OO or HOF. The small program in the study above seems to > capture the scripting languages higher level compared to the > close-to-the-machine languages C & C++. (I have not read all of it > though.) To show advantages of the abstraction facilities we have been > discussing in this thread, I believe much larger programs are needed. Yes, and perhaps to show advantages of one such abstraction facility (say macros) wrt another (say HOFs) would require yet another jump up in application size, if it could be done at all. Unless some great benefactors with a few megabucks to wast^H^H^H^H invest for the general benefit of humanity really feel like spending them in funding such studies, I strongly suspect they're never really going to happen:-(. Alex From guillermo.fernandez at epfl.ch Thu Oct 16 16:18:43 2003 From: guillermo.fernandez at epfl.ch (Guillermo Fernandez) Date: Thu, 16 Oct 2003 22:18:43 +0200 Subject: Python debugger Message-ID: <3f8efd3a@epflnews.epfl.ch> Hi, I'm trying to play with the python debugger. The idea is to put lines in the code to automatically define breakpoints at the starting of the debugger. (like: 1 def a(): 2 #--- break 3 print 'done' would automatically insert a break in the line number 2) I did the code appended (I'm still quite a beginner...) but it makes me problems. Traceback (most recent call last): File "C:\Python23\lib\site-packages\sm\scriptutils.py", line 52, in run sdb.run('exec codeObject in mainDict', locals(), mainDict) File "C:\Python23\lib\site-packages\sm\spedb.py", line 29, in run Sdb().run(statement, globals, locals) File "C:\Python23\lib\site-packages\sm\spedb.py", line 23, in run pdb.Pdb.do_break(self, str(linenbr)) File "C:\Python23\lib\pdb.py", line 262, in do_break filename = self.defaultFile() File "C:\Python23\lib\pdb.py", line 278, in defaultFile filename = self.curframe.f_code.co_filename AttributeError: Sdb instance has no attribute 'curframe' Exception raised while running script I run the program as: import spedb mainDict=__main__.__dict__ # mainDict can also be another argument passed, # I think it's also locals() by default mainDict['codeObject']=codeObject spedb.run('exec codeObject in mainDict', locals(), mainDict) I think it's because the breakpoint it's instaured before the run, but I really don't know how to put the breakpoint "inside" the run. Furthermore, if I define the method run like: def run(self, statement, globals, locals): bdb.Bdb.run(self, statement, globals, locals) it does not even prompt the usual prompt (not any prompt at all...)! I got this: >>> Running 'C:\Python23\Lib\site-packages\sm\spedb.py' ... Script '' returned exit code 0 Could someone give me a hint about: 1) Why it does not work? 2) How to modify it the way I want? Thanks a lot. G import pdb import bdb class Sdb(bdb.Bdb,pdb.Pdb): def __init__(self): pdb.Pdb.__init__(self) bdb.Bdb.__init__(self) def run(self, statement, globals, locals): functions={ '#--- break' : pdb.Pdb.do_break } lines=globals['source'].splitlines() linenbr=0 for line in lines: linenbr+=1 if line in functions: pdb.Pdb.do_break(self, str(linenbr)) bdb.Bdb.run(self, statement, globals, locals) def run(statement, globals=None, locals=None): Sdb().run(statement, globals, locals) From max at alcyone.com Wed Oct 15 19:31:53 2003 From: max at alcyone.com (Erik Max Francis) Date: Wed, 15 Oct 2003 16:31:53 -0700 Subject: expand tuple in string References: <3F8DBEB2.15063C06@alcyone.com> Message-ID: <3F8DD8E9.C9BA1F07@alcyone.com> Steve Lamb wrote: > Or: > > "%s%s%s" % myTuple That will not result in what he asked for: >>> myTuple = 'one', 'two', 'three' >>> '%s%s%s' % myTuple 'onetwothree' -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ There is nothing so subject to the inconstancy of fortune as war. \__/ Miguel de Cervantes From kaz at ashi.footprints.net Mon Oct 13 16:51:22 2003 From: kaz at ashi.footprints.net (Kaz Kylheku) Date: 13 Oct 2003 13:51:22 -0700 Subject: Python syntax in Lisp and Scheme References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> <92c59a2c.0310031345.57d20631@posting.google.com> Message-ID: Matthias Blume wrote in message news:... > Well, no, not really. You can define new syntactic forms in terms of > old ones, and the evaluation rules end up being determined by those of > the old ones. Again, with HOFs you can always get the same > effect -- at the expense of an extra lambda here and there in your > source code. A macro can control optimization: whether or not something is achieved by that extra lambda, or by some open coding. In the worst cases, the HOF solution would require the user to completely obfuscate the code with explicitly-coded lambdas. The code would be unmaintainable. Secondly, it would be unoptimizeable. The result of evaluating a lambda expression is an opaque function object. It can only be called. Consider the task of embedding one programming language into another in a seamless way. I want to be able to write utterances in one programming language in the middle of another. At the same time, I want seamless integration between them right down to the lexical level. For example, the embedded language should be able to refer to an outer variable defined in the host language. HOF's are okay if the embedded language is just some simple construct that controls the evaluation of coarse-grained chunks of the host language. It's not too much of an inconvenience to turn a few coarse-grained chunks into lambdas. But what if the parameters to the macro are not at all chunks of the source language but completely new syntax? What if that syntax contains only microscopic utterances of the host language, such as the mentions of the names of variables bound in surrounding host language? You can't put a lambda around the big construct, because it's not even written in the host language! So what do you do? You can use an escape hatch to code all the individual little references as host-language lambdas, and pepper these into the embedded language utterance. For variables that are both read and written, you need a reader and writer lambda. Now you have a tossed salad. And what's worse, you have poor optimization. The compiler for the embedded language has to work with these lambdas which it cannot crack open. It can't just spit out code that is integrated into the host language compile, where references can be resolved directly. > > This can only be accomplished with functions if you're > > willing to write a set of functions that defer evaluation, by, say > > parsing input, massaging it appropriately, and then passing it to the > > compiler. At that point, however, you've just written your own macro > > system, and invoked Greenspun's 10th Law. > > This is false. Writing your own macro expander is not necessary for > getting the effect. The only thing that macros give you in this > regard is the ability to hide the lambda-suspensions. That's like saying that a higher level language gives you the ability to hide machine instructions. But there is no single unique instruction sequence that corresponds to the higher level utterance. Macros not only hide lambdas, but they hide the implementation choice whether or not lambdas are used, and how! It may be possible to compile the program in different ways, with different choices. Moreover, there might be so many lambda closures involved that writing them by hand may destroy the clarity of expression and maintainability of the code. > To some people > this is more of a disadvantage than an advantage because, when not > done in a very carefully controlled manner, it ends up obscuring the > logic of the code. (Yes, yes, yes, now someone will jump in an tell > me that it can make code less obscure by "canning" certain common > idioms. True, but only when not overdone.) Functions can obscure in the same ways as macros. You have no choice. Large programs are written by delegating details elsewhere so that a concise expression can be obtained. You can no more readily understand some terse code that consists mostly of calls to unfamiliar functions than you can understand some terse code written in an embedded language build on unfamiliar macros. All languages ultimately depend on macros, even those functional languages that don't have user-defined macros. They still have a whole bunch of syntax. You can't define a higher order function if you don't have a compiler which recognizes the higher-order-function-defining syntax, and that syntax is nothing more than a macro that is built into the compiler which captures the idioms of programming with higher order functions! All higher level languages are based on syntax which captures idioms, and this is nothing more than macro processing. From tedNOSPAM94107 at yahoo.com Tue Oct 7 03:49:28 2003 From: tedNOSPAM94107 at yahoo.com (ted) Date: Tue, 7 Oct 2003 00:49:28 -0700 Subject: Could a single web framework popularize Python? References: Message-ID: Here's something I found: http://www.russellbeattie.com/notebook/20030725.html#125136 Talks about finding a good web framework. Here's an excerpt: "So in my humble opinion, it would be great if a corporate entity - bigger and more influential than Zope - started pushing Python a bit more. Documentation, standards, application server reference implementations, etc. In other words, a bit more like Java. There's got to be a middle ground between tight corporate control and open source free-for-all. Corporate sponsership (say by IBM or even Intel or some company of that stature) would also give a boost to its use throughout the rest of the corporate world and maybe give a boost to the numbers of jobs looking for Python skills. The Python people who are happy with the status quo will probably think I'm nuts, and that's fine. I'm writing this for the teeming hoards of Java programmers looking around for something a bit funner (and more productive) to use who are going to run smack into the same issues I've run into." "Dave Harrison" wrote in message news:mailman.1065496032.26719.python-list at python.org... > > Because everyone has made their own, and no one can agree on what a > > dominant web framework might be. Zope *was* that framework, with > > dominant mindshare, but it didn't keep other people from making other > > frameworks. > > > > There's already a ton of frameworks, but I think I saw two brand new > > ones on PyPI this last week. Crazy. > > hehehe.... my opinion is that development in python is fun, I doubt any > on this list would really disagree with me on that point ;-) > > which ultimately means people are much more likely to say, "oh we need a > system that does X, sure, we can write that ourselves !" while chuckling > and rubbing their hands with glee at the prospect ;-) > > so we end up with a huge range of tools for the same kinds of things. > > vive la python !! ;-) *laughs* > From neil.padgen at mon.bbc.co.uk Tue Oct 28 07:54:50 2003 From: neil.padgen at mon.bbc.co.uk (Neil Padgen) Date: Tue, 28 Oct 2003 12:54:50 +0000 Subject: logging module: problem with custom handlers References: Message-ID: <863cddbjz9.fsf@pc-nrp.dev.mon.bbc.co.uk> >>>>> "Peter" == Peter Otten <__peter__ at web.de> writes: Peter> I do not know if there is an "official" way to achieve the Peter> same, but then, why would you build your own Handler in the Peter> first place? I've just done exactly the same approach (independently), because of a need to build two Handlers of my own. One is to avoid tracebacks being logged with a SysLogHandler (it makes the syslog messages too long, so nothing is logged), and the other is a subclass of SMTPHandler which changes the subject of the mail if an exception of a certain type is raised. [1] I can think of plenty of other instances where building a custom Handler is needed; for example, an SQLHandler which might log messages to a database. [1] This might be better done with a different Formatter, but getting a custom Formatter to be used by logging.config is much harder than a custom Handler, due to logging.Formatter() being called from within logging.config.fileConfig(). Personally I think logging.config.fileConfig() is in need of some serious refactoring... if only I had time to look into it! -- Neil From google at dalvander.com Fri Oct 31 08:27:01 2003 From: google at dalvander.com (Anders Dalvander) Date: 31 Oct 2003 05:27:01 -0800 Subject: popen[2-4] does not work with parameters inside quotes References: Message-ID: Derrick 'dman' Hudson wrote in message news:... > Not surprising. Pick command.COM or cmd.exe. *siq* I should have written anycommand.exe instead of command.exe... From seberino at spawar.navy.mil Tue Oct 7 15:45:21 2003 From: seberino at spawar.navy.mil (Christian Seberino) Date: 7 Oct 2003 12:45:21 -0700 Subject: distutils (packaging) newbie questions please.... References: Message-ID: Alex Your email motivated me to buy your book. I think Nutshell was a VERY good purchase. Why? Lots of other docs for newbies don't go into too much detail. Your book is great for the completeness. Intermediate users need that.... especially if they don't like reading python.org docs online. CS Alex Martelli wrote in message news:... > Christian Seberino wrote: > > > I really want to learn distutils to professionally package some open > > source software. > > > > I had some distutils questions after reading python.org distutil docs > > on packaging code > > if you don't mind. I would really appreciate some help..... > > > > > > 0. I'm confused about use of the word "package" in setup.py. > > packages = ["", "", ...] > > Does package here just mean "a new directory of source code to > > consider"??? > > No, it means a Python package. The concept of "package" (a module > that may contain other modules, and corresponds to a directory with > an __init__.py file) exists in Python quite independently from > distutils -- the distutils just SUPPORT the concept, if the code > you want to package-up uses Python packages. > > > > 1. What exactly goes into the __init__.py files? I know what to put in > > setup.py > > and I know __init__.py is used for packages but I don't know what > > to put IN this file. > > Again, not a distutils-related question. A Python package's __init__.py > has the module-body of the package (remember, any package IS a module). > If you need no Python statements whatsoever in that body, __init__.py > may be empty (it must still exist, or else Python will refuse to > consider that directory as a package). Normally you do want, at least, > to assign the appropriate list to __all__ . > > In p. 124 of "Python in a Nutshell", i.e. the section named "Packages", > I summarize the issue as follows: > """ > A package named P resides in a subdirectory, also called P, of some > directory in sys.path. The module body of P is in the file P/__init__.py. > You must have a file named P/__init__.py, even if it's empty (representing > an empty module body), in order to indicate to Python that directory P > is indeed a package. > """ > > Do you find this unclear, or was it hard for you to find -- or didn't > you even considering checking out the Nutshell book before setting > yourself the task to "professionally package" some Python software? > Feedback on this (private or public as you wish) may help me do a > better job next time. [Note that if the issue is with the purchase > price of the Nutshell book, there IS a perfectly legal way to read it > for free: the "Safari" online book service of O'Reilly offers the > first two weeks free, so you can join it, and read Python in a Nutshell, > which is among the over 1000 books on Safari, paying nothing as long > as you cancel before two weeks are up]. > > > > 2. About the data_files option for setup.py.... > > > > data_files = [ "", [ "", > > "", ...] ] > > > > Is there a way to AVOID having to type EVERY single data file?? Can > > I specify just the directory or use wild cards?? > > You can form the list of file names in any way you wish, including, > for example, using the glob module from Python's standard library. > setup.py is a Python script, and any Python construct is available > to you as the author of that script. > > For example, suppose we wanted to package up (for installation under > directory foodir) all the files in our directory named datadir EXCEPT > those whose file-extension is '.not' . That's easy...: > > """ > from distutils.core import setup > > import glob > > thefiles = [] > for afile in glob.glob('datadir/*'): > if afile.endswith('.not'): continue > thefiles.append(afile) > > print "Packaging up", thefiles > > setup(name='justdata', data_files = [ [ 'foodir', thefiles ] ] ) > """ > > Here's an example of how this works: > > [alex at lancelot tryp]$ ls datadir > aa.yes bb.not cc.yes > [alex at lancelot tryp]$ python setup.py bdist > Packaging up ['datadir/aa.yes', 'datadir/cc.yes'] > running bdist > running bdist_dumb > running build > installing to build/bdist.linux-i686/dumb > running install > running install_data > creating build/bdist.linux-i686/dumb > creating build/bdist.linux-i686/dumb/usr > creating build/bdist.linux-i686/dumb/usr/local > creating build/bdist.linux-i686/dumb/usr/local/foodir > copying datadir/aa.yes -> build/bdist.linux-i686/dumb/usr/local/foodir > copying datadir/cc.yes -> build/bdist.linux-i686/dumb/usr/local/foodir > tar -cf /x/tryp/dist/justdata-0.0.0.linux-i686.tar . > gzip -f9 /x/tryp/dist/justdata-0.0.0.linux-i686.tar > removing 'build/bdist.linux-i686/dumb' (and everything under it) > [alex at lancelot tryp]$ tar tvzf dist/justdata-0.0.0.linux-i686.tar.gz > drwxrwxr-x alex/alex 0 2003-10-01 14:25:40 ./ > drwxrwxr-x alex/alex 0 2003-10-01 14:25:40 ./usr/ > drwxrwxr-x alex/alex 0 2003-10-01 14:25:40 ./usr/local/ > drwxrwxr-x alex/alex 0 2003-10-01 14:25:40 ./usr/local/foodir/ > -rw-rw-r-- alex/alex 0 2003-10-01 14:13:48 ./usr/local/foodir/aa.yes > -rw-rw-r-- alex/alex 0 2003-10-01 14:13:55 ./usr/local/foodir/cc.yes > [alex at lancelot tryp]$ > > > > 3. python setup.py sdist will make a package of SOURCE code and > > using "bdist" will put BINARIES in package. What does this > > mean??? > > Will bdist packages unpack to pyc (bytecode) files and sdist will > > unpack > > py (noncompiled) files???? What if I wanted py and pyc files > > installed > > from the package?? (i.e. source and compiled versions) > > Hmmm, if the issue was so unclear (and important) to you, was it > SO hard to try things out...? Say that setup.py is: > > from distutils.core import setup > > setup(name='onemodule', py_modules=['hello']) > > and hello.py in the same directory is: > > def greet(name='World'): > return 'Hello, %s!' % name > > Now, running python setup.py bdist gives the output: > > [alex at lancelot tryp]$ python setup.py bdist > running bdist > running bdist_dumb > running build > running build_py > creating build/lib > copying hello.py -> build/lib > installing to build/bdist.linux-i686/dumb > running install > running install_lib > creating build/bdist.linux-i686/dumb > creating build/bdist.linux-i686/dumb/usr > creating build/bdist.linux-i686/dumb/usr/local > creating build/bdist.linux-i686/dumb/usr/local/lib > creating build/bdist.linux-i686/dumb/usr/local/lib/python2.3 > creating build/bdist.linux-i686/dumb/usr/local/lib/python2.3/site-packages > copying build/lib/hello.py -> > build/bdist.linux-i686/dumb/usr/local/lib/python2.3/site-packages > byte-compiling > build/bdist.linux-i686/dumb/usr/local/lib/python2.3/site-packages/hello.py > to hello.pyc > tar -cf /x/tryp/dist/onemodule-0.0.0.linux-i686.tar . > gzip -f9 /x/tryp/dist/onemodule-0.0.0.linux-i686.tar > removing 'build/bdist.linux-i686/dumb' (and everything under it) > > Notice that hello.py is copied into the directory to be packaged, as > well as hello,pyc. And indeed we can double check what's in the tarball: > > [alex at lancelot tryp]$ tar tvzf dist/onemodule-0.0.0.linux-i686.tar.gz > drwxrwxr-x alex/alex 0 2003-10-01 14:30:41 ./ > drwxrwxr-x alex/alex 0 2003-10-01 14:30:41 ./usr/ > drwxrwxr-x alex/alex 0 2003-10-01 14:30:41 ./usr/local/ > drwxrwxr-x alex/alex 0 2003-10-01 14:30:41 ./usr/local/lib/ > drwxrwxr-x alex/alex 0 2003-10-01 14:30:41 > ./usr/local/lib/python2.3/ > drwxrwxr-x alex/alex 0 2003-10-01 14:30:42 > ./usr/local/lib/python2.3/site-packages/ > -rw-rw-r-- alex/alex 56 2003-10-01 14:30:10 > ./usr/local/lib/python2.3/site-packages/hello.py > -rw-rw-r-- alex/alex 335 2003-10-01 14:30:42 > ./usr/local/lib/python2.3/site-packages/hello.pyc > [alex at lancelot tryp]$ > > See? Both the .py AND the .pyc, as expected. > > Should you want to REMOVE the .py files, for example, that can > easily be achieved by operating directly on the tarball or zipfile, > after distutils is finished (customizing distutils for such > purposes, on the other hand, is harder). > > > Alex From Alexandre.Fayolle at logilab.fr Thu Oct 9 06:20:04 2003 From: Alexandre.Fayolle at logilab.fr (Alexandre Fayolle) Date: Thu, 9 Oct 2003 12:20:04 +0200 Subject: [ANN] xmldiff-0.6.4 In-Reply-To: <20031009101347.GP23519@calvin> References: <20031009101347.GP23519@calvin> Message-ID: <20031009102003.GQ23519@calvin> On Thu, Oct 09, 2003 at 12:13:47PM +0200, Alexandre Fayolle wrote: > Download: ftp://ftp.logilab.org/pub/common/xmldiff-0.6.4.tar.gz Sorry, wrong URL. Please use ftp://ftp.logilab.org/pub/xmldiff/xmldiff-0.6.4.tar.gz -- Alexandre Fayolle LOGILAB, Paris (France). http://www.logilab.com http://www.logilab.fr http://www.logilab.org D?veloppement logiciel avanc? - Intelligence Artificielle - Formations From jjl at pobox.com Mon Oct 6 18:04:38 2003 From: jjl at pobox.com (John J. Lee) Date: 06 Oct 2003 23:04:38 +0100 Subject: Python/Wx dot net References: <3f7fafa6.52380188@news.la.sbcglobal.net> <3F801EF6.5D27230D@engcorp.com> <3f80ab5f.30293589@news.la.sbcglobal.net> <3f818cd7.6422224@news.la.sbcglobal.net> Message-ID: <87llry81l5.fsf@pobox.com> hankc at nospam.com (HankC) writes: [...] > they couldn't use Windows - I think as .net matures there will be > very few apps that won't be capable of running as managed code. > Drivers and other low level stuff may be excepted with an MS > certification or something. [...] Has anyone actually compiled (or tried to compile) CPython with a .NOT C compiler? John From sross at connectmail.carleton.ca Tue Oct 7 09:21:04 2003 From: sross at connectmail.carleton.ca (Sean Ross) Date: Tue, 7 Oct 2003 09:21:04 -0400 Subject: Python syntax in Lisp and Scheme References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> <92c59a2c.0310031345.57d20631@posting.google.com> Message-ID: "Bengt Richter" wrote in message news:bltqr0$eoe$0 at 216.39.172.122... > Just thought of this: a generator list comprehension, so your could write [snip] > Has someone proposed this already? I seems a natural, unless > I am blindly optimistic, which is quite possible ;-) [snip] Hi. Yes, they've been proposed (by Raymond Hettinger, PEP289) and rejected (http://www.python.org/peps/pep-0289.html). Sean From news at yebu.de Wed Oct 8 06:22:12 2003 From: news at yebu.de (Karl Scalet) Date: Wed, 08 Oct 2003 12:22:12 +0200 Subject: print is not a function In-Reply-To: References: Message-ID: Gon?alo Rodrigues wrote: > On Wed, 08 Oct 2003 11:32:20 +0200, Karl Scalet wrote: > > >>Hi, >> >>quite often there is a need to just print out the items of a list. >> >>[ prt(x) for x in my_list ] >> >>that would be nice, except prt() does not exist, and print is a >>statement not a function, hence cannot replace prt as of above. >> >>I don't like to write d >>def prt(x): >> print x >>beforehand and any lambda construct would not be so handy. >>It should be a short one-liner. >>Any ideas? >> >>Karl > > > How about, > > >>>>import sys >>>>sys.stdout.write("Hello world!\n") I came across this, but this requires an extra import sys which not always is there, thanks anyhow. Karl From Rigga at noemail.com Wed Oct 22 12:09:54 2003 From: Rigga at noemail.com (Rigga) Date: Wed, 22 Oct 2003 17:09:54 +0100 Subject: Return variables from modules ?? References: Message-ID: I have tried the code you supplied however it still does not return the reply as expected, I have even tried the following code but I just cant get it to return a variable from a module: My module: we will call it filechk.py ******************************************************************** import sys import os def myfunction(): reply = 'repeat' FilePath = raw_input("Enter path to files: ") def chkpth(FilePath): if os.path.exists(FilePath): # File location exists AccFlag = os.access(FilePath,os.R_OK | os.X_OK | os.W_OK) if (AccFlag): # Cool you have FULL access to # the location chkpth = "OK" reply = 'stop' else: # You do not have access chkpth = "DENIED" reply = 'repeat' else: # No files found exiting... chkpth = "NOT FOUND" reply = 'repeat' return chkpth print chkpth(FilePath) # used to show me chkpth result print reply # always prints repeat no matter what! return reply ******************************************************************** Main program: we will call it testme.py ******************************************************************** import filechk result = filechk.myfunction() print result ******************************************************************** results when ran: --------------------------------------------------- root at mybox:> python testme.py root at mybox:> Enter Path to files: /root/ root at mybox:> None What I expected to happen in the example above for it to return OK (and if I queried the reply variable for it to return 'stop) What am I doing wrong? From skip at pobox.com Mon Oct 27 12:29:52 2003 From: skip at pobox.com (Skip Montanaro) Date: Mon, 27 Oct 2003 11:29:52 -0600 Subject: which re a|l|t|e|r|n|a|t|i|v|e matched? Message-ID: <16285.22032.199699.858487@montanaro.dyndns.org> I have a long regular expression with the top-level form pat = 'A|B|C|D|...' where there are a couple hundred alternatives, each one being a fairly simple regular expression (typically just the name of a machine). Assuming I've compiled that and match against it: matcher = re.compile(pat) match = matcher.match(foo) if match is not None: ... is there a way to know what alternative was matched? Note that I'm not looking for match.group(1). I want to know which pattern among the various was matched. (I realize there might be more than one, but returning just one is okay.) If it helps, the regular expression is formed from the keys of a dictionary like so: pat = '('+'|'.join(d.keys())+')' I'm concatenating them like this so I don't need to make as many re.match() calls. I could narrow things down by doing a binary search of the keys(), but I was hoping for a simple way to do it in one shot. Thx, Skip From barry at python.org Mon Oct 20 11:44:17 2003 From: barry at python.org (Barry Warsaw) Date: Mon, 20 Oct 2003 11:44:17 -0400 Subject: <> and DeprecationWarning In-Reply-To: References: Message-ID: <1066664657.5750.46.camel@anthem> On Mon, 2003-10-20 at 11:21, Wojtek Walczak wrote: > Dnia Mon, 20 Oct 2003 12:18:31 +0200, Gerrit Holl napisa?(a): > > the <> inequality test operator has been deprecated for a loooooong time. > Who said that? Well, Guido doesn't like it, but Just does, so that cancels out the Van Rossum vote . I'm on Just's side though, but this is about as religious an argument as Pythoneers get. I'm confident there's no way <> can be officially deprecated as long as Python 2.x is alive. -Barry -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 316 bytes Desc: This is a digitally signed message part URL: From joachim.durchholz at web.de Thu Oct 23 06:42:15 2003 From: joachim.durchholz at web.de (Joachim Durchholz) Date: Thu, 23 Oct 2003 12:42:15 +0200 Subject: Python from Wise Guy's Viewpoint In-Reply-To: References: <_8Ekb.7543$pT1.318@twister.nyc.rr.com> Message-ID: Pascal Costanza wrote: > For example, static type systems are incompatible with dynamic > metaprogramming. This is objectively a reduction of expressive power, > because programs that don't allow for dynamic metaprogramming can't be > extended in certain ways at runtime, by definition. What is dynamic metaprogramming? Regards, Jo From tjreedy at udel.edu Fri Oct 3 10:19:10 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 3 Oct 2003 10:19:10 -0400 Subject: execfile return values References: Message-ID: "Enrique" wrote in message news:mailman.1065180983.27200.python-list at python.org... ''' ##ex.py### a=execfile('scr.py') print "return value: ", a ##scr.py### print "i'm scr.py" Executing that, a takes None value. ''' As documented in Lib Ref 2.1 Built-in Functions. If you have not read the execfile doc, please do, or reread. If you have read (or reread), tell us what part you do not understand. >Is there a way to handle the execution of the script ordered by the execfile statement?? I do not understand 'handle the execution of'. What you are trying to accomplish that did not happen? Terry J. Reedy From joe at invalid.address Mon Oct 27 13:26:40 2003 From: joe at invalid.address (joe at invalid.address) Date: Mon, 27 Oct 2003 18:26:40 GMT Subject: OT: The Straight Dope References: <3F9C3D01.9C77374E@comcast.net> Message-ID: claird at lairds.com (Cameron Laird) writes: > In article , > Nick Vargish wrote: > > >interactive use) -- very few system scripts are written in C-shell. In > >fact, C-shell programming generally seems to be deprecated in most > >environments. > . > canonically > summarizes why csh programming is naughty and ener- > vating. Also, http://www.grymoire.com/Unix/CshTop10.txt http://www.grymoire.com/Unix/Csh.html#uh-0 Joe From aleax at aleax.it Mon Oct 20 17:40:39 2003 From: aleax at aleax.it (Alex Martelli) Date: Mon, 20 Oct 2003 21:40:39 GMT Subject: Why don't people like lisp? References: <3f9302d7.170372828@news.eircom.net> Message-ID: Pascal Costanza wrote: ... > In the case of Python, couldn't you rightfully regard it as driven by a > one-man commitee? ;-) Ah, what a wonderfully meaningful view that is. >> Specifically: when you want to ALTER SYNTAX... > > If it were only about making small alterations to the syntax, I wouldn't I didn't say SMALL. Small or large, it's about alteration to the syntax. Other lispers have posted (on several of this unending multitude of threads, many but not all of which I've killfiled) stating outright that there is no semantic you can only implement with macros: that macros are ONLY to "make things pretty" for given semantics. If you disagree with them, I suggest pistols at ten paces, but it's up to you lispers of course -- as long as you guys with your huge collective experience of macros stop saying a million completely contradictory things about them and chastising me because (due, you all keep claiming, to my lack of experience) I don't agree with all of them, I'll be glad to debate this again. Till then, this is yet another thread that get killfiled. > lead this discussion. I mean what I say, I am talking about adding > full-fledged language constructs. Right: exactly what I _DON'T_ want to happen to my favourite language. >>>you have to step outside of the language, and for example use program >>>generators. Python doesn't give you a choice here. >> >> ...you can't "just alter Python's own syntax with your own changes": >> you have plenty of choices (implement your chosen semantics within >> Python's syntax, use any of N available parsers to parse your favourite >> syntax -- user EITHER "program generators" OR interpreters at any >> level on the parsed forms -- etc, etc). You just don't have the one >> choice of *altering Python's own syntax wholly within Python itself*. > > Exactly. Lisp-style Macros make these things a breeze. The other > alternatives you suggest are considerably more complicated. As I have What's "considerably more complicated" in, say, my_frobazzer = frobaz_compiler(''' oh my pretty, my beauteous, my own all my own special unique frambunctious *LANGUAGE*!!! ''') and later on call my_frobazzed(bim. bum, bam) at need? The complexity of the frobaz_compiler factory callable depends exclusively on the complexity of the language you want it to parse and compile, and you of course have total choice ("Python doesn't give you a choice" MY LEFT FOOT) on how to apportion the work between the factory and the __call__ method of the resulting my_frobazzer. You just have to respect Python's syntax and fundamental semantics (e.g., strict order when your Python code calls a Python callable -- you can ALWAYS, TOTALLY count on this, NO surprises possible EVER), and you still have a BAZILLION of choices, even AFTER making the decision, which SHOULD be momentous rather than "a breeze" (!!!), to CHOOSE to structure your whole application around your own unique language or sub-language. If Python makes it just as appealing to structure applications in other ways, reserving "language design" for those occasions which really call for it, so much the better. As I've repeatedly posted, I've SUFFERED the consequences of computer scientists "breezily" designing embedded Lisp subdialects for "domain-specific languages" for domains they DIDN'T know 1/10th as well as the poor non-CS'ers forced to suffer under that mishmash (hardware design the domain, hardware design engineers the poor non-CS'ers) -- while at other competing firms language design was treated with the respect it deserves, producing not-embedded-in-anything, not-necessarily- distorted-extended-subsets-of-anything hardware design languages that let people actually DESIGN HARDWARE when that was their job. > said before, Lisp makes the simple things a little bit harder (-> syntax > for beginners), so that the hard things become considerably simpler (-> > adding sophisticated abstractions in order to considerably reduce the > amount of code for complex tasks). The vast majority of applications has absolutely no need to tinker with the language's syntax and fundamental semantics. When you need a language with different syntax, this is best treated as a serious task and devoted all the respect it deserves, NOT treated as "a breeze". PARTICULARLY for domain-specific languages, the language's designers NEED access to domain-specific competence, which typically they won't have enough of for any domain that doesn't happen to be what they've spent many years of their life actually DOING (just STUDYING doesn't cut it); the people WITH the domain-specific competence will in turn not typically be experienced programmers -- they've spent their lives getting experience in the specific domain instead. Making things harder for "beginners" (which may well be the domain-specific experts) is then the wrong choice: those non-programmers fully deserve, if a domain-specific language is indeed warranted by the task's complexity, a language that does NOT just happens to embed bits and pieces of another, harder-for- beginners language, just because it was "a breeze" to design it thus. I'm talking about substantial applications meant to get into heavy production use. For experimentation, play, research in computing itself, whatever, go ahead, not my own interest. For application programming, IF a domain-specific language is needed, I want it to be designed FOR THE USERS' NEEDS AND CONVENIENCE (==productivity!), NOT because it's easy to hack together with macros. And that IF is a big one; more often than not, no weird new syntax and semantics are warranted. If it's too easy to tweak syntax and semantics, they will be tweaked whether that's warranted or not; such frequent and lightly undertaken SYNTAX CHANGES are NOT what I want in the language I will use, in collaboration with many others, to build applications. Some resistance to change is useful. Without attrition, walking would be VERY hard. Without a constitution that's FAR harder to change than ordinary laws, and "balance of powers" so that the legislature, the executive and the courts hamper each other, a democracy might be dangerously unstable (the "Federalist Papers" make that case particularly well). Without an unchanging core, such as syntax and fundamental semantics, a language may be less useful for application development by middling-large groups (the language might be wonderful for play and free-spirited experiments AND at the same time less wonderful for such usage). >> Describing a situation of having 99 available strategies rather than >> 100 as "doesn't give you a choice" can be charitably described as >> "ridiculous", it seems to me. > > I know about these choices, I have tried them all. I have written So, you KNOW "doesn't give you a choice" is ridiculous. > compilers, interpreters, with and without parser generators, and have > co-designed and used transformation frameworks. These things are > considerably harder to build, and you need to spend a considerable > amount of time on the technology itself which distracts you from solving You are (by far) exaggerating the effort. Check out such tools as spark or SimpleParse and you'll see that parsing a custom language, e.g. into an AST, is reasonably trivial. Once you have your AST, you're basically in the same position as you start out with S-exprs, so compiling and/or interpreting them is the same work. What you don't do this way is MERGING LANGUAGE AND META-LANGUAGE -- sprinkling bits and pieces of your own custom language in the middle of your implementation language and vice versa -- not "casually": if and when you decide to embed languages into each other you must deliberately take all decisions about arranging that. As a consequence, the language you design is NOT influenced by the language[s] you choose to use for the implementation thereof -- no special push to make the supposedly application-domain-specific language conform to uses and conventions typical of the implementation language, no fragments of the implementation language suddenly perking up in the middle of the application-domain-specific language. So, for example, the BLM Language being developed at AB Strakt (www.strakt.com) is INDEPENDENT from Python (though the designers have of course been influenced by the parts of Python's syntax they most liked, e.g., significant indentation); in the first implementation, the embedded language for expressions and actions is also Python, but the syntax already provides for embedding multiple procedural/imperative languages even inside a single BLM module. The interface between the declarative parts and the embedded imperative ones is defined in terms of functions and objects, so that, if and when the application-domain-specific experts demand it (and pay for it:-) other languages may just as well be adapter (sufficiently non-dynamic ones will necessarily end up with lots of boilerplate code such as attrib := blm.services->get_attribute(current_name); and the like, but then, users of non-dynamic languages do appear to like such boilerplate:-). Sure, it could perfectly have been done in lisp (or any other sufficiently high-level language just as well), but one would have had to resist the temptation to orient the language being designed towards "ease of implementation with lisp macros and ease of integration with snippets of lisp", making it a totally separate language -- and I've seen, and suffered on my own skin, what typical CS'ers do about resisting such temptation, particularly when convinced (as most, though not all, of you guys seem to be) that lisp is obviously the best language for ANY task, so why EVER could one POSSIBLY want a totally different one for [insert any application domain]...?! [Well, I've seen what they did about it 20+ years ago -- no doubt human nature HAS changed drastically since, I'm sure]. > the problem at hand. With Lisp-style macros, these things are much > simpler to handle once you have gotten it. But will the simple way be the RIGHT one? Or will you end up designing application-domain-specific languages needlessly, in applications that would be much better structured in other ways, AND when an application-domain-specific language IS called for, end up "along the continuum" designing it ``by inertia'' as just some "extended subset" of lisp, instead...? >> But _in practice, people don't_, except for play and experiments >> of various kinds. You can find a bazillion extremely varied >> extensions to Python of all imaginable kinds, *BUT* they're ALL >> *add-ons*, NEVER alteration of syntax or fundamental semantics > > You still have a wrong idea of how macros work. Macros are of course > also only add-ons. You don't alter unrelated syntax or unrelated > portions of source code, and you don't change fundamental semantics. I have HAD to use (several mutually incompatible varieties of) "application-domain-specific languages" built by lispers with their beloved macros (in the early '80s, so it wasn't common lisp yet, but rather a congeries of different lisp dialects, including scheme). I know how macros work: they get hacked by computer scientists that don't really grok the application domain, then the resulting "extended subset of lisp" du jour is foisted on people who DO know the application domain, CLAIMING falsely to be appropriate for the specific application domain -- why, they're (some kind of) lisp, OF COURSE they're automatically ideal for ANY application right? And I'm not sure what the "unrelated" syntax or portions of sources were, if any -- we had to describe system-level, interface-level, circuit-level &c views of a chip being developed in one or more of those (expl.del) "application awful languages" and NO of _course_ you can't use COND here because [gibbledygook] -- that's in AAL 1 as designed in Lab 1, while in AAL 2 designed in Lab 2 OBVIOUSLY you must use COND here, I thought you were HIRED because you had used lisp (I had, scheme actually, but that was the favoured lisp of lab _3_ so mentioning it in labs 1 or 2 made you an instant leper obviously). No doubt "the solution" you proposed would have been to learn a few of those GD macro systems and write the N-plus-1-th divergent incompatible subdialect. Yeah right. I found a better one -- jump ship to IBM Research, get a raise, get to use a GOOD (for the times, mind you -- still over 20 years ago) hardware design language, have the fun of my life designing HW for a while until I had to go back to SW -- and reconciling myself to the latter when I found out it didn't HAVE to mean endlessly designing languages for domains you didn't truly grasp with congeries of pieces of an existing language and half-baked concoctions of your own -- you COULD actually design good systems and algorithms, just like you could with hardware, using SOLID, UNCHANGING (inside a project's timeframe:-), _almost_-decently-designed-for-the-general-domain languages [PLURAL!!!! *YES*!!!]. Admittedly, "almost". I tried my hand at designing specialized languages (one of those sins that just about everybody practices in youth, I guess) and found out that, even when I grasped the application domain perfectly well, that still didn't make my languages usable by other experts of the domain (maybe because I kept falling onto prefix s-exproid syntax in those years -- and just about everybody else hated it). > Instead of spreading misconceptions you should really start to get to > know the things better that you criticize. Been there, done that, *NEVER, NEVER AGAIN*. Don't keep repeating this claim, analogous to one that somebody who's lived and suffered under a dictatorship shouldn't be spreading misconceptions but try being a dictator to "know the things better that you criticize". I don't want to foist my half-baked macro-based lisp dialects on others any more than I'm going to suffer others foisting their own on me, thankyouverymuch. If and when I should find myself working on a solo project for which the need to tweak syntax within an s-expr world appears, I may try some kind of lisp (hopefully, by then, Graham's new baby -- if he's as good as the reverence every lisper devotes him seems to indicate, then his claim that he can make a lisp that's better than both scheme and CL while having the strenths of both -- and then some -- should be credible). But, until then -- bye. And now, to killfile this thread too.... Alex From claird at lairds.com Fri Oct 10 15:33:53 2003 From: claird at lairds.com (Cameron Laird) Date: Fri, 10 Oct 2003 19:33:53 -0000 Subject: Could a single web framework popularize Python? References: <1Ivhb.193919$hE5.6560510@news1.tin.it> Message-ID: In article , Alex Martelli wrote: . . . >they're referring to the .net rather than the .org site. "Annotatable" >docs (perhaps with some overview) sure sounds like a way-cool idea, but >I have no first-hand experience of how well it works in practice. > > >Alex > Sometimes well, sometimes miserably. When *I* come across PHPers, yes, it's the online collaboratively-composed docu- mentation they say they miss. Showing them the Cookbook, the Tutorial, the Reference, and the Wiki goes a long way toward satisfying them. The natural follow-up, one already taking place all around us, is to wonder how to rework python.org so people find the Cookbook, the Tutorial, the Reference, and the Wiki on their own. -- Cameron Laird Business: http://www.Phaseit.net From gt5163b at prism.gatech.edu Sat Oct 25 15:41:52 2003 From: gt5163b at prism.gatech.edu (Brian McNamara!) Date: Sat, 25 Oct 2003 19:41:52 +0000 (UTC) Subject: Python from Wise Guy's Viewpoint References: <8yn9ce2k.fsf@comcast.net> Message-ID: prunesquallor at comcast.net once said: >The other problem is that monads don't compose. I disagree. See the discussion of "monad transformers" in part 3 of http://www.nomaware.com/monads/html/index.html I have even implemented a few of the monad transformers in C++. Composing monads is terrific! -- Brian M. McNamara lorgon at acm.org : I am a parsing fool! ** Reduce - Reuse - Recycle ** : (Where's my medication? ;) ) From $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk Thu Oct 16 06:30:39 2003 From: $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk (Stephen Horne) Date: Thu, 16 Oct 2003 11:30:39 +0100 Subject: AI and cognitive psychology rant (getting more and more OT - tell me if I should shut up) References: <7xvfqs66v6.fsf@ruckus.brouhaha.com> <0KRib.213549$hE5.7197672@news1.tin.it> <7id6cz7rl4.fsf@enark.csis.hku.hk> <9XVib.214859$hE5.7243121@news1.tin.it> <3ovpovc9hmahv5g373jm2oo7mk3i83ldtb@4ax.com> <29cjb.218983$hE5.7379913@news1.tin.it> Message-ID: <5tksov8r4c3caoatfoslfi87q61dupaq81@4ax.com> On Wed, 15 Oct 2003 13:42:22 GMT, Alex Martelli wrote: >Stephen Horne wrote: > ... >>>no understanding, no semantic modeling. >>>no concepts, no abstractions. >> >> Sounds a bit like intuition to me. > >Not to me. E.g., an algorithm (say one of those for long multiplication) >fits the list of no's (it may have been _invented_ or _discovered_ by some >human using any of those -- or suggested to him or her in a drunken stupor >by an alien visitor -- or developed in other ways yet; but that's not >relevant as to what characteristics the algorithm itself exhibits) but >it's nothing like intuition (humans may learn algorithms too, e.g. the >simple one for long multiplication -- they're learned and applied by >rote, "intuition" may sometimes eventually develop after long practice >but the algorithm when correctly followed gives the right numbers anyway). What is your definition of intuition? My dictionary has two definitions, and I'll add a third which seems fairly common in psychology... 1. instinctive knowledge 2. insight without conscious reasoning 3. knowing without knowing how you know The first definition isn't required by my typical use of the word - it may or may not be the case. 'Instinctive' is in any case a poorly defined word these days - it may or may not refer to innate characteristics - so I prefer to avoid it and state 'innate' explicitly if that is what I mean. The third definition will tend to follow from the second (if the insight didn't come from conscious reasoning, you won't know how you know the reasoning behind it). Basically, the second definition is the core of what I intend and nothing you said above contradicts what I claimed. Specifically... >>>no understanding, no semantic modeling. >>>no concepts, no abstractions. ...sounds like "knowing without knowing how you know". Intuitive understanding must be supplied by some algorithm in the brain even when that algorithm is applied subconsciously. I can well believe that (as you say, after long practice) a learned algorithm may be applied entirely unconsciously, in much the same way that (after long practice) drivers don't have to think about how to drive. Besides, just because a long multiplication tends to be consciously worked out by humans, that doesn't mean it can't be an innate ability in either hardware or software. Take your voice recognition example. If the method is Markov chains, then I don't understand it as I don't much remember what Markov chains are - if I was to approach the task I'd probably use a Morlet wavelet to get frequency domain information and feature detection to pick out key features in the frequency domain (and to some degree the original unprocessed waveform) - though I really have no idea how well that would work. However, I don't need any details to make the following observations... The software was not 'aware' of the method being used - the Markov chain stuff was simply programmed in and thus 'innate'. Any 'learning' related to 'parameters' of the method - not the method itself. And the software was not 'aware' of the meaning of those parameters - it simply had the 'innate' ability to collect them in training. This reminds me a lot of human speach recognition - I can't tell you how I know what people are saying to me without going and reading up on it in a cognitive psychology textbook (and even then, the available knowledge is very limited). I am not 'aware' of the method my brain uses, and I am not 'aware' of the meaning of the learned 'parameters' that let me understand a new strong accent after a bit of experience. The precise algorithms for speach recognition used by IBM/Dragons dictation systems and by the brain are probably different, but to me fussing about that is pure anthropocentricity. Maybe one day we'll meet some alien race that uses a very different method of speach recognition to the one used in our brains. In principle, to me, the two systems (human brain and dictation program) have similar claims to being intelligent. Though the human mind wins out in terms of being more successful (more reliable, more flexible, better integrated with other abilities). >> Of course it would be nice if >> computers could invent a rationalisation, the way that human brains >> do. >> >> What? I hear you say... > >You must be mis-hearing (can't be me saying it) because I'm quite aware >of the role of rationalization, and even share your hypothesis that it's >adaptive for reasons connected to modeling human minds. If I have a >halfway decent model of how human minds work, my socialization is thereby >enhanced compared to operating without such a model; models that are >verbalized are easier to play what-if's with, to combine with each other, >etc -- they're generally handier in all of these ways than nonverbal, >"intuitional" models. (You focus on the models OTHER people have of >me and our "need for excuses to give to other people", but I think that >is the weaker half of it; our OWN models of people's minds, in my own >working hypothesis, are the key motivator for rationalizing -- and our >modeling people's minds starts with modeling OUR OWN mind). That might work if people were aware of the rationalisation process - but remember the cut corpus callosum example. When asked to explain 'why?' the person didn't say 'I don't know' or 'I just felt like it' - the logical self-aware explanations if the genuine explanation is not available to the side of the brain doing the explaining. The side of the brain doing the explaining was aware that the person had started moving towards the goal (the coffee) but was not aware of feeling thirsty (unless the experimenters were extremely sloppy in setting up the test conditions) so the explanation of "I felt thirsty" shows a *lack* of self awareness. But giving non-answers such as "I don't know" or "I just felt like it" tends not to be socially acceptable. It creates the appearance of evasiveness. Therefore, giving accurate 'self-aware' answers can be a bad idea in a social context. This is actually particularly pertinent to autism and Asperger syndrome. People with these disorders tend to be too literal, and that can include giving literally true explanations of behaviour. This is directly comparable with this level of automatic rationalisation (the autistic may well not have an automatic rationalisation of behaviour) though of course in most situations it is more about a lack of anticipation of the consequences of what we say and a lack of ability to find a better way to say it (or better thing to say). >> 1. This suggests that the only human intelligence is human >> intelligence. A very anthropocentric viewpoint. > >Of course, by definition of "anthropocentric". And why not? Because 'the type of intelligence humans have' is not, to me, a valid limitation on 'what is intelligence?'. Studying humanity is important. But AI is not (or at least should not be) a study of people - if it aims to provide practical results then it is a study of intelligence. >connection: that "proper study of man" may well be the key reason >that made "runaway" brain development adaptive in our far forebears -- Absolutely - this is IMO almost certainly both why we have a specialised social intelligence and why we have an excess (in terms of our ancestors apparent requirements) of general intelligence. Referring back to the Baldwin effect, an ability to learn social stuff is an essential precursor to it becoming innate. But note we don't need accurate self-awareness to handle this. It could even be counter productive. What we need is the ability to give convincing excuses. >(to the point where >head size became a very serious issue during birth). This is also possibly relevant to autism. Take a look here... http://news.bbc.co.uk/1/hi/health/3067149.stm I don't really agree with the stuff about experience and learning as an explanation in this. I would simply point out that the neurological development of the brain continues after birth (mainly because we hit that size-of-birth-canal issue some hundreds of thousands of years ago), and the processes that build detailed innate neural structures may well be disrupted by rapid brain growth (because evolution has yet to fix the problems that have arisen at the extreme end of the postnatal-brain-growth curve). >area -- what kind of mental approach / modeling is used for purposes >of socialization vs for other purposes. Yes - very much so. >But the point remains that we don't have "innate" mental models >of e.g. the way the mind of a dolphin may work, nor any way to >build such models by effectively extroflecting a mental model of >ourselves as we may do for other humans. Absolutely true. Though it seems to me that people are far to good at empathising with their pets for a claim that human innate mental models are completely distinct from other animals. I figure there is a small core of innate empathy which is quite widespread (certainly among mammals) - and which is 'primitive' enough that even us with Asperger syndrome are quite comfortable with it. And on top of that, there is a learned (but still largely intuitive) sense about pets that comes with familiarity. And as I tried to express elsewhere in different terms, I don't even think 'innate mental models' is fair - perhaps 'innate mental metamodels' would be closer. >> 2. Read some cognitive neuroscience, some social psychology, >> basically whatever you can get your hands on that has cognitive >> leanings (decent textbooks - not just pop psychology) - and > >Done, a little (I clearly don't have quite as much interest in the >issue as you do -- I spread my reading interests very widely). I have the dubious benefit of a long-running 'special interest' (read 'obsession') in this particular field. The practical benefit is supposed to be finding solutions to problems, but it tends not to work that way. Though social psychology obviously turned out to be a real goldmine - actual objective (rather than self-serving) explanations of the things going on in peoples minds in social situations!!! The only problem is that if you apply social psychology principles to understand people, you may predict their behaviour quite well but you absolutely cannot explain your understanding that way - unless, of course, you like being lynched :-( >But that's the least of issues in practical play. I may well be >in the upper tenth of a centile among bridge players in terms of >my ability to do such mental computations at the table -- but that >has very little effect in terms of success in at-the-table results. >My published theoretical results (showing how to _brute-force_ do >the probabilistic estimation of "hand strength", a key issue in >the bidding phase that comes before the actual play) are one thing, >what I achieve at the table quite another:-). Yes, but I never said all learned algorithms are intuitive. This reminds me of something about learning with mnemonics and methods. I don't remember the source, but the idea was basically that the mnemonics, step-by-step instructions etc were there to allow a stage of learning - the stage where you have to think things through. In time, the explanation goes, you don't need the mnemonics and step-by-step methods as handling the problem simply becomes natural. In contexts where this has worked for me, I would say the final intuition goes beyond what the original rules are capable of. ie it isn't just a matter of the steps being held in procedural memory. Presumably heuristics are learned through experience which are much better than the ones verbally stated in the original rules. >And I sure DO know I don't mentally deal a few tens of thousands >of possibilities in a montecarlo sample to apply the method I had >my computer use in the research leading to said published results...;-) How sure are you of that? After all, the brain is a massively parallel machine. Look at what is known about the prefrontal cortex and you may end up with the impression that you are looking at a blackboard-based expert system - a set of specialist 'intelligences' which observe a common working memory and which make additions to that working memory when they spot problems they are able to solve. The ideas going into that working memory seem to be the things that we are consciously aware of. When information has to make round trips to the working memory, I would expect it to be pretty slow - just like most conscious thought processes. But what if something is being handled entirely within a single specialist intelligence unit? That unit may well act rather like a fast 'inner loop' - testing possibilities much quicker than could be done consciously. That doesn't mean it has to be innate - the brain does develop (or at least adapt) specialist structures through learning. My guess is that even then, there would be more dependence on sophisticated heuristics than on brute force searching - but I suspect that there is much more brute force searching going on in peoples minds than they are consciously aware of. -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From glenfant at NOSPAM.bigfoot.com Mon Oct 6 06:24:14 2003 From: glenfant at NOSPAM.bigfoot.com (Gilles Lenfant) Date: Mon, 6 Oct 2003 12:24:14 +0200 Subject: HTML -> text/plain "clever" formatting Message-ID: Hi, I make an app where I need to convert HTML to text in a "clever" way (means it tries to mimic when possible a browser rendering). Actually I spawn with popen2 a "lynx" that makes a perfect job. But I need a 100% pythonic stuff to have my app (Zope product) running on non Unix boxes. Any hint ? Thanks in advance. --Gilles From jaws at ericsson.ca Tue Oct 14 15:46:27 2003 From: jaws at ericsson.ca (JAWS) Date: Tue, 14 Oct 2003 15:46:27 -0400 Subject: Unittest and dynamically created methods Message-ID: <3F8C5293.FF3CC756@ericsson.ca> I get this error message when trying to run a unittest test with a dynamically created test method: Traceback (most recent call last): File "unittest.py", line 215, in __call__ testMethod() TypeError: ?() takes no arguments (1 given) I have no clue as to where the 1 given argument comes from... I am using python 2.2 and here is a copy of the code generating this: #! /bin/env python import unittest, commands, new class Test(unittest.TestCase): done = None def initialization(self): Test.port = 11000 Test.host = 'meadow' def setUp(self): if not Test.done: Test.done = 1 Test.initialization(self) def tearDown(self): pass def testCommandFailure(self): status, output = commands.getstatusoutput('python ../bin/uimClient.py' + ' -p ' + str(Test.port) + ' -h ' + Test.host) self.assertEqual(256, status) def testCommandFailure3(self): status, output = commands.getstatusoutput('python ../bin/uimClient.py' + ' -p ' + str(Test.port) + ' -h ' + Test.host) self.assertEqual(256, status) #====================================BASE TEST================================== if __name__ == '__main__': base = 'def testCommandFailure2(self):\n\t""" Testing test1 method """' +\ '\n\tstatus, output = commands.getstatusoutput("python " +' + \ '" ../bin/uimClient.py -p " + str(Test.port) + " -h " + Test.host)'+\ '\n\tself.assertEqual(status, 256)\n' code = compile(base, 'uimClientFT.py', 'exec') testf = new.function(code, Test.__dict__, 'testCommandFailure2') setattr(Test, 'testCommandFailure2', testf) print Test.__dict__ print type(Test.testCommandFailure2) unittest.main() J-P thankx -------------- next part -------------- An HTML attachment was scrubbed... URL: From ramen at lackingtalent.com Tue Oct 28 19:25:18 2003 From: ramen at lackingtalent.com (Dave Benjamin) Date: Wed, 29 Oct 2003 00:25:18 -0000 Subject: PEP 322: Reverse Iteration (REVISED, please comment) References: <5d83790c.0310281022.6264aa16@posting.google.com> Message-ID: In article <5d83790c.0310281022.6264aa16 at posting.google.com>, Raymond Hettinger wrote: > for elem in inreverse(seqn): > . . . Is there an echo in inhere? +1 +1otherwise... =) -- .:[ dave benjamin (ramenboy) -:- www.ramenfest.com -:- www.3dex.com ]:. : d r i n k i n g l i f e o u t o f t h e c o n t a i n e r : From sandysj at juno.com Thu Oct 30 16:40:30 2003 From: sandysj at juno.com (Jeff Sandys) Date: Thu, 30 Oct 2003 21:40:30 GMT Subject: genealogy and U.S. maps help Message-ID: <3FA1854E.DAAA3E71@juno.com> I'm trying to write a mapping function for genealogy. I want to read a gedcom database and plot an icon at a geographic location based on a user's query. Can you help me find: 1) A python interface to gedcom? (gedcom is a well documented linear file so I can probably do this myself if an interface is not available) 2) An index of U.S. cities and counties with their longitude and latitude? This could be a web site that allows automated queries or a database. (This is the hardest part of the problem since the places in the gedcom database are hand typed by the user. My thought is to try and guess as many locations as possible, then let the user input the rest of the (unknown) locations by clicking on the displayed map (see below) then save this hard earned data for reuse, either in gedcom or as an auxilary dictionary) 3) Graphics of U.S. (country, states and counties) with longitude and latitude relationships suitable for tk or wxpython display? (There are some nice maps available for visio, I'm not sure if they could be used for my purposes) Thanks, Jeff Sandys From mertz at gnosis.cx Thu Oct 16 23:10:52 2003 From: mertz at gnosis.cx (David Mertz) Date: Thu, 16 Oct 2003 23:10:52 -0400 Subject: Python syntax in Lisp and Scheme References: <8CVgb.8$KR3.1846@typhoon.nyu.edu> <20031014050046.GM1454@mapcar.org> <87fzhtlvni.fsf@thalassa.informatimago.com> Message-ID: <821j/kKkXUhA092yn@gnosis.cx> |>And you DO NOT NEED lambdas for HOFs! bokr at oz.net (Bengt Richter) wrote previously: |there could be ways that you need BOTH named and un-named functions. Nope, you do not NEED both. It can be convenient or expressive to have both, but it is certainly not necessary for HOFs or any other computational purpose. And I have yet to see an example where a hypothetical loss of unnamed functions would *significantly* worsen expressiveness. |a function NEEDS a name in order to call itself recursively Nope. That's the point of the Y combinator; you don't need a name to do this (just first class anonymous functions). See, for example: http://en2.wikipedia.org/wiki/Y_combinator |OTOH, if you evaluate a def in a namespace where you don't know what |all the names are, you have a collision risk when you choose a name. |An un-named function eliminates that risk. Sure, that can occassionally be useful in eliminating the small risk. But so can 'grep'. There are always more names out there to use. This particular convenience is VERY small. |Why should the following kind of thing be arbitrarily restricted? | >>> funlist = [ | ... (lambda value: | ... lambda:'My value is %s'%value | ... # imagine freedom to have full suites here | ... )(y) for y in range(5) | ... ] | >>> for fun in funlist: print fun() Obviously, you cannot spell 'funlist' quite that way in Python. But the available spellings are not bad looking IMO. E.g., with no lambda: >>> def ValFactory(x): ... def say_val(x=x): return 'My value is %s' % x ... return say_val ... >>> funlist = map(ValFactory, range(5)) I'm not sure the point here. My spelling happens to be Python's (or at least one option in Python)... and it works fine without any lambdas. If you want, you can even 'del' the name 'ValFactory' after the list is created. Yours, David... -- _/_/_/ THIS MESSAGE WAS BROUGHT TO YOU BY: Postmodern Enterprises _/_/_/ _/_/ ~~~~~~~~~~~~~~~~~~~~[mertz at gnosis.cx]~~~~~~~~~~~~~~~~~~~~~ _/_/ _/_/ The opinions expressed here must be those of my employer... _/_/ _/_/_/_/_/_/_/_/_/_/ Surely you don't think that *I* believe them! _/_/ From mcrider at bigfoot.com Sun Oct 12 18:50:25 2003 From: mcrider at bigfoot.com (2mc) Date: 12 Oct 2003 15:50:25 -0700 Subject: Numerical Python question References: <500a4565.0310112107.22275705@posting.google.com> Message-ID: <500a4565.0310121450.6453f6c3@posting.google.com> Carl Banks wrote in message news:... > Let's say D[i] is the daily high at the end of day i, and N is the > total number of days in the array. To calculate 10-day averages, you > can add ten slices offset by one, then divide the sum by 10: > > A = zeros(N-9,Float) > for j in range(10): > A += D[j:N-9+j] > A /= 10.0 > > Bam, that's it. Instead of looping over tens of thousands of slices > of ten, you're now looping over ten slices of tens of thousands. > > This works because, when you add ten slices offset by one, the result > is that each item contains the sum of ten consecutive numbers from the > original array. Thank you very much for this code. It took me several looks at it, before I understood it. I'm still getting the cobwebs out of my brain over the way I used to do things. I have 2 questions. This code snippet runs at "array speed," right? In other words, it will run much faster than if I tried to duplicate this with lists, correct? Also, can you give me an idea of how you would accomplish the 10 day standard deviation of prices instead of the 10 day average? It would really help me get a handle on this. Thank you. Matt From jzgoda at gazeta.usun.pl Sun Oct 19 13:58:03 2003 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Sun, 19 Oct 2003 17:58:03 +0000 (UTC) Subject: Where is the unix manual ? References: <3f92cd05$0$8763$cc9e4d1f@news.dial.pipex.com> Message-ID: Joe Green pisze: > import socket > print socket.socket().recv.__doc__ > > it tells me to look in the Unix manual. What is it on about, and is this > manual online? Yes, just type "man 2 socket" or "man 2 recv" in your shell. #v+ SOCKET(2) Linux Programmer's Manual SOCKET(2) NAME socket - create an endpoint for communication SYNOPSIS #include #include int socket(int domain, int type, int protocol); DESCRIPTION Socket creates an endpoint for communication and returns a descriptor. #v- And so on... -- Jarek Zgoda Registered Linux User #-1 http://www.zgoda.biz/ JID:jarek at jabberpl.org http://zgoda.jogger.pl/ From goodger at python.org Tue Oct 21 19:06:33 2003 From: goodger at python.org (David Goodger) Date: Tue, 21 Oct 2003 19:06:33 -0400 Subject: Unittest - How do I code lots of simple tests In-Reply-To: References: <3F95A5DC.51828269@engcorp.com> Message-ID: <3F95BBF9.3060506@python.org> Paul Moore wrote: >>> Can anyone suggest a more reasonable way of running this sort of >>> table-driven test via unittest? Take a look at Docutils' test/DocutilsTestSupport.py for ideas. The CustomTestSuite and CustomTestCase classes provide support for named data-driven tests. Most of Docutils' tests are data-driven. Ian Bicking wrote: > unittest is not written with subclassing in mind, except for the > limited subclassing that is documented. (And it uses > double-underscore variables, like it's just *trying* to piss me off! > Double-underscore variables are so arrogant and patronizing. All very true. Double-underscores ought to be banned from the standard library. They inevitably get in the way because no matter how well a class is written, somebody is going to want to subclass it in a way the original author never considered. -- David Goodger http://starship.python.net/~goodger For hire: http://starship.python.net/~goodger/cv Docutils: http://docutils.sourceforge.net/ (includes reStructuredText: http://docutils.sf.net/rst.html) From aleax at aleax.it Wed Oct 1 06:11:58 2003 From: aleax at aleax.it (Alex Martelli) Date: Wed, 01 Oct 2003 10:11:58 GMT Subject: extending methods ? References: Message-ID: Arnd Baecker wrote: > Hi, > > the summary of my question is: > is there a way to append commands to a method inherited from > another class? The canonical way to achieve that is to override the method, and, within the override, call up to the superclass's implementation. > More verbose: Assume the following situation that I have > a class class_A with several methods. > In each of these methods quite a few computations take place > and several variables are defined. Ah, no way, then -- local variables of a method (just like any other function) are totally internal to that method, and there is absolutely no reasonable way to access them from the outside. > However, with several variables and several methods > the code will not look nice. A matter of opinion. I find it much nicer to know that a local variable is local, and an instance variable is not. > (also efficiency is a bit of concern - presumably it shouldn't - Right, it shouldn't. Local variables are fast BECAUSE they are local. If they were non-local -- as you require, in order to work with them from outside the defining method -- then they wouldn't be fast. > to me here as in my application the methods > are used to plot dots, circles, triangles etc. > so that speed is really important) I strongly doubt that the loss of speed due to making some needed variable non-local is going to be measurable. Taking your example...: [alex at lancelot python2.3]$ python timeit.py \ > -s 'class A:' \ > -s ' def method1(self, x): y = 5 * x + 1' \ > -s ' def method2(self, x): self.y = 5 * x + 1' \ > -s 'a=A()' \ > 'a.method1(23)' 1000000 loops, best of 3: 1.47 usec per loop and the same with method2 instead: 1.66 usec per loop. What makes you think that a "slow-down" of 190 nanoseconds, i.e. about 13% on this method call, is gonna be SO crucial? And if you ARE working in an environment where every single nanosecond matter, then what about...: [alex at lancelot python2.3]$ python timeit.py \ > -s 'class A:' \ > -s ' def method1(self, x): y = 5 * x + 1' \ > -s ' def method2(self, x): self.y = 5 * x + 1' \ > -s 'a=A()' \ - -s 'meth=a.method2' \ > 'meth(23)' 1000000 loops, best of 3: 1.25 usec per loop See? Extracting the bound method once and for all saves you a whopping *410* nanoseconds per call, compensating the 190 "lost" by making instance variables where you need them *and then some*. In other words, there are ways and means to squeeze nanoseconds out of some Python bottleneck that do not necessarily require using local variables where you need instance or other non-local ones! > So is there a way to extend methods in the above sense > or is there a better (more pythonic ? ;-) approach to what I want? There is no pythonic way to treat local variables as non-local. (There MAY be horrible bytecode hacks exploiting hooks that are meant for debugging only -- but THOSE *WILL* slow you down SERIOUSLY...). Alex From mloomington at yahoo.ca Mon Oct 27 18:27:42 2003 From: mloomington at yahoo.ca (Michael Loomington) Date: Mon, 27 Oct 2003 18:27:42 -0500 Subject: GMT is off Message-ID: GMT time is off by like 10 minutes when I call strftime("%I:%S", gmtime()) How do you correct it? My windows time is set correctly. Also can you make it report time in the EST time zone? From keflimarcusx at aol.comNOSPAM Mon Oct 27 02:04:57 2003 From: keflimarcusx at aol.comNOSPAM (KefX) Date: 27 Oct 2003 07:04:57 GMT Subject: Python is Considered Harmful References: Message-ID: <20031027020457.27688.00000198@mb-m04.aol.com> Hmm...I think the Haskell syntax looks like crap. ;) Seriously, I can't even guess how it works without some kind of manual. And of course the Python result is only 'surprising' if you don't know the rules of name binding. I'm not bashing Haskell, of course. I'm just saying I already don't like it... - Kef From skip at pobox.com Thu Oct 30 16:45:06 2003 From: skip at pobox.com (Skip Montanaro) Date: Thu, 30 Oct 2003 15:45:06 -0600 Subject: Reverting (key, value) pairs in a dictionary In-Reply-To: <3FA18231.2080806@bu.edu> References: <5d83790c.0310281022.6264aa16@posting.google.com> <3f9ec63f$1@brateggebdc5.br-automation.co.at> <3f9f9d2a$1@brateggebdc5.br-automation.co.at> <3FA1795B.5000601@bu.edu> <3FA18231.2080806@bu.edu> Message-ID: <16289.34402.128350.461168@montanaro.dyndns.org> Shu-Hsien> How do you turn a dictionary of : Shu-Hsien> into : , when Shu-Hsien> there is no duplicate values? Shu-Hsien> For instance, I have a dictionary kk: Shu-Hsien> kk = {'abc': ['B', 'C', 'D', 'E'], 'def':['G', 'H']} Shu-Hsien> and I want a new dictionary newkk which looks like: Shu-Hsien> newkk = {'B':'abc', 'C':'abc', 'D':'abc', 'E':'abc', 'G':'def', 'H':'def'} How about: >>> newkk = {} >>> for key in kk: ... val = kk[key] ... newkk.update(dict(zip(val, [key]*len(val)))) ... >>> newkk {'C': 'abc', 'B': 'abc', 'E': 'abc', 'D': 'abc', 'G': 'def', 'H': 'def'} Skip From ville.spammehardvainio at spamtut.fi Mon Oct 20 05:29:39 2003 From: ville.spammehardvainio at spamtut.fi (Ville Vainio) Date: 20 Oct 2003 12:29:39 +0300 Subject: Why don't people like lisp? References: <3f9302d7.170372828@news.eircom.net> <87ismkcp5d.fsf@bird.agharta.de> Message-ID: Edi Weitz writes: > Yeah, sure. And 95% of all computer users use Windows so it must be > the best OS. You know the "50 million flies" saying? Yep, but when exposed to a clearly superior language, one might assume that at least a part of the students would get the clue and keep on using it after the course. You can only go so far with "all college students are morons". People diss Python if they haven't tried it, but convert soon after giving it a spin; people diss Lisp even after trying it. Perhaps they are morons, flies, whatever. Python also welcomes them with open arms. When all is said and done, being 31337 is not that important. However, Lisp (Emacs Lisp) *is* one of the three languages I actually can find use for. The other two are C++ (day job) and Python. -- Ville Vainio http://www.students.tut.fi/~vainio24 From costanza at web.de Thu Oct 9 20:46:00 2003 From: costanza at web.de (Pascal Costanza) Date: Fri, 10 Oct 2003 02:46:00 +0200 Subject: Python syntax in Lisp and Scheme In-Reply-To: <36w65iyjmyp.fsf@chagall.ti.uni-mannheim.de> References: <8CVgb.8$KR3.1846@typhoon.nyu.edu> <36w65iyjmyp.fsf@chagall.ti.uni-mannheim.de> Message-ID: Matthias wrote: > Why the smiley? Many hours of discussions could be spared if there > were real, scientific, solid studies on the benefit of certain > language features or languages in certain domains or for certain types > of programmers. This presumes that language features can be judged in isolation. I think it's rather more likely that good programming languages are holistic systems, in the sense that the whole language is more than the sum of its features. Pascal From adalke at mindspring.com Wed Oct 22 23:39:46 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Thu, 23 Oct 2003 03:39:46 GMT Subject: Why don't people like lisp? References: <3f9302d7.170372828@news.eircom.net> Message-ID: <64Ilb.1525$I04.1503@newsread4.news.pas.earthlink.net> Kaz Kylheku: > Ah, but in Lisp, this is commonly done at *compile* time. Compile vs. runtime is an implementation issue. Doesn't change expressive power, only performance. Type inferencing suggests that there are other ways to get speed-ups from dynamic languages. > Moreover, > two or more domain-specific languages can be mixed together, nested in > the same lexical scope, even if they were developed in complete > isolation by different programmers. We have decidedly different definitions of what a "domain-specific language" means. To you it means the semantics expressed as an s-exp. To me it means the syntax is also domain specific. Eg, Python is a domain specific language where the domain is "languages where people complain about scope defined by whitespace." ;) Yes, one can support Python in Lisp as a reader macro -- but it isn't done because Lispers would just write the Python out as an S-exp. But then it wouldn't be Python, because the domain language *includes*domain*syntax*. In other words, writing the domain language as an S-exp is a short cut to make it easier on the programmer, and not on the domain specialist. Unless the domain is programming. And you know, very few of the examples of writing a domain specific language in Lisp have been for tasks other than programming. > Do people write any significant amount of code in the > Python parse tree syntax? No. First, it isn't handled as a syntax, it's handled as as operations on a tree data structure. Second -- and this point has been made several times -- that style of programming isn't often needed, so there of course isn't a "significant amount." > Can you use that syntax in a Python source file and have > it processed together with normal code? Did you look at my example doing just that? I built an AST for Python and converted it into a normal function. > What is Python's equivalent to the backquote syntax, if I > want to put some variant pieces into a parse tree template? There isn't. But then there isn't need. The question isn't "how do I do this construct that I expect in Lisp?" it's "how do I solve this problem?" There are other ways to solve that problem than creating a "parse tree template" and to date there have been few cases where the alternatives were significantly worse -- even in the case of translating a domain language into local syntax, which is a Lisp specialty, it's only about twice as long for Python as for Lisp and definitely not "impossible" like you claimed. Python is definitely worse for doing research in new programming styles, but then again that's a small part of what most programmers need, and an even smaller part of what most non-professional programmers need. (Eg, my science work, from a computer science viewpoint, is dead boring.) There's very little evidence that Lisp is significantly better than Python (or vice versa) for solving most problems. It's close enough that it's a judgement call to decide which is more appropriate. But that's a Pythonic answer, which acknowledges that various languages are better for a given domain and that it's relatively easy to use C/Java bindings, shared memory, sockets, etc to make them work together, and not a Lispish answer, which insists that Lisps are the best and only languages people should consider. (Broad brush, I know.) Andrew dalke at dalkescientific.com From eppstein at ics.uci.edu Tue Oct 21 14:29:51 2003 From: eppstein at ics.uci.edu (David Eppstein) Date: Tue, 21 Oct 2003 11:29:51 -0700 Subject: writing code over several lines References: <62e9c66e.0310170556.328072e8@posting.google.com> <3F9531F6.3D1DD233@engcorp.com> <3F9556A3.92F1106C@engcorp.com> <7xd6cqinpn.fsf@ruckus.brouhaha.com> <3F9558D9.E7F720A5@engcorp.com> <7x1xt6bksk.fsf@ruckus.brouhaha.com> <3F9576D2.5BF5AF45@engcorp.com> Message-ID: In article <3F9576D2.5BF5AF45 at engcorp.com>, Peter Hansen wrote: [ re lists allocating extra space to achieve constant amortized time per append operation ] > Is there a published algorithm behind this, or is it just some magic > of the Timbot's that would be found only in the source? The details are in the source, but the same algorithm can be found e.g. in Cormen et al, "Introduction to Algorithms" (2nd ed.), section 17.4 -- David Eppstein http://www.ics.uci.edu/~eppstein/ Univ. of California, Irvine, School of Information & Computer Science From duncan at NOSPAMrcp.co.uk Tue Oct 14 04:46:06 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Tue, 14 Oct 2003 08:46:06 +0000 (UTC) Subject: String search vs regexp search References: <84fc4588.0310120655.ea95af6@posting.google.com> <698f09f8.0310132019.4bd918b2@posting.google.com> Message-ID: Duncan Booth wrote in news:Xns9414603182031duncanrcpcouk at 127.0.0.1: >> Both regular expression searching and string.find will do searching >> one character at a time; given that, it seems impossible to me that >> the hand-coded-in-C "naive" string.find could be slower than the >> machine-translated-coded-in-Python regular expression search. >> Compilation time only serves to further increase string.find's >> advantage. >> > I may have misremembered, but I thought there was a thread discussing > this a little while back which claimed that the regular expression > library looked for constant strings at the start of the regex, and if > it found one used Boyer-Moore to do the search. If it does, then > regular expressions searching for a constant string certainly ought to > be much faster than a plain string.find (as the length of the searched > string tends towards infinity). > > If it doesn't, then it should. Ok, found the code. Regular expression searches do indeed use a form of Boyer-Moore, but not if you are ignoring case. So by specifying re.IGNORECASE the OP got a double hit, not only does the code have to do case insensitive comparisons, but it also has to crawl along looking at every character in the search string instead of skipping most of them. -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From dsilva at ccs.neu.edu Mon Oct 6 21:53:30 2003 From: dsilva at ccs.neu.edu (Daniel P. M. Silva) Date: Mon, 06 Oct 2003 21:53:30 -0400 Subject: Python syntax in Lisp and Scheme References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> <92c59a2c.0310031345.57d20631@posting.google.com> Message-ID: Erann Gat wrote: > [...] But the point is that in pre-yield > Python you were stuck until the langauge designers got around to adding > it. > > I'll try to come up with a more convincing short example if I find some > free time today. > Haven't some people implemented an entire class system as one huge macro? - Daniel From bokr at oz.net Sat Oct 18 00:32:41 2003 From: bokr at oz.net (Bengt Richter) Date: 18 Oct 2003 04:32:41 GMT Subject: Confusing performance results for prime References: Message-ID: On Fri, 17 Oct 2003 15:33:24 -0500, "Greg Brunet" wrote: >In doing some testing of different but simple algorithms for getting a >list of prime numbers, I ended up getting some results that seem a bit >contradictory. Given the following test program (testPrimes.py) with >two algorithms that both check for primes by testing only odd numbers >using factors up to the square root of the value, where Primes1 is based >on all of the existing primes so far, and Primes2 is based on all odd >numbers, I would expect that, as the number of primes we check gets >larger, that Primes1 should get more & more efficient (since it should >be performing less tests for each number). However the ratio seems to >be relatively consistent. Another thing that is interesting is that >once I tested up to n=200000, I got an exception in Primes2. I added >the long typecast in the 'limit=' statement for both versions and the >resulting improvements were strange: Primes1 runs 10-20% SLOWER, and >Primes2 runs about 50% FASTER! > >I am not looking to come up with the most optimized solution to prime >numbers here. Primes1 is faster than Primes2 as I would expect and it >is clear, relatively elegant, and sufficient for me. However, I can't >figure out why the ratio doesn't improve with size, and the strange >results of the long typecast, and I would like to be able to understand >what is causing their behavior. Any ideas? Thanks, Without looking at the implementation code, I could only guess, but you are using range instead of xrange (but maybe range is now optimized not to build and actual list in iterator context?). Also, limit as a float or long being passed to range must cause a little hiccup. Perhaps an iter optimization is being interfered with? If range is not optimized, then you must be taking a hit from building throwaway lists with range instead of using xrange, so your inner loop in Primes2 would have a bunch of overhead. Also, you don't need floating point or long for quite some time, and x*x > y will be faster than x > math.sqrt(y) and avoid the float altogether and long to boot, unless you are generating primes larger than maxint. If you want to conserve space for an all-int primes list, you can use primes = array.array('l',[2]) instead of primes = [2] to start. Just doing that apparently gives about the same speed, but I imagine pre-allocating array space could make it faster, though you'd have to change the append and iteration logic. Hard to say without testing. > >-- >Greg > Sorry, I can't resist suggesting a slight speed improvement ;-) def Primes3(prime_range_top): primes = [2] for prime_candidate in xrange(3,prime_range_top,2): for p in primes: if prime_candidate%p==0: break if p*p>prime_candidate: primes.append(prime_candidate) break else: primes.append(prime_candidate) return primes And maybe running the bunch with if __name__ == "__main__": n=100000 times = [] for pfun in (Primes1, Primes2, Primes3): tb = time.time() l1 = pfun(n) dt = time.time() - tb times.append(dt) print '%s: %s primes up to %s in %5.3f secs' % ( pfun.__name__, len(l1), n, dt) fastest = min(times) print '\nTimes relative to the fastest:' for i, pfun in enumerate((Primes1, Primes2, Primes3)): print '%s: %5.3f'%(pfun.__name__, times[i]/fastest) Which gave me (on older machine ;-) Primes1: 9592 primes up to 100000 in 2.984 secs Primes2: 9592 primes up to 100000 in 5.608 secs Primes3: 9592 primes up to 100000 in 2.444 secs Times relative to the fastest: Primes1: 1.221 Primes2: 2.295 Primes3: 1.000 Regards, Bengt Richter From skip at pobox.com Fri Oct 3 13:59:04 2003 From: skip at pobox.com (Skip Montanaro) Date: Fri, 3 Oct 2003 12:59:04 -0500 Subject: 2.3.2 Installation Problems In-Reply-To: <3f7db25b$1@news.starhub.net.sg> References: <3f7db25b$1@news.starhub.net.sg> Message-ID: <16253.47336.403927.442251@montanaro.dyndns.org> >> Just downloaded the 2.3.2 bzip2 package and trying to install. When I >> run 'make', I get the following error: >> .... >> .... >> running build >> running build_ext >> make: *** [sharedmods] Error 139 Do you have any more output than that? I presume the Python executable itself built okay? If so, does "./python Lib/test/regrtest.py" reveal any problems besides lots of skipped tests because no extension modules have been built? Does building from the .tgz file give you the same problem? There should be no functional difference between the two, but since you mentioned it, I thought I would check to be sure you weren't somehow attributing the problem to the bzip2 package. Skip From floyd at barrow.com Wed Oct 22 00:52:36 2003 From: floyd at barrow.com (Floyd Davidson) Date: Tue, 21 Oct 2003 20:52:36 -0800 Subject: [OT] Inuit? Eskimo? References: <20031020163642.GA5539@nl.linux.org> <4vre61-ku2.ln1@beastie.ix.netcom.com> Message-ID: <87vfqhri0b.fld@barrow.com> Lulu of the Lotus-Eaters wrote: >anton at vredegoor.doge.nl (Anton Vredegoor) wrote previously: >|> "Native American" is to "American Indian" as ______ is to "Eskimo". >|>Anyone in the .ca domain care to educate the .us folks? >|To my (eu-domain) eye the use of "American Indian" instead of "Indian >|American" is strange. > >Incidentally, in Canada, "First Nations" is generally used rather than >"Native American." But in either case, Native Americans themselves are >quite split--as would be any group of people when it comes to >politics--over best names. In a lot of cases, when referring to a >particular person, naming her particular nation and tribe (Navaho, Oglala >Sioux, etc.) is better. But lots of NAs themselves prefer "Indian" as a >term. The term "Native American" is a coined word that the US Federal government came up with to reference *all* indigenous people in the US and its territories. Hence it includes American Indians, Eskimos, Aleuts, Hawaiians, Puerto Ricans, Guamanians, American Somoans and probably somebody I've forgotten to name. It obviously can't mean anyone who is Canadian, by definition. >Probably an influence on the names is that Canada has a much larger >percentage of Indian immigrants (i.e. from India) than does the US--or >their families of 2nd or 3rd generation. The name "Indian" quite apart >from coming from a 500 year old mistake, refers to a quite different >large group of Canadians. Not that Indian-Americans are a rarity in the >USA either, but we USAians are really quite thick in the head, as a >rule. > >Yours, Lulu... Another oddity with naming conventions came up about a dozen years ago. If my memory serves, it was a meeting in regard to education, and involved the Bureau of Indian Affairs or whatever, but it was a national symposium of Native people... and when they had to choose a set of terms, they ran into a problem. Seems that there was obstinate opposition to the term "native" by many Lower-48 Indian groups, yet Alaskans absolutely insisted that the *only* way to reference all of the people indigenous to Alaska was to use the term Native. Hence, they adopted the phrase "American Indian and Alaska Native peoples". You'll find that phrase has been widely adopted by the US Federal government when it refers specifically to that group of people, as opposed to the wider significance of the term Native American. (Boy, any of those Lower-48 folks who don't think there's any difference between Canadians and USAians, really ought to try talking about this subject... it'll cure 'em of such a notion!) -- Floyd L. Davidson Ukpeagvik (Barrow, Alaska) floyd at barrow.com From prunesquallor at comcast.net Sat Oct 11 01:59:06 2003 From: prunesquallor at comcast.net (prunesquallor at comcast.net) Date: Sat, 11 Oct 2003 05:59:06 GMT Subject: Python syntax in Lisp and Scheme References: <3cea3gqq.fsf@comcast.net> Message-ID: Alexander Schmolck writes: > [narrowing down to c.l.l and c.l.p] > prunesquallor at comcast.net writes: > >> > Significantly, AFAICT you can easily do this unambiguously and *locally*, >> > for example your editor can trivially perform this operation on cutting a >> > piece of python code and its inverse on pasting (so that you only >> > cut-and-paste the 'local' indentation). Prima facie I don't see how you >> > loose any fine control. >> >> Only if your cut boundaries are at the same lexical level. If you cut >> across boundaries, it is no longer clear what should happen at the paste. > > The only unclarity would arise from dedents of more than one level on the > corner of your cut region, I think. Suppose I cut just one arm of a conditional. When I paste, it is unclear whether I intend for the code after the paste to be part of that arm, part of the else, or simply part of the same block. >> The fact that the information is replicated, and that there is nothing >> but programmer discipline keeping it consistent is a source of errors. > > Sure there is. Your editor and immediate visual feedback (no need to remember > to reindent after making the semantic changes). `immediate visual feedback' = programmer discipline Laxness at this point is a source of errors. >> > I don't understand why this is any different to e.g. ')))))' in Lisp. The >> > closing ')' for DEFUN just looks the same as that for IF. >> >> That is because the parenthesis *only* encode the grouping information, >> they do not do double duty and encode what they are grouping. >> The key here is to realize that the words `DEFUN' and the `IF' themselves >> look very different. > > Well, I'm evidently still not getting it, because my reply would be "and so do > 'def ...:' and 'if ...:' in python" (and you also can't tell whether the 8 > spaces on the left margin come from a 'def' and and an enclosed 'if' or vice > versa). I'm not sure I can explain any better, I *think* perhaps some of the other Lispers might get what I'm saying here. >> >> Yet the visual representation is not only identical between all of these, it >> >> cannot even be displayed. >> > >> > I don't understand what you mean. Could you maybe give a concrete example of >> > the information that can't be displayed? >> >> Sure. Here are five parens ))))) How much whitespace is there here: > > 10 spaces (which BTW I counted in emacs in just the same way that I'd count a > similar number of parens) -- but what has counting random trailing whitespace > got to do with anything? It is simply an illustration that there is no obvious glyph associated with whitespace, and you wanted a concrete example of something that can't be displayed. >> > Still, I'm sure you're familiar with the following quote (with which I most >> > heartily agree): >> > >> > "[P]rograms must be written for people to read, and only incidentally for >> > machines to execute." >> > >> > People can't "read" '))))))))'. >> >> Funny, the people you just quoted would disagree with you about parenthesis. >> I expect that they would disagree with you about whitespace as well. > > Why, do they know someone with a paren-counting brain-implant? If so every > lisper should get one -- no more carpal tunnel syndrome from frantic C-M-\ > pressing or alphabet wastage due to scheme-style 'aliasing' of '[...]' to > '(...)'. > > Seriously, I really fail to see see what the source of disagreement with the > above statement could be. I cannot read Abelson and Sussman's minds, but neither of them are ignorant of the vast variety of computer languages in the world. Nonetheless, given the opportunity to choose any of them for exposition, they have chosen lisp. Sussman went so far as to introduce lisp syntax into his book on classical mechanics. Apparently he felt that not only *could* people read ')))))))', but that it was often *clearer* than the traditional notation. > If I gave you a piece of lisp code jotted down on paper that (as those > hypothetical examples usually are) for some reason was of vital importance and > that on typing it in revealed a mismatch between the indentation and the > parenthesation in a key section of the code -- which interpretation would you > hedge your bets on in the absence of other indicators; the one suggested by > the indentation or the 9 trailing parens? Obviously the indentation. But I'd notice the mismatch. If I gave you a piece of python code jotted down on paper that (as these hypothetical examples usually are) for some reason was of vital importance but I accidentally misplaced the indentation -- how would you know? From jjl at pobox.com Thu Oct 16 17:42:16 2003 From: jjl at pobox.com (John J. Lee) Date: 16 Oct 2003 22:42:16 +0100 Subject: Speaking Python References: Message-ID: <87smlsrhaf.fsf@pobox.com> Yvonne Thomson writes: [...] > Wow, what a longwinded message to explain something farely basic. sorry > about that, . Don't worry, you're not in the same *league* as Alex there. :-) John From CousinStanley at hotmail.com Wed Oct 22 12:10:22 2003 From: CousinStanley at hotmail.com (Cousin Stanley) Date: Wed, 22 Oct 2003 09:10:22 -0700 Subject: Trailing comma (was: Re: structure in Python) References: Message-ID: | Depending on the style guide the teacher is using, | even "Uncle Scrooge took Huey, Duey, and Louie to the park" | .... "Uncle Scrooge took Huey, Duey and Louie to the park" | .... Dennis .... Thanks for the reply .... This style difference also occurred to me after I posted the example .... I think I remember it being taught that it is a grammatical option and correct in either case .... I always include the _final_ comma in these cases myself, as it usually seems harder to read and potentially confusing without it .... -- Cousin Stanley Human Being Phoenix, Arizona From tocino at wanadoo.es Fri Oct 24 14:40:00 2003 From: tocino at wanadoo.es (David) Date: Fri, 24 Oct 2003 20:40:00 +0200 Subject: wish list for python References: <3F98AEDF.4020505@rdrop.com> Message-ID: <20031024204000.0e9751f5.tocino@wanadoo.es> Con fecha Fri, 24 Oct 2003 06:47:27 +0200 Jim Newton escribi?: > does anyone know where i can find the current wish-list or to-do list > for futer python releases? > > Does anyone know if there is a play to allow non-evaluatable > statements to return values? I'm only a week to this language so > far but it seems very strange to me (coming from a list background) > that i cannot somehow say > x = if a: > then b > else c > > or > > x = for i in some-sequence: > blah blah blah. > > > and what about something like the following? > > x = cond: > a > 1: > 0 > a > 10: > 1 > a > 100: > 2 > True: > -1 > Try Ruby! ;-) From paul.moore at atosorigin.com Wed Oct 22 07:44:26 2003 From: paul.moore at atosorigin.com (Paul Moore) Date: 22 Oct 2003 04:44:26 -0700 Subject: Unittest - How do I code lots of simple tests References: <3F95A5DC.51828269@engcorp.com> Message-ID: <182bcf76.0310220344.1853dab@posting.google.com> David Goodger wrote in message news:... > Paul Moore wrote: > >>> Can anyone suggest a more reasonable way of running this sort of > >>> table-driven test via unittest? > > Take a look at Docutils' test/DocutilsTestSupport.py for ideas. The > CustomTestSuite and CustomTestCase classes provide support for named > data-driven tests. Most of Docutils' tests are data-driven. Urk. That's hairy stuff. Thanks for the pointer, I'll do some research. But I still think that this sort of thing should be easy :-( Paul. From http Fri Oct 17 17:34:35 2003 From: http (Paul Rubin) Date: 17 Oct 2003 14:34:35 -0700 Subject: assignment expression peeve References: <7x1xtfkuky.fsf@ruckus.brouhaha.com> <6q6jb.10882$fv4.3354@nwrdny02.gnilink.net> <7xk77676bt.fsf@ruckus.brouhaha.com> <7xptgy9qr7.fsf@ruckus.brouhaha.com> <7x8ynm6rtu.fsf@ruckus.brouhaha.com> <%iljb.19300$0I6.15247@nwrdny03.gnilink.net> <7x7k366mwe.fsf@ruckus.brouhaha.com> <1066284732.96348@yasure> Message-ID: <7x3cdrk0pg.fsf@ruckus.brouhaha.com> "Donn Cave" writes: > But when you can say > > if g := match(a, b): > > then I suspect you will also be able to say things like - > > if not (dv := start() and f := nfile(dv) > and ((t := f.find("--") > 0 and fx = f[:t]) or (fx = f))): > print "Well, bless me!" Well, yes, you can write messy code in any language. There will always be some need for tastefulness in programming. Language designers can't make that need go away. From jzgoda at gazeta.usun.pl Sun Oct 19 11:20:30 2003 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Sun, 19 Oct 2003 15:20:30 +0000 (UTC) Subject: Python from Wise Guy's Viewpoint References: <3F928FCE.5C57BB6A@engcorp.com> Message-ID: Peter Hansen pisze: > Warning! Troll alert! I missed the three newsgroup cross-post > the first time, so I thought this might be a semi-serious question. That's why I set FUT to this group. -- Jarek Zgoda Registered Linux User #-1 http://www.zgoda.biz/ JID:jarek at jabberpl.org http://zgoda.jogger.pl/ From indigomoon at bonbon.net Wed Oct 1 13:00:31 2003 From: indigomoon at bonbon.net (Indigo Moon Man) Date: Wed, 1 Oct 2003 11:00:31 -0600 Subject: py2exe dll file References: <33803989.0310010616.4330d435@posting.google.com> Message-ID: Miki Tebeka spake thusly: > >> The .dll file that py2exe creates to go with the program is huge even >> for a small program. Is there any way to possibly optomize the .dll >> file to make it smaller? > Which dll? Depending on your program it might have several dlls in the > dist/prog directory. > Oh, the one I have compiled only produced one (python23.dll) so I didn't know that. > If size does matter you might want to try upx > (http://upx.sourceforge.net/). With --best it reduced python23.dll > from 952k to 386k and my proram seems to work. > Cool, thanks for the info! -- Audio Bible Online: http://www.audio-bible.com/ From mspight at dnai.com Fri Oct 24 13:48:50 2003 From: mspight at dnai.com (Marshall Spight) Date: Fri, 24 Oct 2003 17:48:50 GMT Subject: Static typing References: <_8Ekb.7543$pT1.318@twister.nyc.rr.com> <90fk61-j71.ln1@ID-7776.user.dfncis.de> Message-ID: <5Cdmb.18630$Fm2.9443@attbi_s04> "Pascal Costanza" wrote in message news:bnbds3$uui$1 at f1node01.rhrz.uni-bonn.de... > > Expressive power is not Turing equivalence. Agreed. So, does anyone have a formal definition of "expressive power?" Metrics? Examples? Theoretical foundations? It seems like a hard concept to pin down. "Make it possible to write programs that contain as few characters as possible" strikes me as a really bad definition; it suggests that bzip2-encoded C++ would be really expressive. Marshall From fumanchu at amor.org Thu Oct 30 14:39:32 2003 From: fumanchu at amor.org (Robert Brewer) Date: Thu, 30 Oct 2003 11:39:32 -0800 Subject: Removing Unicode from Python? Message-ID: > In general I love Python for text manipulation but at our > company we > have the need to manipulate large text values stored in > either a SQL > Server database or text files. This data is stored in a > "text" field > type and is definitely not unicode though it is often very strange > text since it is either OCR or some kinda electronic file > extraction. Issue #1: You need to find out what encoding is being used. You cannot hope to gloss over this fact, and ignore Unicode altogether and just "get on with life". Read http://www.joelonsoftware.com/articles/Unicode.html for a recent, well-written plea on this issue. You should probably not finish reading my post until you've read that, or my comments will seem needlessly biting. > Unfortunately when it is retrieved into a string type in > python it is invariably a unicode type string. Issue #2: What method is being used to "retrieve into a string type"? Show some code. > The best I can do is try and encode > it to 'latin-1' but that will often throw and error if I use the > ignore parameter then it will wack my data with a bunch of "?". Again, you need to find out what encoding the text is in before the "retrieval". MSSQL2k, for example, can have a different code page in use for each collation. You need to find out what that is for your data. Then, when the unicode() coercion is performed, you will be able to correctly inform that factory function what you're sending it. However you find out, for heaven's sake, don't GUESS. Issue #3: Your data is probably being "wacked" on your display, not in and of itself. In other words, the characters themselves are probably correct, functioning unicode; however, your display (which is.. what? web page? DOS prompt?) is unable to display unicode using the default encoding. It may be possible for you to find out which encodings your display supports and properly encode() the data before it is sent to the display device. > I am just not understanding why python is thinking stuff is > unicode and why > it is failing on conversion. There is no way that a byte > can not be between 0 and 255 right? Right. Unless it's actually two bytes, like UCS-2 (which IIRC SQL Server uses extensively), and your database or other application is trying to insulate the poor little overworked programmer (you) from that fact. Or UTF-8, which can take up to six bytes per glyph. Etcetera. > This problem can be so haunting that I will > start to wish I had coded the solution in VB where at > least a string is a string is a string. Or at least, a string is something which VB isn't going to elaborate on, because some poor overworked programmers don't really *need* to understand Unicode--we'll "help them out" by not mentioning it, and hope it doesn't come back to bite them. > Is there a way to modify Python so that all > strings will always be single byte strings since we have > no need for Unicode support? unicode = str? >:) Just kidding. Issue #4: You have a need for Unicode support. You just don't know it yet. ;) > Any solutions or suggestions to my biggest Python > annoyance would be greatly appreciated. >From my point of view, it seems like a Unicode (and those who would "protect" you from it) annoyance, not a Python one. "There's a set of rules that anything that was in the world when you were born is normal and natural. Anything invented between when you were 15 and 35 is new and revolutionary and exciting, and you'll probably get a career in it. Anything in- vented after you're 35 is against the natural order of things." Douglas Adams Robert Brewer MIS Amor Ministries fumanchu at amor.org From jegenye2001 at fw.hu Thu Oct 16 14:22:23 2003 From: jegenye2001 at fw.hu (Jegenye 2001 Bt) Date: Thu, 16 Oct 2003 20:22:23 +0200 Subject: Can we use emPy, ReST, and/or YAML for report generation References: Message-ID: It's not quite clear what report you mean.. If you want to make PDFs with Python then reportlab is fine. The steep learning curve could be flattened a bit by using their RXML solution, i.e. an XML layout. This does cost money. Also, one can generate nice reports with LaTeX and the learning curve is not that steep. Postscript (latex -> dvi -> ps) and HTML (latex2html or ht) come easily. PS can be converted into PDF with ps2pdf but you can make PDFs with pdflatex directly as well. (it's a better option) Or use some other mark-up tools: LinuxBook, DocBook, lout, etc. (wouldn't recommend groff or troff.. ) These are all multi-output formats, so you can directly get "final output" formats like HTML, PS or PDF. Or use something like the Python-based "AsciiDoc" ( converts an AsciiDoc text file to DocBook, HTML or LinuxDoc ) or reST, etc. You can use, say, emPy, of course, to generate the input to any of the above. And there are other templating engines if you want something else. Or... there are miriads of choices out there. Have a nice digging. :) Mikl?s -- Priszny?k Mikl?s --- Jegenye 2001 Bt. ( mailto:jegenye2001 at parkhosting.com ) Egyedi szoftverk?sz?t?s, tan?csad?s Custom software development, consulting http://jegenye2001.parkhosting.com Samir Patel wrote in message news:ffd90607.0310160431.5fefb027 at posting.google.com... > Currently main choice to create a report in python is reportlab. It > allows a fine control over creation of report at cost of bigger > learning curve. Instead of reportlab, does it make sense to generate > small reports using emPy or ReST with or without use of YAML? Are > there any other choice to create small reports easily in python? From daniel at dittmar.net Thu Oct 16 15:08:53 2003 From: daniel at dittmar.net (Daniel Dittmar) Date: Thu, 16 Oct 2003 21:08:53 +0200 Subject: Jython, GILs and object locking. In-Reply-To: References: Message-ID: Jon Franz_antispam wrote: > What if the reference counter system became smart enough so that there were > n+1 'pools' of objects? n thread-local pools, and one global pool (for > objects > that are in the global scope). This could be painful to implement, and > would > have far-reaching repercussions, but it would remove the locking on > reference > counting for local variables that only have meaning within a specific thread > context. A test would still be needed in the ref counting macros to check for global/thread local. I don't know the overhead for this, but as there are special macros that forfeit the check for NULL, I can imagine that is isn't neglegible. And I can't really imagine how the tagging of objects into global and local can be made safe enough for the Python environment. Adding a local object to a global list would have to tag this object as global as well. But removing the object from the list wouldn't make it local again as there could be other global objects pointing to it. I think "painful to implement" doesn't even begin to describe it. Daniel From pythonguy at Hotpop.com Tue Oct 28 01:23:03 2003 From: pythonguy at Hotpop.com (Anand Pillai) Date: 27 Oct 2003 22:23:03 -0800 Subject: Pdf -> Doc Message-ID: <84fc4588.0310272223.177e33c4@posting.google.com> Is there any python module which will convert Acrobat PDF files to MS Word documents? I googled for it, but could not find much results apart from a pdf2doc plugin which needs the compelte acrobat installation to work. Thanks for any hints. -Anand Pillai From usenet_spam at janc.invalid Sun Oct 26 00:09:40 2003 From: usenet_spam at janc.invalid (JanC) Date: Sun, 26 Oct 2003 04:09:40 GMT Subject: play mp3 files from python References: Message-ID: Adam Endicott schreef: > I got all excited when iTunes was released for Windows. Then I was > quickly disappointed when I found out it only works for XP or 2000 (I'm > out of luck with 98 or ME). So I figured, hey, I've been wanting to write > my own python player anyway, why not make a PyTunes? > > I hit my first stumbling block almost immediately. I can't seem to find > an easy module that will let me play an mp3 file. I'm sure it must be out > there, but I can't figure it out (I'm a newbie to all but the most simple > Python scripts, and I know nothing about audio processing). Bookmarked but never tried this: The "features" mention working on Windows and having Python bindings... -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From goodger at python.org Fri Oct 17 10:06:06 2003 From: goodger at python.org (David Goodger) Date: Fri, 17 Oct 2003 10:06:06 -0400 Subject: The Pythonista's Prayer Message-ID: <3F8FF74E.10809@python.org> With apologies in advance to the devoutly religious among us, who may be offended by this corruption of The Lord's Prayer. No offence intended. The Pythonista's Prayer ======================= Our language, Which art in programs, Python be thy Name. Thy syntax come. Thy will be done, Interpreted as it is in bytecode. Give us this day our daily whitespace. And forgive us our hard tabs, As we forgive those who hard tab against us. And lead us not into temptation, But deliver us from executable line noise. For thine are the classes, and the objects, and the methods, for CLI and GUI and RAD and XP and XML and cross-platform and client/server and Internet services and data processing and [adapt/extend as necessary] ... Amen. ------------------- [This started out as, Our Benevolent Dictator, Who art in The Netherlands -- no, in Virginia -- no, in California now, Guido be thy Name. but that felt too much like one of the commandments was about to be broken.] -- David Goodger http://starship.python.net/~goodger For hire: http://starship.python.net/~goodger/cv Docutils: http://docutils.sourceforge.net/ (includes reStructuredText: http://docutils.sf.net/rst.html) From seberino at spawar.navy.mil Wed Oct 8 19:09:25 2003 From: seberino at spawar.navy.mil (Christian Seberino) Date: 8 Oct 2003 16:09:25 -0700 Subject: distutils question->when do install, says header (.h) file is an unknown file type!?!?! Message-ID: I have a program that has Python and C code. I added Extension stuff to setup.py and all .c and .h files get into tarball fine. (I have something like Extension("foo", glob.glob("bar/*.[ch]") ) When I try to INSTALL the package it says header (.h) file is an unknown type. How fix this??? Chris From mwilson at the-wire.com Sun Oct 26 11:21:41 2003 From: mwilson at the-wire.com (Mel Wilson) Date: Sun, 26 Oct 2003 11:21:41 -0500 Subject: Newbie Questions: Swithing from Perl to Python References: <2rRmb.49323$e5.1791566@news1.tin.it> Message-ID: In article <2rRmb.49323$e5.1791566 at news1.tin.it>, Alex Martelli wrote: >The list.sorted classmethod is more powerful than an instance method >of lists would be: it will let you build a sorted list out of any iterable >at all, AND support smoothly and transparently _subclasses_ of list. .. any finite iterable :> From donn at drizzle.com Sun Oct 12 01:57:09 2003 From: donn at drizzle.com (Donn Cave) Date: Sun, 12 Oct 2003 05:57:09 -0000 Subject: type checking References: Message-ID: <1065938227.288329@yasure> Quoth Stephen Horne <$$$$$$$$$$$$$$$$$@$$$$$$$$$$$$$$$$$$$$.co.uk>: ... | If you really do need static typing (as opposed to simply needing to | get used to the change), Python is simply the wrong choice of | language. Either Java, C# or Delphi may be a good option for you. Also consider functional languages with strong static typing and type inference - Haskell, Clean, ML, Objective CAML. Even if they eventually turn out to be unsuitable for the task at hand, they offer an interesting and rigorous abstraction of computer programming. Donn Cave, donn at drizzle.com From dkuhlman at rexx.com Fri Oct 3 14:50:48 2003 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Fri, 03 Oct 2003 11:50:48 -0700 Subject: GIL in the new glossary References: <3f7c9a8c@news.mt.net.mk> <87smmbyvm7.fsf@pobox.com> Message-ID: John J. Lee wrote: [snip] > > But doesn't Apache also have a multi-process mode? > > If not, why not use a different web server if this becomes a > problem? What about a Web server framework like Twisted, which claims to be single threaded, but uses a deferring mechanism to give up control (or perform other tasks?) during slow operations? Is Twisted depending upon the giving up control during I/O operations (using the deferred mechanism) in order to make use of multiple processors? Does Twisted make good use of multiple processors? Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman dkuhlman at rexx.com From skip at pobox.com Tue Oct 28 12:49:30 2003 From: skip at pobox.com (Skip Montanaro) Date: Tue, 28 Oct 2003 11:49:30 -0600 Subject: blanket except clause -- best practice? In-Reply-To: References: Message-ID: <16286.44074.457717.481199@montanaro.dyndns.org> George> class DatabaseError(StandardError): pass George> class OperationalError(StandardError): pass George> try: George> stuff George> except _pg.error, msg: George> raise DatabaseError, "error '%s' in '%s'" % ( msg, sql ) George> except: George> raise OperationalError, "internal error in '%s'" % sql George> This accomplishes passing useful info, namely "sql", on with the George> exception. Unfortunately it *loses* info in that upstream has George> no way to know *which* exception triggered this or what args it George> might have been given. I'm trying to think of a clean way to George> improve this. I could do: George> try: George> stuff George> except _pg.error, msg: George> raise DatabaseError, "error '%s' in '%s'" % ( msg, sql ) George> except Exception, x: George> raise OperationalError, "internal %s(%s) error in '%s'" (x.__class__, x.args, sql) Perhaps you should simply reraise the original exception: try: stuff except _pg.error, msg: raise DatabaseError, "error '%s' in '%s'" % ( msg, sql ) except: raise The resulting traceback displayed may be lower level than you would like, but at least no information about where the actual error occurred is lost. You can also synthesize a new exception using the original stack frame: try: stuff except _pg.error, msg: raise DatabaseError, "error '%s' in '%s'" % ( msg, sql ) except Exception, x: raise OperationalError, \ "internal %s(%s) error in '%s'" (x.__class__, x.args, sql), \ sys.exc_info()[2] This uses the original traceback object (sys.exc_info()[2]), but raises it with your OperationalError and error string, which can obviously include object values not available at the actual point where the original exception was raised. You could obviously include the first two values from sys.exc_info() in your new exception as well. Skip From syver at inout.no Thu Oct 23 07:42:12 2003 From: syver at inout.no (Syver Enstad) Date: 23 Oct 2003 13:42:12 +0200 Subject: Design Question: GUI+Threads. References: Message-ID: "Frithiof Andreas Jensen" writes: > Hi All, > > I am tinkering with a stock-market analysis program that needs to have (at > least one) a worker thread for processing real-time data and a GUI where one > can control/monitor the function of the worker, set parameters and so forth. > > Is there an elegant and generic way to implement the typical "Model, View, > Controller" pattern so that the "Model+Controller" execute in the context of > the worker thread and the "View" will execute in the GUI thread - and > communication between the two is thread-safe and simple? One way to do it: Use two Queue.Queue's. Do non blocking get's and put's from the gui on a timer. Do blocking gets from the queue instance that the GUI calls put on, do blocking put's on the queue that the GUI calls get from. I usually wrap the use of Queue behind a method interface, so that the GUI calls methods on the threaded class to get and put. If you want to to use a thread pool you can easily make all the threads can share the queue instances. From no at spam.invalid Fri Oct 24 17:46:40 2003 From: no at spam.invalid (Russell E. Owen) Date: Fri, 24 Oct 2003 14:46:40 -0700 Subject: How to set pythonpath in Mac OS X? References: Message-ID: In article , Eric Wichterich wrote: >Hello Pythonistas, > >I am trying to get certain (self-written) libraries imported into my >scripts using statements like > >"from library import function.py". > >But they are not being found. > >I think that the pythonpath-variable must be expanded to the location >to this libraries. > >But, I can't find any usable information using Google on how to set up >the pythonpath properly. >I don't even know where to look for the pythonpath-variable? > >It would be great if anyone could help me out on this? You can define the environment variable PYTHONPATH to include any paths you like, and python will read this info when it starts up. On MacOS X you have several choices for defining environment variables. All work for unix command-line apps, but only can be seen by GUI apps, so it's the one I recommend you use: put the information into a file .MacOSX/environment.plist (which you will probably have to create). Instructions are available at If you only care about command-line usage then you can edit ~/.cshrc and include a command such as setenv PYTHONPATH "/path/one/:path/two:..." (note: .cshrc may not be the best choice, but it certainly works). Warning: do NOT mix these two techniques. At least in Jaguar, environment.plist completely overrides env variables defined or modified in .cshrc. -- Russell From r.steffensen at c2i.net Sat Oct 18 19:19:27 2003 From: r.steffensen at c2i.net (Rune Steffensen) Date: Sat, 18 Oct 2003 23:19:27 GMT Subject: Why don't people like lisp? References: <1A8kb.67406$pv6.3464@twister.nyc.rr.com> Message-ID: ...it could have something to do with its users. Now, if just someone would take this thread, and put it further up than the sun will ever reach... -- -rune Incognito, ergo sum. From felix_mcallister at hotmail.com Fri Oct 3 04:20:28 2003 From: felix_mcallister at hotmail.com (Felix McAllister) Date: Fri, 3 Oct 2003 09:20:28 +0100 Subject: Reading Windows (NT/2000/XP) system and user environment variables References: Message-ID: If you need to get the list of system environment variables and the (separate) list of user environment variables, you'll have to read the following registry settings: System: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment User: HKEY_CURRENT_USER\Environment You can use the win32api functions RegConnectRegistry, RegOpenKey, RegQueryValue etc. for these. Felix. > What is the best way in Python version 2.x to read/get Windows (nt/2000/xp) > system and user environment variables? > > Thanks for the help! > > jep From FBatista at uniFON.com.ar Tue Oct 21 13:49:02 2003 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Tue, 21 Oct 2003 14:49:02 -0300 Subject: prePEP: Money data type Message-ID: Alex Martelli wrote: #- > thousandSeparator = '.' #- > decimalSeparator = '.' #- > #- > the behaviour is unpredictable (should I generate an exception or #- > something?) #- #- Yes (in face of ambiguity refuse the temptation to guess). Added to PEP. #- So, if a $ is pasted in front I need to go to the trouble #- of taking it out anyway, etc. #- #- A 'format' method could take optional arguments specifying which #- locale to use, whether to use money or basic conventions, #- international or basic ones, etc. THAT would be of some use, #- of course. A __str__ method cannot take such arguments, #- and IMHO should therefore default to simplicity -- just #- '12.34' (so I can use a '$%8s' % m to get the kind of format #- shown in the above columnar output). OK. See your point and agree with it. But .format should be very complicated (accepting different arguments, etc, etc) or should be very simple (use '$' and '.', and if you want it different, overload it)? From peter at engcorp.com Wed Oct 8 07:57:56 2003 From: peter at engcorp.com (Peter Hansen) Date: Wed, 08 Oct 2003 07:57:56 -0400 Subject: Communications with DDE References: Message-ID: <3F83FBC4.DA3420DF@engcorp.com> Please don't post using HTML. It makes the message hard to read for many people, and this is Usenet/the mailing list, not the web. Thank you. jonathan hunt wrote: > > Does someone know the set of class and functions from the DDE module? > This module in the distribution of Python2.3 under the form of dde.pyd > and with two examples: Ddeserver.py and Ddeclient.py. > The whole set runs correctly but i search more information because i > want to do communicate a ddeserver written in C++ and a ddeclient written > in Python. The server doesn't know what language is used for the client, and vice versa. Just use the Ddeclient.py example as a starting point to write your own client. It should work fine with the C++ server if you know how to use DDE. If you don't know how to use DDE, then this probably isn't a Python question yet, and you should be doing more research and experimenting before you ask for help. If you have trouble, post small examples of your failing code and make sure to include enough detail that others can help you out. -Peter From abriggs at westnet.com.au Thu Oct 30 07:01:33 2003 From: abriggs at westnet.com.au (Anthony Briggs) Date: Thu, 30 Oct 2003 20:01:33 +0800 Subject: lightweight human-readable config? In-Reply-To: References: Message-ID: At 10:22 PM +0000 29/10/03, Maxim Khesin wrote: >I want to have a config file with my python proggie, satisfying the >following requirements: >1) support key->(value, default) >2) simple and intuitive to read and edit >3) easyly readable into a python datastructure (a dictionary?) >4) not requiring any heavy libraries needed (I am distributing my >proggie as a py2exe executable and do not want to bloat the size) It's probably reinventing the wheel, but here's one I wrote a while ago. It might serve as a starting point, if nothing else. The actual code's quite short - it's all those pesky comments and unit tests that take up all the room ;) It's also possible to have .py files imported (I forget how) from a py2exe program, so you can also go down the python formatted config file route. Anthony -- #!/usr/local/bin/python # A stab at writing a config script # We'll assume that # and ; are comment characters # unless they're in quotes # to run the unit tests, simply execute this script: # config.py -v import sys, os, string import unittest class config: """ A class to store configuration values in a text file, and read them out. To use this class, simply declare it: myconfig = config("config.txt") it will automatically read in all of the values from config.txt, and myconfig will then behave roughly like a dictionary: myconfig['name'] # corresponds to name=... in config.txt There are also the following functions: myconfig.keys() # a list of all of the attributes myconfig.delete('wibble') # delete attribute wibble myconfig.readconfig() # read in the config file again myconfig.writeconfig([filename]) # write the config file # filename is optional """ def __init__(self, configfile): """Set up the class, and read in all of the values.""" self._info={} self._file=configfile if os.access(self._file, os.F_OK) == 1: # we can read in the config file self.readconfig() # A couple of simple functions to make using the class easier # ie. you can just say configclassinstance['blah'] def __getitem__(self, name): return self._info[name] def __setitem__(self, name, value): self._info[name] = value def keys(self): """return all of the config values.""" return self._info.keys() def delete(self, item): """Delete a key from the config directory.""" if item not in self._info.keys(): raise IndexError, 'Item '+str(item)+' not found in the config.' else: del self._info[item] def readconfig(self): """Read in the config file, line by line.""" # First, clear out the old config: self._info = {} # Now, open it and read in each line, calling _readconfigline to parse it file = open(self._file, 'r') for line in file.readlines(): self._readconfigline(line) file.close() return def _readconfigline(self,theline): """Given a line, parse it and put it into the self.info dictionary.""" theline = string.strip(theline) if theline=='' or theline[0]=='#' or theline[0]==';': return # this line is empty or a comment attribute, value = string.split(theline, '=', 1) attribute = string.strip(attribute) value = string.strip(value) if value[0] == '=': raise ValueError, "Too many equal signs in "+theline # First we check for quotes, just to be sure that # there aren't any nested comment chars in them value = string.strip(value) if '"' in value: if value[0]=='"' and string.count(value, '"') == 2: value, ignored = string.split(value[1:], '"', 1) else: # they're playing funny buggers, and gave us # something like attr=blah"blah" raise ValueError, "Quotes misplaced in "+theline else: # no quotes - cut sick! if '#' in value: value, ignored = string.split(value, '#', 1) value = string.strip(value) if ';' in value: value, ignored = string.split(value, ';', 1) value = string.strip(value) self._info[attribute] = value def writeconfig(self, filename=""): """Write out all of the values in the config to a file.""" if filename=="": filename = self._file if os.access(self._file, os.F_OK) == 1: # We might want to raise an error at this point... raise IOError, "File "+self._file+" already exists!" file = open(filename, 'w') for item in self._info.keys(): file.write(item+'="'+self._info[item]+'"\n') file.close() class testItems(unittest.TestCase): """Test that config works correctly.""" configtest = config("testconfig.txt") goodconfiglines = [ # line, attribute, value ['womble=blah', 'womble', 'blah'], ['womble2="blah2"', 'womble2', 'blah2'], ['blah2="wibble" #comment', 'blah2', 'wibble'], ['blah3="wibble2" ;comment', 'blah3', 'wibble2'], ['blah6="####" # A comment', 'blah6', '####'], ['blah7=";;;;" ; A comment', 'blah7', ';;;;'], ['blah10=quotes a go go! ; # # ; ; ##; ;#', 'blah10', 'quotes a go go!'], ['blah5 = "womble5"', 'blah5', 'womble5'], ['blah9=womble72 ; comment!', 'blah9', 'womble72'], ['blah11=" spaces should be preserved! "', 'blah11', " spaces should be preserved! "], ["blah8=This won't break!", 'blah8', "This won't break!"], ] badconfiglines = [ # these config lines should throw a ValueError 'blah11="broken"quotes"', 'blah12="more"broken"quotes"', 'blah13=broken"quotes?"', 'strangequals=="blah"', 'strangeequals2="wibble"="blah"', ] def testAddLines(self): """Test that lines can be added to the config object.""" # First, clear out self.testconfig: for item in self.configtest.keys(): self.configtest.delete(item) for item in self.goodconfiglines: self.configtest._readconfigline(item[0]) self.assertEqual(item[2], self.configtest[item[1]]) def testDelete(self): """Test that delete works.""" # First, clear out self.testconfig: for item in self.configtest.keys(): self.configtest.delete(item) # Now add and delete for item in self.goodconfiglines: self.configtest[item[1]]=item[2] self.failUnless(self.configtest[item[1]]==item[2]) self.configtest.delete(item[1]) self.failIf(item[2] in self.configtest.keys()) def testConfigKeys(self): """Test that items added appear in config.keys().""" # First, clear out self.testconfig: for item in self.configtest.keys(): self.configtest.delete(item) self.failUnless(self.configtest.keys()==[]) # Now add and delete for item in self.goodconfiglines: self.configtest[item[1]]=item[2] self.failUnless(item[1] in self.configtest.keys()) def testConfigLines(self): """Test that all of the types of config lines can be read from a file.""" for item in self.goodconfiglines: #write the line to a config file file = open("testconfig.txt", "w") file.write(item[0]) file.close() # Now check that it can be read from the file self.configtest.readconfig() self.assertEqual(item[2], self.configtest[item[1]]) def testSanityCheck(self): """For each item in goodconfiglines, test that it can be written to a file and read back unchanged.""" # First, clear out self.testconfig: for item in self.configtest.keys(): self.configtest.delete(item) # Now test! for item in self.goodconfiglines: self.configtest[item[1]]=item[2] os.unlink("testconfig.txt") self.configtest.writeconfig("") self.configtest.readconfig() self.assertEqual(item[2],self.configtest[item[1]]) def testBadConfigLines(self): """Test that dodgy config lines will throw an exception.""" for item in self.badconfiglines: self.assertRaises(ValueError, self.configtest._readconfigline, theline=item) if __name__ == "__main__": unittest.main() -- ---------------------------------------------------- HyPEraCtiVE? HeY, WhO aRE YoU cALliNg HypERaCtIve?! aBRiGgS at wEStNeT.cOm.aU ---------------------------------------------------- From adalke at mindspring.com Tue Oct 7 01:41:52 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Tue, 07 Oct 2003 05:41:52 GMT Subject: Python syntax in Lisp and Scheme References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> <92c59a2c.0310031345.57d20631@posting.google.com> <8b9e2260.0310032317.72abd86a@posting.google.com> <8b9e2260.0310040524.229dfd9f@posting.google.com> <20031004163422.22f5d03e.androflux@softhome.net.remove.to.reply> Message-ID: Gerrit Holl: > a = 2 > a = 1 + 1 > a = math.sqrt(4) > a = int((sys.maxint+1) ** (1/31)) > > ...all mean the same thing. Be careful with that. The first two return the integer 4, the third returns the floating point number 4.0 and the last returns 1 because 1/31 is 0 (unless you are using true division). Even if you use 1/31. you'll get a different value on a 32 bit machine vs. a 64 bit machine. pedantically yours, Andrew dalke at dalkescientific.com From kirk at strauser.com Tue Oct 21 16:10:06 2003 From: kirk at strauser.com (Kirk Strauser) Date: Tue, 21 Oct 2003 20:10:06 GMT Subject: structure in Python References: Message-ID: <87y8vfzbgy.fsf@strauser.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 At 2003-10-20T23:13:48Z, "Alberto Vera" writes: > How Can I make it using Python? Ask your instructor for a tutor? :) - -- Kirk Strauser -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.3 (GNU/Linux) iD8DBQE/lHwx5sRg+Y0CpvERAsKsAJ9gK5wIfdjscVEEPlKhHAu/71PcQwCeOaSa WG3b9DzmpIgvsUoDtIA8hlw= =Md0l -----END PGP SIGNATURE----- From alanmk at hotmail.com Mon Oct 20 06:45:55 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Mon, 20 Oct 2003 11:45:55 +0100 Subject: Alternatives to WebUnit References: Message-ID: <3F93BCE3.96CF330D@hotmail.com> Ian Bicking wrote: > puffinhome.org is another Python web tester. The > author was quite gung-ho at one time, but I haven't heard much from it > in a while. It seems to be intended more for QA people, as opposed to > programmer-written tests. Puffin is not a bad little tool, and it's not too hard to get up to speed with it for basic testing. However, there are two major flaws 1. It builds up a *huge* xml DOM to store its results. This rules it out for anything other than simple tests: it *eats* memory. 2. There is hardly any documentation. Meaning that you have to wade through the source to determine necessary details, e.g. whether it supports HTTP 1.1 (IIRC it doesn't), etc. regards, -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From claird at lairds.com Mon Oct 13 14:40:32 2003 From: claird at lairds.com (Cameron Laird) Date: Mon, 13 Oct 2003 18:40:32 -0000 Subject: Tkinter isn't permanently ugly (was: python applications deployement) References: <607d8200.0310130551.13bf2fa5@posting.google.com> Message-ID: In article , Dave Benjamin wrote: >In article , Cameron Laird wrote: >> In article <607d8200.0310130551.13bf2fa5 at posting.google.com>, >> Rodrigo Benenson wrote: >> . >> . >> . >>>To my eyes Python has two very bad things: >>>1- Tkinter is great for programmers but ugly to everyone. >> . >> . >> . >> There's hope that the visual appearance of Tkinter will improve in >> a finite amount of time . > >Hey, nice! Tk is definitely the path of least resistance for me with GUI >coding, but there definitely is a distinct Tk look that might have been >fashionable back when Motif was popular but now looks weird or dated to >most people. However, a lot of this has to do with defaults; on one project, >I was able to produce a Tk app that looked exactly like a typical Windows >interface, with IE-style toolbar buttons and everything. Tk is very >customizable. . . . Brian Griffin has packaged a new collection of defaults which has people raving (with enthusiasm). I don't think anyone's yet writ- ten a coherent explanation or description, but the code's here: http://tcl.projectforum.com/tk/admin/download.html?attachid=19232 He's delivering applications to customers based on this *now*, with success. -- Cameron Laird Business: http://www.Phaseit.net From gh at ghaering.de Wed Oct 1 12:26:52 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Wed, 01 Oct 2003 18:26:52 +0200 Subject: mxODBC In-Reply-To: References: Message-ID: <3F7B004C.1020703@ghaering.de> Andrew Chalk wrote: > What is wrong with the following attempt to perform an SQL INSERT? No error > is thrown but no data is inserted into table FRED in the database. > Especially odd is that SELECT statements work! The database is MS SQL Server > 2000. [...] You don't seem to commit the transaction. Invoke .commit() on the connection object to do so. -- Gerhard From nid_oizo at yahoo.com_remove_the_ Wed Oct 15 13:42:34 2003 From: nid_oizo at yahoo.com_remove_the_ (Nicolas Fleury) Date: Wed, 15 Oct 2003 13:42:34 -0400 Subject: Expat current line/column number In-Reply-To: <3F8D8440.D0038E86@hotmail.com> References: <3F8D8440.D0038E86@hotmail.com> Message-ID: Alan Kennedy wrote: > [Nicolas Fleury] > >> Is it possible with xml.parsers.expat to get the current line and >>column number if an exception is raised by one of the callbacks (not >>necessary an xml.parsers.expat.ExpatError)? > > > Is this the type of thing you mean? This is exactly what I mean. Unfortunately, I've use the parser in xml.parsers.expat and not xml.sax, and it seems that parser only provides line and column numbers for its own exceptions. I will investigate to convert to xml.sax. Thx for your help. Regards, Nicolas Fleury From Scott.Daniels at Acm.Org Wed Oct 8 11:36:19 2003 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 08 Oct 2003 08:36:19 -0700 Subject: mulit-dimensional lists In-Reply-To: References: Message-ID: <3f842ef3$1@nntp0.pdx.net> saoirse_79 wrote: > > Thanks for your help...what I exactly want to do is as follows: I > have a file (a multiple sequence alignment to be exact) This describes your input to you, but not to me. Try a very concrete description with an example. I'll guess: My file looks like: 1 2 3 3 4 5 6 ... > and I want each line in that file to be a separate list, hence > creating a list of lists! Again, I'll guess you mean: [[1, 2, 3], [3], [4, 5, 6] ...] After: f = file(sourcefilename, 'r') result = [] for line in f: result.append(line.split()) f.close() result[5] is the list resulting from splitting the sixth line of the file. -Scott David Daniels Scott.Daniels at Acm.Org From banderson at hp.com Mon Oct 20 21:01:33 2003 From: banderson at hp.com (Bill Anderson) Date: Mon, 20 Oct 2003 19:01:33 -0600 Subject: text ui options in Python Message-ID: A couple of years ago I wrote a small data display app in Python using curses. I know find myeself needing to code something with menus and such, and it must be a TUI, GUI is not an option. So I've been doing some googling, but not to much effect. I've found that pyncurses was discussed as an option to swap curses module over to. Did this happen, and if not will it and if so, when? I've tried to compile pyncurses on RH9 but it bombs bad. The sf.net page shows a debian user w/the same issue. Pyncurses looks dead. I tried anygui, but it seems to just sit there and not display anything. I'd like something higher level than curses. I've found nearly no information on using newt, snack, or Tinter. Any help appreciated. Bill Anderson From wmm at gsoa.net Fri Oct 17 17:06:12 2003 From: wmm at gsoa.net (Mark McClain) Date: Fri, 17 Oct 2003 17:06:12 -0400 (EDT) Subject: xmlrpc server Message-ID: <200310172106.h9HL6C026172@gsoa.net> I have googled and can't find an answer. The xmlrpclib has the flag allow_none. There does not seem to be a similar flag for the the Server. Is this for a particular reason? I am trying to export some code that sometimes returns None. The only way around it seems require reimplementing _marshaled_dispatch. mark From pmaupin at speakeasy.net Fri Oct 24 12:03:32 2003 From: pmaupin at speakeasy.net (Patrick Maupin) Date: 24 Oct 2003 09:03:32 -0700 Subject: Trailing comma (was: Re: structure in Python) References: <3F95585C.3EDF3364@engcorp.com> <653b7547.0310231853.215189da@posting.google.com> Message-ID: <653b7547.0310240803.13fde5e8@posting.google.com> Georgy Pruss wrote: > You can always find a better diff which will show you an added > comma and an additional line. Again, it's a tool problem. Do not presume, simply because I choose to arrange my affairs such that I can usually use a BB gun more effectively than many can use a howitzer, that I have a "tool problem." Pat From gat at jpl.nasa.gov Sun Oct 12 22:14:56 2003 From: gat at jpl.nasa.gov (Erann Gat) Date: Sun, 12 Oct 2003 19:14:56 -0700 Subject: Python syntax in Lisp and Scheme References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> <92c59a2c.0310031345.57d20631@posting.google.com> <6WKdnf4hoZxoRRWiXTWJig@comcast.com> <39hib.205605$hE5.6914649@news1.tin.it> <29kib.206536$hE5.6945256@news1.tin.it> Message-ID: In article <29kib.206536$hE5.6945256 at news1.tin.it>, Alex Martelli wrote: > > What makes you think that macros have farther reaching effects in this > > regard than functions? If I call a method and pass it a function object, > > I also don't know what the method will do with it. > > Of course not -- but it *cannot possibly* do what Gat's example of macros, > WITH-MAINTAINED-CONDITION, is _claimed_ to do... "reason" about the > condition it's meant to maintain (in his example a constraint on a variable > named temperature), about the code over which it is to be maintained > (three functions, or macros, that start, run, and stop the reactor), > presumably infer from that code a model of how a reactor _works_, and > rewrite the control code accordingly to ensure the condition _is_ in fact > being maintained. A callable passed as a parameter is _atomic_ -- you > call it zero or more times with arguments, and/or you store it somewhere > for later calling, *THAT'S IT*. This is _trivially simple_ to document and > reason about, compared to something that has the potential to dissect > and alter the code it's passed to generate completely new one, most > particularly when there are also implicit models of the physical world being > inferred and reasoned about. Given that I've seen nobody say, for days!, > that Gat's example was idiotic, as I had first I thought it might be, and > on the contrary I've seen many endorse it, I use it now as the simplest > way to show why macros are obviously claimed by their proponents to > be _scarily_ more powerful than functions. Why "scarily"? E. From emile at fenx.com Fri Oct 24 11:58:04 2003 From: emile at fenx.com (Emile van Sebille) Date: Fri, 24 Oct 2003 08:58:04 -0700 Subject: PEP 289: Generator Expressions (please comment) References: <5d83790c.0310231158.65595858@posting.google.com> Message-ID: Raymond Hettinger revives pep 289: > Peter Norvig's creative thinking triggered renewed interest in PEP 289. > That led to a number of contributors helping to re-work the pep details > into a form that has been well received on the python-dev list: > > http://www.python.org/peps/pep-0289.html > > In brief, the PEP proposes a list comprehension style syntax for > creating fast, memory efficient generator expressions on the fly: What do you get from: type(x*x for x in roots) I assume you'd get something like genexp that behaves like an iterator and that the consuming function accesses items until StopIteration(StopGenxing? ;) is raised, and that a genexp is otherwise a first class object. >From the PEP: "All free variable bindings are captured at the time this function is defined, and passed into it using default argument values...[snip]...In fact, to date, no examples have been found of code where it would be better to use the execution-time instead of the definition-time value of a free variable." Does this imply then that instead of: dumprec = "\n".join('%s : %s' % (fld.name, fld.val) for fld in rec) for rec in file: print dumprec one would need to write some variation of: for rec in file: print "\n".join('%s : %s' % (fld.name, fld.val) for fld in rec) or: def dumprec(rec): return "\n".join('%s : %s' % (fld.name, fld.val) for fld in rec) for rec in file: print dumprec(rec) I find the first construct easier on the eyes, and it fulfills on the promise of 'generator expression' as opposed to 'iterable generated expression'. Although it does feel much more macro-ish... Overall, +1. Emile van Sebille emile at fenx.com From jmiller at stsci.edu Tue Oct 7 11:42:28 2003 From: jmiller at stsci.edu (Todd Miller) Date: 07 Oct 2003 11:42:28 -0400 Subject: Python on Altix In-Reply-To: <16258.55129.671685.338799@montanaro.dyndns.org> References: <3F82CED3.6020904@stsci.edu> <16258.55129.671685.338799@montanaro.dyndns.org> Message-ID: <1065541348.14522.9.camel@halloween.stsci.edu> On Tue, 2003-10-07 at 11:10, Skip Montanaro wrote: > > You wrote: > > Todd> I configure Python like this: > > Todd> ./configure --prefix=$HOME --with-pydebug --without-threads > > then you jump to: > > Todd> But as soon as I try to run my software self-tests (for the > Todd> numarray Numeric-like array package), I get this: > > ... > > then later: > > Todd> I've poked around with this for a few hours, but I'm not getting > Todd> much out of GDB. Does anyone have any suggestions on how to get > Todd> Python up and running on an Altix or how to solve this problem > Todd> more generally? > > Maybe I'm being too pdeantic, but did Python's own test suite run > successfully? Not completely, but it looked close. There were two failures which may even be "expected": 2 tests failed: test_bsddb test_imp 38 tests skipped: test_aepack test_al test_asynchat test_audioop test_bsddb185 test_bsddb3 test_cd test_cl test_curses test_dl test_email_codecs test_fork1 test_gl test_imageop test_imgfile test_linuxaudiodev test_logging test_macfs test_macostools test_normalization test_ossaudiodev test_pep277 test_plistlib test_queue test_rgbimg test_scriptpackages test_socket test_socket_ssl test_socketserver test_sunaudiodev test_thread test_threaded_import test_threadedtempfile test_threading test_timeout test_urllibnet test_winreg test_winsound 12 skips unexpected on linux2: test_threadedtempfile test_threaded_import test_fork1 test_rgbimg test_threading test_socket test_thread test_queue test_asynchat test_audioop test_imageop test_logging Here are the details: test test_imp failed -- expected imp.lock_held() to be True test_bsddb test test_bsddb failed -- errors occurred; run in verbose mode for details test_bsddb185 test_bsddb185 skipped -- No module named bsddb185 test_bsddb3 test_bsddb3 skipped -- Use of the `bsddb' resource not enabled > You seem to be trying to run before you're walking. > 32->64-bit issues do pop up from time-to-time. It's possible that the > Python developers have tackled this already but that the numarray folks > haven't. Bingo. I maintain and extend numarray. > If you've run "make test" successfully in your Python build > directory, I would imagine you've figured out "how to get Python up and > running on an Altix", and that the problem lives in the numarray code. If > not, you probably need to ignore numarray for the time being while you debug > your basic Python configuration. Sounds like I may be OK already. > At first glance, it looks like whoever wrote to the block in question got > carried away and scribbled off the end of the block. You might try gdb's > "watch" command to keep an eye on that address. You'll probably want to be > careful when you set the watchpoint (whittle your failing test case down as > small as possible, set the watchpoint as close as possible to the error) to > avoid slowing your code down to an unmanageable crawl. This sounds like good advice, I'll give it a try and report back later. Thanks for the help, Todd -- Todd Miller jmiller at stsci.edu STSCI / ESS / SSB From cedmunds at spamless.rochester.rr.com Tue Oct 28 23:30:43 2003 From: cedmunds at spamless.rochester.rr.com (Cy Edmunds) Date: Wed, 29 Oct 2003 04:30:43 GMT Subject: getting MS Access table relationships with pythonWin? References: <3533440.1067377226@dbforums.com> Message-ID: "cvchen" wrote in message news:3533440.1067377226 at dbforums.com... > > Hello, > > I'm implementing a data dictionary (catalogging system) that can be > searched in several ways. I finished the first version without using > any databases, I just had pickled dictionaries to store the data and > I unpickled files as necessary to get at search results, that worked > just fine for me. > > Problem is, my boss wants me to integrate the data into MS Access > because my project will eventually become part of a larger project. > So, I've got all my data in Access tables and have them linked > through relationships; I've found a way to access data from Access > .mdb files at this page: http://www.e-coli.net/pyado.html. > > However, there were no lessons included on how to get to the > relationally linked tables of a certain recordset; googling and > yahooing around hasn't turned up any good leads. Is anyone here > knowledgeable about this? I need to get to the relationally linked > tables because search queries would then move along alot faster than > simple brute force search and sort techniques. If I've been unclear > in anyway, please let me know. Thanks! > > > > -Calvin > > > -- > Posted via http://dbforums.com You can get the "relational" part of relational databases by just using "inner join" in SQL. As I understand it, the primary function of relationships that you can define in Access is to simplify the process of constructing queries. The meaning of the resulting SQL is not dependent on these relationships. Take a look at the SQL Access produces to see what is going on. However, a word of caution: the "SQL" Access produces isn't standard (# delimiter for dates, " delimiter for strings, etc.) -- Cy http://home.rochester.rr.com/cyhome/ From daniel at dittmar.net Thu Oct 16 16:35:25 2003 From: daniel at dittmar.net (Daniel Dittmar) Date: Thu, 16 Oct 2003 22:35:25 +0200 Subject: Jython, GILs and object locking. In-Reply-To: <3f8ef3ed$0$10276$e4fe514c@dreader10.news.xs4all.nl> References: <3F8ED281.2211935F@hotmail.com> <3f8ef3ed$0$10276$e4fe514c@dreader10.news.xs4all.nl> Message-ID: Ype Kingma wrote: > Jython does not have "these problems". It just has another garbage > collecting method than CPython, and normally __del__ is called from > another thread. "Jythons has already these problems" was really the short form for "People porting their programs to the non-reference-counted Python will have problems when they rely on the CPython specific behaviour that objects get destroyed when they are out of scope. People porting their programs to Jython have these problems already today". That's why I was talking about the "language CPython" in the post before that. But the easiest way around this would be to change the exception when the process runs out of file handles. Something like "Serves you right, you shouldn't rely on implementation defined behaviour anyway" perhaps. Daniel From mfranklin1 at gatwick.westerngeco.slb.com Fri Oct 24 05:24:50 2003 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Fri, 24 Oct 2003 10:24:50 +0100 Subject: How to write good Python objects? In-Reply-To: References: Message-ID: <1066987489.1130.17.camel@m-franklin> On Fri, 2003-10-24 at 02:15, John Ladasky wrote: > I have written one nice, self-contained object that contained a DNA > sequence, and various functions to manipulate the data therein. My > wxPython GUI objects, in contrast, are in a state of constant flux. > Rather than importing and reusing a piece of code, I find myself > copying the code into my new program and playing with it, just a bit. > I'm starting to believe that writing a good GUI object, one that you > can really reuse, is actually quite hard. Yes, I know that you can > derive a new object that overrides properties of your old object. > Should I find myself doing this for every object that I write? > John , I see you've been helped with the /Lib folder question. I am more interested to hear about your GUI problem. I don't use wxPython I use Tkinter but hardly ever find myself copying code from one project to another...(these days) perhaps you could share some examples of the kind of GUI elements you find yourself copying... One example I used to find myself copying would be a tool bar (Tkinter does not have a 'toolbar' widget) I would find myself creating a Frame then adding lots of buttons to it now however I use a Toolbar class I created that has an add method that takes a couple of arguments. e.g (untested) I now use something like: class Toolbar(Frame): def __init__(self, parent): Frame.__init__(self, parent) def add(self, label="", icon=None, command=None): b = Button(self, text=label, command=command, image=icon) b.pack(side="left") ... now to use it in some other module... tb = Toolbar(root) tb.pack(fill="x") tools = [("Open", None, self.openFile), ("Close", None, self.closeFile), ("Quit", None, self.quit) ] for label, image, command in tools: tb.add(label=label, icon=image, command=command) ## rather than... toolbar = Frame(parent) toolbar.pack() openButton = Button(toolbar, text="Open", command=self.openFile) openButton.pack(side="left") closeButton = Button(toolbar, text="Close", command=self.closeFile) closeButton.pack(side="left") ... you get the picture... Is this the sort of problem you are having..? Regards Martin -- Martin Franklin From ken at perfect-image.com Sat Oct 25 14:17:06 2003 From: ken at perfect-image.com (Ken Godee) Date: Sat, 25 Oct 2003 11:17:06 -0700 Subject: database widgets In-Reply-To: References: <8765idqwlu.fsf@pobox.com> Message-ID: <3F9ABE22.1030606@perfect-image.com> Daniel Dittmar wrote: > > bromden writes: > > > > > >>Are there any free Python database widgets which provide a link > >>between a database and visual controls? > >>(like those of org.netbeans.lib.sql and org.netbeans.lib.sql.models > >>Java packages or Delphi's DataAccess and DataControls packages) > > John J. Lee wrote: > >> Not quite a Python question, but certainly Qt / PyQt has various DB >> widgets (Qt 3, not Qt 2). No doubt other toolkits do too. > > > But these widgets probably don't bind to Python database drivers. > > Daniel > Hmmm... With PyQt you do not use any "Python database drivers", the PyQt database widgets are "data aware widgets", you simply load the correct Qt/PyQt database driver for your database, write your python code calling any of the PyQt data aware widgets. Really pretty cool, simple and works good. From raffael at mediaone.net Tue Oct 28 23:48:43 2003 From: raffael at mediaone.net (Raffael Cavallaro) Date: 28 Oct 2003 20:48:43 -0800 Subject: Python from Wise Guy's Viewpoint References: <3F9D5D21.2060408@ps.uni-sb.de> Message-ID: Matthias Blume wrote in message news:... > [This whole discussion is entirely due to a mismatch of our notions of > what constitutes expressive power.] No, it is due to your desire to be type constrained inappropriately early in the development process. Lispers know that early on, you don't care about type constraints because you haven't settled on your final data representations yet. So why waste time placating a type-checking compiler before you have to? With lisp, you only add as much type checking as you need, *when* you need it. With a statically typed language, you have to do the compiler type check dance from the very first minute, even though you don't need to solve the type constraint problems yet. From gerrit at nl.linux.org Tue Oct 21 07:13:50 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Tue, 21 Oct 2003 13:13:50 +0200 Subject: GOOD BOOK for PYTHON/Linux In-Reply-To: References: Message-ID: <20031021111349.GA3228@nl.linux.org> English Teacher wrote: > Newsgroups: comp.lang.python, rec.photo.digital, rec.photo.equipment.35mm, > rec.woodworking, comp.os.linux.advocacy Why does spam always crosspost to at least rec.woodworking in c.l.py? Gerrit. -- 23. If the robber is not caught, then shall he who was robbed claim under oath the amount of his loss; then shall the community, and ... on whose ground and territory and in whose domain it was compensate him for the goods stolen. -- 1780 BC, Hammurabi, Code of Law -- Asperger Syndroom - een persoonlijke benadering: http://people.nl.linux.org/~gerrit/ Kom in verzet tegen dit kabinet: http://www.sp.nl/ From alanmk at hotmail.com Fri Oct 3 07:03:17 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Fri, 03 Oct 2003 12:03:17 +0100 Subject: GIL in the new glossary References: <9fc58c06.0310020937.457e36d5@posting.google.com> Message-ID: <3F7D5775.3CC05960@hotmail.com> [Python Glossary] >> global interpreter lock >> >> The lock used by Python threads to assure that only one thread >> can be run at a time. This simplifies Python by assuring that no >> two processes can access the same memory at the same time. Locking >> the entire interpreter makes it easier for the interpreter to be >> multi-threaded, at the expense of some parallelism on >> multi-processor machines. [Luis P Caamano wrote] > Some parallelism??? Wouldn't it be more accurate to say > "at the expense of parallelism?" The GIL doesn't eliminate > "some" paralellism, it completely eliminates any chance of > parallelism within the same interpreter. I just wanted to point out a relation that I have noticed has held true for almost all GIL discussion threads that have come up in this forum recently. That relation is:- The amount of loud complaining and misinformation that originates from people who have just found out about the GIL is inversely proportional to the amount of factual knowledge that they have about the GIL. Or:- The less they understand the subject, the more loudly they complain. dont-complain-before-finding-out-the-facts-ly y'rs, -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From adalke at mindspring.com Thu Oct 9 14:50:46 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Thu, 09 Oct 2003 18:50:46 GMT Subject: Python syntax in Lisp and Scheme References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> <92c59a2c.0310031345.57d20631@posting.google.com> <6CZgb.3273$dn6.860@newsread4.news.pas.earthlink.net> <8765iy2wt3.fsf@thalassa.informatimago.com> Message-ID: Pascal Bourguignon: > Because the present is composed of the past. You have to be > compatible, otherwise you could not debug a Deep Space 1 probe > 160 million km away, (and this one was only two or three years old). Huh? I'm talking purely in the interface. Use ASCII '[' and ']' in the Lisp code and display it locally as something with more "directionality". I'm not suggesting the unicode character be used in the Lisp code. Take advantages of advances in font display to overcome limitations in ASCII. > Mathematicians indeed overload operators with taking into account > their precise properties. But mathematicians are naturally > intelligent. Computers and our programs are not. So it's easier if > you classify operators per properties; if you map the semantics to the > syntax, this allow you to apply transformations on your programs based > on the syntax without having to recover the meaning. Ahhh, so make the language easier for computers to understand and harder for intelligent users to use? ;) Andrew dalke at dalkescientific.com From francisgavila at yahoo.com Sun Oct 5 16:24:08 2003 From: francisgavila at yahoo.com (Francis Avila) Date: Sun, 5 Oct 2003 16:24:08 -0400 Subject: Echo console to a device (and vice-versa)? References: Message-ID: "Peter Otten" <__peter__ at web.de> wrote in message news:bljgqr$995$06$1 at news.t-online.com... > Francis Avila wrote: > > > try: > > ttybuf = os.read(ttyfdout, 1) > > except OSError, err: > > if err == EAGAIN: > > pass > > else: > > os.write(stdout, ttybuf) > > Well, admitting that I don't have any idea what you want to do, the above > code silences *any* OSError, i. e. > > if err == EAGAIN: > pass > > is a NOOP. If you want to catch only EAGAIN, you might consider > > try: > ttybuf = os.read(ttyfdout, 1) > except OSError, err: > if err != EAGAIN: > raise > else: > os.write(stdout, ttybuf) > > instead. > > Peter That's true, thanks. I was thinking a bit sloppily, catching EAGAIN as though it were itself an exception. However, it doesn't effect functioning unless some other fatal exception pops up. The problem was simply that my tty wasn't raw enough. It wasn't sufficient to make the tty raw from the shell (using, in this case, 'stty raw pass8'). Calling tty.setraw on each of the four fd's solved the problem without incident, and the code works exactly as expected. Of course, now there are no excape characters, so I can't even ^C to exit, but this is all resolvable. -- Francis Avila From newsgroups at jhrothjr.com Mon Oct 6 20:36:52 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 6 Oct 2003 20:36:52 -0400 Subject: Accessing global namespace References: <5gngb.30600$541.25337@nwrdny02.gnilink.net> Message-ID: "Carl Banks" wrote in message news:5gngb.30600$541.25337 at nwrdny02.gnilink.net... > John Roth wrote: > > Minor note here - because of the latest > > spate of worms, etc, > > > Worms--do you mean those annoying little programs that exist because > people have casual attitudes about potentially exploitable programming > flaws? Casual? I'd say the persistant use of known insecure programming languages like C and C++ for the foundations of our systems is anything but casual. And the design of Windows to make it very easy to execute unexamined and untrusted code was likewise anything but casual. One is (arguably) criminal laziness on a lot of people's parts, and the other was simple arrogance on the part of a known monopolist. John Roth > > > (I's so sorry, I couldn't resist that--I'm done now--I promise.) I can resist anything - but temptation. Mark Twain > -- > CARL BANKS http://www.aerojockey.com/software From op73418 at mail.telepac.pt Wed Oct 29 14:11:18 2003 From: op73418 at mail.telepac.pt (Gonçalo Rodrigues) Date: Wed, 29 Oct 2003 19:11:18 +0000 Subject: PEP 323: Copyable Iterators References: Message-ID: On Wed, 29 Oct 2003 18:09:49 GMT, Alex Martelli wrote: >Interested parties (essentially, people who write user-coded iterator, or >are intense users of iterators as "stream of data", of standard library >module itertools, etc) are welcome to read, and possibly comment on, a new >PEP on copyable iterators, see: > >http://www.python.org/peps/pep-0323.html > >The PEP is currently at revision 1.2, having already been amended and vastly >extended as a consequence of discussions on these issues on python-dev. > > Ah, an easy choice for a change. A definite +1 and no comments from me. With my best regards, G. Rodrigues From demoss at random-state.net Sat Oct 25 08:09:50 2003 From: demoss at random-state.net (Nikodemus Siivola) Date: Sat, 25 Oct 2003 12:09:50 +0000 (UTC) Subject: Python from Wise Guy's Viewpoint References: <3f972315$1@news.unimelb.edu.au> <1eLlb.2151$ao4.8213@attbi_s51> <0Mqmb.23163$Tr4.48699@attbi_s03> Message-ID: In comp.lang.lisp Marshall Spight wrote: > I'm having a hard time following you. I have a guess about this. You seem -- by your references to Python -- to be implicitly assuming that Pascal, Joe &co are setting up Python as the lightbearer of dynamism. I find this rather unlikely, as most -- if not all -- of the pro-dynamic side of this argument hail from Lisp, not Python. Just a datapoint, since there seemed to be an unstated misunderstanding there. Cheers, -- Nikodemus From fjh at cs.mu.oz.au Fri Oct 31 08:16:06 2003 From: fjh at cs.mu.oz.au (Fergus Henderson) Date: Fri, 31 Oct 2003 13:16:06 GMT Subject: Python from Wise Guy's Viewpoint References: <_8Ekb.7543$pT1.318@twister.nyc.rr.com> <3f972315$1@news.unimelb.edu.au> <3638acfd.0310230039.306b14f@posting.google.com> <3f9d556c$1@news.unimelb.edu.au> <3f9f8f49$1@news.unimelb.edu.au> <3f9fe9b1$1@news.unimelb.edu.au> Message-ID: <3fa26092$1@news.unimelb.edu.au> Lex Spoon writes: >Fergus Henderson writes: >>[someone wrote:] >>>Why? If the collection happens to contain only elements of a single type >>>(or this type at most), you only need to check write accesses if they >>>violate this condition. As long as they don't, you don't need to check >>>read accesses. >> >> So which, if any, implementations of dynamic languages actually perform such >> optimizations? > >I'm sure every implementation does this "optimization", because it is >simply less code. You're wrong. I think you misunderstood what optimization I'm talking about. >The only time you get a dynamic type error are: > > 1. You try to call a method, but the object has no such method. Calling a method is a read access. We were discussing optimizations that ensure that you *don't* need to do a dynamic check for each read access. >If you are simply doing "x := y" then there is no checking required. Yes, we covered that already. But that's not what is happening in the scenario that I was describing. The scenario that I'm describing is Collection c; ... foreach x in c do use(x); where use(x) might be a method call, a field access, or similar. For example, perhaps the collection is a set of integers, and you are computing their sum, so use(x) would be "sum += x". I think that in these situations, dynamically typed language implementations will do O(N) dynamic type checks, where N is the number of elements in "c". In theory it is possible to optimize these away, but I don't know of any such implementations that do, and I would be suprised if there are any (except perhaps in limited cases, e.g. when the collection is an array or is implemented using an array). >Regarding your earlier question, though, the great trick in Self was >to remember the result of a check and thus avoid doing it again >whenever possible. If you do "y := x + 1", and you determine that "x" >is a floating point number, then you know that "y" will also be a >floating point number immediately afterwards. Sure. That helps an implementation avoid checking the type of the collection "c" at every element access. But it doesn't help the implementation avoid checking the type of the element "x" at each iteration of the loop. >This points to a general observation. Dealing with the #1 style >dynamic type errors is a subset of dealing with dynamic dispatch in >general. [....] any optimizations that get rid of these dynamic lookups, >will also get rid of type checks just by their nature. That's true. But the difference between dynamically typed languages and statically typed languages is that in dynamically typed languages, *every* data access (other than just copying data around) involves a dynamic dispatch. Sure, implementations can optimize a lot of them away. But generally you're still left lots that your implementation can't optimize away, but which would not be present in a statically typed language, such as the O(N) dynamic type checks in the example above. -- Fergus Henderson | "I have always known that the pursuit The University of Melbourne | of excellence is a lethal habit" WWW: | -- the last words of T. S. Garp. From dthierbach at gmx.de Mon Oct 27 06:13:43 2003 From: dthierbach at gmx.de (Dirk Thierbach) Date: Mon, 27 Oct 2003 12:13:43 +0100 Subject: Python from Wise Guy's Viewpoint References: Message-ID: <78bv61-h75.ln1@ID-7776.user.dfncis.de> prunesquallor at comcast.net wrote: > Dirk Thierbach writes: > As I mentioned earlier in this thread, the two things I object to in a > static type system are these: > > 1) The rejection of code I know to be useful, yet the system is > unable to prove correct. > > 2) The requirement that I decorate my program with type > information to give the type checker hints to enable it > to check things that are, to me, obviously correct. Yes. I have also said it earlier, but (1) is nearly never going to happen (if you substitute "correct" with "type correct", and for a suitable definition of useful), and you don't have to do (2) if there is type inference. > Being unable to prove code correct is the same thing as being able to > prove it incorrect. This makes three classes of code: > > 1) provably type safe for all inputs > 2) provably erroneous for all inputs > 3) neither of the above > > Both dynamic and static type systems behave the same way for classes 1 > and 2 except that static systems reject the code in section 2 upon > compilation while dynamic systems reject it upon execution. It is > section 3 that is under debate. > Those of us that are suspicious of static typing believe that there > are a large enough number of class 3 programs that they will be > regularly or frequently encountered. Yep. The static typers believe (from experience) that there is a very small number of class 3 programs, and usually all programs you normally write fall into class 1. They also know that this is not true for all static type systems. For languages with a lousy static type system, there is a large number of class 3 programs, where you have to cheat to convince the type checker that they are really type safe. The static typers also believe that with a good static type system, all useful class 3 programs can be changed just a little bit so they fall into class 1. In this process, they will become better in almost all cases (for a suitable definition of "better"). > We believe that a large number of these class 3 programs will have > inputs that cannot be decided by a static type checker but are > nonetheless `obviously' correct. (By obvious I mean fairly apparent > with perhaps a little thought, but certainly nothing so convoluted > as to require serious reasoning.) Why do you believe this? A HM type checker doesn't do anything but automate this "obvious" reasoning (in a restricted field), and points out any errors you might have made (after all, humans make errors). > Static type check aficionados seem to believe that the number of class > 3 programs is vanishingly small and they are encountered rarely. They > appear to believe that any program that is `obviously' correct can be > shown to be correct by a static type checking system. Conversely, > they seem to believe that programs that a static type checker find > undecidable will be extraordinarily convoluted and contrived, or > simply useless curiosities. Yes. > No one has offered any empirical evidence one way or another, but the > static type people have said `if class 3 programs are so ubiquitous, > then it should be easy to demonstrate one'. I'll buy that. Some of > the people in here have offered programs that take user input as an > example. No sane person claims to read the future, so any statically > typed check program would have to perform a runtime check. Yes, and that's what it does. No problem. > I (and Don Geddis) happen to believe that there are a huge number of > perfectly normal, boring, pedestrian programs that will stymie a > static type checker. I've been offering a few that I hope are small > enough to illustrate the problem and not so contrived as to fall into > the `pointless' class. > > The first program I wrote (a CPS lookup routine) generally confuses > wimp-ass static type checking like in Java. > > Stephan Bevan showed that SML/NJ had no problem showing it was type > safe without giving a single type declaration. I find this to be > very cool. Good. > I offered my `black hole' program and got these responses: [...] > Will this the response for any program that does, in fact, fool a > number of static type checkers? No. You have also been shown that it can check statically both in Haskell and OCaml. (I cannot think of any way to make it pass in C++ or Java, but that's to be expected.) > This appears to be getting very close to arguing that static type > checkers never reject useful programs because, by definition, a > program rejected by a static type checker is useless. It may not be useless, but you will definitely need to think about it. And if it is useful, in nearly all cases you can make a little change or express it a little differently, and it will check. > Another one was a CPS routine that traverses two trees in a lazy > manner and determins if they have the same fringe. The point was not > to find out if this could be done in SML or Haskell. I know it can. > The point was to find out if the static type checker could determine > the type safety of the program. > There is a deliberate reason I did not create a `lazy cons' > abstraction. I wanted to see if the type checker, with no help > whatsover, could determine that the type of the lambda abstractions > that are *implementing* the lazy consing. See below for "lazy cons". > Re-writing the program in C++ with huge amounts of type decorations > and eliminating the lambdas by introducing parameterized classes does > not demonstrate the power of static type checking. No, it doesn't. That was just Brian saying "it's so easy, I'll do it the hard way and demonstrate that it can even be done with a lousy static type system as in C++". > Re-writing the program in a lazy language also does nothing to > demonstrate the power of static type checking. May I suggest that you try it yourself? It might be a good way to get some experience with OCaml, though for a beginner it might take some time to get used to the syntax etc. Pure lambda terms are the same in every functional language, after all. The only issue is that one should use datatypes for recursive structures, i.e. one would normally use a 'lazy cons' abstraction (which would be the natural thing to do anyway). In OCaml, you can get around this with -rectypes (someone has already demonstrated how to do lazy lists in this way). In Haskell you would need them, but since Haskell is already lazy, that's probably not the point. So yes, for recursive types you need to give the type checker "a little hint", if you want to put it that way. But that's done on purpose, because it is the natural way to do it, and it is note done because it would be impossible to statically check such terms. So if you are extremely picky, and if you refuse to do the "lazy cons" initially and consider command line options cheating, that's one of the programs of class 3 that can be put into class 1 by making a little change, where this change turns out to make your program better to understand in the first place. Is this so bad that you want to stay clear from static typing at any price? (I bet someone will now comment on that ignoring the "extremely picky" part :-( .) - Dirk From bkelley at wi.mit.edu Thu Oct 23 14:37:57 2003 From: bkelley at wi.mit.edu (Brian Kelley) Date: Thu, 23 Oct 2003 14:37:57 -0400 Subject: Why don't people like lisp? In-Reply-To: <20031023160206.GW1454@mapcar.org> References: <3f96b046$0$556$b45e6eb0@senator-bedfellow.mit.edu> <20031022234546.GS1454@mapcar.org> <3f97eb1f$0$573$b45e6eb0@senator-bedfellow.mit.edu> <20031023160206.GW1454@mapcar.org> Message-ID: <3f981fc4$0$575$b45e6eb0@senator-bedfellow.mit.edu> Matthew Danish wrote: > I would see this as a dependence on an implementation artifact. This > may not be regarded as an issue in the Python world, though. As people have pointed out, I am abusing the C-implementation quite roundly. That being said, I tend to write proxies/models (see FileSafeWrapper) that do the appropriate action on failure modes and don't leave it up the garbage collector. Refer to the "Do as I Do, not as I Say" line of reasoning. > This is not to say that Python couldn't achieve a similar solution to > the Lisp one. In fact, it could get quite nearly there with a > functional solution, though I understand that it is not quite the same > since variable bindings caught in closures are immutable. And it would > probably be most awkward considering Python's lambda. I don't consider proxies as "functional" solutions, but that might just be me. They are just another way of generating something other than the default behavior. Python's lambda is fairly awkward to start with, it is also slower than writing a new function. I fully admit that I have often wanted lambda to be able to look up variables in the calling frame. foo = lambda x: object.insert(x) object = OracleDatabase() foo(x) object = MySqlDatabase() foo(x) But in practice I never write lambda's this way. I always bind them to a namespace (in this case a class). class bar: def some_fun(x): foo = lambda self=self, x: self.object.insert(x) foo(x) Now I could use foo on another object as well. foo(object, x) > I'm not sure I understand this paragraph. The macro only executes the > body code if the file is successfully opened. The failure mode can be > specified by a keyword argument. I can explain what I meant with an example: suppose you wanted to tell the user what file failed to open/write and specify a new file to open. You will have to write a handler for this and supply it to (with-open-file ...) or catch the error some other way. > Not sure what `using macros as a default handler' means. Apologies, I meant to say that writing a macro to handle particular exceptions in a default-application wide way is a good thing and appropriate. > The WITH-OPEN-FILE macro is not really an example of a macro that > performs something unique. It is, I find, simply a handy syntactic > abstraction around something that is more complicated than it appears at > first. And, in fact, I find myself creating similar macros all the time > which guide the use of lower-level functions. Right. I'm was only trying to point out, rather lamely I might add, that the macros I have been seeing I would solve in an object-oriented manner. This might simply be because python doesn't have macros. But I like the thought of "here is your fail-safe file object, use it however you like". It is hard for me to say which is 'better' though, I tend to use the language facilities available (and abuse them as pointedly stated), in fact it took me a while to realize that (with-open-file) was indeed a macro, it simply was "the way it was done(TM)" for a while. Certainly, new (and old) users can forget to use their file I/O in the appropriate macro as easily as forgetting to use try: finally: In python I use my FileSafeWrapper(...) that ensures that the file is properly closed on errors and the like. As I stated, this wasn't handed to me by default though like I remember as (with-file-open ...) was from my CHLS days. So let me ask a lisp question. When is it appropriate to use a macro and when is it appropriate to use a proxy or polymorphism? Perhaps understanding this would break my macro stale-mate. p.s. given some of the other posts, I am heartened by the civility of this particular thread. From rpw3 at rpw3.org Fri Oct 10 08:26:11 2003 From: rpw3 at rpw3.org (Rob Warnock) Date: Fri, 10 Oct 2003 07:26:11 -0500 Subject: Python syntax in Lisp and Scheme References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> Message-ID: Andrew Dalke wrote: +--------------- | (and yes, I know about the lawsuit against disk drive manufacturors | and their strange definition of "gigabyte"... ) +--------------- Oh, you mean the fact that they use the *STANDARD* international scientific/engineering notation for powers of 10 instead of the broken, never-quite-right-except-in-a-few-cases pseudo-binary powers of 10?!?!? [Hmmm... Guess you can tell which side of *that* debate I'm on, eh?] The "when I write powers of 10 which are 3*N just *asssume* that I meant powers of 2 which are 10*N" hack simply fails to work correctly when *some* of the "powers of 10" are *really* powers of 10. It also fails to work correctly with things that aren't instrinsically quantized in powers of 2 at all. Examples: I've had to grab people by the scruff of the neck and push their faces into the applicable reference texts before they believe me when I say that gigabit Ethernet really, really *is* 1000000000.0 bits per second [peak payload, not encoded rate], not 1073741824, and that 64 kb/s DS0 telephone circuits really *are* 64,000.0 bits/sec, not 65536. [And, yes, 56 kb/s circuits are 56000 bits/sec, not 57344.] Solution: *Always* use the internationally-recognized binary prefixes when that's really what you mean, and leave the old scientific/engineering notation alone, as pure powers of 10. [Note: The historical notes on that page are well worth reading.] -Rob p.s. If you're hot to file a lawsuit, go after the Infiniband Trade Association for its repeated claims that 4x IB is "10 Gb/s". It isn't, it's 8 Gb/s [peak user payload rate, not encoded rate]. Go read the IBA spec if you don't believe me; it's right there. ----- Rob Warnock 627 26th Avenue San Mateo, CA 94403 (650)572-2607 From anuradha.k.r at sify.com Fri Oct 10 01:02:03 2003 From: anuradha.k.r at sify.com (anuradha.k.r at sify.com) Date: 9 Oct 2003 22:02:03 -0700 Subject: server side socket program hangs References: <57efaf35.0309260215.5ddd5734@posting.google.com> <3f74571f$0$20952$7a628cd7@news.club-internet.fr> Message-ID: <57efaf35.0310092102.1231b120@posting.google.com> hi, was stuck with another work.now bac to python program. i tried out using PORT = socket.htons(9999) it still doesn't work.here is the code.it still hangs.can some one tell me what could be te problem? #from socket import * import socket import sys HOST = '' #any address PORT = socket.htons(9222) #same port address as client class Sock: def __init__ (self,parent): try: self.s = socket(AF_INET,SOCK_STREAM) except socket.error: print 'socket not created' try: self.s.bind((HOST,PORT)) except self.error: print 'error in bind' try: self.s.listen(5) except self.error: print 'error in listen' conn, addr = self.s.accept() # print 'Connected by',`addr` while 1: data = conn.recv(1024) if not data: break conn.send(data) conn.close() thanx, AKR. "Anthony McDonald" wrote in message news:<3f74571f$0$20952$7a628cd7 at news.club-internet.fr>... > wrote in message > news:57efaf35.0309260215.5ddd5734 at posting.google.com... > > hi, > > i am writing a socket program in python,both client side and server > > side.I've written the client side which is working perfectly > > fine(checked it against server program written in C).but as for my > > server program written in python it simply hangs.it does not show any > > error also.I've tried sample programs available .I don understand what > > the reason is as i am quite new to it. > > here is teh server side program: > > > > /////////////////////// > > from socket import * > > import socket > > import sys > > > > HOST = '' #any address > > PORT = htons(9999) #same port address as client > > > > > > > can someone tell me what the problem is? > > Your applying a function designed to simplyfy transfering IP addresses to a > literal value you want to use for your port. The following should show the > effect thats now happening. > > PythonWin 2.3.1 (#47, Sep 23 2003, 23:47:32) [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 socket > >>> socket.htons(9999) > 3879 > >>> From fraser.gordon at cognos.com Thu Oct 2 10:45:54 2003 From: fraser.gordon at cognos.com (Fraser Gordon) Date: 2 Oct 2003 07:45:54 -0700 Subject: Simultaneous output parsing of child process? Message-ID: Hello, Hopefully someone can help me out with this issue... I have a python script that needs to run a shell command and be able to react to output from that command as it occurs (as opposed to waiting for the whole command to complete and then parsing the output). Is this possible with Python? I created a test script that prints a line of output to stdout every 4 seconds or so. I want to create a "parent" script that kicks off the test script, and prints data as soon as the test script sends anything to the standard output (ie. every 4 seconds). Furthermore, the solution needs to support Windows, several flavors of UNIX and potentially LINUX. I would ideally like to have the following type of behaviour: childPipe = kickOffChild('test.py') while : line = childPipe.checkForStdOutput() if line: # This should trigger once every 4 seconds in the example above print "OUTPUT:", line print "Process completed." Any help would be greatly appreciated. Fraser From edreamleo at charter.net Mon Oct 13 11:23:14 2003 From: edreamleo at charter.net (Edward K. Ream) Date: Mon, 13 Oct 2003 10:23:14 -0500 Subject: ANN: Leo 4.0 beta 4 outlining editor Message-ID: Leo 4.0 beta 4 is now available at: http://sourceforge.net/projects/leo/ This is the fourth public release of Leo 4.0. There are no known serious bugs in this version of Leo. This will be the last beta release before 4.0 final. N.B. 4.0 introduces new file formats. Please make full backups of important files. Highlights of 4.0 beta 4 ------------------------ - Changed all instances of string.letters to string.ascii_letters. string.letters can cause crashes in some locales (Unicode environments). - Fixed several bugs that caused clone marks not to be set properly. Highlights of 4.0 beta 3 ------------------------ - Fixed problems with setting Leo's window icons. - Plugins may now save their own information in and elements in .leo files. - The usual assortment of bug fixes and minor improvements. Highlights of 4.0 beta 2 ------------------------ * Fixed several bugs: - Fixed problems with reading and writing 4.0 derived files. - Fixed several Unicode-related bugs. - Fixed a crasher in the Go To Line Number command. - Fixed a problem with Importing Python files. * Important improvements: - Added allow_clone_drags setting that allows Leo to be used with Aqua. - When running Python 2.3 Leo can now create window icons without third-party packages. - The usual minor improvements and bug fixes. Highlights of 4.0 beta 1 ------------------------ * Improved and simplified format of derived files. - Eliminated child indices, extraneous blank lines and @body sentinels. - Eliminated @node sentinels that indicate outline structure. - New @nl and @nonl sentinels indicate where newlines are and aren't. - These changes largely eliminate unwanted cvs conflicts. * Greatly improved error handling. - Reading derived files _never_ alters outline structure or links. - Read errors leave the outline completely unchanged. - Broken clone links are gone forever. - As a result, using 4.0 is much safer than all previous versions. * Full compatibility will previous versions of Leo. - Leo reads all derived files properly, regardless of version. - Leo writes new-format derived files by default, and this default may be changed. * New commands: - Write 3.x Derived File and Write 4.x Derived File commands. - Import Derived File command. - Clear Recent Files command. * Several new plugins. Quote of the month ------------------ I've written documentation in WordPerfert, Ventura, Word, PageMaker, and FrameMaker and even though they create wonderfully looking and useful documents, they've never been able to do what I've been looking for. HTML, compiled help files, and later PDF came closer, but still not there. I think I've found it in Leo, a way to make a "living" document. A document built out of discrete parts that can be re-organized on the fly to meet the needs of a varying audience...Being a convert for less than a day I've still got a lot to learn, but just the possibility of keeping system maintenance scripts in the IT manual is mind boggling. -- David Nichols What is Leo? ------------ - A programmer's editor, an outlining editor and a flexible browser. - A literate programming tool, compatible with noweb and CWEB. - A data organizer and project manager. Leo provides multiple views of projects within a single outline. - Fully scriptable using Python. Leo saves its files in XML format. - Portable. leo.py is 100% pure Python. - Open Software, distributed under the Python License. Leo requires Python 2.1 or above and tcl/tk 8.3 or above. Leo works on Linux, Windows and MacOs X. Links: ------ Leo: http://webpages.charter.net/edreamleo/front.html Home: http://sourceforge.net/projects/leo/ Download: http://sourceforge.net/project/showfiles.php?group_id=3458 CVS: http://sourceforge.net/cvs/?group_id=3458 Wiki: http://leo.hd1.org/ Edward K. Ream October 13, 2003 -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: Literate Editor with Outlines Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From imbosol at aerojockey.invalid Wed Oct 15 03:10:58 2003 From: imbosol at aerojockey.invalid (Carl Banks) Date: Wed, 15 Oct 2003 07:10:58 GMT Subject: assignment expression peeve References: <7x1xtfkuky.fsf@ruckus.brouhaha.com> Message-ID: <6q6jb.10882$fv4.3354@nwrdny02.gnilink.net> Paul Rubin wrote: > Without assigment expressions, it gets unspeakably ugly. The designers of Python believe that assignment expressions are bad news (which I agree with), and they will NEVER make assigments into expressions just to avoid this little problem. Frankly, I think assignment expressions would cause far more unspeakable ugliness than they would prevent. There's workarounds. Live with them. -- CARL BANKS http://www.aerojockey.com/software As the newest Lady Turnpot descended into the kitchen wrapped only in her celery-green dressing gown, her creamy bosom rising and falling like a temperamental souffle, her tart mouth pursed in distaste, the sous-chef whispered to the scullery boy, "I don't know what to make of her." --Laurel Fortuner, Montendre, France 1992 Bulwer-Lytton Fiction Contest Winner From jjl at pobox.com Sat Oct 4 21:02:30 2003 From: jjl at pobox.com (John J. Lee) Date: 05 Oct 2003 02:02:30 +0100 Subject: python & debian References: Message-ID: <87r81s5wex.fsf@pobox.com> "Enrique" writes: > After several years using windows, now i'm trying debian OS. > In windows i use pythonwin or activepython by the facility of a windows > environment, code completion, dot lists, and a easy help in activepython. > > There is something similar to install under linux?? i`m a newbie. IDE == Integrated Development Environment is the term you want. Too many to list. Use Google Groups to search this group -- something like: IDEs linux group:comp.lang.python Plain old Google will also turn up links. John From sross at connectmail.carleton.ca Sun Oct 12 13:36:41 2003 From: sross at connectmail.carleton.ca (Sean Ross) Date: Sun, 12 Oct 2003 13:36:41 -0400 Subject: private variables/methods References: <3F856275.C884CE5@engcorp.com> Message-ID: <3ogib.657$cT6.27058@news20.bellglobal.com> "Alex Martelli" wrote in message news:Iseib.204801$hE5.6891483 at news1.tin.it... > >> I think that __current_module__ is perhaps a bit too lengthy > > > > and redundant ;-) > > I disagree. Lengthy it may be, but we do want a 'reserved module > name' to use for this purpose. For a normal import instruction to > work, and to work just as well if you cut and paste the same function > elsewhere, I think we want to define that "import somespecificname" is > importing THIS module, the CURRENT module, under that name (or another > specified with 'as'). This can be experimented with easily, by changing > the builtin __import__ (or setting an import hook, maybe) in site-specific > file; and if it catches on the builtin __import__ could easily be customized > to perform the same task quite speedily. Hi. I'm not sure I'm clear on what behaviour "import __current_module__" is expected to have. There's a bit more to follow but I'll ask my main question up front so we're clear: "Which of the following behaviours is preferred?" I've been playing with some code, using my own pet global workaround, and I'm not sure if it's accomplishing the correct behaviour. The results are certainly not the same as yours. in fact, I think the behaviour of my version may be unexpected and dangerous ... If inside module A you import a function f() from another module B that tries to use the current module directly, rather than global, to set variables and you call that function (i.e., B.f()), my version will affect the values of A's global variables whereas yours does not. For example, here is some output from a test run of each method. The code for all of this will be posted at the bottom of this message. Note: I've added some print statements to your code. # Output of running setglobal1.py using import __current_module__ setglobal1.x = 23 ENTERING setglobal1.set_the_global() global x = 23 set __current_module__.x = 45 global x = 45 EXITING setglobal1.set_the_global() ENTERING setglobal2.set_the_global() global x = 57 set __current_module__.x = 88 global x = 88 EXITING setglobal2.set_the_global() setglobal1.x = 45 # Output of running main1.py using import __main__ main1.x = 23 ENTERING main1.foo() global x = 23 set main.x = 45 global x = 45 EXITING main1.foo() ENTERING main2.foo() global x = 57 main2.x = 45 set main.x = 88 global x = 57 EXITING main2.foo() main1.x = 88 As you can see, setglobal1.x = 45 in your version, but my analogous variable main1.x = 88. Here's the code: #============================================== # site.py import __builtin__, sys _base_import = __builtin__.__import__ def __import__(name, *args): if name == '__current_module__': name = sys._getframe(1).f_globals['__name__'] return _base_import(name, *args) __builtin__.__import__ = __import__ # end of part to be executed once #=============================================== # setglobal1.py import setglobal2 x = 23 def set_the_global(): print "ENTERING setglobal1.set_the_global()" import __current_module__ global x print "global x = %s"%x __current_module__.x = 45 print "set __current_module__.x = %s"%__current_module__.x print "global x = %s"%x print "EXITING setglobal1.set_the_global()" if __name__ == "__main__": print "setglobal1.x = %s"%x set_the_global() setglobal2.set_the_global() print "setglobal1.x = %s"%x #=============================================== # setglobal2.py x = 57 def set_the_global(): print "ENTERING setglobal2.set_the_global()" import __current_module__ global x print "global x = %s"%x __current_module__.x = 88 print "set __current_module__.x = %s"%__current_module__.x print "global x = %s"%x print "EXITING setglobal2.set_the_global()" if __name__ == "__main__": print "setglobal2.x = %s"%x set_the_global() print "setglobal2.x = %s"%x # And now my version: #=============================================== # main1.py import main2 x = 23 def foo(): print "ENTERING main1.foo()" import __main__ as main global x print "global x = %s"%main.x main.x = 45 print "set main.x = %s"%main.x print "global x = %s"%x print "EXITING main1.foo()" if __name__ == "__main__": print "main1.x = %s"%x foo() main2.foo() print "main1.x = %s"%x #=============================================== # main2.py x = 57 def foo(): print "ENTERING main2.foo()" import __main__ as main global x print "global x = %s"%x print "main2.x = %s"%main.x main.x = 88 print "set main.x = %s"%main.x print "global x = %s"%x print "EXITING main2.foo()" if __name__ == "__main__": print "main2.x = %s"%x foo() print "main2.x = %s"%x Thanks for your time, Sean From wujek at wujek.com Fri Oct 3 12:05:26 2003 From: wujek at wujek.com (Wujek) Date: Fri, 03 Oct 2003 18:05:26 +0200 Subject: List to dict conversion In-Reply-To: References: Message-ID: Emile van Sebille wrote: > Guessing that this may have been read from a file, you may also be Indeed. > interested in looking at ConfigParser. From the module: Data will be read from number of small files. ConfigParser is too big gun for this fly, I think. This oneliner (from previous posts in this thread) is much better for this task. Regards. From mbrubeck at cs.hmc.edu Tue Oct 7 20:08:52 2003 From: mbrubeck at cs.hmc.edu (Matt Brubeck) Date: 7 Oct 2003 17:08:52 -0700 Subject: Class instantiation question References: Message-ID: Todd Johnson wrote: > Ok, say I have a class MyClass and an __init__(self, > a, b) Say that a and b are required to be integers > for example. So my init looks like: > > __init__(self, a, b): > try: > self.one = int(a) > self.two = int(b) > except ValueError: > #nice error message here > return None > > I have even tried a similar example with if-else > instead of try-except, but no matter what if I call > > thisInstance = MyClass(3, "somestring") > > it will set self.one to 3 and self.two will be > uninitialised. The behavior I am hoping for, is that > thisInstance is not created instead(or is None). How > do I get the behavior I am looking for? Here's one option: >>> class C: ... def __init__(self, a): ... self.a = int(a) ... >>> c = C("hello") Traceback (most recent call last): File "", line 1, in ? File "", line 3, in __init__ ValueError: invalid literal for int(): hello This also allows the following: >>> try: c = C("hello") ... except ValueError: c = None ... >>> print c None If you really want initialization to return None instead of raising an exception, you can override the __new__ method of a new-style class: >>> class C(object): ... def __new__(cls, a): ... try: a = int(a) ... except ValueError: return None ... return object.__new__(cls, a) ... def __init__(self, a): ... self.a = a ... >>> c = C(1) >>> c.a 1 >>> c = C("hello") >>> print c None From max at cNvOiSsiPoAnMtech.com Wed Oct 29 17:22:13 2003 From: max at cNvOiSsiPoAnMtech.com (Maxim Khesin) Date: Wed, 29 Oct 2003 22:22:13 GMT Subject: lightweight human-readable config? Message-ID: I want to have a config file with my python proggie, satisfying the following requirements: 1) support key->(value, default) 2) simple and intuitive to read and edit 3) easyly readable into a python datastructure (a dictionary?) 4) not requiring any heavy libraries needed (I am distributing my proggie as a py2exe executable and do not want to bloat the size) can you guys suggest some format for this? thanks, max From gerrit at nl.linux.org Tue Oct 7 09:19:05 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Tue, 7 Oct 2003 15:19:05 +0200 Subject: Newbie needs to see a large project In-Reply-To: References: <9Clgb.12141$sw6.8259@newssvr25.news.prodigy.com> Message-ID: <20031007131904.GA9306@nl.linux.org> > Google may not be a large business app, it surely is a huge database, > and the performance of Google is excellent. It's a pity they don't > mention what they use Python for. Google is so large, they probably use everything. I have heard they use Ruby. They surely use C. They probably use Java too, and PHP. And Perl. And other languages... Gerrit. -- Mozilla _is_ the web: it grows faster than you can download it. 1011001 1101111 1110101 1110010 1110011 0101100 1000111 1100101 1110010 1110010 1101001 1110100 From tjreedy at udel.edu Wed Oct 15 10:40:20 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 15 Oct 2003 10:40:20 -0400 Subject: else on the same line - howto References: Message-ID: "Helmut Jarausch" wrote in message news:bmj859$iph$1 at nets3.rz.RWTH-Aachen.DE... > Since Python lacks conditional expression > like > > k+= (dy >= 0 ? 1 : -1) For this specific example: k+= (dy >= 0 and 1 or -1) But don't do this unless and until you 1) understand why this works and why the and branch must be non-null and what happens if it is null (this is discussed both in the FAQ and PEP 308) AND 2) accept responsibility for always remembering the caution. Terry J. Reedy From tcronj at ananzi.co.za Thu Oct 2 20:46:12 2003 From: tcronj at ananzi.co.za (tertius) Date: Fri, 03 Oct 2003 02:46:12 +0200 Subject: append special chars with "\" In-Reply-To: <3f793544$0$64721@hades.is.co.za> References: <3f793544$0$64721@hades.is.co.za> Message-ID: tertius wrote: > Is there a better way to append certain chars in a string with a > backslash that the example below? > > chr = "#$%^&_{}" # special chars to look out for > str = "123 45^ & 00 0_" # string to convert > n = "" # init new string > for i in str: > if i in chr: # if special character in str > n+='\\' # append it with a backslash > n+=i > print "old:",str > print "new:",n > > > Thanks > Tertius > I meant *pre*-pend... but the msg got accross. Thanks all!! From rajarshi at presidency.com Wed Oct 8 13:42:19 2003 From: rajarshi at presidency.com (Rajarshi Guha) Date: Wed, 08 Oct 2003 13:42:19 -0400 Subject: splitting a list into n groups Message-ID: Hi, is there an efficient (pythonic) way in which I could split a list into say 5 groups? By split I mean the the first x members would be one group, the next x members another group and so on 5 times. (Obviously x = lengthof list/5) I have done this by a simple for loop and using indexes into the list. But it does'nt seemm very elegant Thanks, From adalke at mindspring.com Thu Oct 9 17:01:49 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Thu, 09 Oct 2003 21:01:49 GMT Subject: Python syntax in Lisp and Scheme References: <8CVgb.8$KR3.1846@typhoon.nyu.edu> Message-ID: <11khb.4433$dn6.944@newsread4.news.pas.earthlink.net> Pascal Costanza: > Here [are some studies on using Scheme to teach programming]: > http://home.adelphi.edu/sbloch/class/hs/testimonials/ Actually, those are testimonials, not studies. For real studies, look at some of the Smalltalk and especially Papert's work with Logo. The problem with testimonials is they are submitted by the people who liked the language. Eg, you don't see testimonials for a diet loss plan which go "I used this plan and I gained 30 pounds in only two weeks -- I loved it!" One of my house mates in grad school learned Scheme at CMU and related how much he didn't like the language. You don't see his testimonial on this site because he didn't dislike it intensely enough to write an essay and convince some pro-Scheme site to host it. Andrew dalke at dalkescientific.com From cliechti at gmx.net Fri Oct 31 21:19:52 2003 From: cliechti at gmx.net (Chris Liechti) Date: 1 Nov 2003 04:19:52 +0200 Subject: Windows 2000 service app References: Message-ID: "Tomas Christiansen" wrote in news:bnur0d$gib$1 at news.cybercity.dk: > Need a simple, robust way to make a Python-app act as a real service in > Windows 2000 (so that it can be started/stopped with NET START/STOP). > > Can someone with experience on this topic give a bid? no experience here, but the py2exe examples seem to have a working service with start/stop commands. (saw that in the 0.5 prerelease) chris -- Chris From fredrik at pythonware.com Wed Oct 29 16:16:30 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 29 Oct 2003 22:16:30 +0100 Subject: different ways to creating two lists from one References: Message-ID: Todd MacCulloch wrote: > But suppose generating s0 is expensive and/or s0 is big. In otherwords I'd > like to go over only once and I don't want to keep it around any longer than > I have to. > > I could do something like: > > for a, b in [(x + x, x * x) for x in s0]: > s1.append(a) > s2.append(b) ouch. > Is there a better / cleaner way that I'm missing? for x in s0: s1.append(x + x) s2.append(x * x) del s0 (memorywise, that's no better than your first alternative. it's a better than your second alternative, though...) if s0 contains large and ugly things, you could do something like this: for i, x in enumerate(s0): s1.append(x + x) s2.append(x * x) s0[i] = None From costanza at web.de Thu Oct 23 11:03:17 2003 From: costanza at web.de (Pascal Costanza) Date: Thu, 23 Oct 2003 17:03:17 +0200 Subject: Python from Wise Guy's Viewpoint In-Reply-To: <87ekx4xaym.dlv@wanadoo.fr> References: <_8Ekb.7543$pT1.318@twister.nyc.rr.com> <3f972315$1@news.unimelb.edu.au> <3638acfd.0310230039.306b14f@posting.google.com> <87ekx4xaym.dlv@wanadoo.fr> Message-ID: Remi Vanicat wrote: > Pascal Costanza writes: >>In a statically typed language, when I write a test case that calls a >>specific method, I need to write at least one class that implements at >>least that method, otherwise the code won't compile. > > Not in ocaml. > ocaml is statically typed. How does ocaml make sure that you don't get a message-not-understood exception at runtime then? Pascal -- Pascal Costanza University of Bonn mailto:costanza at web.de Institute of Computer Science III http://www.pascalcostanza.de R?merstr. 164, D-53117 Bonn (Germany) From mike420 at ziplip.com Mon Oct 13 14:50:23 2003 From: mike420 at ziplip.com (mike420 at ziplip.com) Date: Mon, 13 Oct 2003 11:50:23 -0700 (PDT) Subject: Python syntax in Lisp and Scheme Message-ID: Alex Martelli wrote: > > Preprocessors and macro processors may do different amounts of, say, > "introspection" on their arguments. From the point of view of how to > hack a preprocessor in front of the Python interpreter, that matters > zilch. What DOES matter, of course, is that the language/metalanguage > confusion becomes a bit harder (but far from impossible) to architect into > a preprocessor that's supposed to receive text as input and hand text back > to the following phase[s], rather than working on (e.g.) AST kinds that > are in common with other phases (and s-exprs are such) -- but plugging a > parser in front of a custom preprocessor and a code formatter as its > tail is hardly impossible, if that's how you want your macros to work. > Based on your comments, I still think you do not understand macros. It is probably my fault for not explaining them well enough. An *external* preprocessor, no matter what sophisticated parsing, etc. it does, can never do the same things macros can do (because it's *external*), it can not access the contents of the running program *image* (values, functions, classes defined). Like I said, I think you just need to take a little break, play with macros if you feel like it, do the exercises in Lisp books. After that, you will at least know what you are talking about (no offense). As to the rudeness of fans of macros: we are not rude, we are curt. And if we are curt with you, it's because time is a factor. 420 P.S. "defense" is *a* correct spelling. Suck on this :-) P.P.S. ARC is a Lisp, and it has macros, how can it be a threat to Lisp? From other at cazabon.com Mon Oct 6 13:45:24 2003 From: other at cazabon.com (Kevin) Date: Mon, 06 Oct 2003 17:45:24 GMT Subject: Printing images through Python References: Message-ID: Thanks for the follow-up Tim, I caught that error after cleaning my glasses. :) I've managed to expand on your example to write a stand-alone module for handling printing PIL images on Windows. Interfacing to the standard Windows printer-setup dialog is beyond me for now, so if you have ANY suggestions I'd appreciate it! I'm planning on includinga simple GUI class that handles sizing/margins/etc., but the standard dialogs would be better (and fuller functionality). You can try the first "test" version of the module at (and I'd appreciate some independent testing to make sure it works with many printer setups): http://www.cazabon.com/python/downloads/WinPILprint.py However, I'll be releasing a much updated version under a different name in the next few days (ImagePrintWin, to follow the PIL module naming convention a little better... hopefully I can convince Fredrik to include the final version with the standard PIL dist.) (Thanks again!) Kevin. "Tim Golden" wrote in message news:mailman.1065427827.16502.python-list at python.org... > > From: Kevin [mailto:other at cazabon.com] > > Sent: 04 October 2003 03:21 > > To: tim.golden at viacom-outdoor.co.uk > > Subject: Re: Printing images through Python > > > > Thanks for the help Tim, seems to work well! > > Only too glad I could save someone the hours of frustrating > search it took me to get that far. > > > One problem I had though, just FYI: > > turned out that printer_resolution[1] was a > > function... have to do more looking to figure out why. > > Blowed if I can see why; it's just the return value from GetDeviceCaps. > Ah... looking at my email to you underneath yours to me, the line has > been chopped (hope this makes it across the email systems) thus: > > printer_resolution [...] = hDC.GetDeviceCaps [unintended line break] > (VERTRES) > > which will make Python think that the second value in > the printer_resolution tuple is the function GetDeviceCaps > and that the (VERTRES) is merely a throwaway value. > It should, of course, read: > > [...] = hDC.GetDeviceCaps (VERTRES) > > where VERTRES is the parameter to GetDeviceCaps > > > I just used [0] for both args and it was fine(for now). > > That'll work because, in any case, the code later on takes > the smaller of the two ratios to determine the scaling factor, > and printer_resolution[0] is the width of the page, which > is going to be the smaller of the two anyway. > > Hope it works out for you. I haven't yet bothered to go > into using the Printer Setup dialogue, which truly is a > pain. I'm using a Pygame interface, so I'm trying to cut > down on Windows-esque dialog boxes. > > 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 http Tue Oct 21 12:01:56 2003 From: http (Paul Rubin) Date: 21 Oct 2003 09:01:56 -0700 Subject: writing code over several lines References: <62e9c66e.0310170556.328072e8@posting.google.com> <3F9531F6.3D1DD233@engcorp.com> <3F9556A3.92F1106C@engcorp.com> Message-ID: <7xd6cqinpn.fsf@ruckus.brouhaha.com> Peter Hansen writes: > Tuples are also not significantly faster than lists, as I recall > from past discussions of this. At least, not to the extent that > it should ever be a consideration when initializing "constant" lists. Tuples probably aren't faster, but they do use less memory. From jaredbox at hotmail.com Wed Oct 8 15:28:05 2003 From: jaredbox at hotmail.com (javahead) Date: 8 Oct 2003 12:28:05 -0700 Subject: ImportError: No module named lang - Serious Jython newbie - Please help! Message-ID: I am trying to write a simple gui in Jython that requires the java.awt and java.lang packages. Apparently, my installation is screwed up because I keep getting the following error message indicating that the language package cannot be found. For some reason I can access the swing package but not lang or awt? >>> import java.lang as lang Traceback (innermost last): File "", line 1, in ? ImportError: No module named lang >>> I am running Windows 2000 along with the following java development environments versions: Sun's J2 sdk v1.4.2 and jdk1.3.1_06 Please help! From bkelley at wi.mit.edu Fri Oct 24 12:06:55 2003 From: bkelley at wi.mit.edu (Brian Kelley) Date: Fri, 24 Oct 2003 16:06:55 GMT Subject: Design Question: GUI+Threads. In-Reply-To: References: <3f97ee4a$0$573$b45e6eb0@senator-bedfellow.mit.edu> Message-ID: Frithiof Andreas Jensen wrote: > Thaks for the reply, > > "Brian Kelley" wrote in message > news:3f97ee4a$0$573$b45e6eb0 at senator-bedfellow.mit.edu... > >>Syver Enstad wrote: >> > > >>You might make your life easier by having the controller and the view be >>on the main thread and dispatch a new model to the work thread. > > > Hmm. I think that makes sense, since it is the GUI that "demands" > attention - I was doing sort-of the other way round by having a thread > dispatching messages to models AND the GUI thread.... > > > I was planning to use of a Dispatcher/Mailbox System: > > The worker thread(S) blocks on an input queue until a message is in that > queue - then the worker thread process the message and places a result in an > output queue. The results in the output queue(s) of each worker are read by > the main thread and placed in the input queues of other workers or in the > GUI.....most of the time a worker will sleep, waiting for work. This seems very doable. You have at least two options: 1) use a wxTimer to periodically tell the controller to check the worker's output queues or 2) have the worker send a new wxEvent to the view with the result data. This could be as simple as: wxEVT_WORKER_RESULT = wxNewEventType() def EVT_WORKER_RESULT(win, func): win.Connect(-1, -1, wxEVT_WORKER_RESULT, func) class WorkerResultEvent(wxPyEvent): def __init__(self, result): wxPyEvent.__init__(self) self.SetEventType(wxEVT_WORKER_RESULT) self.data = data # event wrapper so that the worker thread can send # results class EventWrapper: def __init__(self, window): self.window = window def setResult(self, data): wxPostEvent(self.win, WorkerResultEvent(data)) class WorkerThread(thread): def __init__(self, eventSender): ... def Run(self): ... ... self.eventSender(result) self.blockForNextJob() class View: def __init__(self, controller,...): EVT_WORKER_RESULT(self, self.OnResult) def OnResult(self, evt): self.controller.OnResult(evt.result) A good example of this is in the wxPython thread example. Their view is their controller though. From news at yebu.de Thu Oct 9 04:31:21 2003 From: news at yebu.de (Karl Scalet) Date: Thu, 09 Oct 2003 10:31:21 +0200 Subject: print is not a function In-Reply-To: References: Message-ID: Wolfram Kraus wrote: > Heyho! > > Karl Scalet wrote: > [...] > >> For interactively inspecting things, I think >> having it in one line is nice, as it's >> easiest to recall from commandline history. >> >> Which way?: >> >>> [ pprint(x) for x in locals() if x[:3]=='QAc' ] >> or >> >>> for x in locals(): >> >>> if x[:3] == 'QAc': >> >>> print x >> >> I cannot put this second one in a single line, so I >> will stay with my list-comprehension-solution unless >> I'm getting a better idea. >> >> Karl >> > > Why don't you wrap it in a function and put it in your > $PYTHONSTARTUP-file? That way you can call it very fast and don't need > to remember a one-liner. > > Wolfram > Hello Wolfram, you're right, that would be best. I myself however always end up not having all the helper functions available after a while, working in different environments. But that's more an organizational problem:-) Thanks anyhow, Karl From ramen at lackingtalent.com Thu Oct 9 13:41:17 2003 From: ramen at lackingtalent.com (Dave Benjamin) Date: Thu, 09 Oct 2003 17:41:17 -0000 Subject: Code block literals References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> <92c59a2c.0310031345.57d20631@posting.google.com> Message-ID: In article , Alex Martelli wrote: > Dave Benjamin wrote (answering Mike Rovner): > ... >>> "Explicit is better than implicit" >> >> In that case, why do we eschew code blocks, yet have no problem with the >> implicit invocation of an iterator, as in: >> >> for line in file('input.txt'): >> do_something_with(line) > > I don't see that there's anything "implicit" in the concept that a > special operation works as indicated by its syntax. I.e., I do not > find this construct any more "implicit" in the first line than in > its second one, which is the juxtaposition of a name and a pair of > parentheses to indicate calling-with-arguments -- and alternatives... What's implicit to me is that the use of an iterator is never specified. For instance, we could (and I'm *not* suggesting this) do this: iterator = file('input.txt') while iterator.has_next(): line = iterator.next() do_something_with(line) > This has nothing to do with "eschewing code blocks", btw; code blocks > are not "eschewed" -- they are simply syntactically allowed, as > "suites", only im specific positions. If Python's syntax defined > other forms of suites, e.g. hypothetically: > > with : > > > meaning to call the object (or some given method[s] in it, whatever) > with the suite as its argument, it would be just as explicit as, e.g.: > > for in : > > > or > >() This would be an interesting alternative, but it's back to being a special case, like Ruby has. I think it'd be more flexible as a literal that returns a callable. >> This is not to say that I dislike that behavior; in fact, I find it >> *beneficial* that the manner of looping is *implicit* because you can >> substitute a generator for a sequence without changing the usage. But > > You could do so even if you HAD to say iter() instead of > just after every "for in" -- it wouldn't be any > more "explicit", just more verbose (redundant, boiler-platey). So > I do not agree with your motivation for liking "for x in y:" either;-). Well, let's just say I've been on the Java side of the fence for a little while, and it has redefined my personal definition of explicit. One of the reasons Python code is so much smaller than Java code is that a lot of things are implicit that are required to be explicit in Java. I see this as a good thing. >> there's little readability difference, IMHO, between that and: >> >> file('input.txt').each_line({ |line| >> do_something_with(line) >> }) > > Not huge, but the abundance of ({ | &c here hurts a little bit. Well, we all __pick__ our __poisons__... >> Plus, the first example is only obvious because I called my iteration >> variable "line", and because this behavior is already widely known. What >> if I wrote: >> >> for byte in file('input.dat'): >> do_something_with(byte) >> >> That would be a bit misleading, no? But the mistake isn't obvious. OTOH, >> in the more explicit (in this case) Ruby language, it would look silly: >> >> open('input.txt').each_line { |byte| >> # huh? why a byte? we said each_line! >> } > > Here, you're arguing for redundance, not for explicitness: you are claiming > that IF you had to say the same thing more than once, redundantly, then > mistakes might be more easily caught. I.e., the analogy is with: > > file('foo.txt').write('wot?') > > where the error is not at all obvious (until runtime when you get an > exception): file(name) returns an object *open for reading only* -- so > if you could not call file directly but rather than do say, e.g.: > > file.open_for_reading_only('foo.txt').write('wot?') Nah, I'm not arguing for redundancy at all. I'm saying that there is some voodoo going on here. When the *constructor* for a file object behaves like a generator that loops over newline-delimited lines of a text field, doesn't that seem like it's been specialized for a particular domain in an unobvious way? Why lines? Why not bytes, words, unicode characters? I mean, it's more convenient for people that do a lot of text processing, but I don't see anything specific to text or lines in the phrase "file('foo.txt')". That's all I'm saying. >> I think this is important to point out, because the implicit/explicit >> rule comes up all the time, yet Python is implicit about lots of things! >> To name a few: >> >> - for loops and iterators > > Already addressed above: nothing implicit there. Likewise, and I still disagre... =) >> - types of variables > > There are none, so how could such a nonexisting thing be EITHER implicit > OR explicit? Variables don't HAVE types -- OBJECTS do. The very fact that variables to not have types, and following that, that variables do not have manifest types, is an example of implicit being chosen over explicit. I know your argument, and I understand that Python variables are Post-It sticky notes and all of that, but please, just try to look at it from a non-Python-centric perspective. Other languages (like C++, which I hear you are vaguely familiar with ;) require you to be explicit about what type of thing you're defining and sending where. Python does not. This is one of its strengths, because it allows for ad-hoc interfaces and polymorphism without a lot of boilerplate. > Etc, etc -- can't spend another 1000 lines to explain why your "lots of > things" do not indicate violations of "explicit is better than implicit". They're not *violations*. Correct me if I'm wrong, but the Zen of Python is not the LAW! It's a poem! It's very beautiful, very concise, inspiring, and thoughtful, but it's not the 10 commandments! I just get very tired of every idea getting shot down because of some rule from Tim Peters. I really don't think he intended for it to be used to prove the validity of ideas. The implicit/explicit thing is one of the most abused, in my opinion, because it can quite frankly be used to shut down any attempt at creating abstraction. In fact, for that reason alone, I'm tempted to say "Implicit is better than explicit". Say what you want, not how you want it. Be abstract, not concrete. >> If all you're saying is that naming something is better than not naming >> something because explicit is better than implicit, I'd have to ask why: > > Sometimes it is (to avoid perilous nesting), sometimes it isn't (to > avoid wanton naming). I generally don't mind naming things, but it IS > surely possible to overdo it -- without going to the extreme below, > just imagine a language where ONLY named argument passing, and no use > of positional arguments, was allowed (instead of naming arguments being > optional, as it is today in Python). I don't have to imagine. It's called Smalltalk, and also (to some extent) Tcl/Tk. Even Tkinter seems to be named-argument only. It's not that bad. I still like positional parameters, though. > If a Pythonic syntax can't be found to solve ALL use cases you've > raised, then the "balance" may be considered not nice enough to > compensate for the obvious problem -- a serious case of MTOWTDI. That's another argument for another day. ;) >>> Python prioritize things diferently than other languages. >>> It's not an APL. "Readability counts" >> >> This is nothing like APL... if anything, it's like Smalltalk, a language >> designed to be readable by children! > > Cite pls? I knew that Logo and ABC had been specifically designed > with children in mind, but didn't know that of Smalltalk. http://ei.cs.vt.edu/~history/GASCH.KAY.HTML http://www.cosc.canterbury.ac.nz/~wolfgang/cosc205/smalltalk1.html http://www.cs.washington.edu/homes/dugan/history.html >> I realize that APL sacrificed >> readability for expressiveness to an uncomfortable extreme, but I really >> think you're comparing apples and oranges here. List comprehensions are >> closer to APL than code blocks. > > As an ex-user of APL (and APL2) from way back when, I think you're > both talking through your respective hats: neither list comprehensions > (particularly in the Python variation on a Haskell theme, with > keywords rather than punctuation) nor code blocks resemble APL in the least. Well, it was a rough analogy, and I've never done any APL myself, but here's my justification, FWIW: - APL provides syntactical constructs for high-level array processing - List comprehensions do this also - Code blocks have nothing inherently to do with array processing But I agree that neither resemble APL as I've seen. I guess it's like saying a carrot is more like APL than a rutabega. Dave -- .:[ dave benjamin (ramenboy) -:- www.ramenfest.com -:- www.3dex.com ]:. : d r i n k i n g l i f e o u t o f t h e c o n t a i n e r : From paddy3118 at netscape.netNOTthisBIT Sun Oct 19 02:45:24 2003 From: paddy3118 at netscape.netNOTthisBIT (Donald 'Paddy' McCarthy) Date: Sun, 19 Oct 2003 07:45:24 +0100 Subject: Help: GUI wxGlade/traits linkage Message-ID: Hi, I am having a few problems with a GUI. I am new to traits and wxGlade. I have used wxGlade to create a Form with an embedded space for a CustomWidget. I have the traits demo and would like to edit the traits and have the traits form appear instead of the space left for my CustomWidget. wxGlade produces code with the following hook (last line): class MyFrame(wxFrame): def __init__(self, *args, **kwds): # begin wxGlade: MyFrame.__init__ kwds["style"] = wxDEFAULT_FRAME_STYLE wxFrame.__init__(self, *args, **kwds) self.btTraits = CustomWidget(self, -1) <> So with the traits example code of: import traits import traits.wxtrait_sheet class Person ( traits.HasTraits ): __traits__ = { 'name': '', 'age': 9, 'weight': 0.0 } bill = Person() From reading the traits doc I thought that I would just need to change the call to CustomWidget above to: self.btTraits = traits.wxtrait_sheet.TraitSheet ( wxFrame, bill) But that leads to the following error: $ pythone btF.py Traceback (most recent call last): File "btF.py", line 84, in ? frame_1 = MyFrame(None, -1, "") File "btF.py", line 29, in __init__ self.btTraits = traits.wxtrait_sheet.TraitSheet ( wxFrame, bill) File "C:\Python23_Enthought\lib\site-packages\traits\wxtrait_sheet.py", line 3 22, in __init__ wx.wxPanel.__init__( self, parent, -1 ) File ".\site-packages\wxPython\windows.py", line 696, in __init__ TypeError: Type error in argument 1 of new_wxPanel. Expected _wxWindow_p. I would be grateful for a little help. Thanks, Paddy. From my-first-name.my-last-name at jpl.nasa.gov Wed Oct 8 15:01:41 2003 From: my-first-name.my-last-name at jpl.nasa.gov (Erann Gat) Date: Wed, 08 Oct 2003 12:01:41 -0700 Subject: Python syntax in Lisp and Scheme References: Message-ID: In article , tfb at famine.OCF.Berkeley.EDU (Thomas F. Burdick) wrote: > > method overloading, > > How could you have both noncongruent argument lists, and multiple > dispatch? C++ seems to manage it somehow. #include void foo(int x, int y) { printf("1\n"); } void foo(double x, int y) { printf("2\n"); } void foo(char* x) { printf("3\n"); } main() { foo(1,2); foo(1.2,2); foo("foo"); } compiles and runs without complaint. E. From mk at net.mail.penguinista Tue Oct 28 14:27:49 2003 From: mk at net.mail.penguinista (=?UTF-8?B?0LTQsNC80ZjQsNC9INCzLg==?=) Date: Tue, 28 Oct 2003 20:27:49 +0100 Subject: Python Locales under windows References: Message-ID: <3f9ec335@news.mt.net.mk> > >>> print "%.2f" % 1024.36 # should be '1024,36' > 1024.36 [Linux/ Python-2.3.1] well this doesnt work under Linux neither, you need to use: locale.format( "%.2f", 1024.36) after setting the locale > >>> string.letters #should be 54 letters here, including ?? > 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' Its the same here even afer locale was set, but maybe thats because my Linux locale is mk_MK.UTF8 > I'm using python 2.3 under Windows XP and 2K. There is "locale.windows_locale" that may help you, although I don't knowwhat this dictionary is about. -- ?????? (jabberID:damjan at bagra.net.mk) There's no place like ~ From jozef.kosoru at iblsoft.com Fri Oct 24 12:45:15 2003 From: jozef.kosoru at iblsoft.com (Jozef Kosoru) Date: Fri, 24 Oct 2003 18:45:15 +0200 Subject: [Off-Topic] cvs Message-ID: Hello, sorry for the off-topic question but I think this is a good place to ask. I plan to develop open-sourced web application which integrates CVS browser, a bug tracking system and some more interesting features to support development both open-sourced and commercial projects. I would like to know whether it is worth to invest my free time for such a tool. CVS is rather an old system and I have no idea how widely is used in development teams. So my question is easy: Do you use CVS in your development? Thank you, jozef From pythonguy at Hotpop.com Sun Oct 12 10:43:00 2003 From: pythonguy at Hotpop.com (Anand Pillai) Date: 12 Oct 2003 07:43:00 -0700 Subject: How to remove empty lines with re? References: <84fc4588.0310100849.4546e804@posting.google.com> <3f86e96c-da7dc89b-addc-47d2-82cf-a60a482e6e07@news.szn.dk> Message-ID: <84fc4588.0310120643.6a58d37a@posting.google.com> You probably did not read my posting completely. I have added a comma after the print statement and mentioned a comment specifically on this. The 'print line,' statement with a comma after it does not print a newline which you also call as line terminator whereas the 'print' without a comma at the end does just that. No wonder python sometimes feels like high-level psuedocode ;-) It has that ultra intuitive feel for most of its tricks. In this case, the comma is usually put when you have more than one item to print, and python puts a newline after all items. So it very intuitively follows that just putting a comma will not print a newline! It is better than telling the programmer to use another print function to avoid newlines, which you find in many other 'un-pythonic' languages. -Anand Klaus Alexander Seistrup wrote in message news:<3f86e96c-da7dc89b-addc-47d2-82cf-a60a482e6e07 at news.szn.dk>... > Anand Pillai wrote: > > > Here is the complete code. > > > > import re > > > > empty=re.compile('^$') > > for line in open('test.txt').readlines(): > > if empty.match(line): > > continue > > else: > > print line, > > The .readlines() method retains any line terminators, and using the > builtin print will suffix an extra line terminator to every line, > thus effectively producing an empty line for every non-empty line. > You'd want to use e.g. sys.stdout.write() instead of print. > > > // Klaus From antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru Fri Oct 17 10:05:56 2003 From: antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru (anton muhin) Date: Fri, 17 Oct 2003 18:05:56 +0400 Subject: writing code over several lines In-Reply-To: <62e9c66e.0310170556.328072e8@posting.google.com> References: <62e9c66e.0310170556.328072e8@posting.google.com> Message-ID: Dominik Kaspar wrote: > i want to initialize a constant list at the beginning of a python > program. but the list is too big for one line. is there any > possibility to spread the list over several lines, so that the code > looks neat again? > > something like: > LIST = [[100, 101, 102], [200, 201, 202], [300, 301, 302], > [400, 401, 402], [500, 501, 502], [600, 601, 602], > [700, 701, 702], [800, 801, 802], [900, 901, 902]] > > thanks in advance > dominik :) yes. Just type the code and feed it to python interpreter: LIST = [[100, 101, 102], [200, 201, 202], [300, 301, 302], [400, 401, 402], [500, 501, 502], [600, 601, 602], [700, 701, 702], [800, 801, 802], [900, 901, 902]] print LIST [[100, 101, 102], [200, 201, 202], [300, 301, 302], ... regards, anton. From whumeniu at nospamtelus.net Sun Oct 19 13:51:26 2003 From: whumeniu at nospamtelus.net (Wade Humeniuk) Date: Sun, 19 Oct 2003 17:51:26 GMT Subject: Why don't people like lisp? In-Reply-To: <7xvfqlp1qp.fsf@ruckus.brouhaha.com> References: <1A8kb.67406$pv6.3464@twister.nyc.rr.com> <874qy5ear5.fsf@bird.agharta.de> <6Szkb.6421$i92.5421@clgrps13> <7xvfqlp1qp.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > > This is untested but looks simpler than the lisp example: > > def mostn (fn, lst): > max = None > for a in lst: > score = fn(lst) > if max is None or score > max: > max = score > ret = [a] > elif score == max: > ret.append(a) > return ret That's the spirit, now (defun mostn (fn lst &aux (mostn-elems nil) (max nil)) (tagbody find-mostn (unless (null lst) ((lambda (score) (cond ((or (null max) (> score max)) (setf max score mostn-elems (list (car lst)))) ((= score max) (push (car lst) mostn-elems)))) (funcall fn (car lst))) (setf lst (cdr lst)) (go find-mostn))) (values (nreverse mostn-elems) max)) or (defun mostn (fn lst &aux (mostn-elems nil) (max nil)) (map nil (lambda (score elem) (cond ((or (null max) (> score max)) (setf max score mostn-elems (list elem))) ((= score max) (push elem mostn-elems)))) (mapcar fn lst) lst) (values (nreverse mostn-elems) max)) Wade From exarkun at intarweb.us Wed Oct 8 15:20:24 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Wed, 8 Oct 2003 15:20:24 -0400 Subject: IM with python and tkinter? In-Reply-To: <33093.199.169.240.132.1065626450.squirrel@svr1.turboweb.net> References: <33093.199.169.240.132.1065626450.squirrel@svr1.turboweb.net> Message-ID: <20031008192023.GA2158@intarweb.us> On Wed, Oct 08, 2003 at 11:20:50AM -0400, Matthew Wilson wrote: > Hi- > > > I've been using python for a while now for stuff like parsing text files > and drawing graphs with reportlab. I want to move on to a bigger project. > All the people in my office agree that we need could use some kind of > instant-messenger application. > > How hard would it be to write something like this in python? We all use > windows2000 and have static IP addresses inside the intranet. Has > something like this already been written? Can anyone provide a basic > outline of what this would involve? > Tons of free, open source IRC servers exist. I'm sure a few of them even run on Windows. Jp From mnations at airmail.net Wed Oct 15 17:33:52 2003 From: mnations at airmail.net (Marc) Date: 15 Oct 2003 14:33:52 -0700 Subject: py2exe and win32com Message-ID: <4378fa6f.0310151333.4c0c558e@posting.google.com> Hi all, I tried for the first time compiling an app using py2exe and COM and had little success in getting it to run. I browsed for help, but couldn't find anything that was giving the error I'm getting. This is the problem: Traceback (most recent call last): File "", line 7, in ? File "imputil.pyc", line 103, in _import_hook File "", line 52, in _import_top_module File "imputil.pyc", line 216, in import_top File "imputil.pyc", line 271, in _import_one File "", line 128, in _process_result File "excel.pyc", line 1, in ? File "imputil.pyc", line 132, in _import_hook File "", line 70, in _finish_import File "imputil.pyc", line 316, in _load_tail File "imputil.pyc", line 271, in _import_one File "", line 128, in _process_result File "win32com\client\__init__.pyc", line 12, in ? File "imputil.pyc", line 93, in _import_hook File "imputil.pyc", line 347, in _do_import File "imputil.pyc", line 271, in _import_one File "", line 128, in _process_result File "win32com\client\gencache.pyc", line 519, in ? File "win32com\client\gencache.pyc", line 44, in __init__ File "win32com\client\gencache.pyc", line 507, in Rebuild File "win32com\client\gencache.pyc", line 49, in _SaveDicts File "win32com\client\gencache.pyc", line 96, in GetGeneratePath IOError: [Errno 2] No such file or directory: 'L:\\gen_py\\__init__.py' There must be a special way to include the win32 modules, but I can't figure it out. Could someone point me in the right direction. Thanks, Marc From nid_oizo at yahoo.com_remove_the_ Wed Oct 15 14:34:32 2003 From: nid_oizo at yahoo.com_remove_the_ (Nicolas Fleury) Date: Wed, 15 Oct 2003 14:34:32 -0400 Subject: Expat current line/column number In-Reply-To: <3F8D8440.D0038E86@hotmail.com> References: <3F8D8440.D0038E86@hotmail.com> Message-ID: Alan Kennedy wrote: > [Nicolas Fleury] > >> Is it possible with xml.parsers.expat to get the current line and >>column number if an exception is raised by one of the callbacks (not >>necessary an xml.parsers.expat.ExpatError)? > > > Is this the type of thing you mean? It doesn't work on my side or I'm missing something. Here's your example slightly modified: import StringIO import xml.sax import xml.sax.xmlreader import xml.sax.expatreader class ApplicationException(Exception): pass class HandlerThatRaisesExceptions(xml.sax.ContentHandler): def startElement(self, name, attrs): if name == 'hello': raise Exception('wrong') inputfile = StringIO.StringIO(""" """) parser = xml.sax.make_parser(['xml.sax.expatreader']) parser.setContentHandler(HandlerThatRaisesExceptions()) try: parser.parse(inputfile) except Exception, ax: print "App exception:%s: Line %d, Column %d" % (str(ax), \ parser.getLineNumber(), parser.getColumnNumber()) My output is: App exception:wrong: Line 15, Column 0 I don't understand these numbers; there's not even 15 lines... Anyone have an idea what I'm missing? Thx and Regards, Nicolas Fleury From ransom at physics.mcgill.ca Sat Oct 18 11:29:38 2003 From: ransom at physics.mcgill.ca (Scott Ransom) Date: 18 Oct 2003 08:29:38 -0700 Subject: General Numerical Python question References: <500a4565.0310112113.a0840e8@posting.google.com> <500a4565.0310131915.148ce3f5@posting.google.com> <500a4565.0310140541.4f4fd35f@posting.google.com> <%xVib.26249$gi2.16759@fed1read01> <500a4565.0310162140.1d7c9c1b@posting.google.com> Message-ID: mjackson at alumni.caltech.edu (Mark Jackson) wrote in message news:... > mcrider at bigfoot.com (2mc) writes: > > Michael Ressler wrote in message news:... > > > Another example of thinking things differently is suppose you have a > > > vector where the values are randomly positive or negative. Suppose for > > > reasons known only to you, you want to replace the negative values > > > with the sqrt of their absolute values. With Numeric, no loops are > > > involved. > > > > > > from Numeric import * > > > a=array([1.,2.,-3.,4.,-5.,6.,-7.,-8.,9.]) # make up an array > > > idx=nonzero(a<0) # indexes of the negative values > > > sqrs=sqrt(abs(take(a,idx))) # get the sqrts of neg elements > > > put(a,idx,sqrs) # put them back into a > > > print a # works! > > > > > > You can make the whole thing a one-liner if you want to get carried > > > away with it. It's too bad "nonzero" isn't called "whereis" or > > > something like that - it would make the idx= line more obvious. > > > > > > Mike > > > > I think I'm finally getting a handle on this. So, my thanks to > > everyone who has so graciously helped me out with their suggestions. > > > > How would you handle the above if "a" were a 2d array since "nonzero" > > only works on 1d arrays? Could you have used the "nonzero" function > > on a "vertical" slice of the array (from the perspective of an array > > of rows and columns - a vertical slice being the data in the column)? > > I'm very new at this myself (currently porting some Fortran code to > Numeric) but I believe that Numeric.putmask is your friend here: > > >>> a=Numeric.array([i*(-1)**i for i in range(20)],Numeric.Float) > >>> b=a.resize((4,5)) > >>> b > array([[ 0., -1., 2., -3., 4.], > [ -5., 6., -7., 8., -9.], > [ 10., -11., 12., -13., 14.], > [-15., 16., -17., 18., -19.]]) > >>> mask = b<0 > >>> mask > array([[0, 1, 0, 1, 0], > [1, 0, 1, 0, 1], > [0, 1, 0, 1, 0], > [1, 0, 1, 0, 1]]) > >>> Numeric.putmask(b, mask, Numeric.sqrt(abs(b))) > >>> b > array([[ 0. , 1. , 2. , 1.73205081, 4. ], > [ 2.23606798, 6. , 2.64575131, 8. , 3. ], > [ 10. , 3.31662479, 12. , 3.60555128, 14. ], > [ 3.87298335, 16. , 4.12310563, 18. , 4.35889894]]) Once again, this can be done in a single (easy-to-read) line using: b = where(b<0, sqrt(fabs(b)), b) where does all the masking and putmasking for you. Scott From jay at jaydorsey.com Thu Oct 2 11:27:52 2003 From: jay at jaydorsey.com (Jay Dorsey) Date: Thu, 02 Oct 2003 10:27:52 -0500 Subject: How To Check For [a-z] In String? In-Reply-To: <3F7C412A.8050609@jaydorsey.com> References: <3F7C412A.8050609@jaydorsey.com> Message-ID: <3F7C43F8.7070006@jaydorsey.com> Jay Dorsey wrote: > >>> regex = re.compile('[a-z]|[A-Z]') > >>> regex.findall('123a23423b13123c123123A123B123C') > ['a', 'b', 'c', 'A', 'B', 'C'] > Line 1 above should have been [a-zA-Z] (although as posted it works as well). Its just prettier the second way :-) Jay From ville.spammehardvainio at spamtut.fi Wed Oct 22 02:28:40 2003 From: ville.spammehardvainio at spamtut.fi (Ville Vainio) Date: 22 Oct 2003 09:28:40 +0300 Subject: Why don't people like lisp? References: <3f9302d7.170372828@news.eircom.net> Message-ID: Ville Vainio writes: > bill for clever stuff. I'm studying Grahams "On Lisp" as bad-time ^^^ Typo, s/bad/bed, obviously :). -- Ville Vainio http://www.students.tut.fi/~vainio24 From tjreedy at udel.edu Wed Oct 15 02:33:42 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 15 Oct 2003 02:33:42 -0400 Subject: Python syntax in Lisp and Scheme References: <3cea3gqq.fsf@comcast.net> <87ekxfmhhl.fsf@thalassa.informatimago.com> Message-ID: <1cucnY9twevVdxGiU-KYhA@comcast.com> "Pascal Bourguignon" wrote in message news:87ekxfmhhl.fsf at thalassa.informatimago.com... > > prunesquallor at comcast.net writes: > > Since having the correct amount of whitespace is *vital* to the > > correct operation of a Python program, it seems that the task of > > maintaining it is made that much more difficult because it is only > > conspicuous by its absence. > That remembers me that when the languages had significant spaces, the > programming was done with forms, sheets of physical paper preprinted > with empty spaces: [further idiocy snipped] I do believe that several Lispers have suggested that people should give Lisp a fair trial before rejecting it on account of parentheses or macros. The same goes, of course, for Python and significant indents/dedents. For most people who try Python, freedom from visually redundant fences is a feature. Those who find it a bother after trying are welcome to chose another language. What makes the comments above doubly absurd is that Lisp has as much or more need for 'significant spaces' as Python. Compare (1,2,3) versus (1 2 3). Having the "correct amount of whitespace is *vital* to the correct operation of a" Lisp program as much as for any other. Do Lispers therefore use forms? I suspect not ;-) Terry J. Reedy From aleax at aleax.it Fri Oct 31 13:12:38 2003 From: aleax at aleax.it (Alex Martelli) Date: Fri, 31 Oct 2003 18:12:38 GMT Subject: Implementing a scripting language in Python References: Message-ID: Peter Otten wrote: > Gabriele Farina wrote: > >> I guys >> >> I planned to create a new programming language to use to develop web >> applications for my company. >> >> I'd like to develop it using Python, but I don't know if python is fast >> enaught. > > The Python developers, regarded as smart over here, used C :-) > However, there seems to be an effort under way to implement Python in > Python, so it should be doable. Sure. And somebody European, like Gabriele, who's at all interested in that, should RUN to http://codespeak.net/pypy/ and get a plane (cheap -- I've found a trip there and back for EUR 120 + taxes, though that specific special offer is over now) and lodging (we're doing our best to find cheap ways for that too) to be in Amsterdam on Dec 14-21 for the fifth pypy "sprint". With the Amsterdam effort we plan/hope to release a big but not-too-slow cpypy.so (actually generated via pyrex) -- not quite independent from CPython yet, of course, but still, a complete and usable Python runtime whose sources are in Python (we have one now, but running it in purely interpreted Python isn't exactly, ahem, FAST:-). The Python->C translation (with some type annotation) that's intended to give us cpypy.so from the current Python pypy sources is done via pypy itself, btw, with a special objectspace. ((Plus, we plan/hope to release cool tools for interactive display/debug of pypy AND most particularly superior testing tools.)) I know it sounds incestuous and makes one's head spin, but if you study all the materials available on the pypy site (including the complete pypy sources), as is of course advisable before coming all the way to the sprint, it really ain't all that bad -- try it. And then the Sprint experience is going to be VERY advisable for anybody interested in programming language implementation of and/or with Python -- if your head doesn't explode you'll know a LOT more when you go back, >> Someone could help me and give me some ideas? > > Web applications are not rocket science, so why not adopt an existing > language instead of burning your company's money. While we're at it, why > not use Python - I admit I'm biased - and spend your resources on > improving an existing web framework. Yes, it IS nearly inconceivable that creating a new programming language -- rather than using Python and the wealth of tools &c already available for it -- is going to be cost/benefit-effective for a company. Or, using Ruby, Lisp, Scheme, etc, etc, are all choices likely to be still more cost/benefit-effective than developing a new language, even though I agree with you that Python's likely to be best (in most, though not all, situations of web application development -- e.g. if the firm happens to have a Ruby guru or three already onboard, that may change the equation). Alex From baf at texas.antispam.net Sun Oct 12 19:11:16 2003 From: baf at texas.antispam.net (Ben Fairbank) Date: Sun, 12 Oct 2003 23:11:16 GMT Subject: Rankordering for nonparametric statistics (Newbie) Message-ID: <3f89df93.1184733@news.houston.sbcglobal.net> I have a matrix with many rows(say 1000 to make this concrete) and a dozen or so columns. One column has numbers ranging from 1 to several hundred. I have to create a new column with numbers from 1 to 1000 corresponding to the smallest to largest numbers (don't worry about ties (yet)) in the column of interest. The new number thus indicate the ordinal or rank order of the values in the given column. I have been futzing around with argsort, but cannot find an elegant fast way to do it. Can a reader suggest? Thank you, BAFairbank From dkuhlman at rexx.com Mon Oct 13 13:48:33 2003 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Mon, 13 Oct 2003 10:48:33 -0700 Subject: Python vs Visual Basic References: Message-ID: Alex Martelli wrote: > Orange Free wrote: > >> I want to create a program that will ask a user a series of >> questions and then generate a Microsoft Word document whose >> content is dictated >> by the answers. I am not a professional programmer, and I >> understand >> only a little about OO programming. Should I [snip] > > May I suggest an alternative? Perhaps you might be satisfied with > generating a foo.rtf rather than foo.doc file. Now, the RTF > format isn't much easier or better documented than the DOC format, > but it > has the advantage that RTF format files are TEXT. I've read that the latest version of MS Word (or MS Office?) heavily uses XML. If that's true, perahps you should consider generating foo.xml that follows the MS Word XML document definition (again, if there is such a thing). Here is a quote from Tim Bray: When asked how XML-enabling will make a difference in MS Office, Bray quickly zeroes in on what in his view is the key differentiator in an XML-enabled Office suite vs the current one. "The important thing," he explains, "is that Word and Excel (and of course the new XDocs thing) can export their data as XML without information loss. It seems Word can also edit arbitrary XML languages under the control of an XML Schema, but I'm actually more excited by the notion of Word files also being XML files." And here is a link to the complete article: http://www3.sys-con.com/xml/rotate.cfm [snip] Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman dkuhlman at rexx.com From aahz at pythoncraft.com Sat Oct 18 00:48:14 2003 From: aahz at pythoncraft.com (Aahz) Date: 18 Oct 2003 00:48:14 -0400 Subject: wait until change References: Message-ID: In article , Tom wrote: > >I have the following problem. I analyse data from a file. When I am done >analysing all the data that was in that file, I want to let my program >wait until this specific file has changed (which indicates that new data >has been added to the file from a third party program that I don't >control). If that file has changed, I want my program to continue. > >What would be the appropriate command to check if the file changed? And >how can I implement "wait until" into my program? I googled a lot to >find any hints, but couldn't find anything helpful. But I found >something about a python that was stabbed in NY in 2000. :-) Thought >that was funny. :-) os.stat() is the correct answer, but I question the other responses that suggest using time.sleep(). Unless your application stores a lot of data in memory, you might be better off using your OS to periodically run your application; your application stores the result of os.stat() in a private file. On Unix-like systems, the facility is called cron; dunno what that would be on Windows. This would simplify your program; it also means your program would automatically start when the system gets rebooted. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From gherron at islandtraining.com Sun Oct 26 00:06:05 2003 From: gherron at islandtraining.com (Gary Herron) Date: Sat, 25 Oct 2003 21:06:05 -0700 Subject: Regular expressions In-Reply-To: References: Message-ID: <200310252106.05032.gherron@islandtraining.com> On Saturday 25 October 2003 03:41 pm, Kill Bill wrote: > I'm trying to find all combinations of the a string. > I found that [blah]* gives it to me but it uses the same letter multiple > times which I dont' want. Several people have answered (correctly) one of your questions, that being how to get the contents of a variable into a string. However, I think your other question remains unanswered, perhaps it is not very well worded. By saying you don't want it to not "uses the same letter multiple times", I guess your asking about permutations of a given string. For instance the permutations of "abc" are abc acb bca bac cab cba and not things like aac Is this correct? If so, you are a bit out of luck. I don't think regular expressions can do this in any straightforward way. (However as you say regular expressions are complex, so I won't claim that this is not possible.) Perhaps you would be satisfied with something like this: "abc|acb|bca|bac|cab|cba" and if you were clever enough to build a list of all permutations of a given string listOfPermutations = Permutations("abc") # e.g., ['abc', 'acb', ...] then the regular expression could be gotten by '|'.join(listOfPermutations) # e.g., "abc|acb|..." Hope that helps, Gary Herron From wiseworld at web.de Sun Oct 19 15:27:30 2003 From: wiseworld at web.de (Ansgar Wollnik) Date: Sun, 19 Oct 2003 21:27:30 +0200 Subject: MySQLdb integer question In-Reply-To: References: Message-ID: Scenario: # myvalues (1L,'text') # sql="INSERT INTO %s (%s) VALUES %s"% (db,",".join(myfields),myvalues) This doesn't work, because the Integer-Value (1L) is not converted into a Integer (without 'L'), so the INSERT statement is: INSERT INTO db (id, sometext) VALUES (1L,'text') ^^ :-( What can I do? Ansgar From donn at drizzle.com Thu Oct 16 02:12:13 2003 From: donn at drizzle.com (Donn Cave) Date: Thu, 16 Oct 2003 06:12:13 -0000 Subject: assignment expression peeve References: <7x1xtfkuky.fsf@ruckus.brouhaha.com> <6q6jb.10882$fv4.3354@nwrdny02.gnilink.net> <7xk77676bt.fsf@ruckus.brouhaha.com> <7xptgy9qr7.fsf@ruckus.brouhaha.com> <7x8ynm6rtu.fsf@ruckus.brouhaha.com> <%iljb.19300$0I6.15247@nwrdny03.gnilink.net> <7x7k366mwe.fsf@ruckus.brouhaha.com> Message-ID: <1066284732.96348@yasure> Quoth Paul Rubin : | Carl Banks writes: |> Again, apples and oranges. You are comparing meanings, when the |> problem is syntax. "A guy named Bob walks into a bar" and |> "bar.enter(bob := Guy())" might have the same meaning, but they use a |> diffenent syntax to convey it. And the latter uses a syntax with no |> analogue in any natural language I know of. | | Whatever. You're the only programmer I've ever encountered who claims | to have actual trouble understanding assignment expressions. With | other people, the objection is that they can be confused with | comparison expressions, or that they're simply another | not-so-important feature that Python doesn't need. They are an impediment to understanding, says the second programmer. If there were some way to support the functionality you wanted there, and ONLY as represented in your example, then the impediment would not be a severe one, and the only question would be whether such a trivial gain is worth the bother. I think the class wrapper work-arounds, as proposed in your initial post and one or two follow-ups, are better, so it's no gain at all in my eye. But when you can say if g := match(a, b): then I suspect you will also be able to say things like - if not (dv := start() and f := nfile(dv) and ((t := f.find("--") > 0 and fx = f[:t]) or (fx = f))): print "Well, bless me!" Of course no one would do such a thing. I translated this from C code written by someone who is a far more accomplished programmer than I, whose name I know you would recognize. (Identifiers etc. changed to protect the not-entirely-innocent.) Donn Cave, donn at drizzle.com From aleax at aleax.it Wed Oct 8 06:44:33 2003 From: aleax at aleax.it (Alex Martelli) Date: Wed, 08 Oct 2003 10:44:33 GMT Subject: print is not a function References: Message-ID: Karl Scalet wrote: ... >>>>>sys.stdout.write("Hello world!\n") > > I came across this, but this requires an extra import sys > which not always is there, thanks anyhow. Ah, hadn't seen this before I answered your other post. Well. duplicating the print statement functionality in a *built-in* function to let you abuse a list comprehemsion for the side effects and throw away the results just ain't gonna happen. Built-in functions are (or should be: there may well be purges in Python 3.0) just for tasks so important and widespread that an 'import' cannot be considered. Alex From stkni at bigfoot.com Thu Oct 9 07:41:43 2003 From: stkni at bigfoot.com (Steve Knight) Date: 9 Oct 2003 04:41:43 -0700 Subject: Boost + Python C/API: Mixing python return types with boost return types Message-ID: Hello, I'm new to Boost & Python and I'm diving straight in by trying to write an extension module to a third party library. Foolishness probably, but I don't have much choice! My question is how can I write a C++ method that will either return a boost wrapped C++ class or a Python object type depending on some internal value? So I want to do something like: PyObject* Variant::getValue() { switch (type) { case INT: return Py_BuildValue("i", union.int); break; case SOMECLASS: ?????? } } But I can't work out how to get my switch to construct and return my boost C++ wrapped object in this scheme. I'm getting round it by: SomeClass Variant::getSomeClass() { SomeClass s(*reinterpret_cast(union.p_void)); return s; } But it seems a bit nasty. Any ideas? From oblivious at web.de Fri Oct 3 03:26:38 2003 From: oblivious at web.de (Dominic) Date: Fri, 03 Oct 2003 09:26:38 +0200 Subject: Python syntax in Lisp and Scheme In-Reply-To: References: Message-ID: mike420 at ziplip.com wrote: > I think everyone who used Python will agree that its syntax is > the best thing going for it. It is very readable and easy > for everyone to learn. But, Python does not a have very good > macro capabilities, unfortunately. I'd like to know if it may > be possible to add a powerful macro system to Python, while > keeping its amazing syntax, and if it could be possible to > add Pythonistic syntax to Lisp or Scheme, while keeping all > of the functionality and convenience. If the answer is yes, > would many Python programmers switch to Lisp or Scheme if > they were offered identation-based syntax? Well, there's always a programming language which has more features than another. However documentation, libraries, software-engineering tools and developer community have also to be accounted for. So whenever a special features is deemed necessary but not available in the language I suggest to use code generators. E.g. you cannot express grammars in C/Java for parsing so usually you stick to yacc/bison/flex/cups etc. In C++ BOOST provides capabilites to express a parser by means of template metaprogramming but compile times are huge. In my opinion are old fashioned parser generators more transparent. So it's probably not worth the trouble. I have successfuly implemented a simple code generator for real-time control applications in Python which outputs C-source. http://www-user.rhrk.uni-kl.de/~hillbr/public/ Today I'd suggest to use XML-files to describe the problem and generate source code from it. Source code needed for assembling the final result could also be embedded into the XML-files. Eclipse uses a kind of JSP to generate code from templates. (Examples exist for generating source code for enumerations which are not yet supported by Java) However it's still very primitive. At the rapid pace at which Eclipse is developed I am curious what way it is going to take. Ciao, Dominic From Hobbes2176 at yahoo.com Tue Oct 28 11:08:01 2003 From: Hobbes2176 at yahoo.com (Mark) Date: Tue, 28 Oct 2003 16:08:01 GMT Subject: Timer interrupt of execution? Message-ID: Hello all, I know why the following doesn't work ... I can't figure out how to make it work like I want it to. Basically, I only want the loop computing fibonacci numbers to run for approx 5 seconds. The timer fires, the exception is raised, but it is not caught ... because the execution stack for the function that raises isn't in the same thread as the try: except:. How do you fix this? Is it better to do this without exceptions as the control construct? Regards, Mark PS I tried two positions of starting the thread ... unfortunately, lexical scope doesn't affect the execution stack ... it's still in its own space, I guess. #!/usr/bin/env python import threading class TimeException(Exception): def __init__(self, i): self.msg = "Out of time" def raiser(): print "raising" raise TimeException print "raised" def fib(x): if x == 0 or x == 1: return 1 else: return fib(x-1) + fib(x-2) #position 1 #t = threading.Timer(5.0, raiser) #t.start() try: # position 2 t = threading.Timer(5.0, raiser) t.start() for i in range(1,10000000): t = fib(i) print i, ": ", t except TimeException: print "thread done" except: print "other exception" From mabus at operamail.com Sat Oct 25 23:57:51 2003 From: mabus at operamail.com (sashan) Date: Sun, 26 Oct 2003 16:57:51 +1300 Subject: checking if a connect using ServerProxy fails Message-ID: Hi How do you test if a connect fails. I'm doing this at the moment: print 'Connect' try: self.sp = ServerProxy('http://localhost:5001') except Fault, f: print 'fail' but it doesn't fail. I don't have anything listening on port 5001. From wtrenker at hotmail.com Tue Oct 7 09:33:09 2003 From: wtrenker at hotmail.com (William Trenker) Date: Tue, 07 Oct 2003 13:33:09 +0000 Subject: Using TCP/IP In-Reply-To: <6b4v41-o94.ln1@beastie.ix.netcom.com> References: <3F7B100D.5260350C@engcorp.com> <8cf2994e.0310021252.63d4666f@posting.google.com> <6b4v41-o94.ln1@beastie.ix.netcom.com> Message-ID: <20031007133309.2d341fe8.wtrenker@hotmail.com> On Fri, 03 Oct 2003 03:33:57 +0000 (GMT) Dennis Lee Bieber wrote regarding Re: Using TCP/IP: > Interesting. Under Mandrake 8.2, the above returns an error: > > >>> socket.gethostbyname_ex('') > Traceback (most recent call last): > File "", line 1, in ? > socket.herror: (4, 'No address associated with name') I get the same error here. But this works: >>> socket.gethostbyname_ex(socket.gethostname()) ('noodle.noodle.org', ['noodle'], ['127.0.0.1']) Linux 2.4.19; libc.so.6 2.2.5; gcc 2.95.3 GNU ld version 2.13.90.0.4 20020814 GNU Make 3.80 pkg-config 0.14.0 Python 2.3 (#1, Jul 30 2003, 12:02:14) [GCC 2.95.3 20010315 (release)] Bill From FBatista at uniFON.com.ar Mon Oct 20 14:50:34 2003 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Mon, 20 Oct 2003 15:50:34 -0300 Subject: prePEP: Money data type Message-ID: #- Not at all: being able to delegate arithmetic issues to the #- "quantity" #- object (Money in this case) is, on the contrary, crucial to simplify #- higher application levels. There IS a case for "money with currency #- unit" to be separate from pure Money, basically to catch errors due #- to trying to sum Euros and Dollars and the like; but that #- can be built #- by subclassing a Money that's blissfully oblivious to currencies. As #- long as that Money CAN handle arithmetic, though; otherwise, what #- ARE its responsibilities?! By design, Money won't be conscious of currency, meaning that Money(2) are 2 dollars, 2 euros, or two argentinian pesos. #- > I prefer the idea of wrapping money in domain-specific ways, and #- > leaving the money object relatively pure. #- #- A relatively-pure object should generally have an area of #- responsibility #- nevertheless. I see Money's area of responsibility as #- arithmetic, and #- rounding policy as being intrinsic to that. Arithmetic is a *must to* in Money (as a decent numeric type). And rounding is inseparable in arithmetic (anyway, everybody uses rounding when using floating point). #- Using the passed-in object's __class__ may be sufficient in #- that case, #- and that should often be transparently achievable, as calling methods #- on a money instance that return another new money instance should #- automatically use the same class. That's very easy too, #- e.g. consider #- a very toy example, a meant-as-immutable Money that only holds an #- amount and lets you sum a number to that returning a new instance: #- #- class Money(object): #- def __init__(self, amount): self.amount = amount #- def __add__(self, other): #- return self.__class__(self.amount + other) Very good idea, Alex. Any test case that test this? . 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 frodef at cs.uit.no Sat Oct 4 16:11:49 2003 From: frodef at cs.uit.no (Frode Vatvedt Fjeld) Date: Sat, 04 Oct 2003 22:11:49 +0200 Subject: Python syntax in Lisp and Scheme References: <7xvfr6lvh6.fsf@ruckus.brouhaha.com> <92c59a2c.0310031345.57d20631@posting.google.com> <2hy8w188h3.fsf@vserver.cs.uit.no> <47Dfb.224825$R32.7231998@news2.tin.it> Message-ID: <2hoeww930a.fsf@vserver.cs.uit.no> Alex Martelli writes: > Sure, but aren't these the examples that are being presented? Isn't > "with-collector" a general purpose iteration construct, etc? Maybe > only _special_ purpose ones should be built with macros (if you are > right that _general_ purpose ones should not be), but the subtleness > of the distinction leaves me wondering about the practice. It is a subtle distinction, just like a lot of other issues in programming are quite subtle. And I think this particular issue deserves more attention than it has been getting (so far as I know). As for the current practice, I know that I quite dislike code that uses things like with-collector, and I especially dislike it when I have to look at the macro's expansion to see what is going on, and I know there are perfectly fine alternatives in the standard syntax. On the other hand, I do like it when I see a macro call that reduces tens or even hundreds of lines of code to just a few lines that make it immediately apparent what's happening. And I know I'd never want to use a language with anything less than lisp's macros. -- Frode Vatvedt Fjeld From $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk Mon Oct 13 13:18:39 2003 From: $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk (Stephen Horne) Date: Mon, 13 Oct 2003 18:18:39 +0100 Subject: type checking References: <1065938227.288329@yasure> <84fc4588.0310122350.203c9e41@posting.google.com> <84fc4588.0310130904.10282692@posting.google.com> Message-ID: <2lmlovs0bo0928dj2ierutn644o8kcd4kj@4ax.com> On 13 Oct 2003 10:04:21 -0700, pythonguy at Hotpop.com (Anand Pillai) wrote: >I am not trying to impress anyone. Give me a problem and I can >lay a wager I can do it in python and deliver you the beta code in >two weeks. Let that be a fresh problem btw. Give me another two >weeks and I can deliver you commercial quality code without using >a debugger. > >Try me. OK - how about the Turing test? Ah - I see - that's not a fresh problem, having been proposed some 50 years ago ;-) Some problems are complex in any language. -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From peter at engcorp.com Wed Oct 22 09:18:20 2003 From: peter at engcorp.com (Peter Hansen) Date: Wed, 22 Oct 2003 09:18:20 -0400 Subject: Unittest - How do I code lots of simple tests References: <3F95A5DC.51828269@engcorp.com> <182bcf76.0310220211.4ba29f4d@posting.google.com> Message-ID: <3F96839C.C022B118@engcorp.com> Paul Moore wrote: > > Peter Hansen wrote in message news:<3F95A5DC.51828269 at engcorp.com>... > > Paul Moore wrote: > > > > > > Can anyone suggest a more reasonable way of running this sort of > > > table-driven test via unittest? [snip] > > No, you don't get the psychologically affirming "52 tests passed!" > > without changes to the TestRunner, but I assume the non-cosmetic part > > of this is more your concern right now... > > I don't see the remainder of the problem as "non-cosmetic". The error > report I get (or rather the information it offers) is > > 1 test failed - pass count is 25 instead of 52. > > But that doesn't tell me *which* tests failed. > > The key point here is that I'm NOT running one test - I really am > running 52 distinct tests. OK, they are all very similar, differing > only in the data - but for pity's sake, isn't that what an object > oriented structure is supposed to make easy??? Well, look at it this way. Using the built-in assertEquals() and similar functions is a way of explicitly asking for a test method to abort, and for the framework to continue on with the next test method. If you don't want that behaviour, nothing's forcing you to use assertEqual(). Instead, just write up your own comparison routine, which doesn't abort, and have verbose output for each failure. Something I've done repeatedly in the past is to have a routine which says simply (upon failure) "case %s: expected %s, result %s" and then substitute in the test case input, the expected value, and the actual result. The part that is "cosmetic" is insisting that this has to result in the framework reporting the as individual "test" failures. To do that, you need more extensive modifications, because unittest has a clear, simple definition of what constitutes a test, and individual comparisons inside a testMethod() are not it... it's the whole test method that is a test. After all, just because a test has two self.assertEquals() and a single self.assert_() doesn't necessarily mean it's *three* tests. As Anthony B. wrote, you're testing one "aspect" or something... don't think of tests as calls to assertXxxx() methods, think of them as collections of such calls. -Peter From ak at nospam.com Sat Oct 11 19:51:11 2003 From: ak at nospam.com (AK) Date: Sat, 11 Oct 2003 23:51:11 GMT Subject: Data Representation? References: Message-ID: In article , Kris Caselden wrote: > Say I have some data: > >>>> a=[1] >>>> b=[2] >>>> link=[a,b] > > The simplest why to write this to a file represents it as > >>>> print str(link) > [[1], [2]] > > Unfortunately, if this is read back in via execfile(), the whole > dynamic nature of changing 'link' by changing 'a' and 'b' is lost. Is > there any way to write data so that the list name is written instead > of the list's values? Essentially, '[[a], [b]]' instead of '[[1], > [2]]'? Any help most appreciated. Sure, look at pickle and shelve modules in library reference. shelve works kind of like this: s = shelve.open('filename') s['a'] = a s.close() s = shelve.open('filename') a = s['a'] print a code not tested.. -AK From tyler at tylereaves.com Thu Oct 30 18:21:13 2003 From: tyler at tylereaves.com (Tyler Eaves) Date: Thu, 30 Oct 2003 18:21:13 -0500 Subject: Auto-crop in PIL? References: <20031030094258081-0500@braeburn.themorgue.org> <3FA17A8D.C849EF81@alcyone.com> Message-ID: On Thu, 30 Oct 2003 12:54:37 -0800, Erik Max Francis wrote: > Tyler Eaves wrote: > >> That is, the image is in the rectangle (left non-white, top >> non-white), >> (right non-white, top non-white), (right non-white, bottom non-white), >> (left non-white, bottom non-white) > > This only works if you actually know that the object you want to crop in > the middle is rectangular. If it's amorphous, you'll have to scan in > stripes.. I dunno, to me a crop is by definition rectangular, and that's the way it's worked in every image editor I've ever used. From costanza at web.de Mon Oct 20 06:41:01 2003 From: costanza at web.de (Pascal Costanza) Date: Mon, 20 Oct 2003 12:41:01 +0200 Subject: Why don't people like lisp? In-Reply-To: References: <3f9302d7.170372828@news.eircom.net> Message-ID: Ville Vainio wrote: > wallacethinmintr at eircom.net (Russell Wallace) writes: > > >>However, this really applies only when you're doing things the >>language designer anticipated. The great thing I find about Lisp is > > > When I'm really doing something the language designer didn't > anticipate (and the required features don't already exist), I'm > probably doing something wrong and need to revise my design > anyway. So why is it that Python is continuously evolving as a language? Do you think this is going to stop at some stage? Wouldn't it be better if everyone could contribute to the evolution of a language, and then let the community decide what the best approaches are? See for example, the SRFI approach of the Scheme community. >>that when I'm doing something the language was _not_ designed to >>handle, it's not an "oh shit" problem, it's a "well, I suppose I can >>do this with a few macros" problem. > > One can always go to c.l.py and ask, only to see that the problem is > easily solved in plain old Python. I think the benefits of Python far > outweigh the theoretical scenario that I actually needed some feature > that isn't there, and could be done in Lisp. The approach for Lisp is to write a domain-specific language for the problem at hand, and then to write the program in that domain-specific language. (These are not actually two distinct steps, but these parts are usually achieved in an evolutionary way.) If you want to keep your Lisp program in a specific programming style (OOP, functional, imperative, etc.) you can do that either. Lisp gives you a choice here. With Python, you have to stick to the constructs the languages give you. When you want to add domain-specific abstractions on the language level, you have to step outside of the language, and for example use program generators. Python doesn't give you a choice here. This is only to say that in general, we usually don't use macros just to "fix" the language, but we want macros because it enables a programming style that is not available in most other programming languages. > Most often the missing > features involve not having a library to, say, access some database, > and I doubt Lisp has more than Python to offer in that area. That's correct. > Meanwhile, people are voting with their feet: a lot (thousands? don't > know the exact figure) of people are taught Lisp (well, Scheme, but > anyway) at colleges/whatever every year, and they abandon it in a > blink of an eye after the course (obviously this might be because the > courses emphasize functional programming). Many even think that C++, > of all things, is easier! They can't vote with their feet wrt to particular features of the programming languages they use, can they? And as a sidenote, if you are seriously considering to learn and maybe use Lisp in practice, you should take a look at _both_ major dialects, i.e. Common Lisp and Scheme. They are very different in several respects, and if you think that one of them sucks, this doesn't necessarily mean that you will also despise the other one. Pascal -- Pascal Costanza University of Bonn mailto:costanza at web.de Institute of Computer Science III http://www.pascalcostanza.de R?merstr. 164, D-53117 Bonn (Germany) From reply.in.the.newsgroup at my.address.is.invalid Sat Oct 25 12:26:44 2003 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Sat, 25 Oct 2003 18:26:44 +0200 Subject: 2.3 on Debian Woody: doable? References: <0r4lpvos52hovek30hola8i184vmnagvqh@4ax.com> Message-ID: Jan Dries: >Rene Pijlman: >> There doesn't seem to be an apt package for Python 2.3 on Debian Woody. >> >> Should I expect unusual difficulties or unsolvable problems when building >> and installing 2.3 on Woody from the source distribution of Python? >> >> E.g. things like dependencies on other libraries that are not available on >> Woody? > >I've installed 2.3 from source on a minimal Debian Woody, and it went >flawlessly. The only extra software I had to install was BerkeleyDB for >the bsddb package to work, but that has nothing to do with Debian. Great Jan, thanks! -- Ren? Pijlman From stefan at fkp.uni-hannover.de Tue Oct 21 09:32:36 2003 From: stefan at fkp.uni-hannover.de (Stefan) Date: Tue, 21 Oct 2003 15:32:36 +0200 Subject: No Makefile for Demo/embed/missing libpython Message-ID: Hello, I've embedded Python in bigger application on a Debian system. Now I try to compile this application on Suse and find that the shared library libpython.so is not available. So I want to use the archive libpython.a and cannot figure out how to add this to my configure.in. I thought I could learn it from the Demos supplied with Python, but on Suse the Demo/embed directory has no Makefile; the original source-distribution only contains a Makefile for RH which doesn't work here. Any suggestions would be helpful. Stefan From danbmil99 at yahoo.com Tue Oct 21 03:28:09 2003 From: danbmil99 at yahoo.com (dan) Date: 21 Oct 2003 00:28:09 -0700 Subject: Why don't people like lisp? References: <3f9302d7.170372828@news.eircom.net> <87ismkcp5d.fsf@bird.agharta.de> Message-ID: Edi Weitz wrote in message news:<87ismkcp5d.fsf at bird.agharta.de>... [yada yada...] > "If a million people say a foolish thing, it is still a foolish > thing." > > (Anatol France) Did you know that Anatole France had one of the smallest brains on record? See for instance: http://www.sciencenetlinks.com/sci_update.cfm?DocID=166 search for 'anatole' Slightly OT I guess, but these threads get boring fast. ps on the topic -- any language that *requires* bloatware like Emacs in order to use is already out of the running. I wrote my first large Python program in Wordpad. From peter at engcorp.com Tue Oct 7 11:36:00 2003 From: peter at engcorp.com (Peter Hansen) Date: Tue, 07 Oct 2003 11:36:00 -0400 Subject: Python factoids... after 3 three years. References: <8338c7cc.0310070618.41d2544e@posting.google.com> Message-ID: <3F82DD60.E17241CF@engcorp.com> Randy Young wrote: > > Python positives. > ... > 3 By far and I mean by a ton, the best language to use, put down, and > then pick UP AGAIN. I, uh, don't understand this... _why_ would someone drop Python? :-) -Peter From cbeck at mercury.bc.ca Fri Oct 31 00:20:43 2003 From: cbeck at mercury.bc.ca (Coby Beck) Date: Fri, 31 Oct 2003 16:20:43 +1100 Subject: Explanation of macros; Haskell macros References: <87brs2tjut.fsf@memetrics.com> <87he1rdt9d.fsf@memetrics.com> Message-ID: "Pascal Costanza" wrote in message news:bnscfb$p1k$1 at newsreader2.netcologne.de... > > The essence of this is as follows: > > (defmacro my-cond (&body body) > `(cond ,@(append body '(t (handle-the-default-case)))) > Just to provide a more apparently general (and working ;) version, analogous to CL's ECASE: CL-USER 90 > (defmacro econd (&body body) `(cond ,@(append body `((t (error (format nil "fell through ECOND form. could not satisfy any of the following: ~{~%~A~}~%" (mapcar #'(lambda (cond) (car cond)) ',body)))))))) ECOND CL-USER 91 > (econd ((= 3 4) "foo") ((= 4 4) "bar")) "bar" CL-USER 92 > (econd ((= 3 4) "foo") ((= 4 5) "bar")) Error: fell through ECOND form. could not satisfy any of the following: (= 3 4) (= 4 5) 1 (abort) Return to level 0. 2 Return to top loop level 0. Type :b for backtrace, :c